Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22c80b2d94 | ||
|
|
85e14ca626 | ||
|
|
a99b90cc02 |
@@ -4,26 +4,60 @@
|
||||
|
||||
These instructions apply to the entire repository.
|
||||
|
||||
GoodBuddy is a secure, cross-platform Electron desktop assistant. It uses
|
||||
Electron, React, TypeScript, Vite, Vitest, and SQLite. User-facing copy is
|
||||
primarily Simplified Chinese.
|
||||
GoodBuddy is a cross-platform Electron desktop assistant for internal
|
||||
organizational networks. It uses Electron, React, TypeScript, Vite, Vitest, and
|
||||
SQLite. User-facing copy is primarily Simplified Chinese.
|
||||
|
||||
## Product Priorities
|
||||
|
||||
GoodBuddy is primarily an internal-network product. Unless the user states
|
||||
otherwise, assume a trusted organizational environment, not a hostile public,
|
||||
multi-tenant, or zero-trust deployment.
|
||||
|
||||
Use this order when requirements or implementation choices compete:
|
||||
|
||||
1. Working product functionality.
|
||||
2. Performance and responsiveness.
|
||||
1. Complete, working product functionality.
|
||||
2. Measured performance and responsiveness.
|
||||
3. Clear, low-friction user experience.
|
||||
4. Simple, conventional, maintainable implementation.
|
||||
5. Security controls proportional to a concrete, realistic risk.
|
||||
5. Security controls only for a concrete risk in the actual deployment model.
|
||||
|
||||
Follow KISS and YAGNI. Do not add trust tiers, consent ceremonies, durable
|
||||
state machines, protocol phases, cryptographic identities, quotas, recovery
|
||||
machinery, or compatibility layers unless they are needed for an actual user
|
||||
workflow or a demonstrated failure mode. Prefer the normal platform mechanism
|
||||
and the smallest design that works. Test Hosts are test environments; do not
|
||||
turn their workflows into production compliance exercises.
|
||||
Functionality and performance are the primary acceptance criteria. Do not
|
||||
disable, delay, restrict, or complicate a working product path for speculative
|
||||
security hardening. Preserve the existing Electron, credential, user-data, and
|
||||
release-signing boundaries, but do not expand them without a concrete current
|
||||
risk or an explicit user requirement.
|
||||
|
||||
## Design Simplicity
|
||||
|
||||
Follow KISS and YAGNI. Use the smallest conventional design that completes the
|
||||
real user workflow.
|
||||
|
||||
- A demonstrated failure authorizes only the smallest proportional fix, not a
|
||||
general recovery, compatibility, or security framework.
|
||||
- Prefer deleting bounded staging and retrying, idempotent operations, and
|
||||
reconciliation from one authoritative source of truth. Do not persist copies
|
||||
of state that can be derived or safely retried.
|
||||
- Do not add durable snapshots, journals, versioned internal receipts, rollback
|
||||
engines, compatibility readers, multi-phase state machines, protocol phases,
|
||||
cryptographic identities, trust tiers, consent ceremonies, or quotas when
|
||||
cleanup, retry, or reconciliation is safe.
|
||||
- Before introducing any of that machinery, stop before coding. Explain the
|
||||
reproducible current failure, why the simple alternative is insufficient,
|
||||
and obtain the user's explicit approval for the added complexity. A reviewer
|
||||
suggestion, test-only scenario, hypothetical crash, or possible future need
|
||||
is not sufficient evidence.
|
||||
- Performance outranks simplicity only for a measured bottleneck. Security
|
||||
complexity requires a concrete threat at an actual trust boundary.
|
||||
- Ignore hypothetical threats that require a hostile public network,
|
||||
untrusted tenants, or zero-trust deployment unless that environment is an
|
||||
explicit product requirement. Do not turn such findings into implementation
|
||||
work.
|
||||
- A complete workflow means the normal production path plus demonstrated
|
||||
failure cases. It does not require exhaustive recovery from every
|
||||
hypothetical interruption point.
|
||||
- Test Hosts are test environments. Do not turn their workflows into production
|
||||
compliance exercises.
|
||||
|
||||
When the user asks to implement a feature, deliver the complete usable user
|
||||
workflow unless the user explicitly requests a prototype, scaffold, staged
|
||||
@@ -48,7 +82,8 @@ work as the implemented feature.
|
||||
- `build`: packaging scripts and icons.
|
||||
- `out` and `dist`: generated output. Change source files instead.
|
||||
|
||||
Keep Electron security boundaries intact:
|
||||
Keep these existing Electron security boundaries intact. They do not authorize
|
||||
additional hardening beyond the actual internal-network threat model:
|
||||
|
||||
- Preserve context isolation and sandboxing.
|
||||
- Never enable renderer Node integration.
|
||||
@@ -77,7 +112,11 @@ Keep Electron security boundaries intact:
|
||||
|
||||
## Data and Compatibility
|
||||
|
||||
- Preserve existing user data and migrations.
|
||||
- Preserve released user-owned data, migrations required by released data, and
|
||||
supported external contracts.
|
||||
- Compatibility does not apply to unshipped, branch-local, or safely disposable
|
||||
internal operation records. Replace or discard those records instead of
|
||||
adding migrations, legacy readers, versioned receipts, or recovery machinery.
|
||||
- Do not weaken SQLite transaction, lifecycle, deduplication, or cleanup logic.
|
||||
- Treat user workspaces and untracked files as user-owned.
|
||||
- Keep Windows, macOS, Linux x64, and Linux arm64 behavior in mind.
|
||||
@@ -88,6 +127,10 @@ Keep Electron security boundaries intact:
|
||||
- Follow surrounding TypeScript and React patterns.
|
||||
- Reuse installed libraries and shared contracts before adding dependencies.
|
||||
- Keep changes focused. Do not add unrelated refactors or documentation.
|
||||
- Reviewer findings do not expand task scope. Implement a finding only when it
|
||||
identifies a reachable current failure, a released compatibility contract,
|
||||
or reproducible user-visible harm. Record speculative concerns without
|
||||
building machinery around them.
|
||||
- Validate the real end-to-end path, not only schemas, mocks, injected test
|
||||
doubles, or isolated infrastructure. A feature is not complete until its
|
||||
normal UI action reaches the production implementation and produces the
|
||||
@@ -180,276 +223,28 @@ mode.
|
||||
Release note: 修复左上角项目设置与消息通道项目设置不一致的问题;现在从任一入口修改后,另一处会同步显示相同配置。
|
||||
```
|
||||
|
||||
## Release Packaging
|
||||
## Releases
|
||||
|
||||
- `.github/workflows/packages.yml` is the canonical cross-platform packaging
|
||||
workflow. It validates and builds `out` once, then packages on six native
|
||||
runners: Windows, macOS, and Linux, each for x64 and arm64.
|
||||
- The experimental Linux LoongArch (`loong64`) preview is built separately
|
||||
through `build/loongarch-cross` by following
|
||||
`docs/development/loongarch-preview-build.md`. It is not part of
|
||||
`.github/workflows/packages.yml`, the six-runner GitHub Actions matrix,
|
||||
standard release manifests, GitHub Release asset expectations, or the
|
||||
production update index. Do not add it to those paths unless the user
|
||||
explicitly requests a future production-support migration.
|
||||
- Run the unified packager with
|
||||
`npm run release:package -- --platform <platform> --arch <arch>`. It only
|
||||
packages for the native host and writes to
|
||||
`dist/release/<platform>-<arch>`.
|
||||
- Default deliverables are NSIS and portable ZIP for Windows, DMG and ZIP for
|
||||
macOS, and AppImage, DEB, and RPM for Linux. Every target includes
|
||||
`release-manifest.json` with SHA-256 hashes.
|
||||
- `build/build-release.cjs` verifies the unpacked application, `app.asar`,
|
||||
bundled Continue and OpenCode runtimes, executable architecture, and package
|
||||
signatures before atomically replacing a release directory.
|
||||
- All desktop build paths, including local `portable`, package the Agent and
|
||||
remote Runtime version locks plus the public signing-key registry without
|
||||
embedding installable Linux Agent or remote Runtime payloads. Managed SSH is
|
||||
optional: users explicitly download a compatible compound `.gbagent` package
|
||||
from Settings or import one offline before GoodBuddy can install or update a
|
||||
Host.
|
||||
- Each independently published Linux x64 or arm64 `.gbagent` contains the
|
||||
Agent daemon, pinned Node, and the desktop-maintained compatible OpenCode
|
||||
Runtime. Build both architectures on native GitHub Actions runners from one
|
||||
immutable `agent-v<agentVersion>` tag.
|
||||
- Keep the GoodBuddy Agent source, shared protocol/contracts, runtime lock,
|
||||
bundle tooling, and tests in this repository so a desktop commit identifies
|
||||
the exact Agent source it expects. Do not create a separate Agent repository
|
||||
or long-lived Agent release branch unless the Agent becomes an independently
|
||||
released product serving multiple clients.
|
||||
- `.github/workflows/agents.yml` is the branch and pull-request build
|
||||
verification workflow for GoodBuddy Agent. It must build Linux x64 and
|
||||
arm64 on native runners from the checked-out commit, acquire the locked
|
||||
official Node archive and locked OpenCode npm archive, verify every locked
|
||||
digest, use only an ephemeral in-memory test signing identity, and verify the
|
||||
resulting compound package and deterministic archive. It must not read
|
||||
production signing secrets, publish installable release artifacts, or modify
|
||||
the checked-in public key registry.
|
||||
- `.github/workflows/agent-release.yml` is the only production compound Agent
|
||||
publication path. It requires an annotated immutable Agent tag, the protected
|
||||
`agent-signing` Environment, native x64/arm64 builds, one production
|
||||
GoodBuddy signing identity for every layer of the compound package and
|
||||
catalog, a non-Latest GitHub Agent Release, and synchronized immutable
|
||||
Beijing OSS objects plus the final signed latest-catalog pointer.
|
||||
- `.github/workflows/packages.yml` and `release:package` build only desktop
|
||||
products. Missing Agent packages, remote Runtime inputs, or GoodBuddy signing
|
||||
credentials must never block an ordinary desktop package or release.
|
||||
- Keep electron-builder invocations on `--publish never`. Main-branch builds
|
||||
run validation and build the production bundle without running the native
|
||||
package matrix. Manual builds upload 30-day GitHub Actions artifacts.
|
||||
Version-tag builds verify and aggregate packages before publishing GitHub
|
||||
Release assets. The macOS jobs sign, notarize, and verify packages when all
|
||||
five Apple credentials are configured. With no Apple credentials they must
|
||||
use the explicit `--unsigned` path, warn that Gatekeeper may block the
|
||||
packages, and still complete; a partial credential set must fail rather than
|
||||
silently downgrade.
|
||||
- Keep `ELECTRON_CACHE` and `ELECTRON_BUILDER_CACHE` under
|
||||
`${{ runner.temp }}` in step-level workflow contexts. A cache beneath the
|
||||
repository inherits the root `"type": "module"` and breaks electron-builder's
|
||||
CommonJS macOS icon tool.
|
||||
- Tag builds must use `v${package.version}`. The workflow also supports manual
|
||||
dispatch and main-branch changes to release tooling.
|
||||
Detailed release operations are governed by
|
||||
[`docs/development/release-runbook.md`](./docs/development/release-runbook.md).
|
||||
Read that runbook only when preparing, publishing, recovering, or verifying a
|
||||
desktop or GoodBuddy Agent release. It is an operator and CI procedure, not an
|
||||
authorization to add product persistence or recovery machinery.
|
||||
|
||||
### Agent Release Process
|
||||
Repository-wide release invariants:
|
||||
|
||||
- Agent releases use annotated `agent-v${agent-runtime-lock.agentVersion}` tags
|
||||
and are separate from desktop `v${package.version}` releases. Confirm the
|
||||
exact Agent release commit and tag with the user before creating or pushing
|
||||
either.
|
||||
- The tagged commit must be reachable from protected `main`. The two native
|
||||
jobs build the compound x64/arm64 packages from the same source and locks;
|
||||
the catalog job rejects missing architectures, changed bytes for an existing
|
||||
version/architecture identity, invalid prior signatures, and incompatible
|
||||
matrix metadata.
|
||||
- Agent GitHub Releases are ordinary non-draft, non-prerelease releases but
|
||||
must use `--latest=false`; they must never replace the desktop release marked
|
||||
Latest. Publish immutable packages and the versioned catalog to
|
||||
`agent-releases/v<agentVersion>/` in Beijing OSS, publish the GitHub Agent
|
||||
Release, then atomically update the single `agent-releases/latest.json`
|
||||
pointer to that version's immutable catalog and signature.
|
||||
- Do not report an Agent release complete until both public package
|
||||
architectures match the signed catalog by size and SHA-256, the GitHub and
|
||||
OSS catalog bytes/signatures are identical, the application can read the
|
||||
selected source, and GitHub's repository Latest tag remains the desktop tag.
|
||||
|
||||
### Tagged Release Process
|
||||
|
||||
Every version-tag release must follow this sequence. A branch-only push does
|
||||
not require release notes.
|
||||
|
||||
1. Confirm that the user wants a release tag and identify the exact release
|
||||
commit and the new `package.json` version. Separately ask whether this
|
||||
release should also receive an experimental LoongArch preview build; never
|
||||
infer that choice from an earlier release.
|
||||
2. Find the latest stable version tag reachable before the release commit and
|
||||
inspect the complete commit and file diff from that tag to the release
|
||||
commit. For the first tagged release, inspect the relevant repository
|
||||
history instead.
|
||||
3. Draft concise, user-facing release notes in both Simplified Chinese and
|
||||
English based only on verified changes in that range. Use the titles
|
||||
`GoodBuddy <version> 更新内容` and
|
||||
`What's New in GoodBuddy <version>`, with corresponding `功能更新` /
|
||||
`Features` and `问题修复` / `Bug Fixes` sections when applicable. The two
|
||||
language versions must describe the same changes. Do not expose
|
||||
internal-only details, credentials, private content, or unverified claims.
|
||||
4. Show the exact bilingual release-note draft to the user and wait for
|
||||
explicit approval. If the release commit or either language version changes
|
||||
after approval, inspect the updated tag range and request approval again.
|
||||
5. Write the approved notes to the single entry for the release version in
|
||||
`resources/release-notes.json`. A failed unpublished candidate whose content
|
||||
is carried forward must not retain a duplicate packaged entry.
|
||||
6. Verify that `package.json`, the root `package-lock.json` version, and
|
||||
`package-lock.json.packages[""].version` all equal the release version. Run
|
||||
`npm run release:notes:verify`, the required source validators, the
|
||||
production build, and any native candidate launch probe available on the
|
||||
current host. The six native CI jobs remain the cross-platform authority.
|
||||
If the user requested a LoongArch preview in step 1, build it separately
|
||||
from this exact candidate by following the LoongArch build document, record
|
||||
its size and SHA-256, and keep it outside the standard GitHub/OSS release
|
||||
asset set unless the user separately authorizes publishing it.
|
||||
7. Fetch both remotes immediately before tagging. Inspect any remote branch
|
||||
movement instead of overwriting or silently merging it. Confirm the working
|
||||
tree is clean, the candidate tag is unused locally and remotely, and the
|
||||
exact approved commit has not changed.
|
||||
8. Only after all previous steps pass, create an annotated
|
||||
`v${package.version}` tag at the exact approved commit. Push `main` to
|
||||
`origin` and `github`, verify both branch SHAs, then push the tag to both
|
||||
remotes and verify each peeled tag SHA (`refs/tags/<tag>^{}`) equals the
|
||||
release commit.
|
||||
9. Keep both approved language versions as the single source for the GitHub
|
||||
Release body and the packaged first-open release-notes modal. The modal
|
||||
displays the release notes matching the current interface language and
|
||||
contains no button linking to a full release page.
|
||||
10. Observe the tag workflow through publication and complete the public
|
||||
verification checklist below. A successful push is not a completed
|
||||
release.
|
||||
|
||||
### OSS Publication Contract
|
||||
|
||||
The tagged release job publishes through the GitHub Environment selected by
|
||||
`.github/workflows/packages.yml` (`aliyun-oss-release`) and reads the following
|
||||
effective GitHub Actions variables. Before a release or same-tag rerun can
|
||||
publish, verify that repository-, organization-, or environment-level
|
||||
resolution exposes:
|
||||
|
||||
- `ALIYUN_OSS_BUCKET=goodbuddy`
|
||||
- `ALIYUN_OSS_ENDPOINT=https://oss-cn-beijing.aliyuncs.com`
|
||||
- a non-empty `ALIYUN_OIDC_PROVIDER_ARN` matching
|
||||
`acs:ram::*:oidc-provider/*`
|
||||
- a non-empty `ALIYUN_ROLE_ARN` matching `acs:ram::*:role/*`
|
||||
|
||||
For environment-scoped values, use the exact Environment name from the
|
||||
workflow; do not assume a similarly named UI environment such as `Production`
|
||||
contains the active variables.
|
||||
|
||||
The Bucket and Endpoint are a deployment contract, not interchangeable
|
||||
examples. They must stay aligned with the trusted URL checks in
|
||||
`src/main/version-checker.ts`, `sites/app.js`, website validation, and related
|
||||
tests. A host, Bucket, Region, or CDN migration must update and validate every
|
||||
surface together before a new release.
|
||||
|
||||
- Use GitHub OIDC and the RAM Role to obtain short-lived STS credentials.
|
||||
Never add long-lived AccessKeys to repository or environment secrets.
|
||||
- Keep `ossutil` pinned. Its V4 signing requires the Region; derive it from the
|
||||
canonical Endpoint, verify that the production value resolves to
|
||||
`cn-beijing`, and pass `--region` to every `ossutil cp`, including the final
|
||||
`latest.json` update.
|
||||
- Grant the RAM Role only the actions and prefixes required by the workflow.
|
||||
It must be able to write immutable version objects and the final latest
|
||||
pointer without granting unrelated administration privileges.
|
||||
- Upload release assets and `site-release.json` under the immutable
|
||||
`releases/<tag>/` prefix first. Verify all 14 installer URLs publicly before
|
||||
creating or publishing the GitHub Release. Update
|
||||
`releases/latest.json` only after the GitHub Release is public and all prior
|
||||
checks succeeded.
|
||||
- The expected GitHub Release contains 22 assets: 14 installers (two formats
|
||||
for each Windows/macOS target and three formats for each Linux target), six
|
||||
renamed target manifests, one aggregate `release-manifest.json`, and one `SHA256SUMS`.
|
||||
`site-release.json` is an OSS publication artifact, not a GitHub Release
|
||||
asset.
|
||||
|
||||
### Failed Tag Recovery
|
||||
|
||||
Classify a failed tag by the external side effects that completed before
|
||||
choosing a recovery:
|
||||
|
||||
- If no source or release metadata must change, correct only the external
|
||||
configuration and use **Re-run failed jobs** for the same immutable tag. Do
|
||||
not change, move, delete, or recreate the tag.
|
||||
- If immutable OSS objects were partially uploaded but their source bytes are
|
||||
unchanged, a same-tag rerun may idempotently re-upload or verify them. Never
|
||||
point `latest.json` at a partially verified prefix.
|
||||
- If the GitHub Release is already public but the final latest-pointer step
|
||||
failed, it is a published version. Keep its packaged notes and rerun the
|
||||
failed release job for the same tag; do not classify it as an unpublished
|
||||
candidate.
|
||||
- If code or release metadata must change, keep the failed tag immutable,
|
||||
increment the patch version, obtain approval for the revised exact release
|
||||
commit and notes, and create a new tag. Do not reuse the failed version.
|
||||
|
||||
When recovering from a version tag whose workflow never published a public
|
||||
GitHub Release:
|
||||
|
||||
- If a code or metadata change requires a higher version and a new tag, carry
|
||||
the failed candidate's approved user-facing notes forward into the recovery
|
||||
version, then remove the superseded failed version's entry from
|
||||
`resources/release-notes.json`.
|
||||
- The packaged first-open modal must show that carried-forward content only
|
||||
once under the recovery version. Never retain both the failed version and
|
||||
its cumulative recovery copy, because users upgrading across them would see
|
||||
duplicate content.
|
||||
- Never remove the packaged history for a version that successfully published
|
||||
a GitHub Release. Verify the failed release state before treating an entry as
|
||||
superseded.
|
||||
|
||||
### Post-Publication Verification
|
||||
|
||||
Do not report a release complete until all of the following are verified:
|
||||
|
||||
1. The tag workflow and all six native package jobs succeeded. Verify the
|
||||
recorded macOS signing mode: signed builds must pass `codesign`, `spctl`,
|
||||
and `stapler`; unsigned builds must record the Gatekeeper caveat in the
|
||||
Actions log and job summary. In the final release job, explicitly verify
|
||||
the OSS configuration, OIDC authentication, release-index generation,
|
||||
immutable upload, public asset check, GitHub Release publication, and
|
||||
latest-pointer steps.
|
||||
2. The public GitHub Release is non-draft, non-prerelease, marked Latest, and
|
||||
uses the expected tag and title. Its body must exactly match the Markdown
|
||||
generated from the approved packaged bilingual notes.
|
||||
3. The GitHub asset set has exactly the expected 22 names and every asset is
|
||||
uploaded. Compare installer sizes and SHA-256 digests with the aggregate
|
||||
manifest and `SHA256SUMS`.
|
||||
4. The Beijing `releases/latest.json` returns HTTP 200, has the expected stable
|
||||
version, exact six targets and 14 installer entries, the trusted Beijing
|
||||
URLs, and the GitHub fallback URL. It must match the immutable
|
||||
`releases/<tag>/site-release.json`.
|
||||
5. All 14 public installer URLs accept `HEAD` without redirects and report the
|
||||
declared size. For small JSON/checksum metadata, prefer a `GET` byte and
|
||||
digest comparison; OSS may gzip JSON responses and omit an uncompressed
|
||||
`Content-Length` on `HEAD`.
|
||||
6. The live website successfully fetches the index and produces the 14 correct
|
||||
platform/architecture/format links. Exercise the application's actual
|
||||
mirror checker against the public index for all six targets.
|
||||
7. Both remote `main` refs and both peeled tag refs still equal the approved
|
||||
release commit, and the local working tree is clean.
|
||||
|
||||
Never create or push a release tag, and never push a previously created
|
||||
release tag, before the release-note draft has received explicit approval.
|
||||
|
||||
- Before a push that updates the `github` remote, ask whether the user wants a
|
||||
release tag unless they already specified that choice. A branch-only push
|
||||
does not require a version bump or tag. When the user requests a release,
|
||||
verify that `package.json` and `package-lock.json` contain the same release
|
||||
version, create `v${package.version}` at the exact commit being pushed, and
|
||||
push that tag so the native package matrix and GitHub Release run.
|
||||
- Never move or reuse an existing release tag. If `v${package.version}` already
|
||||
exists locally or on a remote at another commit, increment the package
|
||||
version and create a new matching tag before the release push.
|
||||
- Verified release baseline on 2026-08-18: commit
|
||||
`60119a4317118fa3f077db0382664f15266a6682`, annotated tag `v0.10.4`, and
|
||||
GitHub Actions run `32038633609` attempt 2 succeeded through all six native
|
||||
packages, GitHub Release publication, Beijing OSS publication, and the final
|
||||
`latest.json` switch.
|
||||
- Never create or push a release tag before the user approves the exact release
|
||||
commit and bilingual release notes.
|
||||
- Never move, delete, recreate, or reuse a release tag.
|
||||
- Keep desktop and Agent release paths, tags, artifacts, and Latest status
|
||||
separate.
|
||||
- Native GitHub Actions jobs are the cross-platform packaging authority. Never
|
||||
run local Windows packaging or packaged-app probes unless the user explicitly
|
||||
requests them.
|
||||
- LoongArch is a separate experimental preview. Build or publish it only when
|
||||
the user explicitly requests it for that release.
|
||||
- Never commit or publish credentials. Production publication uses the existing
|
||||
protected environments and short-lived credentials described in the runbook.
|
||||
|
||||
## Validation
|
||||
|
||||
@@ -474,6 +269,10 @@ Before committing or pushing, inspect `git status`, `git diff`, and
|
||||
`git diff --cached`. Do not commit secrets, local databases, logs, generated
|
||||
credentials, or private user artifacts.
|
||||
|
||||
Before a push that updates the `github` remote, ask whether the user wants a
|
||||
release tag unless they already specified that choice. A branch-only push does
|
||||
not require a version bump or tag.
|
||||
|
||||
This repository has two synchronized remotes, `origin` and `github`. Unless the
|
||||
user explicitly names a remote, every requested push must update the current
|
||||
branch on both remotes. When the user requests a release tag, push the new tag
|
||||
|
||||
@@ -172,10 +172,12 @@ JSON。签名目录、包描述符、manifest、签名和 payload 的原始字
|
||||
|
||||
两种 acquisition 都把同一签名 compound `.gbagent` 交付到固定 operation staging,随后
|
||||
共用 control-plane `prepare → commit → Agent activate/health → Runtime activate →
|
||||
finalize → cleanup`。commit 终态持久化,通道丢失时只用 `commit-status` 读取恢复而不
|
||||
重放 commit。prepare 完成后、commit 前快照 Agent/Runtime 五个 metadata 文件;任一 adoption 失败恢复
|
||||
原字节或原缺失状态,已发布 side-by-side payload 不成为 current,确认 adoption 后显式
|
||||
cleanup。
|
||||
finalize → cleanup`。Main 只持久化清理 operation staging 所需的 operation ID,不保存
|
||||
Agent/Runtime metadata 副本。操作中断或 adoption 失败后,下一次更新尽力清理旧暂存并
|
||||
重新 prepare,不恢复或续写旧操作。确认 adoption 后显式 cleanup。Host 在 prepare
|
||||
解包时完成一次完整 payload 校验;commit 只复核签名 metadata
|
||||
并原子发布,Agent/Runtime 注册后的 health、capabilities 和 prompt 启动不再遍历或哈希
|
||||
完整 payload。cleanup 失败不回滚已健康环境,也不阻塞下一次 fresh prepare。
|
||||
|
||||
进入“主机与远程执行”设置页只读取本地 Host 列表,不逐台连接。用户点击某台 Host 的
|
||||
“刷新版本”后才执行远端版本和直连准备能力探测。项目切换只更新本地选择,不建立 SSH
|
||||
@@ -217,9 +219,9 @@ Agent、固定 Node 和当前桌面源码维护并适配的签名 OpenCode Runti
|
||||
独立的用户版本流。远程直连所需的有界 one-shot installer 由桌面控制面打包并通过固定
|
||||
SSH prepare channel 发送,不是 `.gbagent` 的必需条目。Host 按签名目录校验完整归档
|
||||
大小和 SHA-256 后,包内固定 Node 解码并运行 installer。两种 acquisition 都在固定
|
||||
operation staging 中执行同一 prepare/commit;commit 终态持久化并可通过只读
|
||||
`commit-status` 恢复。Agent/Runtime adoption 使用 commit 前五个 metadata 文件的原字节
|
||||
或原缺失状态回滚,已发布 side-by-side payload 不会因此成为 current。生产构建命令为:
|
||||
operation staging 中执行同一 prepare/commit;本地 pending record 只保存清理暂存所需的
|
||||
operation ID。失败或中断后的下一次更新尽力清理旧暂存并重新 prepare,不保存或恢复
|
||||
Agent/Runtime metadata 副本。生产构建命令为:
|
||||
|
||||
```bash
|
||||
node build/agent-package.cjs build \
|
||||
|
||||
+2
-2
@@ -23,8 +23,8 @@
|
||||
|
||||
- [x] **直连模型 Runtime**:支持问答、知识总结、受控工具执行和图像生成。
|
||||
- [x] **OpenCode 与 Continue**:使用隔离子进程、环境变量白名单、统一配置、取消、总执行时限、有界流式输出和活动记录;共享进程回收逻辑保留 Windows 完整进程树终止,并对采用独立进程组的 POSIX 子进程执行组回收。交互提问只由前台对话回答,定时任务、远程通道和委派等后台执行遇到提问时会立即失败并提示改为前台运行,避免无限等待。
|
||||
- [x] **托管 SSH OpenCode 闭环(技术预览)**:该能力由“设置 > 平台功能”中的独立“远程项目(技术预览)”页签控制并默认关闭;关闭时不影响任何本地项目、普通桌面功能或桌面发布。启用后可管理固定 Host Key 的 SSH Host、浏览有界远端目录并创建 Ask/Execute 项目;Ask 在 Runtime 边界通过 bubblewrap 保持 Workspace 只读,Execute 使用所选 SSH 账号的完整权限。Main 通过签名 Agent、私有 Unix socket、ACP v3、持久恢复 cursor 和 Main-only 模型桥维持长任务、重连与会话恢复,模型凭据不进入远端。远端组件不嵌入桌面包,项目切换只更新本地选择且不会连接或下载;设置页只读取小型签名目录并按 Linux x64/arm64 显示本地版本、在线最新兼容版本和“有更新/已是最新”,用户点击后才下载签名 `.gbagent`,也可导入/导出离线包。每个复合包包含 Agent、固定 Node 与由桌面源码统一维护适配的 OpenCode Runtime;在线来源跟随“关于与更新”的 GitHub/北京 OSS 选择,签名累计目录绑定最低桌面版本、Agent 协议、架构、大小、SHA-256 和固定 URL。公钥 registry 接受等价 JSON 空白和换行,但仍严格校验 schema、Ed25519 key、环境与撤销;目录、包、manifest、payload 签名和流式 SHA-256 不变。缺少某架构包只使该架构托管 SSH 不可用。项目只保存 Host、远端路径、Runtime 选择和模式;首次实际使用 Workspace/Runtime 时读取 Host current identity,同一进程内其他项目复用已确认 identity 和 Agent 连接。托管 SSH 会话只显示支持的 OpenCode 选择。同一 Host 可并行运行多个项目和对话;活动请求沿精确 resume/replay 恢复,controller 换代遗留的空闲 binding 只在 takeover 已证明且没有活动请求时换新 channel epoch 并恢复原 ACP session。Windows 到 Linux x64 的安装、provider-free 模型桥、断线重放、Session 续接和零残留清理已完成真实 Host 验证;签名 Agent 0.11.2-e2e.12 与 OpenCode Runtime 1.18.9 已完成一次只提交一遍、只调用一个 Ask 原生 read、无标题轮次且精确返回证据内容的有界真实模型验收,当前源码 lock 已更新为待发布 Agent 0.11.7。
|
||||
- [x] **SSH Host 手动环境准备源码链路**:Host Key、认证和系统探针成功后先保存 Host,并只读探测共享 Agent/Runtime;保存 Host、打开项目都不自动安装。Host 卡片只有一个按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮,次级 SegmentedControl 选择默认且不持久化的“自动”、Host 下载或 GoodBuddy 传输;“版本匹配”badge 不等同环境健康。自动模式只在 operation/prepare 前探测并择一,显式选择保持有效,任何 prepare、commit 或 adoption 失败都不跨 acquisition 自动 fallback。两种方式把同一签名 compound `.gbagent` 交付到固定 staging 后,共用 control-plane prepare、持久化 commit、Agent activate/health、Runtime activate、finalize 与显式 cleanup。GoodBuddy 路径可在同一次操作下载并验证缺失候选、缓存并取得 lease,再有界流式 SFTP 上传一个归档和其中已验证的 bootstrap Node,不把约 294 MiB 整包读入 Main `Buffer`;Host 再次校验。通道丢失通过只读 `commit-status` 恢复而不重放 commit;组件 adoption 失败恢复 Agent/Runtime 五个 metadata 文件的原字节或原缺失状态,已发布 side-by-side payload 不成为 current。已有项目在实际使用 Workspace/Runtime 时按需解析 Host current identity 并执行固定 `attach-or-bootstrap`,不安装或扫描 payload。详见 [设计说明](./docs/architecture/remote-host-environment-provisioning-design.md)。
|
||||
- [x] **托管 SSH OpenCode 闭环(技术预览)**:该能力由“设置 > 平台功能”中的独立“远程项目(技术预览)”页签控制并默认关闭;关闭时不影响任何本地项目、普通桌面功能或桌面发布。启用后可管理固定 Host Key 的 SSH Host、浏览有界远端目录并创建 Ask/Execute 项目;Ask 在 Runtime 边界通过 bubblewrap 保持 Workspace 只读,Execute 使用所选 SSH 账号的完整权限。Main 通过签名 Agent、私有 Unix socket、ACP v3、持久恢复 cursor 和 Main-only 模型桥维持长任务、重连与会话恢复,模型凭据不进入远端。远端组件不嵌入桌面包,项目切换只更新本地选择且不会连接或下载;设置页只读取小型签名目录并按 Linux x64/arm64 显示本地版本、在线最新兼容版本和“有更新/已是最新”,用户点击后才下载签名 `.gbagent`,也可导入/导出离线包。每个复合包包含 Agent、固定 Node 与由桌面源码统一维护适配的 OpenCode Runtime;在线来源跟随“关于与更新”的 GitHub/北京 OSS 选择,签名累计目录绑定最低桌面版本、Agent 协议、架构、大小、SHA-256 和固定 URL。公钥 registry 接受等价 JSON 空白和换行,但仍严格校验 schema、Ed25519 key、环境与撤销;目录、包、manifest、payload 签名和流式 SHA-256 不变。缺少某架构包只使该架构托管 SSH 不可用。项目只保存 Host、远端路径、Runtime 选择和模式;首次实际使用 Workspace/Runtime 时读取 Host current identity,同一进程内其他项目复用已确认 identity 和 Agent 连接。托管 SSH 会话只显示支持的 OpenCode 选择。同一 Host 可并行运行多个项目和对话;活动请求沿精确 resume/replay 恢复,controller 换代遗留的空闲 binding 只在 takeover 已证明且没有活动请求时换新 channel epoch 并恢复原 ACP session。Windows 到 Linux x64 的安装、provider-free 模型桥、断线重放、Session 续接和零残留清理已完成真实 Host 验证;签名 Agent 0.11.2-e2e.12 与 OpenCode Runtime 1.18.9 已完成一次只提交一遍、只调用一个 Ask 原生 read、无标题轮次且精确返回证据内容的有界真实模型验收,当前源码 lock 已更新为 Agent 0.11.9。
|
||||
- [x] **SSH Host 手动环境准备源码链路**:Host Key、认证和系统探针成功后先保存 Host,并只读探测共享 Agent/Runtime;保存 Host、打开项目都不自动安装。Host 卡片只有一个按版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮,次级 SegmentedControl 选择默认且不持久化的“自动”、Host 下载或 GoodBuddy 传输;“版本匹配”badge 不等同环境健康。自动模式只在 operation/prepare 前探测并择一,显式选择保持有效,任何 prepare、commit 或 adoption 失败都不跨 acquisition 自动 fallback。两种方式把同一签名 compound `.gbagent` 交付到固定 staging 后,共用 control-plane prepare、commit、Agent activate/health、Runtime activate、finalize 与显式 cleanup。GoodBuddy 路径可在同一次操作下载并验证缺失候选、缓存并取得 lease,再有界流式 SFTP 上传一个归档和其中已验证的 bootstrap Node,不把约 294 MiB 整包读入 Main `Buffer`;Host 在解包时完成一次完整 payload 校验。未完成操作只记录暂存 cleanup 所需的 operation ID;下次更新尽力清理旧暂存后重新 prepare,不保存远端 metadata 副本,也不让 cleanup 失败阻塞新更新或回滚健康环境。已有项目在实际使用 Workspace/Runtime 时按需解析 Host current identity 并执行固定 `attach-or-bootstrap`,注册后的 health、capabilities 和 prompt 启动不扫描完整 payload。详见 [设计说明](./docs/architecture/remote-host-environment-provisioning-design.md)。
|
||||
- [ ] **SSH Host 环境准备真实 Host 验收**:源码已可使用当前 format v1 包;仍需完成 GitHub、北京镜像、Linux x64/arm64、取消和离线 GoodBuddy 传输的真实 Host 验收。当前状态不表示已发布或已完成真实 Host 测试。
|
||||
- [x] **DeepSeek Harness(预览)**:使用 GoodBuddy 固定 Host 和 OpenAI 兼容模型连接;Ask 只允许调用 Host 中真实注册的 `read`、`skill` 以及 Main 管理的 Web Search/Fetch 代理,拒绝插件同名冒充,Execute 放行全部已启用内置及插件工具,并以当前用户权限运行。图像输入跟随所选模型连接的能力声明,文本模型在 Host 或模型调用前拒绝图片,图片模型通过有界内联内容和临时 Attachment Store 接收 JPEG/PNG。
|
||||
- [x] **DSH npm 插件市场**:市场默认关闭,由用户显式开启后搜索公共 npm 的 `dsh-plugin` 包,使用捆绑 npm 执行精确版本安装和普通 lifecycle scripts,并支持启停、JSON 配置、移除、失败启动自动停用和离线管理已安装插件;关闭市场只隐藏目录与管理界面,不改变已有插件的启停状态,第三方代码不受 Ask 初始化隔离。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"agentVersion": "0.11.7",
|
||||
"agentVersion": "0.11.9",
|
||||
"protocol": {
|
||||
"major": 2,
|
||||
"minor": 0
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 状态
|
||||
|
||||
本文记录截至 2026-08-28 的当前代码实现,不定义额外的信任框架。“新增 Host 只探测、Host 卡片手动准备
|
||||
本文记录截至 2026-08-29 的当前代码实现,不定义额外的信任框架。“新增 Host 只探测、Host 卡片手动准备
|
||||
Agent/Runtime、Host 直接从 GitHub/北京镜像下载、项目始终使用 Host current 环境”已经完成源码接线,
|
||||
详细事务与验收边界见
|
||||
[SSH Host 远程环境准备与直连下载设计](./remote-host-environment-provisioning-design.md);
|
||||
@@ -13,10 +13,9 @@ Windows 到 Linux x64 的既有安装、
|
||||
Main-only 模型桥、断线恢复、输出重放、同一 OpenCode Session 续接与终态清理已经在真实
|
||||
Host 上完成 provider-free 验证。上一轮 Linux x64 验收使用 Agent `0.11.2-e2e.12` 与
|
||||
OpenCode Runtime `1.18.9` 完成了一次有界真实模型工具调用;加入每 helper 随机 loopback
|
||||
路径 capability 后,当前源码 lock 已更新为待发布 Agent `0.11.7`。失败的 `agent-v0.11.3`
|
||||
保持不可变且未发布。远程 OpenCode 功能仍处于发布前验证阶段;公开签名 key registry
|
||||
已供应,当前发布门槛是通过独立 Agent workflow 正式发布并公开验证 Linux x64/arm64
|
||||
复合包和签名累计目录。
|
||||
路径 capability 后,Agent `0.11.9` 已通过独立 workflow 发布 Linux x64/arm64 复合包和
|
||||
签名累计目录;当前桌面源码准备 `0.11.10`,修复 Host 更新并消除重复 payload 验证。失败的
|
||||
`agent-v0.11.3` 保持不可变且未发布。
|
||||
|
||||
## 产品语义
|
||||
|
||||
@@ -66,17 +65,16 @@ Detached GoodBuddy Agent
|
||||
|
||||
- Agent bundle 通过 manifest、Ed25519 签名、payload digest、平台和架构校验。
|
||||
- 安装使用当前 SSH 用户目录中的 GoodBuddy-owned 路径和 side-by-side digest 目录。
|
||||
- Agent 代码与固定 Node Runtime 是独立 payload。升级时如果当前 Host Agent 的签名
|
||||
manifest、registry identity、owner/mode/size 和 Node digest 都可验证,且候选
|
||||
manifest 声明完全相同的 Node,安装器直接在新的 side-by-side 目录中复用该 Node;
|
||||
否则正常上传候选 Node。Agent 不匹配不会阻止升级,也不会覆盖旧安装。
|
||||
- Agent 代码与固定 Node Runtime 一起位于签名 compound payload。显式安装或重装从本次
|
||||
已完整校验的准备目录原子发布整个 Agent,不扫描旧安装、不创建跨版本 Node 硬链接;
|
||||
Agent 不匹配不会阻止升级,也不会覆盖 GoodBuddy-owned 路径以外的内容。
|
||||
- 桌面包只携带版本 lock 与 production 公钥,不携带远端 payload。Host 卡片只有一个按
|
||||
版本事实显示“安装远程环境”“更新远程环境”或“重新安装”的主按钮;次级
|
||||
SegmentedControl 选择“自动”“Host 下载”或“GoodBuddy 传输”,默认“自动”且不持久化。
|
||||
每个复合包绑定 Agent、固定 Node 与桌面维护的 OpenCode Runtime 精确工件。添加或重新
|
||||
验证 Host 只保存并探测,不自动传输完整包。
|
||||
- Host 管理独占 Agent/Runtime 的包准备、更新和完整 payload 验证。已有项目的打开和切换
|
||||
只更新本地项目选择。Workspace 和执行路径按需通过安装管理器解析 Host current identity,
|
||||
只更新本地项目选择。Workspace 和执行路径按需读取 Host current registry,
|
||||
执行固定 `attach-or-bootstrap` 并复用当前 Agent 连接;同一进程内复用已确认 identity。
|
||||
它们不取得安装包、不发布组件,也不通过 SFTP 重读或哈希 payload。
|
||||
- Agent 的固定 attach/按需启动命令只读取 Host 管理已提交的 installation registry 和
|
||||
@@ -110,14 +108,16 @@ Detached GoodBuddy Agent
|
||||
bootstrap Node;约 294 MiB 完整包不会一次读入 Main `Buffer`,Host 仍再次校验完整包。
|
||||
- 两种 acquisition 交付到固定 operation staging 后,完全共用 control-plane
|
||||
`prepare → commit → Agent activate/health → Runtime activate → finalize → cleanup`。
|
||||
commit 终态持久化;通道丢失只用 `commit-status` 只读恢复,不重放 commit。prepare
|
||||
完成后、commit 前快照 Agent/Runtime 五个 metadata 文件,任一组件 adoption 失败都恢复其原字节或原缺失
|
||||
状态;已经发布的 side-by-side payload 可以保留但不能成为 current。确认 adoption 后
|
||||
才显式 cleanup。首次 bootstrap 不依赖既有 Agent daemon,也不要求 format v1 归档携带
|
||||
`agent/lib/package-installer.cjs`。
|
||||
Main 只保存清理 operation staging 所需的 operation ID。中断或 adoption 失败后,下次
|
||||
更新尽力清理旧暂存并重新 prepare,不保存或恢复 Agent/Runtime metadata 副本。确认
|
||||
adoption 后才显式 cleanup;cleanup 失败不回滚健康环境,也不阻塞下一次 fresh prepare。
|
||||
Host 在 prepare 解包时
|
||||
完成一次完整 payload 校验,commit 和后续注册检查不再遍历包体。首次 bootstrap 不依赖
|
||||
既有 Agent daemon,也不要求 format v1 归档携带 `agent/lib/package-installer.cjs`。
|
||||
- 即使版本号均为当前版本,Host 卡片仍提供同版本“重新安装”,用于修复 registry、签名
|
||||
或安装 identity 异常。GoodBuddy-owned 同 digest 目录损坏时先隔离后替换,并在发布或
|
||||
激活失败时恢复;不要求删除 Host、凭据或引用项目。
|
||||
原子 commit 失败时恢复;commit 成功后的激活失败保留新发布内容,下次点击重新安装时
|
||||
清理旧暂存并重新 prepare/adopt。不要求删除 Host、凭据或引用项目。
|
||||
- Host 卡片的“版本匹配”badge 只表达版本事实,不代表 Agent 正在运行或环境健康。重新安装
|
||||
失败时明确显示本次操作未完成,并以随后重新检查的版本卡片表达当前事实;提交结果
|
||||
不确定时不声称旧版本未被替换。
|
||||
@@ -187,8 +187,8 @@ Execute 不经过 Ask 的 bubblewrap profile:
|
||||
|
||||
- 直接启动已签名 Runtime entrypoint;
|
||||
- 使用 Main-only 模型桥时,签名 Agent launcher 会 `exec` 候选 manifest 锁定的
|
||||
Node Runtime;完全相同且已验证的 Node 可在 Agent 版本间复用。进程 owner 校验
|
||||
最终 Node executable,而不是已经被替换的 shell launcher 路径;
|
||||
Node Runtime;进程 owner 校验最终 Node executable,而不是已经被替换的 shell
|
||||
launcher 路径;
|
||||
- `cwd` 为项目 Workspace;
|
||||
- 继承 SSH 账号的正常环境、文件系统、进程和网络能力;
|
||||
- 不进行 T2/T3、confinement attestation、approval bridge 或逐工具批准。
|
||||
@@ -245,7 +245,8 @@ Execute 不经过 Ask 的 bubblewrap profile:
|
||||
|
||||
- 2026-08 的本地 fixture 完整验证 Linux x64 Agent `0.11.2-e2e.12`、Node `24.19.0`
|
||||
和 Agent protocol `2.0`;当时没有 arm64 fixture,因此该记录不能作为当前独立发布
|
||||
的双架构验收。当前源码 lock 是待发布版本 `0.11.7`,需要由新的复合包发布流程另行验证。
|
||||
的双架构验收。Agent `0.11.9` 后续已由原生 workflow 发布并公开验证双架构工件;
|
||||
当前源码 lock 固定为 `0.11.9`。
|
||||
- 正常 Host 更新路径把 Linux x64 Host 的 Agent 更新为 `0.11.2-e2e.12`,并确认
|
||||
OpenCode Runtime 已安装版本与所需版本均为 `1.18.9`。
|
||||
- 一条新的 Ask 用户操作只提交一次。OpenCode 先在 build 模型轮次请求一个原生
|
||||
|
||||
@@ -150,17 +150,15 @@ daemon 参与。两种 acquisition 的差别只在于如何把同一个签名 co
|
||||
|
||||
1. Main 创建带 operation ID、总时限、输出上限和取消信号的准备操作,并通过固定
|
||||
`prepare` channel 发送有界 one-shot installer 与结构化输入。
|
||||
2. Host 校验归档大小、SHA-256、外层及内层签名、平台、架构、协议和 payload digest,
|
||||
只把候选准备到 side-by-side 目录,不改变 current。
|
||||
3. `prepare` 完成后、`commit` 前按原字节记录 Agent 与 Runtime 的五个
|
||||
current/registry metadata 文件,
|
||||
同时记录原本缺失的状态。
|
||||
4. `commit` 终态先持久化到 operation staging。控制通道丢失时,Main 只用同一 operation
|
||||
的 `commit-status` 恢复结果,绝不重放 `commit`。
|
||||
5. commit 后依次完成 Agent activate/health、Runtime activate 和 finalize。任一组件
|
||||
adoption 失败都停止候选,并把五个 metadata 文件恢复为原字节或原缺失状态;已经发布的
|
||||
side-by-side payload 可以保留,但不能成为 current。
|
||||
6. Main 确认 adoption 后才显式执行 cleanup,释放 staging、缓存 lease 和操作资源。
|
||||
2. Host 在解包写入准备目录的同一遍处理中校验归档大小、SHA-256、外层及内层签名、
|
||||
平台、架构、协议和每个 payload digest;不再先完整扫描 payload、再重复解包和哈希。
|
||||
3. `commit` 只复核有界的签名 manifest、准备回执和入口 metadata,再以目录 rename 发布
|
||||
已准备内容及包内认证的公钥 registry/Runtime lock;不会重读归档或遍历 payload。
|
||||
4. commit 后在同一条已固定身份的 SSH lease 上执行 Agent bootstrap/readiness 和 Runtime
|
||||
activate。新 Agent 最多完整验证一次,新 Runtime 最多完整验证一次;注册成功后的
|
||||
health、capabilities 和 prompt 启动只读取 registry、签名 manifest 与入口 metadata。
|
||||
5. Main 确认 adoption 后显式执行 cleanup。cleanup 失败不回滚已经健康的 Agent/Runtime,
|
||||
也不阻塞下一次更新。
|
||||
|
||||
这不是两个并行安装管理器,也不存在把 Agent 与 Runtime payload 逐文件走 SFTP 安装的
|
||||
第二条路径。两种 acquisition 共享相同的 prepare、commit、adoption、finalize 与 cleanup。
|
||||
@@ -182,16 +180,16 @@ Host 下载返回明确失败;本次操作不自动切换 acquisition,用户
|
||||
后也走同一缓存 lease、上传和 Host 校验流程。
|
||||
- 本地项目和普通桌面打包不依赖任何远端 Agent 工件。
|
||||
|
||||
## 完整包与复用
|
||||
## 完整包与发布
|
||||
|
||||
第一阶段继续发布和下载完整复合 `.gbagent`,不同时引入组件化增量发布:
|
||||
|
||||
- 远程直连和 GoodBuddy 本机下载都会传输完整包,其中包含 Agent、固定 Node 和 OpenCode
|
||||
Runtime。
|
||||
- 新 Agent 安装时,如果旧 manifest、registry identity、owner/mode/size 和 Node digest
|
||||
全部可验证,并且候选声明同一 Node,则使用硬链接复用,不重新写入 Node 数据。
|
||||
- 相同 Runtime bundle digest 已存在且完整时只验证并激活,不重复上传或解包。
|
||||
- Agent 其他文件或变化后的 Runtime 仍按完整候选安装。
|
||||
- 每次显式安装或重装都从本次已经校验并解包的准备目录原子替换对应 Agent 与 Runtime
|
||||
digest 目录,不为节省本机磁盘写入而重新遍历旧目录,也不使用跨安装硬链接。
|
||||
- 操作中断后不续写旧 operation。下一次更新尽力清理其 staging,并从签名候选重新
|
||||
prepare;正常 cleanup 随后删除本次准备目录。
|
||||
|
||||
只有真实包体和发布频率证明网络成本仍不可接受时,才另行设计 Agent、Node 和 Runtime
|
||||
独立签名组件目录;本功能不提前引入第二套发布协议。
|
||||
@@ -216,11 +214,11 @@ Host 下载返回明确失败;本次操作不自动切换 acquisition,用户
|
||||
|
||||
同一 Host identity 同时只允许一个由用户启动、Main-owned 的准备操作。重复观察者加入
|
||||
已有操作,不启动第二次发布;窗口关闭、显式取消、Host identity 改变或 Main 退出时执行
|
||||
有界取消。Main 在 commit 前为该 Host 持久化一个不含凭据的 pending operation 记录;
|
||||
commit 指令开始后若 SSH 通道、输出或终态丢失,当前操作保留该记录和远端 staging。
|
||||
下一次重试或应用重启后的首次操作先对同一 Host identity 执行只读 `commit-status` 和
|
||||
cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清理后删除 pending 记录。
|
||||
取消在最终原子切换完成后不再伪装成回滚成功。
|
||||
有界取消。Main 只为该 Host 持久化一个不含凭据的 version-1 pending operation ID,用于
|
||||
下一次操作开始时尽力清理旧 staging。无论旧 cleanup 成功、目标已变化还是旧记录损坏,
|
||||
都删除这条可丢弃记录并开始 fresh prepare;不保存远端 metadata 副本,不续写旧 commit,
|
||||
也不跨重启恢复 adoption。当前操作中可确定的失败会立即尽力 cleanup。环境已健康后的
|
||||
cleanup 失败不回滚环境,也不阻塞下一次更新。
|
||||
|
||||
## 项目创建与切换
|
||||
|
||||
@@ -264,19 +262,21 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
- 扩展当前 Host 系统探针和远程环境 inspector,返回瞬时下载准备能力。
|
||||
- 让当前 `RemoteEnvironmentUpdateService` 演进为 Host 环境准备编排器,统一用户手动
|
||||
启动的首次安装和后续更新、自动 acquisition 选择、进度、取消和最终失效。
|
||||
- Host 管理使用安装管理器完成准备、更新和完整验证。项目切换不调用安装管理器;
|
||||
Workspace 和执行路径按需解析 current identity,并在当前进程内复用已确认 identity 和
|
||||
Agent 连接;Host 编辑或环境更新定向清空这些缓存。这些路径不会取得安装包或发布组件。
|
||||
- Host 环境准备编排器直接完成一次 package prepare/commit 及 Agent/Runtime adoption。
|
||||
Workspace 和执行路径只读取 current registry 并调用 Host 侧轻量 identity/health 检查,
|
||||
在当前进程内复用已确认 identity 和 Agent 连接;Host 编辑或环境更新定向清空这些缓存。
|
||||
这些路径不会取得安装包、发布组件或通过 SFTP 扫描 payload。
|
||||
- Host 卡片即使显示相同版本也保留显式重装操作,用于修复 registry、签名或 payload
|
||||
identity 异常;若同一 digest 的 GoodBuddy-owned 目录校验失败,重装会先隔离旧目录,
|
||||
完整发布并验证新目录,失败时恢复旧目录。重装不要求删除 Host、凭据或项目,也不会处理
|
||||
所有者异常、符号链接或非 GoodBuddy 管理路径。
|
||||
并在原子 commit 失败时恢复旧目录。commit 成功后的 adoption 失败保留新发布内容,
|
||||
下次重装清理旧暂存并重新 prepare/adopt。重装不要求删除 Host、凭据或项目,也不会
|
||||
处理所有者异常、符号链接或非 GoodBuddy 管理路径。
|
||||
- 由桌面控制面打包有界 one-shot installer,并通过固定短命令 `exec sh -s` 和 stdin
|
||||
发送脚本及结构化输入,避免 SSH command 长度限制;既有 package format v1 归档内固定
|
||||
Node 负责解码和运行它。
|
||||
- Preload 只暴露明确的 Host 探测、准备、取消和进度方法,不暴露 URL 或任意 SSH 命令。
|
||||
- 现有 Agent/Runtime side-by-side、Node 硬链接复用、Host identity 二次核对、Host 端
|
||||
发布后复验、连接失效和项目稳定配置事务继续作为唯一实现。
|
||||
- 现有 Agent/Runtime side-by-side、固定 SSH lease、Host 端一次完整验证、注册后轻量检查、
|
||||
连接失效和项目稳定配置事务继续作为唯一实现。
|
||||
|
||||
## 迁移
|
||||
|
||||
@@ -288,6 +288,8 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
- 如果 Host 未就绪或版本不兼容,项目仍可在本地选择,但实际远程操作失败;不再走旧的
|
||||
隐式安装。
|
||||
- 已下载或导入的本地 `.gbagent` 保持可用,不能因加入远程直连而迁移或删除。
|
||||
- pending operation 保持 version 1,只记录 Host、目标 identity 与 operation ID,用于
|
||||
尽力清理旧 staging;它不是远端环境状态或恢复日志。
|
||||
- 远程直连继续使用现有 package format version 1,不要求归档携带 installer,也不要求
|
||||
目录声明额外的 bootstrap 能力元数据。
|
||||
|
||||
@@ -303,7 +305,9 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
4. 直接下载严格匹配签名目录中的 URL、大小和 SHA-256;GoodBuddy 传输可在同一次操作中
|
||||
下载并验证缺失候选,以有界流式 SFTP 上传完整归档和已验证 bootstrap Node。Host 对
|
||||
两者完成相同的外层与内层签名、路径、架构、协议和 payload 校验。
|
||||
5. 相同 Node 在可验证且支持硬链接时不重复传输或写入;相同 Runtime digest 不重复安装。
|
||||
5. Host 对本次候选只完成一次完整 payload 校验;commit、adoption、health、capabilities
|
||||
和 prompt 启动不得再次遍历或哈希完整 Agent/Runtime,显式重装仍能用本次准备内容修复
|
||||
同 digest 的损坏目录。
|
||||
6. 创建、打开和切换项目不会产生 `.gbagent` 下载、Agent payload SFTP 上传或安装目录发布。
|
||||
7. 未就绪 Host 不能创建远程项目;已有项目仍可本地选择,但远程操作失败并引导到 Host 设置。
|
||||
8. Host 编辑或更新后,引用项目使用 Host 管理的当前连接和 current registry,不读取项目
|
||||
@@ -317,5 +321,6 @@ cleanup,不重放未知 commit,也不开始第二条 acquisition;确认清
|
||||
仍待完成。
|
||||
12. Host 不可达或远端目录不存在时,用户仍可从项目浮动管理入口删除本地项目;删除 Host
|
||||
会列出并本地清理全部关联项目,但不会连接 Host 或删除任何远端目录和内容。
|
||||
13. commit 终态可在通道丢失后用 `commit-status` 只读恢复且不重放;Agent 或 Runtime
|
||||
adoption 失败恢复五个 metadata 文件的原字节/原缺失状态,确认 adoption 后显式 cleanup。
|
||||
13. 中断或 adoption 失败后的下一次更新只尽力清理旧 staging,然后 fresh prepare;
|
||||
pending record 不包含远端 metadata 副本。已健康环境的 cleanup 失败不触发回滚,
|
||||
也不阻塞下一次更新。
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
# GoodBuddy Release Runbook
|
||||
|
||||
Read this runbook only when preparing, publishing, recovering, or verifying a
|
||||
desktop or GoodBuddy Agent release.
|
||||
|
||||
This is an operator and CI procedure. It does not authorize adding application
|
||||
persistence, snapshots, journals, rollback engines, recovery protocols, or
|
||||
compatibility layers to automate release operations. Determine release recovery
|
||||
from the authoritative GitHub, OSS, workflow, and Git state, then use the
|
||||
smallest existing idempotent rerun or a new immutable version as specified
|
||||
below.
|
||||
|
||||
## Release Packaging
|
||||
|
||||
- Unless the user explicitly requests a local Windows package, never run local
|
||||
Windows packaging or launch probes as part of release preparation. In
|
||||
particular, do not run `npm run portable`, Windows
|
||||
`npm run release:package`, direct `electron-builder` packaging, or launch a
|
||||
locally packaged Windows app before publishing a release. Source validation
|
||||
and the native GitHub Actions jobs are the release authorities.
|
||||
- After a release is published, confirm only that the expected Windows assets
|
||||
exist in the public release metadata. Do not locally rebuild or launch the
|
||||
Windows package, download or hash published installers, attach browser
|
||||
automation to a packaged app, or perform exhaustive per-asset network probes
|
||||
unless the user explicitly asks for that additional validation.
|
||||
- `.github/workflows/packages.yml` is the canonical cross-platform packaging
|
||||
workflow. It validates and builds `out` once, then packages on six native
|
||||
runners: Windows, macOS, and Linux, each for x64 and arm64.
|
||||
- The experimental Linux LoongArch (`loong64`) preview is built separately
|
||||
through `build/loongarch-cross` by following
|
||||
`docs/development/loongarch-preview-build.md`. It is not part of
|
||||
`.github/workflows/packages.yml`, the six-runner GitHub Actions matrix,
|
||||
standard release manifests, GitHub Release asset expectations, or the
|
||||
production update index. Do not add it to those paths unless the user
|
||||
explicitly requests a future production-support migration.
|
||||
- Run the unified packager with
|
||||
`npm run release:package -- --platform <platform> --arch <arch>`. It only
|
||||
packages for the native host and writes to
|
||||
`dist/release/<platform>-<arch>`.
|
||||
- Default deliverables are NSIS and portable ZIP for Windows, DMG and ZIP for
|
||||
macOS, and AppImage, DEB, and RPM for Linux. Every target includes
|
||||
`release-manifest.json` with SHA-256 hashes.
|
||||
- `build/build-release.cjs` verifies the unpacked application, `app.asar`,
|
||||
bundled Continue and OpenCode runtimes, executable architecture, and package
|
||||
signatures before atomically replacing a release directory.
|
||||
- All desktop build paths, including local `portable`, package the Agent and
|
||||
remote Runtime version locks plus the public signing-key registry without
|
||||
embedding installable Linux Agent or remote Runtime payloads. Managed SSH is
|
||||
optional: users explicitly download a compatible compound `.gbagent` package
|
||||
from Settings or import one offline before GoodBuddy can install or update a
|
||||
Host.
|
||||
- Each independently published Linux x64 or arm64 `.gbagent` contains the
|
||||
Agent daemon, pinned Node, and the desktop-maintained compatible OpenCode
|
||||
Runtime. Build both architectures on native GitHub Actions runners from one
|
||||
immutable `agent-v<agentVersion>` tag.
|
||||
- Keep the GoodBuddy Agent source, shared protocol/contracts, runtime lock,
|
||||
bundle tooling, and tests in this repository so a desktop commit identifies
|
||||
the exact Agent source it expects. Do not create a separate Agent repository
|
||||
or long-lived Agent release branch unless the Agent becomes an independently
|
||||
released product serving multiple clients.
|
||||
- `.github/workflows/agents.yml` is the branch and pull-request build
|
||||
verification workflow for GoodBuddy Agent. It must build Linux x64 and
|
||||
arm64 on native runners from the checked-out commit, acquire the locked
|
||||
official Node archive and locked OpenCode npm archive, verify every locked
|
||||
digest, use only an ephemeral in-memory test signing identity, and verify the
|
||||
resulting compound package and deterministic archive. It must not read
|
||||
production signing secrets, publish installable release artifacts, or modify
|
||||
the checked-in public key registry.
|
||||
- `.github/workflows/agent-release.yml` is the only production compound Agent
|
||||
publication path. It requires an annotated immutable Agent tag, the protected
|
||||
`agent-signing` Environment, native x64/arm64 builds, one production
|
||||
GoodBuddy signing identity for every layer of the compound package and
|
||||
catalog, a non-Latest GitHub Agent Release, and synchronized immutable
|
||||
Beijing OSS objects plus the final signed latest-catalog pointer.
|
||||
- `.github/workflows/packages.yml` and `release:package` build only desktop
|
||||
products. Missing Agent packages, remote Runtime inputs, or GoodBuddy signing
|
||||
credentials must never block an ordinary desktop package or release.
|
||||
- Keep electron-builder invocations on `--publish never`. Main-branch builds
|
||||
run validation and build the production bundle without running the native
|
||||
package matrix. Manual builds upload 30-day GitHub Actions artifacts.
|
||||
Version-tag builds verify and aggregate packages before publishing GitHub
|
||||
Release assets. The macOS jobs sign, notarize, and verify packages when all
|
||||
five Apple credentials are configured. With no Apple credentials they must
|
||||
use the explicit `--unsigned` path, warn that Gatekeeper may block the
|
||||
packages, and still complete; a partial credential set must fail rather than
|
||||
silently downgrade.
|
||||
- Keep `ELECTRON_CACHE` and `ELECTRON_BUILDER_CACHE` under
|
||||
`${{ runner.temp }}` in step-level workflow contexts. A cache beneath the
|
||||
repository inherits the root `"type": "module"` and breaks electron-builder's
|
||||
CommonJS macOS icon tool.
|
||||
- Tag builds must use `v${package.version}`. The workflow also supports manual
|
||||
dispatch and main-branch changes to release tooling.
|
||||
|
||||
### Agent Release Process
|
||||
|
||||
- Agent releases use annotated `agent-v${agent-runtime-lock.agentVersion}` tags
|
||||
and are separate from desktop `v${package.version}` releases. Confirm the
|
||||
exact Agent release commit and tag with the user before creating or pushing
|
||||
either.
|
||||
- The tagged commit must be reachable from protected `main`. The two native
|
||||
jobs build the compound x64/arm64 packages from the same source and locks;
|
||||
the catalog job rejects missing architectures, changed bytes for an existing
|
||||
version/architecture identity, invalid prior signatures, and incompatible
|
||||
matrix metadata.
|
||||
- Agent GitHub Releases are ordinary non-draft, non-prerelease releases but
|
||||
must use `--latest=false`; they must never replace the desktop release marked
|
||||
Latest. Publish immutable packages and the versioned catalog to
|
||||
`agent-releases/v<agentVersion>/` in Beijing OSS, publish the GitHub Agent
|
||||
Release, then atomically update the single `agent-releases/latest.json`
|
||||
pointer to that version's immutable catalog and signature.
|
||||
- Do not report an Agent release complete until both public package
|
||||
architectures match the signed catalog by size and SHA-256, the GitHub and
|
||||
OSS catalog bytes/signatures are identical, the application can read the
|
||||
selected source, and GitHub's repository Latest tag remains the desktop tag.
|
||||
|
||||
### Tagged Release Process
|
||||
|
||||
Every version-tag release must follow this sequence. A branch-only push does
|
||||
not require release notes.
|
||||
|
||||
1. Confirm that the user wants a release tag and identify the exact release
|
||||
commit and the new `package.json` version. Separately ask whether this
|
||||
release should also receive an experimental LoongArch preview build; never
|
||||
infer that choice from an earlier release.
|
||||
2. Find the latest stable version tag reachable before the release commit and
|
||||
inspect the complete commit and file diff from that tag to the release
|
||||
commit. For the first tagged release, inspect the relevant repository
|
||||
history instead.
|
||||
3. Draft concise, user-facing release notes in both Simplified Chinese and
|
||||
English based only on verified changes in that range. Use the titles
|
||||
`GoodBuddy <version> 更新内容` and
|
||||
`What's New in GoodBuddy <version>`, with corresponding `功能更新` /
|
||||
`Features` and `问题修复` / `Bug Fixes` sections when applicable. The two
|
||||
language versions must describe the same changes. Do not expose
|
||||
internal-only details, credentials, private content, or unverified claims.
|
||||
4. Show the exact bilingual release-note draft to the user and wait for
|
||||
explicit approval. If the release commit or either language version changes
|
||||
after approval, inspect the updated tag range and request approval again.
|
||||
5. Write the approved notes to the single entry for the release version in
|
||||
`resources/release-notes.json`. A failed unpublished candidate whose content
|
||||
is carried forward must not retain a duplicate packaged entry.
|
||||
6. Verify that `package.json`, the root `package-lock.json` version, and
|
||||
`package-lock.json.packages[""].version` all equal the release version. Run
|
||||
`npm run release:notes:verify`, the required source validators, the
|
||||
production build. The six native CI jobs remain the cross-platform
|
||||
authority; do not add local packaging or packaged-app launch probes unless
|
||||
the user explicitly requests them.
|
||||
If the user requested a LoongArch preview in step 1, build it separately
|
||||
from this exact candidate by following the LoongArch build document, record
|
||||
its size and SHA-256, and keep it outside the standard GitHub/OSS release
|
||||
asset set unless the user separately authorizes publishing it.
|
||||
7. Fetch both remotes immediately before tagging. Inspect any remote branch
|
||||
movement instead of overwriting or silently merging it. Confirm the working
|
||||
tree is clean, the candidate tag is unused locally and remotely, and the
|
||||
exact approved commit has not changed.
|
||||
8. Only after all previous steps pass, create an annotated
|
||||
`v${package.version}` tag at the exact approved commit. Push `main` to
|
||||
`origin` and `github`, verify both branch SHAs, then push the tag to both
|
||||
remotes and verify each peeled tag SHA (`refs/tags/<tag>^{}`) equals the
|
||||
release commit.
|
||||
9. Keep both approved language versions as the single source for the GitHub
|
||||
Release body and the packaged first-open release-notes modal. The modal
|
||||
displays the release notes matching the current interface language and
|
||||
contains no button linking to a full release page.
|
||||
10. Observe the tag workflow through publication and complete the public
|
||||
verification checklist below. A successful push is not a completed
|
||||
release.
|
||||
|
||||
### OSS Publication Contract
|
||||
|
||||
The tagged release job publishes through the GitHub Environment selected by
|
||||
`.github/workflows/packages.yml` (`aliyun-oss-release`) and reads the following
|
||||
effective GitHub Actions variables. Before a release or same-tag rerun can
|
||||
publish, verify that repository-, organization-, or environment-level
|
||||
resolution exposes:
|
||||
|
||||
- `ALIYUN_OSS_BUCKET=goodbuddy`
|
||||
- `ALIYUN_OSS_ENDPOINT=https://oss-cn-beijing.aliyuncs.com`
|
||||
- a non-empty `ALIYUN_OIDC_PROVIDER_ARN` matching
|
||||
`acs:ram::*:oidc-provider/*`
|
||||
- a non-empty `ALIYUN_ROLE_ARN` matching `acs:ram::*:role/*`
|
||||
|
||||
For environment-scoped values, use the exact Environment name from the
|
||||
workflow; do not assume a similarly named UI environment such as `Production`
|
||||
contains the active variables.
|
||||
|
||||
The Bucket and Endpoint are a deployment contract, not interchangeable
|
||||
examples. They must stay aligned with the trusted URL checks in
|
||||
`src/main/version-checker.ts`, `sites/app.js`, website validation, and related
|
||||
tests. A host, Bucket, Region, or CDN migration must update and validate every
|
||||
surface together before a new release.
|
||||
|
||||
- Use GitHub OIDC and the RAM Role to obtain short-lived STS credentials.
|
||||
Never add long-lived AccessKeys to repository or environment secrets.
|
||||
- Keep `ossutil` pinned. Its V4 signing requires the Region; derive it from the
|
||||
canonical Endpoint, verify that the production value resolves to
|
||||
`cn-beijing`, and pass `--region` to every `ossutil cp`, including the final
|
||||
`latest.json` update.
|
||||
- Grant the RAM Role only the actions and prefixes required by the workflow.
|
||||
It must be able to write immutable version objects and the final latest
|
||||
pointer without granting unrelated administration privileges.
|
||||
- Upload release assets and `site-release.json` under the immutable
|
||||
`releases/<tag>/` prefix first. Verify all 14 installer URLs publicly before
|
||||
creating or publishing the GitHub Release. Update
|
||||
`releases/latest.json` only after the GitHub Release is public and all prior
|
||||
checks succeeded.
|
||||
- The expected GitHub Release contains 22 assets: 14 installers (two formats
|
||||
for each Windows/macOS target and three formats for each Linux target), six
|
||||
renamed target manifests, one aggregate `release-manifest.json`, and one `SHA256SUMS`.
|
||||
`site-release.json` is an OSS publication artifact, not a GitHub Release
|
||||
asset.
|
||||
|
||||
### Failed Tag Recovery
|
||||
|
||||
Classify a failed tag by the external side effects that completed before
|
||||
choosing a recovery:
|
||||
|
||||
- If no source or release metadata must change, correct only the external
|
||||
configuration and use **Re-run failed jobs** for the same immutable tag. Do
|
||||
not change, move, delete, or recreate the tag.
|
||||
- If immutable OSS objects were partially uploaded but their source bytes are
|
||||
unchanged, a same-tag rerun may idempotently re-upload or verify them. Never
|
||||
point `latest.json` at a partially verified prefix.
|
||||
- If the GitHub Release is already public but the final latest-pointer step
|
||||
failed, it is a published version. Keep its packaged notes and rerun the
|
||||
failed release job for the same tag; do not classify it as an unpublished
|
||||
candidate.
|
||||
- If code or release metadata must change, keep the failed tag immutable,
|
||||
increment the patch version, obtain approval for the revised exact release
|
||||
commit and notes, and create a new tag. Do not reuse the failed version.
|
||||
|
||||
When recovering from a version tag whose workflow never published a public
|
||||
GitHub Release:
|
||||
|
||||
- If a code or metadata change requires a higher version and a new tag, carry
|
||||
the failed candidate's approved user-facing notes forward into the recovery
|
||||
version, then remove the superseded failed version's entry from
|
||||
`resources/release-notes.json`.
|
||||
- The packaged first-open modal must show that carried-forward content only
|
||||
once under the recovery version. Never retain both the failed version and
|
||||
its cumulative recovery copy, because users upgrading across them would see
|
||||
duplicate content.
|
||||
- Never remove the packaged history for a version that successfully published
|
||||
a GitHub Release. Verify the failed release state before treating an entry as
|
||||
superseded.
|
||||
|
||||
### Post-Publication Verification
|
||||
|
||||
Do not report a release complete until all of the following are verified:
|
||||
|
||||
1. The tag workflow and all six native package jobs succeeded. Verify the
|
||||
recorded macOS signing mode: signed builds must pass `codesign`, `spctl`,
|
||||
and `stapler`; unsigned builds must record the Gatekeeper caveat in the
|
||||
Actions log and job summary. In the final release job, explicitly verify
|
||||
the OSS configuration, OIDC authentication, release-index generation,
|
||||
immutable upload, public asset check, GitHub Release publication, and
|
||||
latest-pointer steps.
|
||||
2. The public GitHub Release is non-draft, non-prerelease, marked Latest, and
|
||||
uses the expected tag and title. Its body must exactly match the Markdown
|
||||
generated from the approved packaged bilingual notes.
|
||||
3. GitHub release metadata contains exactly the expected 22 uploaded asset
|
||||
names, including the expected Windows x64 and arm64 assets. Do not download,
|
||||
hash, launch, or send individual network probes to published installers
|
||||
unless the user explicitly requests that additional validation.
|
||||
4. The Beijing `releases/latest.json` returns HTTP 200, has the expected stable
|
||||
version, exact six targets and 14 installer entries, the trusted Beijing
|
||||
URLs, and the GitHub fallback URL. It must match the immutable
|
||||
`releases/<tag>/site-release.json`. Fetching and comparing these small JSON
|
||||
metadata files is sufficient; rely on the successful publication job for
|
||||
its per-asset public checks.
|
||||
5. The live website successfully fetches the index and produces the 14 correct
|
||||
platform/architecture/format links from that metadata.
|
||||
6. Both remote `main` refs and both peeled tag refs still equal the approved
|
||||
release commit, and the local working tree is clean.
|
||||
|
||||
Never create or push a release tag, and never push a previously created
|
||||
release tag, before the release-note draft has received explicit approval.
|
||||
|
||||
- Before a push that updates the `github` remote, ask whether the user wants a
|
||||
release tag unless they already specified that choice. A branch-only push
|
||||
does not require a version bump or tag. When the user requests a release,
|
||||
verify that `package.json` and `package-lock.json` contain the same release
|
||||
version, create `v${package.version}` at the exact commit being pushed, and
|
||||
push that tag so the native package matrix and GitHub Release run.
|
||||
- Never move or reuse an existing release tag. If `v${package.version}` already
|
||||
exists locally or on a remote at another commit, increment the package
|
||||
version and create a new matching tag before the release push.
|
||||
- Verified release baseline on 2026-08-18: commit
|
||||
`60119a4317118fa3f077db0382664f15266a6682`, annotated tag `v0.10.4`, and
|
||||
GitHub Actions run `32038633609` attempt 2 succeeded through all six native
|
||||
packages, GitHub Release publication, Beijing OSS publication, and the final
|
||||
`latest.json` switch.
|
||||
@@ -586,12 +586,14 @@ attach 并读取 current registry,不存在项目中的旧 Host revision 或
|
||||
prepare channel 发送有界 one-shot installer;Host 先验证目录绑定的归档大小和 SHA-256,
|
||||
再由 format v1 归档内固定 Node 解码并运行 installer。归档无需包含
|
||||
`agent/lib/package-installer.cjs`,目录不提供或检查额外的 bootstrap 能力元数据。
|
||||
- Agent 与 Runtime 各自维护版本,签名摘要标识精确工件;使用 side-by-side 安装、自检和
|
||||
健康切换,失败时不改变当前项目绑定。相同且可验证的 Node 使用硬链接复用,相同 Runtime
|
||||
digest 不重复安装。
|
||||
- commit 终态持久化,控制通道丢失时只用 `commit-status` 恢复而不重放。prepare 完成后、commit 前快照
|
||||
Agent/Runtime 五个 metadata 文件;任一组件 adoption 失败恢复原字节或原缺失状态,
|
||||
已发布 payload 不得成为 current,确认 adoption 后显式 cleanup。
|
||||
- Agent 与 Runtime 各自维护版本,签名摘要标识精确工件。Host 在解包到准备目录的同一遍
|
||||
处理中完成完整 payload 校验,commit 只复核签名 metadata 并原子替换 side-by-side
|
||||
目录,不重新读取归档、扫描旧目录或使用跨安装硬链接。
|
||||
- Main 只保存清理 operation staging 所需的 operation ID。控制通道中断或 adoption 失败
|
||||
后,下次更新尽力清理旧暂存并重新 prepare,不保存或恢复 Agent/Runtime metadata 副本。
|
||||
新 Agent/Runtime 各自最多完整验证一次;注册后的
|
||||
health、capabilities 和 prompt 启动只检查 registry、签名 manifest 与入口 metadata。
|
||||
确认 adoption 后显式 cleanup,cleanup 失败不回滚健康环境,也不阻塞下一次 fresh prepare。
|
||||
- 握手报告 installation、Daemon boot identity、协议、系统、架构、用户监督器和能力。
|
||||
- 在远程执行路径规范化、Git、文件、PTY、进程组和 Runtime 管理。
|
||||
- 持久化有界 Agent 到 Main 输出;SSH 断开后 Agent 继续运行,同一 Agent 重连时只恢复
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.10",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.10",
|
||||
"license": "0BSD",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "0.25.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.7",
|
||||
"version": "0.11.10",
|
||||
"private": true,
|
||||
"description": "Secure desktop AI workspace with controlled Agent Runtimes",
|
||||
"desktopName": "GoodBuddy",
|
||||
|
||||
@@ -1,6 +1,40 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"releases": [
|
||||
{
|
||||
"version": "0.11.10",
|
||||
"releasedAt": "2026-08-29",
|
||||
"notes": {
|
||||
"zh-CN": {
|
||||
"highlights": [
|
||||
"GoodBuddy 0.11.10 修复正式环境中的 Host 更新失败,并显著缩短 Agent 与 OpenCode Runtime 的安装、恢复和日常启动校验。"
|
||||
],
|
||||
"features": [],
|
||||
"fixes": [
|
||||
"**Host 更新恢复可用。** 修复已发布 OpenCode Runtime 在采用阶段被桌面内置锁重复校验而失败的问题。Host 现在使用签名复合包中的版本锁和身份,并在同一条固定 SSH 连接上完成 Agent 启动、健康检查与 Runtime 激活。",
|
||||
"**不再重复扫描远端包体。** 每种获取路径只对复合包执行一次完整 SHA-256;Host installer 在解包时验证全部签名与 payload digest,commit 只检查签名元数据。Main 不再通过 SFTP 逐文件读取 Agent/Runtime,后续健康检查、能力发现和每次提问只使用已登记 identity、manifest 与入口元数据。仍保留 SHA-256,提速来自消除重复读取。",
|
||||
"**失败后直接重试。** 未完成操作只保留一个小型 staging 清理记录;下次更新先尽力清理旧暂存,再重新 prepare,不保存或回滚 Agent/Runtime 元数据副本。已健康环境不会因暂存清理失败而回滚,安装错误仍会显示具体的有界原因。"
|
||||
],
|
||||
"notices": [
|
||||
"**技术预览与版本要求。** 远程项目仍默认关闭且为技术预览。Host 需要安装单独发布的 Agent `0.11.9`,提供 Linux x64 和 arm64;桌面包不内置 Agent 或远程 Runtime,本次不构建 LoongArch 预览。"
|
||||
]
|
||||
},
|
||||
"en-US": {
|
||||
"highlights": [
|
||||
"GoodBuddy 0.11.10 fixes Host updates in production and substantially reduces Agent and OpenCode Runtime verification during installation, recovery, and normal startup."
|
||||
],
|
||||
"features": [],
|
||||
"fixes": [
|
||||
"**Host updates work again.** Fixed published OpenCode Runtime adoption failing because it was redundantly checked against the desktop-bundled lock. The Host now uses the signed compound package's lock and identity, then starts and health-checks the Agent and activates Runtime on one pinned SSH connection.",
|
||||
"**No repeated remote payload scans.** Each acquisition path performs one full SHA-256 pass over the compound package. The Host installer verifies every signature and payload digest while extracting, and commit checks only signed metadata. Main no longer reads Agent or Runtime file trees over SFTP. Later health, capability, and prompt paths use registered identities, manifests, and entrypoint metadata. SHA-256 remains; the speedup comes from eliminating rereads.",
|
||||
"**Simple retry after failures.** An unfinished operation keeps only a small staging-cleanup receipt. The next update makes one best-effort cleanup attempt and performs a fresh prepare without saving or restoring copies of Agent or Runtime metadata. A healthy environment is not rolled back for staging cleanup failures, and bounded installer errors retain their concrete cause."
|
||||
],
|
||||
"notices": [
|
||||
"**Technical preview and version requirement.** Remote Projects remain disabled by default and in technical preview. Hosts require the separately published Agent `0.11.9` for Linux x64 or arm64. Desktop packages do not embed the Agent or remote Runtime, and this release does not build a LoongArch preview."
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "0.11.7",
|
||||
"releasedAt": "2026-08-29",
|
||||
|
||||
@@ -192,11 +192,13 @@ describe('Agent CLI fixed command contract', () => {
|
||||
state: 'ready' as const,
|
||||
installationId
|
||||
}))
|
||||
const verifyInstallation = vi.fn(async () => verified)
|
||||
const dependencies: AgentCliDependencies = {
|
||||
installationPaths: () => installationPaths,
|
||||
releaseKeyRegistry,
|
||||
installationRegistry,
|
||||
verifyInstallation: async () => verified,
|
||||
verifyInstallation,
|
||||
loadRegisteredInstallation: async () => verified,
|
||||
createLifecycle: (() => ({
|
||||
status,
|
||||
bootstrap
|
||||
@@ -227,6 +229,21 @@ describe('Agent CLI fixed command contract', () => {
|
||||
).toBe(0)
|
||||
expect(status).toHaveBeenCalledOnce()
|
||||
expect(bootstrap).toHaveBeenCalledOnce()
|
||||
expect(
|
||||
installationRegistry.snapshot().current?.installationId
|
||||
).toBe(installationId)
|
||||
|
||||
expect(
|
||||
await runAgentCli(
|
||||
buildFixedAgentCliArgv(installationId, {
|
||||
kind: 'lifecycle',
|
||||
action: 'adopt'
|
||||
}),
|
||||
{ ...dependencies, io: cliIo() }
|
||||
)
|
||||
).toBe(0)
|
||||
expect(verifyInstallation).toHaveBeenCalledOnce()
|
||||
expect(bootstrap).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('dispatches generated attach argv using only derived managed paths', async () => {
|
||||
@@ -469,6 +486,31 @@ describe('Agent CLI fixed command contract', () => {
|
||||
architecture: 'x64',
|
||||
runtimeVersion: '1.18.9'
|
||||
})
|
||||
|
||||
expect(
|
||||
await runAgentCli(
|
||||
buildFixedAgentCliArgv(
|
||||
verifyAgentInstallationId('install-1'),
|
||||
{
|
||||
kind: 'runtime-activate',
|
||||
runtimeId: 'opencode',
|
||||
bundleDigest,
|
||||
architecture: 'x64',
|
||||
forceVerification: true
|
||||
}
|
||||
),
|
||||
{
|
||||
runtimePaths: () => paths,
|
||||
runtimeReleaseKeyRegistry: releaseKeyRegistry,
|
||||
runtimeLock: {} as RemoteRuntimeLock,
|
||||
runtimeRegistry: registry,
|
||||
verifyRuntime,
|
||||
currentArchitecture: () => 'x64',
|
||||
io: cliIo()
|
||||
}
|
||||
)
|
||||
).toBe(0)
|
||||
expect(verifyRuntime).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('derives Runtime paths and rejects activation argv injection', async () => {
|
||||
|
||||
+188
-40
@@ -31,7 +31,7 @@ import {
|
||||
loadRegisteredAgentBundle,
|
||||
readManagedAgentReleaseKeyRegistry,
|
||||
RegisteredAgentBundleError,
|
||||
verifyInstalledAgentBundle,
|
||||
verifyPublishedAgentBundle,
|
||||
type VerifiedInstalledAgentBundle
|
||||
} from './installed-bundle-verifier'
|
||||
import { InstallationRegistry } from './installation-registry'
|
||||
@@ -39,8 +39,9 @@ import {
|
||||
RuntimeBundleRegistry
|
||||
} from './runtime-bundle-registry'
|
||||
import {
|
||||
loadRegisteredRuntimeBundle,
|
||||
readRemoteRuntimeLock,
|
||||
verifyRuntimeBundle,
|
||||
verifyPublishedRuntimeBundle,
|
||||
type VerifiedRuntimeBundle
|
||||
} from './runtime-bundle-verifier'
|
||||
import { createProductionRuntimeProtocol } from './runtime-composition'
|
||||
@@ -90,7 +91,7 @@ export type AgentCliDependencies = {
|
||||
runtimeReleaseKeyRegistry?: AgentReleaseKeyRegistry
|
||||
runtimeLock?: RemoteRuntimeLock
|
||||
runtimeRegistry?: RuntimeBundleRegistry
|
||||
verifyRuntime?: typeof verifyRuntimeBundle
|
||||
verifyRuntime?: typeof verifyPublishedRuntimeBundle
|
||||
runtimeVerificationEnvironment?: 'production' | 'test'
|
||||
currentArchitecture?: () => AgentArchitecture
|
||||
runModelBridgeHelper?: typeof runOpenCodeModelBridgeHelper
|
||||
@@ -111,6 +112,7 @@ export type ManagedRuntimePaths = {
|
||||
}
|
||||
|
||||
const LIFECYCLE_ACTIONS = new Set([
|
||||
'adopt',
|
||||
'bootstrap',
|
||||
'status',
|
||||
'health',
|
||||
@@ -225,7 +227,8 @@ async function runRuntime(
|
||||
'installation-id',
|
||||
'runtime-id',
|
||||
'bundle-digest',
|
||||
'architecture'
|
||||
'architecture',
|
||||
'force-verification'
|
||||
])
|
||||
requireOptions(options, [
|
||||
'installation-id',
|
||||
@@ -243,6 +246,16 @@ async function runRuntime(
|
||||
const architecture = validateRuntimeArchitecture(
|
||||
options.architecture!
|
||||
)
|
||||
const forceVerification =
|
||||
options['force-verification'] === 'true'
|
||||
if (
|
||||
options['force-verification'] !== undefined &&
|
||||
!forceVerification
|
||||
) {
|
||||
throw new Error(
|
||||
'Invalid Runtime force-verification option'
|
||||
)
|
||||
}
|
||||
const hostArchitecture =
|
||||
dependencies.currentArchitecture?.() ??
|
||||
currentAgentArchitecture()
|
||||
@@ -271,15 +284,30 @@ async function runRuntime(
|
||||
runtimeRoot: paths.runtimeRoot,
|
||||
storagePath: paths.registryPath
|
||||
})
|
||||
const verified = await (
|
||||
dependencies.verifyRuntime ?? verifyRuntimeBundle
|
||||
)(paths.bundleDirectory, {
|
||||
const verificationOptions = {
|
||||
architecture,
|
||||
releaseKeyRegistry,
|
||||
runtimeLock,
|
||||
verificationEnvironment:
|
||||
dependencies.runtimeVerificationEnvironment ?? 'production'
|
||||
})
|
||||
} as const
|
||||
const registered = registry.find(
|
||||
runtimeId,
|
||||
bundleDigest,
|
||||
architecture
|
||||
)
|
||||
const verified =
|
||||
registered === undefined || forceVerification
|
||||
? await (
|
||||
dependencies.verifyRuntime ?? verifyPublishedRuntimeBundle
|
||||
)(paths.bundleDirectory, verificationOptions)
|
||||
: await loadRegisteredRuntimeBundle(
|
||||
registered.bundleDirectory,
|
||||
{
|
||||
...verificationOptions,
|
||||
registered: registered.entry
|
||||
}
|
||||
)
|
||||
assertActivatedRuntimeIdentity(
|
||||
verified,
|
||||
runtimeId,
|
||||
@@ -352,7 +380,8 @@ async function runDaemon(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered'
|
||||
'registered',
|
||||
verified
|
||||
).recordCurrentDaemonReady(daemon.status().daemonBootId)
|
||||
await (dependencies.waitForShutdown?.() ?? waitForShutdownSignal())
|
||||
} finally {
|
||||
@@ -374,7 +403,7 @@ async function runAttach(
|
||||
installationId,
|
||||
dependencies
|
||||
)
|
||||
await loadManagedInstallation(
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
@@ -399,7 +428,8 @@ async function runAttach(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered'
|
||||
'registered',
|
||||
verified
|
||||
).bootstrap()
|
||||
}
|
||||
})
|
||||
@@ -451,10 +481,17 @@ async function runDoctor(
|
||||
options['installation-id']!
|
||||
)
|
||||
const paths = resolveInstallationPaths(installationId, dependencies)
|
||||
const status = await createDetachedLifecycle(
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const status = await createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
).status()
|
||||
io.output.write(`${JSON.stringify({
|
||||
platform: process.platform,
|
||||
@@ -479,48 +516,155 @@ async function runLifecycle(
|
||||
options['installation-id']!
|
||||
)
|
||||
const paths = resolveInstallationPaths(installationId, dependencies)
|
||||
const { verified, registry } = await verifyManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
switch (action) {
|
||||
case 'bootstrap': {
|
||||
registry.stageCandidate(verified)
|
||||
case 'adopt': {
|
||||
const { verified, registry } =
|
||||
await verifyManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const currentInstallationMatches =
|
||||
registry.snapshot().current?.installationId ===
|
||||
installationId
|
||||
const alreadyCurrent = registry.isCurrent(verified)
|
||||
if (!alreadyCurrent && !currentInstallationMatches) {
|
||||
registry.stageCandidate(verified)
|
||||
}
|
||||
prepareManagedSocketDirectory(paths)
|
||||
const status = await lifecycle.bootstrap()
|
||||
const status = await createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'verified',
|
||||
verified
|
||||
).bootstrap()
|
||||
if (!alreadyCurrent) {
|
||||
if (currentInstallationMatches) {
|
||||
registry.refreshCurrent(verified)
|
||||
} else {
|
||||
registry.promoteCandidate(installationId)
|
||||
}
|
||||
}
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
}
|
||||
case 'status': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
io.output.write(`${JSON.stringify(await lifecycle.status())}\n`)
|
||||
break
|
||||
}
|
||||
case 'health': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
const status = await lifecycle.health()
|
||||
if (
|
||||
registry.snapshot().candidate?.installationId ===
|
||||
case 'bootstrap': {
|
||||
const agentRoot = dirname(
|
||||
dirname(dirname(paths.executablePath))
|
||||
)
|
||||
const registry =
|
||||
dependencies.installationRegistry ??
|
||||
new InstallationRegistry({
|
||||
storagePath: resolve(agentRoot, 'registry.json')
|
||||
})
|
||||
const snapshot = registry.snapshot()
|
||||
const current = snapshot.current?.installationId ===
|
||||
installationId
|
||||
) {
|
||||
? snapshot.current
|
||||
: undefined
|
||||
const candidate = snapshot.candidate?.installationId ===
|
||||
installationId
|
||||
? snapshot.candidate
|
||||
: undefined
|
||||
const registered = current ?? candidate
|
||||
const isNewInstallation = registered === undefined
|
||||
const verified = isNewInstallation
|
||||
? (
|
||||
await verifyManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
).verified
|
||||
: await (
|
||||
dependencies.loadRegisteredInstallation ??
|
||||
loadRegisteredAgentBundle
|
||||
)(dirname(paths.executablePath), {
|
||||
installationId,
|
||||
architecture: currentAgentArchitecture(),
|
||||
registered
|
||||
})
|
||||
if (isNewInstallation) {
|
||||
registry.stageCandidate(verified)
|
||||
}
|
||||
prepareManagedSocketDirectory(paths)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'verified',
|
||||
verified
|
||||
)
|
||||
const status = await lifecycle.bootstrap()
|
||||
if (current === undefined) {
|
||||
registry.promoteCandidate(installationId)
|
||||
}
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
}
|
||||
case 'status': {
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
io.output.write(`${JSON.stringify(await lifecycle.status())}\n`)
|
||||
break
|
||||
}
|
||||
case 'health': {
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
const status = await lifecycle.health()
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
}
|
||||
case 'stop': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
io.output.write(`${JSON.stringify(await lifecycle.stop())}\n`)
|
||||
break
|
||||
}
|
||||
case 'retire': {
|
||||
registry.assertVerifiedRole(verified, ['current', 'candidate'])
|
||||
const { verified } = await loadManagedInstallation(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const lifecycle = createDetachedLifecycle(
|
||||
installationId,
|
||||
paths,
|
||||
dependencies,
|
||||
'registered',
|
||||
verified
|
||||
)
|
||||
io.output.write(`${JSON.stringify(await lifecycle.retire())}\n`)
|
||||
break
|
||||
}
|
||||
@@ -531,7 +675,8 @@ function createDetachedLifecycle(
|
||||
installationId: string,
|
||||
paths: ManagedInstallationPaths,
|
||||
dependencies: AgentCliDependencies,
|
||||
identitySource: 'verified' | 'registered' = 'verified'
|
||||
identitySource: 'verified' | 'registered' = 'verified',
|
||||
verifiedInstallation?: VerifiedInstalledAgentBundle
|
||||
): DetachedAgentLifecycle {
|
||||
const options: DetachedAgentLifecycleOptions = {
|
||||
installationId,
|
||||
@@ -539,6 +684,9 @@ function createDetachedLifecycle(
|
||||
stateDirectory: paths.stateDirectory,
|
||||
socketPath: paths.socketPath,
|
||||
verifyInstallation: async () => {
|
||||
if (verifiedInstallation !== undefined) {
|
||||
return verifiedInstallation
|
||||
}
|
||||
if (identitySource === 'registered') {
|
||||
return (
|
||||
await loadManagedInstallation(
|
||||
@@ -614,7 +762,7 @@ async function verifyManagedInstallation(
|
||||
storagePath: resolve(agentRoot, 'registry.json')
|
||||
})
|
||||
const verified = await (
|
||||
dependencies.verifyInstallation ?? verifyInstalledAgentBundle
|
||||
dependencies.verifyInstallation ?? verifyPublishedAgentBundle
|
||||
)(dirname(paths.executablePath), {
|
||||
installationId,
|
||||
architecture,
|
||||
|
||||
@@ -76,6 +76,33 @@ describe('Agent installation registry', () => {
|
||||
).toThrow('authorized registry role')
|
||||
})
|
||||
|
||||
it('replaces same-installation legacy metadata after verification', () => {
|
||||
const root = privateTemporaryDirectory()
|
||||
const storagePath = resolve(root, 'registry.json')
|
||||
writeFileSync(
|
||||
storagePath,
|
||||
`${JSON.stringify({
|
||||
formatVersion: 1,
|
||||
current: {
|
||||
installationId: 'install-a',
|
||||
agentVersion: '0.11.1',
|
||||
manifestSha256: 'a'.repeat(64),
|
||||
arch: 'x64'
|
||||
}
|
||||
}, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
)
|
||||
const registry = new InstallationRegistry({ storagePath })
|
||||
const current = verified('install-a', '0.11.1', 'a')
|
||||
|
||||
expect(registry.isCurrent(current)).toBe(false)
|
||||
registry.refreshCurrent(current)
|
||||
expect(registry.snapshot().current).toMatchObject({
|
||||
installationId: 'install-a',
|
||||
protocol: { major: 1, minor: 0 }
|
||||
})
|
||||
})
|
||||
|
||||
it('replaces a stale candidate with the requested signed identity', () => {
|
||||
const { registry } = createRegistry()
|
||||
registry.stageCandidate(verified('install-a', '0.11.0', 'a'))
|
||||
@@ -116,7 +143,8 @@ describe('Agent installation registry', () => {
|
||||
installationId: 'install-a',
|
||||
agentVersion: '0.11.0',
|
||||
manifestSha256: 'a'.repeat(64),
|
||||
arch: 'x64'
|
||||
arch: 'x64',
|
||||
protocol: { major: 1, minor: 0 }
|
||||
}
|
||||
})
|
||||
expect(readFileSync(storagePath, 'utf8')).toBe(legacyBytes)
|
||||
|
||||
@@ -40,6 +40,14 @@ export class InstallationRegistry {
|
||||
return structuredClone(this.#state)
|
||||
}
|
||||
|
||||
isCurrent(verified: VerifiedInstalledAgentBundle): boolean {
|
||||
const current = this.#state.current
|
||||
return (
|
||||
current !== undefined &&
|
||||
entryEquals(current, entryFromVerified(verified))
|
||||
)
|
||||
}
|
||||
|
||||
stageCandidate(
|
||||
verified: VerifiedInstalledAgentBundle
|
||||
): InstallationRegistryEntry {
|
||||
@@ -100,6 +108,25 @@ export class InstallationRegistry {
|
||||
return this.snapshot()
|
||||
}
|
||||
|
||||
refreshCurrent(
|
||||
verified: VerifiedInstalledAgentBundle
|
||||
): InstallationRegistryState {
|
||||
const entry = entryFromVerified(verified)
|
||||
if (
|
||||
this.#state.current?.installationId !==
|
||||
entry.installationId
|
||||
) {
|
||||
throw new Error(
|
||||
'Verified Agent installation is not the current identity'
|
||||
)
|
||||
}
|
||||
this.#commit({
|
||||
formatVersion: 1,
|
||||
current: entry
|
||||
})
|
||||
return this.snapshot()
|
||||
}
|
||||
|
||||
assertVerifiedRole(
|
||||
verified: VerifiedInstalledAgentBundle,
|
||||
roles: readonly ('current' | 'candidate')[]
|
||||
@@ -221,7 +248,8 @@ function entryFromVerified(
|
||||
installationId: verified.installationId,
|
||||
agentVersion: verified.manifest.agentVersion,
|
||||
manifestSha256: verified.manifestSha256,
|
||||
arch: verified.manifest.arch
|
||||
arch: verified.manifest.arch,
|
||||
protocol: verified.manifest.protocol
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,7 +261,9 @@ function entryEquals(
|
||||
left.installationId === right.installationId &&
|
||||
left.agentVersion === right.agentVersion &&
|
||||
left.manifestSha256 === right.manifestSha256 &&
|
||||
left.arch === right.arch
|
||||
left.arch === right.arch &&
|
||||
JSON.stringify(left.protocol) ===
|
||||
JSON.stringify(right.protocol)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
canonicalInstalledAgentManifestBytes,
|
||||
installedAgentManifestSignaturePayload,
|
||||
loadRegisteredAgentBundle,
|
||||
verifyPublishedAgentBundle,
|
||||
verifyInstalledAgentBundle
|
||||
} from './installed-bundle-verifier'
|
||||
|
||||
@@ -88,7 +89,7 @@ describe('installed Agent bundle verifier', () => {
|
||||
'tampered'
|
||||
)
|
||||
await expect(verifyBundle()).rejects.toThrow(
|
||||
/size mismatch|hash mismatch/u
|
||||
/entrypoint metadata changed|size mismatch|hash mismatch/u
|
||||
)
|
||||
|
||||
resetInstallation()
|
||||
@@ -112,7 +113,9 @@ describe('installed Agent bundle verifier', () => {
|
||||
if (process.platform !== 'win32') {
|
||||
writeBundle()
|
||||
chmodSync(join(installationDirectory, 'goodbuddy-agent'), 0o777)
|
||||
await expect(verifyBundle()).rejects.toThrow('mode mismatch')
|
||||
await expect(verifyBundle()).rejects.toThrow(
|
||||
'entrypoint metadata changed'
|
||||
)
|
||||
resetInstallation()
|
||||
}
|
||||
|
||||
@@ -134,6 +137,26 @@ describe('installed Agent bundle verifier', () => {
|
||||
|
||||
})
|
||||
|
||||
it('adopts signed published metadata without rehashing unrelated payload', async () => {
|
||||
writeBundle()
|
||||
writeFileSync(
|
||||
join(installationDirectory, 'licenses', 'GoodBuddy-0BSD.txt'),
|
||||
'changed after extraction'
|
||||
)
|
||||
await expect(verifyPublishedBundle()).resolves.toMatchObject({
|
||||
installationId: 'install-10',
|
||||
manifest: { agentVersion: '0.11.0' }
|
||||
})
|
||||
|
||||
writeFileSync(
|
||||
join(installationDirectory, 'lib', 'agent.cjs'),
|
||||
'changed entrypoint'
|
||||
)
|
||||
await expect(verifyPublishedBundle()).rejects.toThrow(
|
||||
'entrypoint metadata changed'
|
||||
)
|
||||
})
|
||||
|
||||
it('loads Host-managed registry evidence without repeating signature or payload verification', async () => {
|
||||
writeBundle()
|
||||
const manifestBytes = readFileSync(
|
||||
@@ -269,6 +292,16 @@ function verifyBundle() {
|
||||
})
|
||||
}
|
||||
|
||||
function verifyPublishedBundle() {
|
||||
return verifyPublishedAgentBundle(installationDirectory, {
|
||||
installationId: 'install-10',
|
||||
architecture: 'x64',
|
||||
releaseKeyRegistry,
|
||||
verificationEnvironment: 'test',
|
||||
enforceFilesystemMode: process.platform !== 'win32'
|
||||
})
|
||||
}
|
||||
|
||||
function elf(architecture: 'x64' | 'arm64'): Buffer {
|
||||
const header = Buffer.alloc(64)
|
||||
header.set([0x7f, 0x45, 0x4c, 0x46])
|
||||
|
||||
@@ -110,6 +110,66 @@ export async function readManagedAgentReleaseKeyRegistry(
|
||||
export async function verifyInstalledAgentBundle(
|
||||
installationDirectoryInput: string,
|
||||
options: VerifyInstalledAgentBundleOptions
|
||||
): Promise<VerifiedInstalledAgentBundle> {
|
||||
const verified = await verifyPublishedAgentBundle(
|
||||
installationDirectoryInput,
|
||||
options
|
||||
)
|
||||
const {
|
||||
installationDirectory,
|
||||
manifest
|
||||
} = verified
|
||||
const declaredPaths = new Set(
|
||||
manifest.files.map((file) => file.path)
|
||||
)
|
||||
for (const file of manifest.files) {
|
||||
const filePath = join(
|
||||
installationDirectory,
|
||||
...file.path.split('/')
|
||||
)
|
||||
const stat = await lstat(filePath)
|
||||
assertOwnedRegularFile(stat, file.path, options.uid)
|
||||
if (stat.size !== file.size) {
|
||||
throw new Error(`Agent payload size mismatch: ${file.path}`)
|
||||
}
|
||||
if ((await sha256File(filePath)) !== file.sha256) {
|
||||
throw new Error(`Agent payload hash mismatch: ${file.path}`)
|
||||
}
|
||||
if (
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(stat.mode) !== file.mode
|
||||
) {
|
||||
throw new Error(`Agent payload mode mismatch: ${file.path}`)
|
||||
}
|
||||
}
|
||||
|
||||
const actualPaths = new Set(
|
||||
await listInstallationFiles(installationDirectory, options)
|
||||
)
|
||||
const expectedPaths = new Set([
|
||||
...declaredPaths,
|
||||
MANIFEST_FILE_NAME,
|
||||
SIGNATURE_FILE_NAME
|
||||
])
|
||||
if (
|
||||
actualPaths.size !== expectedPaths.size ||
|
||||
[...actualPaths].some((path) => !expectedPaths.has(path))
|
||||
) {
|
||||
throw new Error(
|
||||
'Agent installation contains undeclared or missing files'
|
||||
)
|
||||
}
|
||||
return verified
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates a package-installer-published Agent from signed metadata and
|
||||
* bounded entrypoint metadata. The installer already hashed every payload
|
||||
* file while extracting it.
|
||||
*/
|
||||
export async function verifyPublishedAgentBundle(
|
||||
installationDirectoryInput: string,
|
||||
options: VerifyInstalledAgentBundleOptions
|
||||
): Promise<VerifiedInstalledAgentBundle> {
|
||||
const installationId = validateInstallationId(options.installationId)
|
||||
const installationDirectory = resolve(installationDirectoryInput)
|
||||
@@ -162,47 +222,11 @@ export async function verifyInstalledAgentBundle(
|
||||
)
|
||||
}
|
||||
|
||||
const declaredPaths = new Set(
|
||||
manifest.files.map((file) => file.path)
|
||||
const executablePath = await assertAgentEntrypoints(
|
||||
installationDirectory,
|
||||
manifest,
|
||||
options
|
||||
)
|
||||
for (const file of manifest.files) {
|
||||
const filePath = join(
|
||||
installationDirectory,
|
||||
...file.path.split('/')
|
||||
)
|
||||
const stat = await lstat(filePath)
|
||||
assertOwnedRegularFile(stat, file.path, options.uid)
|
||||
if (stat.size !== file.size) {
|
||||
throw new Error(`Agent payload size mismatch: ${file.path}`)
|
||||
}
|
||||
if ((await sha256File(filePath)) !== file.sha256) {
|
||||
throw new Error(`Agent payload hash mismatch: ${file.path}`)
|
||||
}
|
||||
if (
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(stat.mode) !== file.mode
|
||||
) {
|
||||
throw new Error(`Agent payload mode mismatch: ${file.path}`)
|
||||
}
|
||||
}
|
||||
|
||||
const actualPaths = new Set(
|
||||
await listInstallationFiles(installationDirectory, options)
|
||||
)
|
||||
const expectedPaths = new Set([
|
||||
...declaredPaths,
|
||||
MANIFEST_FILE_NAME,
|
||||
SIGNATURE_FILE_NAME
|
||||
])
|
||||
if (
|
||||
actualPaths.size !== expectedPaths.size ||
|
||||
[...actualPaths].some((path) => !expectedPaths.has(path))
|
||||
) {
|
||||
throw new Error(
|
||||
'Agent installation contains undeclared or missing files'
|
||||
)
|
||||
}
|
||||
|
||||
await assertElfArchitecture(
|
||||
join(installationDirectory, manifest.entrypoint.runtimePath),
|
||||
manifest.arch,
|
||||
@@ -212,10 +236,7 @@ export async function verifyInstalledAgentBundle(
|
||||
return {
|
||||
installationId,
|
||||
installationDirectory,
|
||||
executablePath: join(
|
||||
installationDirectory,
|
||||
manifest.entrypoint.path
|
||||
),
|
||||
executablePath,
|
||||
manifest,
|
||||
manifestSha256,
|
||||
binaryDigest: `sha256:${manifestSha256}`
|
||||
@@ -310,26 +331,25 @@ async function loadRegisteredAgentBundleUnchecked(
|
||||
manifestBytes
|
||||
) ||
|
||||
manifest.agentVersion !== registered.agentVersion ||
|
||||
manifest.arch !== registered.arch
|
||||
manifest.arch !== registered.arch ||
|
||||
(
|
||||
registered.protocol !== undefined &&
|
||||
(
|
||||
manifest.protocol.major !==
|
||||
registered.protocol.major ||
|
||||
manifest.protocol.minor !==
|
||||
registered.protocol.minor
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'Agent manifest does not match the Host-managed registry'
|
||||
)
|
||||
}
|
||||
|
||||
const executablePath = join(
|
||||
const executablePath = await assertAgentEntrypoints(
|
||||
installationDirectory,
|
||||
manifest.entrypoint.path
|
||||
)
|
||||
await assertRegisteredEntrypoint(executablePath, '0755', options)
|
||||
await assertRegisteredEntrypoint(
|
||||
join(installationDirectory, manifest.entrypoint.runtimePath),
|
||||
'0755',
|
||||
options
|
||||
)
|
||||
await assertRegisteredEntrypoint(
|
||||
join(installationDirectory, manifest.entrypoint.scriptPath),
|
||||
'0644',
|
||||
manifest,
|
||||
options
|
||||
)
|
||||
return {
|
||||
@@ -491,24 +511,45 @@ function importPublicKey(key: AgentReleaseKey) {
|
||||
return publicKey
|
||||
}
|
||||
|
||||
async function assertRegisteredEntrypoint(
|
||||
filePath: string,
|
||||
expectedMode: string,
|
||||
async function assertAgentEntrypoints(
|
||||
installationDirectory: string,
|
||||
manifest: AgentBundleManifest,
|
||||
options: Pick<
|
||||
LoadRegisteredAgentBundleOptions,
|
||||
VerifyInstalledAgentBundleOptions,
|
||||
'uid' | 'filesystemPlatform' | 'enforceFilesystemMode'
|
||||
>
|
||||
): Promise<void> {
|
||||
const stat = await lstat(filePath)
|
||||
assertOwnedRegularFile(stat, filePath, options.uid)
|
||||
if (
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(stat.mode) !== expectedMode
|
||||
) {
|
||||
throw new Error(
|
||||
`Agent payload mode mismatch: ${basename(filePath)}`
|
||||
): Promise<string> {
|
||||
for (const path of [
|
||||
manifest.entrypoint.path,
|
||||
manifest.entrypoint.runtimePath,
|
||||
manifest.entrypoint.scriptPath
|
||||
]) {
|
||||
const record = manifest.files.find((file) => file.path === path)
|
||||
if (record === undefined) {
|
||||
throw new Error(`Agent entrypoint is not declared: ${path}`)
|
||||
}
|
||||
const filePath = join(
|
||||
installationDirectory,
|
||||
...path.split('/')
|
||||
)
|
||||
const stat = await lstat(filePath)
|
||||
assertOwnedRegularFile(stat, filePath, options.uid)
|
||||
if (
|
||||
stat.size !== record.size ||
|
||||
(
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(stat.mode) !== record.mode
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
`Agent entrypoint metadata changed: ${basename(filePath)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
return join(
|
||||
installationDirectory,
|
||||
manifest.entrypoint.path
|
||||
)
|
||||
}
|
||||
|
||||
async function readMetadataFile(
|
||||
|
||||
@@ -268,7 +268,7 @@ function harness(input: {
|
||||
const backend = new RuntimeAcpBackend({
|
||||
journal,
|
||||
resolveRuntimeBundle: vi.fn(async () => resolved),
|
||||
reverifyRuntimeBundle: vi.fn(async () => verifiedBundle()),
|
||||
loadRegisteredRuntimeBundle: vi.fn(async () => verifiedBundle()),
|
||||
resolveWorkspace: vi.fn(async (preparation) => ({
|
||||
workspaceIdentity: preparation.workspaceIdentity,
|
||||
workspaceDirectory: '/workspace',
|
||||
|
||||
@@ -227,7 +227,7 @@ export type RuntimeAcpBackendOptions = {
|
||||
runtimeId: string,
|
||||
runtimeBundleDigest: string
|
||||
): RuntimeAcpResolvedBundle | Promise<RuntimeAcpResolvedBundle>
|
||||
reverifyRuntimeBundle(
|
||||
loadRegisteredRuntimeBundle(
|
||||
resolved: RuntimeAcpResolvedBundle,
|
||||
preparation: RemotePromptOperationPreparation
|
||||
): RuntimeAcpVerifiedBundle | Promise<RuntimeAcpVerifiedBundle>
|
||||
@@ -947,7 +947,7 @@ export class RuntimeAcpBackend {
|
||||
|
||||
let verified: RuntimeAcpVerifiedBundle
|
||||
try {
|
||||
verified = await this.#options.reverifyRuntimeBundle(
|
||||
verified = await this.#options.loadRegisteredRuntimeBundle(
|
||||
binding.resolvedBundle,
|
||||
preparation
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from './managed-paths'
|
||||
import type { InstalledBundleVerificationEnvironment } from './installed-bundle-verifier'
|
||||
import {
|
||||
verifyRuntimeBundle,
|
||||
loadRegisteredRuntimeBundle,
|
||||
type VerifiedRuntimeBundle
|
||||
} from './runtime-bundle-verifier'
|
||||
|
||||
@@ -120,6 +120,27 @@ export class RuntimeBundleRegistry {
|
||||
entry: RuntimeRegistryEntry
|
||||
bundleDirectory: string
|
||||
} {
|
||||
const resolved = this.find(
|
||||
runtimeIdInput,
|
||||
bundleDigestInput,
|
||||
architecture
|
||||
)
|
||||
if (resolved === undefined) {
|
||||
throw new Error(
|
||||
'Runtime bundle is not the verified current bundle'
|
||||
)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
find(
|
||||
runtimeIdInput: string,
|
||||
bundleDigestInput: string,
|
||||
architecture: AgentArchitecture
|
||||
): {
|
||||
entry: RuntimeRegistryEntry
|
||||
bundleDirectory: string
|
||||
} | undefined {
|
||||
const runtimeId = agentIdentifierSchema.parse(runtimeIdInput)
|
||||
const bundleDigest = sha256DigestSchema.parse(bundleDigestInput)
|
||||
this.#state = this.#load({ createIfMissing: false })
|
||||
@@ -130,9 +151,7 @@ export class RuntimeBundleRegistry {
|
||||
candidate.architecture === architecture
|
||||
)
|
||||
if (entry === undefined) {
|
||||
throw new Error(
|
||||
'Runtime bundle is not the verified current bundle'
|
||||
)
|
||||
return undefined
|
||||
}
|
||||
return {
|
||||
entry: { ...entry },
|
||||
@@ -231,7 +250,7 @@ export class RuntimeBundleRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
export function createVerifiedRuntimeCapabilitySource(options: {
|
||||
type VerifiedRuntimeCapabilitySourceOptions = {
|
||||
registry: RuntimeBundleRegistry
|
||||
architecture: AgentArchitecture
|
||||
releaseKeyRegistry: AgentReleaseKeyRegistry
|
||||
@@ -241,64 +260,65 @@ export function createVerifiedRuntimeCapabilitySource(options: {
|
||||
filesystemPlatform?: NodeJS.Platform
|
||||
uid?: number
|
||||
reportError?: (message: string, error: unknown) => void
|
||||
}): () => Promise<DaemonCapabilities['runtimes']> {
|
||||
loadRegistered?: (
|
||||
entry: RuntimeRegistryEntry,
|
||||
bundleDirectory: string
|
||||
) => Promise<VerifiedRuntimeBundle>
|
||||
}
|
||||
|
||||
export function createVerifiedRuntimeCapabilitySource(
|
||||
options: VerifiedRuntimeCapabilitySourceOptions
|
||||
): () => Promise<DaemonCapabilities['runtimes']> {
|
||||
return async () => await loadVerifiedRuntimeCapabilities(options)
|
||||
}
|
||||
|
||||
async function loadVerifiedRuntimeCapabilities(options: {
|
||||
registry: RuntimeBundleRegistry
|
||||
architecture: AgentArchitecture
|
||||
releaseKeyRegistry: AgentReleaseKeyRegistry
|
||||
runtimeLock: RemoteRuntimeLock
|
||||
verificationEnvironment?: InstalledBundleVerificationEnvironment
|
||||
enforceFilesystemMode?: boolean
|
||||
filesystemPlatform?: NodeJS.Platform
|
||||
uid?: number
|
||||
reportError?: (message: string, error: unknown) => void
|
||||
}): Promise<DaemonCapabilities['runtimes']> {
|
||||
async function loadVerifiedRuntimeCapabilities(
|
||||
options: VerifiedRuntimeCapabilitySourceOptions
|
||||
): Promise<DaemonCapabilities['runtimes']> {
|
||||
const capabilities: DaemonCapabilities['runtimes'] = []
|
||||
for (const entry of options.registry.current(options.architecture)) {
|
||||
try {
|
||||
const verified = await verifyRuntimeBundle(
|
||||
const bundleDirectory =
|
||||
options.registry.bundleDirectory(
|
||||
entry.runtimeId,
|
||||
entry.bundleDigest
|
||||
),
|
||||
{
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry: options.releaseKeyRegistry,
|
||||
runtimeLock: options.runtimeLock,
|
||||
...(options.verificationEnvironment === undefined
|
||||
? {}
|
||||
: {
|
||||
verificationEnvironment:
|
||||
options.verificationEnvironment
|
||||
}),
|
||||
...(options.enforceFilesystemMode === undefined
|
||||
? {}
|
||||
: {
|
||||
enforceFilesystemMode:
|
||||
options.enforceFilesystemMode
|
||||
}),
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform: options.filesystemPlatform
|
||||
}),
|
||||
...(options.uid === undefined ? {} : { uid: options.uid })
|
||||
}
|
||||
)
|
||||
if (
|
||||
verified.manifest.runtimeVersion !== entry.runtimeVersion ||
|
||||
verified.manifestDigest !== entry.manifestDigest ||
|
||||
verified.manifest.bundleDigest !== entry.bundleDigest ||
|
||||
verified.manifest.acpCapabilitiesDigest !==
|
||||
entry.acpCapabilitiesDigest
|
||||
) {
|
||||
throw new Error(
|
||||
'Runtime bundle no longer matches its registry identity'
|
||||
)
|
||||
}
|
||||
await (options.loadRegistered === undefined
|
||||
? loadRegisteredRuntimeBundle(
|
||||
bundleDirectory,
|
||||
{
|
||||
registered: entry,
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry:
|
||||
options.releaseKeyRegistry,
|
||||
runtimeLock: options.runtimeLock,
|
||||
...(options.verificationEnvironment === undefined
|
||||
? {}
|
||||
: {
|
||||
verificationEnvironment:
|
||||
options.verificationEnvironment
|
||||
}),
|
||||
...(options.enforceFilesystemMode === undefined
|
||||
? {}
|
||||
: {
|
||||
enforceFilesystemMode:
|
||||
options.enforceFilesystemMode
|
||||
}),
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform:
|
||||
options.filesystemPlatform
|
||||
}),
|
||||
...(options.uid === undefined
|
||||
? {}
|
||||
: { uid: options.uid })
|
||||
}
|
||||
)
|
||||
: options.loadRegistered(
|
||||
entry,
|
||||
bundleDirectory
|
||||
))
|
||||
capabilities.push({
|
||||
runtimeId: entry.runtimeId,
|
||||
version: entry.runtimeVersion,
|
||||
@@ -326,6 +346,7 @@ function entryFromVerified(
|
||||
architecture: verified.manifest.architecture,
|
||||
bundleDigest: verified.manifest.bundleDigest,
|
||||
manifestDigest: verified.manifestDigest,
|
||||
runtimeAdapterDigest: verified.manifest.adapterDigest,
|
||||
acpCapabilitiesDigest:
|
||||
verified.manifest.acpCapabilitiesDigest
|
||||
})
|
||||
|
||||
@@ -8,7 +8,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
type RemoteRuntimeBundleManifest
|
||||
} from '../shared/remote-runtime-launch-contracts'
|
||||
import { verifyRuntimeBundle } from './runtime-bundle-verifier'
|
||||
import {
|
||||
verifyPublishedRuntimeBundle,
|
||||
verifyRuntimeBundle
|
||||
} from './runtime-bundle-verifier'
|
||||
import {
|
||||
RuntimeBundleRegistry,
|
||||
createVerifiedRuntimeCapabilitySource
|
||||
@@ -155,7 +158,7 @@ describe('Remote Runtime bundle verifier', () => {
|
||||
).rejects.toThrow(/managed directory/iu)
|
||||
})
|
||||
|
||||
it('advertises only a bundle that still verifies against its registry', async () => {
|
||||
it('uses registered metadata without rereading Runtime payload files', async () => {
|
||||
const fixture = await createBundle()
|
||||
const runtimeRoot = dirname(dirname(fixture.bundleDirectory))
|
||||
const registry = new RuntimeBundleRegistry({
|
||||
@@ -198,12 +201,63 @@ describe('Remote Runtime bundle verifier', () => {
|
||||
join(fixture.bundleDirectory, 'licenses', 'opencode.txt'),
|
||||
'mutated'
|
||||
)
|
||||
await expect(capabilities()).resolves.toHaveLength(1)
|
||||
expect(reportError).not.toHaveBeenCalled()
|
||||
|
||||
writeFileSync(
|
||||
join(fixture.bundleDirectory, 'bin', 'opencode'),
|
||||
Buffer.concat([
|
||||
readFileSync(
|
||||
join(fixture.bundleDirectory, 'bin', 'opencode')
|
||||
),
|
||||
Buffer.from('changed')
|
||||
])
|
||||
)
|
||||
await expect(capabilities()).resolves.toEqual([])
|
||||
expect(reportError).toHaveBeenCalledWith(
|
||||
'Verified Runtime unavailable: opencode',
|
||||
expect.any(Error)
|
||||
)
|
||||
})
|
||||
|
||||
it('adopts signed published metadata without rehashing unrelated payload', async () => {
|
||||
const fixture = await createBundle()
|
||||
const options = {
|
||||
architecture: 'x64' as const,
|
||||
releaseKeyRegistry: fixture.registry,
|
||||
runtimeLock: lock,
|
||||
verificationEnvironment: 'test' as const,
|
||||
filesystemPlatform: 'win32' as const
|
||||
}
|
||||
writeFileSync(
|
||||
join(fixture.bundleDirectory, 'licenses', 'opencode.txt'),
|
||||
'changed after extraction'
|
||||
)
|
||||
await expect(
|
||||
verifyPublishedRuntimeBundle(
|
||||
fixture.bundleDirectory,
|
||||
options
|
||||
)
|
||||
).resolves.toMatchObject({
|
||||
manifest: { runtimeVersion: '1.18.9' }
|
||||
})
|
||||
|
||||
writeFileSync(
|
||||
join(fixture.bundleDirectory, 'bin', 'opencode'),
|
||||
Buffer.concat([
|
||||
readFileSync(
|
||||
join(fixture.bundleDirectory, 'bin', 'opencode')
|
||||
),
|
||||
Buffer.from('changed')
|
||||
])
|
||||
)
|
||||
await expect(
|
||||
verifyPublishedRuntimeBundle(
|
||||
fixture.bundleDirectory,
|
||||
options
|
||||
)
|
||||
).rejects.toThrow('entrypoint metadata changed')
|
||||
})
|
||||
})
|
||||
|
||||
async function createBundle(
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
export {
|
||||
canonicalRuntimeManifestBytes,
|
||||
loadRegisteredRuntimeBundle,
|
||||
readRemoteRuntimeLock,
|
||||
runtimeManifestSignaturePayload,
|
||||
verifyPublishedRuntimeBundle,
|
||||
verifyRuntimeBundle,
|
||||
verifyRuntimeManifestSignature
|
||||
} from '../shared/node/runtime-bundle-verifier'
|
||||
|
||||
export type {
|
||||
VerifiedRuntimeBundle,
|
||||
LoadRegisteredRuntimeBundleOptions,
|
||||
VerifyRuntimeBundleOptions
|
||||
} from '../shared/node/runtime-bundle-verifier'
|
||||
|
||||
@@ -37,7 +37,7 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('production Runtime composition', () => {
|
||||
it('keeps ACP live and reloads managed metadata installed after daemon startup', async () => {
|
||||
it('loads metadata installed after startup and caches the registered Runtime identity', async () => {
|
||||
const fixture = await createRuntimeBundleTestFixture()
|
||||
const root = fixture.root
|
||||
temporaryPaths.push(root)
|
||||
@@ -121,11 +121,8 @@ describe('production Runtime composition', () => {
|
||||
}, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
)
|
||||
await expect(protocol.runtimes()).resolves.toEqual([])
|
||||
expect(reportError).toHaveBeenCalledWith(
|
||||
'Verified Runtime unavailable: opencode',
|
||||
expect.any(Error)
|
||||
)
|
||||
await expect(protocol.runtimes()).resolves.toHaveLength(1)
|
||||
expect(reportError).not.toHaveBeenCalled()
|
||||
|
||||
await expect(protocol.dispose()).resolves.toBeUndefined()
|
||||
events.close()
|
||||
|
||||
@@ -7,6 +7,9 @@ import type {
|
||||
AgentReleaseKeyRegistry
|
||||
} from '../shared/agent-installation-contracts'
|
||||
import type { AgentFrame } from '../shared/agent-protocol'
|
||||
import type {
|
||||
RuntimeRegistryEntry
|
||||
} from '../shared/remote-environment-registry-contracts'
|
||||
import type { RemoteRuntimeLock } from '../shared/remote-runtime-launch-contracts'
|
||||
import type { EventJournal } from './event-journal'
|
||||
import {
|
||||
@@ -22,7 +25,8 @@ import {
|
||||
} from './runtime-bundle-registry'
|
||||
import {
|
||||
readRemoteRuntimeLock,
|
||||
verifyRuntimeBundle
|
||||
loadRegisteredRuntimeBundle,
|
||||
type VerifiedRuntimeBundle
|
||||
} from './runtime-bundle-verifier'
|
||||
import { RuntimeAcpBackend } from './runtime-acp-backend'
|
||||
import type { ProtocolMethodContext } from './protocol-server'
|
||||
@@ -111,37 +115,90 @@ export async function createProductionRuntimeProtocol(
|
||||
}
|
||||
return registry
|
||||
}
|
||||
const currentVerificationOptions = async () => {
|
||||
const metadataOptions =
|
||||
options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: { filesystemPlatform: options.filesystemPlatform }
|
||||
const [releaseKeyRegistry, runtimeLock] = await Promise.all([
|
||||
options.releaseKeyRegistry ??
|
||||
readManagedAgentReleaseKeyRegistry(
|
||||
join(runtimeRoot, 'release-keys.json'),
|
||||
metadataOptions
|
||||
),
|
||||
options.runtimeLock ??
|
||||
readRemoteRuntimeLock(
|
||||
join(runtimeRoot, 'remote-runtime-lock.json'),
|
||||
metadataOptions
|
||||
)
|
||||
])
|
||||
return {
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry,
|
||||
runtimeLock,
|
||||
verificationEnvironment,
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: { filesystemPlatform: options.filesystemPlatform })
|
||||
} as const
|
||||
let verificationOptionsPromise:
|
||||
| Promise<{
|
||||
architecture: AgentArchitecture
|
||||
releaseKeyRegistry: AgentReleaseKeyRegistry
|
||||
runtimeLock: RemoteRuntimeLock
|
||||
verificationEnvironment: 'production' | 'test'
|
||||
filesystemPlatform?: NodeJS.Platform
|
||||
}>
|
||||
| undefined
|
||||
const currentVerificationOptions = () => {
|
||||
verificationOptionsPromise ??= (async () => {
|
||||
const metadataOptions =
|
||||
options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform:
|
||||
options.filesystemPlatform
|
||||
}
|
||||
const [releaseKeyRegistry, runtimeLock] =
|
||||
await Promise.all([
|
||||
options.releaseKeyRegistry ??
|
||||
readManagedAgentReleaseKeyRegistry(
|
||||
join(runtimeRoot, 'release-keys.json'),
|
||||
metadataOptions
|
||||
),
|
||||
options.runtimeLock ??
|
||||
readRemoteRuntimeLock(
|
||||
join(
|
||||
runtimeRoot,
|
||||
'remote-runtime-lock.json'
|
||||
),
|
||||
metadataOptions
|
||||
)
|
||||
])
|
||||
return {
|
||||
architecture: options.architecture,
|
||||
releaseKeyRegistry,
|
||||
runtimeLock,
|
||||
verificationEnvironment,
|
||||
...(options.filesystemPlatform === undefined
|
||||
? {}
|
||||
: {
|
||||
filesystemPlatform:
|
||||
options.filesystemPlatform
|
||||
})
|
||||
}
|
||||
})()
|
||||
void verificationOptionsPromise.catch(() => {
|
||||
verificationOptionsPromise = undefined
|
||||
})
|
||||
return verificationOptionsPromise
|
||||
}
|
||||
const verifiedRuntimeCache =
|
||||
new Map<string, Promise<VerifiedRuntimeBundle>>()
|
||||
const loadRegistered = (
|
||||
entry: RuntimeRegistryEntry,
|
||||
bundleDirectory: string
|
||||
): Promise<VerifiedRuntimeBundle> => {
|
||||
const key = `${bundleDirectory}\0${JSON.stringify(entry)}`
|
||||
const cached = verifiedRuntimeCache.get(key)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
const loading = (async () =>
|
||||
await loadRegisteredRuntimeBundle(
|
||||
bundleDirectory,
|
||||
{
|
||||
...(await currentVerificationOptions()),
|
||||
registered: entry
|
||||
}
|
||||
))()
|
||||
verifiedRuntimeCache.set(key, loading)
|
||||
void loading.catch(() => {
|
||||
if (verifiedRuntimeCache.get(key) === loading) {
|
||||
verifiedRuntimeCache.delete(key)
|
||||
}
|
||||
})
|
||||
return loading
|
||||
}
|
||||
const verifiedCapabilities = async () => {
|
||||
const source = createVerifiedRuntimeCapabilitySource({
|
||||
registry: currentRegistry(),
|
||||
...(await currentVerificationOptions()),
|
||||
loadRegistered,
|
||||
reportError: options.reportError
|
||||
})
|
||||
return await source()
|
||||
@@ -182,21 +239,11 @@ export async function createProductionRuntimeProtocol(
|
||||
bundleDigest,
|
||||
options.architecture
|
||||
),
|
||||
reverifyRuntimeBundle: async (resolved) => {
|
||||
const verified = await verifyRuntimeBundle(
|
||||
resolved.bundleDirectory,
|
||||
await currentVerificationOptions()
|
||||
loadRegisteredRuntimeBundle: async (resolved) => {
|
||||
return await loadRegistered(
|
||||
resolved.entry,
|
||||
resolved.bundleDirectory
|
||||
)
|
||||
if (
|
||||
verified.manifestDigest !== resolved.entry.manifestDigest ||
|
||||
verified.manifest.bundleDigest !==
|
||||
resolved.entry.bundleDigest
|
||||
) {
|
||||
throw new Error(
|
||||
'Runtime bundle no longer matches its registered identity'
|
||||
)
|
||||
}
|
||||
return verified
|
||||
},
|
||||
resolveWorkspace: async (preparation, context) =>
|
||||
resolveCurrentWorkspace(
|
||||
|
||||
@@ -1260,11 +1260,6 @@ if (hasSingleInstanceLock) {
|
||||
resolver: startupRemoteAgentServices.targetResolver,
|
||||
sshPool: startupRemoteAgentServices.sshPool,
|
||||
agentPackageManager,
|
||||
agentInstallationManager:
|
||||
startupRemoteAgentServices.installationManager,
|
||||
runtimeInstallationManager:
|
||||
startupManagedRemoteExecutionServices
|
||||
.runtimeInstallationManager,
|
||||
operationStore:
|
||||
new RemoteEnvironmentOperationStore(
|
||||
app.getPath('userData')
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,21 @@
|
||||
export function boundedDiagnostic(
|
||||
value: string,
|
||||
maximumCharacters = 800
|
||||
): string {
|
||||
let printable = ''
|
||||
for (const character of value) {
|
||||
const code = character.charCodeAt(0)
|
||||
if (
|
||||
code === 9 ||
|
||||
code === 10 ||
|
||||
code === 13 ||
|
||||
(code >= 32 && code !== 127)
|
||||
) {
|
||||
printable += character
|
||||
}
|
||||
}
|
||||
return printable
|
||||
.replace(/\s+/gu, ' ')
|
||||
.trim()
|
||||
.slice(0, maximumCharacters)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,255 @@
|
||||
import { settleBoundedly } from './bounded-settlement'
|
||||
|
||||
const DISPOSE_WAIT_TIMEOUT_MS = 5_000
|
||||
|
||||
type ActiveActivation<TValue, TPhase extends string> = {
|
||||
promise: Promise<TValue>
|
||||
controller: AbortController
|
||||
progressCallbacks: Set<(phase: TPhase) => void>
|
||||
waiters: number
|
||||
settled: boolean
|
||||
}
|
||||
|
||||
export class HostActivationCoordinator<
|
||||
TValue,
|
||||
TPhase extends string
|
||||
> {
|
||||
readonly #maximumConcurrentHosts: number
|
||||
readonly #capacityError: () => Error
|
||||
readonly #disposeMessage: string
|
||||
readonly #active =
|
||||
new Map<string, ActiveActivation<TValue, TPhase>>()
|
||||
readonly #current = new Map<
|
||||
string,
|
||||
{
|
||||
targetKey: string
|
||||
variantKey: string
|
||||
value: TValue
|
||||
}
|
||||
>()
|
||||
readonly #cacheGenerations = new Map<string, number>()
|
||||
#closed = false
|
||||
#disposePromise: Promise<void> | undefined
|
||||
|
||||
constructor(options: {
|
||||
maximumConcurrentHosts?: number
|
||||
capacityError: () => Error
|
||||
disposeMessage: string
|
||||
}) {
|
||||
this.#maximumConcurrentHosts =
|
||||
options.maximumConcurrentHosts ?? 8
|
||||
this.#capacityError = options.capacityError
|
||||
this.#disposeMessage = options.disposeMessage
|
||||
if (
|
||||
!Number.isSafeInteger(this.#maximumConcurrentHosts) ||
|
||||
this.#maximumConcurrentHosts <= 0 ||
|
||||
this.#maximumConcurrentHosts > 32
|
||||
) {
|
||||
throw new Error(
|
||||
'Host activation concurrency limit is invalid'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
assertAvailable(): void {
|
||||
if (this.#closed) {
|
||||
throw new Error(this.#disposeMessage)
|
||||
}
|
||||
}
|
||||
|
||||
cached(
|
||||
hostId: string,
|
||||
targetKey: string,
|
||||
variantKey: string
|
||||
): TValue | undefined {
|
||||
this.assertAvailable()
|
||||
const cached = this.#current.get(hostId)
|
||||
return (
|
||||
cached?.targetKey === targetKey &&
|
||||
cached.variantKey === variantKey
|
||||
)
|
||||
? cached.value
|
||||
: undefined
|
||||
}
|
||||
|
||||
cachedForHost(
|
||||
hostId: string,
|
||||
variantKey: string
|
||||
): TValue | undefined {
|
||||
this.assertAvailable()
|
||||
const cached = this.#current.get(hostId)
|
||||
return cached?.variantKey === variantKey
|
||||
? cached.value
|
||||
: undefined
|
||||
}
|
||||
|
||||
run(options: {
|
||||
hostId: string
|
||||
targetKey: string
|
||||
variantKey: string
|
||||
signal?: AbortSignal
|
||||
onProgress?: (phase: TPhase) => void
|
||||
operation: (
|
||||
signal: AbortSignal,
|
||||
progress: (phase: TPhase) => void
|
||||
) => Promise<TValue>
|
||||
}): Promise<TValue> {
|
||||
this.assertAvailable()
|
||||
options.signal?.throwIfAborted()
|
||||
const operationKey =
|
||||
`${options.targetKey}\0${options.variantKey}`
|
||||
const existing = this.#active.get(operationKey)
|
||||
if (existing) {
|
||||
return this.#waitForActive(existing, options)
|
||||
}
|
||||
if (this.#active.size >= this.#maximumConcurrentHosts) {
|
||||
throw this.#capacityError()
|
||||
}
|
||||
|
||||
const cacheGeneration =
|
||||
this.#cacheGenerations.get(options.hostId) ?? 0
|
||||
const progressCallbacks = new Set<
|
||||
(phase: TPhase) => void
|
||||
>()
|
||||
if (options.onProgress) {
|
||||
progressCallbacks.add(options.onProgress)
|
||||
}
|
||||
const progress = (phase: TPhase): void => {
|
||||
for (const callback of progressCallbacks) {
|
||||
emitProgress(callback, phase)
|
||||
}
|
||||
}
|
||||
const controller = new AbortController()
|
||||
const promise = options.operation(
|
||||
controller.signal,
|
||||
progress
|
||||
).then((value) => {
|
||||
if (
|
||||
(this.#cacheGenerations.get(options.hostId) ?? 0) ===
|
||||
cacheGeneration
|
||||
) {
|
||||
this.#current.set(options.hostId, {
|
||||
targetKey: options.targetKey,
|
||||
variantKey: options.variantKey,
|
||||
value
|
||||
})
|
||||
}
|
||||
return value
|
||||
})
|
||||
const active: ActiveActivation<TValue, TPhase> = {
|
||||
promise,
|
||||
controller,
|
||||
progressCallbacks,
|
||||
waiters: 0,
|
||||
settled: false
|
||||
}
|
||||
this.#active.set(operationKey, active)
|
||||
void promise.finally(() => {
|
||||
active.settled = true
|
||||
if (this.#active.get(operationKey) === active) {
|
||||
this.#active.delete(operationKey)
|
||||
}
|
||||
}).catch(() => undefined)
|
||||
return this.#waitForActive(active, options)
|
||||
}
|
||||
|
||||
invalidate(hostId: string): void {
|
||||
this.#current.delete(hostId)
|
||||
this.#cacheGenerations.set(
|
||||
hostId,
|
||||
(this.#cacheGenerations.get(hostId) ?? 0) + 1
|
||||
)
|
||||
}
|
||||
|
||||
dispose(): Promise<void> {
|
||||
if (this.#disposePromise) {
|
||||
return this.#disposePromise
|
||||
}
|
||||
this.#closed = true
|
||||
this.#current.clear()
|
||||
this.#cacheGenerations.clear()
|
||||
const operations = [...this.#active.values()]
|
||||
const reason = new DOMException(
|
||||
this.#disposeMessage,
|
||||
'AbortError'
|
||||
)
|
||||
for (const operation of operations) {
|
||||
operation.controller.abort(reason)
|
||||
}
|
||||
this.#disposePromise = settleBoundedly(
|
||||
operations.map((operation) => operation.promise),
|
||||
DISPOSE_WAIT_TIMEOUT_MS
|
||||
)
|
||||
return this.#disposePromise
|
||||
}
|
||||
|
||||
async #waitForActive(
|
||||
active: ActiveActivation<TValue, TPhase>,
|
||||
options: {
|
||||
signal?: AbortSignal
|
||||
onProgress?: (phase: TPhase) => void
|
||||
}
|
||||
): Promise<TValue> {
|
||||
active.waiters += 1
|
||||
if (options.onProgress) {
|
||||
active.progressCallbacks.add(options.onProgress)
|
||||
}
|
||||
try {
|
||||
return await waitForOperation(
|
||||
active.promise,
|
||||
options.signal
|
||||
)
|
||||
} finally {
|
||||
if (options.onProgress) {
|
||||
active.progressCallbacks.delete(options.onProgress)
|
||||
}
|
||||
active.waiters -= 1
|
||||
if (
|
||||
active.waiters === 0 &&
|
||||
!active.settled &&
|
||||
!active.controller.signal.aborted
|
||||
) {
|
||||
active.controller.abort(
|
||||
new DOMException(
|
||||
'Host activation has no remaining waiters',
|
||||
'AbortError'
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitProgress<TPhase extends string>(
|
||||
callback: (phase: TPhase) => void,
|
||||
phase: TPhase
|
||||
): void {
|
||||
try {
|
||||
callback(phase)
|
||||
} catch {
|
||||
// Progress observers cannot alter activation state.
|
||||
}
|
||||
}
|
||||
|
||||
function waitForOperation<T>(
|
||||
operation: Promise<T>,
|
||||
signal?: AbortSignal
|
||||
): Promise<T> {
|
||||
if (!signal) {
|
||||
return operation
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const abort = (): void => reject(
|
||||
signal.reason ??
|
||||
new DOMException(
|
||||
'The operation was aborted',
|
||||
'AbortError'
|
||||
)
|
||||
)
|
||||
signal.addEventListener('abort', abort, { once: true })
|
||||
void operation.then(resolve, reject).finally(() => {
|
||||
signal.removeEventListener('abort', abort)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -21,13 +21,11 @@ import {
|
||||
RemoteRuntimeInstallationManager,
|
||||
type RemoteRuntimeActivator
|
||||
} from './remote-runtime-installation-manager'
|
||||
import {
|
||||
loadRemoteRuntimeVerificationMetadata
|
||||
} from './remote-runtime-resource-loader'
|
||||
import {
|
||||
createManagedModelBridge,
|
||||
reconcileStartupModelCalls
|
||||
} from './managed-model-bridge'
|
||||
import { boundedDiagnostic } from './bounded-diagnostic'
|
||||
|
||||
const RUNTIME_BINDING_DATABASE_NAME = 'remote-runtime-bindings.sqlite'
|
||||
const MODEL_CALL_DATABASE_NAME = 'remote-model-calls-v2.sqlite'
|
||||
@@ -101,19 +99,9 @@ export class ManagedRemoteExecutionServices {
|
||||
)
|
||||
).installationId
|
||||
signal.throwIfAborted()
|
||||
const current = await options.agentServices.targetResolver.resolve(
|
||||
lease.identity.hostId
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
if (
|
||||
runtimeId !== 'opencode' ||
|
||||
current.host.id !== lease.identity.hostId ||
|
||||
current.hostRevision !== lease.identity.hostRevision ||
|
||||
current.hostKeyGeneration !==
|
||||
lease.identity.hostKeyGeneration
|
||||
) {
|
||||
if (runtimeId !== 'opencode') {
|
||||
throw new Error(
|
||||
'Remote Agent or SSH host identity changed before Runtime activation'
|
||||
'Remote Runtime identity is unsupported'
|
||||
)
|
||||
}
|
||||
const result = await lease.runAgentRuntimeAction(
|
||||
@@ -127,17 +115,20 @@ export class ManagedRemoteExecutionServices {
|
||||
signal
|
||||
)
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error('Remote Runtime activation failed')
|
||||
const detail = boundedDiagnostic(
|
||||
`${result.stderr}\n${result.stdout}`
|
||||
)
|
||||
throw new Error(
|
||||
detail.length > 0
|
||||
? `Remote Runtime activation failed: ${detail}`
|
||||
: `Remote Runtime activation failed (exit ${String(result.exitCode)})`
|
||||
)
|
||||
}
|
||||
}
|
||||
this.runtimeInstallationManager =
|
||||
new RemoteRuntimeInstallationManager({
|
||||
resolver: options.agentServices.targetResolver,
|
||||
sshPool: options.agentServices.sshPool,
|
||||
loadVerificationMetadata: () =>
|
||||
loadRemoteRuntimeVerificationMetadata(
|
||||
this.runtimeResourcePaths
|
||||
),
|
||||
activate
|
||||
})
|
||||
this.runtimeValidator = new ManagedRemoteProjectRuntimeValidator({
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
SftpEntryMetadata,
|
||||
StagedSftp
|
||||
} from '../ssh/bounded-sftp'
|
||||
import {
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS,
|
||||
restoreRemoteEnvironmentMetadata,
|
||||
snapshotRemoteEnvironmentMetadata,
|
||||
type RemoteEnvironmentMetadataSnapshot
|
||||
} from './remote-environment-metadata'
|
||||
|
||||
const UID = 1000
|
||||
|
||||
function missingPath(): Error & { code: string } {
|
||||
return Object.assign(new Error('missing'), { code: 'ENOENT' })
|
||||
}
|
||||
|
||||
function fileMetadata(
|
||||
contents: Buffer,
|
||||
overrides: Partial<SftpEntryMetadata> = {}
|
||||
): SftpEntryMetadata {
|
||||
return {
|
||||
type: 'file',
|
||||
size: contents.byteLength,
|
||||
mode: 0o600,
|
||||
uid: UID,
|
||||
gid: UID,
|
||||
atime: 0,
|
||||
mtime: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function createSftp(
|
||||
initial: ReadonlyMap<string, Buffer>,
|
||||
metadataOverrides: ReadonlyMap<string, Partial<SftpEntryMetadata>> =
|
||||
new Map()
|
||||
) {
|
||||
const files = new Map(
|
||||
[...initial].map(([path, contents]) => [path, Buffer.from(contents)])
|
||||
)
|
||||
const temporary = new Map<string, Buffer>()
|
||||
const sftp: StagedSftp = {
|
||||
stagingDirectory: '/home/goodbuddy',
|
||||
mkdir: vi.fn(),
|
||||
uploadFile: vi.fn(),
|
||||
writeFile: vi.fn(async (path, contents) => {
|
||||
temporary.set(path, Buffer.from(contents))
|
||||
}),
|
||||
readFile: vi.fn(async (path) => {
|
||||
const contents = files.get(path) ?? temporary.get(path)
|
||||
if (!contents) throw missingPath()
|
||||
return Buffer.from(contents)
|
||||
}),
|
||||
lstat: vi.fn(async (path) => {
|
||||
const contents = files.get(path) ?? temporary.get(path)
|
||||
if (!contents) throw missingPath()
|
||||
return fileMetadata(
|
||||
contents,
|
||||
metadataOverrides.get(path)
|
||||
)
|
||||
}),
|
||||
stat: vi.fn(),
|
||||
chmod: vi.fn(),
|
||||
setExecutable: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
replaceFile: vi.fn(async (source, destination) => {
|
||||
const contents = temporary.get(source)
|
||||
if (!contents) throw missingPath()
|
||||
files.set(destination, Buffer.from(contents))
|
||||
temporary.delete(source)
|
||||
}),
|
||||
unlink: vi.fn(async (path) => {
|
||||
if (!files.delete(path) && !temporary.delete(path)) {
|
||||
throw missingPath()
|
||||
}
|
||||
}),
|
||||
rmdir: vi.fn(),
|
||||
close: vi.fn()
|
||||
}
|
||||
return { sftp, files, temporary }
|
||||
}
|
||||
|
||||
describe('remote environment metadata', () => {
|
||||
it('snapshots original bytes and restores them exactly', async () => {
|
||||
const originals = new Map(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map((path, index) => [
|
||||
path,
|
||||
Buffer.from([0, index, 255, 10])
|
||||
])
|
||||
)
|
||||
const value = createSftp(originals)
|
||||
const snapshots = await snapshotRemoteEnvironmentMetadata(
|
||||
value.sftp,
|
||||
UID,
|
||||
new AbortController().signal
|
||||
)
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
value.files.set(path, Buffer.from('changed'))
|
||||
}
|
||||
|
||||
await restoreRemoteEnvironmentMetadata(value.sftp, snapshots)
|
||||
|
||||
expect(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map((path) =>
|
||||
value.files.get(path)
|
||||
)
|
||||
).toEqual(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map((path) =>
|
||||
originals.get(path)
|
||||
)
|
||||
)
|
||||
expect(value.sftp.chmod).toHaveBeenCalledTimes(5)
|
||||
expect(value.sftp.replaceFile).toHaveBeenCalledTimes(5)
|
||||
})
|
||||
|
||||
it('records missing metadata and removes files created after the snapshot', async () => {
|
||||
const value = createSftp(new Map())
|
||||
const snapshots = await snapshotRemoteEnvironmentMetadata(
|
||||
value.sftp,
|
||||
UID,
|
||||
new AbortController().signal
|
||||
)
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
value.files.set(path, Buffer.from('new'))
|
||||
}
|
||||
|
||||
await restoreRemoteEnvironmentMetadata(value.sftp, snapshots)
|
||||
|
||||
expect(value.files.size).toBe(0)
|
||||
expect(value.sftp.unlink).toHaveBeenCalledTimes(5)
|
||||
})
|
||||
|
||||
it('distinguishes an empty original file from a missing file', async () => {
|
||||
const path = REMOTE_ENVIRONMENT_METADATA_PATHS[0]
|
||||
const value = createSftp(
|
||||
new Map([[path, Buffer.alloc(0)]])
|
||||
)
|
||||
const snapshots = await snapshotRemoteEnvironmentMetadata(
|
||||
value.sftp,
|
||||
UID,
|
||||
new AbortController().signal
|
||||
)
|
||||
value.files.set(path, Buffer.from('changed'))
|
||||
|
||||
await restoreRemoteEnvironmentMetadata(value.sftp, snapshots)
|
||||
|
||||
expect(value.files.get(path)).toEqual(Buffer.alloc(0))
|
||||
})
|
||||
|
||||
it.each([
|
||||
['permissions', { mode: 0o644 }],
|
||||
['owner', { uid: UID + 1 }],
|
||||
['symbolic link', { type: 'symbolic-link' as const }]
|
||||
])('rejects metadata with invalid %s', async (_label, override) => {
|
||||
const path = REMOTE_ENVIRONMENT_METADATA_PATHS[0]
|
||||
const contents = Buffer.from('metadata')
|
||||
const value = createSftp(
|
||||
new Map([[path, contents]]),
|
||||
new Map([[path, override]])
|
||||
)
|
||||
|
||||
await expect(snapshotRemoteEnvironmentMetadata(
|
||||
value.sftp,
|
||||
UID,
|
||||
new AbortController().signal
|
||||
)).rejects.toThrow('类型、所有者或权限无效')
|
||||
expect(value.sftp.readFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('continues restoring remaining files and aggregates every error', async () => {
|
||||
const first = REMOTE_ENVIRONMENT_METADATA_PATHS[0]
|
||||
const second = REMOTE_ENVIRONMENT_METADATA_PATHS[1]
|
||||
const third = REMOTE_ENVIRONMENT_METADATA_PATHS[2]
|
||||
const value = createSftp(new Map([
|
||||
[first, Buffer.from('changed-1')],
|
||||
[second, Buffer.from('changed-2')],
|
||||
[third, Buffer.from('created')]
|
||||
]))
|
||||
const firstError = new Error('first replace failed')
|
||||
const secondError = new Error('second replace failed')
|
||||
vi.mocked(value.sftp.replaceFile).mockImplementation(
|
||||
async (_source, destination) => {
|
||||
throw destination === first ? firstError : secondError
|
||||
}
|
||||
)
|
||||
const snapshots: readonly RemoteEnvironmentMetadataSnapshot[] = [
|
||||
{ path: first, contents: Buffer.from('original-1'), uid: UID },
|
||||
{ path: second, contents: Buffer.from('original-2'), uid: UID },
|
||||
{ path: third, uid: UID }
|
||||
]
|
||||
|
||||
const caught = await restoreRemoteEnvironmentMetadata(
|
||||
value.sftp,
|
||||
snapshots
|
||||
).catch((error: unknown) => error)
|
||||
|
||||
expect(caught).toBeInstanceOf(AggregateError)
|
||||
expect((caught as AggregateError).errors).toEqual([
|
||||
firstError,
|
||||
secondError
|
||||
])
|
||||
expect(value.sftp.replaceFile).toHaveBeenCalledTimes(2)
|
||||
expect(value.files.has(third)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,142 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { StagedSftp } from '../ssh/bounded-sftp'
|
||||
import { isMissingPathError } from './path-errors'
|
||||
|
||||
const PRIVATE_FILE_MODE = 0o600
|
||||
|
||||
export const REMOTE_ENVIRONMENT_METADATA_PATHS = [
|
||||
'.goodbuddy/agent/release-keys.json',
|
||||
'.goodbuddy/agent/registry.json',
|
||||
'.goodbuddy/runtimes/release-keys.json',
|
||||
'.goodbuddy/runtimes/remote-runtime-lock.json',
|
||||
'.goodbuddy/runtimes/registry.json'
|
||||
] as const
|
||||
|
||||
export type RemoteEnvironmentMetadataSnapshot = {
|
||||
path: (typeof REMOTE_ENVIRONMENT_METADATA_PATHS)[number]
|
||||
contents?: Buffer
|
||||
uid: number
|
||||
}
|
||||
|
||||
export async function snapshotRemoteEnvironmentMetadata(
|
||||
sftp: StagedSftp,
|
||||
uid: number,
|
||||
signal: AbortSignal
|
||||
): Promise<readonly RemoteEnvironmentMetadataSnapshot[]> {
|
||||
const snapshots: RemoteEnvironmentMetadataSnapshot[] = []
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
signal.throwIfAborted()
|
||||
const metadata = await metadataIfPresent(sftp, path, signal)
|
||||
if (!metadata) {
|
||||
snapshots.push({ path, uid })
|
||||
continue
|
||||
}
|
||||
assertPrivateFile(metadata, path, uid)
|
||||
snapshots.push({
|
||||
path,
|
||||
contents: await sftp.readFile(path, signal),
|
||||
uid
|
||||
})
|
||||
}
|
||||
return snapshots
|
||||
}
|
||||
|
||||
export async function restoreRemoteEnvironmentMetadata(
|
||||
sftp: StagedSftp,
|
||||
snapshots: readonly RemoteEnvironmentMetadataSnapshot[]
|
||||
): Promise<void> {
|
||||
const errors: unknown[] = []
|
||||
for (const snapshot of snapshots) {
|
||||
try {
|
||||
await restoreRemoteEnvironmentMetadataFile(sftp, snapshot)
|
||||
} catch (error) {
|
||||
errors.push(error)
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(
|
||||
errors,
|
||||
'远程运行环境元数据回滚不完整'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreRemoteEnvironmentMetadataFile(
|
||||
sftp: StagedSftp,
|
||||
snapshot: RemoteEnvironmentMetadataSnapshot
|
||||
): Promise<void> {
|
||||
const existing = await metadataIfPresent(sftp, snapshot.path)
|
||||
if (snapshot.contents === undefined) {
|
||||
if (existing) {
|
||||
assertPrivateFile(existing, snapshot.path, snapshot.uid)
|
||||
await sftp.unlink(snapshot.path)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
assertPrivateFile(existing, snapshot.path, snapshot.uid)
|
||||
if (
|
||||
existing.size === snapshot.contents.byteLength &&
|
||||
(await sftp.readFile(snapshot.path)).equals(snapshot.contents)
|
||||
) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const temporary =
|
||||
`.goodbuddy/.environment-metadata-rollback-${randomUUID()}.tmp`
|
||||
try {
|
||||
await sftp.writeFile(temporary, snapshot.contents)
|
||||
await sftp.chmod(temporary, PRIVATE_FILE_MODE)
|
||||
await sftp.replaceFile(temporary, snapshot.path)
|
||||
const restored = await sftp.lstat(snapshot.path)
|
||||
assertPrivateFile(restored, snapshot.path, snapshot.uid)
|
||||
if (
|
||||
restored.size !== snapshot.contents.byteLength ||
|
||||
!(await sftp.readFile(snapshot.path)).equals(snapshot.contents)
|
||||
) {
|
||||
throw new Error(
|
||||
`远程运行环境元数据 ${snapshot.path} 回滚校验失败`
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
await sftp.unlink(temporary).catch((cleanupError: unknown) => {
|
||||
if (!isMissingPathError(cleanupError)) {
|
||||
throw cleanupError
|
||||
}
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function metadataIfPresent(
|
||||
sftp: StagedSftp,
|
||||
path: string,
|
||||
signal?: AbortSignal
|
||||
) {
|
||||
try {
|
||||
return await sftp.lstat(path, signal)
|
||||
} catch (error) {
|
||||
if (isMissingPathError(error)) {
|
||||
return undefined
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function assertPrivateFile(
|
||||
metadata: Awaited<ReturnType<StagedSftp['lstat']>>,
|
||||
path: string,
|
||||
uid: number
|
||||
): void {
|
||||
if (
|
||||
metadata.type !== 'file' ||
|
||||
metadata.uid !== uid ||
|
||||
metadata.mode !== PRIVATE_FILE_MODE
|
||||
) {
|
||||
throw new Error(
|
||||
`远程运行环境元数据 ${path} 的类型、所有者或权限无效`
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,7 @@ const operation: PendingRemoteEnvironmentOperation = {
|
||||
version: 1,
|
||||
hostId: 'host-1',
|
||||
targetIdentity: 'a'.repeat(64),
|
||||
operationId: '00000000-0000-4000-8000-000000000777',
|
||||
size: 123,
|
||||
sha256: 'b'.repeat(64),
|
||||
urls: []
|
||||
operationId: '00000000-0000-4000-8000-000000000777'
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -58,7 +55,7 @@ describe('RemoteEnvironmentOperationStore', () => {
|
||||
const [record] = await readdir(files)
|
||||
await writeFile(
|
||||
join(files, record!),
|
||||
Buffer.alloc(64 * 1024 + 1)
|
||||
Buffer.alloc(4 * 1024 + 1)
|
||||
)
|
||||
|
||||
await expect(store.load(operation.hostId)).rejects.toThrow(
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
writeJsonFileAtomically
|
||||
} from '../settings-file-utils'
|
||||
|
||||
const MAXIMUM_RECORD_BYTES = 64 * 1024
|
||||
const MAXIMUM_RECORD_BYTES = 4 * 1024
|
||||
const OPERATION_ID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
|
||||
const SHA256_PATTERN = /^[a-f0-9]{64}$/u
|
||||
@@ -16,9 +16,6 @@ export type PendingRemoteEnvironmentOperation = {
|
||||
hostId: string
|
||||
targetIdentity: string
|
||||
operationId: string
|
||||
size: number
|
||||
sha256: string
|
||||
urls: readonly string[]
|
||||
}
|
||||
|
||||
export class RemoteEnvironmentOperationStore {
|
||||
@@ -91,41 +88,29 @@ function parsePendingOperation(
|
||||
value: unknown,
|
||||
expectedHostId: string
|
||||
): PendingRemoteEnvironmentOperation {
|
||||
if (
|
||||
typeof value !== 'object' ||
|
||||
value === null ||
|
||||
Object.keys(value).sort().join('\0') !==
|
||||
[
|
||||
'hostId',
|
||||
'operationId',
|
||||
'sha256',
|
||||
'size',
|
||||
'targetIdentity',
|
||||
'urls',
|
||||
'version'
|
||||
].sort().join('\0')
|
||||
) {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const record = value as Record<string, unknown>
|
||||
const expectedKeys = [
|
||||
'hostId',
|
||||
'operationId',
|
||||
'targetIdentity',
|
||||
'version'
|
||||
]
|
||||
if (
|
||||
Object.keys(value).sort().join('\0') !==
|
||||
expectedKeys.sort().join('\0')
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
if (
|
||||
record.version !== 1 ||
|
||||
record.hostId !== expectedHostId ||
|
||||
typeof record.targetIdentity !== 'string' ||
|
||||
!SHA256_PATTERN.test(record.targetIdentity) ||
|
||||
typeof record.operationId !== 'string' ||
|
||||
!OPERATION_ID_PATTERN.test(record.operationId) ||
|
||||
!Number.isSafeInteger(record.size) ||
|
||||
Number(record.size) <= 0 ||
|
||||
typeof record.sha256 !== 'string' ||
|
||||
!SHA256_PATTERN.test(record.sha256) ||
|
||||
!Array.isArray(record.urls) ||
|
||||
record.urls.length > 4 ||
|
||||
record.urls.some(
|
||||
(url) =>
|
||||
typeof url !== 'string' ||
|
||||
Buffer.byteLength(url, 'utf8') > 4_096
|
||||
)
|
||||
!OPERATION_ID_PATTERN.test(record.operationId)
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
@@ -133,9 +118,6 @@ function parsePendingOperation(
|
||||
version: 1,
|
||||
hostId: expectedHostId,
|
||||
targetIdentity: record.targetIdentity,
|
||||
operationId: record.operationId,
|
||||
size: Number(record.size),
|
||||
sha256: record.sha256,
|
||||
urls: [...record.urls] as string[]
|
||||
operationId: record.operationId
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,12 +4,10 @@ import {
|
||||
SshRemotePackageCommitIndeterminateError,
|
||||
type SshRemotePackageIdentity
|
||||
} from '../ssh/ssh-remote-package-bootstrap'
|
||||
import type { StagedSftp } from '../ssh/bounded-sftp'
|
||||
import type {
|
||||
AgentPackageArchiveLease,
|
||||
VerifiedRemoteAgentInstallCandidate
|
||||
} from './agent-package-manager'
|
||||
import { REMOTE_ENVIRONMENT_METADATA_PATHS } from './remote-environment-metadata'
|
||||
import type {
|
||||
PendingRemoteEnvironmentOperation
|
||||
} from './remote-environment-operation-store'
|
||||
@@ -100,70 +98,13 @@ type FixtureOptions = {
|
||||
prepare?: ReturnType<typeof vi.fn>
|
||||
prepareUploaded?: ReturnType<typeof vi.fn>
|
||||
commit?: ReturnType<typeof vi.fn>
|
||||
cleanup?: ReturnType<typeof vi.fn>
|
||||
uploadFile?: ReturnType<typeof vi.fn>
|
||||
activateAgent?: ReturnType<typeof vi.fn>
|
||||
activateRuntime?: ReturnType<typeof vi.fn>
|
||||
metadataFiles?: Map<string, Buffer>
|
||||
metadataReplaceFailure?: Error
|
||||
pendingOperation?: PendingRemoteEnvironmentOperation
|
||||
}
|
||||
|
||||
function missingPath(): Error & { code: string } {
|
||||
return Object.assign(new Error('missing'), { code: 'ENOENT' })
|
||||
}
|
||||
|
||||
function metadataSftp(
|
||||
files: Map<string, Buffer>,
|
||||
calls: string[],
|
||||
replaceFailure?: Error
|
||||
): StagedSftp {
|
||||
const temporary = new Map<string, Buffer>()
|
||||
return {
|
||||
stagingDirectory: '/home/goodbuddy',
|
||||
mkdir: vi.fn(),
|
||||
uploadFile: vi.fn(),
|
||||
writeFile: vi.fn(async (path: string, contents: Buffer) => {
|
||||
temporary.set(path, Buffer.from(contents))
|
||||
}),
|
||||
readFile: vi.fn(async (path: string) => {
|
||||
const contents = files.get(path) ?? temporary.get(path)
|
||||
if (!contents) throw missingPath()
|
||||
return Buffer.from(contents)
|
||||
}),
|
||||
lstat: vi.fn(async (path: string) => {
|
||||
const contents = files.get(path) ?? temporary.get(path)
|
||||
if (!contents) throw missingPath()
|
||||
return {
|
||||
type: 'file' as const,
|
||||
size: contents.byteLength,
|
||||
mode: 0o600,
|
||||
uid: 1000,
|
||||
gid: 1000,
|
||||
atime: 0,
|
||||
mtime: 0
|
||||
}
|
||||
}),
|
||||
stat: vi.fn(),
|
||||
chmod: vi.fn(),
|
||||
setExecutable: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
replaceFile: vi.fn(async (source: string, destination: string) => {
|
||||
if (replaceFailure) throw replaceFailure
|
||||
const contents = temporary.get(source)
|
||||
if (!contents) throw missingPath()
|
||||
files.set(destination, contents)
|
||||
temporary.delete(source)
|
||||
}),
|
||||
unlink: vi.fn(async (path: string) => {
|
||||
if (!files.delete(path) && !temporary.delete(path)) {
|
||||
throw missingPath()
|
||||
}
|
||||
}),
|
||||
rmdir: vi.fn(),
|
||||
close: vi.fn(() => calls.push('close-metadata'))
|
||||
}
|
||||
}
|
||||
|
||||
function fixture(options: FixtureOptions = {}) {
|
||||
const calls: string[] = []
|
||||
const targets = options.targets ?? [target()]
|
||||
@@ -180,12 +121,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
hostKeyGeneration: targets[0]!.hostKeyGeneration,
|
||||
authenticationIdentity: '3'.repeat(64)
|
||||
}
|
||||
const metadataFiles = options.metadataFiles ?? new Map<string, Buffer>()
|
||||
const metadata = metadataSftp(
|
||||
metadataFiles,
|
||||
calls,
|
||||
options.metadataReplaceFailure
|
||||
)
|
||||
const uploadFile = options.uploadFile ?? vi.fn(async (
|
||||
path: string
|
||||
) => {
|
||||
@@ -200,8 +135,13 @@ function fixture(options: FixtureOptions = {}) {
|
||||
close: vi.fn(() => calls.push('close-upload'))
|
||||
}
|
||||
const regularRelease = vi.fn(() => calls.push('release-probe'))
|
||||
const stopCandidate = vi.fn(async () => {
|
||||
calls.push('stop-candidate')
|
||||
const activateAgent = options.activateAgent ?? vi.fn(async () => {
|
||||
calls.push('agent')
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
})
|
||||
const activateRuntime = options.activateRuntime ?? vi.fn(async () => {
|
||||
calls.push('runtime')
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
})
|
||||
const regularLease = {
|
||||
identity: leaseIdentity,
|
||||
@@ -218,15 +158,24 @@ function fixture(options: FixtureOptions = {}) {
|
||||
procfs: 'ready'
|
||||
}
|
||||
}),
|
||||
openStagedSftp: vi.fn(async (root: string) => {
|
||||
if (root.includes('install-operations')) {
|
||||
calls.push('open-upload')
|
||||
return uploadSftp
|
||||
}
|
||||
calls.push('open-metadata')
|
||||
return metadata
|
||||
openStagedSftp: vi.fn(async () => {
|
||||
calls.push('open-upload')
|
||||
return uploadSftp
|
||||
}),
|
||||
runAgentLifecycleAction: stopCandidate,
|
||||
runAgentLifecycleAction: vi.fn(async (
|
||||
installationId: string,
|
||||
action: string
|
||||
) => (activateAgent as (
|
||||
installationId: string,
|
||||
action: string
|
||||
) => Promise<unknown>)(installationId, action)),
|
||||
runAgentRuntimeAction: vi.fn(async (
|
||||
installationId: string,
|
||||
action: unknown
|
||||
) => (activateRuntime as (
|
||||
installationId: string,
|
||||
action: unknown
|
||||
) => Promise<unknown>)(installationId, action)),
|
||||
release: regularRelease
|
||||
}
|
||||
const prepare = options.prepare ?? vi.fn(async (
|
||||
@@ -264,17 +213,10 @@ function fixture(options: FixtureOptions = {}) {
|
||||
identity: structuredClone(identity)
|
||||
}
|
||||
})
|
||||
const cleanup = vi.fn(async (operationId: string) => {
|
||||
const cleanup = options.cleanup ?? vi.fn(async (operationId: string) => {
|
||||
calls.push('cleanup')
|
||||
return { cleaned: true, operationId }
|
||||
})
|
||||
const commitStatus = vi.fn(async (
|
||||
input: { operationId: string }
|
||||
) => ({
|
||||
committed: true,
|
||||
operationId: input.operationId,
|
||||
identity
|
||||
}))
|
||||
const bootstrapRelease = vi.fn(() => calls.push('release-bootstrap'))
|
||||
const probe = vi.fn(async () => {
|
||||
calls.push('method-probe')
|
||||
@@ -303,7 +245,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
prepare,
|
||||
prepareUploaded,
|
||||
commit,
|
||||
commitStatus,
|
||||
cleanup,
|
||||
release: bootstrapRelease
|
||||
}
|
||||
@@ -326,13 +267,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
calls.push('acquire-archive')
|
||||
return archive
|
||||
})
|
||||
const activateAgent = options.activateAgent ?? vi.fn(async () => {
|
||||
calls.push('agent')
|
||||
return identity.agent
|
||||
})
|
||||
const activateRuntime = options.activateRuntime ?? vi.fn(async () => {
|
||||
calls.push('runtime')
|
||||
})
|
||||
let pendingOperation = options.pendingOperation
|
||||
const operationStore = {
|
||||
load: vi.fn(async () => pendingOperation),
|
||||
@@ -367,12 +301,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
acquireInstallArchive,
|
||||
acquireGoodBuddyInstallArchive
|
||||
},
|
||||
agentInstallationManager: {
|
||||
activatePublished: activateAgent
|
||||
} as never,
|
||||
runtimeInstallationManager: {
|
||||
activatePublished: activateRuntime
|
||||
} as never,
|
||||
operationStore
|
||||
})
|
||||
return {
|
||||
@@ -381,8 +309,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
resolver,
|
||||
regularLease,
|
||||
bootstrapLease,
|
||||
metadata,
|
||||
metadataFiles,
|
||||
uploadFile,
|
||||
probe,
|
||||
createUploadStaging,
|
||||
@@ -396,8 +322,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
archiveRelease,
|
||||
regularRelease,
|
||||
bootstrapRelease,
|
||||
stopCandidate,
|
||||
commitStatus,
|
||||
operationStore
|
||||
}
|
||||
}
|
||||
@@ -424,17 +348,12 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
'acquire-bootstrap',
|
||||
'save-operation',
|
||||
'prepare',
|
||||
'open-metadata',
|
||||
'resolve',
|
||||
'commit',
|
||||
'resolve',
|
||||
'agent',
|
||||
'resolve',
|
||||
'runtime',
|
||||
'resolve',
|
||||
'cleanup',
|
||||
'remove-operation',
|
||||
'close-metadata',
|
||||
'release-bootstrap',
|
||||
'release-probe'
|
||||
])
|
||||
@@ -447,17 +366,18 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(remoteCandidate.operationId).toMatch(/^[0-9a-f-]{36}$/u)
|
||||
expect(value.commit.mock.calls[0]?.[0]).toEqual(remoteCandidate)
|
||||
expect(value.activateAgent).toHaveBeenCalledWith(
|
||||
HOST_ID,
|
||||
identity.agent,
|
||||
expect.objectContaining({ signal: controller.signal })
|
||||
identity.agent.installationId,
|
||||
'adopt'
|
||||
)
|
||||
expect(value.activateRuntime).toHaveBeenCalledWith(
|
||||
HOST_ID,
|
||||
identity.runtime,
|
||||
expect.objectContaining({
|
||||
agentInstallationId: identity.agent.installationId,
|
||||
signal: controller.signal
|
||||
})
|
||||
identity.agent.installationId,
|
||||
{
|
||||
kind: 'runtime-activate',
|
||||
runtimeId: identity.runtime.runtimeId,
|
||||
bundleDigest: identity.runtime.bundleDigest,
|
||||
architecture: identity.runtime.architecture,
|
||||
forceVerification: true
|
||||
}
|
||||
)
|
||||
expect(value.cleanup).toHaveBeenCalledWith(
|
||||
remoteCandidate.operationId,
|
||||
@@ -495,6 +415,26 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.archiveRelease).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps an adopted environment healthy when staging cleanup must be retried', async () => {
|
||||
const value = fixture({
|
||||
cleanup: vi.fn(async (operationId: string) => ({
|
||||
cleaned: false,
|
||||
operationId,
|
||||
reason: 'cleanup-failed'
|
||||
}))
|
||||
})
|
||||
|
||||
await expect(value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)).resolves.toBeUndefined()
|
||||
expect(value.activateAgent).toHaveBeenCalledOnce()
|
||||
expect(value.activateRuntime).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('releases the archive and cleans the operation when a GoodBuddy upload fails', async () => {
|
||||
const uploadFailure = new Error('upload failed')
|
||||
const value = fixture({
|
||||
@@ -690,6 +630,32 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.activateRuntime).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cleans staging when cancellation arrives with a successful commit result', async () => {
|
||||
const controller = new AbortController()
|
||||
const cancellation =
|
||||
new DOMException('cancelled after commit', 'AbortError')
|
||||
const value = fixture({
|
||||
commit: vi.fn(async (input: { operationId: string }) => {
|
||||
controller.abort(cancellation)
|
||||
return {
|
||||
committed: true,
|
||||
operationId: input.operationId,
|
||||
identity
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
await expect(value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
controller.signal
|
||||
)).rejects.toBe(cancellation)
|
||||
expect(value.cleanup).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
expect(value.activateAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps rollback-incomplete commits recoverable without cleanup', async () => {
|
||||
const value = fixture({
|
||||
commit: vi.fn(async () => ({
|
||||
@@ -710,28 +676,18 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reconciles and cleans a pending commit before starting new work', async () => {
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000777'
|
||||
it('cleans pending staging and starts a fresh authenticated prepare', async () => {
|
||||
const originalTarget = target()
|
||||
const renamedTarget = target({
|
||||
host: {
|
||||
...originalTarget.host,
|
||||
name: 'Renamed builder'
|
||||
},
|
||||
hostRevision: 99
|
||||
})
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000780'
|
||||
const value = fixture({
|
||||
targets: [renamedTarget],
|
||||
targets: [originalTarget],
|
||||
pendingOperation: {
|
||||
version: 1,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId: pendingOperationId,
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls
|
||||
operationId: pendingOperationId
|
||||
}
|
||||
})
|
||||
|
||||
@@ -742,12 +698,6 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
new AbortController().signal
|
||||
)
|
||||
|
||||
expect(value.commitStatus).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
operationId: pendingOperationId
|
||||
}),
|
||||
expect.any(Object)
|
||||
)
|
||||
expect(value.cleanup.mock.calls[0]?.[0]).toBe(
|
||||
pendingOperationId
|
||||
)
|
||||
@@ -755,27 +705,31 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.operationStore.remove).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('retains pending recovery evidence when the real SSH target changes', async () => {
|
||||
it('does not block a fresh prepare when stale staging cleanup fails', async () => {
|
||||
const originalTarget = target()
|
||||
const changedTarget = target({
|
||||
host: {
|
||||
...originalTarget.host,
|
||||
hostname: 'different.example'
|
||||
}
|
||||
})
|
||||
let cleanupCalls = 0
|
||||
const value = fixture({
|
||||
targets: [changedTarget],
|
||||
targets: [originalTarget],
|
||||
pendingOperation: {
|
||||
version: 1,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId:
|
||||
'00000000-0000-4000-8000-000000000778',
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls
|
||||
}
|
||||
'00000000-0000-4000-8000-000000000779'
|
||||
},
|
||||
cleanup: vi.fn(async (operationId: string) => {
|
||||
cleanupCalls += 1
|
||||
return cleanupCalls === 1
|
||||
? {
|
||||
cleaned: false as const,
|
||||
reason: 'cleanup-failed' as const
|
||||
}
|
||||
: {
|
||||
cleaned: true as const,
|
||||
operationId
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
await expect(value.preparer.prepare(
|
||||
@@ -783,32 +737,51 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)).rejects.toBeInstanceOf(
|
||||
SshRemotePackageCommitIndeterminateError
|
||||
)
|
||||
expect(value.commitStatus).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
)).resolves.toBeUndefined()
|
||||
|
||||
expect(value.prepare).toHaveBeenCalledOnce()
|
||||
expect(value.cleanup).toHaveBeenCalledTimes(2)
|
||||
expect(value.operationStore.remove).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('stops the committed Agent and restores all five metadata files when Runtime adoption fails', async () => {
|
||||
const originals = new Map<string, Buffer>()
|
||||
for (const [index, path] of REMOTE_ENVIRONMENT_METADATA_PATHS.entries()) {
|
||||
if (index !== 2) originals.set(path, Buffer.from(`original-${index}`))
|
||||
}
|
||||
const files = new Map(
|
||||
[...originals].map(([path, contents]) => [path, Buffer.from(contents)])
|
||||
it('drops stale cleanup state when the SSH target changed and starts fresh', async () => {
|
||||
const originalTarget = target()
|
||||
const changedTarget = target({
|
||||
host: {
|
||||
...originalTarget.host,
|
||||
hostname: 'different.example'
|
||||
}
|
||||
})
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000778'
|
||||
const value = fixture({
|
||||
targets: [changedTarget],
|
||||
pendingOperation: {
|
||||
version: 1,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId: pendingOperationId
|
||||
}
|
||||
})
|
||||
|
||||
await value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)
|
||||
const runtimeFailure = new Error('runtime health failed')
|
||||
|
||||
expect(value.prepare).toHaveBeenCalledOnce()
|
||||
expect(value.cleanup.mock.calls.some(
|
||||
(call) => call[0] === pendingOperationId
|
||||
)).toBe(false)
|
||||
expect(value.operationStore.remove).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('cleans staging and leaves a fresh retry after Runtime adoption fails', async () => {
|
||||
const runtimeFailure = new Error('runtime failed')
|
||||
const value = fixture({
|
||||
metadataFiles: files,
|
||||
activateAgent: vi.fn(async () => {
|
||||
value.metadataFiles.clear()
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
value.metadataFiles.set(path, Buffer.from('new'))
|
||||
}
|
||||
return identity.agent
|
||||
value.calls.push('agent')
|
||||
}),
|
||||
activateRuntime: vi.fn(async () => {
|
||||
throw runtimeFailure
|
||||
})
|
||||
@@ -820,42 +793,7 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)).rejects.toBe(runtimeFailure)
|
||||
expect(value.stopCandidate).toHaveBeenCalledWith(
|
||||
identity.agent.installationId,
|
||||
'stop'
|
||||
)
|
||||
expect([...value.metadataFiles]).toEqual([...originals])
|
||||
expect(value.cleanup).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('throws AggregateError when adoption and metadata rollback both fail', async () => {
|
||||
const path = REMOTE_ENVIRONMENT_METADATA_PATHS[0]
|
||||
const files = new Map([[path, Buffer.from('original')]])
|
||||
const runtimeFailure = new Error('runtime failed')
|
||||
const rollbackFailure = new Error('replace failed')
|
||||
const value = fixture({
|
||||
metadataFiles: files,
|
||||
metadataReplaceFailure: rollbackFailure,
|
||||
activateAgent: vi.fn(async () => {
|
||||
files.set(path, Buffer.from('changed'))
|
||||
return identity.agent
|
||||
}),
|
||||
activateRuntime: vi.fn(async () => {
|
||||
throw runtimeFailure
|
||||
})
|
||||
})
|
||||
|
||||
const caught = await value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
).catch((error: unknown) => error)
|
||||
expect(caught).toBeInstanceOf(AggregateError)
|
||||
expect((caught as AggregateError).errors[0]).toBe(runtimeFailure)
|
||||
expect((caught as AggregateError).errors[1]).toBeInstanceOf(
|
||||
AggregateError
|
||||
)
|
||||
expect(value.stopCandidate).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,9 +5,9 @@ import type {
|
||||
RemoteEnvironmentPreparationMethod,
|
||||
RemoteEnvironmentUpdateProgress
|
||||
} from '../../shared/ssh-host-contracts'
|
||||
import type { StagedSftp } from '../ssh/bounded-sftp'
|
||||
import { verifyAgentInstallationId } from '../ssh/ssh-agent-command'
|
||||
import type {
|
||||
AgentDiagnosticResult,
|
||||
SshConnectionLease,
|
||||
SshConnectionPool,
|
||||
SshRemotePackageBootstrapLease
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
type SshRemotePackageIdentity
|
||||
} from '../ssh/ssh-remote-package-bootstrap'
|
||||
import type {
|
||||
AgentInstallationManager,
|
||||
AgentInstallationTargetResolver
|
||||
} from './agent-installation-manager'
|
||||
import type {
|
||||
@@ -33,31 +32,40 @@ import type {
|
||||
AgentPackageManager,
|
||||
VerifiedRemoteAgentInstallCandidate
|
||||
} from './agent-package-manager'
|
||||
import {
|
||||
restoreRemoteEnvironmentMetadata,
|
||||
snapshotRemoteEnvironmentMetadata,
|
||||
type RemoteEnvironmentMetadataSnapshot
|
||||
} from './remote-environment-metadata'
|
||||
import {
|
||||
mapAgentInstallationPhase,
|
||||
mapRuntimeInstallationPhase
|
||||
} from './remote-environment-progress'
|
||||
import type {
|
||||
PendingRemoteEnvironmentOperation,
|
||||
RemoteEnvironmentOperationStore
|
||||
} from './remote-environment-operation-store'
|
||||
import type {
|
||||
RemoteEnvironmentPreparer as Preparer,
|
||||
RemoteEnvironmentUpdateProgressObserver
|
||||
} from './remote-environment-update-service'
|
||||
import type {
|
||||
RemoteRuntimeInstallationManager
|
||||
} from './remote-runtime-installation-manager'
|
||||
import {
|
||||
remoteHostRecoveryIdentityKey
|
||||
} from './remote-host-target-identity'
|
||||
import { boundedDiagnostic } from './bounded-diagnostic'
|
||||
|
||||
const MAXIMUM_PACKAGE_BYTES = 512 * 1024 * 1024
|
||||
const MAXIMUM_METADATA_BYTES = 1024 * 1024
|
||||
const MAXIMUM_DIAGNOSTIC_CHARACTERS = 800
|
||||
|
||||
function assertAgentCommandSucceeded(
|
||||
result: AgentDiagnosticResult,
|
||||
label: string
|
||||
): void {
|
||||
if (result.exitCode === 0) {
|
||||
return
|
||||
}
|
||||
const detail = `${result.stderr}\n${result.stdout}`
|
||||
const bounded = boundedDiagnostic(
|
||||
detail,
|
||||
MAXIMUM_DIAGNOSTIC_CHARACTERS
|
||||
)
|
||||
throw new Error(
|
||||
bounded.length > 0
|
||||
? `${label}失败:${bounded}`
|
||||
: `${label}失败,退出码 ${String(result.exitCode)}`
|
||||
)
|
||||
}
|
||||
|
||||
export type RemoteEnvironmentPreparerOptions = {
|
||||
resolver: AgentInstallationTargetResolver
|
||||
@@ -71,14 +79,6 @@ export type RemoteEnvironmentPreparerOptions = {
|
||||
| 'acquireInstallArchive'
|
||||
| 'acquireGoodBuddyInstallArchive'
|
||||
>
|
||||
agentInstallationManager: Pick<
|
||||
AgentInstallationManager,
|
||||
'activatePublished'
|
||||
>
|
||||
runtimeInstallationManager: Pick<
|
||||
RemoteRuntimeInstallationManager,
|
||||
'activatePublished'
|
||||
>
|
||||
operationStore: Pick<
|
||||
RemoteEnvironmentOperationStore,
|
||||
'load' | 'save' | 'remove'
|
||||
@@ -88,17 +88,13 @@ export type RemoteEnvironmentPreparerOptions = {
|
||||
/**
|
||||
* Prepares one signed compound environment. The selected method controls only
|
||||
* how the archive reaches the Host; both paths share prepare, commit,
|
||||
* activation, rollback, health checks, and cleanup.
|
||||
* activation, health checks, and cleanup.
|
||||
*/
|
||||
export class RemoteEnvironmentPreparer implements Preparer {
|
||||
readonly #resolver: AgentInstallationTargetResolver
|
||||
readonly #sshPool: RemoteEnvironmentPreparerOptions['sshPool']
|
||||
readonly #agentPackageManager:
|
||||
RemoteEnvironmentPreparerOptions['agentPackageManager']
|
||||
readonly #agentInstallationManager:
|
||||
RemoteEnvironmentPreparerOptions['agentInstallationManager']
|
||||
readonly #runtimeInstallationManager:
|
||||
RemoteEnvironmentPreparerOptions['runtimeInstallationManager']
|
||||
readonly #operationStore:
|
||||
RemoteEnvironmentPreparerOptions['operationStore']
|
||||
|
||||
@@ -106,10 +102,6 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
this.#resolver = options.resolver
|
||||
this.#sshPool = options.sshPool
|
||||
this.#agentPackageManager = options.agentPackageManager
|
||||
this.#agentInstallationManager =
|
||||
options.agentInstallationManager
|
||||
this.#runtimeInstallationManager =
|
||||
options.runtimeInstallationManager
|
||||
this.#operationStore = options.operationStore
|
||||
}
|
||||
|
||||
@@ -135,7 +127,7 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
const target = await this.#resolver.resolve(hostId)
|
||||
signal.throwIfAborted()
|
||||
assertValidSshConnectionTarget(hostId, target)
|
||||
await this.#reconcilePendingOperation(
|
||||
await this.#cleanupPendingOperation(
|
||||
hostId,
|
||||
target,
|
||||
emit,
|
||||
@@ -147,14 +139,9 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
| SshRemotePackageBootstrapLease
|
||||
| undefined
|
||||
let archiveLease: AgentPackageArchiveLease | undefined
|
||||
let metadataSftp: StagedSftp | undefined
|
||||
let metadataSnapshots:
|
||||
| readonly RemoteEnvironmentMetadataSnapshot[]
|
||||
| undefined
|
||||
let operationId: string | undefined
|
||||
let operationCleaned = false
|
||||
let pendingOperationSaved = false
|
||||
let committedIdentity: SshRemotePackageIdentity | undefined
|
||||
try {
|
||||
probeLease = await this.#sshPool.acquire(target, signal)
|
||||
assertLeaseMatchesTarget(probeLease, target)
|
||||
@@ -254,16 +241,13 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
}
|
||||
emit(method, 'probing')
|
||||
|
||||
// Persist recovery identity before either preparation path may create
|
||||
// remote staging. A Main crash must never leave an untracked operation.
|
||||
// Keep only the operation ID needed to clean stale staging before the
|
||||
// next fresh attempt. No remote environment state is copied locally.
|
||||
await this.#operationStore.save({
|
||||
version: 1,
|
||||
hostId,
|
||||
targetIdentity: remoteHostRecoveryIdentityKey(target),
|
||||
operationId,
|
||||
size: remoteCandidate.size,
|
||||
sha256: remoteCandidate.sha256,
|
||||
urls: [...remoteCandidate.urls]
|
||||
operationId
|
||||
})
|
||||
pendingOperationSaved = true
|
||||
|
||||
@@ -287,24 +271,6 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
assertPrepared(prepared, operationId)
|
||||
assertPackageIdentity(prepared.identity, candidate)
|
||||
|
||||
// Snapshot the complete environment before commit so an Agent success
|
||||
// followed by a Runtime failure cannot expose a partially adopted pair.
|
||||
metadataSftp = await probeLease.openStagedSftp(
|
||||
probe.canonicalHomeDirectory,
|
||||
{
|
||||
maximumFileBytes: MAXIMUM_METADATA_BYTES,
|
||||
maximumTotalBytes: MAXIMUM_METADATA_BYTES * 24,
|
||||
maximumOperations: 128
|
||||
},
|
||||
signal
|
||||
)
|
||||
metadataSnapshots =
|
||||
await snapshotRemoteEnvironmentMetadata(
|
||||
metadataSftp,
|
||||
probe.uid,
|
||||
signal
|
||||
)
|
||||
|
||||
// Keep the full target re-resolution immediately adjacent to commit.
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
assertLeaseMatchesTarget(bootstrapLease, target)
|
||||
@@ -319,7 +285,6 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
}
|
||||
}
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
if (!committed.committed) {
|
||||
if (
|
||||
committed.reason ===
|
||||
@@ -330,7 +295,7 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
)
|
||||
}
|
||||
throw new Error(
|
||||
`远端安装提交失败:${committed.reason}`
|
||||
`远端安装提交失败:${committed.detail ?? committed.reason}`
|
||||
)
|
||||
}
|
||||
if (
|
||||
@@ -343,73 +308,38 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
throw new Error('远端安装提交身份与准备身份不匹配')
|
||||
}
|
||||
assertPackageIdentity(committed.identity, candidate)
|
||||
committedIdentity = committed.identity
|
||||
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
const activeAgent =
|
||||
await this.#agentInstallationManager.activatePublished(
|
||||
hostId,
|
||||
committed.identity.agent,
|
||||
{
|
||||
signal,
|
||||
onProgress: (phase) => {
|
||||
const mapped = mapAgentInstallationPhase(phase)
|
||||
if (mapped) {
|
||||
emit(method, mapped)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
|
||||
await this.#runtimeInstallationManager.activatePublished(
|
||||
hostId,
|
||||
committed.identity.runtime,
|
||||
{
|
||||
agentInstallationId: activeAgent.installationId,
|
||||
signal,
|
||||
onProgress: (phase) => {
|
||||
const mapped = mapRuntimeInstallationPhase(phase)
|
||||
if (mapped) {
|
||||
emit(method, mapped)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
|
||||
const cleanup = await bootstrapLease.cleanup(operationId, {
|
||||
await this.#adoptCommittedEnvironment(
|
||||
probeLease,
|
||||
committed.identity,
|
||||
method,
|
||||
emit,
|
||||
signal
|
||||
})
|
||||
if (!cleanup.cleaned) {
|
||||
throw new Error(
|
||||
`远程环境已安装,但暂存文件清理失败:${cleanup.reason}`
|
||||
)
|
||||
|
||||
emit(method, 'finalizing')
|
||||
try {
|
||||
const cleanup = await bootstrapLease.cleanup(
|
||||
operationId,
|
||||
{ signal }
|
||||
)
|
||||
}
|
||||
operationCleaned = true
|
||||
await this.#operationStore.remove(hostId)
|
||||
} catch (error) {
|
||||
let rollbackError: unknown
|
||||
if (
|
||||
committedIdentity &&
|
||||
metadataSftp &&
|
||||
metadataSnapshots
|
||||
) {
|
||||
await stopCandidateBestEffort(
|
||||
probeLease,
|
||||
committedIdentity.agent.installationId
|
||||
)
|
||||
try {
|
||||
await restoreRemoteEnvironmentMetadata(
|
||||
metadataSftp,
|
||||
metadataSnapshots
|
||||
)
|
||||
} catch (reason) {
|
||||
rollbackError = reason
|
||||
if (
|
||||
cleanup.cleaned ||
|
||||
cleanup.reason === 'operation-unavailable'
|
||||
) {
|
||||
operationCleaned = true
|
||||
try {
|
||||
await this.#operationStore.remove(hostId)
|
||||
} catch {
|
||||
// A stale local receipt is harmless after remote cleanup.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// The environment is already healthy. The next update will retry
|
||||
// cleanup before starting a fresh operation.
|
||||
}
|
||||
} catch (error) {
|
||||
if (
|
||||
operationId &&
|
||||
bootstrapLease &&
|
||||
@@ -421,25 +351,59 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
operationId
|
||||
)
|
||||
if (operationCleaned && pendingOperationSaved) {
|
||||
await this.#operationStore.remove(hostId)
|
||||
await this.#operationStore.remove(hostId).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
if (rollbackError) {
|
||||
throw new AggregateError(
|
||||
[error, rollbackError],
|
||||
'远程运行环境准备失败,且原有环境元数据未能完整恢复',
|
||||
{ cause: error }
|
||||
)
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
metadataSftp?.close()
|
||||
archiveLease?.release()
|
||||
bootstrapLease?.release()
|
||||
probeLease?.release()
|
||||
}
|
||||
}
|
||||
|
||||
async #adoptCommittedEnvironment(
|
||||
lease: SshConnectionLease,
|
||||
identity: SshRemotePackageIdentity,
|
||||
method: RemoteEnvironmentPreparationMethod,
|
||||
emit: (
|
||||
method: RemoteEnvironmentPreparationMethod,
|
||||
phase: RemoteEnvironmentUpdateProgress['phase']
|
||||
) => void,
|
||||
signal: AbortSignal
|
||||
): Promise<void> {
|
||||
const installationId = verifyAgentInstallationId(
|
||||
identity.agent.installationId
|
||||
)
|
||||
emit(method, 'installing-agent')
|
||||
assertAgentCommandSucceeded(
|
||||
await lease.runAgentLifecycleAction(
|
||||
installationId,
|
||||
'adopt',
|
||||
signal
|
||||
),
|
||||
'GoodBuddy Agent 启动与健康检查'
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
|
||||
emit(method, 'installing-runtime')
|
||||
assertAgentCommandSucceeded(
|
||||
await lease.runAgentRuntimeAction(
|
||||
installationId,
|
||||
{
|
||||
kind: 'runtime-activate',
|
||||
runtimeId: identity.runtime.runtimeId,
|
||||
bundleDigest: identity.runtime.bundleDigest,
|
||||
architecture: identity.runtime.architecture,
|
||||
forceVerification: true
|
||||
},
|
||||
signal
|
||||
),
|
||||
'OpenCode Runtime 激活'
|
||||
)
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
|
||||
async #prepareUploadedArchive(options: {
|
||||
probeLease: SshConnectionLease
|
||||
bootstrapLease: SshRemotePackageBootstrapLease
|
||||
@@ -559,7 +523,7 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
)
|
||||
}
|
||||
|
||||
async #reconcilePendingOperation(
|
||||
async #cleanupPendingOperation(
|
||||
hostId: string,
|
||||
target: SshConnectionTarget,
|
||||
emit: (
|
||||
@@ -568,7 +532,13 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
) => void,
|
||||
signal: AbortSignal
|
||||
): Promise<void> {
|
||||
const pending = await this.#operationStore.load(hostId)
|
||||
let pending: PendingRemoteEnvironmentOperation | undefined
|
||||
try {
|
||||
pending = await this.#operationStore.load(hostId)
|
||||
} catch {
|
||||
await this.#operationStore.remove(hostId)
|
||||
return
|
||||
}
|
||||
if (!pending) {
|
||||
return
|
||||
}
|
||||
@@ -576,60 +546,27 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
pending.targetIdentity !==
|
||||
remoteHostRecoveryIdentityKey(target)
|
||||
) {
|
||||
throw new SshRemotePackageCommitIndeterminateError(
|
||||
'SSH Host 连接目标已变化,无法确认上一次远程环境提交;请恢复原 Host 连接后重试,或删除此 Host 以明确放弃恢复'
|
||||
)
|
||||
await this.#operationStore.remove(hostId)
|
||||
return
|
||||
}
|
||||
emit('auto', 'applying')
|
||||
const candidate: SshRemotePackageCandidate = {
|
||||
operationId: pending.operationId,
|
||||
size: pending.size,
|
||||
sha256: pending.sha256,
|
||||
urls: pending.urls
|
||||
}
|
||||
const lease =
|
||||
const bootstrapLease =
|
||||
await this.#sshPool.acquireRemotePackageBootstrap(
|
||||
target,
|
||||
signal
|
||||
)
|
||||
).catch(() => undefined)
|
||||
try {
|
||||
assertLeaseMatchesTarget(lease, target)
|
||||
const status = await lease.commitStatus(candidate, {
|
||||
signal
|
||||
})
|
||||
if (
|
||||
!status.committed &&
|
||||
status.reason === 'installer-rollback-incomplete'
|
||||
) {
|
||||
throw new SshRemotePackageCommitIndeterminateError(
|
||||
'上一次远程环境发布失败且回滚结果不完整,请检查 Host 状态'
|
||||
)
|
||||
if (!bootstrapLease) {
|
||||
return
|
||||
}
|
||||
const cleanup = await lease.cleanup(
|
||||
assertLeaseMatchesTarget(bootstrapLease, target)
|
||||
await bootstrapLease.cleanup(
|
||||
pending.operationId,
|
||||
{ signal }
|
||||
)
|
||||
if (
|
||||
!cleanup.cleaned &&
|
||||
cleanup.reason !== 'operation-unavailable'
|
||||
) {
|
||||
throw new Error(
|
||||
`上一次远程环境暂存清理失败:${cleanup.reason}`
|
||||
)
|
||||
}
|
||||
await this.#operationStore.remove(hostId)
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof
|
||||
SshRemotePackageCommitIndeterminateError
|
||||
) {
|
||||
throw error
|
||||
}
|
||||
throw new SshRemotePackageCommitIndeterminateError(
|
||||
'上一次远程环境提交结果仍不确定,请稍后重试'
|
||||
)
|
||||
).catch(() => undefined)
|
||||
} finally {
|
||||
lease.release()
|
||||
bootstrapLease?.release()
|
||||
await this.#operationStore.remove(hostId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -660,7 +597,7 @@ function assertPrepared(
|
||||
throw new Error(
|
||||
prepared.unavailable
|
||||
? `远端环境准备不可用:${prepared.reason}`
|
||||
: `远端环境准备失败:${prepared.reason}`
|
||||
: `远端环境准备失败:${prepared.detail ?? prepared.reason}`
|
||||
)
|
||||
}
|
||||
if (prepared.operationId !== operationId) {
|
||||
@@ -684,23 +621,6 @@ async function cleanupBestEffort(
|
||||
}
|
||||
}
|
||||
|
||||
async function stopCandidateBestEffort(
|
||||
lease: SshConnectionLease | undefined,
|
||||
installationId: string
|
||||
): Promise<void> {
|
||||
if (!lease?.isUsable()) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await lease.runAgentLifecycleAction(
|
||||
verifyAgentInstallationId(installationId),
|
||||
'stop'
|
||||
)
|
||||
} catch {
|
||||
// Metadata rollback remains the authoritative recovery action.
|
||||
}
|
||||
}
|
||||
|
||||
async function assertTargetCurrent(
|
||||
resolver: AgentInstallationTargetResolver,
|
||||
expected: SshConnectionTarget,
|
||||
@@ -809,7 +729,6 @@ function mapBootstrapPhase(
|
||||
case 'verifying-zip':
|
||||
case 'verifying-payload':
|
||||
case 'validating-prepared-state':
|
||||
case 'revalidating-archive':
|
||||
return 'verifying'
|
||||
case 'extracting':
|
||||
case 'preparing':
|
||||
@@ -819,6 +738,7 @@ function mapBootstrapPhase(
|
||||
case 'persisting-prepared-state':
|
||||
case 'extracting-payload':
|
||||
case 'publishing-content':
|
||||
case 'publishing-metadata':
|
||||
case 'cleaning':
|
||||
return 'applying'
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import type { RemoteEnvironmentUpdateProgress } from '../../shared/ssh-host-contracts'
|
||||
import type { AgentInstallationPhase } from './agent-installation-manager'
|
||||
import type { RemoteRuntimeInstallationPhase } from './remote-runtime-installation-manager'
|
||||
|
||||
export function mapAgentInstallationPhase(
|
||||
phase: AgentInstallationPhase
|
||||
): RemoteEnvironmentUpdateProgress['phase'] | undefined {
|
||||
switch (phase) {
|
||||
case 'inspecting-host':
|
||||
return 'probing'
|
||||
case 'verifying-bundle':
|
||||
return 'verifying'
|
||||
case 'starting-agent':
|
||||
return 'installing-agent'
|
||||
case 'checking-health':
|
||||
return 'checking-health'
|
||||
case 'complete':
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function mapRuntimeInstallationPhase(
|
||||
phase: RemoteRuntimeInstallationPhase
|
||||
): RemoteEnvironmentUpdateProgress['phase'] | undefined {
|
||||
switch (phase) {
|
||||
case 'inspecting-host':
|
||||
return 'probing'
|
||||
case 'verifying-bundle':
|
||||
return 'verifying'
|
||||
case 'activating-runtime':
|
||||
return 'installing-runtime'
|
||||
case 'complete':
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -24,6 +24,7 @@ export const AGENT_BOOTSTRAP_PROBE_COMMAND = [
|
||||
].join('; ')
|
||||
|
||||
const lifecycleActions = [
|
||||
'adopt',
|
||||
'bootstrap',
|
||||
'health',
|
||||
'status',
|
||||
@@ -48,6 +49,7 @@ export type AgentRuntimeActivationAction = {
|
||||
runtimeId: typeof RUNTIME_ID
|
||||
bundleDigest: string
|
||||
architecture: AgentRuntimeArchitecture
|
||||
forceVerification?: true
|
||||
}
|
||||
|
||||
export type FixedAgentSshAction =
|
||||
@@ -232,7 +234,10 @@ export function buildFixedAgentCliArgv(
|
||||
'--bundle-digest',
|
||||
action.bundleDigest,
|
||||
'--architecture',
|
||||
action.architecture
|
||||
action.architecture,
|
||||
...(action.forceVerification === true
|
||||
? ['--force-verification', 'true']
|
||||
: [])
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,6 @@ function createConnection(identity: SshPoolConnectionIdentity) {
|
||||
prepareRemotePackageBootstrap: vi.fn(),
|
||||
prepareUploadedRemotePackageBootstrap: vi.fn(),
|
||||
commitRemotePackageBootstrap: vi.fn(),
|
||||
getRemotePackageBootstrapCommitStatus: vi.fn(),
|
||||
cleanupRemotePackageBootstrap: vi.fn(),
|
||||
runAgentLifecycleAction: vi.fn(),
|
||||
runAgentRuntimeAction: vi.fn(),
|
||||
@@ -270,10 +269,6 @@ describe("SSH connection pool", () => {
|
||||
unavailable: false,
|
||||
reason: "size-mismatch",
|
||||
});
|
||||
connection.getRemotePackageBootstrapCommitStatus.mockResolvedValue({
|
||||
committed: false,
|
||||
reason: "operation-unavailable",
|
||||
});
|
||||
const pool = new SshConnectionPool(async () => connection);
|
||||
const lease = await pool.acquireRemotePackageBootstrap(createTarget());
|
||||
const candidate = {
|
||||
@@ -305,12 +300,6 @@ describe("SSH connection pool", () => {
|
||||
expect(
|
||||
connection.prepareUploadedRemotePackageBootstrap,
|
||||
).toHaveBeenCalledWith(candidate, undefined);
|
||||
await expect(lease.commitStatus(candidate)).resolves.toMatchObject({
|
||||
reason: "operation-unavailable",
|
||||
});
|
||||
expect(
|
||||
connection.getRemotePackageBootstrapCommitStatus,
|
||||
).toHaveBeenCalledWith(candidate, undefined);
|
||||
expect(lease).not.toHaveProperty("exec");
|
||||
expect(lease).not.toHaveProperty("sftp");
|
||||
lease.release();
|
||||
@@ -699,6 +688,10 @@ describe("authenticated ssh2 connection", () => {
|
||||
{ createClient: () => client as never },
|
||||
);
|
||||
|
||||
await expect(connection.runAgentBootstrapProbe()).resolves.toMatchObject({
|
||||
ready: true,
|
||||
architecture: "arm64",
|
||||
});
|
||||
await expect(connection.runAgentBootstrapProbe()).resolves.toMatchObject({
|
||||
ready: true,
|
||||
architecture: "arm64",
|
||||
@@ -713,6 +706,71 @@ describe("authenticated ssh2 connection", () => {
|
||||
},
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(client.exec).toHaveBeenCalledOnce();
|
||||
client.emit("close");
|
||||
await expect(connection.runAgentBootstrapProbe()).rejects.toThrow(
|
||||
"SSH 连接已关闭",
|
||||
);
|
||||
});
|
||||
|
||||
it("caches an incompatible bootstrap result on the connection", async () => {
|
||||
const channel = Object.assign(new EventEmitter(), {
|
||||
stderr: new EventEmitter(),
|
||||
destroy: vi.fn(),
|
||||
});
|
||||
const output = [
|
||||
"GOODBUDDY_AGENT_BOOTSTRAP_PROBE_V1",
|
||||
"home=/home/builder",
|
||||
"uid=1001",
|
||||
"os=Linux",
|
||||
"arch=riscv64",
|
||||
"shell=/bin/bash",
|
||||
"procfs=ready",
|
||||
"",
|
||||
].join("\n");
|
||||
const client = Object.assign(new EventEmitter(), {
|
||||
connect: vi.fn(function connect(this: EventEmitter) {
|
||||
this.emit("ready");
|
||||
}),
|
||||
end: vi.fn(),
|
||||
destroy: vi.fn(),
|
||||
exec: vi.fn(
|
||||
(
|
||||
_command: string,
|
||||
_options: unknown,
|
||||
callback: (error: Error | undefined, stream: typeof channel) => void,
|
||||
) => {
|
||||
callback(undefined, channel);
|
||||
setTimeout(() => {
|
||||
channel.emit("data", output);
|
||||
channel.emit("close", 0);
|
||||
}, 0);
|
||||
},
|
||||
),
|
||||
sftp: vi.fn(),
|
||||
});
|
||||
const target = createTarget();
|
||||
const connection = await Ssh2AuthenticatedConnection.connect(
|
||||
target,
|
||||
{
|
||||
hostId: target.host.id,
|
||||
hostRevision: target.hostRevision,
|
||||
hostKeyGeneration: target.hostKeyGeneration,
|
||||
authenticationIdentity: "a".repeat(64),
|
||||
},
|
||||
new AbortController().signal,
|
||||
{ createClient: () => client as never },
|
||||
);
|
||||
|
||||
await expect(connection.runAgentBootstrapProbe()).resolves.toEqual({
|
||||
ready: false,
|
||||
reason: "unsupported-architecture",
|
||||
});
|
||||
await expect(connection.runAgentBootstrapProbe()).resolves.toEqual({
|
||||
ready: false,
|
||||
reason: "unsupported-architecture",
|
||||
});
|
||||
expect(client.exec).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("cancels a running bootstrap probe and destroys its channel", async () => {
|
||||
|
||||
@@ -99,10 +99,6 @@ export interface AuthenticatedSshConnection {
|
||||
candidate: SshRemotePackageCandidate,
|
||||
options?: SshRemotePackageBootstrapOptions,
|
||||
): Promise<SshRemotePackageBootstrapCommitResult>;
|
||||
getRemotePackageBootstrapCommitStatus(
|
||||
candidate: SshRemotePackageCandidate,
|
||||
options?: SshRemotePackageBootstrapOptions,
|
||||
): Promise<SshRemotePackageBootstrapCommitResult>;
|
||||
cleanupRemotePackageBootstrap(
|
||||
operationId: string,
|
||||
options?: Pick<SshRemotePackageBootstrapOptions, "signal">,
|
||||
@@ -134,7 +130,6 @@ export interface SshConnectionLease extends Omit<
|
||||
| "dispose"
|
||||
| "createRemotePackageUploadStaging"
|
||||
| "prepareUploadedRemotePackageBootstrap"
|
||||
| "getRemotePackageBootstrapCommitStatus"
|
||||
> {
|
||||
release(): void;
|
||||
}
|
||||
@@ -150,7 +145,6 @@ type InternalSshConnectionLease = SshConnectionLease &
|
||||
AuthenticatedSshConnection,
|
||||
| "createRemotePackageUploadStaging"
|
||||
| "prepareUploadedRemotePackageBootstrap"
|
||||
| "getRemotePackageBootstrapCommitStatus"
|
||||
>;
|
||||
|
||||
type ClientLike = Pick<
|
||||
@@ -290,6 +284,7 @@ function waitForSharedConnection(
|
||||
export class Ssh2AuthenticatedConnection implements AuthenticatedSshConnection {
|
||||
private usable = true;
|
||||
private disposed = false;
|
||||
private agentBootstrapProbe: AgentBootstrapProbeResult | undefined;
|
||||
|
||||
private constructor(
|
||||
readonly identity: SshPoolConnectionIdentity,
|
||||
@@ -298,6 +293,7 @@ export class Ssh2AuthenticatedConnection implements AuthenticatedSshConnection {
|
||||
) {
|
||||
const disconnected = (): void => {
|
||||
this.usable = false;
|
||||
this.agentBootstrapProbe = undefined;
|
||||
};
|
||||
this.client.on("close", disconnected);
|
||||
this.client.on("end", disconnected);
|
||||
@@ -423,6 +419,11 @@ export class Ssh2AuthenticatedConnection implements AuthenticatedSshConnection {
|
||||
async runAgentBootstrapProbe(
|
||||
signal?: AbortSignal,
|
||||
): Promise<AgentBootstrapProbeResult> {
|
||||
this.assertUsable();
|
||||
signal?.throwIfAborted();
|
||||
if (this.agentBootstrapProbe !== undefined) {
|
||||
return this.agentBootstrapProbe;
|
||||
}
|
||||
const result = await this.runBoundedCommand(
|
||||
AGENT_BOOTSTRAP_PROBE_COMMAND,
|
||||
signal,
|
||||
@@ -430,7 +431,9 @@ export class Ssh2AuthenticatedConnection implements AuthenticatedSshConnection {
|
||||
if (result.exitCode !== 0 || result.stderr.length !== 0) {
|
||||
throw new Error("Agent 启动探针执行失败");
|
||||
}
|
||||
return parseAgentBootstrapProbeOutput(result.stdout);
|
||||
const probe = parseAgentBootstrapProbeOutput(result.stdout);
|
||||
this.agentBootstrapProbe = probe;
|
||||
return probe;
|
||||
}
|
||||
|
||||
probeRemotePackageBootstrap(
|
||||
@@ -471,13 +474,6 @@ export class Ssh2AuthenticatedConnection implements AuthenticatedSshConnection {
|
||||
return this.remotePackageBootstrap().commit(candidate, options);
|
||||
}
|
||||
|
||||
getRemotePackageBootstrapCommitStatus(
|
||||
candidate: SshRemotePackageCandidate,
|
||||
options?: SshRemotePackageBootstrapOptions,
|
||||
): Promise<SshRemotePackageBootstrapCommitResult> {
|
||||
return this.remotePackageBootstrap().commitStatus(candidate, options);
|
||||
}
|
||||
|
||||
cleanupRemotePackageBootstrap(
|
||||
operationId: string,
|
||||
options?: Pick<SshRemotePackageBootstrapOptions, "signal">,
|
||||
@@ -587,6 +583,7 @@ export class Ssh2AuthenticatedConnection implements AuthenticatedSshConnection {
|
||||
}
|
||||
this.disposed = true;
|
||||
this.usable = false;
|
||||
this.agentBootstrapProbe = undefined;
|
||||
this.client.end();
|
||||
this.client.destroy();
|
||||
}
|
||||
@@ -878,11 +875,6 @@ export class SshConnectionPool {
|
||||
),
|
||||
commit: (candidate, options) =>
|
||||
lease.commitRemotePackageBootstrap(candidate, options),
|
||||
commitStatus: (candidate, options) =>
|
||||
bootstrapConnection.getRemotePackageBootstrapCommitStatus(
|
||||
candidate,
|
||||
options,
|
||||
),
|
||||
cleanup: (operationId, options) =>
|
||||
lease.cleanupRemotePackageBootstrap(operationId, options),
|
||||
release: () => lease.release(),
|
||||
@@ -955,13 +947,6 @@ export class SshConnectionPool {
|
||||
assertActive();
|
||||
return connection.commitRemotePackageBootstrap(candidate, options);
|
||||
},
|
||||
getRemotePackageBootstrapCommitStatus: (candidate, options) => {
|
||||
assertActive();
|
||||
return connection.getRemotePackageBootstrapCommitStatus(
|
||||
candidate,
|
||||
options,
|
||||
);
|
||||
},
|
||||
cleanupRemotePackageBootstrap: (operationId, options) => {
|
||||
assertActive();
|
||||
return connection.cleanupRemotePackageBootstrap(operationId, options);
|
||||
|
||||
@@ -230,7 +230,6 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
await executor.prepare(candidate);
|
||||
await executor.prepareUploaded(candidate);
|
||||
await executor.commit(candidate);
|
||||
await executor.commitStatus(candidate);
|
||||
await executor.cleanup(operationId);
|
||||
|
||||
const fields = requests.map((request) => request.split("\n"));
|
||||
@@ -246,7 +245,7 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
controlPlaneInstallerSha256,
|
||||
controlPlaneInstaller.toString("base64"),
|
||||
]);
|
||||
for (const index of [4, 5, 6]) {
|
||||
for (const index of [4, 5]) {
|
||||
expect(fields[index]?.slice(5, 8)).toEqual(["0", "0".repeat(64), ""]);
|
||||
}
|
||||
expect(requests.map((request) => request.split("\n")[1])).toEqual([
|
||||
@@ -255,7 +254,6 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
"prepare",
|
||||
"prepare-uploaded",
|
||||
"commit",
|
||||
"commit-status",
|
||||
"cleanup",
|
||||
]);
|
||||
expect(fields[3]?.slice(8)).toEqual(["0", ""]);
|
||||
@@ -501,6 +499,12 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
expect(uploadedBlock).toContain('[ ! -x "$bootstrap/agent/node" ]');
|
||||
expect(uploadedBlock).toContain("run_prepare");
|
||||
expect(uploadedBlock).not.toMatch(/\b(?:curl|sha256sum|unzip)\b/u);
|
||||
expect(SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT).toContain(
|
||||
'--archive-sha256-verified true',
|
||||
);
|
||||
expect(SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT).toContain(
|
||||
'actual_sha256=$(sha256sum "$archive"',
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects empty installer terminal files for prepare and status", () => {
|
||||
@@ -508,10 +512,13 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT.match(
|
||||
/\[ "\$installer_output_size" -gt 0 \]/gu,
|
||||
),
|
||||
).toHaveLength(4);
|
||||
).toHaveLength(3);
|
||||
expect(SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT).toContain(
|
||||
'[ "$installer_output_size" -le 49152 ]',
|
||||
);
|
||||
expect(SSH_REMOTE_PACKAGE_BOOTSTRAP_SCRIPT).toContain(
|
||||
'action=commit',
|
||||
);
|
||||
});
|
||||
|
||||
it("parses bounded split NDJSON progress and a prepared result", async () => {
|
||||
@@ -677,6 +684,7 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
prepared: false,
|
||||
unavailable: false,
|
||||
reason: "installer-failed",
|
||||
detail: "archive verification failed",
|
||||
});
|
||||
|
||||
const rollbackFailure = createChannel((_payload, active) => {
|
||||
@@ -692,6 +700,7 @@ describe("fixed SSH remote package bootstrap", () => {
|
||||
).resolves.toEqual({
|
||||
committed: false,
|
||||
reason: "installer-rollback-incomplete",
|
||||
detail: "managed destination restore failed",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -46,9 +46,9 @@ const progressPhases = [
|
||||
"verifying-payload",
|
||||
"persisting-prepared-state",
|
||||
"validating-prepared-state",
|
||||
"revalidating-archive",
|
||||
"extracting-payload",
|
||||
"publishing-content",
|
||||
"publishing-metadata",
|
||||
] as const;
|
||||
|
||||
const unavailableReasons = [
|
||||
@@ -166,6 +166,7 @@ export type SshRemotePackageBootstrapPrepareResult =
|
||||
prepared: false;
|
||||
unavailable: false;
|
||||
reason: SshRemotePackageBootstrapFailureReason;
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
export type SshRemotePackageUploadStagingResult =
|
||||
@@ -195,6 +196,7 @@ export type SshRemotePackageBootstrapCommitResult =
|
||||
| {
|
||||
committed: false;
|
||||
reason: SshRemotePackageBootstrapFailureReason;
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
export type SshRemotePackageBootstrapCleanupResult =
|
||||
@@ -231,10 +233,6 @@ export interface SshRemotePackageBootstrapExecutor {
|
||||
candidate: SshRemotePackageCandidate,
|
||||
options?: SshRemotePackageBootstrapOptions,
|
||||
): Promise<SshRemotePackageBootstrapCommitResult>;
|
||||
commitStatus(
|
||||
candidate: SshRemotePackageCandidate,
|
||||
options?: SshRemotePackageBootstrapOptions,
|
||||
): Promise<SshRemotePackageBootstrapCommitResult>;
|
||||
cleanup(
|
||||
operationId: string,
|
||||
options?: Pick<SshRemotePackageBootstrapOptions, "signal">,
|
||||
@@ -268,6 +266,7 @@ type TerminalMessage =
|
||||
type: "result";
|
||||
status: "failed";
|
||||
reason: SshRemotePackageBootstrapFailureReason;
|
||||
detail?: string;
|
||||
}
|
||||
| {
|
||||
type: "result";
|
||||
@@ -467,23 +466,29 @@ if [ "$action" = prepare-status ]; then
|
||||
fi
|
||||
if [ "$action" = commit-status ]; then
|
||||
installer_output="$operation_root/installer-commit.ndjson"
|
||||
if [ ! -d "$operation_root" ] || [ -L "$operation_root" ] ||
|
||||
[ ! -f "$installer_output" ] || [ -L "$installer_output" ]; then
|
||||
stop failed operation-unavailable
|
||||
if [ -d "$operation_root" ] && [ ! -L "$operation_root" ] &&
|
||||
[ -f "$installer_output" ] && [ ! -L "$installer_output" ]; then
|
||||
installer_output_size=$(wc -c < "$installer_output" 2>/dev/null) ||
|
||||
stop failed operation-unavailable
|
||||
set -- $installer_output_size
|
||||
installer_output_size=${SHELL_FIRST_POSITIONAL_OR_EMPTY}
|
||||
case "$installer_output_size" in
|
||||
""|*[!0-9]*) stop failed operation-unavailable ;;
|
||||
esac
|
||||
[ "$installer_output_size" -le 49152 ] ||
|
||||
stop failed operation-unavailable
|
||||
terminal_line=$(tail -n 1 "$installer_output" 2>/dev/null) ||
|
||||
stop failed operation-unavailable
|
||||
if printf %s "$terminal_line" | grep '"type":"result"' >/dev/null 2>&1 ||
|
||||
printf %s "$terminal_line" | grep '"type":"error"' >/dev/null 2>&1; then
|
||||
cat -- "$installer_output" || stop failed operation-unavailable
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
installer_output_size=$(wc -c < "$installer_output" 2>/dev/null) ||
|
||||
stop failed operation-unavailable
|
||||
set -- $installer_output_size
|
||||
installer_output_size=${SHELL_FIRST_POSITIONAL_OR_EMPTY}
|
||||
case "$installer_output_size" in
|
||||
""|*[!0-9]*) stop failed operation-unavailable ;;
|
||||
esac
|
||||
[ "$installer_output_size" -gt 0 ] ||
|
||||
stop failed operation-unavailable
|
||||
[ "$installer_output_size" -le 49152 ] ||
|
||||
stop failed operation-unavailable
|
||||
cat -- "$installer_output" || stop failed operation-unavailable
|
||||
exit 0
|
||||
# A process or channel loss may leave a partial publication without a
|
||||
# terminal line. The installer commit is idempotent and completes it from
|
||||
# the authenticated prepared state.
|
||||
action=commit
|
||||
fi
|
||||
if [ "$action" = commit ]; then
|
||||
if [ ! -d "$operation_root" ] || [ -L "$operation_root" ] ||
|
||||
@@ -563,6 +568,7 @@ run_prepare() {
|
||||
"$bootstrap/agent/node" "$bootstrap/package-installer.mjs" \
|
||||
prepare --operation-root "$operation_root" --archive "$archive" \
|
||||
--expected-sha256 "$expected_sha256" \
|
||||
--archive-sha256-verified true \
|
||||
>"$installer_output" 2>/dev/null || true
|
||||
installer_output_size=$(wc -c < "$installer_output" 2>/dev/null) ||
|
||||
stop failed installer-failed
|
||||
@@ -1109,6 +1115,7 @@ function parseMessage(
|
||||
message.status === "rollback-incomplete"
|
||||
? "installer-rollback-incomplete"
|
||||
: "installer-failed",
|
||||
detail: message.message,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1444,6 +1451,9 @@ export function createSshRemotePackageBootstrapExecutor(
|
||||
prepared: false,
|
||||
unavailable: false,
|
||||
reason: result.reason,
|
||||
...(result.detail === undefined
|
||||
? {}
|
||||
: { detail: result.detail }),
|
||||
};
|
||||
}
|
||||
throw new Error("Agent 远程安装准备返回了无效结果");
|
||||
@@ -1473,7 +1483,13 @@ export function createSshRemotePackageBootstrapExecutor(
|
||||
};
|
||||
}
|
||||
if (result.status === "failed") {
|
||||
return { committed: false, reason: result.reason };
|
||||
return {
|
||||
committed: false,
|
||||
reason: result.reason,
|
||||
...(result.detail === undefined
|
||||
? {}
|
||||
: { detail: result.detail }),
|
||||
};
|
||||
}
|
||||
throw new Error("Agent 远程安装提交状态返回了无效结果");
|
||||
};
|
||||
@@ -1582,13 +1598,16 @@ export function createSshRemotePackageBootstrapExecutor(
|
||||
};
|
||||
}
|
||||
if (result.status === "failed") {
|
||||
return { committed: false, reason: result.reason };
|
||||
return {
|
||||
committed: false,
|
||||
reason: result.reason,
|
||||
...(result.detail === undefined
|
||||
? {}
|
||||
: { detail: result.detail }),
|
||||
};
|
||||
}
|
||||
throw new Error("Agent 远程安装提交返回了无效结果");
|
||||
},
|
||||
commitStatus(candidate, options = {}) {
|
||||
return readCommitStatus(candidate, options);
|
||||
},
|
||||
async cleanup(operationId, options = {}) {
|
||||
const verifiedOperationId = validateOperationId(operationId);
|
||||
const result = await runBootstrapCommand(
|
||||
|
||||
@@ -26,13 +26,17 @@ import {
|
||||
type AgentReleaseKeyRegistry
|
||||
} from '../agent-installation-contracts'
|
||||
import {
|
||||
assertDetachedRemoteRuntimeBundleDigest,
|
||||
digestRemoteRuntimeBundleIdentity,
|
||||
digestRemoteRuntimeBundleManifest,
|
||||
remoteRuntimeBundleManifestSchema,
|
||||
remoteRuntimeLockSchema,
|
||||
type RemoteRuntimeBundleManifest,
|
||||
type RemoteRuntimeLock
|
||||
} from '../remote-runtime-launch-contracts'
|
||||
import {
|
||||
runtimeRegistryEntrySchema,
|
||||
type RuntimeRegistryEntry
|
||||
} from '../remote-environment-registry-contracts'
|
||||
|
||||
export type InstalledBundleVerificationEnvironment =
|
||||
| 'production'
|
||||
@@ -63,9 +67,76 @@ export type VerifyRuntimeBundleOptions = {
|
||||
uid?: number
|
||||
}
|
||||
|
||||
export type LoadRegisteredRuntimeBundleOptions =
|
||||
VerifyRuntimeBundleOptions & {
|
||||
registered: RuntimeRegistryEntry
|
||||
}
|
||||
|
||||
export async function verifyRuntimeBundle(
|
||||
bundleDirectoryInput: string,
|
||||
options: VerifyRuntimeBundleOptions
|
||||
): Promise<VerifiedRuntimeBundle> {
|
||||
const verified = await verifyPublishedRuntimeBundle(
|
||||
bundleDirectoryInput,
|
||||
options
|
||||
)
|
||||
const { bundleDirectory, manifest } = verified
|
||||
const inventory = await inventoryBundleFiles(
|
||||
bundleDirectory,
|
||||
options.uid
|
||||
)
|
||||
const declaredPaths = new Set(
|
||||
manifest.files.map((file) => file.path)
|
||||
)
|
||||
for (const file of manifest.files) {
|
||||
const filePath = join(
|
||||
bundleDirectory,
|
||||
...file.path.split('/')
|
||||
)
|
||||
const stat = inventory.get(file.path)
|
||||
if (stat === undefined) {
|
||||
throw new Error(`Runtime payload is missing: ${file.path}`)
|
||||
}
|
||||
if (stat.size !== file.size) {
|
||||
throw new Error(`Runtime payload size mismatch: ${file.path}`)
|
||||
}
|
||||
if ((await sha256File(filePath)) !== file.sha256) {
|
||||
throw new Error(`Runtime payload hash mismatch: ${file.path}`)
|
||||
}
|
||||
if (
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(stat.mode) !== file.mode
|
||||
) {
|
||||
throw new Error(`Runtime payload mode mismatch: ${file.path}`)
|
||||
}
|
||||
}
|
||||
|
||||
const actualPaths = new Set(inventory.keys())
|
||||
const expectedPaths = new Set([
|
||||
...declaredPaths,
|
||||
MANIFEST_FILE_NAME,
|
||||
SIGNATURE_FILE_NAME
|
||||
])
|
||||
if (
|
||||
actualPaths.size !== expectedPaths.size ||
|
||||
[...actualPaths].some((path) => !expectedPaths.has(path))
|
||||
) {
|
||||
throw new Error(
|
||||
'Runtime bundle contains undeclared or missing files'
|
||||
)
|
||||
}
|
||||
|
||||
return verified
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates a package-installer-published Runtime from signed metadata and
|
||||
* bounded entrypoint metadata. The installer already hashed every payload
|
||||
* file while extracting it.
|
||||
*/
|
||||
export async function verifyPublishedRuntimeBundle(
|
||||
bundleDirectoryInput: string,
|
||||
options: VerifyRuntimeBundleOptions
|
||||
): Promise<VerifiedRuntimeBundle> {
|
||||
const bundleDirectory = assertAbsoluteManagedPath(
|
||||
resolve(bundleDirectoryInput)
|
||||
@@ -116,55 +187,35 @@ export async function verifyRuntimeBundle(
|
||||
)
|
||||
}
|
||||
|
||||
const inventory = await inventoryBundleFiles(
|
||||
bundleDirectory,
|
||||
options.uid
|
||||
const executableRecord = manifest.files.find(
|
||||
(file) => file.path === manifest.entrypoint.path
|
||||
)
|
||||
const declaredPaths = new Set(
|
||||
manifest.files.map((file) => file.path)
|
||||
)
|
||||
for (const file of manifest.files) {
|
||||
const filePath = join(
|
||||
bundleDirectory,
|
||||
...file.path.split('/')
|
||||
)
|
||||
const stat = inventory.get(file.path)
|
||||
if (stat === undefined) {
|
||||
throw new Error(`Runtime payload is missing: ${file.path}`)
|
||||
}
|
||||
if (stat.size !== file.size) {
|
||||
throw new Error(`Runtime payload size mismatch: ${file.path}`)
|
||||
}
|
||||
if ((await sha256File(filePath)) !== file.sha256) {
|
||||
throw new Error(`Runtime payload hash mismatch: ${file.path}`)
|
||||
}
|
||||
if (
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(stat.mode) !== file.mode
|
||||
) {
|
||||
throw new Error(`Runtime payload mode mismatch: ${file.path}`)
|
||||
}
|
||||
}
|
||||
|
||||
const actualPaths = new Set(inventory.keys())
|
||||
const expectedPaths = new Set([
|
||||
...declaredPaths,
|
||||
MANIFEST_FILE_NAME,
|
||||
SIGNATURE_FILE_NAME
|
||||
])
|
||||
if (
|
||||
actualPaths.size !== expectedPaths.size ||
|
||||
[...actualPaths].some((path) => !expectedPaths.has(path))
|
||||
) {
|
||||
if (executableRecord === undefined) {
|
||||
throw new Error(
|
||||
'Runtime bundle contains undeclared or missing files'
|
||||
'Published Runtime entrypoint is not declared'
|
||||
)
|
||||
}
|
||||
|
||||
const executablePath = join(
|
||||
bundleDirectory,
|
||||
...manifest.entrypoint.path.split('/')
|
||||
)
|
||||
const executableStat = await lstat(executablePath)
|
||||
assertOwnedRegularFile(
|
||||
executableStat,
|
||||
'Runtime executable',
|
||||
options.uid
|
||||
)
|
||||
if (
|
||||
executableStat.size !== executableRecord.size ||
|
||||
(
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(executableStat.mode) !== executableRecord.mode
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'Published Runtime entrypoint metadata changed'
|
||||
)
|
||||
}
|
||||
await assertElfArchitecture(
|
||||
executablePath,
|
||||
options.architecture,
|
||||
@@ -179,6 +230,44 @@ export async function verifyRuntimeBundle(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstructs a Runtime identity that was fully verified when it was
|
||||
* registered. Normal capabilities and prompt launches use this bounded
|
||||
* metadata path instead of hashing the complete Runtime payload again.
|
||||
*/
|
||||
export async function loadRegisteredRuntimeBundle(
|
||||
bundleDirectoryInput: string,
|
||||
options: LoadRegisteredRuntimeBundleOptions
|
||||
): Promise<VerifiedRuntimeBundle> {
|
||||
const registered = runtimeRegistryEntrySchema.parse(
|
||||
options.registered
|
||||
)
|
||||
const verified = await verifyPublishedRuntimeBundle(
|
||||
bundleDirectoryInput,
|
||||
options
|
||||
)
|
||||
const { manifest, manifestDigest } = verified
|
||||
if (
|
||||
manifest.runtimeId !== registered.runtimeId ||
|
||||
manifest.runtimeVersion !== registered.runtimeVersion ||
|
||||
manifest.architecture !== registered.architecture ||
|
||||
manifest.bundleDigest !== registered.bundleDigest ||
|
||||
manifestDigest !== registered.manifestDigest ||
|
||||
(
|
||||
registered.runtimeAdapterDigest !== undefined &&
|
||||
manifest.adapterDigest !== registered.runtimeAdapterDigest
|
||||
) ||
|
||||
manifest.acpCapabilitiesDigest !==
|
||||
registered.acpCapabilitiesDigest
|
||||
) {
|
||||
throw new Error(
|
||||
'Runtime manifest does not match its registered identity'
|
||||
)
|
||||
}
|
||||
|
||||
return verified
|
||||
}
|
||||
|
||||
export function canonicalRuntimeManifestBytes(
|
||||
manifest: RemoteRuntimeBundleManifest
|
||||
): Buffer {
|
||||
@@ -238,16 +327,12 @@ export async function verifyRuntimeManifestSignature(
|
||||
) {
|
||||
throw new Error('Runtime manifest signature verification failed')
|
||||
}
|
||||
await assertDetachedRemoteRuntimeBundleDigest({
|
||||
manifest,
|
||||
detachedSignature: {
|
||||
manifestDigest:
|
||||
await digestRemoteRuntimeBundleManifest(manifest),
|
||||
algorithm: 'ed25519',
|
||||
keyId: manifest.signingKeyId,
|
||||
signatureBase64: signatureBytes.toString('base64')
|
||||
}
|
||||
})
|
||||
if (
|
||||
await digestRemoteRuntimeBundleIdentity(manifest) !==
|
||||
manifest.bundleDigest
|
||||
) {
|
||||
throw new Error('Runtime bundle identity digest does not match')
|
||||
}
|
||||
return manifest
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,14 @@ export const installationRegistryEntrySchema = z
|
||||
installationId: installationRegistryIdSchema,
|
||||
agentVersion: componentVersionSchema,
|
||||
manifestSha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
arch: z.enum(['x64', 'arm64'])
|
||||
arch: z.enum(['x64', 'arm64']),
|
||||
protocol: z
|
||||
.object({
|
||||
major: z.number().int().min(0).max(65_535),
|
||||
minor: z.number().int().min(0).max(65_535)
|
||||
})
|
||||
.strict()
|
||||
.optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
@@ -137,6 +144,7 @@ export const runtimeRegistryEntrySchema = z
|
||||
architecture: z.enum(['x64', 'arm64']),
|
||||
bundleDigest: sha256DigestSchema,
|
||||
manifestDigest: sha256DigestSchema,
|
||||
runtimeAdapterDigest: sha256DigestSchema.optional(),
|
||||
acpCapabilitiesDigest: sha256DigestSchema
|
||||
})
|
||||
.strict()
|
||||
@@ -219,7 +227,10 @@ function canonicalInstallationEntry(
|
||||
installationId: entry.installationId,
|
||||
agentVersion: entry.agentVersion,
|
||||
manifestSha256: entry.manifestSha256,
|
||||
arch: entry.arch
|
||||
arch: entry.arch,
|
||||
...(entry.protocol === undefined
|
||||
? {}
|
||||
: { protocol: entry.protocol })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,6 +244,12 @@ function canonicalRuntimeEntry(
|
||||
architecture: entry.architecture,
|
||||
bundleDigest: entry.bundleDigest,
|
||||
manifestDigest: entry.manifestDigest,
|
||||
...(entry.runtimeAdapterDigest === undefined
|
||||
? {}
|
||||
: {
|
||||
runtimeAdapterDigest:
|
||||
entry.runtimeAdapterDigest
|
||||
}),
|
||||
acpCapabilitiesDigest: entry.acpCapabilitiesDigest
|
||||
})
|
||||
}
|
||||
@@ -245,6 +262,7 @@ function installationEntryEquals(
|
||||
left.installationId === right.installationId &&
|
||||
left.agentVersion === right.agentVersion &&
|
||||
left.manifestSha256 === right.manifestSha256 &&
|
||||
left.arch === right.arch
|
||||
left.arch === right.arch &&
|
||||
JSON.stringify(left.protocol) === JSON.stringify(right.protocol)
|
||||
)
|
||||
}
|
||||
|
||||
+127
-12
@@ -12,6 +12,7 @@ import {
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync
|
||||
@@ -497,7 +498,15 @@ describe('compound Agent packages', () => {
|
||||
})
|
||||
expect(events.at(-1)).toEqual(prepared)
|
||||
expect(readdirSync(join(operationRoot, 'prepared')))
|
||||
.toEqual(['result.json'])
|
||||
.toEqual([
|
||||
'agent-package.json',
|
||||
'agent-package.sig',
|
||||
'agent-release-keys.json',
|
||||
'agent-runtime-lock.json',
|
||||
'payload',
|
||||
'remote-runtime-lock.json',
|
||||
'result.json'
|
||||
])
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
|
||||
const cliOperationRoot = join(temporaryRoot, 'remote-cli-operation')
|
||||
@@ -569,13 +578,23 @@ describe('compound Agent packages', () => {
|
||||
commitEvents.filter(
|
||||
(event) =>
|
||||
event.type === 'progress' &&
|
||||
event.phase === 'extracting-payload'
|
||||
event.phase === 'publishing-content'
|
||||
)
|
||||
).toHaveLength(1)
|
||||
expect(readdirSync(join(operationRoot, 'prepared')))
|
||||
.toEqual(['result.json'])
|
||||
.toEqual([
|
||||
'agent-package.json',
|
||||
'agent-package.sig',
|
||||
'agent-release-keys.json',
|
||||
'agent-runtime-lock.json',
|
||||
'payload',
|
||||
'remote-runtime-lock.json',
|
||||
'result.json'
|
||||
])
|
||||
expect(readdirSync(operationRoot)).toEqual(['prepared'])
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
globalMetadata
|
||||
)
|
||||
|
||||
packageInstaller.preparePackage({
|
||||
operationRoot,
|
||||
@@ -591,7 +610,76 @@ describe('compound Agent packages', () => {
|
||||
homeDirectory
|
||||
})
|
||||
).not.toThrow()
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
globalMetadata
|
||||
)
|
||||
})
|
||||
|
||||
it('resumes commit after an Agent directory was already published', () => {
|
||||
const operationRoot = join(
|
||||
temporaryRoot,
|
||||
'partial-commit-operation'
|
||||
)
|
||||
const homeDirectory = join(
|
||||
temporaryRoot,
|
||||
'partial-commit-home'
|
||||
)
|
||||
const prepared = packageInstaller.preparePackage({
|
||||
operationRoot,
|
||||
archive: packagePath,
|
||||
expectedSha256: packageResult.sha256,
|
||||
homeDirectory
|
||||
})
|
||||
const agentSource = join(
|
||||
operationRoot,
|
||||
'prepared',
|
||||
'payload',
|
||||
'agent'
|
||||
)
|
||||
const agentDestination = join(
|
||||
homeDirectory,
|
||||
'.goodbuddy',
|
||||
'agent',
|
||||
'installations',
|
||||
prepared.agent.installationId
|
||||
)
|
||||
mkdirSync(dirname(agentDestination), {
|
||||
recursive: true,
|
||||
mode: 0o700
|
||||
})
|
||||
renameSync(agentSource, agentDestination)
|
||||
|
||||
expect(
|
||||
packageInstaller.commitPackage({
|
||||
operationRoot,
|
||||
archive: packagePath,
|
||||
expectedSha256: packageResult.sha256,
|
||||
homeDirectory
|
||||
})
|
||||
).toMatchObject({
|
||||
status: 'committed',
|
||||
agent: prepared.agent,
|
||||
runtime: prepared.runtime
|
||||
})
|
||||
expect(
|
||||
lstatSync(join(agentDestination, 'goodbuddy-agent'))
|
||||
.isFile()
|
||||
).toBe(true)
|
||||
expect(
|
||||
lstatSync(
|
||||
join(
|
||||
homeDirectory,
|
||||
'.goodbuddy',
|
||||
'runtimes',
|
||||
'opencode',
|
||||
prepared.runtime.bundleDigest.slice(
|
||||
'sha256:'.length
|
||||
),
|
||||
'bin',
|
||||
'opencode'
|
||||
)
|
||||
).isFile()
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('requires untampered prepared state before commit mutation', () => {
|
||||
@@ -816,7 +904,9 @@ describe('compound Agent packages', () => {
|
||||
expect(
|
||||
readFileSync(join(agentDestination, 'manifest.json'))
|
||||
).toBeTruthy()
|
||||
expectGlobalMetadataUnchanged(globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
globalMetadata
|
||||
)
|
||||
})
|
||||
|
||||
it('restores a replaced Agent directory when Runtime publication fails', () => {
|
||||
@@ -861,7 +951,7 @@ describe('compound Agent packages', () => {
|
||||
expect(readdirSync(agentDestination)).toEqual(['old-marker'])
|
||||
})
|
||||
|
||||
it('reuses only an identical trusted installed Node without changing global metadata', () => {
|
||||
it('publishes each Agent payload independently of existing installations', () => {
|
||||
const variantAgent = join(temporaryRoot, 'reuse-variant-agent')
|
||||
writeAgentBundle(variantAgent, 'x64')
|
||||
writeFileSync(
|
||||
@@ -999,7 +1089,7 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
expect(
|
||||
lstatSync(identical.currentNode).ino
|
||||
).toBe(
|
||||
).not.toBe(
|
||||
lstatSync(
|
||||
installedVariantNode(
|
||||
identical.homeDirectory,
|
||||
@@ -1007,7 +1097,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(identical.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
identical.globalMetadata
|
||||
)
|
||||
|
||||
const changed = installCurrent('changed')
|
||||
const changedResult = prepareAndCommit({
|
||||
@@ -1029,7 +1121,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(changed.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
changed.globalMetadata
|
||||
)
|
||||
|
||||
const corrupt = installCurrent('corrupt')
|
||||
writeFileSync(corrupt.currentNode, Buffer.from('corrupt Node'))
|
||||
@@ -1044,7 +1138,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(corrupt.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
corrupt.globalMetadata
|
||||
)
|
||||
|
||||
const untrusted = installCurrent('untrusted')
|
||||
const currentRoot = dirname(untrusted.currentNode)
|
||||
@@ -1063,7 +1159,9 @@ describe('compound Agent packages', () => {
|
||||
)
|
||||
).ino
|
||||
)
|
||||
expectGlobalMetadataUnchanged(untrusted.globalMetadata)
|
||||
expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
untrusted.globalMetadata
|
||||
)
|
||||
})
|
||||
|
||||
it('fails the remote installer closed on traversal, duplicates, corruption, and hash mismatch', () => {
|
||||
@@ -2285,3 +2383,20 @@ function expectGlobalMetadataUnchanged(
|
||||
expect(readFileSync(path)).toEqual(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
function expectRegistriesUnchangedAndPackageTrustPublished(
|
||||
files: ReadonlyMap<string, Buffer>
|
||||
): void {
|
||||
for (const [path, bytes] of files) {
|
||||
if (path.endsWith('registry.json')) {
|
||||
expect(readFileSync(path)).toEqual(bytes)
|
||||
continue
|
||||
}
|
||||
const actual = JSON.parse(readFileSync(path, 'utf8'))
|
||||
expect(actual).toEqual(
|
||||
path.endsWith('remote-runtime-lock.json')
|
||||
? remoteRuntimeLock
|
||||
: registry
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user