fix: make Host updates simple and fast
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
GoodBuddy Agents / Validate Agent source (push) Canceled after 0s
GoodBuddy Agents / Build Linux arm64 Agent (push) Canceled after 0s
GoodBuddy Agents / Build Linux x64 Agent (push) Canceled after 0s
GoodBuddy Agent Release / Authorize Agent release (push) Canceled after 0s
Cross-platform packages / Validate source (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux arm64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Build Linux x64 compound package (push) Canceled after 0s
GoodBuddy Agent Release / Sign cumulative Agent catalog (push) Canceled after 0s
GoodBuddy Agent Release / Publish Agent to GitHub and OSS (push) Canceled after 0s
Cross-platform packages / Authorize desktop packaging (push) Canceled after 0s
Cross-platform packages / linux arm64 (push) Canceled after 0s
Cross-platform packages / macos arm64 (push) Canceled after 0s
Cross-platform packages / windows arm64 (push) Canceled after 0s
Cross-platform packages / linux x64 (push) Canceled after 0s
Cross-platform packages / macos x64 (push) Canceled after 0s
Cross-platform packages / windows x64 (push) Canceled after 0s
Cross-platform packages / Publish GitHub and OSS release (push) Canceled after 0s
Host repair could fail while adopting the published OpenCode Runtime, then repeat package and payload verification and carry durable metadata snapshots for recovery. Host preparation now verifies each acquired compound archive once, adopts signed Agent and Runtime metadata without rereading payload trees, and retries failed work by cleaning staging and preparing fresh. The desktop and Agent versions are advanced to 0.11.9 with the approved bilingual release notes. Remote Projects remain a disabled-by-default technical preview, Agent packages remain separate Linux x64/arm64 releases, and this release has no LoongArch preview. Release note: 修复 Host 更新采用失败,移除重复远端包体校验,并将中断恢复简化为清理暂存后重新准备。
This commit is contained in:
@@ -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,287 +223,28 @@ mode.
|
||||
Release note: 修复左上角项目设置与消息通道项目设置不一致的问题;现在从任一入口修改后,另一处会同步显示相同配置。
|
||||
```
|
||||
|
||||
## Release Packaging
|
||||
## Releases
|
||||
|
||||
- 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.
|
||||
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
|
||||
|
||||
@@ -485,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,13 +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-status` 会从已认证准备状态幂等完成剩余
|
||||
rename/metadata 发布。prepare 完成后、commit 前快照 Agent/Runtime 五个 metadata 文件;任一 adoption 失败恢复
|
||||
原字节或原缺失状态,已发布 side-by-side payload 不成为 current,确认 adoption 后显式
|
||||
cleanup。Host 在 prepare 解包时完成一次完整 payload 校验;commit 只复核签名 metadata
|
||||
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 失败保留为维护重试,不回滚已健康环境。
|
||||
完整 payload。cleanup 失败不回滚已健康环境,也不阻塞下一次 fresh prepare。
|
||||
|
||||
进入“主机与远程执行”设置页只读取本地 Host 列表,不逐台连接。用户点击某台 Host 的
|
||||
“刷新版本”后才执行远端版本和直连准备能力探测。项目切换只更新本地选择,不建立 SSH
|
||||
@@ -220,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.8。
|
||||
- [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 校验。通道丢失时 `commit-status` 读取终态或从已认证准备状态幂等完成中断发布;组件 adoption 失败恢复 Agent/Runtime 五个 metadata 文件的原字节或原缺失状态,已健康环境的 cleanup 失败不触发回滚。已有项目在实际使用 Workspace/Runtime 时按需解析 Host current identity 并执行固定 `attach-or-bootstrap`,注册后的 health、capabilities 和 prompt 启动不扫描完整 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.8",
|
||||
"agentVersion": "0.11.9",
|
||||
"protocol": {
|
||||
"major": 2,
|
||||
"minor": 0
|
||||
|
||||
@@ -14,7 +14,7 @@ Main-only 模型桥、断线恢复、输出重放、同一 OpenCode Session 续
|
||||
Host 上完成 provider-free 验证。上一轮 Linux x64 验收使用 Agent `0.11.2-e2e.12` 与
|
||||
OpenCode Runtime `1.18.9` 完成了一次有界真实模型工具调用;加入每 helper 随机 loopback
|
||||
路径 capability 后,Agent `0.11.7` 已通过独立 workflow 发布 Linux x64/arm64 复合包和
|
||||
签名累计目录;当前源码准备 `0.11.8`,修复 Host 更新并消除重复 payload 验证。失败的
|
||||
签名累计目录;当前源码准备 `0.11.9`,修复 Host 更新并消除重复 payload 验证。失败的
|
||||
`agent-v0.11.3` 保持不可变且未发布。
|
||||
|
||||
## 产品语义
|
||||
@@ -108,16 +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` 读取终态,或从已认证准备状态幂等完成
|
||||
中断的目录/metadata 发布,不重新下载或准备包。prepare
|
||||
完成后、commit 前快照 Agent/Runtime 五个 metadata 文件,任一组件 adoption 失败都恢复其原字节或原缺失
|
||||
状态;已经发布的 side-by-side payload 可以保留但不能成为 current。确认 adoption 后
|
||||
才显式 cleanup;cleanup 失败只保留维护重试,不回滚健康环境。Host 在 prepare 解包时
|
||||
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 正在运行或环境健康。重新安装
|
||||
失败时明确显示本次操作未完成,并以随后重新检查的版本卡片表达当前事实;提交结果
|
||||
不确定时不声称旧版本未被替换。
|
||||
@@ -246,7 +246,7 @@ 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,因此该记录不能作为当前独立发布
|
||||
的双架构验收。Agent `0.11.7` 后续已由原生 workflow 发布并公开验证双架构工件;
|
||||
当前源码 lock 是修复候选 `0.11.8`。
|
||||
当前源码 lock 是修复候选 `0.11.9`。
|
||||
- 正常 Host 更新路径把 Linux x64 Host 的 Agent 更新为 `0.11.2-e2e.12`,并确认
|
||||
OpenCode Runtime 已安装版本与所需版本均为 `1.18.9`。
|
||||
- 一条新的 Ask 用户操作只提交一次。OpenCode 先在 build 模型轮次请求一个原生
|
||||
|
||||
@@ -152,19 +152,13 @@ daemon 参与。两种 acquisition 的差别只在于如何把同一个签名 co
|
||||
`prepare` channel 发送有界 one-shot installer 与结构化输入。
|
||||
2. Host 在解包写入准备目录的同一遍处理中校验归档大小、SHA-256、外层及内层签名、
|
||||
平台、架构、协议和每个 payload digest;不再先完整扫描 payload、再重复解包和哈希。
|
||||
3. `prepare` 完成后、`commit` 前按原字节记录 Agent 与 Runtime 的五个
|
||||
current/registry metadata 文件,
|
||||
同时记录原本缺失的状态。
|
||||
4. `commit` 只复核有界的签名 manifest、准备回执和入口 metadata,再以目录 rename 发布
|
||||
3. `commit` 只复核有界的签名 manifest、准备回执和入口 metadata,再以目录 rename 发布
|
||||
已准备内容及包内认证的公钥 registry/Runtime lock;不会重读归档或遍历 payload。
|
||||
终态先持久化到 operation staging;控制通道丢失时,同一 operation 的
|
||||
`commit-status` 读取终态,或从已认证准备状态幂等完成中断的 rename/metadata 发布。
|
||||
5. commit 后在同一条已固定身份的 SSH lease 上执行 Agent bootstrap/readiness 和 Runtime
|
||||
4. commit 后在同一条已固定身份的 SSH lease 上执行 Agent bootstrap/readiness 和 Runtime
|
||||
activate。新 Agent 最多完整验证一次,新 Runtime 最多完整验证一次;注册成功后的
|
||||
health、capabilities 和 prompt 启动只读取 registry、签名 manifest 与入口 metadata。
|
||||
adoption 失败时停止候选,并把五个 metadata 文件恢复为原字节或原缺失状态。
|
||||
6. Main 确认 adoption 后显式执行 cleanup。cleanup 失败只保留待重试的有界 operation,
|
||||
不回滚已经健康的 Agent/Runtime。
|
||||
5. Main 确认 adoption 后显式执行 cleanup。cleanup 失败不回滚已经健康的 Agent/Runtime,
|
||||
也不阻塞下一次更新。
|
||||
|
||||
这不是两个并行安装管理器,也不存在把 Agent 与 Runtime payload 逐文件走 SFTP 安装的
|
||||
第二条路径。两种 acquisition 共享相同的 prepare、commit、adoption、finalize 与 cleanup。
|
||||
@@ -194,8 +188,8 @@ Host 下载返回明确失败;本次操作不自动切换 acquisition,用户
|
||||
Runtime。
|
||||
- 每次显式安装或重装都从本次已经校验并解包的准备目录原子替换对应 Agent 与 Runtime
|
||||
digest 目录,不为节省本机磁盘写入而重新遍历旧目录,也不使用跨安装硬链接。
|
||||
- 操作响应丢失后的同 operation 重试只检查签名 manifest、registry identity 和三份小型
|
||||
trust metadata,不重新读取归档或 payload;正常 cleanup 随后删除准备目录。
|
||||
- 操作中断后不续写旧 operation。下一次更新尽力清理其 staging,并从签名候选重新
|
||||
prepare;正常 cleanup 随后删除本次准备目录。
|
||||
|
||||
只有真实包体和发布频率证明网络成本仍不可接受时,才另行设计 Agent、Node 和 Runtime
|
||||
独立签名组件目录;本功能不提前引入第二套发布协议。
|
||||
@@ -220,14 +214,11 @@ Host 下载返回明确失败;本次操作不自动切换 acquisition,用户
|
||||
|
||||
同一 Host identity 同时只允许一个由用户启动、Main-owned 的准备操作。重复观察者加入
|
||||
已有操作,不启动第二次发布;窗口关闭、显式取消、Host identity 改变或 Main 退出时执行
|
||||
有界取消。Main 在 commit 前为该 Host 持久化一个不含凭据的 pending operation 记录,
|
||||
其中包含五份有界 metadata 的原字节/原缺失快照;
|
||||
commit 指令开始后若 SSH 通道、输出或终态丢失,当前操作保留该记录和远端 staging。
|
||||
下一次重试或应用重启后的首次操作先对同一 Host identity 执行 `commit-status` 并
|
||||
恢复 adoption;恢复中的 Agent/Runtime adoption 失败仍使用该持久化快照回滚。它不会
|
||||
重新下载或准备包,也不开始第二条 acquisition。环境健康后再重试
|
||||
cleanup,确认清理后删除 pending 记录。
|
||||
取消在最终原子切换完成后不再伪装成回滚成功。
|
||||
有界取消。Main 只为该 Host 持久化一个不含凭据的 version-1 pending operation ID,用于
|
||||
下一次操作开始时尽力清理旧 staging。无论旧 cleanup 成功、目标已变化还是旧记录损坏,
|
||||
都删除这条可丢弃记录并开始 fresh prepare;不保存远端 metadata 副本,不续写旧 commit,
|
||||
也不跨重启恢复 adoption。当前操作中可确定的失败会立即尽力 cleanup。环境已健康后的
|
||||
cleanup 失败不回滚环境,也不阻塞下一次更新。
|
||||
|
||||
## 项目创建与切换
|
||||
|
||||
@@ -277,8 +268,9 @@ cleanup,确认清理后删除 pending 记录。
|
||||
这些路径不会取得安装包、发布组件或通过 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 负责解码和运行它。
|
||||
@@ -296,9 +288,8 @@ cleanup,确认清理后删除 pending 记录。
|
||||
- 如果 Host 未就绪或版本不兼容,项目仍可在本地选择,但实际远程操作失败;不再走旧的
|
||||
隐式安装。
|
||||
- 已下载或导入的本地 `.gbagent` 保持可用,不能因加入远程直连而迁移或删除。
|
||||
- `0.11.7` 遗留的 version-1 pending operation 没有持久化 metadata 快照,也没有新格式的
|
||||
已解包准备状态;`0.11.8` 只清理其暂存并重新执行一次认证 prepare,不尝试用新 installer
|
||||
续写旧 commit。
|
||||
- pending operation 保持 version 1,只记录 Host、目标 identity 与 operation ID,用于
|
||||
尽力清理旧 staging;它不是远端环境状态或恢复日志。
|
||||
- 远程直连继续使用现有 package format version 1,不要求归档携带 installer,也不要求
|
||||
目录声明额外的 bootstrap 能力元数据。
|
||||
|
||||
@@ -330,7 +321,6 @@ cleanup,确认清理后删除 pending 记录。
|
||||
仍待完成。
|
||||
12. Host 不可达或远端目录不存在时,用户仍可从项目浮动管理入口删除本地项目;删除 Host
|
||||
会列出并本地清理全部关联项目,但不会连接 Host 或删除任何远端目录和内容。
|
||||
13. commit 终态可在通道丢失后用 `commit-status` 读取,或从已认证准备状态幂等完成;
|
||||
Agent 或 Runtime
|
||||
adoption 失败恢复五个 metadata 文件的原字节/原缺失状态;已健康环境的 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.
|
||||
@@ -589,12 +589,11 @@ attach 并读取 current registry,不存在项目中的旧 Host revision 或
|
||||
- Agent 与 Runtime 各自维护版本,签名摘要标识精确工件。Host 在解包到准备目录的同一遍
|
||||
处理中完成完整 payload 校验,commit 只复核签名 metadata 并原子替换 side-by-side
|
||||
目录,不重新读取归档、扫描旧目录或使用跨安装硬链接。
|
||||
- commit 终态持久化;控制通道丢失时,`commit-status` 读取终态,或从已认证准备状态
|
||||
幂等完成中断的目录/metadata 发布,不重新下载或准备包。prepare 完成后、commit 前快照
|
||||
Agent/Runtime 五个 metadata 文件;任一组件 adoption 失败恢复原字节或原缺失状态,
|
||||
已发布 payload 不得成为 current。新 Agent/Runtime 各自最多完整验证一次;注册后的
|
||||
- Main 只保存清理 operation staging 所需的 operation ID。控制通道中断或 adoption 失败
|
||||
后,下次更新尽力清理旧暂存并重新 prepare,不保存或恢复 Agent/Runtime metadata 副本。
|
||||
新 Agent/Runtime 各自最多完整验证一次;注册后的
|
||||
health、capabilities 和 prompt 启动只检查 registry、签名 manifest 与入口 metadata。
|
||||
确认 adoption 后显式 cleanup,cleanup 失败不回滚健康环境。
|
||||
确认 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.8",
|
||||
"version": "0.11.9",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.8",
|
||||
"version": "0.11.9",
|
||||
"license": "0BSD",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "0.25.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "goodbuddy",
|
||||
"version": "0.11.8",
|
||||
"version": "0.11.9",
|
||||
"private": true,
|
||||
"description": "Secure desktop AI workspace with controlled Agent Runtimes",
|
||||
"desktopName": "GoodBuddy",
|
||||
|
||||
@@ -2,35 +2,35 @@
|
||||
"formatVersion": 1,
|
||||
"releases": [
|
||||
{
|
||||
"version": "0.11.8",
|
||||
"version": "0.11.9",
|
||||
"releasedAt": "2026-08-29",
|
||||
"notes": {
|
||||
"zh-CN": {
|
||||
"highlights": [
|
||||
"GoodBuddy 0.11.8 修复正式环境中的 Host 更新失败,并显著缩短 Agent 与 OpenCode Runtime 的安装、恢复和日常启动校验。"
|
||||
"GoodBuddy 0.11.9 修复正式环境中的 Host 更新失败,并显著缩短 Agent 与 OpenCode Runtime 的安装、恢复和日常启动校验。"
|
||||
],
|
||||
"features": [],
|
||||
"fixes": [
|
||||
"**Host 更新恢复可用。** 修复已发布 OpenCode Runtime 在采用阶段被桌面内置锁重复校验而失败的问题。Host 现在信任签名复合包中的版本锁和身份,并在同一条固定 SSH 连接上完成 Agent 启动、健康检查与 Runtime 激活。",
|
||||
"**不再重复扫描远端包体。** Host 在解包时完成完整 SHA-256 与签名校验;commit 只检查签名元数据。Main 不再通过 SFTP 逐文件读取 Agent/Runtime,后续健康检查、能力发现和每次提问只使用已登记 identity、manifest 与入口元数据。仍保留 SHA-256,提速来自消除重复读取。",
|
||||
"**中断与清理更可靠。** 中断的 commit 可从已认证准备状态继续,待恢复操作会保留五份元数据快照并在采用失败时回滚。环境已健康后,暂存清理失败只留待重试,不再错误回滚;安装错误会显示具体的有界原因。"
|
||||
"**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.8`,提供 Linux x64 和 arm64;桌面包不内置 Agent 或远程 Runtime,本次不构建 LoongArch 预览。"
|
||||
"**技术预览与版本要求。** 远程项目仍默认关闭且为技术预览。Host 需要安装单独发布的 Agent `0.11.9`,提供 Linux x64 和 arm64;桌面包不内置 Agent 或远程 Runtime,本次不构建 LoongArch 预览。"
|
||||
]
|
||||
},
|
||||
"en-US": {
|
||||
"highlights": [
|
||||
"GoodBuddy 0.11.8 fixes Host updates in production and substantially reduces Agent and OpenCode Runtime verification during installation, recovery, and normal startup."
|
||||
"GoodBuddy 0.11.9 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.** The Host completes full SHA-256 and signature verification 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.",
|
||||
"**Reliable interruption and cleanup recovery.** Interrupted commits resume from authenticated prepared state. Pending recovery keeps snapshots of all five metadata files and restores them if adoption fails. Once the environment is healthy, staging cleanup failures are retried instead of rolling it back, and bounded installer errors retain their concrete cause."
|
||||
"**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.8` for Linux x64 or arm64. Desktop packages do not embed the Agent or remote Runtime, and this release does not build a LoongArch preview."
|
||||
"**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."
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
+13
-8
@@ -31,7 +31,7 @@ import {
|
||||
loadRegisteredAgentBundle,
|
||||
readManagedAgentReleaseKeyRegistry,
|
||||
RegisteredAgentBundleError,
|
||||
verifyInstalledAgentBundle,
|
||||
verifyPublishedAgentBundle,
|
||||
type VerifiedInstalledAgentBundle
|
||||
} from './installed-bundle-verifier'
|
||||
import { InstallationRegistry } from './installation-registry'
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
import {
|
||||
loadRegisteredRuntimeBundle,
|
||||
readRemoteRuntimeLock,
|
||||
verifyRuntimeBundle,
|
||||
verifyPublishedRuntimeBundle,
|
||||
type VerifiedRuntimeBundle
|
||||
} from './runtime-bundle-verifier'
|
||||
import { createProductionRuntimeProtocol } from './runtime-composition'
|
||||
@@ -91,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
|
||||
@@ -299,7 +299,7 @@ async function runRuntime(
|
||||
const verified =
|
||||
registered === undefined || forceVerification
|
||||
? await (
|
||||
dependencies.verifyRuntime ?? verifyRuntimeBundle
|
||||
dependencies.verifyRuntime ?? verifyPublishedRuntimeBundle
|
||||
)(paths.bundleDirectory, verificationOptions)
|
||||
: await loadRegisteredRuntimeBundle(
|
||||
registered.bundleDirectory,
|
||||
@@ -524,10 +524,11 @@ async function runLifecycle(
|
||||
paths,
|
||||
dependencies
|
||||
)
|
||||
const alreadyCurrent =
|
||||
const currentInstallationMatches =
|
||||
registry.snapshot().current?.installationId ===
|
||||
installationId
|
||||
if (!alreadyCurrent) {
|
||||
const alreadyCurrent = registry.isCurrent(verified)
|
||||
if (!alreadyCurrent && !currentInstallationMatches) {
|
||||
registry.stageCandidate(verified)
|
||||
}
|
||||
prepareManagedSocketDirectory(paths)
|
||||
@@ -539,7 +540,11 @@ async function runLifecycle(
|
||||
verified
|
||||
).bootstrap()
|
||||
if (!alreadyCurrent) {
|
||||
registry.promoteCandidate(installationId)
|
||||
if (currentInstallationMatches) {
|
||||
registry.refreshCurrent(verified)
|
||||
} else {
|
||||
registry.promoteCandidate(installationId)
|
||||
}
|
||||
}
|
||||
io.output.write(`${JSON.stringify(status)}\n`)
|
||||
break
|
||||
@@ -757,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'))
|
||||
|
||||
@@ -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')[]
|
||||
@@ -234,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()
|
||||
@@ -134,6 +135,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 +290,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}`
|
||||
@@ -326,19 +347,9 @@ async function loadRegisteredAgentBundleUnchecked(
|
||||
)
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -500,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(
|
||||
|
||||
@@ -283,8 +283,8 @@ async function loadVerifiedRuntimeCapabilities(
|
||||
entry.runtimeId,
|
||||
entry.bundleDigest
|
||||
)
|
||||
const verified = options.loadRegistered === undefined
|
||||
? await loadRegisteredRuntimeBundle(
|
||||
await (options.loadRegistered === undefined
|
||||
? loadRegisteredRuntimeBundle(
|
||||
bundleDirectory,
|
||||
{
|
||||
registered: entry,
|
||||
@@ -315,21 +315,10 @@ async function loadVerifiedRuntimeCapabilities(
|
||||
: { uid: options.uid })
|
||||
}
|
||||
)
|
||||
: await options.loadRegistered(
|
||||
: options.loadRegistered(
|
||||
entry,
|
||||
bundleDirectory
|
||||
)
|
||||
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'
|
||||
)
|
||||
}
|
||||
))
|
||||
capabilities.push({
|
||||
runtimeId: entry.runtimeId,
|
||||
version: entry.runtimeVersion,
|
||||
|
||||
@@ -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
|
||||
@@ -216,6 +219,45 @@ describe('Remote Runtime bundle verifier', () => {
|
||||
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(
|
||||
|
||||
@@ -3,6 +3,7 @@ export {
|
||||
loadRegisteredRuntimeBundle,
|
||||
readRemoteRuntimeLock,
|
||||
runtimeManifestSignaturePayload,
|
||||
verifyPublishedRuntimeBundle,
|
||||
verifyRuntimeBundle,
|
||||
verifyRuntimeManifestSignature
|
||||
} from '../shared/node/runtime-bundle-verifier'
|
||||
|
||||
@@ -240,20 +240,10 @@ export async function createProductionRuntimeProtocol(
|
||||
options.architecture
|
||||
),
|
||||
loadRegisteredRuntimeBundle: async (resolved) => {
|
||||
const verified = await loadRegistered(
|
||||
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(
|
||||
|
||||
@@ -25,7 +25,6 @@ import { HostActivationCoordinator } from './host-activation-coordinator'
|
||||
import { isMissingPathError } from './path-errors'
|
||||
import { remoteHostTargetIdentityKey } from './remote-host-target-identity'
|
||||
|
||||
const PRIVATE_FILE_MODE = 0o600
|
||||
const MAXIMUM_METADATA_BYTES = 1024 * 1024
|
||||
const AGENT_REGISTRY_PATH = '.goodbuddy/agent/registry.json'
|
||||
const MAXIMUM_DIAGNOSTIC_CHARACTERS = 800
|
||||
@@ -192,19 +191,6 @@ export class AgentInstallationManager {
|
||||
},
|
||||
signal
|
||||
)
|
||||
const metadata = await sftp.lstat(
|
||||
AGENT_REGISTRY_PATH,
|
||||
signal
|
||||
)
|
||||
if (
|
||||
metadata.type !== 'file' ||
|
||||
metadata.uid !== probe.uid ||
|
||||
metadata.mode !== PRIVATE_FILE_MODE
|
||||
) {
|
||||
throw new Error(
|
||||
'Installed Agent registry metadata is invalid'
|
||||
)
|
||||
}
|
||||
const registry = parseInstallationRegistryState(
|
||||
parseJsonBytes(
|
||||
await sftp.readFile(AGENT_REGISTRY_PATH, signal),
|
||||
|
||||
@@ -142,6 +142,8 @@ type InstallerOptions = {
|
||||
operationRoot: string
|
||||
archive: string
|
||||
expectedSha256: string
|
||||
/** The acquisition path verified the archive before installer execution. */
|
||||
archiveSha256Verified?: boolean
|
||||
homeDirectory?: string
|
||||
emit?: (event: PackageInstallerEvent) => void
|
||||
}
|
||||
@@ -1361,6 +1363,7 @@ function sameSnapshot(
|
||||
function verifyArchive(
|
||||
archivePath: string,
|
||||
expectedSha256: string,
|
||||
archiveSha256Verified: boolean,
|
||||
emit: (phase: string) => void
|
||||
): VerifiedPackage {
|
||||
const handle = openSync(
|
||||
@@ -1376,11 +1379,14 @@ function verifyArchive(
|
||||
) {
|
||||
throw new Error('Agent package archive is not a bounded regular file')
|
||||
}
|
||||
emit('hashing-archive')
|
||||
const archiveSha256 = hashArchive(handle, snapshot.size)
|
||||
if (archiveSha256 !== expectedSha256) {
|
||||
throw new Error('Agent package archive SHA-256 does not match the authenticated catalog')
|
||||
if (!archiveSha256Verified) {
|
||||
emit('hashing-archive')
|
||||
const archiveSha256 = hashArchive(handle, snapshot.size)
|
||||
if (archiveSha256 !== expectedSha256) {
|
||||
throw new Error('Agent package archive SHA-256 does not match the authenticated catalog')
|
||||
}
|
||||
}
|
||||
const archiveSha256 = expectedSha256
|
||||
emit('verifying-zip')
|
||||
const entries = parseZip(handle, snapshot.size)
|
||||
const descriptorBytes = readEntry(handle, entries, PACKAGE_DESCRIPTOR)
|
||||
@@ -1637,28 +1643,7 @@ function persistPreparedState(
|
||||
if (bytes.length > MAXIMUM_METADATA_BYTES) {
|
||||
throw new Error('Prepared package state exceeds its limit')
|
||||
}
|
||||
const handle = openSync(
|
||||
temporary,
|
||||
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,
|
||||
0o600
|
||||
)
|
||||
try {
|
||||
let offset = 0
|
||||
while (offset < bytes.length) {
|
||||
offset += writeFileChunk(handle, bytes, offset)
|
||||
}
|
||||
fsyncSync(handle)
|
||||
} finally {
|
||||
closeSync(handle)
|
||||
}
|
||||
try {
|
||||
chmodSync(temporary, 0o600)
|
||||
renameSync(temporary, destination)
|
||||
} finally {
|
||||
if (existsSync(temporary)) {
|
||||
unlinkSync(temporary)
|
||||
}
|
||||
}
|
||||
writeBufferAtomically(destination, temporary, bytes)
|
||||
}
|
||||
|
||||
function writePreparedFile(
|
||||
@@ -1677,6 +1662,15 @@ function writePreparedFile(
|
||||
directory,
|
||||
`.${name}-${process.pid}-${Date.now().toString(36)}.tmp`
|
||||
)
|
||||
writeBufferAtomically(destination, temporary, bytes)
|
||||
}
|
||||
|
||||
function writeBufferAtomically(
|
||||
destination: string,
|
||||
temporary: string,
|
||||
bytes: Buffer,
|
||||
replaceExistingOnWindows = false
|
||||
): void {
|
||||
const handle = openSync(
|
||||
temporary,
|
||||
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,
|
||||
@@ -1693,6 +1687,13 @@ function writePreparedFile(
|
||||
}
|
||||
try {
|
||||
chmodSync(temporary, 0o600)
|
||||
if (
|
||||
replaceExistingOnWindows &&
|
||||
process.platform === 'win32' &&
|
||||
existsSync(destination)
|
||||
) {
|
||||
unlinkSync(destination)
|
||||
}
|
||||
renameSync(temporary, destination)
|
||||
} finally {
|
||||
if (existsSync(temporary)) {
|
||||
@@ -1808,6 +1809,7 @@ export function preparePackage(options: InstallerOptions): PackageInstallerResul
|
||||
const verified = verifyArchive(
|
||||
inputs.archive,
|
||||
inputs.expectedSha256,
|
||||
options.archiveSha256Verified === true,
|
||||
progress
|
||||
)
|
||||
try {
|
||||
@@ -1940,31 +1942,12 @@ function writePrivateFileAtomic(
|
||||
dirname(destination),
|
||||
`.${basename(destination)}-${process.pid}-${Date.now().toString(36)}.tmp`
|
||||
)
|
||||
const handle = openSync(
|
||||
writeBufferAtomically(
|
||||
destination,
|
||||
temporary,
|
||||
constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,
|
||||
0o600
|
||||
contents,
|
||||
true
|
||||
)
|
||||
try {
|
||||
let offset = 0
|
||||
while (offset < contents.length) {
|
||||
offset += writeFileChunk(handle, contents, offset)
|
||||
}
|
||||
fsyncSync(handle)
|
||||
} finally {
|
||||
closeSync(handle)
|
||||
}
|
||||
try {
|
||||
chmodSync(temporary, 0o600)
|
||||
if (process.platform === 'win32' && existsSync(destination)) {
|
||||
unlinkSync(destination)
|
||||
}
|
||||
renameSync(temporary, destination)
|
||||
} finally {
|
||||
if (existsSync(temporary)) {
|
||||
unlinkSync(temporary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function restoreLocalMetadata(
|
||||
@@ -2571,14 +2554,18 @@ function parseCli(argv: readonly string[]): {
|
||||
const command = argv[0]
|
||||
if (command !== 'prepare' && command !== 'commit') {
|
||||
throw new Error(
|
||||
'Usage: remote-package-installer.mjs <prepare|commit> --operation-root <absolute-path> --archive <absolute-path> --expected-sha256 <hex>'
|
||||
'Usage: remote-package-installer.mjs <prepare|commit> --operation-root <absolute-path> --archive <absolute-path> --expected-sha256 <hex> [--archive-sha256-verified true]'
|
||||
)
|
||||
}
|
||||
const values: Record<string, string> = {}
|
||||
const allowed = new Set([
|
||||
const required = [
|
||||
'--operation-root',
|
||||
'--archive',
|
||||
'--expected-sha256'
|
||||
] as const
|
||||
const allowed = new Set([
|
||||
...required,
|
||||
'--archive-sha256-verified'
|
||||
])
|
||||
for (let index = 1; index < argv.length; index += 2) {
|
||||
const flag = argv[index]
|
||||
@@ -2594,17 +2581,25 @@ function parseCli(argv: readonly string[]): {
|
||||
}
|
||||
values[flag] = value
|
||||
}
|
||||
for (const flag of allowed) {
|
||||
for (const flag of required) {
|
||||
if (values[flag] === undefined) {
|
||||
throw new Error(`Missing required package installer argument: ${flag}`)
|
||||
}
|
||||
}
|
||||
if (
|
||||
values['--archive-sha256-verified'] !== undefined &&
|
||||
values['--archive-sha256-verified'] !== 'true'
|
||||
) {
|
||||
throw new Error('Invalid package installer argument')
|
||||
}
|
||||
return {
|
||||
command,
|
||||
options: {
|
||||
operationRoot: values['--operation-root']!,
|
||||
archive: values['--archive']!,
|
||||
expectedSha256: values['--expected-sha256']!
|
||||
expectedSha256: values['--expected-sha256']!,
|
||||
archiveSha256Verified:
|
||||
values['--archive-sha256-verified'] === 'true'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 () => {
|
||||
@@ -42,39 +39,6 @@ describe('RemoteEnvironmentOperationStore', () => {
|
||||
await expect(store.load(operation.hostId)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('persists bounded metadata snapshots for post-commit recovery', async () => {
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), 'goodbuddy-environment-operation-')
|
||||
)
|
||||
temporaryDirectories.push(root)
|
||||
const store = new RemoteEnvironmentOperationStore(root)
|
||||
const recovered: PendingRemoteEnvironmentOperation = {
|
||||
...operation,
|
||||
version: 2,
|
||||
metadataSnapshots: [
|
||||
'.goodbuddy/agent/release-keys.json',
|
||||
'.goodbuddy/agent/registry.json',
|
||||
'.goodbuddy/runtimes/release-keys.json',
|
||||
'.goodbuddy/runtimes/remote-runtime-lock.json',
|
||||
'.goodbuddy/runtimes/registry.json'
|
||||
].map((path, index) => ({
|
||||
path: path as never,
|
||||
uid: 1000,
|
||||
...(index === 1
|
||||
? {}
|
||||
: {
|
||||
contentsBase64:
|
||||
Buffer.from(`metadata-${index}`).toString('base64')
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
await store.save(recovered)
|
||||
await expect(store.load(operation.hostId)).resolves.toEqual(
|
||||
recovered
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a mismatched or oversized recovery record', async () => {
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), 'goodbuddy-environment-operation-')
|
||||
@@ -91,7 +55,7 @@ describe('RemoteEnvironmentOperationStore', () => {
|
||||
const [record] = await readdir(files)
|
||||
await writeFile(
|
||||
join(files, record!),
|
||||
Buffer.alloc(8 * 1024 * 1024 + 1)
|
||||
Buffer.alloc(4 * 1024 + 1)
|
||||
)
|
||||
|
||||
await expect(store.load(operation.hostId)).rejects.toThrow(
|
||||
|
||||
@@ -6,42 +6,18 @@ import {
|
||||
writeJsonFileAtomically
|
||||
} from '../settings-file-utils'
|
||||
|
||||
const MAXIMUM_RECORD_BYTES = 8 * 1024 * 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
|
||||
|
||||
type PendingRemoteEnvironmentOperationBase = {
|
||||
export type PendingRemoteEnvironmentOperation = {
|
||||
version: 1
|
||||
hostId: string
|
||||
targetIdentity: string
|
||||
operationId: string
|
||||
size: number
|
||||
sha256: string
|
||||
urls: readonly string[]
|
||||
}
|
||||
|
||||
export type PersistedRemoteEnvironmentMetadataSnapshot = {
|
||||
path:
|
||||
| '.goodbuddy/agent/release-keys.json'
|
||||
| '.goodbuddy/agent/registry.json'
|
||||
| '.goodbuddy/runtimes/release-keys.json'
|
||||
| '.goodbuddy/runtimes/remote-runtime-lock.json'
|
||||
| '.goodbuddy/runtimes/registry.json'
|
||||
contentsBase64?: string
|
||||
uid: number
|
||||
}
|
||||
|
||||
export type PendingRemoteEnvironmentOperation =
|
||||
PendingRemoteEnvironmentOperationBase &
|
||||
(
|
||||
| { version: 1 }
|
||||
| {
|
||||
version: 2
|
||||
metadataSnapshots:
|
||||
readonly PersistedRemoteEnvironmentMetadataSnapshot[]
|
||||
}
|
||||
)
|
||||
|
||||
export class RemoteEnvironmentOperationStore {
|
||||
readonly #directory: string
|
||||
|
||||
@@ -116,27 +92,12 @@ function parsePendingOperation(
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const record = value as Record<string, unknown>
|
||||
const version = record.version
|
||||
const expectedKeys = version === 2
|
||||
? [
|
||||
'hostId',
|
||||
'metadataSnapshots',
|
||||
'operationId',
|
||||
'sha256',
|
||||
'size',
|
||||
'targetIdentity',
|
||||
'urls',
|
||||
'version'
|
||||
]
|
||||
: [
|
||||
'hostId',
|
||||
'operationId',
|
||||
'sha256',
|
||||
'size',
|
||||
'targetIdentity',
|
||||
'urls',
|
||||
'version'
|
||||
]
|
||||
const expectedKeys = [
|
||||
'hostId',
|
||||
'operationId',
|
||||
'targetIdentity',
|
||||
'version'
|
||||
]
|
||||
if (
|
||||
Object.keys(value).sort().join('\0') !==
|
||||
expectedKeys.sort().join('\0')
|
||||
@@ -144,128 +105,19 @@ function parsePendingOperation(
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
if (
|
||||
(version !== 1 && version !== 2) ||
|
||||
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('远程环境恢复记录无效')
|
||||
}
|
||||
const base: PendingRemoteEnvironmentOperationBase = {
|
||||
hostId: expectedHostId,
|
||||
targetIdentity: record.targetIdentity,
|
||||
operationId: record.operationId,
|
||||
size: Number(record.size),
|
||||
sha256: record.sha256,
|
||||
urls: [...record.urls] as string[]
|
||||
}
|
||||
if (version === 1) {
|
||||
return { version: 1, ...base }
|
||||
}
|
||||
return {
|
||||
version: 2,
|
||||
...base,
|
||||
metadataSnapshots: parseMetadataSnapshots(
|
||||
record.metadataSnapshots
|
||||
)
|
||||
version: 1,
|
||||
hostId: expectedHostId,
|
||||
targetIdentity: record.targetIdentity,
|
||||
operationId: record.operationId
|
||||
}
|
||||
}
|
||||
|
||||
const metadataPaths =
|
||||
new Set<PersistedRemoteEnvironmentMetadataSnapshot['path']>([
|
||||
'.goodbuddy/agent/release-keys.json',
|
||||
'.goodbuddy/agent/registry.json',
|
||||
'.goodbuddy/runtimes/release-keys.json',
|
||||
'.goodbuddy/runtimes/remote-runtime-lock.json',
|
||||
'.goodbuddy/runtimes/registry.json'
|
||||
])
|
||||
|
||||
function parseMetadataSnapshots(
|
||||
value: unknown
|
||||
): readonly PersistedRemoteEnvironmentMetadataSnapshot[] {
|
||||
if (!Array.isArray(value) || value.length !== metadataPaths.size) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const paths = new Set<string>()
|
||||
let totalBytes = 0
|
||||
const snapshots = value.map((item) => {
|
||||
if (
|
||||
typeof item !== 'object' ||
|
||||
item === null ||
|
||||
!(
|
||||
Object.keys(item).sort().join('\0') ===
|
||||
['path', 'uid'].sort().join('\0') ||
|
||||
Object.keys(item).sort().join('\0') ===
|
||||
['contentsBase64', 'path', 'uid'].sort().join('\0')
|
||||
)
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const snapshot = item as Record<string, unknown>
|
||||
if (
|
||||
typeof snapshot.path !== 'string' ||
|
||||
!metadataPaths.has(
|
||||
snapshot.path as PersistedRemoteEnvironmentMetadataSnapshot['path']
|
||||
) ||
|
||||
paths.has(snapshot.path) ||
|
||||
!Number.isSafeInteger(snapshot.uid) ||
|
||||
Number(snapshot.uid) < 0
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
paths.add(snapshot.path)
|
||||
if (snapshot.contentsBase64 === undefined) {
|
||||
return {
|
||||
path:
|
||||
snapshot.path as PersistedRemoteEnvironmentMetadataSnapshot['path'],
|
||||
uid: Number(snapshot.uid)
|
||||
}
|
||||
}
|
||||
if (
|
||||
typeof snapshot.contentsBase64 !== 'string' ||
|
||||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u
|
||||
.test(snapshot.contentsBase64)
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
const contents = Buffer.from(
|
||||
snapshot.contentsBase64,
|
||||
'base64'
|
||||
)
|
||||
if (
|
||||
contents.toString('base64') !==
|
||||
snapshot.contentsBase64 ||
|
||||
contents.byteLength > 1024 * 1024
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
totalBytes += contents.byteLength
|
||||
return {
|
||||
path:
|
||||
snapshot.path as PersistedRemoteEnvironmentMetadataSnapshot['path'],
|
||||
contentsBase64: snapshot.contentsBase64,
|
||||
uid: Number(snapshot.uid)
|
||||
}
|
||||
})
|
||||
if (
|
||||
paths.size !== metadataPaths.size ||
|
||||
[...metadataPaths].some((path) => !paths.has(path)) ||
|
||||
totalBytes > 5 * 1024 * 1024
|
||||
) {
|
||||
throw new Error('远程环境恢复记录无效')
|
||||
}
|
||||
return snapshots
|
||||
}
|
||||
|
||||
@@ -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,72 +98,13 @@ type FixtureOptions = {
|
||||
prepare?: ReturnType<typeof vi.fn>
|
||||
prepareUploaded?: ReturnType<typeof vi.fn>
|
||||
commit?: ReturnType<typeof vi.fn>
|
||||
commitStatus?: 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()]
|
||||
@@ -182,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
|
||||
) => {
|
||||
@@ -202,14 +135,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
close: vi.fn(() => calls.push('close-upload'))
|
||||
}
|
||||
const regularRelease = vi.fn(() => calls.push('release-probe'))
|
||||
const stopCandidate = vi.fn(async (
|
||||
_installationId?: string,
|
||||
_action?: string
|
||||
) => {
|
||||
void _installationId
|
||||
void _action
|
||||
calls.push('stop-candidate')
|
||||
})
|
||||
const activateAgent = options.activateAgent ?? vi.fn(async () => {
|
||||
calls.push('agent')
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
@@ -233,27 +158,17 @@ 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: vi.fn(async (
|
||||
installationId: string,
|
||||
action: string
|
||||
) => {
|
||||
if (action === 'stop') {
|
||||
await stopCandidate(installationId, action)
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}
|
||||
return (activateAgent as (
|
||||
) => (activateAgent as (
|
||||
installationId: string,
|
||||
action: string
|
||||
) => Promise<unknown>)(installationId, action)
|
||||
}),
|
||||
) => Promise<unknown>)(installationId, action)),
|
||||
runAgentRuntimeAction: vi.fn(async (
|
||||
installationId: string,
|
||||
action: unknown
|
||||
@@ -302,13 +217,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
calls.push('cleanup')
|
||||
return { cleaned: true, operationId }
|
||||
})
|
||||
const commitStatus = options.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')
|
||||
@@ -337,7 +245,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
prepare,
|
||||
prepareUploaded,
|
||||
commit,
|
||||
commitStatus,
|
||||
cleanup,
|
||||
release: bootstrapRelease
|
||||
}
|
||||
@@ -402,8 +309,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
resolver,
|
||||
regularLease,
|
||||
bootstrapLease,
|
||||
metadata,
|
||||
metadataFiles,
|
||||
uploadFile,
|
||||
probe,
|
||||
createUploadStaging,
|
||||
@@ -417,8 +322,6 @@ function fixture(options: FixtureOptions = {}) {
|
||||
archiveRelease,
|
||||
regularRelease,
|
||||
bootstrapRelease,
|
||||
stopCandidate,
|
||||
commitStatus,
|
||||
operationStore
|
||||
}
|
||||
}
|
||||
@@ -445,15 +348,12 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
'acquire-bootstrap',
|
||||
'save-operation',
|
||||
'prepare',
|
||||
'open-metadata',
|
||||
'save-operation',
|
||||
'resolve',
|
||||
'commit',
|
||||
'agent',
|
||||
'runtime',
|
||||
'cleanup',
|
||||
'remove-operation',
|
||||
'close-metadata',
|
||||
'release-bootstrap',
|
||||
'release-probe'
|
||||
])
|
||||
@@ -483,7 +383,7 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
remoteCandidate.operationId,
|
||||
{ signal: controller.signal }
|
||||
)
|
||||
expect(value.operationStore.save).toHaveBeenCalledTimes(2)
|
||||
expect(value.operationStore.save).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
expect(progress.some((event) =>
|
||||
event.method === 'remote-download' &&
|
||||
@@ -532,7 +432,6 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
)).resolves.toBeUndefined()
|
||||
expect(value.activateAgent).toHaveBeenCalledOnce()
|
||||
expect(value.activateRuntime).toHaveBeenCalledOnce()
|
||||
expect(value.stopCandidate).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -725,13 +624,13 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
new AbortController().signal
|
||||
)).rejects.toBeInstanceOf(SshRemotePackageCommitIndeterminateError)
|
||||
expect(value.cleanup).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.save).toHaveBeenCalledTimes(2)
|
||||
expect(value.operationStore.save).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
expect(value.activateAgent).not.toHaveBeenCalled()
|
||||
expect(value.activateRuntime).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rolls metadata back when cancellation arrives with a successful commit result', async () => {
|
||||
it('cleans staging when cancellation arrives with a successful commit result', async () => {
|
||||
const controller = new AbortController()
|
||||
const cancellation =
|
||||
new DOMException('cancelled after commit', 'AbortError')
|
||||
@@ -752,7 +651,6 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
undefined,
|
||||
controller.signal
|
||||
)).rejects.toBe(cancellation)
|
||||
expect(value.stopCandidate).toHaveBeenCalledOnce()
|
||||
expect(value.cleanup).toHaveBeenCalledOnce()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
expect(value.activateAgent).not.toHaveBeenCalled()
|
||||
@@ -778,61 +676,7 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resumes adoption for a committed operation instead of reinstalling it', async () => {
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000777'
|
||||
const originalTarget = target()
|
||||
const renamedTarget = target({
|
||||
host: {
|
||||
...originalTarget.host,
|
||||
name: 'Renamed builder'
|
||||
},
|
||||
hostRevision: 99
|
||||
})
|
||||
const value = fixture({
|
||||
targets: [renamedTarget],
|
||||
pendingOperation: {
|
||||
version: 2,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId: pendingOperationId,
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls,
|
||||
metadataSnapshots:
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path) => ({
|
||||
path,
|
||||
uid: 1000
|
||||
})
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
await value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)
|
||||
|
||||
expect(value.commitStatus).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
operationId: pendingOperationId
|
||||
}),
|
||||
expect.any(Object)
|
||||
)
|
||||
expect(value.cleanup.mock.calls[0]?.[0]).toBe(
|
||||
pendingOperationId
|
||||
)
|
||||
expect(value.activateAgent).toHaveBeenCalledOnce()
|
||||
expect(value.activateRuntime).toHaveBeenCalledOnce()
|
||||
expect(value.prepare).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.remove).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('cleans a legacy pending operation and starts a fresh authenticated prepare', async () => {
|
||||
it('cleans pending staging and starts a fresh authenticated prepare', async () => {
|
||||
const originalTarget = target()
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000780'
|
||||
@@ -843,10 +687,7 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId: pendingOperationId,
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls
|
||||
operationId: pendingOperationId
|
||||
}
|
||||
})
|
||||
|
||||
@@ -857,7 +698,6 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
new AbortController().signal
|
||||
)
|
||||
|
||||
expect(value.commitStatus).not.toHaveBeenCalled()
|
||||
expect(value.cleanup.mock.calls[0]?.[0]).toBe(
|
||||
pendingOperationId
|
||||
)
|
||||
@@ -865,104 +705,30 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
expect(value.operationStore.remove).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('restores the durable snapshot when resumed commit does not complete', async () => {
|
||||
it('does not block a fresh prepare when stale staging cleanup fails', async () => {
|
||||
const originalTarget = target()
|
||||
const originals = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path, index) => [
|
||||
path,
|
||||
Buffer.from(`before-commit-${index}`)
|
||||
]
|
||||
)
|
||||
)
|
||||
const files = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path) => [path, Buffer.from('partial-commit')]
|
||||
)
|
||||
)
|
||||
let cleanupCalls = 0
|
||||
const value = fixture({
|
||||
targets: [originalTarget],
|
||||
metadataFiles: files,
|
||||
pendingOperation: {
|
||||
version: 2,
|
||||
version: 1,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId:
|
||||
'00000000-0000-4000-8000-000000000781',
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls,
|
||||
metadataSnapshots: [...originals].map(
|
||||
([path, contents]) => ({
|
||||
path: path as never,
|
||||
uid: 1000,
|
||||
contentsBase64: contents.toString('base64')
|
||||
})
|
||||
)
|
||||
'00000000-0000-4000-8000-000000000779'
|
||||
},
|
||||
commitStatus: vi.fn(async () => ({
|
||||
committed: false,
|
||||
reason: 'installer-failed'
|
||||
}))
|
||||
})
|
||||
|
||||
await value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)
|
||||
|
||||
expect([...files]).toEqual([...originals])
|
||||
expect(value.prepare).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('restores persisted pre-commit metadata when resumed Runtime adoption fails', async () => {
|
||||
const originalTarget = target()
|
||||
const originals = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path, index) => [
|
||||
path,
|
||||
Buffer.from(`original-${index}`)
|
||||
]
|
||||
)
|
||||
)
|
||||
const files = new Map<string, Buffer>(
|
||||
REMOTE_ENVIRONMENT_METADATA_PATHS.map(
|
||||
(path) => [path, Buffer.from('published')]
|
||||
)
|
||||
)
|
||||
const runtimeFailure = new Error('runtime recovery failed')
|
||||
const value = fixture({
|
||||
targets: [originalTarget],
|
||||
metadataFiles: files,
|
||||
pendingOperation: {
|
||||
version: 2,
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId:
|
||||
'00000000-0000-4000-8000-000000000779',
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls,
|
||||
metadataSnapshots: [...originals].map(
|
||||
([path, contents]) => ({
|
||||
path: path as never,
|
||||
uid: 1000,
|
||||
contentsBase64: contents.toString('base64')
|
||||
})
|
||||
)
|
||||
},
|
||||
activateAgent: vi.fn(async () => {
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
files.set(path, Buffer.from('adopting'))
|
||||
}
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}),
|
||||
activateRuntime: vi.fn(async () => {
|
||||
throw runtimeFailure
|
||||
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
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -971,14 +737,14 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)).rejects.toThrow('runtime recovery failed')
|
||||
expect([...files]).toEqual([...originals])
|
||||
expect(value.stopCandidate).toHaveBeenCalledOnce()
|
||||
expect(value.cleanup).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('retains pending recovery evidence when the real SSH target changes', async () => {
|
||||
it('drops stale cleanup state when the SSH target changed and starts fresh', async () => {
|
||||
const originalTarget = target()
|
||||
const changedTarget = target({
|
||||
host: {
|
||||
@@ -986,6 +752,8 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
hostname: 'different.example'
|
||||
}
|
||||
})
|
||||
const pendingOperationId =
|
||||
'00000000-0000-4000-8000-000000000778'
|
||||
const value = fixture({
|
||||
targets: [changedTarget],
|
||||
pendingOperation: {
|
||||
@@ -993,45 +761,27 @@ describe('RemoteEnvironmentPreparer', () => {
|
||||
hostId: HOST_ID,
|
||||
targetIdentity:
|
||||
remoteHostRecoveryIdentityKey(originalTarget),
|
||||
operationId:
|
||||
'00000000-0000-4000-8000-000000000778',
|
||||
size: candidate.size,
|
||||
sha256: candidate.sha256,
|
||||
urls: candidate.urls
|
||||
operationId: pendingOperationId
|
||||
}
|
||||
})
|
||||
|
||||
await expect(value.preparer.prepare(
|
||||
await value.preparer.prepare(
|
||||
HOST_ID,
|
||||
'remote-download',
|
||||
undefined,
|
||||
new AbortController().signal
|
||||
)).rejects.toBeInstanceOf(
|
||||
SshRemotePackageCommitIndeterminateError
|
||||
)
|
||||
expect(value.commitStatus).not.toHaveBeenCalled()
|
||||
expect(value.operationStore.remove).not.toHaveBeenCalled()
|
||||
|
||||
expect(value.prepare).toHaveBeenCalledOnce()
|
||||
expect(value.cleanup.mock.calls.some(
|
||||
(call) => call[0] === pendingOperationId
|
||||
)).toBe(false)
|
||||
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)])
|
||||
)
|
||||
const runtimeFailure = new Error('runtime health failed')
|
||||
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.calls.push('agent')
|
||||
value.metadataFiles.clear()
|
||||
for (const path of REMOTE_ENVIRONMENT_METADATA_PATHS) {
|
||||
value.metadataFiles.set(path, Buffer.from('new'))
|
||||
}
|
||||
return { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}),
|
||||
activateRuntime: vi.fn(async () => {
|
||||
throw runtimeFailure
|
||||
})
|
||||
@@ -1043,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 { exitCode: 0, stdout: '{}', stderr: '' }
|
||||
}),
|
||||
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,7 +5,6 @@ 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,
|
||||
@@ -33,13 +32,8 @@ import type {
|
||||
AgentPackageManager,
|
||||
VerifiedRemoteAgentInstallCandidate
|
||||
} from './agent-package-manager'
|
||||
import {
|
||||
restoreRemoteEnvironmentMetadata,
|
||||
snapshotRemoteEnvironmentMetadata,
|
||||
type RemoteEnvironmentMetadataSnapshot
|
||||
} from './remote-environment-metadata'
|
||||
import type {
|
||||
PersistedRemoteEnvironmentMetadataSnapshot,
|
||||
PendingRemoteEnvironmentOperation,
|
||||
RemoteEnvironmentOperationStore
|
||||
} from './remote-environment-operation-store'
|
||||
import type {
|
||||
@@ -52,7 +46,6 @@ import {
|
||||
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(
|
||||
@@ -95,7 +88,7 @@ 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
|
||||
@@ -134,29 +127,21 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
const target = await this.#resolver.resolve(hostId)
|
||||
signal.throwIfAborted()
|
||||
assertValidSshConnectionTarget(hostId, target)
|
||||
const recovered = await this.#reconcilePendingOperation(
|
||||
await this.#cleanupPendingOperation(
|
||||
hostId,
|
||||
target,
|
||||
emit,
|
||||
signal
|
||||
)
|
||||
if (recovered) {
|
||||
return
|
||||
}
|
||||
|
||||
let probeLease: SshConnectionLease | undefined
|
||||
let bootstrapLease:
|
||||
| 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)
|
||||
@@ -256,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
|
||||
|
||||
@@ -289,35 +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
|
||||
)
|
||||
await this.#operationStore.save({
|
||||
version: 2,
|
||||
hostId,
|
||||
targetIdentity: remoteHostRecoveryIdentityKey(target),
|
||||
operationId,
|
||||
size: remoteCandidate.size,
|
||||
sha256: remoteCandidate.sha256,
|
||||
urls: [...remoteCandidate.urls],
|
||||
metadataSnapshots:
|
||||
persistMetadataSnapshots(metadataSnapshots)
|
||||
})
|
||||
|
||||
// Keep the full target re-resolution immediately adjacent to commit.
|
||||
await assertTargetCurrent(this.#resolver, target, signal)
|
||||
assertLeaseMatchesTarget(bootstrapLease, target)
|
||||
@@ -355,7 +308,6 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
throw new Error('远端安装提交身份与准备身份不匹配')
|
||||
}
|
||||
assertPackageIdentity(committed.identity, candidate)
|
||||
committedIdentity = committed.identity
|
||||
signal.throwIfAborted()
|
||||
|
||||
await this.#adoptCommittedEnvironment(
|
||||
@@ -372,7 +324,10 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
operationId,
|
||||
{ signal }
|
||||
)
|
||||
if (cleanup.cleaned) {
|
||||
if (
|
||||
cleanup.cleaned ||
|
||||
cleanup.reason === 'operation-unavailable'
|
||||
) {
|
||||
operationCleaned = true
|
||||
try {
|
||||
await this.#operationStore.remove(hostId)
|
||||
@@ -381,29 +336,10 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// The environment is already healthy. Leave the bounded
|
||||
// operation for a later maintenance retry.
|
||||
// The environment is already healthy. The next update will retry
|
||||
// cleanup before starting a fresh operation.
|
||||
}
|
||||
} 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 (
|
||||
operationId &&
|
||||
bootstrapLease &&
|
||||
@@ -415,19 +351,11 @@ 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()
|
||||
@@ -595,7 +523,7 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
)
|
||||
}
|
||||
|
||||
async #reconcilePendingOperation(
|
||||
async #cleanupPendingOperation(
|
||||
hostId: string,
|
||||
target: SshConnectionTarget,
|
||||
emit: (
|
||||
@@ -603,207 +531,46 @@ export class RemoteEnvironmentPreparer implements Preparer {
|
||||
phase: RemoteEnvironmentUpdateProgress['phase']
|
||||
) => void,
|
||||
signal: AbortSignal
|
||||
): Promise<boolean> {
|
||||
const pending = await this.#operationStore.load(hostId)
|
||||
): Promise<void> {
|
||||
let pending: PendingRemoteEnvironmentOperation | undefined
|
||||
try {
|
||||
pending = await this.#operationStore.load(hostId)
|
||||
} catch {
|
||||
await this.#operationStore.remove(hostId)
|
||||
return
|
||||
}
|
||||
if (!pending) {
|
||||
return false
|
||||
return
|
||||
}
|
||||
if (
|
||||
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 bootstrapLease =
|
||||
await this.#sshPool.acquireRemotePackageBootstrap(
|
||||
target,
|
||||
signal
|
||||
)
|
||||
let commandLease: SshConnectionLease | undefined
|
||||
let recoveryMetadataSftp: StagedSftp | undefined
|
||||
).catch(() => undefined)
|
||||
try {
|
||||
if (!bootstrapLease) {
|
||||
return
|
||||
}
|
||||
assertLeaseMatchesTarget(bootstrapLease, target)
|
||||
if (pending.version === 1) {
|
||||
const cleanup = await bootstrapLease.cleanup(
|
||||
pending.operationId,
|
||||
{ signal }
|
||||
)
|
||||
if (
|
||||
!cleanup.cleaned &&
|
||||
cleanup.reason !== 'operation-unavailable'
|
||||
) {
|
||||
throw new Error(
|
||||
`旧版远程环境暂存清理失败:${cleanup.reason}`
|
||||
)
|
||||
}
|
||||
await this.#operationStore.remove(hostId)
|
||||
return false
|
||||
}
|
||||
const status = await bootstrapLease.commitStatus(
|
||||
candidate,
|
||||
{ signal }
|
||||
)
|
||||
if (
|
||||
!status.committed &&
|
||||
status.reason === 'operation-unavailable'
|
||||
) {
|
||||
await this.#operationStore.remove(hostId)
|
||||
return false
|
||||
}
|
||||
if (
|
||||
!status.committed &&
|
||||
status.reason === 'installer-rollback-incomplete'
|
||||
) {
|
||||
throw new SshRemotePackageCommitIndeterminateError(
|
||||
'上一次远程环境发布失败且回滚结果不完整,请检查 Host 状态'
|
||||
)
|
||||
}
|
||||
commandLease = await this.#sshPool.acquire(
|
||||
target,
|
||||
signal
|
||||
)
|
||||
assertLeaseMatchesTarget(commandLease, target)
|
||||
const probe =
|
||||
await commandLease.runAgentBootstrapProbe(signal)
|
||||
if (!probe.ready) {
|
||||
throw new Error(
|
||||
`远端系统不能恢复 GoodBuddy 环境:${probe.reason}`
|
||||
)
|
||||
}
|
||||
recoveryMetadataSftp =
|
||||
await commandLease.openStagedSftp(
|
||||
probe.canonicalHomeDirectory,
|
||||
{
|
||||
maximumFileBytes: MAXIMUM_METADATA_BYTES,
|
||||
maximumTotalBytes:
|
||||
MAXIMUM_METADATA_BYTES * 24,
|
||||
maximumOperations: 128
|
||||
},
|
||||
signal
|
||||
)
|
||||
const recoverySnapshots =
|
||||
restorePersistedMetadataSnapshots(
|
||||
pending.metadataSnapshots,
|
||||
probe.uid
|
||||
)
|
||||
if (status.committed) {
|
||||
try {
|
||||
await this.#adoptCommittedEnvironment(
|
||||
commandLease,
|
||||
status.identity,
|
||||
'auto',
|
||||
emit,
|
||||
signal
|
||||
)
|
||||
} catch (error) {
|
||||
await stopCandidateBestEffort(
|
||||
commandLease,
|
||||
status.identity.agent.installationId
|
||||
)
|
||||
try {
|
||||
await restoreRemoteEnvironmentMetadata(
|
||||
recoveryMetadataSftp,
|
||||
recoverySnapshots
|
||||
)
|
||||
} catch (rollbackError) {
|
||||
throw new AggregateError(
|
||||
[error, rollbackError],
|
||||
'上一次远程环境恢复失败,且原有环境元数据未能完整恢复',
|
||||
{ cause: rollbackError }
|
||||
)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} else {
|
||||
await restoreRemoteEnvironmentMetadata(
|
||||
recoveryMetadataSftp,
|
||||
recoverySnapshots
|
||||
)
|
||||
}
|
||||
const cleanup = await bootstrapLease.cleanup(
|
||||
await bootstrapLease.cleanup(
|
||||
pending.operationId,
|
||||
{ signal }
|
||||
)
|
||||
if (
|
||||
cleanup.cleaned ||
|
||||
cleanup.reason === 'operation-unavailable'
|
||||
) {
|
||||
await this.#operationStore.remove(hostId)
|
||||
} else if (!status.committed) {
|
||||
throw new Error(
|
||||
`上一次未提交的远程环境暂存清理失败:${cleanup.reason}`
|
||||
)
|
||||
}
|
||||
return status.committed
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof
|
||||
SshRemotePackageCommitIndeterminateError
|
||||
) {
|
||||
throw error
|
||||
}
|
||||
const detail = error instanceof Error
|
||||
? error.message
|
||||
: String(error)
|
||||
throw new SshRemotePackageCommitIndeterminateError(
|
||||
`上一次远程环境恢复失败:${detail}`
|
||||
)
|
||||
).catch(() => undefined)
|
||||
} finally {
|
||||
recoveryMetadataSftp?.close()
|
||||
commandLease?.release()
|
||||
bootstrapLease.release()
|
||||
bootstrapLease?.release()
|
||||
await this.#operationStore.remove(hostId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function persistMetadataSnapshots(
|
||||
snapshots: readonly RemoteEnvironmentMetadataSnapshot[]
|
||||
): readonly PersistedRemoteEnvironmentMetadataSnapshot[] {
|
||||
return snapshots.map((snapshot) => ({
|
||||
path: snapshot.path,
|
||||
uid: snapshot.uid,
|
||||
...(snapshot.contents === undefined
|
||||
? {}
|
||||
: {
|
||||
contentsBase64:
|
||||
snapshot.contents.toString('base64')
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
function restorePersistedMetadataSnapshots(
|
||||
snapshots:
|
||||
readonly PersistedRemoteEnvironmentMetadataSnapshot[],
|
||||
uid: number
|
||||
): readonly RemoteEnvironmentMetadataSnapshot[] {
|
||||
if (snapshots.some((snapshot) => snapshot.uid !== uid)) {
|
||||
throw new Error(
|
||||
'远程环境恢复元数据与当前 SSH 用户不匹配'
|
||||
)
|
||||
}
|
||||
return snapshots.map((snapshot) => ({
|
||||
path: snapshot.path,
|
||||
uid: snapshot.uid,
|
||||
...(snapshot.contentsBase64 === undefined
|
||||
? {}
|
||||
: {
|
||||
contents: Buffer.from(
|
||||
snapshot.contentsBase64,
|
||||
'base64'
|
||||
)
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
async function resolvePreparationMethod(
|
||||
requested: RemoteEnvironmentPreparationMethod,
|
||||
lease: SshRemotePackageBootstrapLease,
|
||||
@@ -854,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,
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import {
|
||||
readFileSync,
|
||||
readdirSync
|
||||
} from 'node:fs'
|
||||
import {
|
||||
join,
|
||||
resolve
|
||||
} from 'node:path'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
RemoteRuntimeBundleManifest
|
||||
} from '../../shared/remote-runtime-launch-contracts'
|
||||
import type {
|
||||
SshConnectionPoolTarget
|
||||
} from '../ssh/ssh-connection-pool'
|
||||
@@ -17,24 +12,62 @@ import {
|
||||
|
||||
const HOST_ID = 'host-1'
|
||||
const AGENT_ID = `agent-${'a'.repeat(64)}` as never
|
||||
const runtimeRoot = resolve(
|
||||
'.remote-runtime-resources',
|
||||
'linux-x64',
|
||||
'opencode'
|
||||
)
|
||||
const digestDirectory = readdirSync(runtimeRoot)[0]!
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(
|
||||
join(runtimeRoot, digestDirectory, 'manifest.json'),
|
||||
'utf8'
|
||||
)
|
||||
) as {
|
||||
runtimeId: string
|
||||
runtimeVersion: string
|
||||
architecture: 'x64'
|
||||
bundleDigest: string
|
||||
adapterDigest: string
|
||||
acpCapabilitiesDigest: string
|
||||
const digestDirectory = 'a'.repeat(64)
|
||||
const manifest: RemoteRuntimeBundleManifest = {
|
||||
formatVersion: 2,
|
||||
product: 'GoodBuddy',
|
||||
runtimeId: 'opencode',
|
||||
runtimeVersion: '1.18.9',
|
||||
provider: 'opencode',
|
||||
platform: 'linux',
|
||||
architecture: 'x64',
|
||||
signingKeyId: 'runtime-test',
|
||||
bundleDigest: `sha256:${digestDirectory}`,
|
||||
adapterDigest: `sha256:${'b'.repeat(64)}`,
|
||||
sourcePackage: {
|
||||
name: 'opencode-linux-x64-baseline',
|
||||
integrity:
|
||||
'sha512-x4KiJk9EF7ktM18Ru5Jue4kTntxMvlhWb7tHniQGGRvY2KeoK1iIkyAFd7ri5H/fSkM22hNv/Gg1Jk6/h9IlxQ=='
|
||||
},
|
||||
entrypoint: {
|
||||
identity: 'opencode-acp',
|
||||
path: 'bin/opencode',
|
||||
sha256: 'c'.repeat(64),
|
||||
argvPrefix: ['acp']
|
||||
},
|
||||
files: [
|
||||
{
|
||||
path: 'bin/opencode',
|
||||
size: 100,
|
||||
sha256: 'c'.repeat(64),
|
||||
mode: '0755'
|
||||
},
|
||||
{
|
||||
path: 'licenses/opencode.txt',
|
||||
size: 10,
|
||||
sha256: 'd'.repeat(64),
|
||||
mode: '0644'
|
||||
}
|
||||
],
|
||||
licenses: [
|
||||
{
|
||||
package: 'opencode',
|
||||
version: '1.18.9',
|
||||
spdx: 'MIT',
|
||||
path: 'licenses/opencode.txt'
|
||||
}
|
||||
],
|
||||
allowedEnvironmentNames: ['HOME', 'LANG'],
|
||||
protocol: {
|
||||
major: 2,
|
||||
minor: 0
|
||||
},
|
||||
acpCapabilitiesDigest: `sha256:${'e'.repeat(64)}`,
|
||||
limits: {
|
||||
maximumPromptRuntimeMilliseconds: 60_000,
|
||||
maximumPromptInputBytes: 4096,
|
||||
maximumPromptOutputBytes: 1024
|
||||
}
|
||||
}
|
||||
const entry = {
|
||||
runtimeId: manifest.runtimeId,
|
||||
|
||||
@@ -19,7 +19,6 @@ import { isMissingPathError } from './path-errors'
|
||||
import { remoteHostTargetIdentityKey } from './remote-host-target-identity'
|
||||
|
||||
const MAXIMUM_METADATA_BYTES = 1024 * 1024
|
||||
const PRIVATE_FILE_MODE = 0o600
|
||||
const RUNTIME_REGISTRY_PATH =
|
||||
'.goodbuddy/runtimes/registry.json'
|
||||
const OPENCODE_ROOT = '.goodbuddy/runtimes/opencode'
|
||||
@@ -212,12 +211,6 @@ export class RemoteRuntimeInstallationManager {
|
||||
},
|
||||
signal
|
||||
)
|
||||
await assertPrivateMetadata(
|
||||
sftp,
|
||||
RUNTIME_REGISTRY_PATH,
|
||||
probe.uid,
|
||||
signal
|
||||
)
|
||||
const registry = parseRuntimeRegistryState(
|
||||
parseJsonBytes(
|
||||
await sftp.readFile(
|
||||
@@ -246,12 +239,6 @@ export class RemoteRuntimeInstallationManager {
|
||||
`${OPENCODE_ROOT}/${digestDirectoryName(
|
||||
current.bundleDigest
|
||||
)}/manifest.json`
|
||||
await assertPublicMetadata(
|
||||
sftp,
|
||||
manifestPath,
|
||||
probe.uid,
|
||||
signal
|
||||
)
|
||||
const manifest =
|
||||
remoteRuntimeBundleManifestSchema.parse(
|
||||
parseJsonBytes(
|
||||
@@ -319,44 +306,6 @@ export class RemoteRuntimeInstallationManager {
|
||||
|
||||
}
|
||||
|
||||
async function assertPrivateMetadata(
|
||||
sftp: StagedSftp,
|
||||
path: string,
|
||||
uid: number,
|
||||
signal: AbortSignal
|
||||
): Promise<void> {
|
||||
const metadata = await sftp.lstat(path, signal)
|
||||
if (
|
||||
metadata.type !== 'file' ||
|
||||
metadata.uid !== uid ||
|
||||
metadata.mode !== PRIVATE_FILE_MODE ||
|
||||
metadata.size > MAXIMUM_METADATA_BYTES
|
||||
) {
|
||||
throw new Error(
|
||||
`Remote Runtime metadata is invalid: ${path}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function assertPublicMetadata(
|
||||
sftp: StagedSftp,
|
||||
path: string,
|
||||
uid: number,
|
||||
signal: AbortSignal
|
||||
): Promise<void> {
|
||||
const metadata = await sftp.lstat(path, signal)
|
||||
if (
|
||||
metadata.type !== 'file' ||
|
||||
metadata.uid !== uid ||
|
||||
metadata.mode !== 0o644 ||
|
||||
metadata.size > MAXIMUM_METADATA_BYTES
|
||||
) {
|
||||
throw new Error(
|
||||
`Remote Runtime manifest metadata is invalid: ${path}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function digestDirectoryName(bundleDigest: string): string {
|
||||
if (!/^sha256:[a-f0-9]{64}$/u.test(bundleDigest)) {
|
||||
throw new Error('Runtime bundle digest is invalid')
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -233,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">,
|
||||
@@ -572,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
|
||||
@@ -1611,9 +1608,6 @@ export function createSshRemotePackageBootstrapExecutor(
|
||||
}
|
||||
throw new Error("Agent 远程安装提交返回了无效结果");
|
||||
},
|
||||
commitStatus(candidate, options = {}) {
|
||||
return readCommitStatus(candidate, options);
|
||||
},
|
||||
async cleanup(operationId, options = {}) {
|
||||
const verifiedOperationId = validateOperationId(operationId);
|
||||
const result = await runBootstrapCommand(
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
type AgentReleaseKeyRegistry
|
||||
} from '../agent-installation-contracts'
|
||||
import {
|
||||
assertDetachedRemoteRuntimeBundleDigest,
|
||||
digestRemoteRuntimeBundleIdentity,
|
||||
digestRemoteRuntimeBundleManifest,
|
||||
remoteRuntimeBundleManifestSchema,
|
||||
remoteRuntimeLockSchema,
|
||||
@@ -75,6 +75,68 @@ export type LoadRegisteredRuntimeBundleOptions =
|
||||
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)
|
||||
@@ -125,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,
|
||||
@@ -197,57 +239,14 @@ export async function loadRegisteredRuntimeBundle(
|
||||
bundleDirectoryInput: string,
|
||||
options: LoadRegisteredRuntimeBundleOptions
|
||||
): Promise<VerifiedRuntimeBundle> {
|
||||
const bundleDirectory = assertAbsoluteManagedPath(
|
||||
resolve(bundleDirectoryInput)
|
||||
)
|
||||
const registered = runtimeRegistryEntrySchema.parse(
|
||||
options.registered
|
||||
)
|
||||
const rootStat = await lstat(bundleDirectory)
|
||||
assertOwnedDirectory(
|
||||
rootStat,
|
||||
'Runtime bundle directory',
|
||||
options.uid
|
||||
)
|
||||
if (
|
||||
shouldEnforceMode(options) &&
|
||||
modeString(rootStat.mode) !== '0700'
|
||||
) {
|
||||
throw new Error(
|
||||
'Runtime bundle directory permissions must be 0700'
|
||||
)
|
||||
}
|
||||
if (
|
||||
basename(bundleDirectory) !==
|
||||
registered.bundleDigest.slice('sha256:'.length)
|
||||
) {
|
||||
throw new Error(
|
||||
'Registered Runtime digest does not match its managed directory'
|
||||
)
|
||||
}
|
||||
|
||||
const manifestBytes = await readMetadataFile(
|
||||
join(bundleDirectory, MANIFEST_FILE_NAME),
|
||||
'Runtime manifest',
|
||||
const verified = await verifyPublishedRuntimeBundle(
|
||||
bundleDirectoryInput,
|
||||
options
|
||||
)
|
||||
const signatureBytes = await readSignature(
|
||||
join(bundleDirectory, SIGNATURE_FILE_NAME),
|
||||
options
|
||||
)
|
||||
const manifest = await verifyRuntimeManifestSignature(
|
||||
manifestBytes,
|
||||
signatureBytes,
|
||||
options.releaseKeyRegistry,
|
||||
options.verificationEnvironment ?? 'production'
|
||||
)
|
||||
assertRuntimeManifestMatchesLock(
|
||||
manifest,
|
||||
remoteRuntimeLockSchema.parse(options.runtimeLock),
|
||||
options.architecture
|
||||
)
|
||||
const manifestDigest =
|
||||
await digestRemoteRuntimeBundleManifest(manifest)
|
||||
const { manifest, manifestDigest } = verified
|
||||
if (
|
||||
manifest.runtimeId !== registered.runtimeId ||
|
||||
manifest.runtimeVersion !== registered.runtimeVersion ||
|
||||
@@ -266,41 +265,7 @@ export async function loadRegisteredRuntimeBundle(
|
||||
)
|
||||
}
|
||||
|
||||
const executableRecord = manifest.files.find(
|
||||
(file) => file.path === manifest.entrypoint.path
|
||||
)
|
||||
if (executableRecord === undefined) {
|
||||
throw new Error(
|
||||
'Registered 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(
|
||||
'Registered Runtime entrypoint metadata changed'
|
||||
)
|
||||
}
|
||||
return {
|
||||
bundleDirectory,
|
||||
executablePath,
|
||||
manifest,
|
||||
manifestDigest
|
||||
}
|
||||
return verified
|
||||
}
|
||||
|
||||
export function canonicalRuntimeManifestBytes(
|
||||
@@ -362,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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user