diff --git a/AGENTS.md b/AGENTS.md index c7c0ed71ff9..c332141e5fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,10 @@ Package-specific guides: | Run all tests for broad changes | `npm test` | | Render behavior-oriented test tree | `npm run test:spec` | | Run fast source tests | `npm run test:fast` | +| Run tests affected by current changes | `npm run test:changed` | +| Watch focused source tests | `npm run test:watch` | +| Shuffle focused tests without coverage | `npm run test:shuffle` | +| Diagnose async leaks or shutdown hangs | `npm run test:diagnose:leaks` | | Run integration tests | `npm run test:integration` | | Run package contracts | `npm run test:package` | | Run E2E support tests | `npx vitest run --project e2e-support` | @@ -95,6 +99,8 @@ When writing tests: - Import CLI source from ordinary tests. Put genuine compiled-artifact assertions under `test/package-contract/`. - Keep project globs disjoint; `npm run test:projects:check` derives membership from Vitest and rejects overlap. - Deterministic projects clear mock calls, restore `vi.spyOn`, and undo `vi.stubEnv` and `vi.stubGlobal` before each test. Create those spies and stubs in `beforeEach` or the test body unless a documented import-time stub must run before module evaluation. Restore direct environment or global mutations yourself, and reset mock implementations explicitly when needed. Live E2E and automatic `mockReset` are intentionally excluded. +- Use `npm run test:changed` or `npm run test:watch` for focused CLI, plugin, and E2E-support feedback. Add only concrete opaque-input mappings to `test/helpers/vitest-watch-triggers.ts` when the import graph cannot see a YAML, Python, shell, generated, or workflow dependency. +- Use `npm run test:shuffle -- --sequence.seed=` to replay a printed test-order seed. Use `npm run test:diagnose:leaks` for async-resource or shutdown-hang diagnostics; both commands keep coverage disabled, and leak diagnostics can accompany exit code 0 when assertions pass. - Write behavior-oriented titles, put local issue references in a final `(#1234)` suffix, and use `npm run test:spec` for the hierarchical specification view. - Mock external dependencies; don't call real NVIDIA APIs in unit tests - E2E tests run on ephemeral Brev cloud instances diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dd571de191d..e5eee6ac6e1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -201,6 +201,10 @@ These are the primary npm scripts for day-to-day development: | `npm test` | Build package artifacts and run every non-live Vitest project for broad changes | | `npm run test:spec` | Run every non-live test with hierarchical behavior-oriented output | | `npm run test:fast` | Clean `dist/` and run source CLI, plugin, and E2E-support tests | +| `npm run test:changed` | Run tests affected by staged, unstaged, or untracked changes in the CLI, plugin, and E2E-support projects | +| `npm run test:watch` | Watch the CLI, plugin, and E2E-support projects and rerun affected tests | +| `npm run test:shuffle` | Shuffle test order in the focused source projects without collecting coverage | +| `npm run test:diagnose:leaks` | Report async-resource leaks and diagnose a Vitest process that hangs during shutdown | | `npm run test:integration` | Clean-build the CLI and run root integration and installer tests | | `npm run test:package` | Clean-build CLI/plugin artifacts and run compiled-package contracts | | `npm run test:live-e2e` | Opt into live E2E scenarios (mutates real external state) | @@ -222,6 +226,33 @@ npx vitest run --project e2e-support This project is fast and does not run live targets. Live E2E remains opt-in through `npm run test:live-e2e` or the applicable GitHub Actions workflow. +### Focused Vitest Feedback + +Use `npm run test:changed` for the staged, unstaged, and untracked changes in the current checkout, +or keep `npm run test:watch` running while editing. Both commands select only the source-backed +`cli`, `plugin`, and `e2e-support` projects. Watch mode also maps the repository's current opaque +YAML, Python, shell, generated, and workflow inputs to the concrete contract tests that read or +execute them outside Vitest's import graph. Add a narrow mapping in +`test/helpers/vitest-watch-triggers.ts` when a new opaque input needs the same treatment. + +Use `npm run test:shuffle` to expose order dependencies in those focused projects. The command +shuffles tests within files and leaves coverage disabled. Vitest prints the chosen seed at the +start of the run. Replay that order by appending the printed value: + +```bash +npm run test:shuffle -- --sequence.seed=6692 +``` + +Use `npm run test:diagnose:leaks` when a test file leaves an async resource active or Vitest hangs +during shutdown. It enables Vitest's async-leak detector and hanging-process reporter while +keeping coverage disabled. This is a diagnostic command: inspect its leak output even when all +assertions pass, because reported async leaks do not independently change a successful test exit +code. + +Vitest chooses the environment-appropriate reporter for ordinary local runs. In CI, console logs +from passing tests stay hidden while logs attached to failures are replayed; GitHub Actions still +receives test annotations. + ### Test State Isolation The `cli`, `integration`, `installer-integration`, `package-contract`, `plugin`, and `e2e-support` diff --git a/ci/cli-test-timing-hints.json b/ci/cli-test-timing-hints.json index fbfbdd06784..aad68273747 100644 --- a/ci/cli-test-timing-hints.json +++ b/ci/cli-test-timing-hints.json @@ -2,93 +2,103 @@ "schemaVersion": 1, "defaultDurationMs": 5000, "source": { - "runId": 29135065089, - "headSha": "7bd6f6685758fa72f84896c3b8aa183f6ed3145a", - "recordedAt": "2026-07-11T01:48:06Z" + "runId": 29180354863, + "headSha": "92439a702f1a8c7cca8609f1259304115a10931d", + "recordedAt": "2026-07-12T05:00:19Z" }, "files": { - "src/lib/actions/sandbox/doctor-flow.test.ts": 7188, - "src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts": 13111, - "src/lib/actions/sandbox/mcp-bridge-status-state.test.ts": 6323, - "src/lib/shields/flow.test.ts": 7842, - "src/lib/shields/index.test.ts": 5773, - "src/lib/tunnel/services.test.ts": 5469, - "test/channels-remove-full-teardown.test.ts": 7869, - "test/cli/connect-recovery.test.ts": 5286, - "test/cli/debug-command.test.ts": 15439, - "test/cli/destroy-gateway-cleanup.test.ts": 11834, - "test/cli/dispatch-basics.test.ts": 6048, - "test/cli/docker-outage.test.ts": 7963, - "test/cli/doctor-gateway-token.test.ts": 12666, - "test/cli/list-inference.test.ts": 13506, - "test/cli/list-share-live-inference.test.ts": 13787, - "test/cli/logs.test.ts": 9628, - "test/cli/onboard-compatibility.test.ts": 7785, - "test/cli/sandbox-mutations.test.ts": 13836, - "test/cli/sandbox-status-json.test.ts": 14811, - "test/cli/sandbox-status-text.test.ts": 9317, - "test/cli/snapshot-shields.test.ts": 8393, - "test/cli/tunnel-command.test.ts": 8792, - "test/dcode-wrapper-identity.test.ts": 9787, - "test/exit-code-user-error-surfaces.test.ts": 11372, - "test/gateway-state-reconcile-2276.test.ts": 7723, - "test/hermes-restart-config-seal.test.ts": 50253, - "test/hermes-runtime-api-key.test.ts": 9123, - "test/install-onboard-yes.test.ts": 5576, - "test/install-openshell-upgrade-prompt.test.ts": 17762, - "test/installer-hash-check.test.ts": 10012, - "test/internal-cli.test.ts": 7876, - "test/langchain-deepagents-code-direct-module-patch.test.ts": 19322, - "test/langchain-deepagents-code-image-credentials.test.ts": 25411, - "test/langchain-deepagents-code-nemotron-profile-plugin.test.ts": 6709, - "test/list-command-helper-uses.test.ts": 7200, - "test/local-credential-helper.test.ts": 51442, - "test/mcp-add-crash-consistency.test.ts": 14629, - "test/mcp-bridge-destroy-marker-recovery.test.ts": 7342, - "test/mcp-bridge-servers.test.ts": 13169, - "test/mcp-policy-key-ownership.test.ts": 7067, - "test/nemo-deepagents-alias.test.ts": 11070, - "test/nemoclaw-start-gateway-health.test.ts": 5551, - "test/nemoclaw-start.test.ts": 26821, - "test/nemohermes-alias.test.ts": 9181, - "test/onboard-custom-dockerfile.test.ts": 9202, - "test/onboard-fsm-live-slices.test.ts": 7716, - "test/onboard-messaging.test.ts": 22893, - "test/onboard-ollama-autostart.test.ts": 9245, - "test/onboard-prompt-default-case.test.ts": 8464, - "test/onboard-reservation-recreate.test.ts": 5160, - "test/onboard-selection-vllm.test.ts": 6921, - "test/onboard-selection.test.ts": 19596, - "test/onboard.test.ts": 35406, - "test/openclaw-chat-send-patch.test.ts": 7337, - "test/openclaw-config-guard.test.ts": 16719, - "test/openclaw-device-self-approval-patch.test.ts": 15212, - "test/openclaw-device-stored-auth-patch.test.ts": 6607, - "test/openclaw-integrity-pin.test.ts": 33852, - "test/policy-add-remove-session-sync.test.ts": 6114, - "test/policy-channel-agent-resolution.test.ts": 5834, - "test/policy-tiers-onboard.test.ts": 5200, - "test/pr-workflow-contract.test.ts": 14722, - "test/reboot-identity-drift.test.ts": 10041, - "test/rebuild-credential-preflight.test.ts": 17713, - "test/rebuild-shields-auto-unlock.test.ts": 8723, - "test/recover-port-forward.test.ts": 8091, - "test/release-latest-tag.test.ts": 27029, - "test/repro-2201.test.ts": 16819, - "test/repro-2666-silent-list-status.test.ts": 5854, - "test/sandbox-connect-inference/auto-pair-approval.test.ts": 12342, - "test/sandbox-connect-inference/route-swap-repair.test.ts": 13530, - "test/sandbox-sessions-export-cli.test.ts": 12313, - "test/sandbox-stuck-recovery.test.ts": 6539, - "test/skills/check-gates-compliance.test.ts": 10699, - "test/skills/triage-runtime.test.ts": 9690, - "test/snapshot-gateway-guard.test.ts": 5501, - "test/snapshot-openclaw-managed-extensions.test.ts": 16367, - "test/snapshot-restore-existing-dest.test.ts": 10738, - "test/snapshot.test.ts": 21849, - "test/state-dir-guard.test.ts": 7440, - "test/uninstall-prompt-pty.test.ts": 9308, - "test/uninstall.test.ts": 7691, - "test/update.test.ts": 5843 + "src/lib/actions/sandbox/doctor-flow.test.ts": 6480, + "src/lib/actions/sandbox/mcp-bridge-status-resolution.test.ts": 13403, + "src/lib/actions/sandbox/mcp-bridge-status-state.test.ts": 6644, + "src/lib/shields/flow.test.ts": 9944, + "src/lib/shields/index.test.ts": 6267, + "src/lib/shields/legacy-hermes-compat.test.ts": 5463, + "src/lib/tunnel/services.test.ts": 7253, + "test/channels-remove-full-teardown.test.ts": 6619, + "test/cli/connect-recovery.test.ts": 6351, + "test/cli/debug-command.test.ts": 16626, + "test/cli/destroy-gateway-cleanup.test.ts": 12114, + "test/cli/dispatch-basics.test.ts": 6350, + "test/cli/docker-outage.test.ts": 8031, + "test/cli/doctor-gateway-token.test.ts": 12778, + "test/cli/helpers.test.ts": 5627, + "test/cli/list-inference.test.ts": 14574, + "test/cli/list-share-live-inference.test.ts": 14263, + "test/cli/logs.test.ts": 12412, + "test/cli/maintenance-command.test.ts": 6187, + "test/cli/onboard-compatibility.test.ts": 8156, + "test/cli/sandbox-mutations.test.ts": 14331, + "test/cli/sandbox-status-json.test.ts": 18108, + "test/cli/sandbox-status-text.test.ts": 9679, + "test/cli/snapshot-shields.test.ts": 8835, + "test/cli/tunnel-command.test.ts": 9000, + "test/dcode-session-supervisor.test.ts": 7628, + "test/dcode-wrapper-identity.test.ts": 10212, + "test/exit-code-user-error-surfaces.test.ts": 14609, + "test/fetch-guard-patch-regression.test.ts": 5118, + "test/gateway-state-reconcile-2276.test.ts": 7485, + "test/hermes-restart-config-seal-write-lock.test.ts": 43338, + "test/hermes-runtime-api-key.test.ts": 9275, + "test/install-onboard-yes.test.ts": 5722, + "test/install-openshell-upgrade-prompt.test.ts": 22675, + "test/installer-hash-check.test.ts": 10253, + "test/internal-cli.test.ts": 8071, + "test/langchain-deepagents-code-config.test.ts": 5745, + "test/langchain-deepagents-code-direct-module-patch.test.ts": 18520, + "test/langchain-deepagents-code-image-credentials.test.ts": 26951, + "test/langchain-deepagents-code-nemotron-profile-plugin.test.ts": 5557, + "test/list-command-helper-uses.test.ts": 7276, + "test/local-credential-helper-fields.test.ts": 46777, + "test/local-credential-helper-session.test.ts": 5318, + "test/mcp-add-crash-consistency.test.ts": 18749, + "test/mcp-bridge-destroy-marker-recovery.test.ts": 8167, + "test/mcp-bridge-servers.test.ts": 13182, + "test/mcp-policy-key-ownership.test.ts": 7439, + "test/nemo-deepagents-alias.test.ts": 11841, + "test/nemoclaw-start-gateway-health.test.ts": 5508, + "test/nemoclaw-start.test.ts": 26549, + "test/nemohermes-alias.test.ts": 9507, + "test/ollama-proxy-recovery.test.ts": 5672, + "test/onboard-custom-dockerfile.test.ts": 8270, + "test/onboard-fsm-live-slices.test.ts": 7774, + "test/onboard-messaging.test.ts": 24788, + "test/onboard-ollama-autostart.test.ts": 6497, + "test/onboard-prompt-default-case.test.ts": 9107, + "test/onboard-sandbox-build.test.ts": 6376, + "test/onboard-sandbox-recreation.test.ts": 16082, + "test/onboard-selection-vllm.test.ts": 5151, + "test/onboard-selection.test.ts": 26005, + "test/openclaw-chat-send-patch.test.ts": 7689, + "test/openclaw-config-guard.test.ts": 16891, + "test/openclaw-device-self-approval-patch.test.ts": 15630, + "test/openclaw-device-stored-auth-patch.test.ts": 6887, + "test/openclaw-integrity-pin-base.test.ts": 23614, + "test/openclaw-integrity-pin-plugin-install.test.ts": 7841, + "test/plugin-vitest-project.test.ts": 7140, + "test/policy-add-remove-session-sync.test.ts": 6369, + "test/policy-channel-agent-resolution.test.ts": 5978, + "test/pr-workflow-contract.test.ts": 14986, + "test/reboot-identity-drift.test.ts": 10091, + "test/rebuild-credential-hydration.test.ts": 5580, + "test/rebuild-credential-preflight.test.ts": 18993, + "test/rebuild-shields-auto-unlock.test.ts": 9424, + "test/recover-port-forward.test.ts": 9918, + "test/release-latest-tag.test.ts": 27167, + "test/repro-2201.test.ts": 17598, + "test/repro-2666-silent-list-status.test.ts": 8676, + "test/sandbox-connect-inference/auto-pair-approval.test.ts": 12530, + "test/sandbox-connect-inference/route-swap-repair.test.ts": 19653, + "test/sandbox-sessions-export-cli.test.ts": 12907, + "test/sandbox-stuck-recovery.test.ts": 6643, + "test/skills/check-gates-compliance.test.ts": 10363, + "test/skills/triage-runtime.test.ts": 9918, + "test/snapshot-gateway-guard.test.ts": 7138, + "test/snapshot-openclaw-managed-extensions.test.ts": 16951, + "test/snapshot-restore-existing-dest.test.ts": 11219, + "test/snapshot.test.ts": 22248, + "test/state-dir-guard.test.ts": 7375, + "test/uninstall-prompt-pty.test.ts": 9494, + "test/uninstall.test.ts": 7873, + "test/update.test.ts": 6145 } } diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 5395c28d86f..26bc3cac228 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -10,7 +10,6 @@ "test/nemoclaw-start.test.ts": 4826, "test/onboard-messaging.test.ts": 2049, "test/onboard-selection.test.ts": 4769, - "test/onboard.test.ts": 4039, "test/policies.test.ts": 2242 } } diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index 58e0a165c4a..df0283ea7d4 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -8,7 +8,9 @@ Scope: NemoClaw runtime pin `openclaw@2026.6.10`, runtime helper pin `@zed-indus ## Issue #5591 Acceptance Mapping -Issue #5591 is the dependency-update umbrella, and its proposed design has three literal clauses. "Latest stable version of Hermes" is satisfied by merged PR #5594 (`hermes-agent==2026.6.19`); "Latest version of OpenShell" is satisfied by merged PR #5596 (`openshell==0.0.71`); and "Latest stable version of OpenClaw" is the clause owned by this PR. For that OpenClaw clause, the repository pins the reviewed non-prerelease `openclaw@2026.6.10` artifact and its plugin SRIs, while `test/openclaw-integrity-pin.test.ts`, `test/openclaw-dependency-review.test.ts`, and the E2E matrix for the PR head commit provide the acceptance evidence. This PR references rather than closes #5591 because the issue tracks the coordinated dependency set and release, not only the OpenClaw slice. +The integrity-pin regression is split by boundary: `test/openclaw-integrity-pin-base.test.ts` covers protected base provenance and archive filename confinement; `test/openclaw-integrity-pin-contract.test.ts` covers review-note and manifest pin alignment plus production build-argument ownership; and `test/openclaw-integrity-pin-plugin-install.test.ts` covers optional, core, and Codex ACP registry/download verification plus reviewed local-archive installation. + +Issue #5591 is the dependency-update umbrella, and its proposed design has three literal clauses. "Latest stable version of Hermes" is satisfied by merged PR #5594 (`hermes-agent==2026.6.19`); "Latest version of OpenShell" is satisfied by merged PR #5596 (`openshell==0.0.71`); and "Latest stable version of OpenClaw" is the clause owned by this PR. For that OpenClaw clause, the repository pins the reviewed non-prerelease `openclaw@2026.6.10` artifact and its plugin SRIs, while the integrity-pin suites, `test/openclaw-dependency-review.test.ts`, and the E2E matrix for the PR head commit provide the acceptance evidence. This PR references rather than closes #5591 because the issue tracks the coordinated dependency set and release, not only the OpenClaw slice. ## Package Identity @@ -102,7 +104,7 @@ The SRI-verified `openclaw@2026.6.10` artifact's `package/skills/weather/SKILL.m After `Dockerfile.base` completes the OpenClaw archive transaction and reviewed lifecycle, installs mcporter from the committed lock, checks both installed versions, and passes mcporter advisory and signature audits, it atomically publishes a root-owned, read-only provenance marker. The marker binds the OpenClaw package, SRI, tarball, and lifecycle recipe plus the mcporter package, SRI, lockfile SHA-256, and audited-install recipe. The production Dockerfile may reuse both installs only for an official NemoClaw base reference (or the resolver's local base name) when the marker is a non-symlink regular file with exact `root:root` ownership, mode `0444`, byte-for-byte content, and both installed versions match. It removes the marker before applying NemoClaw patches so a derived image cannot claim pristine-base provenance. Missing, malformed, writable, symlinked, mismatched, custom-base, stale, or incomplete provenance takes the complete reviewed install fallback; a base newer than the reviewed OpenClaw target remains a hard failure. -Invalid state: `npm view` returns the reviewed SRI but the downloaded artifact used for install has different bytes; `npm pack --json` reports a filename such as `../package.tgz`, `/tmp/package.tgz`, or a name containing path separators so the later install consumes a path outside the fresh pack directory; or the production image reuses OpenClaw or mcporter without every provenance, metadata, trusted-base, lock-hash, and installed-version check above. Source boundary: Dockerfile npm install and provenance blocks, `Dockerfile.base`, the committed mcporter lock, optional plugin install blocks, and `src/lib/messaging/applier/build/messaging-build-applier.mts`. Source-fix constraint: npm package installation must stay artifact-bound for reviewed pins rather than reverting to a later floating package-spec transaction, and local archive path validation must be enforced at NemoClaw's install boundary because npm's JSON filename is untrusted input. Regression test: `test/openclaw-integrity-pin.test.ts` exercises registry drift, reviewed tarball URL drift, local archive install behavior, unsafe reported archive filenames, exact OpenClaw/mcporter provenance reuse, fifteen fallback states, marker consumption, and newer-base rejection; `test/messaging-build-applier.test.ts` verifies messaging plugins run through `npm pack --json` and install the verified archive path; `test/messaging-build-applier-integrity.test.ts` verifies the messaging plugin install fails closed when packed archive integrity drifts or the reported archive filename escapes the pack directory. Removal condition: keep this archive verification and delegated-base provenance until the repo moves the OpenClaw/plugin dependency set to a lockfile path where npm enforces the committed SRI directly and no installer code consumes raw `npm pack --json` filenames. +Invalid state: `npm view` returns the reviewed SRI but the downloaded artifact used for install has different bytes; `npm pack --json` reports a filename such as `../package.tgz`, `/tmp/package.tgz`, or a name containing path separators so the later install consumes a path outside the fresh pack directory; or the production image reuses OpenClaw or mcporter without every provenance, metadata, trusted-base, lock-hash, and installed-version check above. Source boundary: Dockerfile npm install and provenance blocks, `Dockerfile.base`, the committed mcporter lock, optional plugin install blocks, and `src/lib/messaging/applier/build/messaging-build-applier.mts`. Source-fix constraint: npm package installation must stay artifact-bound for reviewed pins rather than reverting to a later floating package-spec transaction, and local archive path validation must be enforced at NemoClaw's install boundary because npm's JSON filename is untrusted input. Regression tests: the integrity-pin plugin-install suite exercises registry drift, reviewed tarball URL drift, downloaded archive verification, and reviewed local-archive installation; the integrity-pin base suite exercises unsafe reported archive filenames, exact OpenClaw/mcporter provenance reuse, fifteen fallback states, marker consumption, and newer-base rejection. `test/messaging-build-applier.test.ts` verifies messaging plugins run through `npm pack --json` and install the verified archive path; `test/messaging-build-applier-integrity.test.ts` verifies the messaging plugin install fails closed when packed archive integrity drifts or the reported archive filename escapes the pack directory. Removal condition: keep this archive verification and delegated-base provenance until the repo moves the OpenClaw/plugin dependency set to a lockfile path where npm enforces the committed SRI directly and no installer code consumes raw `npm pack --json` filenames. #### Reviewed npm Lifecycle Boundary @@ -126,7 +128,7 @@ Isolated `node:22-trixie-slim` containers globally installed the reviewed OpenCl Invalid state: any reviewed archive install can run package-controlled install hooks, a package other than an exact allowlisted OpenClaw version receives an explicit lifecycle invocation, or the allowed manifest command/path changes without review. Source boundary: the five Docker install transactions, `installOpenClawMessagingPlugins`, and `ci/reviewed-npm-lifecycle-allowlist.json`. Source-fix constraint: lifecycle suppression must remain caller-controlled even while OpenClaw's plugin installer independently applies the same policy; do not replace the fixed postinstall command with `npm rebuild`, `npm run` against an unverified package spec, or a blanket script enablement. -Regression tests: `test/openclaw-lifecycle-policy.test.ts` pins the complete reviewed package set and the two exact exceptions; `test/openclaw-integrity-pin.test.ts`, `test/fetch-guard-patch-regression.test.ts`, and `test/messaging-build-applier.test.ts` pin script suppression and the fixed postinstall command at the execution boundaries. +Regression tests: `test/openclaw-lifecycle-policy.test.ts` pins the complete reviewed package set and the two exact exceptions; the integrity-pin base and plugin-install suites, `test/fetch-guard-patch-regression.test.ts`, and `test/messaging-build-applier.test.ts` pin script suppression and the fixed postinstall command at the execution boundaries. Removal condition: re-audit manifests, shrinkwrap `hasInstallScript` entries, and native prebuild coverage on every OpenClaw/plugin bump; remove an exception when the reviewed package no longer needs it, and never carry an exception to a new version implicitly. #### Messaging Plugin Registry Provenance Boundary @@ -145,7 +147,7 @@ Removal condition: keep these provenance checks when issue #5896 consolidates th The four Docker shell boundaries (Codex ACP, runtime OpenClaw, base-image OpenClaw, and optional plugins) and the two-stage Node verifier shared by every messaging-plugin install deliberately keep the same install security matrix at their caller boundaries: exact reviewed package identity, registry SRI, reviewed registry tarball URL, packed-byte SRI, a nonempty basename contained in a fresh pack directory, install from the resolved local archive only, cleanup, and failure before install on any mismatch. Runtime OpenClaw either executes that full transaction or consumes the exact protected result of the base-image transaction under the bounded provenance checks above; it never substitutes a floating package-spec install. Runtime mcporter likewise either installs and audits the committed lock or consumes the marker-bound result of that exact locked and audited base-image transaction. -Invalid state: one local verifier drops a common invariant while the others retain it. Source boundary: the four Docker transactions plus `packVerifiedOpenClawPluginArchive`/`packNpmArchive`, which form one shared Node primitive for all messaging consumers. Source-fix constraint: consolidating shell build layers and a host-side Node installer changes every trusted install boundary together; issue #5896 section 2 requires that migration to retain thin caller wrappers and caller-specific regressions in one focused change. Regression tests: `test/openclaw-dependency-review.test.ts` names all five implementation boundaries and asserts the common invariant markers, fresh directories, cleanup, and local-archive-only install; `test/openclaw-integrity-pin.test.ts` and `test/messaging-build-applier-integrity.test.ts` execute drift and unsafe-filename failures at both execution environments. Removal condition: close this deferral only when #5896 section 2 replaces the local implementations with a reviewed shared implementation while retaining every caller-boundary regression. +Invalid state: one local verifier drops a common invariant while the others retain it. Source boundary: the four Docker transactions plus `packVerifiedOpenClawPluginArchive`/`packNpmArchive`, which form one shared Node primitive for all messaging consumers. Source-fix constraint: consolidating shell build layers and a host-side Node installer changes every trusted install boundary together; issue #5896 section 2 requires that migration to retain thin caller wrappers and caller-specific regressions in one focused change. Regression tests: `test/openclaw-dependency-review.test.ts` names all five implementation boundaries and asserts the common invariant markers, fresh directories, cleanup, and local-archive-only install; the integrity-pin base and plugin-install suites plus `test/messaging-build-applier-integrity.test.ts` execute drift and unsafe-filename failures at both execution environments. Removal condition: close this deferral only when #5896 section 2 replaces the local implementations with a reviewed shared implementation while retaining every caller-boundary regression. ### OpenClaw Compiled-Dist Patch Runtime Boundary @@ -176,9 +178,9 @@ The reviewed `@openclaw/diagnostics-otel@2026.6.10` package dist imports `OTLPTr ### Legacy Fixture Pins -The legacy `2026.3.11` and `2026.4.24` OpenClaw pins are retained only for stale-upgrade fixture builds. Production Dockerfile install blocks now reject those versions unless `NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1` is set explicitly. The E2E-scoped name is intentionally noisy so production build workflows do not treat it as a general override. Production image workflows run `scripts/check-production-build-args.sh` before production Docker builds so the fixture flag, both legacy version values, and every integrity/tarball Docker ARG declared by a production Dockerfile cannot be overridden through production build args or their corresponding environment variables. The guard also rejects future positional `*_INTEGRITY` and `*_TARBALL` names, keeping reviewed pin values repository-controlled even before the Dockerfile's registry and downloaded-archive checks run. The stale-upgrade E2E build contexts pass their fixture values only on fixture-specific build paths, and `test/openclaw-integrity-pin.test.ts` verifies the default rejection, the explicit fixture opt-in, and the production workflow guard. +The legacy `2026.3.11` and `2026.4.24` OpenClaw pins are retained only for stale-upgrade fixture builds. Production Dockerfile install blocks now reject those versions unless `NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1` is set explicitly. The E2E-scoped name is intentionally noisy so production build workflows do not treat it as a general override. Production image workflows run `scripts/check-production-build-args.sh` before production Docker builds so the fixture flag, both legacy version values, and every integrity/tarball Docker ARG declared by a production Dockerfile cannot be overridden through production build args or their corresponding environment variables. The guard also rejects future positional `*_INTEGRITY` and `*_TARBALL` names, keeping reviewed pin values repository-controlled even before the Dockerfile's registry and downloaded-archive checks run. The stale-upgrade E2E build contexts pass their fixture values only on fixture-specific build paths, and the integrity-pin contract suite verifies the default rejection, the explicit fixture opt-in, and the production workflow guard. -Invalid state: a production image build overriding `OPENCLAW_VERSION` to an old fixture pin or replacing any repository-reviewed integrity/tarball value while still passing the workflow boundary. Source boundary: Dockerfile and Dockerfile.base install blocks plus the guard that precedes every production image build. Source-fix constraint: keep stale-upgrade E2Es able to build old images without normalizing those pins or accepting caller-controlled production package identity. Regression tests: `test/openclaw-integrity-pin.test.ts` rejects the flag, both legacy versions, all declared integrity/tarball ARG overrides through direct, `--build-arg`, and environment paths, and a future-shaped positional pin name; `test/openclaw-dependency-review.test.ts` proves all seven production image builds are guard-protected and carry no literal fixture selectors. Removal condition: issue #5896 section 9 retires the old-base fixture strategy and fixture flag; the general repository-owned production pin guard remains until production builds no longer expose package identity as Docker ARGs. +Invalid state: a production image build overriding `OPENCLAW_VERSION` to an old fixture pin or replacing any repository-reviewed integrity/tarball value while still passing the workflow boundary. Source boundary: Dockerfile and Dockerfile.base install blocks plus the guard that precedes every production image build. Source-fix constraint: keep stale-upgrade E2Es able to build old images without normalizing those pins or accepting caller-controlled production package identity. Regression tests: the integrity-pin contract suite rejects the flag, both legacy versions, all declared integrity/tarball ARG overrides through direct, `--build-arg`, and environment paths, and a future-shaped positional pin name; `test/openclaw-dependency-review.test.ts` proves all seven production image builds are guard-protected and carry no literal fixture selectors. Removal condition: issue #5896 section 9 retires the old-base fixture strategy and fixture flag; the general repository-owned production pin guard remains until production builds no longer expose package identity as Docker ARGs. ### OpenClaw Device Approval Convergence Boundary @@ -292,4 +294,4 @@ No real Microsoft Teams tenant proof is included in this PR. The work remains tr - Retained older OpenClaw pins are inactive compatibility/rollback branches, not the production default. Before every production image build, the production guard rejects the fixture flag, both legacy version values, every declared integrity/tarball ARG override from positional or environment input, and future-shaped positional pin names; the Dockerfile then fails closed unless the selected version has its repository-owned SRI and reviewed tarball URL. Issue #5896 section 9 retires the fixture branch while the general production pin-ownership guard remains tied to the Docker ARG boundary. - The #4434 patch uses the SRI-verified `openclaw@2026.6.10` artifact, fails closed on unknown or ambiguous formatter shapes, and is applied/audited against the real distribution in CI. A second generated-file hash allowlist would duplicate the package SRI plus shape audit and is deferred unless a future patch can no longer identify one unambiguous formatter boundary. - Each OpenClaw `messaging-build-applier.mts --agent openclaw` Dockerfile phase receives `OPENCLAW_VERSION="${OPENCLAW_VERSION}"` from the Dockerfile build arg before rendering or installing messaging plugins. -- The integrity pin, messaging render-safety, and provider-recovery follow-ups are covered by `test/openclaw-integrity-pin.test.ts`, `test/messaging-build-applier-render-safety.test.ts`, and `test/onboard-resume-provider-recovery.test.ts`. +- The integrity pin, messaging render-safety, and provider-recovery follow-ups are covered by the integrity-pin suites, `test/messaging-build-applier-render-safety.test.ts`, and `test/onboard-resume-provider-recovery.test.ts`. diff --git a/package.json b/package.json index 8555ed054e5..95742b22844 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,10 @@ "test": "npm run clean:cli && npm --prefix nemoclaw run clean && npm run build:cli && npm --prefix nemoclaw run build && vitest run --project cli --project integration --project installer-integration --project package-contract --project plugin --project e2e-support", "test:spec": "npm test -- --reporter=tree", "test:fast": "npm run clean:cli && vitest run --project cli --project plugin --project e2e-support", + "test:changed": "vitest run --changed --project cli --project plugin --project e2e-support", + "test:watch": "vitest watch --project cli --project plugin --project e2e-support", + "test:shuffle": "vitest run --project cli --project plugin --project e2e-support --sequence.shuffle.tests --coverage=false", + "test:diagnose:leaks": "vitest run --project cli --project plugin --project e2e-support --detectAsyncLeaks --coverage=false --reporter=default --reporter=hanging-process", "test:integration": "npm run clean:cli && npm run build:cli && vitest run --project integration --project installer-integration", "test:package": "npm run clean:cli && npm --prefix nemoclaw run clean && npm run build:cli && npm --prefix nemoclaw run build && vitest run --project package-contract", "test:coverage:cli": "npm run clean:cli && npm run build:cli && tsx scripts/check-dist-sourcemaps.ts dist && vitest run --project cli --project integration --coverage --coverage.reporter=text-summary --coverage.reporter=json-summary --coverage.reportsDirectory=coverage/cli --coverage.include=\"bin/**/*.js\" --coverage.include=\"src/**/*.ts\" --coverage.exclude=\"test/**/*.js\" --coverage.exclude=\"test/**/*.ts\" && tsx scripts/check-coverage-ratchet.ts coverage/cli/coverage-summary.json ci/coverage-threshold-cli.json \"CLI coverage\"", diff --git a/test/cli-coverage-sequencer.test.ts b/test/cli-coverage-sequencer.test.ts index bb2aa07f127..c7c8bbcb176 100644 --- a/test/cli-coverage-sequencer.test.ts +++ b/test/cli-coverage-sequencer.test.ts @@ -86,8 +86,8 @@ describe("CLI coverage duration-aware sharding", () => { it("wires the measured hints into the Vitest sequencer", async () => { const specifications = [ - testSpecification("test/local-credential-helper.test.ts", "local-credentials"), - testSpecification("test/hermes-restart-config-seal.test.ts", "hermes-config"), + testSpecification("test/local-credential-helper-fields.test.ts", "local-credentials"), + testSpecification("test/hermes-restart-config-seal-write-lock.test.ts", "hermes-config"), ...Array.from({ length: 8 }, (_, index) => testSpecification(`test/regular-${index}.test.ts`, `regular-${index}`), ), diff --git a/test/helpers/hermes-restart-config-seal-fixture.ts b/test/helpers/hermes-restart-config-seal-fixture.ts new file mode 100644 index 00000000000..763208ad158 --- /dev/null +++ b/test/helpers/hermes-restart-config-seal-fixture.ts @@ -0,0 +1,241 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { expect } from "vitest"; + +export const RUNTIME_CONFIG_GUARD = path.join( + import.meta.dirname, + "..", + "..", + "agents", + "hermes", + "runtime-config-guard.py", +); + +export interface RestartFixture { + root: string; + sandboxDir: string; + hermesDir: string; + configPath: string; + envPath: string; + hashPath: string; + compatHashPath: string; + statePath: string; + trustedConfig: string; + trustedEnv: string; +} + +export function mode(pathname: string): number { + return fs.statSync(pathname).mode & 0o7777; +} + +export function readFileSnapshot(pathname: string): Buffer { + const fd = fs.openSync(pathname, "r"); + try { + return fs.readFileSync(fd); + } finally { + fs.closeSync(fd); + } +} + +export function readTextFileSnapshot(pathname: string): string { + return readFileSnapshot(pathname).toString("utf8"); +} + +export function hashInputs(configPath: string, envPath: string): string { + const result = spawnSync("sha256sum", [configPath, envPath], { + encoding: "utf-8", + timeout: 5000, + }); + expect(result.status, result.stderr).toBe(0); + const mcpDigest = createHash("sha256").update("{}").digest("hex"); + return `${result.stdout}# nemoclaw-hermes-mcp-state-v1 intended=${mcpDigest} applied=${mcpDigest}\n`; +} + +export function createRestartFixture(): RestartFixture { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-restart-seal-")); + const sandboxDir = path.join(root, "sandbox"); + const hermesDir = path.join(sandboxDir, ".hermes"); + const configPath = path.join(hermesDir, "config.yaml"); + const envPath = path.join(hermesDir, ".env"); + const hashPath = path.join(root, "hermes.config-hash"); + const compatHashPath = path.join(hermesDir, ".config-hash"); + const statePath = path.join(root, "hermes-restart-seal.json"); + const trustedConfig = "model:\n default: trusted-model\n"; + const trustedEnv = "API_SERVER_PORT=18642\nSAFE_SETTING=trusted\n"; + + fs.mkdirSync(hermesDir, { recursive: true }); + fs.chmodSync(sandboxDir, 0o770); + fs.chmodSync(hermesDir, 0o3770); + fs.writeFileSync(configPath, trustedConfig, { mode: 0o640 }); + fs.chmodSync(configPath, 0o640); + fs.writeFileSync(envPath, trustedEnv, { mode: 0o600 }); + fs.chmodSync(envPath, 0o600); + + const hash = hashInputs(configPath, envPath); + fs.writeFileSync(hashPath, hash, { mode: 0o600 }); + fs.writeFileSync(compatHashPath, hash, { mode: 0o600 }); + + return { + root, + sandboxDir, + hermesDir, + configPath, + envPath, + hashPath, + compatHashPath, + statePath, + trustedConfig, + trustedEnv, + }; +} + +export function runWriteConfig(fixture: RestartFixture, expectedDigest: string, content: string) { + return spawnSync( + "python3", + [ + RUNTIME_CONFIG_GUARD, + "write-config", + "--hermes-dir", + fixture.hermesDir, + "--hash-file", + fixture.hashPath, + "--state-file", + fixture.statePath, + "--expected-config-sha256", + expectedDigest, + ], + { encoding: "utf-8", input: content, timeout: 5000 }, + ); +} + +export function writeMutationLock(fixture: RestartFixture, token: string): string { + const lockPath = path.join(fixture.root, "hermes-config-mutation.lock"); + fs.writeFileSync( + lockPath, + `${JSON.stringify({ + version: 1, + token, + purpose: "seal-restart", + pid: 999_999_999, + pid_start_time: "1", + })}\n`, + { mode: 0o600 }, + ); + return lockPath; +} + +export function runGuard(action: "seal-restart" | "unseal-restart", fixture: RestartFixture) { + const args = [ + RUNTIME_CONFIG_GUARD, + action, + "--hermes-dir", + fixture.hermesDir, + "--state-file", + fixture.statePath, + ]; + args.push(...(action === "seal-restart" ? ["--hash-file", fixture.hashPath] : [])); + return spawnSync("python3", args, { + encoding: "utf-8", + timeout: 5000, + }); +} + +export function runShieldsTransition(fixture: RestartFixture, shieldsMode: "locked" | "mutable") { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: shieldsMode, + }); + switch (begun.status) { + case 0: + break; + default: + return begun; + } + const token = shieldsTransactionToken(begun.stdout); + switch (token) { + case undefined: + throw new Error("Expected begin-shields-transition to emit a token"); + default: + break; + } + switch (shieldsMode) { + case "locked": + // The production host restores 0755 only after the recursive state guard's + // independent verification pass. This focused top-guard fixture has no + // recursive state, so model that successful handoff explicitly. + fs.chmodSync(fixture.hermesDir, 0o755); + break; + case "mutable": + break; + } + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + switch (applied.status) { + case 0: + break; + default: + return applied; + } + return runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); +} + +export function runShieldsTransactionAction( + fixture: RestartFixture, + action: + | "begin-shields-transition" + | "apply-shields-transition" + | "finish-shields-transition" + | "prepare-shields-abort" + | "abort-shields-transition" + | "inspect-mutation-owner", + options: { + mode?: "locked" | "mutable"; + rollbackMode?: "locked" | "mutable"; + token?: string; + } = {}, +) { + const args = [ + RUNTIME_CONFIG_GUARD, + action, + "--hermes-dir", + fixture.hermesDir, + "--state-file", + fixture.statePath, + ]; + args.push( + ...(action === "begin-shields-transition" || action === "finish-shields-transition" + ? ["--hash-file", fixture.hashPath] + : []), + ...(options.mode ? ["--shields-mode", options.mode] : []), + ...(options.rollbackMode ? ["--rollback-shields-mode", options.rollbackMode] : []), + ...(options.token ? ["--lock-token", options.token] : []), + ); + return spawnSync("python3", args, { encoding: "utf-8", timeout: 5000 }); +} + +export function strictHashIsValid(fixture: RestartFixture): boolean { + return ( + spawnSync("sha256sum", ["-c", fixture.hashPath, "--status"], { + encoding: "utf-8", + timeout: 5000, + }).status === 0 + ); +} + +export function shieldsTransactionToken(output: string): string | undefined { + return /^lock_token=([0-9a-f]{64}) original_locked=[01]\s*$/.exec(output)?.[1]; +} + +export function overwriteThroughOldFd(fd: number, originalSize: number, byte: string): void { + const attackerBytes = Buffer.alloc(originalSize, byte); + fs.writeSync(fd, attackerBytes, 0, attackerBytes.length, 0); + fs.fsyncSync(fd); +} diff --git a/test/helpers/onboard-split-context.ts b/test/helpers/onboard-split-context.ts new file mode 100644 index 00000000000..2afd238e83a --- /dev/null +++ b/test/helpers/onboard-split-context.ts @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import path from "node:path"; + +import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; +import { createDirectSetupInferenceHarnessFactory } from "../support/setup-inference-test-harness.js"; + +export type ShimScalar = string | number | boolean | null | undefined; +export type ShimCallable = (...args: readonly string[]) => ShimValue; +export type ShimValue = ShimScalar | { [key: string]: ShimValue } | ShimValue[] | ShimCallable; +export type ShimFn = (...args: ShimValue[]) => TReturn; +export type CommandEntry = { + command: string; + env?: Record; + ignoreError?: boolean; + policyContent?: string; + policyReadError?: string; + dockerfileContent?: string; + dockerfileReadError?: string; +}; +export type ResumeConflict = { + field: string; + requested: string | null; + recorded: string | null; +}; +export type OnboardTestInternals = { + getNavigationChoice: (value?: string | null) => string | null; + getFutureShellPathHint: (binDir: string, pathValue?: string) => string | null; + getRequestedModelHint: ShimFn; + getRequestedProviderHint: ShimFn; + getRequestedSandboxNameHint: ShimFn; + getResumeConfigConflicts: ShimFn; + getResumeSandboxConflict: ShimFn<{ + requestedSandboxName: string; + recordedSandboxName: string; + } | null>; + clearAgentScopedResumeState: >( + session: T, + selectedAgentName: string, + ) => T; + pullAndResolveBaseImageDigest: () => { digest: string | null; ref: string } | null; + createSetupInference: (overrides?: Partial) => SetupInference; + SANDBOX_BASE_IMAGE: string; +}; + +export function parseStdoutJson(stdout: string): T { + const line = stdout.trim().split("\n").pop(); + assert.ok(line, `expected JSON payload in stdout:\n${stdout}`); + return JSON.parse(line); +} + +export function stripMessagingEnv(source: NodeJS.ProcessEnv): Record { + const env = { ...source } as Record; + for (const key of Object.keys(env)) { + if (key.startsWith("DISCORD_") || key.startsWith("TELEGRAM_")) { + delete env[key]; + } + } + return env; +} + +type OnboardTestInternalsCandidate = Partial | null; + +function isOnboardTestInternals( + value: OnboardTestInternalsCandidate, +): value is OnboardTestInternals { + return value !== null && typeof value.getNavigationChoice === "function"; +} + +const loadedOnboardInternals = require("../../src/lib/onboard"); +const onboardTestInternals = + typeof loadedOnboardInternals === "object" && loadedOnboardInternals !== null + ? loadedOnboardInternals + : null; +if (!isOnboardTestInternals(onboardTestInternals)) { + throw new Error("Expected onboard test internals to expose helper functions"); +} + +export const { + getNavigationChoice, + getFutureShellPathHint, + getRequestedModelHint, + getRequestedProviderHint, + getRequestedSandboxNameHint, + getResumeConfigConflicts, + getResumeSandboxConflict, + clearAgentScopedResumeState, + createSetupInference, + SANDBOX_BASE_IMAGE, +} = onboardTestInternals; + +export const bedrockRuntimeOnboard = + require("../../src/lib/onboard/bedrock-runtime") as typeof import("../../src/lib/onboard/bedrock-runtime.js"); +export const createDirectSetupInferenceHarness = + createDirectSetupInferenceHarnessFactory(createSetupInference); + +export const repoRoot = path.join(import.meta.dirname, "../.."); +export const onboardScriptMocksPath = JSON.stringify( + path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), +); diff --git a/test/helpers/vitest-feedback.ts b/test/helpers/vitest-feedback.ts new file mode 100644 index 00000000000..c45d000e65a --- /dev/null +++ b/test/helpers/vitest-feedback.ts @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export type VitestFeedback = { + isCi: boolean; + silent: false | "passed-only"; +}; + +export function resolveVitestFeedback( + environment: NodeJS.ProcessEnv = process.env, +): VitestFeedback { + const isCi = + environment.GITHUB_ACTIONS === "true" || environment.CI === "true" || environment.CI === "1"; + return { isCi, silent: isCi ? "passed-only" : false }; +} diff --git a/test/helpers/vitest-npm-script.ts b/test/helpers/vitest-npm-script.ts new file mode 100644 index 00000000000..3e983d256a0 --- /dev/null +++ b/test/helpers/vitest-npm-script.ts @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +import type { OwnedTestResources } from "./owned-test-resources"; + +export function runVitestNpmScript( + resources: OwnedTestResources, + script: string, + extraArguments: string[] = [], +): string { + const npmCli = process.env.npm_execpath; + if (!npmCli) throw new Error("npm_execpath is required to exercise npm script dispatch"); + const fixtureRoot = resources.temporaryDirectory("nemoclaw-vitest-feedback-"); + const fakeBin = path.join(fixtureRoot, "bin"); + const commandLog = path.join(fixtureRoot, "commands.log"); + const scriptShell = path.join(fixtureRoot, "script-shell"); + fs.mkdirSync(fakeBin); + fs.writeFileSync( + path.join(fakeBin, "vitest"), + '#!/bin/sh\nprintf \'vitest %s\\n\' "$*" > "$COMMAND_LOG"\n', + { mode: 0o755 }, + ); + fs.writeFileSync( + scriptShell, + `#!/bin/sh\nPATH="$FAKE_BIN:${path.dirname(process.execPath)}:/usr/bin:/bin"\nexport PATH\nexec /bin/sh "$@"\n`, + { mode: 0o755 }, + ); + + const result = spawnSync(process.execPath, [npmCli, "run", script, ...extraArguments], { + cwd: process.cwd(), + encoding: "utf8", + env: { + ...process.env, + COMMAND_LOG: commandLog, + FAKE_BIN: fakeBin, + npm_config_script_shell: scriptShell, + }, + }); + if (result.status !== 0) { + throw new Error(result.stderr || result.stdout || `${script} exited ${result.status}`); + } + return fs.readFileSync(commandLog, "utf8").trim(); +} diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts new file mode 100644 index 00000000000..83f80db0261 --- /dev/null +++ b/test/helpers/vitest-watch-triggers.ts @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export type VitestWatchTriggerPattern = { + pattern: RegExp; + testsToRun: (file: string, match: RegExpMatchArray) => string[]; +}; + +const E2E_WORKFLOW_CONTRACTS = [ + "test/e2e/support/channels-add-remove-workflow-boundary.test.ts", + "test/e2e/support/dcode-profile-import-gate-workflow-boundary.test.ts", + "test/e2e/support/dockerhub-auth-workflow-boundary.test.ts", + "test/e2e/support/e2e-host-dependency-workflow-boundary.test.ts", + "test/e2e/support/e2e-operations-workflow-boundary.test.ts", + "test/e2e/support/e2e-report-to-pr-workflow-boundary.test.ts", + "test/e2e/support/e2e-workflow.test.ts", + "test/e2e/support/e2e-workflow-trace.test.ts", + "test/e2e/support/gateway-guard-workflow-boundary.test.ts", + "test/e2e/support/hermes-dashboard-workflow-boundary.test.ts", + "test/e2e/support/hermes-workflow-boundary.test.ts", + "test/e2e/support/inference-switch-workflow-boundary.test.ts", + "test/e2e/support/jetson-workflow-boundary.test.ts", + "test/e2e/support/mcp-workflow-boundary.test.ts", + "test/e2e/support/mcp-workflow-compatibility.test.ts", + "test/e2e/support/openclaw-discord-workflow-boundary.test.ts", + "test/e2e/support/openclaw-plugin-runtime-exdev-workflow-boundary.test.ts", + "test/e2e/support/openclaw-slack-workflow-boundary.test.ts", + "test/e2e/support/openshell-gateway-auth-contract-workflow-boundary.test.ts", + "test/e2e/support/openshell-gateway-upgrade-workflow-boundary.test.ts", + "test/e2e/support/overlayfs-autofix-workflow-boundary.test.ts", + "test/e2e/support/prepare-e2e-workflow-boundary.test.ts", + "test/e2e/support/rlimit-connect-workflow-boundary.test.ts", + "test/e2e/support/sandbox-images-workflow-boundary.test.ts", + "test/e2e/support/sandbox-operations-workflow-boundary.test.ts", + "test/e2e/support/security-posture-workflow-boundary.test.ts", + "test/e2e/support/shared-e2e-workflow-boundary.test.ts", + "test/e2e/support/spark-install-workflow-boundary.test.ts", + "test/e2e/support/tunnel-lifecycle-workflow-boundary.test.ts", + "test/e2e/support/upload-e2e-artifacts-workflow-boundary.test.ts", + "test/e2e/support/workflow-plan.test.ts", +] as const; + +function runTests(...tests: string[]): () => string[] { + return () => [...tests]; +} + +export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ + { + pattern: /(?:^|\/)agents\/hermes\/policy-additions\.yaml$/, + testsToRun: runTests( + "src/lib/onboard/initial-policy-real-policy.test.ts", + "src/lib/onboard/initial-policy.test.ts", + ), + }, + { + pattern: /(?:^|\/)src\/lib\/messaging\/channels\/[^/]+\/policy\/(?:hermes|openclaw)\.yaml$/, + testsToRun: runTests("src/lib/messaging/channels/policy.test.ts"), + }, + { + pattern: /(?:^|\/)nemoclaw-blueprint\/policies\/presets\/local-inference\.yaml$/, + testsToRun: runTests( + "src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts", + ), + }, + { + pattern: /(?:^|\/)agents\/hermes\/(?:mcp-config-transaction|runtime-config-guard)\.py$/, + testsToRun: runTests("src/lib/actions/sandbox/gateway-restart-hermes-drift.test.ts"), + }, + { + pattern: /(?:^|\/)test\/e2e\/lib\/ci-compatible-inference\.sh$/, + testsToRun: runTests("test/e2e/support/hosted-inference.test.ts"), + }, + { + pattern: /(?:^|\/)scripts\/e2e\/sanitize-trace-timing\.py$/, + testsToRun: runTests( + "test/e2e/support/e2e-scorecard.test.ts", + "test/e2e/support/sanitize-trace-timing.test.ts", + ), + }, + { + pattern: /(?:^|\/)test\/e2e\/manifests\/[^/]+\.yaml$/, + testsToRun: runTests("test/e2e/support/e2e-manifests.test.ts"), + }, + { + pattern: /(?:^|\/)test\/e2e\/docs\/parity-inventory\.generated\.json$/, + testsToRun: runTests("test/e2e/support/e2e-migration-policy.test.ts"), + }, + { + pattern: /(?:^|\/)\.github\/workflows\/e2e\.yaml$/, + testsToRun: runTests(...E2E_WORKFLOW_CONTRACTS), + }, +]; + +export function resolveVitestWatchTests(file: string): string[] { + const normalized = file.replaceAll("\\", "/"); + const tests = new Set(); + for (const trigger of vitestWatchTriggerPatterns) { + const match = trigger.pattern.exec(normalized); + if (!match) continue; + for (const test of trigger.testsToRun(normalized, match)) tests.add(test); + } + return [...tests]; +} diff --git a/test/hermes-restart-config-seal-hostile-input.test.ts b/test/hermes-restart-config-seal-hostile-input.test.ts new file mode 100644 index 00000000000..48be1a82176 --- /dev/null +++ b/test/hermes-restart-config-seal-hostile-input.test.ts @@ -0,0 +1,192 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + createRestartFixture, + mode, + readTextFileSnapshot, + runShieldsTransactionAction, + shieldsTransactionToken, +} from "./helpers/hermes-restart-config-seal-fixture"; + +describe.skipIf(process.platform === "win32")("Hermes mutable restart input seal", () => { + for (const oversizedName of ["config.yaml", ".env"] as const) { + it(`contains an oversized sparse ${oversizedName} without reading its logical payload`, () => { + const fixture = createRestartFixture(); + const oversizedPath = oversizedName === "config.yaml" ? fixture.configPath : fixture.envPath; + fs.truncateSync( + oversizedPath, + oversizedName === "config.yaml" ? 16 * 1024 * 1024 + 1 : 4 * 1024 * 1024 + 1, + ); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(true); + expect(transition.shields_transition.unavailable_reasons.join("\n")).toContain( + "oversized runtime config path", + ); + expect(fs.statSync(oversizedPath).size).toBeLessThan(1024); + expect(mode(oversizedPath)).toBe(0o400); + expect(mode(fixture.hermesDir)).toBe(0o500); + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + } + + it("fresh-seals a hardlinked input and revokes the external writable inode", () => { + const fixture = createRestartFixture(); + const external = path.join(fixture.root, "external-config"); + fs.unlinkSync(fixture.configPath); + fs.writeFileSync(external, fixture.trustedConfig, { mode: 0o666 }); + fs.linkSync(external, fixture.configPath); + const externalFd = fs.openSync(external, "r+"); + const linkedInode = fs.fstatSync(externalFd).ino; + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(fs.statSync(fixture.configPath).ino).not.toBe(linkedInode); + expect(fs.statSync(fixture.configPath).nlink).toBe(1); + expect( + JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")).shields_transition.unavailable, + ).toBe(false); + fs.ftruncateSync(externalFd, 0); + fs.writeSync(externalFd, "attacker rewrite\n", 0, "utf8"); + fs.fsyncSync(externalFd); + expect(readTextFileSnapshot(fixture.configPath)).toBe(fixture.trustedConfig); + + fs.chmodSync(fixture.hermesDir, 0o755); + expect( + runShieldsTransactionAction(fixture, "apply-shields-transition", { token }).status, + ).toBe(0); + expect( + runShieldsTransactionAction(fixture, "finish-shields-transition", { token }).status, + ).toBe(0); + } finally { + fs.closeSync(externalFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + for (const hostileKind of ["symlink", "fifo"] as const) { + it(`seals a hostile ${hostileKind} config entry into a root-only unavailable posture`, () => { + const fixture = createRestartFixture(); + fs.unlinkSync(fixture.configPath); + const arrangeHostileConfig = { + symlink: () => { + const victim = path.join(fixture.root, "victim"); + fs.writeFileSync(victim, "victim stays untouched\n"); + fs.symlinkSync(victim, fixture.configPath); + }, + fifo: () => expect(spawnSync("mkfifo", [fixture.configPath]).status).toBe(0), + } satisfies Record void>; + arrangeHostileConfig[hostileKind](); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(true); + expect(fs.lstatSync(fixture.configPath).isFile()).toBe(true); + expect(mode(fixture.configPath)).toBe(0o400); + expect(mode(fixture.hermesDir)).toBe(0o500); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status).not.toBe(0); + expect(applied.stderr).toContain("sealed root-only and is unavailable"); + expect(mode(fixture.sandboxDir)).toBe(0o700); + expect(mode(fixture.hermesDir)).toBe(0o500); + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + } + + for (const hostileKind of ["symlink", "fifo"] as const) { + it(`quarantines an outer .hermes ${hostileKind} only after freezing /sandbox`, () => { + const fixture = createRestartFixture(); + fs.rmSync(fixture.hermesDir, { recursive: true, force: true }); + const victim = path.join(fixture.root, "outer-victim"); + const arrangeHostileHome = { + symlink: () => { + fs.mkdirSync(victim); + fs.writeFileSync(path.join(victim, "proof"), "untouched\n"); + fs.symlinkSync(victim, fixture.hermesDir); + }, + fifo: () => expect(spawnSync("mkfifo", [fixture.hermesDir]).status).toBe(0), + } satisfies Record void>; + arrangeHostileHome[hostileKind](); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + expect(fs.lstatSync(fixture.hermesDir).isDirectory()).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o700); + expect(mode(fixture.hermesDir)).toBe(0o500); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(true); + for (const proofPath of hostileKind === "symlink" ? [path.join(victim, "proof")] : []) { + expect(fs.readFileSync(proofPath, "utf-8")).toBe("untouched\n"); + } + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + } + + it("re-seals an applied mutable transition before recursive rollback", () => { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "mutable", + rollbackMode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(mode(fixture.hermesDir)).toBe(0o700); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { token }); + expect(applied.status, applied.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o3770); + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { token }); + expect(prepared.status, prepared.stderr).toBe(0); + const abortState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(abortState.shields_transition.mode).toBe("locked"); + expect(mode(fixture.hermesDir)).toBe(0o700); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { token }); + expect(aborted.status, aborted.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/hermes-restart-config-seal-recovery.test.ts b/test/hermes-restart-config-seal-recovery.test.ts new file mode 100644 index 00000000000..5615f5f772d --- /dev/null +++ b/test/hermes-restart-config-seal-recovery.test.ts @@ -0,0 +1,350 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + createRestartFixture, + mode, + overwriteThroughOldFd, + readTextFileSnapshot, + runGuard, + runShieldsTransactionAction, + runShieldsTransition, + shieldsTransactionToken, + strictHashIsValid, +} from "./helpers/hermes-restart-config-seal-fixture"; + +describe.skipIf(process.platform === "win32")("Hermes mutable restart input seal", () => { + it.runIf( + process.platform === "linux" && + process.getuid?.() === 0 && + spawnSync("setpriv", ["--version"], { encoding: "utf-8" }).status === 0, + )("keeps the locked Hermes entry sticky-protected while allowing ordinary home writes", () => { + const fixture = createRestartFixture(); + + try { + const locked = runShieldsTransition(fixture, "locked"); + expect(locked.status, locked.stderr).toBe(0); + const parent = fs.statSync(fixture.sandboxDir); + expect(parent.uid).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(fs.statSync(fixture.hermesDir).uid).toBe(0); + + const peer = spawnSync( + "setpriv", + [ + "--reuid=65534", + "--regid=65534", + `--groups=${String(parent.gid)}`, + "sh", + "-c", + 'touch "$1/peer-home-file" || exit 10; mv "$1/.hermes" "$1/.hermes-moved" 2>/dev/null && exit 20; test -d "$1/.hermes"', + "sh", + fixture.sandboxDir, + ], + { encoding: "utf-8", timeout: 5000 }, + ); + + expect(peer.status, peer.stderr).toBe(0); + expect(fs.existsSync(path.join(fixture.sandboxDir, "peer-home-file"))).toBe(true); + expect(fs.existsSync(fixture.hermesDir)).toBe(true); + expect(fs.existsSync(path.join(fixture.sandboxDir, ".hermes-moved"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses to finish after the sealed Hermes directory is swapped", () => { + const fixture = createRestartFixture(); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + + const displaced = path.join(fixture.sandboxDir, ".hermes.displaced"); + fs.renameSync(fixture.hermesDir, displaced); + fs.mkdirSync(fixture.hermesDir, { mode: 0o755 }); + + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status).not.toBe(0); + expect(finished.stderr).toContain("refusing shields finish because .hermes changed"); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o755); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("keeps the transaction sealed when abort finds a corrupted compatibility hash", () => { + const fixture = createRestartFixture(); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + + fs.unlinkSync(fixture.compatHashPath); + fs.writeFileSync(fixture.compatHashPath, "attacker-controlled hash\n", { mode: 0o444 }); + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + + expect(aborted.status).not.toBe(0); + expect(aborted.stderr).toContain("compat hash verification failed"); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + true, + ); + expect(mode(fixture.sandboxDir)).toBe(0o700); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("revokes descriptors opened after mutable apply before rolling back to locked", () => { + const fixture = createRestartFixture(); + fs.chmodSync(fixture.sandboxDir, 0o1775); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + let mutableFd: number | undefined; + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "mutable", + rollbackMode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + expect(begun.stdout).toContain("original_locked=1"); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + mutableFd = fs.openSync(fixture.configPath, "r+"); + const appliedInode = fs.fstatSync(mutableFd).ino; + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + expect(fs.statSync(fixture.configPath).ino).not.toBe(appliedInode); + + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + expect(aborted.status, aborted.stderr).toBe(0); + fs.writeSync(mutableFd, Buffer.from("PWNED!"), 0, 6, 0); + fs.fsyncSync(mutableFd); + + expect(readTextFileSnapshot(fixture.configPath)).toBe(fixture.trustedConfig); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + for (const openFd of mutableFd === undefined ? [] : [mutableFd]) fs.closeSync(openFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("rejects a foreign shields token and lets the owner abort to the exact prior posture", () => { + const fixture = createRestartFixture(); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + + const foreign = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token: randomBytes(32).toString("hex"), + }); + expect(foreign.status).not.toBe(0); + expect(foreign.stderr).toContain("lock token mismatch"); + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + expect(aborted.status, aborted.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o640); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.chmodSync(fixture.sandboxDir, 0o700); + fs.chmodSync(fixture.hermesDir, 0o700); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("fails closed without replacing or locking paths when the strict hash is stale", () => { + const fixture = createRestartFixture(); + const configFd = fs.openSync(fixture.configPath, "r+"); + const configBefore = fs.fstatSync(configFd); + const envBefore = fs.statSync(fixture.envPath); + try { + fs.ftruncateSync(configFd, 0); + fs.writeSync(configFd, "model:\n default: attacker-model\n", 0, "utf8"); + fs.fsyncSync(configFd); + } finally { + fs.closeSync(configFd); + } + + try { + const sealed = runGuard("seal-restart", fixture); + + expect(sealed.status).not.toBe(0); + expect(sealed.stderr).toContain("strict hash verification failed"); + expect(fs.statSync(fixture.configPath).ino).toBe(configBefore.ino); + expect(fs.statSync(fixture.envPath).ino).toBe(envBefore.ino); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o600); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("does not bless a compat hash changed through a pre-open descriptor", () => { + const fixture = createRestartFixture(); + const compatFd = fs.openSync(fixture.compatHashPath, "r+"); + const compatBefore = fs.fstatSync(compatFd); + + try { + overwriteThroughOldFd(compatFd, compatBefore.size, "Z"); + const sealed = runGuard("seal-restart", fixture); + + expect(sealed.status).not.toBe(0); + expect(sealed.stderr).toContain("compat hash verification failed"); + expect(strictHashIsValid(fixture)).toBe(true); + expect(readTextFileSnapshot(fixture.compatHashPath)).not.toBe( + readTextFileSnapshot(fixture.hashPath), + ); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.closeSync(compatFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("preserves an already trusted shields-up directory posture across seal and unseal", () => { + const fixture = createRestartFixture(); + fs.chmodSync(fixture.sandboxDir, 0o755); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + const configBefore = fs.statSync(fixture.configPath); + const envBefore = fs.statSync(fixture.envPath); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore.ino); + expect(fs.statSync(fixture.envPath).ino).not.toBe(envBefore.ino); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(fs.statSync(fixture.hermesDir).uid).toBe(process.getuid!()); + expect(strictHashIsValid(fixture)).toBe(true); + + const unsealed = runGuard("unseal-restart", fixture); + expect(unsealed.status, unsealed.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it.runIf( + process.platform === "linux" && + process.getuid?.() === 0 && + spawnSync("setpriv", ["--version"], { encoding: "utf-8" }).status === 0, + )("lets a sandbox-group peer create state but not unlink sealed config names", () => { + const fixture = createRestartFixture(); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + + const hermesGid = fs.statSync(fixture.hermesDir).gid; + const peer = spawnSync( + "setpriv", + [ + "--reuid=65534", + "--regid=65534", + `--groups=${hermesGid}`, + "sh", + "-c", + 'touch "$1/peer-runtime-state" || exit 10; rm "$1/config.yaml" 2>/dev/null && exit 20; test -f "$1/config.yaml"', + "sh", + fixture.hermesDir, + ], + { encoding: "utf-8", timeout: 5000 }, + ); + + expect(peer.status, peer.stderr).toBe(0); + expect(fs.existsSync(path.join(fixture.hermesDir, "peer-runtime-state"))).toBe(true); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + + const unsealed = runGuard("unseal-restart", fixture); + expect(unsealed.status, unsealed.stderr).toBe(0); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/hermes-restart-config-seal-transition.test.ts b/test/hermes-restart-config-seal-transition.test.ts new file mode 100644 index 00000000000..d8922d6e92a --- /dev/null +++ b/test/hermes-restart-config-seal-transition.test.ts @@ -0,0 +1,409 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + createRestartFixture, + mode, + overwriteThroughOldFd, + readFileSnapshot, + readTextFileSnapshot, + runGuard, + runShieldsTransactionAction, + runShieldsTransition, + runWriteConfig, + shieldsTransactionToken, + strictHashIsValid, +} from "./helpers/hermes-restart-config-seal-fixture"; + +describe.skipIf(process.platform === "win32")("Hermes mutable restart input seal", () => { + it("revokes pre-open writable fds while preserving trusted path bytes and strict hashes", () => { + const fixture = createRestartFixture(); + const configFd = fs.openSync(fixture.configPath, "r+"); + const envFd = fs.openSync(fixture.envPath, "r+"); + const configBefore = fs.fstatSync(configFd); + const envBefore = fs.fstatSync(envFd); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + + const configSealed = fs.statSync(fixture.configPath); + const envSealed = fs.statSync(fixture.envPath); + expect(configSealed.ino).not.toBe(configBefore.ino); + expect(envSealed.ino).not.toBe(envBefore.ino); + expect(configSealed.uid).toBe(process.getuid!()); + expect(envSealed.uid).toBe(process.getuid!()); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(configSealed.uid).toBe(fs.statSync(fixture.hermesDir).uid); + expect(envSealed.uid).toBe(fs.statSync(fixture.hermesDir).uid); + expect(mode(fixture.statePath)).toBe(0o600); + expect(strictHashIsValid(fixture)).toBe(true); + + overwriteThroughOldFd(configFd, configBefore.size, "X"); + overwriteThroughOldFd(envFd, envBefore.size, "Y"); + + expect(readTextFileSnapshot(fixture.configPath)).toBe(fixture.trustedConfig); + expect(readTextFileSnapshot(fixture.envPath)).toBe(fixture.trustedEnv); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.statSync(fixture.configPath).ino).toBe(configSealed.ino); + expect(fs.statSync(fixture.envPath).ino).toBe(envSealed.ino); + + const unsealed = runGuard("unseal-restart", fixture); + expect(unsealed.status, unsealed.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o600); + expect(fs.statSync(fixture.configPath).uid).toBe(configBefore.uid); + expect(fs.statSync(fixture.configPath).gid).toBe(configBefore.gid); + expect(fs.statSync(fixture.envPath).uid).toBe(envBefore.uid); + expect(fs.statSync(fixture.envPath).gid).toBe(envBefore.gid); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(readTextFileSnapshot(fixture.configPath)).toBe(fixture.trustedConfig); + expect(readTextFileSnapshot(fixture.envPath)).toBe(fixture.trustedEnv); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + fs.closeSync(configFd); + fs.closeSync(envFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("revokes pre-open descriptors across shields lock and restores the mutable contract", () => { + const fixture = createRestartFixture(); + const configFd = fs.openSync(fixture.configPath, "r+"); + const envFd = fs.openSync(fixture.envPath, "r+"); + const compatFd = fs.openSync(fixture.compatHashPath, "r+"); + const configBefore = fs.fstatSync(configFd); + const envBefore = fs.fstatSync(envFd); + const compatBefore = fs.fstatSync(compatFd); + + try { + const locked = runShieldsTransition(fixture, "locked"); + expect(locked.status, locked.stderr).toBe(0); + expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore.ino); + expect(fs.statSync(fixture.envPath).ino).not.toBe(envBefore.ino); + expect(fs.statSync(fixture.compatHashPath).ino).not.toBe(compatBefore.ino); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(mode(fixture.compatHashPath)).toBe(0o444); + + overwriteThroughOldFd(configFd, configBefore.size, "X"); + overwriteThroughOldFd(envFd, envBefore.size, "Y"); + overwriteThroughOldFd(compatFd, compatBefore.size, "Z"); + expect(readTextFileSnapshot(fixture.configPath)).toBe(fixture.trustedConfig); + expect(readTextFileSnapshot(fixture.envPath)).toBe(fixture.trustedEnv); + expect(strictHashIsValid(fixture)).toBe(true); + + const mutable = runShieldsTransition(fixture, "mutable"); + expect(mutable.status, mutable.stderr).toBe(0); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o640); + expect(mode(fixture.compatHashPath)).toBe(0o640); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + false, + ); + } finally { + fs.closeSync(configFd); + fs.closeSync(envFd); + fs.closeSync(compatFd); + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("holds the mutation lock through begin, apply, verification, and finish", () => { + const fixture = createRestartFixture(); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + true, + ); + expect(mode(fixture.sandboxDir)).toBe(0o700); + expect(mode(fixture.hermesDir)).toBe(0o500); + + const owner = runShieldsTransactionAction(fixture, "inspect-mutation-owner"); + expect(owner.status, owner.stderr).toBe(0); + expect(owner.stdout).toContain("owner_active=1"); + expect(owner.stdout).toContain("recovery_safe=0"); + + const competingRestart = runGuard("seal-restart", fixture); + expect(competingRestart.status).not.toBe(0); + expect(competingRestart.stderr).toContain("restart seal is already active"); + const competingWrite = runWriteConfig( + fixture, + expectedDigest, + "model:\n default: must-not-interleave\n", + ); + expect(competingWrite.status).not.toBe(0); + expect(competingWrite.stderr).toContain("restart seal is already active"); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + expect(applied.stdout).toContain("shields_mode=locked"); + expect(fs.existsSync(fixture.statePath)).toBe(true); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + true, + ); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.sandboxDir)).toBe(0o755); + + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( + false, + ); + expect(mode(fixture.sandboxDir)).toBe(0o1775); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("keeps weakening fan-out inaccessible and keeps monotonic lock fan-out readable", () => { + for (const targetMode of ["mutable", "locked"] as const) { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: targetMode, + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(mode(fixture.hermesDir)).toBe(targetMode === "mutable" ? 0o700 : 0o500); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { + token, + }); + expect(prepared.status, prepared.stderr).toBe(0); + const abortState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(abortState.shields_transition.mode).toBe("mutable"); + // State-dir rollback is another recursive transition. It remains + // root-only until abort commits the original posture. + expect(mode(fixture.hermesDir)).toBe(0o700); + expect(mode(fixture.sandboxDir)).toBe(0o700); + + const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { + token, + }); + expect(aborted.status, aborted.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o3770); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + } + }); + + it("retains the 0500 recursive clamp and resumes the same lock transaction", () => { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + expect(mode(fixture.hermesDir)).toBe(0o500); + + const premature = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(premature.status).not.toBe(0); + expect(premature.stderr).toContain("retaining root-only 0500 clamp for retry"); + expect(mode(fixture.hermesDir)).toBe(0o500); + expect(fs.existsSync(fixture.statePath)).toBe(true); + + const resumed = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(resumed.status, resumed.stderr).toBe(0); + expect(shieldsTransactionToken(resumed.stdout)).toBe(token); + expect(mode(fixture.hermesDir)).toBe(0o500); + + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o755); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("cold-resumes an applied lock transaction before its final commit", () => { + const fixture = createRestartFixture(); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + fs.chmodSync(fixture.hermesDir, 0o755); + const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(applied.status, applied.stderr).toBe(0); + + const resumed = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(resumed.status, resumed.stderr).toBe(0); + expect(shieldsTransactionToken(resumed.stdout)).toBe(token); + expect(mode(fixture.hermesDir)).toBe(0o500); + fs.chmodSync(fixture.hermesDir, 0o755); + const reapplied = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token, + }); + expect(reapplied.status, reapplied.stderr).toBe(0); + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(mode(fixture.hermesDir)).toBe(0o755); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("takes over an expired applied mutable transition only after its worker lease ends", () => { + const fixture = createRestartFixture(); + fs.chmodSync(fixture.sandboxDir, 0o1775); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + let staleFd: number | undefined; + try { + const mutableBegin = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "mutable", + rollbackMode: "locked", + }); + expect(mutableBegin.status, mutableBegin.stderr).toBe(0); + const mutableToken = shieldsTransactionToken(mutableBegin.stdout); + expect(mutableToken).toMatch(/^[0-9a-f]{64}$/); + const mutableApply = runShieldsTransactionAction(fixture, "apply-shields-transition", { + token: mutableToken, + }); + expect(mutableApply.status, mutableApply.stderr).toBe(0); + staleFd = fs.openSync(fixture.configPath, "r+"); + + const premature = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(premature.status).not.toBe(0); + expect(premature.stderr).toContain("mutable transition lease has not expired"); + + const staleState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + staleState.shields_transition.lease_expires_ns = 1; + fs.writeFileSync(fixture.statePath, `${JSON.stringify(staleState)}\n`, { mode: 0o600 }); + const beforeTakeoverInode = fs.statSync(fixture.configPath).ino; + const lockedBegin = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(lockedBegin.status, lockedBegin.stderr).toBe(0); + const lockedToken = shieldsTransactionToken(lockedBegin.stdout); + expect(lockedToken).toMatch(/^[0-9a-f]{64}$/); + expect(lockedToken).not.toBe(mutableToken); + expect(fs.statSync(fixture.configPath).ino).not.toBe(beforeTakeoverInode); + expect(mode(fixture.hermesDir)).toBe(0o500); + const sealedBytes = readFileSnapshot(fixture.configPath); + overwriteThroughOldFd(staleFd, sealedBytes.length, "X"); + expect(readFileSnapshot(fixture.configPath)).toEqual(sealedBytes); + + fs.chmodSync(fixture.hermesDir, 0o755); + expect( + runShieldsTransactionAction(fixture, "apply-shields-transition", { + token: lockedToken, + }).status, + ).toBe(0); + const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { + token: lockedToken, + }); + expect(finished.status, finished.stderr).toBe(0); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + } finally { + for (const openFd of staleFd === undefined ? [] : [staleFd]) fs.closeSync(openFd); + fs.chmodSync(fixture.sandboxDir, 0o700); + for (const existingHermesDir of fs.existsSync(fixture.hermesDir) ? [fixture.hermesDir] : []) { + fs.chmodSync(existingHermesDir, 0o700); + } + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("hardens mutable modes and stale hashes from the frozen current bytes", () => { + const fixture = createRestartFixture(); + const configBefore = fs.statSync(fixture.configPath).ino; + fs.chmodSync(fixture.configPath, 0o666); + fs.chmodSync(fixture.envPath, 0o666); + fs.writeFileSync(fixture.hashPath, "stale strict hash\n"); + fs.writeFileSync(fixture.compatHashPath, "stale compatibility hash\n"); + try { + const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { + mode: "locked", + }); + expect(begun.status, begun.stderr).toBe(0); + const token = shieldsTransactionToken(begun.stdout); + expect(token).toMatch(/^[0-9a-f]{64}$/); + const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + expect(transition.shields_transition.unavailable).toBe(false); + expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe( + fs.readFileSync(fixture.compatHashPath, "utf-8"), + ); + + fs.chmodSync(fixture.hermesDir, 0o755); + expect( + runShieldsTransactionAction(fixture, "apply-shields-transition", { token }).status, + ).toBe(0); + expect( + runShieldsTransactionAction(fixture, "finish-shields-transition", { token }).status, + ).toBe(0); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/hermes-restart-config-seal-write-lock.test.ts b/test/hermes-restart-config-seal-write-lock.test.ts new file mode 100644 index 00000000000..58a56f6e825 --- /dev/null +++ b/test/hermes-restart-config-seal-write-lock.test.ts @@ -0,0 +1,251 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + createRestartFixture, + hashInputs, + mode, + RUNTIME_CONFIG_GUARD, + runGuard, + runWriteConfig, + strictHashIsValid, + writeMutationLock, +} from "./helpers/hermes-restart-config-seal-fixture"; + +describe.skipIf(process.platform === "win32")("Hermes mutable restart input seal", () => { + it("atomically binds a host config write to the bytes that were read and refreshes both hashes", () => { + const fixture = createRestartFixture(); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + const updatedConfig = "model:\n default: trusted-model-v2\n"; + + try { + const updated = runWriteConfig(fixture, expectedDigest, updatedConfig); + + expect(updated.status, updated.stderr).toBe(0); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(updatedConfig); + expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe( + fs.readFileSync(fixture.compatHashPath, "utf-8"), + ); + expect(strictHashIsValid(fixture)).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(mode(fixture.envPath)).toBe(0o600); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("keeps a maximum-size config write journal below its bounded state cap", { + timeout: 60_000, + }, () => { + const fixture = createRestartFixture(); + const boundarySize = 16 * 1024 * 1024; + const payloadSize = boundarySize - "payload: \n".length; + const originalConfig = `payload: ${"a".repeat(payloadSize)}\n`; + const updatedConfig = `payload: ${"b".repeat(payloadSize)}\n`; + fs.writeFileSync(fixture.configPath, originalConfig); + const hash = hashInputs(fixture.configPath, fixture.envPath); + fs.writeFileSync(fixture.hashPath, hash); + fs.writeFileSync(fixture.compatHashPath, hash); + const expectedDigest = createHash("sha256").update(originalConfig).digest("hex"); + + try { + const updated = spawnSync( + "python3", + [ + RUNTIME_CONFIG_GUARD, + "write-config", + "--hermes-dir", + fixture.hermesDir, + "--hash-file", + fixture.hashPath, + "--state-file", + fixture.statePath, + "--expected-config-sha256", + expectedDigest, + ], + { encoding: "utf-8", input: updatedConfig, timeout: 45_000 }, + ); + expect(updated.status, updated.stderr).toBe(0); + const updatedBytes = fs.readFileSync(fixture.configPath); + expect(updatedBytes).toHaveLength(boundarySize); + expect(createHash("sha256").update(updatedBytes).digest("hex")).toBe( + createHash("sha256").update(updatedConfig).digest("hex"), + ); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses to launder a stale host read and leaves the trusted config unchanged", () => { + const fixture = createRestartFixture(); + const staleDigest = createHash("sha256").update("attacker-controlled read\n").digest("hex"); + + try { + const updated = runWriteConfig( + fixture, + staleDigest, + "model:\n default: attacker-derived-model\n", + ); + + expect(updated.status).not.toBe(0); + expect(updated.stderr).toContain("config changed after the host read"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("refuses host config writes while shields are up and restores the locked posture", () => { + const fixture = createRestartFixture(); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + fs.chmodSync(fixture.sandboxDir, 0o755); + fs.chmodSync(fixture.hermesDir, 0o755); + fs.chmodSync(fixture.configPath, 0o444); + fs.chmodSync(fixture.envPath, 0o444); + fs.chmodSync(fixture.compatHashPath, 0o444); + + try { + const updated = runWriteConfig( + fixture, + expectedDigest, + "model:\n default: must-not-apply\n", + ); + + expect(updated.status).not.toBe(0); + expect(updated.stderr).toContain("config writes are unavailable while shields are up"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(mode(fixture.sandboxDir)).toBe(0o755); + expect(mode(fixture.hermesDir)).toBe(0o755); + expect(mode(fixture.configPath)).toBe(0o444); + expect(mode(fixture.envPath)).toBe(0o444); + expect(strictHashIsValid(fixture)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("serializes restart sealing against a host-held shields mutation lock", () => { + const fixture = createRestartFixture(); + const token = randomBytes(32).toString("hex"); + + try { + const lockPath = writeMutationLock(fixture, token); + + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status).not.toBe(0); + expect(sealed.stderr).toContain("config mutation is already in progress"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(mode(fixture.sandboxDir)).toBe(0o770); + + fs.unlinkSync(lockPath); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("recovers a dead mutation lock published before seal state creation", () => { + const fixture = createRestartFixture(); + const token = randomBytes(32).toString("hex"); + try { + const lockPath = writeMutationLock(fixture, token); + expect(fs.existsSync(lockPath)).toBe(true); + expect(fs.existsSync(fixture.statePath)).toBe(false); + const recovered = spawnSync( + "python3", + [ + RUNTIME_CONFIG_GUARD, + "recover-prestate-lock", + "--hermes-dir", + fixture.hermesDir, + "--state-file", + fixture.statePath, + "--startup-owner", + ], + { encoding: "utf-8", timeout: 5000 }, + ); + expect(recovered.status, recovered.stderr).toBe(0); + expect(recovered.stdout.trim()).toBe("recovered=1"); + expect(fs.existsSync(lockPath)).toBe(false); + expect(fs.existsSync(fixture.statePath)).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("rejects a host config transaction while another Hermes mutation owns the lock", () => { + const fixture = createRestartFixture(); + const token = randomBytes(32).toString("hex"); + const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); + + try { + const lockPath = writeMutationLock(fixture, token); + + const updated = runWriteConfig( + fixture, + expectedDigest, + "model:\n default: should-not-commit\n", + ); + expect(updated.status).not.toBe(0); + expect(updated.stderr).toContain("config mutation is already in progress"); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(strictHashIsValid(fixture)).toBe(true); + + fs.unlinkSync(lockPath); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); + + it("rolls back a config-write phase killed after rename but before strict hash refresh", () => { + const fixture = createRestartFixture(); + + try { + const sealed = runGuard("seal-restart", fixture); + expect(sealed.status, sealed.stderr).toBe(0); + + const state = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); + state.phase = "config-write-prepared"; + state.config_write = { + original_base64: Buffer.from(fixture.trustedConfig).toString("base64"), + original_sha256: createHash("sha256").update(fixture.trustedConfig).digest("hex"), + }; + fs.writeFileSync(fixture.statePath, `${JSON.stringify(state)}\n`, { mode: 0o600 }); + fs.chmodSync(fixture.statePath, 0o600); + + const replacement = path.join(fixture.hermesDir, ".config.crash-test"); + fs.writeFileSync(replacement, "model:\n default: interrupted-write\n", { mode: 0o444 }); + fs.chmodSync(replacement, 0o444); + fs.renameSync(replacement, fixture.configPath); + expect(strictHashIsValid(fixture)).toBe(false); + + const recovered = runGuard("unseal-restart", fixture); + expect(recovered.status, recovered.stderr).toBe(0); + expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); + expect(strictHashIsValid(fixture)).toBe(true); + expect(mode(fixture.sandboxDir)).toBe(0o770); + expect(mode(fixture.hermesDir)).toBe(0o3770); + expect(mode(fixture.configPath)).toBe(0o640); + expect(fs.existsSync(fixture.statePath)).toBe(false); + expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }); +}); diff --git a/test/hermes-restart-config-seal.test.ts b/test/hermes-restart-config-seal.test.ts deleted file mode 100644 index 7286ed0b499..00000000000 --- a/test/hermes-restart-config-seal.test.ts +++ /dev/null @@ -1,1336 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { spawnSync } from "node:child_process"; -import { createHash, randomBytes } from "node:crypto"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { describe, expect, it } from "vitest"; - -const RUNTIME_CONFIG_GUARD = path.join( - import.meta.dirname, - "..", - "agents", - "hermes", - "runtime-config-guard.py", -); - -interface RestartFixture { - root: string; - sandboxDir: string; - hermesDir: string; - configPath: string; - envPath: string; - hashPath: string; - compatHashPath: string; - statePath: string; - trustedConfig: string; - trustedEnv: string; -} - -function mode(pathname: string): number { - return fs.statSync(pathname).mode & 0o7777; -} - -function hashInputs(configPath: string, envPath: string): string { - const result = spawnSync("sha256sum", [configPath, envPath], { - encoding: "utf-8", - timeout: 5000, - }); - expect(result.status, result.stderr).toBe(0); - const mcpDigest = createHash("sha256").update("{}").digest("hex"); - return `${result.stdout}# nemoclaw-hermes-mcp-state-v1 intended=${mcpDigest} applied=${mcpDigest}\n`; -} - -function createRestartFixture(): RestartFixture { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-restart-seal-")); - const sandboxDir = path.join(root, "sandbox"); - const hermesDir = path.join(sandboxDir, ".hermes"); - const configPath = path.join(hermesDir, "config.yaml"); - const envPath = path.join(hermesDir, ".env"); - const hashPath = path.join(root, "hermes.config-hash"); - const compatHashPath = path.join(hermesDir, ".config-hash"); - const statePath = path.join(root, "hermes-restart-seal.json"); - const trustedConfig = "model:\n default: trusted-model\n"; - const trustedEnv = "API_SERVER_PORT=18642\nSAFE_SETTING=trusted\n"; - - fs.mkdirSync(hermesDir, { recursive: true }); - fs.chmodSync(sandboxDir, 0o770); - fs.chmodSync(hermesDir, 0o3770); - fs.writeFileSync(configPath, trustedConfig, { mode: 0o640 }); - fs.chmodSync(configPath, 0o640); - fs.writeFileSync(envPath, trustedEnv, { mode: 0o600 }); - fs.chmodSync(envPath, 0o600); - - const hash = hashInputs(configPath, envPath); - fs.writeFileSync(hashPath, hash, { mode: 0o600 }); - fs.writeFileSync(compatHashPath, hash, { mode: 0o600 }); - - return { - root, - sandboxDir, - hermesDir, - configPath, - envPath, - hashPath, - compatHashPath, - statePath, - trustedConfig, - trustedEnv, - }; -} - -function runWriteConfig(fixture: RestartFixture, expectedDigest: string, content: string) { - return spawnSync( - "python3", - [ - RUNTIME_CONFIG_GUARD, - "write-config", - "--hermes-dir", - fixture.hermesDir, - "--hash-file", - fixture.hashPath, - "--state-file", - fixture.statePath, - "--expected-config-sha256", - expectedDigest, - ], - { encoding: "utf-8", input: content, timeout: 5000 }, - ); -} - -function writeMutationLock(fixture: RestartFixture, token: string): string { - const lockPath = path.join(fixture.root, "hermes-config-mutation.lock"); - fs.writeFileSync( - lockPath, - `${JSON.stringify({ - version: 1, - token, - purpose: "seal-restart", - pid: 999_999_999, - pid_start_time: "1", - })}\n`, - { mode: 0o600 }, - ); - return lockPath; -} - -function runGuard(action: "seal-restart" | "unseal-restart", fixture: RestartFixture) { - const args = [ - RUNTIME_CONFIG_GUARD, - action, - "--hermes-dir", - fixture.hermesDir, - "--state-file", - fixture.statePath, - ]; - args.push(...(action === "seal-restart" ? ["--hash-file", fixture.hashPath] : [])); - return spawnSync("python3", args, { - encoding: "utf-8", - timeout: 5000, - }); -} - -function runShieldsTransition(fixture: RestartFixture, shieldsMode: "locked" | "mutable") { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: shieldsMode, - }); - switch (begun.status) { - case 0: - break; - default: - return begun; - } - const token = shieldsTransactionToken(begun.stdout); - switch (token) { - case undefined: - throw new Error("Expected begin-shields-transition to emit a token"); - default: - break; - } - switch (shieldsMode) { - case "locked": - // The production host restores 0755 only after the recursive state guard's - // independent verification pass. This focused top-guard fixture has no - // recursive state, so model that successful handoff explicitly. - fs.chmodSync(fixture.hermesDir, 0o755); - break; - case "mutable": - break; - } - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - switch (applied.status) { - case 0: - break; - default: - return applied; - } - return runShieldsTransactionAction(fixture, "finish-shields-transition", { - token, - }); -} - -function runShieldsTransactionAction( - fixture: RestartFixture, - action: - | "begin-shields-transition" - | "apply-shields-transition" - | "finish-shields-transition" - | "prepare-shields-abort" - | "abort-shields-transition" - | "inspect-mutation-owner", - options: { - mode?: "locked" | "mutable"; - rollbackMode?: "locked" | "mutable"; - token?: string; - } = {}, -) { - const args = [ - RUNTIME_CONFIG_GUARD, - action, - "--hermes-dir", - fixture.hermesDir, - "--state-file", - fixture.statePath, - ]; - args.push( - ...(action === "begin-shields-transition" || action === "finish-shields-transition" - ? ["--hash-file", fixture.hashPath] - : []), - ...(options.mode ? ["--shields-mode", options.mode] : []), - ...(options.rollbackMode ? ["--rollback-shields-mode", options.rollbackMode] : []), - ...(options.token ? ["--lock-token", options.token] : []), - ); - return spawnSync("python3", args, { encoding: "utf-8", timeout: 5000 }); -} - -function strictHashIsValid(fixture: RestartFixture): boolean { - return ( - spawnSync("sha256sum", ["-c", fixture.hashPath, "--status"], { - encoding: "utf-8", - timeout: 5000, - }).status === 0 - ); -} - -function shieldsTransactionToken(output: string): string | undefined { - return /^lock_token=([0-9a-f]{64}) original_locked=[01]\s*$/.exec(output)?.[1]; -} - -function overwriteThroughOldFd(fd: number, originalSize: number, byte: string): void { - const attackerBytes = Buffer.alloc(originalSize, byte); - fs.writeSync(fd, attackerBytes, 0, attackerBytes.length, 0); - fs.fsyncSync(fd); -} - -describe.skipIf(process.platform === "win32")("Hermes mutable restart input seal", () => { - it("atomically binds a host config write to the bytes that were read and refreshes both hashes", () => { - const fixture = createRestartFixture(); - const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); - const updatedConfig = "model:\n default: trusted-model-v2\n"; - - try { - const updated = runWriteConfig(fixture, expectedDigest, updatedConfig); - - expect(updated.status, updated.stderr).toBe(0); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(updatedConfig); - expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe( - fs.readFileSync(fixture.compatHashPath, "utf-8"), - ); - expect(strictHashIsValid(fixture)).toBe(true); - expect(mode(fixture.sandboxDir)).toBe(0o770); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(mode(fixture.configPath)).toBe(0o640); - expect(mode(fixture.envPath)).toBe(0o600); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("keeps a maximum-size config write journal below its bounded state cap", { - timeout: 60_000, - }, () => { - const fixture = createRestartFixture(); - const boundarySize = 16 * 1024 * 1024; - const payloadSize = boundarySize - "payload: \n".length; - const originalConfig = `payload: ${"a".repeat(payloadSize)}\n`; - const updatedConfig = `payload: ${"b".repeat(payloadSize)}\n`; - fs.writeFileSync(fixture.configPath, originalConfig); - const hash = hashInputs(fixture.configPath, fixture.envPath); - fs.writeFileSync(fixture.hashPath, hash); - fs.writeFileSync(fixture.compatHashPath, hash); - const expectedDigest = createHash("sha256").update(originalConfig).digest("hex"); - - try { - const updated = spawnSync( - "python3", - [ - RUNTIME_CONFIG_GUARD, - "write-config", - "--hermes-dir", - fixture.hermesDir, - "--hash-file", - fixture.hashPath, - "--state-file", - fixture.statePath, - "--expected-config-sha256", - expectedDigest, - ], - { encoding: "utf-8", input: updatedConfig, timeout: 45_000 }, - ); - expect(updated.status, updated.stderr).toBe(0); - expect(fs.statSync(fixture.configPath).size).toBe(boundarySize); - expect(createHash("sha256").update(fs.readFileSync(fixture.configPath)).digest("hex")).toBe( - createHash("sha256").update(updatedConfig).digest("hex"), - ); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.existsSync(fixture.statePath)).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("refuses to launder a stale host read and leaves the trusted config unchanged", () => { - const fixture = createRestartFixture(); - const staleDigest = createHash("sha256").update("attacker-controlled read\n").digest("hex"); - - try { - const updated = runWriteConfig( - fixture, - staleDigest, - "model:\n default: attacker-derived-model\n", - ); - - expect(updated.status).not.toBe(0); - expect(updated.stderr).toContain("config changed after the host read"); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("refuses host config writes while shields are up and restores the locked posture", () => { - const fixture = createRestartFixture(); - const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); - fs.chmodSync(fixture.sandboxDir, 0o755); - fs.chmodSync(fixture.hermesDir, 0o755); - fs.chmodSync(fixture.configPath, 0o444); - fs.chmodSync(fixture.envPath, 0o444); - fs.chmodSync(fixture.compatHashPath, 0o444); - - try { - const updated = runWriteConfig( - fixture, - expectedDigest, - "model:\n default: must-not-apply\n", - ); - - expect(updated.status).not.toBe(0); - expect(updated.stderr).toContain("config writes are unavailable while shields are up"); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(mode(fixture.sandboxDir)).toBe(0o755); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.configPath)).toBe(0o444); - expect(mode(fixture.envPath)).toBe(0o444); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("serializes restart sealing against a host-held shields mutation lock", () => { - const fixture = createRestartFixture(); - const token = randomBytes(32).toString("hex"); - - try { - const lockPath = writeMutationLock(fixture, token); - - const sealed = runGuard("seal-restart", fixture); - expect(sealed.status).not.toBe(0); - expect(sealed.stderr).toContain("config mutation is already in progress"); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(mode(fixture.sandboxDir)).toBe(0o770); - - fs.unlinkSync(lockPath); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("recovers a dead mutation lock published before seal state creation", () => { - const fixture = createRestartFixture(); - const token = randomBytes(32).toString("hex"); - try { - const lockPath = writeMutationLock(fixture, token); - expect(fs.existsSync(lockPath)).toBe(true); - expect(fs.existsSync(fixture.statePath)).toBe(false); - const recovered = spawnSync( - "python3", - [ - RUNTIME_CONFIG_GUARD, - "recover-prestate-lock", - "--hermes-dir", - fixture.hermesDir, - "--state-file", - fixture.statePath, - "--startup-owner", - ], - { encoding: "utf-8", timeout: 5000 }, - ); - expect(recovered.status, recovered.stderr).toBe(0); - expect(recovered.stdout.trim()).toBe("recovered=1"); - expect(fs.existsSync(lockPath)).toBe(false); - expect(fs.existsSync(fixture.statePath)).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("rejects a host config transaction while another Hermes mutation owns the lock", () => { - const fixture = createRestartFixture(); - const token = randomBytes(32).toString("hex"); - const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); - - try { - const lockPath = writeMutationLock(fixture, token); - - const updated = runWriteConfig( - fixture, - expectedDigest, - "model:\n default: should-not-commit\n", - ); - expect(updated.status).not.toBe(0); - expect(updated.stderr).toContain("config mutation is already in progress"); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(strictHashIsValid(fixture)).toBe(true); - - fs.unlinkSync(lockPath); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("rolls back a config-write phase killed after rename but before strict hash refresh", () => { - const fixture = createRestartFixture(); - - try { - const sealed = runGuard("seal-restart", fixture); - expect(sealed.status, sealed.stderr).toBe(0); - - const state = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - state.phase = "config-write-prepared"; - state.config_write = { - original_base64: Buffer.from(fixture.trustedConfig).toString("base64"), - original_sha256: createHash("sha256").update(fixture.trustedConfig).digest("hex"), - }; - fs.writeFileSync(fixture.statePath, `${JSON.stringify(state)}\n`, { mode: 0o600 }); - fs.chmodSync(fixture.statePath, 0o600); - - const replacement = path.join(fixture.hermesDir, ".config.crash-test"); - fs.writeFileSync(replacement, "model:\n default: interrupted-write\n", { mode: 0o444 }); - fs.chmodSync(replacement, 0o444); - fs.renameSync(replacement, fixture.configPath); - expect(strictHashIsValid(fixture)).toBe(false); - - const recovered = runGuard("unseal-restart", fixture); - expect(recovered.status, recovered.stderr).toBe(0); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(strictHashIsValid(fixture)).toBe(true); - expect(mode(fixture.sandboxDir)).toBe(0o770); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(mode(fixture.configPath)).toBe(0o640); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("revokes pre-open writable fds while preserving trusted path bytes and strict hashes", () => { - const fixture = createRestartFixture(); - const configBefore = fs.statSync(fixture.configPath); - const envBefore = fs.statSync(fixture.envPath); - const configFd = fs.openSync(fixture.configPath, "r+"); - const envFd = fs.openSync(fixture.envPath, "r+"); - - try { - const sealed = runGuard("seal-restart", fixture); - expect(sealed.status, sealed.stderr).toBe(0); - - const configSealed = fs.statSync(fixture.configPath); - const envSealed = fs.statSync(fixture.envPath); - expect(configSealed.ino).not.toBe(configBefore.ino); - expect(envSealed.ino).not.toBe(envBefore.ino); - expect(configSealed.uid).toBe(process.getuid!()); - expect(envSealed.uid).toBe(process.getuid!()); - expect(mode(fixture.sandboxDir)).toBe(0o755); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(mode(fixture.configPath)).toBe(0o444); - expect(mode(fixture.envPath)).toBe(0o444); - expect(configSealed.uid).toBe(fs.statSync(fixture.hermesDir).uid); - expect(envSealed.uid).toBe(fs.statSync(fixture.hermesDir).uid); - expect(mode(fixture.statePath)).toBe(0o600); - expect(strictHashIsValid(fixture)).toBe(true); - - overwriteThroughOldFd(configFd, configBefore.size, "X"); - overwriteThroughOldFd(envFd, envBefore.size, "Y"); - - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(fs.readFileSync(fixture.envPath, "utf-8")).toBe(fixture.trustedEnv); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.statSync(fixture.configPath).ino).toBe(configSealed.ino); - expect(fs.statSync(fixture.envPath).ino).toBe(envSealed.ino); - - const unsealed = runGuard("unseal-restart", fixture); - expect(unsealed.status, unsealed.stderr).toBe(0); - expect(mode(fixture.sandboxDir)).toBe(0o770); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(mode(fixture.configPath)).toBe(0o640); - expect(mode(fixture.envPath)).toBe(0o600); - expect(fs.statSync(fixture.configPath).uid).toBe(configBefore.uid); - expect(fs.statSync(fixture.configPath).gid).toBe(configBefore.gid); - expect(fs.statSync(fixture.envPath).uid).toBe(envBefore.uid); - expect(fs.statSync(fixture.envPath).gid).toBe(envBefore.gid); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(fs.readFileSync(fixture.envPath, "utf-8")).toBe(fixture.trustedEnv); - expect(strictHashIsValid(fixture)).toBe(true); - } finally { - fs.closeSync(configFd); - fs.closeSync(envFd); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("revokes pre-open descriptors across shields lock and restores the mutable contract", () => { - const fixture = createRestartFixture(); - const configBefore = fs.statSync(fixture.configPath); - const envBefore = fs.statSync(fixture.envPath); - const compatBefore = fs.statSync(fixture.compatHashPath); - const configFd = fs.openSync(fixture.configPath, "r+"); - const envFd = fs.openSync(fixture.envPath, "r+"); - const compatFd = fs.openSync(fixture.compatHashPath, "r+"); - - try { - const locked = runShieldsTransition(fixture, "locked"); - expect(locked.status, locked.stderr).toBe(0); - expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore.ino); - expect(fs.statSync(fixture.envPath).ino).not.toBe(envBefore.ino); - expect(fs.statSync(fixture.compatHashPath).ino).not.toBe(compatBefore.ino); - expect(mode(fixture.sandboxDir)).toBe(0o1775); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.configPath)).toBe(0o444); - expect(mode(fixture.envPath)).toBe(0o444); - expect(mode(fixture.compatHashPath)).toBe(0o444); - - overwriteThroughOldFd(configFd, configBefore.size, "X"); - overwriteThroughOldFd(envFd, envBefore.size, "Y"); - overwriteThroughOldFd(compatFd, compatBefore.size, "Z"); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(fs.readFileSync(fixture.envPath, "utf-8")).toBe(fixture.trustedEnv); - expect(strictHashIsValid(fixture)).toBe(true); - - const mutable = runShieldsTransition(fixture, "mutable"); - expect(mutable.status, mutable.stderr).toBe(0); - expect(mode(fixture.sandboxDir)).toBe(0o755); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(mode(fixture.configPath)).toBe(0o640); - expect(mode(fixture.envPath)).toBe(0o640); - expect(mode(fixture.compatHashPath)).toBe(0o640); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); - expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( - false, - ); - } finally { - fs.closeSync(configFd); - fs.closeSync(envFd); - fs.closeSync(compatFd); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("holds the mutation lock through begin, apply, verification, and finish", () => { - const fixture = createRestartFixture(); - const expectedDigest = createHash("sha256").update(fixture.trustedConfig).digest("hex"); - - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - expect(fs.existsSync(fixture.statePath)).toBe(true); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); - expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( - true, - ); - expect(mode(fixture.sandboxDir)).toBe(0o700); - expect(mode(fixture.hermesDir)).toBe(0o500); - - const owner = runShieldsTransactionAction(fixture, "inspect-mutation-owner"); - expect(owner.status, owner.stderr).toBe(0); - expect(owner.stdout).toContain("owner_active=1"); - expect(owner.stdout).toContain("recovery_safe=0"); - - const competingRestart = runGuard("seal-restart", fixture); - expect(competingRestart.status).not.toBe(0); - expect(competingRestart.stderr).toContain("restart seal is already active"); - const competingWrite = runWriteConfig( - fixture, - expectedDigest, - "model:\n default: must-not-interleave\n", - ); - expect(competingWrite.status).not.toBe(0); - expect(competingWrite.stderr).toContain("restart seal is already active"); - - fs.chmodSync(fixture.hermesDir, 0o755); - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(applied.status, applied.stderr).toBe(0); - expect(applied.stdout).toContain("shields_mode=locked"); - expect(fs.existsSync(fixture.statePath)).toBe(true); - expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( - true, - ); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.configPath)).toBe(0o444); - expect(mode(fixture.sandboxDir)).toBe(0o755); - - const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { - token, - }); - expect(finished.status, finished.stderr).toBe(0); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(false); - expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( - false, - ); - expect(mode(fixture.sandboxDir)).toBe(0o1775); - expect(strictHashIsValid(fixture)).toBe(true); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("keeps weakening fan-out inaccessible and keeps monotonic lock fan-out readable", () => { - for (const targetMode of ["mutable", "locked"] as const) { - const fixture = createRestartFixture(); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: targetMode, - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - expect(mode(fixture.hermesDir)).toBe(targetMode === "mutable" ? 0o700 : 0o500); - expect(mode(fixture.sandboxDir)).toBe(0o700); - - const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { - token, - }); - expect(prepared.status, prepared.stderr).toBe(0); - const abortState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - expect(abortState.shields_transition.mode).toBe("mutable"); - // State-dir rollback is another recursive transition. It remains - // root-only until abort commits the original posture. - expect(mode(fixture.hermesDir)).toBe(0o700); - expect(mode(fixture.sandboxDir)).toBe(0o700); - - const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { - token, - }); - expect(aborted.status, aborted.stderr).toBe(0); - expect(mode(fixture.hermesDir)).toBe(0o3770); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - } - }); - - it("retains the 0500 recursive clamp and resumes the same lock transaction", () => { - const fixture = createRestartFixture(); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - expect(mode(fixture.hermesDir)).toBe(0o500); - - const premature = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(premature.status).not.toBe(0); - expect(premature.stderr).toContain("retaining root-only 0500 clamp for retry"); - expect(mode(fixture.hermesDir)).toBe(0o500); - expect(fs.existsSync(fixture.statePath)).toBe(true); - - const resumed = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(resumed.status, resumed.stderr).toBe(0); - expect(shieldsTransactionToken(resumed.stdout)).toBe(token); - expect(mode(fixture.hermesDir)).toBe(0o500); - - fs.chmodSync(fixture.hermesDir, 0o755); - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(applied.status, applied.stderr).toBe(0); - const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { - token, - }); - expect(finished.status, finished.stderr).toBe(0); - expect(mode(fixture.hermesDir)).toBe(0o755); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("cold-resumes an applied lock transaction before its final commit", () => { - const fixture = createRestartFixture(); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - fs.chmodSync(fixture.hermesDir, 0o755); - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(applied.status, applied.stderr).toBe(0); - - const resumed = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(resumed.status, resumed.stderr).toBe(0); - expect(shieldsTransactionToken(resumed.stdout)).toBe(token); - expect(mode(fixture.hermesDir)).toBe(0o500); - fs.chmodSync(fixture.hermesDir, 0o755); - const reapplied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(reapplied.status, reapplied.stderr).toBe(0); - const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { - token, - }); - expect(finished.status, finished.stderr).toBe(0); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(mode(fixture.hermesDir)).toBe(0o755); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("takes over an expired applied mutable transition only after its worker lease ends", () => { - const fixture = createRestartFixture(); - fs.chmodSync(fixture.sandboxDir, 0o1775); - fs.chmodSync(fixture.hermesDir, 0o755); - fs.chmodSync(fixture.configPath, 0o444); - fs.chmodSync(fixture.envPath, 0o444); - fs.chmodSync(fixture.compatHashPath, 0o444); - let staleFd: number | undefined; - try { - const mutableBegin = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "mutable", - rollbackMode: "locked", - }); - expect(mutableBegin.status, mutableBegin.stderr).toBe(0); - const mutableToken = shieldsTransactionToken(mutableBegin.stdout); - expect(mutableToken).toMatch(/^[0-9a-f]{64}$/); - const mutableApply = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token: mutableToken, - }); - expect(mutableApply.status, mutableApply.stderr).toBe(0); - staleFd = fs.openSync(fixture.configPath, "r+"); - - const premature = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(premature.status).not.toBe(0); - expect(premature.stderr).toContain("mutable transition lease has not expired"); - - const staleState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - staleState.shields_transition.lease_expires_ns = 1; - fs.writeFileSync(fixture.statePath, `${JSON.stringify(staleState)}\n`, { mode: 0o600 }); - const beforeTakeoverInode = fs.statSync(fixture.configPath).ino; - const lockedBegin = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(lockedBegin.status, lockedBegin.stderr).toBe(0); - const lockedToken = shieldsTransactionToken(lockedBegin.stdout); - expect(lockedToken).toMatch(/^[0-9a-f]{64}$/); - expect(lockedToken).not.toBe(mutableToken); - expect(fs.statSync(fixture.configPath).ino).not.toBe(beforeTakeoverInode); - expect(mode(fixture.hermesDir)).toBe(0o500); - const sealedBytes = fs.readFileSync(fixture.configPath); - overwriteThroughOldFd(staleFd, sealedBytes.length, "X"); - expect(fs.readFileSync(fixture.configPath)).toEqual(sealedBytes); - - fs.chmodSync(fixture.hermesDir, 0o755); - expect( - runShieldsTransactionAction(fixture, "apply-shields-transition", { - token: lockedToken, - }).status, - ).toBe(0); - const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { - token: lockedToken, - }); - expect(finished.status, finished.stderr).toBe(0); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.configPath)).toBe(0o444); - expect(strictHashIsValid(fixture)).toBe(true); - } finally { - for (const openFd of staleFd === undefined ? [] : [staleFd]) fs.closeSync(openFd); - fs.chmodSync(fixture.sandboxDir, 0o700); - for (const existingHermesDir of fs.existsSync(fixture.hermesDir) ? [fixture.hermesDir] : []) { - fs.chmodSync(existingHermesDir, 0o700); - } - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("hardens mutable modes and stale hashes from the frozen current bytes", () => { - const fixture = createRestartFixture(); - const configBefore = fs.statSync(fixture.configPath).ino; - fs.chmodSync(fixture.configPath, 0o666); - fs.chmodSync(fixture.envPath, 0o666); - fs.writeFileSync(fixture.hashPath, "stale strict hash\n"); - fs.writeFileSync(fixture.compatHashPath, "stale compatibility hash\n"); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - expect(transition.shields_transition.unavailable).toBe(false); - expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore); - expect(mode(fixture.configPath)).toBe(0o444); - expect(mode(fixture.envPath)).toBe(0o444); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.readFileSync(fixture.hashPath, "utf-8")).toBe( - fs.readFileSync(fixture.compatHashPath, "utf-8"), - ); - - fs.chmodSync(fixture.hermesDir, 0o755); - expect( - runShieldsTransactionAction(fixture, "apply-shields-transition", { token }).status, - ).toBe(0); - expect( - runShieldsTransactionAction(fixture, "finish-shields-transition", { token }).status, - ).toBe(0); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - for (const oversizedName of ["config.yaml", ".env"] as const) { - it(`contains an oversized sparse ${oversizedName} without reading its logical payload`, () => { - const fixture = createRestartFixture(); - const oversizedPath = oversizedName === "config.yaml" ? fixture.configPath : fixture.envPath; - fs.truncateSync( - oversizedPath, - oversizedName === "config.yaml" ? 16 * 1024 * 1024 + 1 : 4 * 1024 * 1024 + 1, - ); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - expect(transition.shields_transition.unavailable).toBe(true); - expect(transition.shields_transition.unavailable_reasons.join("\n")).toContain( - "oversized runtime config path", - ); - expect(fs.statSync(oversizedPath).size).toBeLessThan(1024); - expect(mode(oversizedPath)).toBe(0o400); - expect(mode(fixture.hermesDir)).toBe(0o500); - } finally { - fs.chmodSync(fixture.sandboxDir, 0o700); - fs.chmodSync(fixture.hermesDir, 0o700); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - } - - it("fresh-seals a hardlinked input and revokes the external writable inode", () => { - const fixture = createRestartFixture(); - const external = path.join(fixture.root, "external-config"); - fs.unlinkSync(fixture.configPath); - fs.writeFileSync(external, fixture.trustedConfig, { mode: 0o666 }); - fs.linkSync(external, fixture.configPath); - const linkedInode = fs.statSync(external).ino; - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - expect(fs.statSync(fixture.configPath).ino).not.toBe(linkedInode); - expect(fs.statSync(fixture.configPath).nlink).toBe(1); - expect( - JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")).shields_transition.unavailable, - ).toBe(false); - fs.writeFileSync(external, "attacker rewrite\n"); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - - fs.chmodSync(fixture.hermesDir, 0o755); - expect( - runShieldsTransactionAction(fixture, "apply-shields-transition", { token }).status, - ).toBe(0); - expect( - runShieldsTransactionAction(fixture, "finish-shields-transition", { token }).status, - ).toBe(0); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - for (const hostileKind of ["symlink", "fifo"] as const) { - it(`seals a hostile ${hostileKind} config entry into a root-only unavailable posture`, () => { - const fixture = createRestartFixture(); - fs.unlinkSync(fixture.configPath); - const arrangeHostileConfig = { - symlink: () => { - const victim = path.join(fixture.root, "victim"); - fs.writeFileSync(victim, "victim stays untouched\n"); - fs.symlinkSync(victim, fixture.configPath); - }, - fifo: () => expect(spawnSync("mkfifo", [fixture.configPath]).status).toBe(0), - } satisfies Record void>; - arrangeHostileConfig[hostileKind](); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - expect(transition.shields_transition.unavailable).toBe(true); - expect(fs.lstatSync(fixture.configPath).isFile()).toBe(true); - expect(mode(fixture.configPath)).toBe(0o400); - expect(mode(fixture.hermesDir)).toBe(0o500); - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(applied.status).not.toBe(0); - expect(applied.stderr).toContain("sealed root-only and is unavailable"); - expect(mode(fixture.sandboxDir)).toBe(0o700); - expect(mode(fixture.hermesDir)).toBe(0o500); - } finally { - fs.chmodSync(fixture.sandboxDir, 0o700); - fs.chmodSync(fixture.hermesDir, 0o700); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - } - - for (const hostileKind of ["symlink", "fifo"] as const) { - it(`quarantines an outer .hermes ${hostileKind} only after freezing /sandbox`, () => { - const fixture = createRestartFixture(); - fs.rmSync(fixture.hermesDir, { recursive: true, force: true }); - const victim = path.join(fixture.root, "outer-victim"); - const arrangeHostileHome = { - symlink: () => { - fs.mkdirSync(victim); - fs.writeFileSync(path.join(victim, "proof"), "untouched\n"); - fs.symlinkSync(victim, fixture.hermesDir); - }, - fifo: () => expect(spawnSync("mkfifo", [fixture.hermesDir]).status).toBe(0), - } satisfies Record void>; - arrangeHostileHome[hostileKind](); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - expect(fs.lstatSync(fixture.hermesDir).isDirectory()).toBe(true); - expect(mode(fixture.sandboxDir)).toBe(0o700); - expect(mode(fixture.hermesDir)).toBe(0o500); - const transition = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - expect(transition.shields_transition.unavailable).toBe(true); - for (const proofPath of hostileKind === "symlink" ? [path.join(victim, "proof")] : []) { - expect(fs.readFileSync(proofPath, "utf-8")).toBe("untouched\n"); - } - } finally { - fs.chmodSync(fixture.sandboxDir, 0o700); - fs.chmodSync(fixture.hermesDir, 0o700); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - } - - it("re-seals an applied mutable transition before recursive rollback", () => { - const fixture = createRestartFixture(); - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "mutable", - rollbackMode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - expect(mode(fixture.hermesDir)).toBe(0o700); - expect(mode(fixture.sandboxDir)).toBe(0o700); - - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { token }); - expect(applied.status, applied.stderr).toBe(0); - expect(mode(fixture.hermesDir)).toBe(0o3770); - - const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { token }); - expect(prepared.status, prepared.stderr).toBe(0); - const abortState = JSON.parse(fs.readFileSync(fixture.statePath, "utf-8")); - expect(abortState.shields_transition.mode).toBe("locked"); - expect(mode(fixture.hermesDir)).toBe(0o700); - expect(mode(fixture.sandboxDir)).toBe(0o700); - - const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { token }); - expect(aborted.status, aborted.stderr).toBe(0); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.sandboxDir)).toBe(0o1775); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it.runIf( - process.platform === "linux" && - process.getuid?.() === 0 && - spawnSync("setpriv", ["--version"], { encoding: "utf-8" }).status === 0, - )("keeps the locked Hermes entry sticky-protected while allowing ordinary home writes", () => { - const fixture = createRestartFixture(); - - try { - const locked = runShieldsTransition(fixture, "locked"); - expect(locked.status, locked.stderr).toBe(0); - const parent = fs.statSync(fixture.sandboxDir); - expect(parent.uid).toBe(0); - expect(mode(fixture.sandboxDir)).toBe(0o1775); - expect(fs.statSync(fixture.hermesDir).uid).toBe(0); - - const peer = spawnSync( - "setpriv", - [ - "--reuid=65534", - "--regid=65534", - `--groups=${String(parent.gid)}`, - "sh", - "-c", - 'touch "$1/peer-home-file" || exit 10; mv "$1/.hermes" "$1/.hermes-moved" 2>/dev/null && exit 20; test -d "$1/.hermes"', - "sh", - fixture.sandboxDir, - ], - { encoding: "utf-8", timeout: 5000 }, - ); - - expect(peer.status, peer.stderr).toBe(0); - expect(fs.existsSync(path.join(fixture.sandboxDir, "peer-home-file"))).toBe(true); - expect(fs.existsSync(fixture.hermesDir)).toBe(true); - expect(fs.existsSync(path.join(fixture.sandboxDir, ".hermes-moved"))).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("refuses to finish after the sealed Hermes directory is swapped", () => { - const fixture = createRestartFixture(); - - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - - fs.chmodSync(fixture.hermesDir, 0o755); - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(applied.status, applied.stderr).toBe(0); - expect(mode(fixture.sandboxDir)).toBe(0o755); - - const displaced = path.join(fixture.sandboxDir, ".hermes.displaced"); - fs.renameSync(fixture.hermesDir, displaced); - fs.mkdirSync(fixture.hermesDir, { mode: 0o755 }); - - const finished = runShieldsTransactionAction(fixture, "finish-shields-transition", { - token, - }); - expect(finished.status).not.toBe(0); - expect(finished.stderr).toContain("refusing shields finish because .hermes changed"); - expect(fs.existsSync(fixture.statePath)).toBe(true); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); - expect(mode(fixture.sandboxDir)).toBe(0o755); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("keeps the transaction sealed when abort finds a corrupted compatibility hash", () => { - const fixture = createRestartFixture(); - - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - - fs.chmodSync(fixture.hermesDir, 0o755); - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(applied.status, applied.stderr).toBe(0); - - fs.unlinkSync(fixture.compatHashPath); - fs.writeFileSync(fixture.compatHashPath, "attacker-controlled hash\n", { mode: 0o444 }); - const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { - token, - }); - expect(prepared.status, prepared.stderr).toBe(0); - const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { - token, - }); - - expect(aborted.status).not.toBe(0); - expect(aborted.stderr).toContain("compat hash verification failed"); - expect(fs.existsSync(fixture.statePath)).toBe(true); - expect(fs.existsSync(path.join(fixture.root, "hermes-config-mutation.lock"))).toBe(true); - expect(fs.existsSync(path.join(fixture.hermesDir, ".nemoclaw-hermes-restart-seal"))).toBe( - true, - ); - expect(mode(fixture.sandboxDir)).toBe(0o700); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("revokes descriptors opened after mutable apply before rolling back to locked", () => { - const fixture = createRestartFixture(); - fs.chmodSync(fixture.sandboxDir, 0o1775); - fs.chmodSync(fixture.hermesDir, 0o755); - fs.chmodSync(fixture.configPath, 0o444); - fs.chmodSync(fixture.envPath, 0o444); - fs.chmodSync(fixture.compatHashPath, 0o444); - let mutableFd: number | undefined; - - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "mutable", - rollbackMode: "locked", - }); - expect(begun.status, begun.stderr).toBe(0); - expect(begun.stdout).toContain("original_locked=1"); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - - const applied = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token, - }); - expect(applied.status, applied.stderr).toBe(0); - const appliedInode = fs.statSync(fixture.configPath).ino; - mutableFd = fs.openSync(fixture.configPath, "r+"); - - const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { - token, - }); - expect(prepared.status, prepared.stderr).toBe(0); - expect(fs.statSync(fixture.configPath).ino).not.toBe(appliedInode); - - const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { - token, - }); - expect(aborted.status, aborted.stderr).toBe(0); - fs.writeSync(mutableFd, Buffer.from("PWNED!"), 0, 6, 0); - fs.fsyncSync(mutableFd); - - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - expect(mode(fixture.sandboxDir)).toBe(0o1775); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.configPath)).toBe(0o444); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.existsSync(fixture.statePath)).toBe(false); - } finally { - for (const openFd of mutableFd === undefined ? [] : [mutableFd]) fs.closeSync(openFd); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("rejects a foreign shields token and lets the owner abort to the exact prior posture", () => { - const fixture = createRestartFixture(); - - try { - const begun = runShieldsTransactionAction(fixture, "begin-shields-transition", { - mode: "locked", - }); - const token = shieldsTransactionToken(begun.stdout); - expect(token).toMatch(/^[0-9a-f]{64}$/); - - const foreign = runShieldsTransactionAction(fixture, "apply-shields-transition", { - token: randomBytes(32).toString("hex"), - }); - expect(foreign.status).not.toBe(0); - expect(foreign.stderr).toContain("lock token mismatch"); - - const prepared = runShieldsTransactionAction(fixture, "prepare-shields-abort", { - token, - }); - expect(prepared.status, prepared.stderr).toBe(0); - const aborted = runShieldsTransactionAction(fixture, "abort-shields-transition", { - token, - }); - expect(aborted.status, aborted.stderr).toBe(0); - expect(mode(fixture.sandboxDir)).toBe(0o755); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(mode(fixture.configPath)).toBe(0o640); - expect(mode(fixture.envPath)).toBe(0o640); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.existsSync(fixture.statePath)).toBe(false); - } finally { - fs.chmodSync(fixture.sandboxDir, 0o700); - fs.chmodSync(fixture.hermesDir, 0o700); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("fails closed without replacing or locking paths when the strict hash is stale", () => { - const fixture = createRestartFixture(); - const configBefore = fs.statSync(fixture.configPath); - const envBefore = fs.statSync(fixture.envPath); - fs.writeFileSync(fixture.configPath, "model:\n default: attacker-model\n"); - - try { - const sealed = runGuard("seal-restart", fixture); - - expect(sealed.status).not.toBe(0); - expect(sealed.stderr).toContain("strict hash verification failed"); - expect(fs.statSync(fixture.configPath).ino).toBe(configBefore.ino); - expect(fs.statSync(fixture.envPath).ino).toBe(envBefore.ino); - expect(mode(fixture.sandboxDir)).toBe(0o770); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(mode(fixture.configPath)).toBe(0o640); - expect(mode(fixture.envPath)).toBe(0o600); - expect(fs.existsSync(fixture.statePath)).toBe(false); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("does not bless a compat hash changed through a pre-open descriptor", () => { - const fixture = createRestartFixture(); - const compatBefore = fs.statSync(fixture.compatHashPath); - const compatFd = fs.openSync(fixture.compatHashPath, "r+"); - - try { - overwriteThroughOldFd(compatFd, compatBefore.size, "Z"); - const sealed = runGuard("seal-restart", fixture); - - expect(sealed.status).not.toBe(0); - expect(sealed.stderr).toContain("compat hash verification failed"); - expect(strictHashIsValid(fixture)).toBe(true); - expect(fs.readFileSync(fixture.compatHashPath, "utf-8")).not.toBe( - fs.readFileSync(fixture.hashPath, "utf-8"), - ); - expect(mode(fixture.sandboxDir)).toBe(0o770); - expect(mode(fixture.hermesDir)).toBe(0o3770); - expect(fs.existsSync(fixture.statePath)).toBe(false); - } finally { - fs.closeSync(compatFd); - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it("preserves an already trusted shields-up directory posture across seal and unseal", () => { - const fixture = createRestartFixture(); - fs.chmodSync(fixture.sandboxDir, 0o755); - fs.chmodSync(fixture.hermesDir, 0o755); - fs.chmodSync(fixture.configPath, 0o444); - fs.chmodSync(fixture.envPath, 0o444); - const configBefore = fs.statSync(fixture.configPath); - const envBefore = fs.statSync(fixture.envPath); - - try { - const sealed = runGuard("seal-restart", fixture); - expect(sealed.status, sealed.stderr).toBe(0); - expect(fs.statSync(fixture.configPath).ino).not.toBe(configBefore.ino); - expect(fs.statSync(fixture.envPath).ino).not.toBe(envBefore.ino); - expect(mode(fixture.sandboxDir)).toBe(0o755); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.configPath)).toBe(0o444); - expect(mode(fixture.envPath)).toBe(0o444); - expect(fs.statSync(fixture.hermesDir).uid).toBe(process.getuid!()); - expect(strictHashIsValid(fixture)).toBe(true); - - const unsealed = runGuard("unseal-restart", fixture); - expect(unsealed.status, unsealed.stderr).toBe(0); - expect(mode(fixture.sandboxDir)).toBe(0o755); - expect(mode(fixture.hermesDir)).toBe(0o755); - expect(mode(fixture.configPath)).toBe(0o444); - expect(mode(fixture.envPath)).toBe(0o444); - expect(fs.existsSync(fixture.statePath)).toBe(false); - expect(strictHashIsValid(fixture)).toBe(true); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); - - it.runIf( - process.platform === "linux" && - process.getuid?.() === 0 && - spawnSync("setpriv", ["--version"], { encoding: "utf-8" }).status === 0, - )("lets a sandbox-group peer create state but not unlink sealed config names", () => { - const fixture = createRestartFixture(); - - try { - const sealed = runGuard("seal-restart", fixture); - expect(sealed.status, sealed.stderr).toBe(0); - - const hermesGid = fs.statSync(fixture.hermesDir).gid; - const peer = spawnSync( - "setpriv", - [ - "--reuid=65534", - "--regid=65534", - `--groups=${hermesGid}`, - "sh", - "-c", - 'touch "$1/peer-runtime-state" || exit 10; rm "$1/config.yaml" 2>/dev/null && exit 20; test -f "$1/config.yaml"', - "sh", - fixture.hermesDir, - ], - { encoding: "utf-8", timeout: 5000 }, - ); - - expect(peer.status, peer.stderr).toBe(0); - expect(fs.existsSync(path.join(fixture.hermesDir, "peer-runtime-state"))).toBe(true); - expect(fs.readFileSync(fixture.configPath, "utf-8")).toBe(fixture.trustedConfig); - - const unsealed = runGuard("unseal-restart", fixture); - expect(unsealed.status, unsealed.stderr).toBe(0); - } finally { - fs.rmSync(fixture.root, { recursive: true, force: true }); - } - }); -}); diff --git a/test/local-credential-helper-contract.test.ts b/test/local-credential-helper-contract.test.ts new file mode 100644 index 00000000000..1072a2fcbac --- /dev/null +++ b/test/local-credential-helper-contract.test.ts @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { registerLocalCredentialHelperTests } from "./local-credential-helper-suite"; + +registerLocalCredentialHelperTests("contract"); diff --git a/test/local-credential-helper-fields.test.ts b/test/local-credential-helper-fields.test.ts new file mode 100644 index 00000000000..a635a2d401d --- /dev/null +++ b/test/local-credential-helper-fields.test.ts @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { registerLocalCredentialHelperTests } from "./local-credential-helper-suite"; + +registerLocalCredentialHelperTests("fields"); diff --git a/test/local-credential-helper-session.test.ts b/test/local-credential-helper-session.test.ts new file mode 100644 index 00000000000..f2b90a43645 --- /dev/null +++ b/test/local-credential-helper-session.test.ts @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { registerLocalCredentialHelperTests } from "./local-credential-helper-suite"; + +registerLocalCredentialHelperTests("session"); diff --git a/test/local-credential-helper-suite.ts b/test/local-credential-helper-suite.ts new file mode 100644 index 00000000000..3bab1f15987 --- /dev/null +++ b/test/local-credential-helper-suite.ts @@ -0,0 +1,1296 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { type ChildProcess, execFileSync, spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import http, { type IncomingHttpHeaders } from "node:http"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + buildCredentialFormCsp, + parseCredentialField, + sanitizeInheritedChildEnvironment, + startLocalCredentialHelper, +} from "../scripts/local-credential-helper.mts"; + +const REPO_ROOT = path.resolve(import.meta.dirname, ".."); +const HELPER_PATH = path.join(REPO_ROOT, "scripts", "local-credential-helper.mts"); +const FORM_PATH = path.join(REPO_ROOT, "docs", "resources", "local-credential-form.html"); +const READINESS_URL_PATTERN = /http:\/\/127\.0\.0\.1:\d+\/\S*#cap=[A-Za-z0-9_-]{43}/; +const PROCESS_TIMEOUT_MS = 5_000; +const TEST_SECRET = "integration-secret-value"; +const TEST_PUBLIC_VALUE = "public-id"; +const CONFIG_ROOT_ENV_NAMES = [ + "ALLUSERSPROFILE", + "APPDATA", + "CURL_HOME", + "DOCKER_CERT_PATH", + "DOCKER_CONFIG", + "DOCKER_CONTEXT", + "DOCKER_HOST", + "DOCKER_TLS_VERIFY", + "GCONV_PATH", + "GIT_COMMON_DIR", + "GIT_DIR", + "GLIBC_TUNABLES", + "HOME", + "HOMEDRIVE", + "HOMEPATH", + "KUBECONFIG", + "LOCALAPPDATA", + "LOCPATH", + "NETRC", + "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", + "NEMOCLAW_BOOTSTRAP_PAYLOAD", + "NEMOCLAW_INSTALL_REF", + "NEMOCLAW_INSTALL_TAG", + "NEMOCLAW_INSTALLER_STAGED", + "NEMOCLAW_INSTALLER_URL", + "NEMOCLAW_OPENSHELL_BIN", + "NEMOCLAW_OPENSHELL_CHANNEL", + "NEMOCLAW_OPENSHELL_GATEWAY_BIN", + "NEMOCLAW_OPENSHELL_SANDBOX_BIN", + "NEMOCLAW_REPO_ROOT", + "NEMOCLAW_SOURCE_ROOT", + "NVM_DIR", + "OLDPWD", + "OPENSSL_CONF", + "OPENSSL_CONF_INCLUDE", + "OPENSSL_ENGINES", + "OPENSSL_MODULES", + "PROGRAMDATA", + "PSMODULEPATH", + "PWD", + "PYTHONUSERBASE", + "TEMP", + "TMP", + "TMPDIR", + "USERPROFILE", + "VIRTUAL_ENV", + "XDG_BIN_HOME", + "XDG_CACHE_HOME", + "XDG_CONFIG_DIRS", + "XDG_CONFIG_HOME", + "XDG_DATA_DIRS", + "XDG_DATA_HOME", + "XDG_RUNTIME_DIR", + "XDG_STATE_HOME", + "ZDOTDIR", +]; +const CONFIG_ROOT_ENV_OVERRIDES = Object.fromEntries( + CONFIG_ROOT_ENV_NAMES.map((name) => [name, `/ambient/${name.toLowerCase()}`]), +) satisfies NodeJS.ProcessEnv; +const PRIVATE_EXECUTION_ENV_PATHS = { + APPDATA: ["appdata", "roaming"], + CURL_HOME: ["config"], + HOME: [], + LOCALAPPDATA: ["appdata", "local"], + PWD: [], + TEMP: ["tmp"], + TMP: ["tmp"], + TMPDIR: ["tmp"], + USERPROFILE: [], + XDG_CACHE_HOME: ["cache"], + XDG_CONFIG_DIRS: ["config-dirs"], + XDG_CONFIG_HOME: ["config"], + XDG_DATA_DIRS: ["data-dirs"], + XDG_DATA_HOME: ["data"], + XDG_RUNTIME_DIR: ["runtime"], + XDG_STATE_HOME: ["state"], +} as const; +const NETWORK_TRUST_ENV_NAMES = [ + "ALL_PROXY", + "AWS_CA_BUNDLE", + "CURL_CA_BUNDLE", + "DENO_CERT", + "FTP_PROXY", + "GIT_PROXY_SSL_CAINFO", + "GIT_SSL_CAINFO", + "GIT_SSL_CAPATH", + "GIT_SSL_NO_VERIFY", + "GRPC_DEFAULT_SSL_ROOTS_FILE_PATH", + "GRPC_PROXY", + "HTTP_PROXY", + "HTTPS_PROXY", + "NODE_EXTRA_CA_CERTS", + "NODE_TLS_REJECT_UNAUTHORIZED", + "NODE_USE_ENV_PROXY", + "NODE_USE_SYSTEM_CA", + "NO_PROXY", + "REQUESTS_CA_BUNDLE", + "SSLKEYLOGFILE", + "SSL_CERT_DIR", + "SSL_CERT_FILE", +]; +const NETWORK_TRUST_ENV_OVERRIDES = { + ...Object.fromEntries( + NETWORK_TRUST_ENV_NAMES.map((name) => [name, `ambient-${name.toLowerCase()}`]), + ), + GIT_SSL_NO_VERIFY: "1", + NODE_EXTRA_CA_CERTS: "", + NODE_TLS_REJECT_UNAUTHORIZED: "0", + NO_PROXY: "*", +} satisfies NodeJS.ProcessEnv; +const PACKAGE_CONTROL_ENV_OVERRIDES = { + npm_config_registry: "https://ambient-registry.invalid", + Pip_Index_Url: "https://ambient-index.invalid/simple", +} satisfies NodeJS.ProcessEnv; +const BLOCKED_INHERITED_ENV_NAMES = [ + ...NETWORK_TRUST_ENV_NAMES, + ...Object.keys(PACKAGE_CONTROL_ENV_OVERRIDES), + "BASH_ENV", + "BASH_FUNC_echo%%", + "DOTNET_STARTUP_HOOKS", + "GIT_EXEC_PATH", + "GIT_CONFIG", + "GH_TOKEN", + "GIT_CONFIG_COUNT", + "GIT_EXTERNAL_DIFF", + "GIT_PROXY_COMMAND", + "GIT_TRACE2_EVENT", + "GIT_SSH", + "Gh_ToKeN", + "NODE_OPTIONS", + "Node_Options", + "NEMOCLAW_PROVIDER", + "OPENSHELL_DOCKER_SUPERVISOR_IMAGE", + "PATH", + "Path", + "UNRELATED_API_TOKEN", +]; + +interface ExitResult { + code: number | null; + signal: NodeJS.Signals | null; +} + +interface CapturedChild { + child: ChildProcess; + closed: Promise; + output(): string; +} + +interface RunningHelper extends CapturedChild { + capability: string; + formUrl: URL; +} + +interface HttpResult { + body: string; + headers: IncomingHttpHeaders; + status: number; +} + +interface RequestOptions { + body?: Buffer | string; + headers?: Record; + method?: string; + omitContentLength?: boolean; + path?: string; +} + +type ReadinessState = { kind: "exited" } | { kind: "ready"; url: string } | { kind: "waiting" }; + +export type LocalCredentialHelperTestGroup = "contract" | "fields" | "session"; + +export function registerLocalCredentialHelperTests(group: LocalCredentialHelperTestGroup): void { + const activeChildren = new Set(); + const tempDirs = new Set(); + + function privateExecutionRoots(): string[] { + return fs + .readdirSync(path.dirname(HELPER_PATH)) + .filter((name) => name.startsWith(".credential-child-")) + .sort(); + } + + afterEach(async () => { + await Promise.all([...activeChildren].map((captured) => terminate(captured))); + activeChildren.clear(); + for (const dir of tempDirs) fs.rmSync(dir, { force: true, recursive: true }); + tempDirs.clear(); + }); + + function captureChild( + args: string[], + envOverrides: NodeJS.ProcessEnv = {}, + cwd = REPO_ROOT, + ): CapturedChild { + const child = spawn(process.execPath, args, { + cwd, + env: { ...process.env, ...envOverrides, NO_COLOR: "1" }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk: Buffer) => { + stdout += chunk.toString("utf8"); + }); + child.stderr.on("data", (chunk: Buffer) => { + stderr += chunk.toString("utf8"); + }); + const closed = new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", (code, signal) => resolve({ code, signal })); + }); + const captured = { + child, + closed, + output: () => `${stdout}${stderr}`, + }; + activeChildren.add(captured); + return captured; + } + + function childHasExited(captured: CapturedChild): boolean { + return captured.child.exitCode !== null || captured.child.signalCode !== null; + } + + async function awaitClosed(captured: CapturedChild): Promise { + await captured.closed.catch(() => undefined); + } + + async function terminateRunning(captured: CapturedChild): Promise { + captured.child.kill("SIGTERM"); + try { + await withTimeout(captured.closed, 1_000, "credential helper SIGTERM"); + } catch { + captured.child.kill("SIGKILL"); + await awaitClosed(captured); + } + } + + async function terminate(captured: CapturedChild): Promise { + await (childHasExited(captured) ? awaitClosed(captured) : terminateRunning(captured)); + } + + async function withTimeout(promise: Promise, timeoutMs: number, label: string): Promise { + let timer: NodeJS.Timeout | undefined; + try { + return await Promise.race([ + promise, + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs); + }), + ]); + } finally { + clearTimeout(timer); + } + } + + function helperArgs( + fields: string[], + command: string[], + formPath = FORM_PATH, + executionProfile: "account-home" | "isolated" = "isolated", + commandCwd?: string, + ): string[] { + const cwdArgs = commandCwd === undefined ? [] : ["--cwd", commandCwd]; + const args = [ + "--experimental-strip-types", + HELPER_PATH, + "--execution-profile", + executionProfile, + "--form", + formPath, + ...cwdArgs, + ]; + return [...args, ...fields.flatMap((field) => ["--field", field]), "--", ...command]; + } + + function readinessState(captured: CapturedChild): ReadinessState { + const url = captured.output().match(READINESS_URL_PATTERN)?.[0]; + return url !== undefined + ? { kind: "ready", url } + : childHasExited(captured) + ? { kind: "exited" } + : { kind: "waiting" }; + } + + async function waitForReadiness(captured: CapturedChild): Promise { + const deadline = Date.now() + PROCESS_TIMEOUT_MS; + while (Date.now() < deadline) { + const state = readinessState(captured); + switch (state.kind) { + case "ready": + return new URL(state.url); + case "exited": { + const result = await captured.closed; + throw new Error( + `credential helper exited before readiness (${result.code ?? result.signal}):\n${captured.output()}`, + ); + } + case "waiting": + await new Promise((resolve) => setTimeout(resolve, 10)); + } + } + throw new Error(`credential helper did not report readiness:\n${captured.output()}`); + } + + async function startHelper( + command: string[], + envOverrides: NodeJS.ProcessEnv = {}, + executionProfile: "account-home" | "isolated" = "isolated", + commandCwd?: string, + helperCwd = REPO_ROOT, + ): Promise { + const captured = captureChild( + helperArgs( + ["OPENAI_API_KEY:secret", "PUBLIC_ID:text"], + command, + FORM_PATH, + executionProfile, + commandCwd, + ), + envOverrides, + helperCwd, + ); + const formUrl = await waitForReadiness(captured); + const fragment = new URLSearchParams(formUrl.hash.slice(1)); + const capability = fragment.get("cap") ?? ""; + expect(capability).toMatch(/^[A-Za-z0-9_-]{43}$/); + return { ...captured, capability, formUrl }; + } + + function createCommandFixture(): { + command: string[]; + markerPath: string; + unexpectedShellPath: string; + } { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-helper-test-")); + tempDirs.add(dir); + const markerPath = path.join(dir, "command-runs.txt"); + const unexpectedShellPath = path.join(dir, "unexpected-shell-execution"); + const secretHash = createHash("sha256").update(TEST_SECRET).digest("hex"); + const fixture = [ + 'const fs = require("node:fs");', + 'const crypto = require("node:crypto");', + 'const path = require("node:path");', + "const [markerPath, publicValue, unexpectedShellPath] = process.argv.slice(1);", + 'const secret = process.env.OPENAI_API_KEY || "";', + 'const actualHash = crypto.createHash("sha256").update(secret).digest("hex");', + `if (actualHash !== ${JSON.stringify(secretHash)}) process.exit(21);`, + `if (process.env.PUBLIC_ID !== ${JSON.stringify(TEST_PUBLIC_VALUE)}) process.exit(22);`, + `if (publicValue !== ${JSON.stringify(TEST_PUBLIC_VALUE)}) process.exit(23);`, + 'if (!process.argv.includes("--")) process.exit(25);', + `if (${JSON.stringify(BLOCKED_INHERITED_ENV_NAMES)}.some((name) => Object.hasOwn(process.env, name))) process.exit(26);`, + `if (Object.values(process.env).some((value) => ${JSON.stringify(Object.values(CONFIG_ROOT_ENV_OVERRIDES))}.includes(value))) process.exit(27);`, + 'const privateRoot = process.env.HOME || "";', + `for (const [name, parts] of Object.entries(${JSON.stringify(PRIVATE_EXECUTION_ENV_PATHS)})) if (process.env[name] !== path.join(privateRoot, ...parts)) process.exit(28);`, + `if (${JSON.stringify(CONFIG_ROOT_ENV_NAMES.filter((name) => !Object.hasOwn(PRIVATE_EXECUTION_ENV_PATHS, name)))}.some((name) => Object.hasOwn(process.env, name))) process.exit(29);`, + "if (!path.isAbsolute(privateRoot) || process.cwd() !== privateRoot) process.exit(30);", + 'if (process.platform !== "win32" && (fs.statSync(privateRoot).mode & 0o077) !== 0) process.exit(31);', + 'if ([".curlrc", ".gitconfig", ".npmrc", ".netrc"].some((name) => fs.existsSync(path.join(privateRoot, name)))) process.exit(32);', + 'fs.writeFileSync(markerPath + ".private-root", privateRoot);', + 'fs.appendFileSync(markerPath, "ran\\n");', + "if (fs.existsSync(unexpectedShellPath)) process.exit(24);", + ].join(""); + return { + command: [ + process.execPath, + "-e", + fixture, + markerPath, + TEST_PUBLIC_VALUE, + unexpectedShellPath, + "--", + "opaque-command-argument", + ], + markerPath, + unexpectedShellPath, + }; + } + + function request(url: URL, options: RequestOptions = {}): Promise { + const body = + typeof options.body === "string" ? Buffer.from(options.body, "utf8") : options.body; + const suppliedHeaders = options.headers ?? {}; + const hasContentLength = Object.keys(suppliedHeaders).some( + (name) => name.toLowerCase() === "content-length", + ); + const generatedHeaders = + body !== undefined && !hasContentLength && !options.omitContentLength + ? { "content-length": String(body.length) } + : {}; + const headers = { ...suppliedHeaders, ...generatedHeaders }; + + return new Promise((resolve, reject) => { + const clientRequest = http.request( + { + agent: false, + headers, + hostname: url.hostname, + method: options.method ?? "GET", + path: options.path ?? `${url.pathname}${url.search}`, + port: url.port, + }, + (response) => { + const chunks: Buffer[] = []; + response.on("data", (chunk: Buffer) => chunks.push(chunk)); + response.on("end", () => { + resolve({ + body: Buffer.concat(chunks).toString("utf8"), + headers: response.headers, + status: response.statusCode ?? 0, + }); + }); + }, + ); + clientRequest.setTimeout(3_000, () => { + clientRequest.destroy(new Error("credential helper request timed out")); + }); + clientRequest.on("error", reject); + clientRequest.end(body); + }); + } + + function validHeaders(helper: RunningHelper): Record { + return { + "content-type": "application/json", + origin: helper.formUrl.origin, + "x-nemoclaw-capability": helper.capability, + }; + } + + function validBody(): string { + return JSON.stringify({ + values: { + OPENAI_API_KEY: TEST_SECRET, + PUBLIC_ID: TEST_PUBLIC_VALUE, + }, + }); + } + + function expectNoCors(headers: IncomingHttpHeaders): void { + expect(headers["access-control-allow-origin"]).toBeUndefined(); + expect(headers["access-control-allow-credentials"]).toBeUndefined(); + expect(headers["access-control-allow-headers"]).toBeUndefined(); + expect(headers["access-control-allow-methods"]).toBeUndefined(); + } + + function expectRejected(result: HttpResult): void { + expect(result.status).toBeGreaterThanOrEqual(400); + expect(result.status).toBeLessThan(500); + expectNoCors(result.headers); + expect(result.body).not.toContain(TEST_SECRET); + } + + function expectHttpStatus(result: HttpResult, expected: number): void { + expect(result.status).toBe(expected); + } + + async function expectCompletionCode( + completion: Promise, + expected: number, + ): Promise { + expect(await completion).toBe(expected); + } + + function commandRunCount(markerPath: string): number { + try { + return fs.readFileSync(markerPath, "utf8").split("\n").filter(Boolean).length; + } catch { + return 0; + } + } + + async function expectSuccessfulCompletion( + helper: RunningHelper, + markerPath: string, + ): Promise { + const result = await withTimeout(helper.closed, PROCESS_TIMEOUT_MS, "credential helper exit"); + expect(result).toEqual({ code: 0, signal: null }); + expect(commandRunCount(markerPath)).toBe(1); + const privateRootMarker = `${markerPath}.private-root`; + const privateRootStillExists = + fs.existsSync(privateRootMarker) && fs.existsSync(fs.readFileSync(privateRootMarker, "utf8")); + expect(privateRootStillExists).toBe(false); + } + + describe("local credential helper", () => { + if (group === "contract") { + it("hashes inline form tags case-insensitively for CSP generation (#5048)", () => { + const csp = buildCredentialFormCsp(Buffer.from("")); + + expect(csp).toContain("script-src 'sha256-"); + expect(csp).toContain("style-src 'sha256-"); + }); + + it("drops every ambient entry without mutating the source environment (#5048)", () => { + const ambient = { + ...CONFIG_ROOT_ENV_OVERRIDES, + ...NETWORK_TRUST_ENV_OVERRIDES, + ...PACKAGE_CONTROL_ENV_OVERRIDES, + BASH_ENV: "shell-hook", + "BASH_FUNC_echo%%": '() { printf "%s" "$OPENAI_API_KEY"; }', + DOTNET_STARTUP_HOOKS: "startup-hook", + DYLD_INSERT_LIBRARIES: "loader-hook", + Gh_ToKeN: "credential", + GIT_CONFIG: "git-config", + GIT_CONFIG_COUNT: "1", + GIT_EXTERNAL_DIFF: "/ambient/diff-wrapper", + GIT_EXEC_PATH: "/ambient/git-core", + GIT_PROXY_COMMAND: "/ambient/proxy-wrapper", + GIT_TRACE2_EVENT: "/ambient/git-trace.json", + GIT_SSH: "/ambient/ssh-wrapper", + LD_PRELOAD: "loader-hook", + NEMOCLAW_PROVIDER: "ambient-provider", + Node_Options: "--no-warnings", + Path: "/ambient/search/path", + Public_Id: "ambient-field-collision", + UNKNOWN_AMBIENT_SETTING: "removed", + SSH_AUTH_SOCK: "/ambient/agent.sock", + } satisfies NodeJS.ProcessEnv; + const original = { ...ambient }; + + const sanitized = sanitizeInheritedChildEnvironment(ambient, new Set(["PUBLIC_ID"])); + + expect(sanitized).toEqual({}); + expect(ambient).toEqual(original); + }); + + it("allows explicitly collected NemoClaw settings while denying their ambient values (#5048)", () => { + expect(parseCredentialField("NEMOCLAW_PROVIDER:text")).toEqual({ + name: "NEMOCLAW_PROVIDER", + type: "text", + }); + expect( + sanitizeInheritedChildEnvironment( + { NEMOCLAW_MODEL: "ambient-model", NEMOCLAW_PROVIDER: "ambient-provider" }, + new Set(["NEMOCLAW_PROVIDER"]), + ), + ).toEqual({}); + }); + } + + if (group === "fields") { + it.each([ + { + fields: ["OPENAI_API_KEY:text"], + label: "secret-shaped field declared as text", + }, + { fields: ["PATH:text"], label: "process search path field" }, + { fields: ["NODE_OPTIONS:secret"], label: "Node process-control field" }, + { fields: ["BASH_FUNC_ECHO:secret"], label: "exported Bash function field prefix" }, + { fields: ["DOTNET_STARTUP_HOOKS:secret"], label: ".NET startup hook field" }, + { fields: ["GIT_EXEC_PATH:secret"], label: "Git executable path field" }, + { fields: ["GIT_EXTERNAL_DIFF:secret"], label: "Git external diff field" }, + { fields: ["GIT_PROXY_COMMAND:secret"], label: "Git proxy command field" }, + { fields: ["GIT_TRACE2_EVENT:secret"], label: "Git trace field prefix" }, + { fields: ["GIT_SSH:secret"], label: "Git SSH wrapper field" }, + { fields: ["LD_PRELOAD:secret"], label: "dynamic-loader field prefix" }, + { fields: ["DYLD_INSERT_LIBRARIES:secret"], label: "macOS dynamic-loader field prefix" }, + { fields: ["GIT_CONFIG:secret"], label: "exact Git config process-control field" }, + { fields: ["GIT_CONFIG_COUNT:secret"], label: "Git config process-control field prefix" }, + ...CONFIG_ROOT_ENV_NAMES.map((name) => ({ + fields: [`${name}:text`], + label: `${name} configuration-root field`, + })), + ...NETWORK_TRUST_ENV_NAMES.map((name) => ({ + fields: [`${name}:text`], + label: `${name} network or trust control field`, + })), + { fields: ["NPM_CONFIG_REGISTRY:text"], label: "npm configuration field prefix" }, + { + fields: ["OPENSHELL_DOCKER_SUPERVISOR_IMAGE:text"], + label: "OpenShell configuration field prefix", + }, + { fields: ["PIP_INDEX_URL:text"], label: "pip configuration field prefix" }, + { + fields: ["PUBLIC_ID:text", "PUBLIC_ID:text"], + label: "duplicate field", + }, + { + fields: Array.from({ length: 17 }, (_value, index) => `PUBLIC_ID_${index}:text`), + label: "field count above the session limit", + }, + { fields: ["bad-name:secret"], label: "malformed field name" }, + ])("rejects $label before listening (#5048)", async ({ fields }) => { + const captured = captureChild( + helperArgs(fields, [process.execPath, "-e", "process.exit(0)"]), + ); + + const result = await withTimeout(captured.closed, PROCESS_TIMEOUT_MS, "invalid helper CLI"); + + expect(result.code).not.toBe(0); + expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); + }); + + it.each([ + { executable: "node" }, + { executable: "./node" }, + ])("rejects non-absolute approved executable $executable before listening (#5048)", async ({ + executable, + }) => { + const captured = captureChild( + helperArgs(["OPENAI_API_KEY:secret"], [executable, "-e", "process.exit(0)"]), + ); + + const result = await withTimeout( + captured.closed, + PROCESS_TIMEOUT_MS, + "relative executable", + ); + + expect(result.code).not.toBe(0); + expect(captured.output()).toContain( + "approved command executable must use an absolute path", + ); + expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); + }); + + it.each([ + { + options: [], + expected: "--execution-profile isolated or --execution-profile account-home is required", + }, + { + options: ["--execution-profile", "unknown"], + expected: "--execution-profile must be isolated or account-home", + }, + { + options: ["--execution-profile", "account-home"], + expected: "--execution-profile account-home requires an absolute --cwd path", + }, + { + options: ["--execution-profile", "account-home", "--cwd", "relative"], + expected: "--cwd must be an absolute path without NUL bytes", + }, + { + options: ["--execution-profile", "isolated", "--cwd", REPO_ROOT], + expected: "--execution-profile isolated does not accept --cwd", + }, + ])("rejects an unsafe or ambiguous execution profile before listening (#5048)", async ({ + expected, + options, + }) => { + const captured = captureChild([ + "--experimental-strip-types", + HELPER_PATH, + ...options, + "--field", + "OPENAI_API_KEY:secret", + "--", + process.execPath, + "-e", + "process.exit(0)", + ]); + + const result = await withTimeout(captured.closed, PROCESS_TIMEOUT_MS, "execution profile"); + + expect(result.code).not.toBe(0); + expect(captured.output()).toContain(expected); + expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); + }); + } + + if (group === "contract") { + it("rejects a non-absolute executable through the direct session API (#5048)", async () => { + await expect( + startLocalCredentialHelper({ + commandArgv: ["node", "-e", "process.exit(0)"], + executionProfile: "isolated", + fields: [{ name: "OPENAI_API_KEY", type: "secret" }], + formBytes: fs.readFileSync(FORM_PATH), + }), + ).rejects.toThrow("approved command executable must use an absolute path"); + }); + + it("rejects a missing or unknown execution profile through the direct session API (#5048)", async () => { + await expect( + startLocalCredentialHelper({ + commandArgv: [process.execPath, "-e", "process.exit(0)"], + executionProfile: "unknown" as "isolated", + fields: [{ name: "OPENAI_API_KEY", type: "secret" }], + formBytes: fs.readFileSync(FORM_PATH), + }), + ).rejects.toThrow("execution profile must be isolated or account-home"); + }); + } + + if (group === "session") { + it("removes the isolated execution root when a session expires (#5048)", async () => { + const rootsBefore = privateExecutionRoots(); + const session = await startLocalCredentialHelper({ + commandArgv: [process.execPath, "-e", "process.exit(0)"], + executionProfile: "isolated", + fields: [{ name: "OPENAI_API_KEY", type: "secret" }], + formBytes: fs.readFileSync(FORM_PATH), + timeoutMs: 20, + }); + + await expectCompletionCode(session.completion, 1); + expect(privateExecutionRoots()).toEqual(rootsBefore); + }); + + it("removes the isolated execution root when the approved executable cannot start (#5048)", async () => { + const rootsBefore = privateExecutionRoots(); + const missingExecutable = path.join( + path.parse(process.execPath).root, + "nemoclaw-definitely-missing-executable", + ); + const session = await startLocalCredentialHelper({ + commandArgv: [missingExecutable], + executionProfile: "isolated", + fields: [ + { name: "OPENAI_API_KEY", type: "secret" }, + { name: "PUBLIC_ID", type: "text" }, + ], + formBytes: fs.readFileSync(FORM_PATH), + }); + const formUrl = new URL(session.url); + const capability = new URLSearchParams(formUrl.hash.slice(1)).get("cap") ?? ""; + const accepted = await request(formUrl, { + body: validBody(), + headers: { + "content-type": "application/json", + origin: formUrl.origin, + "x-nemoclaw-capability": capability, + }, + method: "POST", + path: "/submit", + }); + + expectHttpStatus(accepted, 202); + await expectCompletionCode(session.completion, 1); + expect(privateExecutionRoots()).toEqual(rootsBefore); + }); + + it("rejects a modified credential form before listening (#5048)", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-form-test-")); + tempDirs.add(dir); + const modifiedFormPath = path.join(dir, "local-credential-form.html"); + const modifiedForm = Buffer.concat([fs.readFileSync(FORM_PATH), Buffer.from("\n")]); + fs.writeFileSync(modifiedFormPath, modifiedForm); + const captured = captureChild( + helperArgs( + ["OPENAI_API_KEY:secret"], + [process.execPath, "-e", "process.exit(0)"], + modifiedFormPath, + ), + ); + + const result = await withTimeout( + captured.closed, + PROCESS_TIMEOUT_MS, + "modified helper form", + ); + + expect(result.code).not.toBe(0); + expect(captured.output()).toContain("Local credential form SHA-256 mismatch"); + expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); + }); + + it("serves only the exact form bytes with hardened non-CORS headers (#5048)", async () => { + const fixture = createCommandFixture(); + const helper = await startHelper(fixture.command); + const result = await request(helper.formUrl); + + expect(helper.formUrl.origin).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/); + expect(helper.formUrl.searchParams.has("cap")).toBe(false); + expect(result.status).toBe(200); + expect(result.body).toContain("NemoClaw Local Credential Form"); + expect(Number(result.headers["content-length"])).toBe(Buffer.byteLength(result.body)); + expect(result.body).not.toContain(helper.capability); + expect(JSON.stringify(result.headers)).not.toContain(helper.capability); + expect(result.headers["content-type"]).toMatch(/^text\/html(?:;\s*charset=utf-8)?$/i); + expect(result.headers["content-security-policy"]).toContain("frame-ancestors 'none'"); + expect(result.headers["cache-control"]).toBe("no-store"); + expect(result.headers["x-content-type-options"]).toBe("nosniff"); + expect(result.headers["referrer-policy"]).toBe("no-referrer"); + expect(result.headers["cross-origin-resource-policy"]).toBe("same-origin"); + expect(result.headers["cross-origin-opener-policy"]).toBe("same-origin"); + expectNoCors(result.headers); + expect(commandRunCount(fixture.markerPath)).toBe(0); + + const modifiedTarget = await request(helper.formUrl, { + path: `${helper.formUrl.pathname}${helper.formUrl.search}&unexpected=1`, + }); + expectRejected(modifiedTarget); + + const stillAvailable = await request(helper.formUrl); + expect(stillAvailable.status).toBe(200); + expect(stillAvailable.body).toBe(result.body); + expect(commandRunCount(fixture.markerPath)).toBe(0); + }); + + it("strips inherited credentials and process controls before launching the approved command (#5048)", async () => { + const fixture = createCommandFixture(); + const hostileConfigRoot = fs.mkdtempSync( + path.join(os.tmpdir(), "nemoclaw-hostile-config-"), + ); + tempDirs.add(hostileConfigRoot); + for (const relativePath of [".curlrc", ".gitconfig", ".netrc", ".npmrc", ".zshenv"]) { + fs.writeFileSync(path.join(hostileConfigRoot, relativePath), "attack-marker\n"); + } + fs.mkdirSync(path.join(hostileConfigRoot, ".git")); + fs.writeFileSync( + path.join(hostileConfigRoot, ".git", "config"), + "[credential]\nhelper = attack\n", + ); + fs.mkdirSync(path.join(hostileConfigRoot, "pip")); + fs.writeFileSync( + path.join(hostileConfigRoot, "pip", "pip.conf"), + "[global]\nindex-url=attack\n", + ); + const helper = await startHelper( + fixture.command, + { + ...CONFIG_ROOT_ENV_OVERRIDES, + ...NETWORK_TRUST_ENV_OVERRIDES, + ...PACKAGE_CONTROL_ENV_OVERRIDES, + BASH_ENV: "ambient-shell-hook", + "BASH_FUNC_echo%%": '() { printf "%s" "$OPENAI_API_KEY"; }', + DOTNET_STARTUP_HOOKS: "ambient-startup-hook", + GIT_EXEC_PATH: "/ambient/git-core", + GIT_CONFIG: "ambient-git-config", + GH_TOKEN: "ambient-github-token", + Gh_ToKeN: "ambient-mixed-case-github-token", + GIT_CONFIG_COUNT: "1", + GIT_EXTERNAL_DIFF: "/ambient/diff-wrapper", + GIT_PROXY_COMMAND: "/ambient/proxy-wrapper", + GIT_TRACE2_EVENT: "/ambient/git-trace.json", + GIT_SSH: "/ambient/ssh-wrapper", + NODE_OPTIONS: "--no-warnings", + Node_Options: "--no-warnings", + NEMOCLAW_PROVIDER: "ambient-provider", + OPENSHELL_DOCKER_SUPERVISOR_IMAGE: "attacker.invalid/supervisor:latest", + OPENAI_API_KEY: "ambient-openai-key", + PATH: "/ambient/search/path", + Path: "/ambient/mixed-case/search/path", + PUBLIC_ID: "ambient-public-id", + UNRELATED_API_TOKEN: "ambient-generic-token", + HOME: hostileConfigRoot, + XDG_CONFIG_HOME: hostileConfigRoot, + }, + "isolated", + undefined, + hostileConfigRoot, + ); + + const accepted = await request(helper.formUrl, { + body: validBody(), + headers: validHeaders(helper), + method: "POST", + path: "/submit", + }); + + expect(accepted.status).toBe(202); + await expectSuccessfulCompletion(helper, fixture.markerPath); + }); + + it.runIf(process.platform !== "win32" && fs.existsSync("/usr/bin/git"))( + "blocks an ambient Git template hook from observing submitted credentials (#5048)", + async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-git-template-test-")); + tempDirs.add(dir); + const source = path.join(dir, "source"); + const destination = path.join(dir, "clone"); + const template = path.join(dir, "template"); + const hooks = path.join(template, "hooks"); + const leakPath = path.join(dir, "leaked-secret.txt"); + fs.mkdirSync(hooks, { recursive: true }); + + execFileSync("/usr/bin/git", ["init", "--quiet", source]); + fs.writeFileSync(path.join(source, "tracked.txt"), "fixture\n"); + execFileSync("/usr/bin/git", ["-C", source, "add", "tracked.txt"]); + execFileSync("/usr/bin/git", [ + "-C", + source, + "-c", + "user.name=NemoClaw Test", + "-c", + "user.email=nemoclaw-test@example.invalid", + "commit", + "--quiet", + "--no-gpg-sign", + "-m", + "fixture", + ]); + + const hookPath = path.join(hooks, "post-checkout"); + const quotedLeakPath = `'${leakPath.replaceAll("'", `'"'"'`)}'`; + fs.writeFileSync( + hookPath, + `#!/bin/sh\nprintf '%s' "$OPENAI_API_KEY" > ${quotedLeakPath}\n`, + ); + fs.chmodSync(hookPath, 0o755); + + const helper = await startHelper( + ["/usr/bin/git", "clone", "--quiet", source, destination], + { + GIT_TEMPLATE_DIR: template, + }, + ); + const accepted = await request(helper.formUrl, { + body: validBody(), + headers: validHeaders(helper), + method: "POST", + path: "/submit", + }); + + expect(accepted.status).toBe(202); + await expect(helper.closed).resolves.toEqual({ code: 0, signal: null }); + expect(fs.readFileSync(path.join(destination, "tracked.txt"), "utf8")).toBe("fixture\n"); + expect(fs.existsSync(path.join(destination, ".git", "hooks", "post-checkout"))).toBe( + false, + ); + expect(fs.existsSync(leakPath)).toBe(false); + expect(helper.output()).not.toContain(TEST_SECRET); + }, + ); + + it("uses only the explicit cwd and OS account home in account-home mode (#5048)", async () => { + const commandCwd = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-account-cwd-test-")); + tempDirs.add(commandCwd); + const markerPath = path.join(commandCwd, "account-context.json"); + const command = [ + process.execPath, + "-e", + `require("node:fs").writeFileSync(process.argv[1], JSON.stringify({cwd:process.cwd(),environment:Object.fromEntries(${JSON.stringify(CONFIG_ROOT_ENV_NAMES)}.map((name)=>[name,process.env[name]]))}))`, + markerPath, + ]; + const helper = await startHelper( + command, + CONFIG_ROOT_ENV_OVERRIDES, + "account-home", + commandCwd, + ); + + const accepted = await request(helper.formUrl, { + body: validBody(), + headers: validHeaders(helper), + method: "POST", + path: "/submit", + }); + + expect(accepted.status).toBe(202); + await expectSuccessfulCompletion(helper, markerPath); + const observed = JSON.parse(fs.readFileSync(markerPath, "utf8")) as { + cwd: string; + environment: Record; + }; + const accountHome = os.userInfo().homedir; + const accountTemp = path.join(accountHome, "AppData", "Local", "Temp"); + const hasWindowsDrive = /^[A-Za-z]:[\\/]/.test(accountHome); + const expectedEnvironment: Record = + process.platform === "win32" + ? { + APPDATA: path.join(accountHome, "AppData", "Roaming"), + ...(hasWindowsDrive + ? { + HOMEDRIVE: accountHome.slice(0, 2), + HOMEPATH: accountHome.slice(2) || "\\", + } + : {}), + HOME: accountHome, + LOCALAPPDATA: path.join(accountHome, "AppData", "Local"), + PWD: commandCwd, + TEMP: accountTemp, + TMP: accountTemp, + TMPDIR: accountTemp, + USERPROFILE: accountHome, + } + : { HOME: accountHome, PWD: commandCwd }; + expect(observed.cwd).toBe(commandCwd); + expect( + Object.fromEntries(Object.entries(observed.environment).filter(([, value]) => value)), + ).toEqual(expectedEnvironment); + }); + + it("preserves explicit approved proxy, CA, and config arguments byte-for-byte (#5048)", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-argv-test-")); + tempDirs.add(dir); + const markerPath = path.join(dir, "command-argv.json"); + const expectedArgv = [ + "--proxy", + "http://trusted-proxy.internal:3128", + "--noproxy", + "127.0.0.1", + "--cacert", + "/trusted/ca.pem", + "--config", + "/trusted/client.conf", + "--profile", + "approved-profile", + ]; + const command = [ + process.execPath, + "-e", + 'require("node:fs").writeFileSync(process.argv[1], JSON.stringify(process.argv.slice(2)))', + markerPath, + ...expectedArgv, + ]; + const helper = await startHelper(command, NETWORK_TRUST_ENV_OVERRIDES); + + const accepted = await request(helper.formUrl, { + body: validBody(), + headers: validHeaders(helper), + method: "POST", + path: "/submit", + }); + + expect(accepted.status).toBe(202); + await expectSuccessfulCompletion(helper, markerPath); + expect(JSON.parse(fs.readFileSync(markerPath, "utf8"))).toEqual(expectedArgv); + }); + + it("blocks an inherited Bash function from intercepting the approved command (#5048)", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-bash-test-")); + tempDirs.add(dir); + const markerPath = path.join(dir, "command-runs.txt"); + const attackMarkerPath = path.join(dir, "ambient-function-ran.txt"); + const command = [ + "/bin/bash", + "--noprofile", + "--norc", + "-c", + 'echo safe >/dev/null && test ! -e "$ATTACK_MARKER" && printf "ran\\n" > "$1"', + "bash", + markerPath, + ]; + const helper = await startHelper(command, { + ATTACK_MARKER: attackMarkerPath, + "BASH_FUNC_echo%%": '() { printf "%s" "$OPENAI_API_KEY" > "$ATTACK_MARKER"; }', + PATH: "/ambient/search/path", + }); + + const accepted = await request(helper.formUrl, { + body: validBody(), + headers: validHeaders(helper), + method: "POST", + path: "/submit", + }); + + expect(accepted.status).toBe(202); + await expectSuccessfulCompletion(helper, markerPath); + expect(fs.existsSync(attackMarkerPath)).toBe(false); + }); + + it("rejects Host, Origin, capability, and CORS probes without consuming the session (#5048)", async () => { + const fixture = createCommandFixture(); + const helper = await startHelper(fixture.command); + const body = validBody(); + const attacks: RequestOptions[] = [ + { + body, + headers: { ...validHeaders(helper), host: `localhost:${helper.formUrl.port}` }, + method: "POST", + path: "/submit", + }, + { + body, + headers: { ...validHeaders(helper), origin: `http://localhost:${helper.formUrl.port}` }, + method: "POST", + path: "/submit", + }, + { + body, + headers: { + ...validHeaders(helper), + "x-nemoclaw-capability": "x".repeat(43), + }, + method: "POST", + path: "/submit", + }, + { + body, + headers: { + "content-type": "application/json", + origin: helper.formUrl.origin, + }, + method: "POST", + path: "/submit", + }, + { + headers: { + "access-control-request-headers": "x-nemoclaw-capability, content-type", + "access-control-request-method": "POST", + origin: "https://attacker.invalid", + }, + method: "OPTIONS", + path: "/submit", + }, + ]; + + for (const attack of attacks) { + expectRejected(await request(helper.formUrl, attack)); + expect(commandRunCount(fixture.markerPath)).toBe(0); + } + + const accepted = await request(helper.formUrl, { + body, + headers: validHeaders(helper), + method: "POST", + path: "/submit", + }); + expect(accepted.status).toBe(202); + expectNoCors(accepted.headers); + await expectSuccessfulCompletion(helper, fixture.markerPath); + }); + + it("rejects media, encoding, body, and exact-schema violations without consuming the session (#5048)", async () => { + const fixture = createCommandFixture(); + const helper = await startHelper(fixture.command); + const authHeaders = validHeaders(helper); + const invalidRequests: RequestOptions[] = [ + { + body: validBody(), + headers: { ...authHeaders, "content-type": "text/plain" }, + method: "POST", + path: "/submit", + }, + { + body: validBody(), + headers: { ...authHeaders, "content-type": "application/json; charset=utf-8" }, + method: "POST", + path: "/submit", + }, + { + body: validBody(), + headers: { ...authHeaders, "content-encoding": "gzip" }, + method: "POST", + path: "/submit", + }, + { + body: validBody(), + headers: { ...authHeaders, "transfer-encoding": "chunked" }, + method: "POST", + omitContentLength: true, + path: "/submit", + }, + { + body: Buffer.alloc(65_537, 0x61), + headers: authHeaders, + method: "POST", + path: "/submit", + }, + { + body: "{not-json", + headers: authHeaders, + method: "POST", + path: "/submit", + }, + { + body: JSON.stringify({ values: { OPENAI_API_KEY: TEST_SECRET } }), + headers: authHeaders, + method: "POST", + path: "/submit", + }, + { + body: JSON.stringify({ + argv: ["sh", "-c", "unexpected"], + values: { OPENAI_API_KEY: TEST_SECRET, PUBLIC_ID: TEST_PUBLIC_VALUE }, + }), + headers: authHeaders, + method: "POST", + path: "/submit", + }, + { + body: JSON.stringify({ + values: { OPENAI_API_KEY: TEST_SECRET, PUBLIC_ID: 42 }, + }), + headers: authHeaders, + method: "POST", + path: "/submit", + }, + { + body: JSON.stringify({ + values: { OPENAI_API_KEY: TEST_SECRET, PUBLIC_ID: "é".repeat(8_193) }, + }), + headers: authHeaders, + method: "POST", + path: "/submit", + }, + ]; + + for (const invalid of invalidRequests) { + expectRejected(await request(helper.formUrl, invalid)); + expect(commandRunCount(fixture.markerPath)).toBe(0); + } + + const accepted = await request(helper.formUrl, { + body: validBody(), + headers: authHeaders, + method: "POST", + path: "/submit", + }); + expect(accepted.status).toBe(202); + await expectSuccessfulCompletion(helper, fixture.markerPath); + }); + + it("claims one racing submission, runs the command once, and closes the listener (#5048)", async () => { + const fixture = createCommandFixture(); + const helper = await startHelper(fixture.command); + const submission = () => + request(helper.formUrl, { + body: validBody(), + headers: validHeaders(helper), + method: "POST", + path: "/submit", + }); + + const outcomes = await Promise.allSettled([submission(), submission()]); + const responses = outcomes.flatMap((outcome) => + outcome.status === "fulfilled" ? [outcome.value] : [], + ); + const accepted = responses.filter((response) => response.status === 202); + + expect(accepted).toHaveLength(1); + expect( + responses.filter((response) => response.status >= 200 && response.status < 300), + ).toEqual(accepted); + for (const response of responses.filter((response) => response.status !== 202)) { + expect(response.status).toBe(409); + expectNoCors(response.headers); + } + expect(accepted[0]?.headers.connection).toBe("close"); + expect(accepted[0]?.body).not.toContain(TEST_SECRET); + + await expectSuccessfulCompletion(helper, fixture.markerPath); + expect(helper.output()).not.toContain(TEST_SECRET); + expect(fs.existsSync(fixture.unexpectedShellPath)).toBe(false); + await expect(request(helper.formUrl)).rejects.toBeInstanceOf(Error); + }); + + it("executes once when the client sends a valid request and abandons the response (#5048)", async () => { + const fixture = createCommandFixture(); + const helper = await startHelper(fixture.command); + const body = validBody(); + const rawRequest = [ + "POST /submit HTTP/1.1", + `Host: ${helper.formUrl.host}`, + `Origin: ${helper.formUrl.origin}`, + `X-NemoClaw-Capability: ${helper.capability}`, + "Content-Type: application/json", + `Content-Length: ${Buffer.byteLength(body)}`, + "Connection: close", + "", + body, + ].join("\r\n"); + + await new Promise((resolve, reject) => { + const socket = net.createConnection( + { host: helper.formUrl.hostname, port: Number(helper.formUrl.port) }, + () => { + socket.end(rawRequest, () => { + socket.destroy(); + resolve(); + }); + }, + ); + socket.once("error", reject); + }); + + await expectSuccessfulCompletion(helper, fixture.markerPath); + expect(helper.output()).not.toContain(TEST_SECRET); + await expect(request(helper.formUrl)).rejects.toBeInstanceOf(Error); + }); + } + }); +} diff --git a/test/local-credential-helper.test.ts b/test/local-credential-helper.test.ts deleted file mode 100644 index b942ca664a7..00000000000 --- a/test/local-credential-helper.test.ts +++ /dev/null @@ -1,1258 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { type ChildProcess, execFileSync, spawn } from "node:child_process"; -import { createHash } from "node:crypto"; -import fs from "node:fs"; -import http, { type IncomingHttpHeaders } from "node:http"; -import net from "node:net"; -import os from "node:os"; -import path from "node:path"; - -import { afterEach, describe, expect, it } from "vitest"; - -import { - buildCredentialFormCsp, - parseCredentialField, - sanitizeInheritedChildEnvironment, - startLocalCredentialHelper, -} from "../scripts/local-credential-helper.mts"; - -const REPO_ROOT = path.resolve(import.meta.dirname, ".."); -const HELPER_PATH = path.join(REPO_ROOT, "scripts", "local-credential-helper.mts"); -const FORM_PATH = path.join(REPO_ROOT, "docs", "resources", "local-credential-form.html"); -const READINESS_URL_PATTERN = /http:\/\/127\.0\.0\.1:\d+\/\S*#cap=[A-Za-z0-9_-]{43}/; -const PROCESS_TIMEOUT_MS = 5_000; -const TEST_SECRET = "integration-secret-value"; -const TEST_PUBLIC_VALUE = "public-id"; -const CONFIG_ROOT_ENV_NAMES = [ - "ALLUSERSPROFILE", - "APPDATA", - "CURL_HOME", - "DOCKER_CERT_PATH", - "DOCKER_CONFIG", - "DOCKER_CONTEXT", - "DOCKER_HOST", - "DOCKER_TLS_VERIFY", - "GCONV_PATH", - "GIT_COMMON_DIR", - "GIT_DIR", - "GLIBC_TUNABLES", - "HOME", - "HOMEDRIVE", - "HOMEPATH", - "KUBECONFIG", - "LOCALAPPDATA", - "LOCPATH", - "NETRC", - "NEMOCLAW_ACCEPT_DEV_UNVERIFIED_INSTALL", - "NEMOCLAW_BOOTSTRAP_PAYLOAD", - "NEMOCLAW_INSTALL_REF", - "NEMOCLAW_INSTALL_TAG", - "NEMOCLAW_INSTALLER_STAGED", - "NEMOCLAW_INSTALLER_URL", - "NEMOCLAW_OPENSHELL_BIN", - "NEMOCLAW_OPENSHELL_CHANNEL", - "NEMOCLAW_OPENSHELL_GATEWAY_BIN", - "NEMOCLAW_OPENSHELL_SANDBOX_BIN", - "NEMOCLAW_REPO_ROOT", - "NEMOCLAW_SOURCE_ROOT", - "NVM_DIR", - "OLDPWD", - "OPENSSL_CONF", - "OPENSSL_CONF_INCLUDE", - "OPENSSL_ENGINES", - "OPENSSL_MODULES", - "PROGRAMDATA", - "PSMODULEPATH", - "PWD", - "PYTHONUSERBASE", - "TEMP", - "TMP", - "TMPDIR", - "USERPROFILE", - "VIRTUAL_ENV", - "XDG_BIN_HOME", - "XDG_CACHE_HOME", - "XDG_CONFIG_DIRS", - "XDG_CONFIG_HOME", - "XDG_DATA_DIRS", - "XDG_DATA_HOME", - "XDG_RUNTIME_DIR", - "XDG_STATE_HOME", - "ZDOTDIR", -]; -const CONFIG_ROOT_ENV_OVERRIDES = Object.fromEntries( - CONFIG_ROOT_ENV_NAMES.map((name) => [name, `/ambient/${name.toLowerCase()}`]), -) satisfies NodeJS.ProcessEnv; -const PRIVATE_EXECUTION_ENV_PATHS = { - APPDATA: ["appdata", "roaming"], - CURL_HOME: ["config"], - HOME: [], - LOCALAPPDATA: ["appdata", "local"], - PWD: [], - TEMP: ["tmp"], - TMP: ["tmp"], - TMPDIR: ["tmp"], - USERPROFILE: [], - XDG_CACHE_HOME: ["cache"], - XDG_CONFIG_DIRS: ["config-dirs"], - XDG_CONFIG_HOME: ["config"], - XDG_DATA_DIRS: ["data-dirs"], - XDG_DATA_HOME: ["data"], - XDG_RUNTIME_DIR: ["runtime"], - XDG_STATE_HOME: ["state"], -} as const; -const NETWORK_TRUST_ENV_NAMES = [ - "ALL_PROXY", - "AWS_CA_BUNDLE", - "CURL_CA_BUNDLE", - "DENO_CERT", - "FTP_PROXY", - "GIT_PROXY_SSL_CAINFO", - "GIT_SSL_CAINFO", - "GIT_SSL_CAPATH", - "GIT_SSL_NO_VERIFY", - "GRPC_DEFAULT_SSL_ROOTS_FILE_PATH", - "GRPC_PROXY", - "HTTP_PROXY", - "HTTPS_PROXY", - "NODE_EXTRA_CA_CERTS", - "NODE_TLS_REJECT_UNAUTHORIZED", - "NODE_USE_ENV_PROXY", - "NODE_USE_SYSTEM_CA", - "NO_PROXY", - "REQUESTS_CA_BUNDLE", - "SSLKEYLOGFILE", - "SSL_CERT_DIR", - "SSL_CERT_FILE", -]; -const NETWORK_TRUST_ENV_OVERRIDES = { - ...Object.fromEntries( - NETWORK_TRUST_ENV_NAMES.map((name) => [name, `ambient-${name.toLowerCase()}`]), - ), - GIT_SSL_NO_VERIFY: "1", - NODE_EXTRA_CA_CERTS: "", - NODE_TLS_REJECT_UNAUTHORIZED: "0", - NO_PROXY: "*", -} satisfies NodeJS.ProcessEnv; -const PACKAGE_CONTROL_ENV_OVERRIDES = { - npm_config_registry: "https://ambient-registry.invalid", - Pip_Index_Url: "https://ambient-index.invalid/simple", -} satisfies NodeJS.ProcessEnv; -const BLOCKED_INHERITED_ENV_NAMES = [ - ...NETWORK_TRUST_ENV_NAMES, - ...Object.keys(PACKAGE_CONTROL_ENV_OVERRIDES), - "BASH_ENV", - "BASH_FUNC_echo%%", - "DOTNET_STARTUP_HOOKS", - "GIT_EXEC_PATH", - "GIT_CONFIG", - "GH_TOKEN", - "GIT_CONFIG_COUNT", - "GIT_EXTERNAL_DIFF", - "GIT_PROXY_COMMAND", - "GIT_TRACE2_EVENT", - "GIT_SSH", - "Gh_ToKeN", - "NODE_OPTIONS", - "Node_Options", - "NEMOCLAW_PROVIDER", - "OPENSHELL_DOCKER_SUPERVISOR_IMAGE", - "PATH", - "Path", - "UNRELATED_API_TOKEN", -]; - -interface ExitResult { - code: number | null; - signal: NodeJS.Signals | null; -} - -interface CapturedChild { - child: ChildProcess; - closed: Promise; - output(): string; -} - -interface RunningHelper extends CapturedChild { - capability: string; - formUrl: URL; -} - -interface HttpResult { - body: string; - headers: IncomingHttpHeaders; - status: number; -} - -interface RequestOptions { - body?: Buffer | string; - headers?: Record; - method?: string; - omitContentLength?: boolean; - path?: string; -} - -type ReadinessState = { kind: "exited" } | { kind: "ready"; url: string } | { kind: "waiting" }; - -const activeChildren = new Set(); -const tempDirs = new Set(); - -function privateExecutionRoots(): string[] { - return fs - .readdirSync(path.dirname(HELPER_PATH)) - .filter((name) => name.startsWith(".credential-child-")) - .sort(); -} - -afterEach(async () => { - await Promise.all([...activeChildren].map((captured) => terminate(captured))); - activeChildren.clear(); - for (const dir of tempDirs) fs.rmSync(dir, { force: true, recursive: true }); - tempDirs.clear(); -}); - -function captureChild( - args: string[], - envOverrides: NodeJS.ProcessEnv = {}, - cwd = REPO_ROOT, -): CapturedChild { - const child = spawn(process.execPath, args, { - cwd, - env: { ...process.env, ...envOverrides, NO_COLOR: "1" }, - stdio: ["ignore", "pipe", "pipe"], - }); - let stdout = ""; - let stderr = ""; - child.stdout.on("data", (chunk: Buffer) => { - stdout += chunk.toString("utf8"); - }); - child.stderr.on("data", (chunk: Buffer) => { - stderr += chunk.toString("utf8"); - }); - const closed = new Promise((resolve, reject) => { - child.once("error", reject); - child.once("close", (code, signal) => resolve({ code, signal })); - }); - const captured = { - child, - closed, - output: () => `${stdout}${stderr}`, - }; - activeChildren.add(captured); - return captured; -} - -function childHasExited(captured: CapturedChild): boolean { - return captured.child.exitCode !== null || captured.child.signalCode !== null; -} - -async function awaitClosed(captured: CapturedChild): Promise { - await captured.closed.catch(() => undefined); -} - -async function terminateRunning(captured: CapturedChild): Promise { - captured.child.kill("SIGTERM"); - try { - await withTimeout(captured.closed, 1_000, "credential helper SIGTERM"); - } catch { - captured.child.kill("SIGKILL"); - await awaitClosed(captured); - } -} - -async function terminate(captured: CapturedChild): Promise { - await (childHasExited(captured) ? awaitClosed(captured) : terminateRunning(captured)); -} - -async function withTimeout(promise: Promise, timeoutMs: number, label: string): Promise { - let timer: NodeJS.Timeout | undefined; - try { - return await Promise.race([ - promise, - new Promise((_resolve, reject) => { - timer = setTimeout(() => reject(new Error(`${label} timed out`)), timeoutMs); - }), - ]); - } finally { - clearTimeout(timer); - } -} - -function helperArgs( - fields: string[], - command: string[], - formPath = FORM_PATH, - executionProfile: "account-home" | "isolated" = "isolated", - commandCwd?: string, -): string[] { - const cwdArgs = commandCwd === undefined ? [] : ["--cwd", commandCwd]; - const args = [ - "--experimental-strip-types", - HELPER_PATH, - "--execution-profile", - executionProfile, - "--form", - formPath, - ...cwdArgs, - ]; - return [...args, ...fields.flatMap((field) => ["--field", field]), "--", ...command]; -} - -function readinessState(captured: CapturedChild): ReadinessState { - const url = captured.output().match(READINESS_URL_PATTERN)?.[0]; - return url !== undefined - ? { kind: "ready", url } - : childHasExited(captured) - ? { kind: "exited" } - : { kind: "waiting" }; -} - -async function waitForReadiness(captured: CapturedChild): Promise { - const deadline = Date.now() + PROCESS_TIMEOUT_MS; - while (Date.now() < deadline) { - const state = readinessState(captured); - switch (state.kind) { - case "ready": - return new URL(state.url); - case "exited": { - const result = await captured.closed; - throw new Error( - `credential helper exited before readiness (${result.code ?? result.signal}):\n${captured.output()}`, - ); - } - case "waiting": - await new Promise((resolve) => setTimeout(resolve, 10)); - } - } - throw new Error(`credential helper did not report readiness:\n${captured.output()}`); -} - -async function startHelper( - command: string[], - envOverrides: NodeJS.ProcessEnv = {}, - executionProfile: "account-home" | "isolated" = "isolated", - commandCwd?: string, - helperCwd = REPO_ROOT, -): Promise { - const captured = captureChild( - helperArgs( - ["OPENAI_API_KEY:secret", "PUBLIC_ID:text"], - command, - FORM_PATH, - executionProfile, - commandCwd, - ), - envOverrides, - helperCwd, - ); - const formUrl = await waitForReadiness(captured); - const fragment = new URLSearchParams(formUrl.hash.slice(1)); - const capability = fragment.get("cap") ?? ""; - expect(capability).toMatch(/^[A-Za-z0-9_-]{43}$/); - return { ...captured, capability, formUrl }; -} - -function createCommandFixture(): { - command: string[]; - markerPath: string; - unexpectedShellPath: string; -} { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-helper-test-")); - tempDirs.add(dir); - const markerPath = path.join(dir, "command-runs.txt"); - const unexpectedShellPath = path.join(dir, "unexpected-shell-execution"); - const secretHash = createHash("sha256").update(TEST_SECRET).digest("hex"); - const fixture = [ - 'const fs = require("node:fs");', - 'const crypto = require("node:crypto");', - 'const path = require("node:path");', - "const [markerPath, publicValue, unexpectedShellPath] = process.argv.slice(1);", - 'const secret = process.env.OPENAI_API_KEY || "";', - 'const actualHash = crypto.createHash("sha256").update(secret).digest("hex");', - `if (actualHash !== ${JSON.stringify(secretHash)}) process.exit(21);`, - `if (process.env.PUBLIC_ID !== ${JSON.stringify(TEST_PUBLIC_VALUE)}) process.exit(22);`, - `if (publicValue !== ${JSON.stringify(TEST_PUBLIC_VALUE)}) process.exit(23);`, - 'if (!process.argv.includes("--")) process.exit(25);', - `if (${JSON.stringify(BLOCKED_INHERITED_ENV_NAMES)}.some((name) => Object.hasOwn(process.env, name))) process.exit(26);`, - `if (Object.values(process.env).some((value) => ${JSON.stringify(Object.values(CONFIG_ROOT_ENV_OVERRIDES))}.includes(value))) process.exit(27);`, - 'const privateRoot = process.env.HOME || "";', - `for (const [name, parts] of Object.entries(${JSON.stringify(PRIVATE_EXECUTION_ENV_PATHS)})) if (process.env[name] !== path.join(privateRoot, ...parts)) process.exit(28);`, - `if (${JSON.stringify(CONFIG_ROOT_ENV_NAMES.filter((name) => !Object.hasOwn(PRIVATE_EXECUTION_ENV_PATHS, name)))}.some((name) => Object.hasOwn(process.env, name))) process.exit(29);`, - "if (!path.isAbsolute(privateRoot) || process.cwd() !== privateRoot) process.exit(30);", - 'if (process.platform !== "win32" && (fs.statSync(privateRoot).mode & 0o077) !== 0) process.exit(31);', - 'if ([".curlrc", ".gitconfig", ".npmrc", ".netrc"].some((name) => fs.existsSync(path.join(privateRoot, name)))) process.exit(32);', - 'fs.writeFileSync(markerPath + ".private-root", privateRoot);', - 'fs.appendFileSync(markerPath, "ran\\n");', - "if (fs.existsSync(unexpectedShellPath)) process.exit(24);", - ].join(""); - return { - command: [ - process.execPath, - "-e", - fixture, - markerPath, - TEST_PUBLIC_VALUE, - unexpectedShellPath, - "--", - "opaque-command-argument", - ], - markerPath, - unexpectedShellPath, - }; -} - -function request(url: URL, options: RequestOptions = {}): Promise { - const body = typeof options.body === "string" ? Buffer.from(options.body, "utf8") : options.body; - const suppliedHeaders = options.headers ?? {}; - const hasContentLength = Object.keys(suppliedHeaders).some( - (name) => name.toLowerCase() === "content-length", - ); - const generatedHeaders = - body !== undefined && !hasContentLength && !options.omitContentLength - ? { "content-length": String(body.length) } - : {}; - const headers = { ...suppliedHeaders, ...generatedHeaders }; - - return new Promise((resolve, reject) => { - const clientRequest = http.request( - { - agent: false, - headers, - hostname: url.hostname, - method: options.method ?? "GET", - path: options.path ?? `${url.pathname}${url.search}`, - port: url.port, - }, - (response) => { - const chunks: Buffer[] = []; - response.on("data", (chunk: Buffer) => chunks.push(chunk)); - response.on("end", () => { - resolve({ - body: Buffer.concat(chunks).toString("utf8"), - headers: response.headers, - status: response.statusCode ?? 0, - }); - }); - }, - ); - clientRequest.setTimeout(3_000, () => { - clientRequest.destroy(new Error("credential helper request timed out")); - }); - clientRequest.on("error", reject); - clientRequest.end(body); - }); -} - -function validHeaders(helper: RunningHelper): Record { - return { - "content-type": "application/json", - origin: helper.formUrl.origin, - "x-nemoclaw-capability": helper.capability, - }; -} - -function validBody(): string { - return JSON.stringify({ - values: { - OPENAI_API_KEY: TEST_SECRET, - PUBLIC_ID: TEST_PUBLIC_VALUE, - }, - }); -} - -function expectNoCors(headers: IncomingHttpHeaders): void { - expect(headers["access-control-allow-origin"]).toBeUndefined(); - expect(headers["access-control-allow-credentials"]).toBeUndefined(); - expect(headers["access-control-allow-headers"]).toBeUndefined(); - expect(headers["access-control-allow-methods"]).toBeUndefined(); -} - -function expectRejected(result: HttpResult): void { - expect(result.status).toBeGreaterThanOrEqual(400); - expect(result.status).toBeLessThan(500); - expectNoCors(result.headers); - expect(result.body).not.toContain(TEST_SECRET); -} - -function expectHttpStatus(result: HttpResult, expected: number): void { - expect(result.status).toBe(expected); -} - -async function expectCompletionCode(completion: Promise, expected: number): Promise { - expect(await completion).toBe(expected); -} - -function commandRunCount(markerPath: string): number { - try { - return fs.readFileSync(markerPath, "utf8").split("\n").filter(Boolean).length; - } catch { - return 0; - } -} - -async function expectSuccessfulCompletion( - helper: RunningHelper, - markerPath: string, -): Promise { - const result = await withTimeout(helper.closed, PROCESS_TIMEOUT_MS, "credential helper exit"); - expect(result).toEqual({ code: 0, signal: null }); - expect(commandRunCount(markerPath)).toBe(1); - const privateRootMarker = `${markerPath}.private-root`; - const privateRootStillExists = - fs.existsSync(privateRootMarker) && fs.existsSync(fs.readFileSync(privateRootMarker, "utf8")); - expect(privateRootStillExists).toBe(false); -} - -describe("local credential helper", () => { - it("hashes inline form tags case-insensitively for CSP generation (#5048)", () => { - const csp = buildCredentialFormCsp(Buffer.from("")); - - expect(csp).toContain("script-src 'sha256-"); - expect(csp).toContain("style-src 'sha256-"); - }); - - it("drops every ambient entry without mutating the source environment (#5048)", () => { - const ambient = { - ...CONFIG_ROOT_ENV_OVERRIDES, - ...NETWORK_TRUST_ENV_OVERRIDES, - ...PACKAGE_CONTROL_ENV_OVERRIDES, - BASH_ENV: "shell-hook", - "BASH_FUNC_echo%%": '() { printf "%s" "$OPENAI_API_KEY"; }', - DOTNET_STARTUP_HOOKS: "startup-hook", - DYLD_INSERT_LIBRARIES: "loader-hook", - Gh_ToKeN: "credential", - GIT_CONFIG: "git-config", - GIT_CONFIG_COUNT: "1", - GIT_EXTERNAL_DIFF: "/ambient/diff-wrapper", - GIT_EXEC_PATH: "/ambient/git-core", - GIT_PROXY_COMMAND: "/ambient/proxy-wrapper", - GIT_TRACE2_EVENT: "/ambient/git-trace.json", - GIT_SSH: "/ambient/ssh-wrapper", - LD_PRELOAD: "loader-hook", - NEMOCLAW_PROVIDER: "ambient-provider", - Node_Options: "--no-warnings", - Path: "/ambient/search/path", - Public_Id: "ambient-field-collision", - UNKNOWN_AMBIENT_SETTING: "removed", - SSH_AUTH_SOCK: "/ambient/agent.sock", - } satisfies NodeJS.ProcessEnv; - const original = { ...ambient }; - - const sanitized = sanitizeInheritedChildEnvironment(ambient, new Set(["PUBLIC_ID"])); - - expect(sanitized).toEqual({}); - expect(ambient).toEqual(original); - }); - - it("allows explicitly collected NemoClaw settings while denying their ambient values (#5048)", () => { - expect(parseCredentialField("NEMOCLAW_PROVIDER:text")).toEqual({ - name: "NEMOCLAW_PROVIDER", - type: "text", - }); - expect( - sanitizeInheritedChildEnvironment( - { NEMOCLAW_MODEL: "ambient-model", NEMOCLAW_PROVIDER: "ambient-provider" }, - new Set(["NEMOCLAW_PROVIDER"]), - ), - ).toEqual({}); - }); - - it.each([ - { - fields: ["OPENAI_API_KEY:text"], - label: "secret-shaped field declared as text", - }, - { fields: ["PATH:text"], label: "process search path field" }, - { fields: ["NODE_OPTIONS:secret"], label: "Node process-control field" }, - { fields: ["BASH_FUNC_ECHO:secret"], label: "exported Bash function field prefix" }, - { fields: ["DOTNET_STARTUP_HOOKS:secret"], label: ".NET startup hook field" }, - { fields: ["GIT_EXEC_PATH:secret"], label: "Git executable path field" }, - { fields: ["GIT_EXTERNAL_DIFF:secret"], label: "Git external diff field" }, - { fields: ["GIT_PROXY_COMMAND:secret"], label: "Git proxy command field" }, - { fields: ["GIT_TRACE2_EVENT:secret"], label: "Git trace field prefix" }, - { fields: ["GIT_SSH:secret"], label: "Git SSH wrapper field" }, - { fields: ["LD_PRELOAD:secret"], label: "dynamic-loader field prefix" }, - { fields: ["DYLD_INSERT_LIBRARIES:secret"], label: "macOS dynamic-loader field prefix" }, - { fields: ["GIT_CONFIG:secret"], label: "exact Git config process-control field" }, - { fields: ["GIT_CONFIG_COUNT:secret"], label: "Git config process-control field prefix" }, - ...CONFIG_ROOT_ENV_NAMES.map((name) => ({ - fields: [`${name}:text`], - label: `${name} configuration-root field`, - })), - ...NETWORK_TRUST_ENV_NAMES.map((name) => ({ - fields: [`${name}:text`], - label: `${name} network or trust control field`, - })), - { fields: ["NPM_CONFIG_REGISTRY:text"], label: "npm configuration field prefix" }, - { - fields: ["OPENSHELL_DOCKER_SUPERVISOR_IMAGE:text"], - label: "OpenShell configuration field prefix", - }, - { fields: ["PIP_INDEX_URL:text"], label: "pip configuration field prefix" }, - { - fields: ["PUBLIC_ID:text", "PUBLIC_ID:text"], - label: "duplicate field", - }, - { - fields: Array.from({ length: 17 }, (_value, index) => `PUBLIC_ID_${index}:text`), - label: "field count above the session limit", - }, - { fields: ["bad-name:secret"], label: "malformed field name" }, - ])("rejects $label before listening (#5048)", async ({ fields }) => { - const captured = captureChild(helperArgs(fields, [process.execPath, "-e", "process.exit(0)"])); - - const result = await withTimeout(captured.closed, PROCESS_TIMEOUT_MS, "invalid helper CLI"); - - expect(result.code).not.toBe(0); - expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); - }); - - it.each([ - { executable: "node" }, - { executable: "./node" }, - ])("rejects non-absolute approved executable $executable before listening (#5048)", async ({ - executable, - }) => { - const captured = captureChild( - helperArgs(["OPENAI_API_KEY:secret"], [executable, "-e", "process.exit(0)"]), - ); - - const result = await withTimeout(captured.closed, PROCESS_TIMEOUT_MS, "relative executable"); - - expect(result.code).not.toBe(0); - expect(captured.output()).toContain("approved command executable must use an absolute path"); - expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); - }); - - it.each([ - { - options: [], - expected: "--execution-profile isolated or --execution-profile account-home is required", - }, - { - options: ["--execution-profile", "unknown"], - expected: "--execution-profile must be isolated or account-home", - }, - { - options: ["--execution-profile", "account-home"], - expected: "--execution-profile account-home requires an absolute --cwd path", - }, - { - options: ["--execution-profile", "account-home", "--cwd", "relative"], - expected: "--cwd must be an absolute path without NUL bytes", - }, - { - options: ["--execution-profile", "isolated", "--cwd", REPO_ROOT], - expected: "--execution-profile isolated does not accept --cwd", - }, - ])("rejects an unsafe or ambiguous execution profile before listening (#5048)", async ({ - expected, - options, - }) => { - const captured = captureChild([ - "--experimental-strip-types", - HELPER_PATH, - ...options, - "--field", - "OPENAI_API_KEY:secret", - "--", - process.execPath, - "-e", - "process.exit(0)", - ]); - - const result = await withTimeout(captured.closed, PROCESS_TIMEOUT_MS, "execution profile"); - - expect(result.code).not.toBe(0); - expect(captured.output()).toContain(expected); - expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); - }); - - it("rejects a non-absolute executable through the direct session API (#5048)", async () => { - await expect( - startLocalCredentialHelper({ - commandArgv: ["node", "-e", "process.exit(0)"], - executionProfile: "isolated", - fields: [{ name: "OPENAI_API_KEY", type: "secret" }], - formBytes: fs.readFileSync(FORM_PATH), - }), - ).rejects.toThrow("approved command executable must use an absolute path"); - }); - - it("rejects a missing or unknown execution profile through the direct session API (#5048)", async () => { - await expect( - startLocalCredentialHelper({ - commandArgv: [process.execPath, "-e", "process.exit(0)"], - executionProfile: "unknown" as "isolated", - fields: [{ name: "OPENAI_API_KEY", type: "secret" }], - formBytes: fs.readFileSync(FORM_PATH), - }), - ).rejects.toThrow("execution profile must be isolated or account-home"); - }); - - it("removes the isolated execution root when a session expires (#5048)", async () => { - const rootsBefore = privateExecutionRoots(); - const session = await startLocalCredentialHelper({ - commandArgv: [process.execPath, "-e", "process.exit(0)"], - executionProfile: "isolated", - fields: [{ name: "OPENAI_API_KEY", type: "secret" }], - formBytes: fs.readFileSync(FORM_PATH), - timeoutMs: 20, - }); - - await expectCompletionCode(session.completion, 1); - expect(privateExecutionRoots()).toEqual(rootsBefore); - }); - - it("removes the isolated execution root when the approved executable cannot start (#5048)", async () => { - const rootsBefore = privateExecutionRoots(); - const missingExecutable = path.join( - path.parse(process.execPath).root, - "nemoclaw-definitely-missing-executable", - ); - const session = await startLocalCredentialHelper({ - commandArgv: [missingExecutable], - executionProfile: "isolated", - fields: [ - { name: "OPENAI_API_KEY", type: "secret" }, - { name: "PUBLIC_ID", type: "text" }, - ], - formBytes: fs.readFileSync(FORM_PATH), - }); - const formUrl = new URL(session.url); - const capability = new URLSearchParams(formUrl.hash.slice(1)).get("cap") ?? ""; - const accepted = await request(formUrl, { - body: validBody(), - headers: { - "content-type": "application/json", - origin: formUrl.origin, - "x-nemoclaw-capability": capability, - }, - method: "POST", - path: "/submit", - }); - - expectHttpStatus(accepted, 202); - await expectCompletionCode(session.completion, 1); - expect(privateExecutionRoots()).toEqual(rootsBefore); - }); - - it("rejects a modified credential form before listening (#5048)", async () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-form-test-")); - tempDirs.add(dir); - const modifiedFormPath = path.join(dir, "local-credential-form.html"); - const modifiedForm = Buffer.concat([fs.readFileSync(FORM_PATH), Buffer.from("\n")]); - fs.writeFileSync(modifiedFormPath, modifiedForm); - const captured = captureChild( - helperArgs( - ["OPENAI_API_KEY:secret"], - [process.execPath, "-e", "process.exit(0)"], - modifiedFormPath, - ), - ); - - const result = await withTimeout(captured.closed, PROCESS_TIMEOUT_MS, "modified helper form"); - - expect(result.code).not.toBe(0); - expect(captured.output()).toContain("Local credential form SHA-256 mismatch"); - expect(captured.output()).not.toMatch(READINESS_URL_PATTERN); - }); - - it("serves only the exact form bytes with hardened non-CORS headers (#5048)", async () => { - const fixture = createCommandFixture(); - const helper = await startHelper(fixture.command); - const result = await request(helper.formUrl); - - expect(helper.formUrl.origin).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/); - expect(helper.formUrl.searchParams.has("cap")).toBe(false); - expect(result.status).toBe(200); - expect(result.body).toContain("NemoClaw Local Credential Form"); - expect(Number(result.headers["content-length"])).toBe(Buffer.byteLength(result.body)); - expect(result.body).not.toContain(helper.capability); - expect(JSON.stringify(result.headers)).not.toContain(helper.capability); - expect(result.headers["content-type"]).toMatch(/^text\/html(?:;\s*charset=utf-8)?$/i); - expect(result.headers["content-security-policy"]).toContain("frame-ancestors 'none'"); - expect(result.headers["cache-control"]).toBe("no-store"); - expect(result.headers["x-content-type-options"]).toBe("nosniff"); - expect(result.headers["referrer-policy"]).toBe("no-referrer"); - expect(result.headers["cross-origin-resource-policy"]).toBe("same-origin"); - expect(result.headers["cross-origin-opener-policy"]).toBe("same-origin"); - expectNoCors(result.headers); - expect(commandRunCount(fixture.markerPath)).toBe(0); - - const modifiedTarget = await request(helper.formUrl, { - path: `${helper.formUrl.pathname}${helper.formUrl.search}&unexpected=1`, - }); - expectRejected(modifiedTarget); - - const stillAvailable = await request(helper.formUrl); - expect(stillAvailable.status).toBe(200); - expect(stillAvailable.body).toBe(result.body); - expect(commandRunCount(fixture.markerPath)).toBe(0); - }); - - it("strips inherited credentials and process controls before launching the approved command (#5048)", async () => { - const fixture = createCommandFixture(); - const hostileConfigRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hostile-config-")); - tempDirs.add(hostileConfigRoot); - for (const relativePath of [".curlrc", ".gitconfig", ".netrc", ".npmrc", ".zshenv"]) { - fs.writeFileSync(path.join(hostileConfigRoot, relativePath), "attack-marker\n"); - } - fs.mkdirSync(path.join(hostileConfigRoot, ".git")); - fs.writeFileSync( - path.join(hostileConfigRoot, ".git", "config"), - "[credential]\nhelper = attack\n", - ); - fs.mkdirSync(path.join(hostileConfigRoot, "pip")); - fs.writeFileSync( - path.join(hostileConfigRoot, "pip", "pip.conf"), - "[global]\nindex-url=attack\n", - ); - const helper = await startHelper( - fixture.command, - { - ...CONFIG_ROOT_ENV_OVERRIDES, - ...NETWORK_TRUST_ENV_OVERRIDES, - ...PACKAGE_CONTROL_ENV_OVERRIDES, - BASH_ENV: "ambient-shell-hook", - "BASH_FUNC_echo%%": '() { printf "%s" "$OPENAI_API_KEY"; }', - DOTNET_STARTUP_HOOKS: "ambient-startup-hook", - GIT_EXEC_PATH: "/ambient/git-core", - GIT_CONFIG: "ambient-git-config", - GH_TOKEN: "ambient-github-token", - Gh_ToKeN: "ambient-mixed-case-github-token", - GIT_CONFIG_COUNT: "1", - GIT_EXTERNAL_DIFF: "/ambient/diff-wrapper", - GIT_PROXY_COMMAND: "/ambient/proxy-wrapper", - GIT_TRACE2_EVENT: "/ambient/git-trace.json", - GIT_SSH: "/ambient/ssh-wrapper", - NODE_OPTIONS: "--no-warnings", - Node_Options: "--no-warnings", - NEMOCLAW_PROVIDER: "ambient-provider", - OPENSHELL_DOCKER_SUPERVISOR_IMAGE: "attacker.invalid/supervisor:latest", - OPENAI_API_KEY: "ambient-openai-key", - PATH: "/ambient/search/path", - Path: "/ambient/mixed-case/search/path", - PUBLIC_ID: "ambient-public-id", - UNRELATED_API_TOKEN: "ambient-generic-token", - HOME: hostileConfigRoot, - XDG_CONFIG_HOME: hostileConfigRoot, - }, - "isolated", - undefined, - hostileConfigRoot, - ); - - const accepted = await request(helper.formUrl, { - body: validBody(), - headers: validHeaders(helper), - method: "POST", - path: "/submit", - }); - - expect(accepted.status).toBe(202); - await expectSuccessfulCompletion(helper, fixture.markerPath); - }); - - it.runIf(process.platform !== "win32" && fs.existsSync("/usr/bin/git"))( - "blocks an ambient Git template hook from observing submitted credentials (#5048)", - async () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-git-template-test-")); - tempDirs.add(dir); - const source = path.join(dir, "source"); - const destination = path.join(dir, "clone"); - const template = path.join(dir, "template"); - const hooks = path.join(template, "hooks"); - const leakPath = path.join(dir, "leaked-secret.txt"); - fs.mkdirSync(hooks, { recursive: true }); - - execFileSync("/usr/bin/git", ["init", "--quiet", source]); - fs.writeFileSync(path.join(source, "tracked.txt"), "fixture\n"); - execFileSync("/usr/bin/git", ["-C", source, "add", "tracked.txt"]); - execFileSync("/usr/bin/git", [ - "-C", - source, - "-c", - "user.name=NemoClaw Test", - "-c", - "user.email=nemoclaw-test@example.invalid", - "commit", - "--quiet", - "--no-gpg-sign", - "-m", - "fixture", - ]); - - const hookPath = path.join(hooks, "post-checkout"); - const quotedLeakPath = `'${leakPath.replaceAll("'", `'"'"'`)}'`; - fs.writeFileSync(hookPath, `#!/bin/sh\nprintf '%s' "$OPENAI_API_KEY" > ${quotedLeakPath}\n`); - fs.chmodSync(hookPath, 0o755); - - const helper = await startHelper(["/usr/bin/git", "clone", "--quiet", source, destination], { - GIT_TEMPLATE_DIR: template, - }); - const accepted = await request(helper.formUrl, { - body: validBody(), - headers: validHeaders(helper), - method: "POST", - path: "/submit", - }); - - expect(accepted.status).toBe(202); - await expect(helper.closed).resolves.toEqual({ code: 0, signal: null }); - expect(fs.readFileSync(path.join(destination, "tracked.txt"), "utf8")).toBe("fixture\n"); - expect(fs.existsSync(path.join(destination, ".git", "hooks", "post-checkout"))).toBe(false); - expect(fs.existsSync(leakPath)).toBe(false); - expect(helper.output()).not.toContain(TEST_SECRET); - }, - ); - - it("uses only the explicit cwd and OS account home in account-home mode (#5048)", async () => { - const commandCwd = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-account-cwd-test-")); - tempDirs.add(commandCwd); - const markerPath = path.join(commandCwd, "account-context.json"); - const command = [ - process.execPath, - "-e", - `require("node:fs").writeFileSync(process.argv[1], JSON.stringify({cwd:process.cwd(),environment:Object.fromEntries(${JSON.stringify(CONFIG_ROOT_ENV_NAMES)}.map((name)=>[name,process.env[name]]))}))`, - markerPath, - ]; - const helper = await startHelper( - command, - CONFIG_ROOT_ENV_OVERRIDES, - "account-home", - commandCwd, - ); - - const accepted = await request(helper.formUrl, { - body: validBody(), - headers: validHeaders(helper), - method: "POST", - path: "/submit", - }); - - expect(accepted.status).toBe(202); - await expectSuccessfulCompletion(helper, markerPath); - const observed = JSON.parse(fs.readFileSync(markerPath, "utf8")) as { - cwd: string; - environment: Record; - }; - const accountHome = os.userInfo().homedir; - const accountTemp = path.join(accountHome, "AppData", "Local", "Temp"); - const hasWindowsDrive = /^[A-Za-z]:[\\/]/.test(accountHome); - const expectedEnvironment: Record = - process.platform === "win32" - ? { - APPDATA: path.join(accountHome, "AppData", "Roaming"), - ...(hasWindowsDrive - ? { - HOMEDRIVE: accountHome.slice(0, 2), - HOMEPATH: accountHome.slice(2) || "\\", - } - : {}), - HOME: accountHome, - LOCALAPPDATA: path.join(accountHome, "AppData", "Local"), - PWD: commandCwd, - TEMP: accountTemp, - TMP: accountTemp, - TMPDIR: accountTemp, - USERPROFILE: accountHome, - } - : { HOME: accountHome, PWD: commandCwd }; - expect(observed.cwd).toBe(commandCwd); - expect( - Object.fromEntries(Object.entries(observed.environment).filter(([, value]) => value)), - ).toEqual(expectedEnvironment); - }); - - it("preserves explicit approved proxy, CA, and config arguments byte-for-byte (#5048)", async () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-argv-test-")); - tempDirs.add(dir); - const markerPath = path.join(dir, "command-argv.json"); - const expectedArgv = [ - "--proxy", - "http://trusted-proxy.internal:3128", - "--noproxy", - "127.0.0.1", - "--cacert", - "/trusted/ca.pem", - "--config", - "/trusted/client.conf", - "--profile", - "approved-profile", - ]; - const command = [ - process.execPath, - "-e", - 'require("node:fs").writeFileSync(process.argv[1], JSON.stringify(process.argv.slice(2)))', - markerPath, - ...expectedArgv, - ]; - const helper = await startHelper(command, NETWORK_TRUST_ENV_OVERRIDES); - - const accepted = await request(helper.formUrl, { - body: validBody(), - headers: validHeaders(helper), - method: "POST", - path: "/submit", - }); - - expect(accepted.status).toBe(202); - await expectSuccessfulCompletion(helper, markerPath); - expect(JSON.parse(fs.readFileSync(markerPath, "utf8"))).toEqual(expectedArgv); - }); - - it("blocks an inherited Bash function from intercepting the approved command (#5048)", async () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-credential-bash-test-")); - tempDirs.add(dir); - const markerPath = path.join(dir, "command-runs.txt"); - const attackMarkerPath = path.join(dir, "ambient-function-ran.txt"); - const command = [ - "/bin/bash", - "--noprofile", - "--norc", - "-c", - 'echo safe >/dev/null && test ! -e "$ATTACK_MARKER" && printf "ran\\n" > "$1"', - "bash", - markerPath, - ]; - const helper = await startHelper(command, { - ATTACK_MARKER: attackMarkerPath, - "BASH_FUNC_echo%%": '() { printf "%s" "$OPENAI_API_KEY" > "$ATTACK_MARKER"; }', - PATH: "/ambient/search/path", - }); - - const accepted = await request(helper.formUrl, { - body: validBody(), - headers: validHeaders(helper), - method: "POST", - path: "/submit", - }); - - expect(accepted.status).toBe(202); - await expectSuccessfulCompletion(helper, markerPath); - expect(fs.existsSync(attackMarkerPath)).toBe(false); - }); - - it("rejects Host, Origin, capability, and CORS probes without consuming the session (#5048)", async () => { - const fixture = createCommandFixture(); - const helper = await startHelper(fixture.command); - const body = validBody(); - const attacks: RequestOptions[] = [ - { - body, - headers: { ...validHeaders(helper), host: `localhost:${helper.formUrl.port}` }, - method: "POST", - path: "/submit", - }, - { - body, - headers: { ...validHeaders(helper), origin: `http://localhost:${helper.formUrl.port}` }, - method: "POST", - path: "/submit", - }, - { - body, - headers: { - ...validHeaders(helper), - "x-nemoclaw-capability": "x".repeat(43), - }, - method: "POST", - path: "/submit", - }, - { - body, - headers: { - "content-type": "application/json", - origin: helper.formUrl.origin, - }, - method: "POST", - path: "/submit", - }, - { - headers: { - "access-control-request-headers": "x-nemoclaw-capability, content-type", - "access-control-request-method": "POST", - origin: "https://attacker.invalid", - }, - method: "OPTIONS", - path: "/submit", - }, - ]; - - for (const attack of attacks) { - expectRejected(await request(helper.formUrl, attack)); - expect(commandRunCount(fixture.markerPath)).toBe(0); - } - - const accepted = await request(helper.formUrl, { - body, - headers: validHeaders(helper), - method: "POST", - path: "/submit", - }); - expect(accepted.status).toBe(202); - expectNoCors(accepted.headers); - await expectSuccessfulCompletion(helper, fixture.markerPath); - }); - - it("rejects media, encoding, body, and exact-schema violations without consuming the session (#5048)", async () => { - const fixture = createCommandFixture(); - const helper = await startHelper(fixture.command); - const authHeaders = validHeaders(helper); - const invalidRequests: RequestOptions[] = [ - { - body: validBody(), - headers: { ...authHeaders, "content-type": "text/plain" }, - method: "POST", - path: "/submit", - }, - { - body: validBody(), - headers: { ...authHeaders, "content-type": "application/json; charset=utf-8" }, - method: "POST", - path: "/submit", - }, - { - body: validBody(), - headers: { ...authHeaders, "content-encoding": "gzip" }, - method: "POST", - path: "/submit", - }, - { - body: validBody(), - headers: { ...authHeaders, "transfer-encoding": "chunked" }, - method: "POST", - omitContentLength: true, - path: "/submit", - }, - { - body: Buffer.alloc(65_537, 0x61), - headers: authHeaders, - method: "POST", - path: "/submit", - }, - { - body: "{not-json", - headers: authHeaders, - method: "POST", - path: "/submit", - }, - { - body: JSON.stringify({ values: { OPENAI_API_KEY: TEST_SECRET } }), - headers: authHeaders, - method: "POST", - path: "/submit", - }, - { - body: JSON.stringify({ - argv: ["sh", "-c", "unexpected"], - values: { OPENAI_API_KEY: TEST_SECRET, PUBLIC_ID: TEST_PUBLIC_VALUE }, - }), - headers: authHeaders, - method: "POST", - path: "/submit", - }, - { - body: JSON.stringify({ - values: { OPENAI_API_KEY: TEST_SECRET, PUBLIC_ID: 42 }, - }), - headers: authHeaders, - method: "POST", - path: "/submit", - }, - { - body: JSON.stringify({ - values: { OPENAI_API_KEY: TEST_SECRET, PUBLIC_ID: "é".repeat(8_193) }, - }), - headers: authHeaders, - method: "POST", - path: "/submit", - }, - ]; - - for (const invalid of invalidRequests) { - expectRejected(await request(helper.formUrl, invalid)); - expect(commandRunCount(fixture.markerPath)).toBe(0); - } - - const accepted = await request(helper.formUrl, { - body: validBody(), - headers: authHeaders, - method: "POST", - path: "/submit", - }); - expect(accepted.status).toBe(202); - await expectSuccessfulCompletion(helper, fixture.markerPath); - }); - - it("claims one racing submission, runs the command once, and closes the listener (#5048)", async () => { - const fixture = createCommandFixture(); - const helper = await startHelper(fixture.command); - const submission = () => - request(helper.formUrl, { - body: validBody(), - headers: validHeaders(helper), - method: "POST", - path: "/submit", - }); - - const outcomes = await Promise.allSettled([submission(), submission()]); - const responses = outcomes.flatMap((outcome) => - outcome.status === "fulfilled" ? [outcome.value] : [], - ); - const accepted = responses.filter((response) => response.status === 202); - - expect(accepted).toHaveLength(1); - expect(responses.filter((response) => response.status >= 200 && response.status < 300)).toEqual( - accepted, - ); - for (const response of responses.filter((response) => response.status !== 202)) { - expect(response.status).toBe(409); - expectNoCors(response.headers); - } - expect(accepted[0]?.headers.connection).toBe("close"); - expect(accepted[0]?.body).not.toContain(TEST_SECRET); - - await expectSuccessfulCompletion(helper, fixture.markerPath); - expect(helper.output()).not.toContain(TEST_SECRET); - expect(fs.existsSync(fixture.unexpectedShellPath)).toBe(false); - await expect(request(helper.formUrl)).rejects.toBeInstanceOf(Error); - }); - - it("executes once when the client sends a valid request and abandons the response (#5048)", async () => { - const fixture = createCommandFixture(); - const helper = await startHelper(fixture.command); - const body = validBody(); - const rawRequest = [ - "POST /submit HTTP/1.1", - `Host: ${helper.formUrl.host}`, - `Origin: ${helper.formUrl.origin}`, - `X-NemoClaw-Capability: ${helper.capability}`, - "Content-Type: application/json", - `Content-Length: ${Buffer.byteLength(body)}`, - "Connection: close", - "", - body, - ].join("\r\n"); - - await new Promise((resolve, reject) => { - const socket = net.createConnection( - { host: helper.formUrl.hostname, port: Number(helper.formUrl.port) }, - () => { - socket.end(rawRequest, () => { - socket.destroy(); - resolve(); - }); - }, - ); - socket.once("error", reject); - }); - - await expectSuccessfulCompletion(helper, fixture.markerPath); - expect(helper.output()).not.toContain(TEST_SECRET); - await expect(request(helper.formUrl)).rejects.toBeInstanceOf(Error); - }); -}); diff --git a/test/onboard-inference-reconciliation.test.ts b/test/onboard-inference-reconciliation.test.ts new file mode 100644 index 00000000000..ce26d31d189 --- /dev/null +++ b/test/onboard-inference-reconciliation.test.ts @@ -0,0 +1,984 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; +import { createLocalInferenceRouteApplier } from "../src/lib/onboard/local-inference-route.js"; +import type { SetupInference } from "../src/lib/onboard/setup-inference.js"; +import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; +import { + bedrockRuntimeOnboard, + type CommandEntry, + createDirectSetupInferenceHarness, + parseStdoutJson, + stripMessagingEnv, +} from "./helpers/onboard-split-context"; +import { + createDirectCommandRouter, + withProcessEnv, +} from "./support/setup-inference-test-harness.js"; + +describe("onboard helpers", () => { + it("reuses a registered Hermes Provider without re-collecting host credentials", async () => { + await withProcessEnv( + { + NOUS_API_KEY: "nous-host-secret", + OPENAI_API_KEY: "openai-host-secret", + }, + async () => { + const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.join(" ") === "provider get -g nemoclaw hermes-provider" + ? { status: 0, stdout: "Provider: hermes-provider", stderr: "" } + : undefined, + overrides: { isNonInteractive: () => true }, + }); + + await harness.setupInference( + "test-box", + "moonshotai/kimi-k2.6", + "hermes-provider", + "https://8.8.8.8/v1", + "OPENAI_API_KEY", + "oauth", + ); + + const commands = harness.commands; + assert.equal(commands.length, 3); + assert.equal(commands[0].command, "provider list -g nemoclaw"); + assert.equal(commands[1].command, "provider get -g nemoclaw hermes-provider"); + assert.match( + commands[2].command, + /inference set -g nemoclaw --no-verify --provider hermes-provider/, + ); + assert.ok(!commands.some((entry) => entry.command.startsWith("gateway select"))); + assert.ok(!commands.some((entry) => /provider (create|update)/.test(entry.command))); + assert.ok(!commands.some((entry) => entry.env?.NOUS_API_KEY || entry.env?.OPENAI_API_KEY)); + assert.ok( + !commands.some((entry) => /nous-host-secret|openai-host-secret/.test(entry.command)), + "host credential values must not appear in argv", + ); + }, + ); + }); + it("routes Bedrock Runtime custom Anthropic endpoints through the hidden OpenAI adapter", async () => { + await withProcessEnv({ COMPATIBLE_ANTHROPIC_API_KEY: "bedrock-bearer" }, async () => { + const updateSandbox = vi.fn(() => true); + const ensureAdapter = vi.fn(async () => ({ + baseUrl: "http://host.openshell.internal:11436/v1", + localBaseUrl: "http://127.0.0.1:11436/v1", + credentialEnv: "NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN", + token: "adapter-token", + region: "us-east-1", + logPath: "/tmp/bedrock-adapter.log", + })); + const setupBedrockRuntimeInference = bedrockRuntimeOnboard.setupBedrockRuntimeInference; + const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.join(" ") === "provider get -g nemoclaw compatible-anthropic-endpoint" + ? { status: 1, stdout: "", stderr: "" } + : undefined, + overrides: { + updateSandbox, + bedrockRuntimeOnboard: { + setupBedrockRuntimeInference: ( + input: Parameters[0], + ) => setupBedrockRuntimeInference({ ...input, ensureAdapter }), + }, + }, + }); + const consoleOutput: string[] = []; + const captureConsole = (...args: unknown[]) => consoleOutput.push(args.map(String).join(" ")); + const error = vi.spyOn(console, "error").mockImplementation(captureConsole); + const log = vi.spyOn(console, "log").mockImplementation(captureConsole); + try { + await harness.setupInference( + "test-box", + "anthropic.claude-3-5-sonnet-20240620-v1:0", + "compatible-anthropic-endpoint", + "https://bedrock-runtime.us-east-1.amazonaws.com", + "COMPATIBLE_ANTHROPIC_API_KEY", + ); + } finally { + error.mockRestore(); + log.mockRestore(); + } + + const commands = harness.commands; + const providerCommand = commands.find((entry) => /provider create/.test(entry.command)); + assert.ok(providerCommand, "expected hidden adapter provider registration"); + assert.match(providerCommand.command, /--name compatible-anthropic-endpoint/); + assert.match(providerCommand.command, /--type openai/); + assert.match(providerCommand.command, /--credential NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN/); + assert.match( + providerCommand.command, + /OPENAI_BASE_URL=http:\/\/host\.openshell\.internal:11436\/v1/, + ); + assert.equal(providerCommand.env?.NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN, "adapter-token"); + assert.ok( + !JSON.stringify(commands).includes("bedrock-bearer"), + "Bedrock bearer token must not appear in OpenShell argv or env", + ); + assert.deepEqual(harness.errors, []); + assert.deepEqual(harness.logs, [ + " Bedrock Runtime adapter ready: region us-east-1, sandbox route http://host.openshell.internal:11436/v1, host log /tmp/bedrock-adapter.log", + " ✓ Inference route set: compatible-anthropic-endpoint / anthropic.claude-3-5-sonnet-20240620-v1:0", + ]); + assert.doesNotMatch( + [...harness.logs, ...harness.errors, ...consoleOutput].join("\n"), + /bedrock-bearer|adapter-token/, + "Bedrock tokens must not appear in onboarding console output", + ); + const sandboxCommands = commands.filter((entry) => /\bsandbox\b/.test(entry.command)); + assert.ok( + !sandboxCommands.some((entry) => + JSON.stringify(entry).includes("NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN"), + ), + "adapter credential env must not be passed to sandbox commands", + ); + assert.ok( + !sandboxCommands.some((entry) => JSON.stringify(entry).includes("adapter-token")), + "adapter token must not be passed to sandbox commands", + ); + assert.match( + commands.at(-1)?.command || "", + /inference set -g nemoclaw --no-verify --provider compatible-anthropic-endpoint --model anthropic\.claude-3-5-sonnet-20240620-v1:0/, + ); + // biome-ignore format: keep the complete route reservation assertion within this legacy file's enforced budget. + expect(updateSandbox).toHaveBeenCalledWith("test-box", { model: "anthropic.claude-3-5-sonnet-20240620-v1:0", provider: "compatible-anthropic-endpoint", endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", preferredInferenceApi: null, gatewayName: "nemoclaw" }); + }); + }); + it("resolves a sandbox name before reconciling Hermes Provider on resume", { + timeout: 60_000, + }, () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-hermes-resume-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "hermes-resume-sandbox-name-check.js"); + const openshellPath = JSON.stringify(path.join(fakeBin, "openshell")); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const sessionPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + const nimPath = JSON.stringify(path.join(repoRoot, "src", "lib", "inference", "nim.ts")); + const gatewayStatePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "gateway.ts"), + ); + const dockerDriverPlatformPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "docker-driver-platform.ts"), + ); + const gatewayGpuPassthroughPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "gateway-gpu-passthrough.ts"), + ); + const onboardProbesPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "inference", "onboard-probes.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const registry = require(${registryPath}); +const onboardSession = require(${sessionPath}); +const credentials = require(${credentialsPath}); +const nim = require(${nimPath}); +const gatewayState = require(${gatewayStatePath}); +const dockerDriverPlatform = require(${dockerDriverPlatformPath}); +const gatewayGpuPassthrough = require(${gatewayGpuPassthroughPath}); +const onboardProbes = require(${onboardProbesPath}); + +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const commands = []; +const prompts = []; +const registryUpdates = []; +const done = new Error("INFERENCE_STEP_DONE"); +let inferenceSessionSnapshot = null; + +delete process.env.NEMOCLAW_NON_INTERACTIVE; +delete process.env.NEMOCLAW_SANDBOX_NAME; +delete process.env.NOUS_API_KEY; +for (const key of Object.keys(process.env)) { + if (key.startsWith("DISCORD_") || key.startsWith("TELEGRAM_")) { + delete process.env[key]; + } +} +process.env.NEMOCLAW_OPENSHELL_BIN = ${openshellPath}; +process.env.OPENSHELL_GATEWAY = "nemoclaw"; + +try { + Object.defineProperty(process.stdin, "isTTY", { value: true, configurable: true }); + Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true }); +} catch { + process.stdin.isTTY = true; + process.stdout.isTTY = true; +} + +runner.run = (command, opts = {}) => { + const normalized = _n(command); + commands.push({ command: normalized, env: opts.env || null }); + return { status: 0, stdout: "", stderr: "" }; +}; +runner.runCapture = (command) => { + const normalized = _n(command); + if (normalized.includes("inference get")) { + return [ + "Gateway inference:", + "", + " Route: inference.local", + " Provider: hermes-provider", + " Model: moonshotai/kimi-k2.6", + " Version: 1", + ].join("\n"); + } + return ""; +}; + +registry.getSandbox = (name) => + name === "hermes-resume" + ? { + name, + gpuEnabled: false, + provider: "hermes-provider", + model: "moonshotai/kimi-k2.6", + hermesToolGateways: [], + policies: ["nous-web"], + } + : null; +registry.reserveSandboxInferenceRoute = (name, updates) => { + registryUpdates.push({ name, updates }); + return true; +}; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +credentials.prompt = async (question) => { + prompts.push(String(question)); + if (String(question).includes("Sandbox name")) return "hermes-resume"; + return "yes"; +}; + +nim.detectGpu = () => null; +gatewayState.getGatewayReuseState = () => "healthy"; +gatewayState.shouldSelectNamedGatewayForReuse = () => false; +gatewayState.getSandboxStateFromOutputs = () => "ready"; +gatewayState.isGatewayHealthy = () => true; +dockerDriverPlatform.isLinuxDockerDriverGatewayEnabled = () => false; +gatewayGpuPassthrough.reconcileGatewayGpuReuseForGpuIntent = ({ gatewayReuseState }) => gatewayReuseState; +onboardProbes.verifyOnboardInferenceSmoke = () => {}; + +const complete = () => ({ + status: "complete", + startedAt: new Date().toISOString(), + completedAt: new Date().toISOString(), + error: null, +}); +onboardSession.saveSession( + onboardSession.createSession({ + mode: "interactive", + agent: "hermes", + sandboxName: null, + provider: "hermes-provider", + model: "moonshotai/kimi-k2.6", + endpointUrl: "https://8.8.8.8/v1", + credentialEnv: "NOUS_API_KEY", + hermesAuthMethod: "api_key", + hermesToolGateways: [], + policyPresets: ["nous-web"], + metadata: { gatewayName: "nemoclaw", fromDockerfile: null }, + steps: { + preflight: complete(), + gateway: complete(), + provider_selection: complete(), + }, + }), +); + +const originalMarkStepComplete = onboardSession.markStepComplete; +onboardSession.markStepComplete = (stepName, updates = {}) => { + const result = originalMarkStepComplete(stepName, updates); + if (stepName === "inference") { + inferenceSessionSnapshot = result; + throw done; + } + return result; +}; + +const { onboard } = require(${onboardPath}); + +(async () => { + try { + await onboard({ resume: true, agent: "hermes", acceptThirdPartySoftware: true, noGpu: true }); + throw new Error("Expected onboarding to reach the inference step"); + } catch (error) { + if (error === done || error?.message === done.message) { + console.log(JSON.stringify({ + commands, + prompts, + registryUpdates, + inferenceSessionSandboxName: inferenceSessionSnapshot?.sandboxName ?? null, + })); + return; + } + console.error(error); + process.exit(1); + } +})(); +`; + fs.writeFileSync(scriptPath, script); + + const env: Record = { + ...stripMessagingEnv(process.env), + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_OPENSHELL_BIN: path.join(fakeBin, "openshell"), + }; + delete env.NEMOCLAW_NON_INTERACTIVE; + delete env.NEMOCLAW_SANDBOX_NAME; + delete env.NOUS_API_KEY; + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env, + }); + + assert.equal(result.status, 0, result.stderr); + assert.doesNotMatch( + `${result.stderr}\n${result.stdout}`, + /Hermes Provider requires a sandbox name/, + ); + const payload = parseStdoutJson<{ + commands: CommandEntry[]; + prompts: string[]; + registryUpdates: Array<{ name: string; updates: Record }>; + inferenceSessionSandboxName: string | null; + }>(result.stdout); + + assert.ok( + payload.prompts.some((question) => question.includes("Sandbox name")), + "resume should prompt for the missing sandbox name before Hermes inference reconciliation", + ); + assert.ok( + payload.commands.some((entry) => + /inference set -g nemoclaw --no-verify --provider hermes-provider/.test(entry.command), + ), + "resume should reach openshell inference set", + ); + assert.ok(!payload.commands.some((entry) => /provider (create|update)/.test(entry.command))); + assert.equal( + payload.inferenceSessionSandboxName, + null, + "resume inference must not persist sandboxName before sandbox creation", + ); + assert.ok( + payload.registryUpdates.some( + (call) => + call.name === "hermes-resume" && + call.updates.provider === "hermes-provider" && + call.updates.model === "moonshotai/kimi-k2.6", + ), + "Hermes setup should reconcile inference against the resolved sandbox name", + ); + }); + + it("reconciles a registered Hermes Provider when a fresh shell Nous key is selected", async () => { + await withProcessEnv( + { + NOUS_API_KEY: "nous-host-secret", + OPENAI_API_KEY: undefined, + }, + async () => { + const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.join(" ") === "provider get -g nemoclaw hermes-provider" + ? { status: 0, stdout: "Provider: hermes-provider", stderr: "" } + : undefined, + overrides: { isNonInteractive: () => true }, + }); + + await harness.setupInference( + "test-box", + "moonshotai/kimi-k2.6", + "hermes-provider", + "https://8.8.8.8/v1", + "NOUS_API_KEY", + "api_key", + ); + + const update = harness.commands.find((entry) => + /provider update -g nemoclaw hermes-provider/.test(entry.command), + ); + assert.ok(update); + assert.match(update.command, /--credential NOUS_API_KEY/); + assert.equal(update.env?.NOUS_API_KEY, "nous-host-secret"); + assert.ok( + !harness.commands.some((entry) => /nous-host-secret/.test(entry.command)), + "shell credential value must not appear in argv", + ); + assert.match( + harness.commands.at(-1)?.command || "", + /inference set -g nemoclaw --no-verify --provider hermes-provider/, + ); + }, + ); + }); + it("does not delete saved OpenAI credentials when configuring local vLLM", async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-local-vllm-")); + const credentials = require("../src/lib/credentials/store") as { + saveCredential(key: string, value: string): void; + getCredential(key: string): string | null; + }; + try { + await withProcessEnv({ HOME: tmpDir, OPENAI_API_KEY: undefined }, async () => { + credentials.saveCredential("OPENAI_API_KEY", "sk-existing"); + let harness: ReturnType; + const applyLocalInferenceRoute = createLocalInferenceRouteApplier({ + runOpenshell: (args, options) => harness.runOpenshell(args, options), + isNonInteractive: () => false, + promptValidationRecovery: async () => "selection", + classifyApplyFailure: () => ({}) as never, + compactText: (value) => value.trim(), + redact: (value) => value, + localInferenceTimeoutSecs: 120, + error: vi.fn(), + exitProcess: () => assert.fail("unexpected exit"), + }); + harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" + ? { status: 1, stdout: "", stderr: "" } + : undefined, + overrides: { applyLocalInferenceRoute }, + }); + await harness.setupInference("test-box", "meta-llama", "vllm-local"); + const providerCommand = harness.commands.find((entry) => + entry.command.includes("provider create"), + ); + assert.ok(providerCommand, "expected local vLLM provider create command"); + assert.match(providerCommand.command, /--credential NEMOCLAW_VLLM_LOCAL_TOKEN/); + assert.doesNotMatch(providerCommand.command, /--credential OPENAI_API_KEY/); + assert.equal(providerCommand.env?.NEMOCLAW_VLLM_LOCAL_TOKEN, "dummy"); + assert.equal(credentials.getCredential("OPENAI_API_KEY"), "sk-existing"); + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + it("recovers the Ollama auth proxy on WSL when the sandbox needs proxy fronting", async () => { + const proxyCalls: string[] = []; + const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" + ? { status: 1, stdout: "", stderr: "" } + : undefined, + overrides: { + validateLocalProvider: () => ({ + ok: false, + message: "container cannot reach Ollama", + diagnostic: "simulated WSL native Docker reachability failure", + }), + shouldFrontOllamaWithProxy: () => true, + ensureOllamaAuthProxy: () => proxyCalls.push("ensure"), + isProxyHealthy: () => { + proxyCalls.push("healthy"); + return true; + }, + getOllamaProxyToken: () => "proxy-token", + persistAndProbeOllamaProxy: async (token: string) => { + proxyCalls.push(`persist:${token}`); + }, + applyLocalInferenceRoute: undefined, + }, + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"); + } finally { + warn.mockRestore(); + } + assert.deepEqual(proxyCalls, ["ensure", "healthy", "persist:proxy-token"]); + const providerCommand = harness.commands.find( + (entry) => + entry.command.includes("provider create") && entry.command.includes("ollama-local"), + ); + assert.ok(providerCommand, "expected ollama-local provider create command"); + assert.match(providerCommand.command, /--credential NEMOCLAW_OLLAMA_PROXY_TOKEN/); + assert.equal(providerCommand.env?.NEMOCLAW_OLLAMA_PROXY_TOKEN, "proxy-token"); + assert.doesNotMatch(providerCommand.command, /proxy-token/); + assert.ok( + harness.commands.some((entry) => + entry.command.includes("inference set -g nemoclaw --no-verify --provider ollama-local"), + ), + "expected ollama-local inference route to be selected", + ); + }); + it("surfaces a contextual error and exits when ollama-local inference set fails after the proxy-ready warning (#4257)", async () => { + const error = vi.fn(); + const exitProcess = vi.fn((code: number): never => { + throw Object.assign(new Error(`EXIT_CALLED:${code}`), { __exit: true }); + }); + const commandRouter = createDirectCommandRouter([ + { + name: "provider-get", + matches: (command) => command.startsWith("provider get"), + results: [{ status: 1, stdout: "", stderr: "" }], + }, + { + name: "ollama-inference-set", + matches: (command) => command.includes("inference set") && command.includes("ollama-local"), + results: [{ status: 7, stdout: "", stderr: "openshell: route apply failed" }], + }, + ]); + const harness = createDirectSetupInferenceHarness({ + runOpenshell: commandRouter.runOpenshell, + overrides: { + isNonInteractive: () => true, + validateLocalProvider: () => ({ + ok: false, + message: "container cannot reach Ollama", + diagnostic: "simulated WSL native Docker reachability failure", + }), + shouldFrontOllamaWithProxy: () => true, + ensureOllamaAuthProxy: () => {}, + isProxyHealthy: () => true, + getOllamaProxyToken: () => "proxy-token", + persistAndProbeOllamaProxy: async () => {}, + applyLocalInferenceRoute: undefined, + error, + exitProcess, + }, + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await assert.rejects( + harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"), + (error: Error & { __exit?: boolean }) => error.__exit === true, + ); + } finally { + warn.mockRestore(); + } + const setCmd = harness.commands.find((entry) => + entry.command.includes("inference set -g nemoclaw --no-verify --provider ollama-local"), + ); + assert.ok(setCmd, "expected ollama-local inference set command to be issued"); + assert.equal( + setCmd.ignoreError, + true, + "ollama-local inference set must use ignoreError so onboard can recover", + ); + const combinedErr = error.mock.calls.flat().join("\n"); + assert.equal(exitProcess.mock.calls.length, 1); + assert.equal(exitProcess.mock.calls[0]?.[0], 7); + assert.match(combinedErr, /No sandbox was created/); + assert.match(combinedErr, /nemoclaw onboard --resume/); + }); + it("surfaces a contextual error and exits when vllm-local inference set fails (#4257)", async () => { + const exitProcess = vi.fn((code: number): never => { + throw Object.assign(new Error(`EXIT_CALLED:${code}`), { __exit: true }); + }); + const commandRouter = createDirectCommandRouter([ + { + name: "provider-get", + matches: (command) => command.startsWith("provider get"), + results: [{ status: 1, stdout: "", stderr: "" }], + }, + { + name: "vllm-inference-set", + matches: (command) => command.includes("inference set") && command.includes("vllm-local"), + results: [{ status: 13, stdout: "", stderr: "openshell: vllm route apply failed" }], + }, + ]); + const harness = createDirectSetupInferenceHarness({ + runOpenshell: commandRouter.runOpenshell, + overrides: { + isNonInteractive: () => true, + applyLocalInferenceRoute: undefined, + exitProcess, + }, + }); + + await assert.rejects( + harness.setupInference("test-box", "meta-llama", "vllm-local"), + (error: Error & { __exit?: boolean }) => error.__exit === true, + ); + + const setCmd = harness.commands.find((entry) => + entry.command.includes("inference set -g nemoclaw --no-verify --provider vllm-local"), + ); + assert.ok(setCmd, "expected vllm-local inference set command to be issued"); + assert.equal( + setCmd.ignoreError, + true, + "vllm-local inference set must use ignoreError so onboard can recover", + ); + const combinedErr = harness.errors.join("\n"); + assert.equal(exitProcess.mock.calls.length, 1); + assert.equal(exitProcess.mock.calls[0]?.[0], 13); + assert.match(combinedErr, /No sandbox was created/); + assert.match(combinedErr, /nemoclaw onboard --resume/); + }); + it("detects when the live inference route already matches the requested provider and model", () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-inference-ready-")); + const fakeOpenshell = path.join(tmpDir, "openshell"); + const scriptPath = path.join(tmpDir, "inference-ready-check.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + + fs.writeFileSync( + fakeOpenshell, + `#!/usr/bin/env bash +if [ "$1" = "inference" ] && [ "$2" = "get" ] && [ "$3" = "-g" ] && [ "$4" = "team-gateway" ]; then + cat <<'EOF' +Gateway inference: + + Route: inference.local + Provider: nvidia-prod + Model: nvidia/nemotron-3-super-120b-a12b + Version: 1 +EOF + exit 0 +fi +exit 1 +`, + { mode: 0o755 }, + ); + + fs.writeFileSync( + scriptPath, + ` +const { isInferenceRouteReady } = require(${onboardPath}); +console.log(JSON.stringify({ + same: isInferenceRouteReady("team-gateway", "nvidia-prod", "nvidia/nemotron-3-super-120b-a12b"), + otherModel: isInferenceRouteReady("team-gateway", "nvidia-prod", "nvidia/other-model"), + otherProvider: isInferenceRouteReady("team-gateway", "openai-api", "nvidia/nemotron-3-super-120b-a12b"), +})); +`, + ); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + PATH: `${tmpDir}:${process.env.PATH || ""}`, + }, + }); + + try { + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout.trim())).toEqual({ + same: true, + otherModel: false, + otherProvider: false, + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("detects when OpenClaw is already configured inside the sandbox", () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-ready-")); + const fakeOpenshell = path.join(tmpDir, "openshell"); + const scriptPath = path.join(tmpDir, "openclaw-ready-check.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + + fs.writeFileSync( + fakeOpenshell, + `#!/usr/bin/env bash +if [ "$1" = "sandbox" ] && [ "$2" = "download" ]; then + dest="\${@: -1}" + mkdir -p "$dest/sandbox/.openclaw" + cat > "$dest/sandbox/.openclaw/openclaw.json" <<'EOF' +{"gateway":{"auth":{"token":"test-token"}}} +EOF + exit 0 +fi +exit 1 +`, + { mode: 0o755 }, + ); + + fs.writeFileSync( + scriptPath, + ` +const { isOpenclawReady } = require(${onboardPath}); +console.log(JSON.stringify({ + ready: isOpenclawReady("my-assistant"), +})); +`, + ); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + PATH: `${tmpDir}:${process.env.PATH || ""}`, + }, + }); + + try { + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout.trim())).toEqual({ ready: true }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("detects when recorded policy presets are already applied", () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-ready-")); + const registryDir = path.join(tmpDir, ".nemoclaw"); + const registryFile = path.join(registryDir, "sandboxes.json"); + const scriptPath = path.join(tmpDir, "policy-ready-check.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync( + registryFile, + JSON.stringify( + { + sandboxes: { + "my-assistant": { + name: "my-assistant", + policies: ["pypi", "npm"], + }, + }, + defaultSandbox: "my-assistant", + }, + null, + 2, + ), + ); + + fs.writeFileSync( + scriptPath, + ` +const { arePolicyPresetsApplied } = require(${onboardPath}); +console.log(JSON.stringify({ + ready: arePolicyPresetsApplied("my-assistant", ["pypi", "npm"]), + missing: arePolicyPresetsApplied("my-assistant", ["pypi", "slack"]), + empty: arePolicyPresetsApplied("my-assistant", []), +})); +`, + ); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + }, + }); + + try { + expect(result.status).toBe(0); + const payload = JSON.parse(result.stdout.trim()); + expect(payload).toEqual({ + ready: true, + missing: false, + empty: false, + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + it("uses native Anthropic provider creation without embedding the secret in argv", async () => { + await withProcessEnv({ ANTHROPIC_API_KEY: "sk-ant-TEST-NOT-A-REAL-VALUE" }, async () => { + const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" + ? { status: 1, stdout: "", stderr: "" } + : undefined, + }); + + await harness.setupInference( + "test-box", + "claude-sonnet-4-5", + "anthropic-prod", + "https://api.anthropic.com", + "ANTHROPIC_API_KEY", + ); + + const commands = harness.commands; + assert.equal(commands.length, 3); + assert.match(commands[0].command, /^provider get -g nemoclaw /); + assert.match(commands[1].command, /^provider create -g nemoclaw /); + assert.match(commands[1].command, /--type anthropic/); + assert.match(commands[1].command, /--credential ANTHROPIC_API_KEY/); + assert.doesNotMatch(commands[1].command, /sk-ant-TEST-NOT-A-REAL-VALUE/); + assert.match(commands[2].command, /^inference set -g nemoclaw /); + assert.match(commands[2].command, /--provider anthropic-prod/); + }); + }); + it("updates OpenAI-compatible providers without passing an unsupported --type flag", async () => { + await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" + ? { status: 0, stdout: "", stderr: "" } + : undefined, + }); + + await harness.setupInference( + "test-box", + "gpt-5.4", + "openai-api", + "https://api.openai.com/v1", + "OPENAI_API_KEY", + ); + + const commands = harness.commands; + assert.equal(commands.length, 3); + assert.match(commands[0].command, /^provider get -g nemoclaw /); + assert.match(commands[1].command, /^provider update -g nemoclaw openai-api/); + assert.doesNotMatch(commands[1].command, /--type/); + assert.match(commands[2].command, /^inference set -g nemoclaw --no-verify/); + }); + }); + it("re-prompts for credentials when openshell inference set fails with authorization errors", async () => { + await withProcessEnv({ OPENAI_API_KEY: "sk-bad" }, async () => { + const commandRouter = createDirectCommandRouter([ + { + name: "provider-get", + matches: (command) => command.startsWith("provider get"), + results: [{ status: 0, stdout: "", stderr: "" }], + }, + { + name: "inference-set", + matches: (command) => command.includes("inference set"), + results: [{ status: 1, stdout: "", stderr: "HTTP 403: forbidden" }, undefined], + }, + ]); + const harness = createDirectSetupInferenceHarness({ + runOpenshell: commandRouter.runOpenshell, + overrides: { + promptValidationRecovery: async () => { + process.env.OPENAI_API_KEY = "sk-good"; + return "retry"; + }, + }, + }); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + await harness.setupInference( + "test-box", + "gpt-5.4", + "openai-api", + "https://api.openai.com/v1", + "OPENAI_API_KEY", + ); + } finally { + error.mockRestore(); + } + + assert.equal(process.env.OPENAI_API_KEY, "sk-good"); + assert.equal(commandRouter.callCount("inference-set"), 2); + const providerEnvs = harness.commands + .filter((entry) => entry.command.includes("provider")) + .map((entry) => entry.env?.OPENAI_API_KEY) + .filter(Boolean); + assert.deepEqual(providerEnvs, ["sk-bad", "sk-good"]); + }); + }); + it("returns control to provider selection when inference apply recovery chooses back", async () => { + await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + const commandRouter = createDirectCommandRouter([ + { + name: "provider-get", + matches: (command) => command.startsWith("provider get"), + results: [{ status: 0, stdout: "", stderr: "" }], + }, + { + name: "inference-set", + matches: (command) => command.includes("inference set"), + results: [{ status: 1, stdout: "", stderr: "HTTP 404: model not found" }], + }, + ]); + const harness = createDirectSetupInferenceHarness({ + runOpenshell: commandRouter.runOpenshell, + overrides: { promptValidationRecovery: async () => "selection" }, + }); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + let result: Awaited>; + try { + result = await harness.setupInference( + "test-box", + "gpt-5.4", + "openai-api", + "https://api.openai.com/v1", + "OPENAI_API_KEY", + ); + } finally { + error.mockRestore(); + } + + assert.deepEqual(result, { retry: "selection" }); + assert.equal( + harness.commands.filter((entry) => entry.command.includes("inference set")).length, + 1, + ); + }); + }); + it("migrates a legacy credentials.json into env so setupInference can register the provider", async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-resume-cred-")); + const legacyDir = path.join(tmpDir, ".nemoclaw"); + const legacyFile = path.join(legacyDir, "credentials.json"); + fs.mkdirSync(legacyDir, { recursive: true, mode: 0o700 }); + fs.writeFileSync( + legacyFile, + JSON.stringify({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-STORED-KEY" }), + { mode: 0o600 }, + ); + const credentialEnv = + require("../src/lib/onboard/credential-env") as typeof import("../src/lib/onboard/credential-env.js"); + try { + await withProcessEnv({ HOME: tmpDir, OPENAI_API_KEY: undefined }, async () => { + const harness = createDirectSetupInferenceHarness({ + runOpenshell: (args) => + args.slice(0, 2).join(" ") === "provider get" + ? { status: 0, stdout: "", stderr: "" } + : undefined, + overrides: { hydrateCredentialEnv: credentialEnv.hydrateCredentialEnv }, + }); + + await harness.setupInference( + "test-box", + "gpt-5.4", + "openai-api", + "https://api.openai.com/v1", + "OPENAI_API_KEY", + ); + + assert.equal(process.env.OPENAI_API_KEY, "sk-TEST-NOT-A-REAL-STORED-KEY"); + assert.equal( + fs.existsSync(legacyFile), + true, + "legacy credentials.json must survive the staging-only hydrate path", + ); + const providerUpdate = harness.commands.find((entry) => + entry.command.includes("provider update -g nemoclaw openai-api"), + ); + assert.ok(providerUpdate, "expected provider update command"); + assert.equal(providerUpdate.env?.OPENAI_API_KEY, "sk-TEST-NOT-A-REAL-STORED-KEY"); + assert.doesNotMatch(providerUpdate.command, /sk-TEST-NOT-A-REAL-STORED-KEY/); + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); +}); diff --git a/test/onboard-sandbox-build.test.ts b/test/onboard-sandbox-build.test.ts new file mode 100644 index 00000000000..02df5dcdf98 --- /dev/null +++ b/test/onboard-sandbox-build.test.ts @@ -0,0 +1,848 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, it } from "vitest"; +import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; +import { + type CommandEntry, + onboardScriptMocksPath, + parseStdoutJson, + stripMessagingEnv, +} from "./helpers/onboard-split-context"; + +describe("onboard helpers", () => { + it("drops stale local sandbox registry entries when the live sandbox is gone", () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-stale-sandbox-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "stale-sandbox-check.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const registry = require(${registryPath}); +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +runner.runCapture = (command) => (_n(command).includes("sandbox get my-assistant") ? "" : ""); + +registry.registerSandbox({ name: "my-assistant" }); + +const { pruneStaleSandboxEntry } = require(${onboardPath}); + +const liveExists = pruneStaleSandboxEntry("my-assistant"); +console.log(JSON.stringify({ liveExists, sandbox: registry.getSandbox("my-assistant") })); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + assert.equal(payload.liveExists, false); + assert.equal(payload.sandbox, null); + }); + + it("builds the sandbox without uploading an external OpenClaw config file", { + timeout: 90_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-create-sandbox-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "create-sandbox-check.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const preflightPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const preflight = require(${preflightPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const commands = []; +const registerCalls = []; +const updateCalls = []; +const defaultCalls = []; +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return ""; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); + if (mockedCapture !== null) return mockedCapture; + } + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + return ""; +}; +registry.registerSandbox = (entry) => { + registerCalls.push(entry); + return true; +}; +registry.updateSandbox = (name, updates) => { + updateCalls.push({ name, updates }); + return true; +}; +registry.setDefault = (name) => { + defaultCalls.push(name); + return true; +}; +registry.removeSandbox = () => true; +preflight.checkPortAvailable = async () => ({ ok: true }); +credentials.prompt = async () => ""; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const sandboxName = await createSandbox(null, "gpt-5.4"); + console.log(JSON.stringify({ sandboxName, commands, registerCalls, updateCalls, defaultCalls })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + assert.equal(payload.sandboxName, "my-assistant"); + // createSandbox no longer marks the sandbox default — that is deferred to the + // finalization step so a cancel at policy presets can't leave an unconfigured + // sandbox as default (#4614). + assert.deepEqual(payload.defaultCalls, []); + assert.ok( + payload.registerCalls.some( + (entry: Record) => + entry.name === "my-assistant" && + entry.model === "gpt-5.4" && + Object.prototype.hasOwnProperty.call(entry, "agentVersion"), + ), + "expected registry metadata for created sandbox", + ); + assert.ok( + payload.updateCalls.every( + (call: { name: string; updates: Record }) => + call.name === "my-assistant" && call.updates, + ), + "expected any registry metadata updates to target the created sandbox", + ); + const createCommand = payload.commands.find((entry: CommandEntry) => + entry.command.includes("sandbox create"), + ); + assert.ok(createCommand, "expected sandbox create command"); + assert.match(createCommand.command, /nemoclaw-start/); + assert.doesNotMatch(createCommand.command, /--upload/); + assert.doesNotMatch(createCommand.command, /OPENCLAW_CONFIG_PATH/); + assert.doesNotMatch(createCommand.command, /NVIDIA_INFERENCE_API_KEY=/); + assert.doesNotMatch(createCommand.command, /DISCORD_BOT_TOKEN=/); + assert.doesNotMatch(createCommand.command, /SLACK_BOT_TOKEN=/); + assert.ok( + payload.commands.some( + (entry: CommandEntry) => + entry.command.includes("forward start --background 18789 my-assistant") || + entry.command.includes("forward start --background 0.0.0.0:18789 my-assistant"), + ), + "expected dashboard forward (loopback or WSL 0.0.0.0)", + ); + }); + + it("skips OpenClaw sandbox-base resolution for agent-staged Dockerfiles", async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-agent-base-skip-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "agent-base-skip.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const preflightPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + const agentOnboardPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "agent", "onboard.ts"), + ); + const sandboxBaseImagePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "sandbox-base-image.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const preflight = require(${preflightPath}); +const credentials = require(${credentialsPath}); +const agentOnboard = require(${agentOnboardPath}); +const sandboxBaseImage = require(${sandboxBaseImagePath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); +require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "docker-driver-platform.ts"))}).isLinuxDockerDriverGatewayEnabled = () => false; +const commands = []; +const logs = []; +const warnings = []; +const baseResolutionCalls = []; +const originalLog = console.log; +const originalWarn = console.warn; +console.log = (...args) => { + logs.push(args.join(" ")); + originalLog(...args); +}; +console.warn = (...args) => { + warnings.push(args.join(" ")); + originalWarn(...args); +}; + +sandboxBaseImage.resolveSandboxBaseImage = (options) => { + baseResolutionCalls.push(options); + return { + ref: "ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + digest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + source: "latest", + glibcVersion: "2.39", + }; +}; + +agentOnboard.createAgentSandbox = () => { + const buildCtx = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-agent-build-")); + const stagedDockerfile = path.join(buildCtx, "Dockerfile"); + fs.writeFileSync( + stagedDockerfile, + [ + "ARG BASE_IMAGE=nemoclaw-hermes-sandbox-base-local:test", + "FROM \${BASE_IMAGE}", + "ARG NEMOCLAW_MODEL=nvidia/nemotron-3-super-120b-a12b", + "ARG NEMOCLAW_PROVIDER_KEY=custom", + "ARG NEMOCLAW_PRIMARY_MODEL_REF=nvidia/nemotron-3-super-120b-a12b", + "ARG CHAT_UI_URL=http://127.0.0.1:18789", + "ARG NEMOCLAW_INFERENCE_BASE_URL=https://inference.local/v1", + "ARG NEMOCLAW_INFERENCE_API=openai-completions", + "ARG NEMOCLAW_INFERENCE_COMPAT_B64=e30=", + "ARG NEMOCLAW_MESSAGING_PLAN_B64=", + "ARG NEMOCLAW_HERMES_TOOL_GATEWAY_BROKER=0", + "ARG NEMOCLAW_HERMES_TOOL_GATEWAY_PRESETS_B64=W10=", + "ARG NEMOCLAW_BUILD_ID=default", + "ARG NEMOCLAW_DARWIN_VM_COMPAT=0", + "CMD [\"/bin/bash\"]", + ].join("\\n"), + ); + return { buildCtx, stagedDockerfile }; +}; + +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runFile = (file, args = [], opts = {}) => { + commands.push({ command: _n([file, ...args]), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get hermes-sandbox")) return ""; + if (_n(command).includes("sandbox list")) return "hermes-sandbox Ready"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); + if (mockedCapture !== null) return mockedCapture; + } + if (_n(command).includes("forward list")) return "hermes-sandbox 127.0.0.1 18789 12345 running\nhermes-sandbox 127.0.0.1 8642 12346 running"; + return ""; +}; +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; +registry.getSandbox = () => null; +preflight.checkPortAvailable = async () => ({ ok: true }); +credentials.prompt = async () => ""; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: hermes-sandbox\\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const agent = { + name: "hermes", + displayName: "Hermes Agent", + forwardPort: 18789, + forward_ports: [18789, 8642], + healthProbe: { url: "http://127.0.0.1:8642/health", port: 8642, timeout_seconds: 90 }, + dashboard: { kind: "ui", label: "Dashboard", path: "/", healthPath: "/api/status", auth: "session" }, + expectedVersion: "2026.4.23", + policyAdditionsPath: null, + }; + await createSandbox( + null, + "gpt-5.4", + "nvidia-prod", + null, + "hermes-sandbox", + null, + [], + null, + agent, + null, + null, + null, + ["nous-web"], + ); + console.log(JSON.stringify({ commands, logs, warnings, baseResolutionCalls })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...stripMessagingEnv(process.env), + HOME: tmpDir, + NEMOCLAW_HOME: path.join(tmpDir, ".nemoclaw"), + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payload = parseStdoutJson<{ + commands: CommandEntry[]; + logs: string[]; + warnings: string[]; + baseResolutionCalls: unknown[]; + }>(result.stdout); + assert.equal(payload.baseResolutionCalls.length, 0); + const createCommand = payload.commands.find((entry) => + entry.command.includes("sandbox create"), + ); + assert.ok(createCommand, "expected sandbox create command"); + assert.match(createCommand.command, /--provider hermes-sandbox-hermes-tool-gateway/); + assert.doesNotMatch(createCommand.command, /TOOL_GATEWAY_USER_TOKEN=/); + assert.doesNotMatch(createCommand.command, /NEMOCLAW_HERMES_TOOL_GATEWAY_REFRESH_TOKEN=/); + assert.ok( + !payload.logs.some((line) => line.includes("Using sandbox base image")), + "Hermes agent Dockerfile path should not log OpenClaw sandbox-base usage", + ); + assert.ok( + !payload.warnings.some((line) => line.includes("base image")), + "Hermes agent Dockerfile path should not warn about OpenClaw sandbox-base availability", + ); + }); + + it("keeps resolving the OpenClaw sandbox base image on the default Dockerfile path", async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-base-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "openclaw-base-resolve.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const preflightPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + const buildContextPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "sandbox", "build-context.ts"), + ); + const sandboxBaseImagePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "sandbox-base-image.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const preflight = require(${preflightPath}); +const credentials = require(${credentialsPath}); +const buildContext = require(${buildContextPath}); +const sandboxBaseImage = require(${sandboxBaseImagePath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const commands = []; +const logs = []; +const baseResolutionCalls = []; +const originalLog = console.log; +console.log = (...args) => { + logs.push(args.join(" ")); + originalLog(...args); +}; + +sandboxBaseImage.resolveSandboxBaseImage = (options) => { + baseResolutionCalls.push(options); + return { + ref: "ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + digest: "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + source: "latest", + glibcVersion: "2.39", + }; +}; +buildContext.stageOptimizedSandboxBuildContext = () => { + const buildCtx = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-build-")); + const stagedDockerfile = path.join(buildCtx, "Dockerfile"); + fs.writeFileSync( + stagedDockerfile, + [ + "ARG BASE_IMAGE=ghcr.io/nvidia/nemoclaw/sandbox-base:latest", + "FROM \${BASE_IMAGE}", + "ARG NEMOCLAW_MODEL=nvidia/nemotron-3-super-120b-a12b", + "ARG NEMOCLAW_PROVIDER_KEY=nvidia", + "ARG NEMOCLAW_PRIMARY_MODEL_REF=nvidia/nemotron-3-super-120b-a12b", + "ARG CHAT_UI_URL=http://127.0.0.1:18789", + "ARG NEMOCLAW_INFERENCE_BASE_URL=https://inference.local/v1", + "ARG NEMOCLAW_INFERENCE_API=openai-completions", + "ARG NEMOCLAW_INFERENCE_COMPAT_B64=e30=", + "ARG NEMOCLAW_MESSAGING_PLAN_B64=", + "ARG NEMOCLAW_BUILD_ID=default", + "ARG NEMOCLAW_DARWIN_VM_COMPAT=0", + "CMD [\"/bin/bash\"]", + ].join("\\n"), + ); + return { buildCtx, stagedDockerfile }; +}; + +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runFile = (file, args = [], opts = {}) => { + commands.push({ command: _n([file, ...args]), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return ""; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); + if (mockedCapture !== null) return mockedCapture; + } + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + return ""; +}; +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; +registry.getSandbox = () => null; +preflight.checkPortAvailable = async () => ({ ok: true }); +credentials.prompt = async () => ""; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ commands, logs, baseResolutionCalls })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...stripMessagingEnv(process.env), + HOME: tmpDir, + NEMOCLAW_HOME: path.join(tmpDir, ".nemoclaw"), + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payload = parseStdoutJson<{ + logs: string[]; + baseResolutionCalls: Array<{ imageName?: string }>; + }>(result.stdout); + assert.equal(payload.baseResolutionCalls.length, 1); + assert.equal(payload.baseResolutionCalls[0]?.imageName, "ghcr.io/nvidia/nemoclaw/sandbox-base"); + assert.ok( + payload.logs.some((line) => line.includes("Pinning base image to sha256:bbbbbbbbbbbb")), + "default OpenClaw path should still log base-image pinning", + ); + }); + + it("binds the dashboard forward to 0.0.0.0 when CHAT_UI_URL points to a remote host", async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-remote-forward-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "create-sandbox-remote-forward.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const preflightPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const preflight = require(${preflightPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const commands = []; +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return ""; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); + if (mockedCapture !== null) return mockedCapture; + } + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + return ""; +}; +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; +preflight.checkPortAvailable = async () => ({ ok: true }); +credentials.prompt = async () => ""; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.CHAT_UI_URL = "https://chat.example.com"; + await createSandbox(null, "gpt-5.4"); + console.log(JSON.stringify(commands)); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const commands = parseStdoutJson(result.stdout); + assert.ok( + commands.some((entry: CommandEntry) => + entry.command.includes("forward start --background 0.0.0.0:18789 my-assistant"), + ), + "expected remote dashboard forward target", + ); + }); + + it("injects NEMOCLAW_DASHBOARD_PORT into sandbox create envArgs when set (#1925)", async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-dashboard-port-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "dashboard-port-envargs.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const preflightPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const preflight = require(${preflightPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const commands = []; +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runFile = (file, args = [], opts = {}) => { + commands.push({ command: _n([file, ...args]), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return ""; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + // Custom port: dashboard readiness curl uses 19000 (DASHBOARD_PORT from env) + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); + if (mockedCapture !== null) return mockedCapture; + } + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 19000 12345 running"; + return ""; +}; +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; +preflight.checkPortAvailable = async () => ({ ok: true }); +credentials.prompt = async () => ""; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const sandboxName = await createSandbox(null, "gpt-5.4"); + console.log(JSON.stringify({ sandboxName, commands })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + // Strip CHAT_UI_URL so createSandbox falls back to http://127.0.0.1:19000. + // Without this, a CHAT_UI_URL set in the developer's shell or CI would be + // inherited, causing chatUiUrl to use the wrong port and making the forward + // command assertion below fail spuriously. + const { + CHAT_UI_URL: _stripped, + HTTP_PROXY: _httpProxy, + HTTPS_PROXY: _httpsProxy, + NO_PROXY: _noProxy, + http_proxy: _lowerHttpProxy, + https_proxy: _lowerHttpsProxy, + no_proxy: _lowerNoProxy, + ...inheritedEnv + } = process.env; + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...inheritedEnv, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + NEMOCLAW_DASHBOARD_PORT: "19000", + HTTP_PROXY: "http://127.0.0.1:8888", + HTTPS_PROXY: "http://127.0.0.1:8888", + NO_PROXY: "corp.internal", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + const createCommand = payload.commands.find((entry: CommandEntry) => + entry.command.includes("sandbox create"), + ); + assert.ok(createCommand, "expected sandbox create command"); + // Part 1 of fix (#1925): NEMOCLAW_DASHBOARD_PORT must be in envArgs so + // nemoclaw-start.sh can unconditionally override CHAT_UI_URL at runtime, + // overriding whatever value the Docker image had baked in. + assert.match(createCommand.command, /NEMOCLAW_DASHBOARD_PORT=19000/); + assert.match(createCommand.command, /HTTP_PROXY=http:\/\/127\.0\.0\.1:8888/); + assert.match(createCommand.command, /HTTPS_PROXY=http:\/\/127\.0\.0\.1:8888/); + // OpenClaw home/state/workspace dirs must be pinned in the sandbox env so + // `openclaw skills install` and `openclaw skills list` resolve the same + // paths. Without this, the upstream skill loader can fall back to a + // hardcoded DEFAULT_AGENT_WORKSPACE_DIR that drifts from the install path + // and hides workspace-installed skills from `skills list`. + assert.match(createCommand.command, /OPENCLAW_HOME=\/sandbox(?:\s|$)/); + assert.match(createCommand.command, /OPENCLAW_STATE_DIR=\/sandbox\/\.openclaw(?:\s|$)/); + assert.match( + createCommand.command, + /OPENCLAW_WORKSPACE_DIR=\/sandbox\/\.openclaw\/workspace(?:\s|$)/, + ); + const noProxyMatch = createCommand.command.match(/(?:^|\s)NO_PROXY=([^\s]+)/); + assert.ok( + noProxyMatch, + `expected NO_PROXY in sandbox create command:\n${createCommand.command}`, + ); + const noProxyEntries = noProxyMatch[1].split(","); + assert.ok(noProxyEntries.includes("corp.internal")); + assert.ok(noProxyEntries.includes("localhost")); + assert.ok(noProxyEntries.includes("127.0.0.1")); + assert.ok(noProxyEntries.includes("host.docker.internal")); + // Forward must use same-port mapping (openshell does not support asymmetric) + assert.ok( + payload.commands.some( + (entry: CommandEntry) => + entry.command.includes("forward start --background 19000 my-assistant") || + entry.command.includes("forward start --background 0.0.0.0:19000 my-assistant"), + ), + "expected dashboard forward for port 19000", + ); + assert.ok( + !payload.commands.some((entry: CommandEntry) => entry.command.includes("19000:18789")), + "forward must not use asymmetric 19000:18789 mapping", + ); + assert.ok( + !payload.commands.some((entry: CommandEntry) => entry.command.includes("19000:19000")), + "forward must not use port:port form (openshell does not support it)", + ); + }); +}); diff --git a/test/onboard-sandbox-recreation.test.ts b/test/onboard-sandbox-recreation.test.ts new file mode 100644 index 00000000000..69547d80169 --- /dev/null +++ b/test/onboard-sandbox-recreation.test.ts @@ -0,0 +1,1268 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, it } from "vitest"; +import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; +import { type CommandEntry, onboardScriptMocksPath } from "./helpers/onboard-split-context"; + +describe("onboard helpers", () => { + it("non-interactive exits with error when existing sandbox is not ready", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync( + path.join(os.tmpdir(), "nemoclaw-onboard-noninteractive-notready-"), + ); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "noninteractive-notready.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const childProcess = require("node:child_process"); + +runner.run = (command) => { + if (_n(command).includes("sandbox delete")) { + throw new Error("unexpected sandbox delete"); + } + return { status: 0 }; +}; +runner.runCapture = (command) => { + // Existing sandbox that is NOT ready + if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; + if (_n(command).includes("sandbox list")) return "my-assistant NotReady"; + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +childProcess.spawn = () => { + throw new Error("unexpected sandbox create"); +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log("ERROR_DID_NOT_EXIT"); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const env: Record = { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }; + delete env["NEMOCLAW_RECREATE_SANDBOX"]; + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env, + }); + + assert.notEqual(result.status, 0, "expected non-zero exit for not-ready sandbox"); + assert.ok( + !result.stdout.includes("ERROR_DID_NOT_EXIT"), + "should have exited before reaching sandbox create", + ); + const output = (result.stdout || "") + (result.stderr || ""); + assert.ok( + output.includes("--recreate-sandbox") || output.includes("NEMOCLAW_RECREATE_SANDBOX"), + "should hint about --recreate-sandbox flag", + ); + }); + + it("recreate-sandbox flag forces deletion and recreation of a ready sandbox", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-flag-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "recreate-flag.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const commands = []; let registeredSandbox = null; +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { + defaultCurlOutput: "ok", + }); + if (mockedCapture !== null) return mockedCapture; + } + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); +registry.registerSandbox = (entry) => { registeredSandbox = entry; return true; }; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); +preflight.checkPortAvailable = async () => ({ ok: true }); + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; + process.env.NEMOCLAW_RECREATE_WITHOUT_BACKUP = "1"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, commands, registeredSandbox })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + NEMOCLAW_POLICY_TIER: "restricted", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + assert.ok( + payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox delete")), + "should delete existing sandbox when --recreate-sandbox is set", + ); + assert.ok( + payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox create")) && + payload.registeredSandbox?.policyTier === "restricted", + "should create a sandbox and persist its tier before policy finalization", + ); + }); + it("recreate-sandbox flag backs up and restores workspace state", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-backup-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "recreate-backup.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const sandboxStatePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "sandbox.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const sandboxState = require(${sandboxStatePath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const events = []; +runner.run = (command) => { + events.push({ kind: "run", cmd: _n(command) }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + const cmd = _n(command); + if (cmd.includes("sandbox get my-assistant")) return "my-assistant"; + if (cmd.includes("sandbox list")) return "my-assistant Ready"; + if (cmd.includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { + defaultCurlOutput: "ok", + }); + if (mockedCapture !== null) return mockedCapture; + } + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +sandboxState.backupSandboxState = (name) => { + events.push({ kind: "backup", name }); + return { + success: true, + backedUpDirs: ["workspace", "skills"], + failedDirs: [], + backedUpFiles: ["UPGRADE_MARKER.md"], + failedFiles: [], + manifest: { backupPath: "/tmp/fake-backup-path", timestamp: "2026-05-25T00:00:00Z" }, + }; +}; +sandboxState.restoreRecreatedSandboxState = (name, backupPath, options) => { + events.push({ kind: "restore", name, backupPath, options }); + return { + success: true, + restoredDirs: ["workspace", "skills"], + failedDirs: [], + restoredFiles: ["UPGRADE_MARKER.md"], + failedFiles: [], + }; +}; + +const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); +preflight.checkPortAvailable = async () => ({ ok: true }); + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4243; + events.push({ kind: "spawn", cmd: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]) }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, events })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + + const events = payload.events as Array<{ + kind: string; + cmd?: string; + name?: string; + backupPath?: string; + options?: { targetAgentType?: string; freshOpenClawImagePluginInstalls?: unknown[] }; + }>; + const backupIndex = events.findIndex((e) => e.kind === "backup"); + const deleteIndex = events.findIndex( + (e) => e.kind === "run" && (e.cmd || "").includes("sandbox delete"), + ); + const restoreIndex = events.findIndex((e) => e.kind === "restore"); + + assert.ok(backupIndex >= 0, "should call backupSandboxState before delete"); + assert.ok(deleteIndex > backupIndex, "backup must happen before sandbox delete"); + assert.ok(restoreIndex > deleteIndex, "restore must happen after sandbox recreate"); + const backupEvent = events[backupIndex]; + assert.equal(backupEvent?.name, "my-assistant", "backup target must match sandbox name"); + const restoreEvent = events[restoreIndex]; + assert.equal(restoreEvent?.backupPath, "/tmp/fake-backup-path", "restore must use backup path"); + assert.equal(restoreEvent?.options?.targetAgentType, "openclaw"); + assert.equal(restoreEvent?.options?.freshOpenClawImagePluginInstalls, undefined); + }); + + it("recreate-sandbox with NEMOCLAW_RECREATE_WITHOUT_BACKUP=1 skips backup", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-skip-backup-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "recreate-skip-backup.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const sandboxStatePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "sandbox.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const sandboxState = require(${sandboxStatePath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const events = []; +runner.run = (command) => { + events.push({ kind: "run", cmd: _n(command) }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + const cmd = _n(command); + if (cmd.includes("sandbox get my-assistant")) return "my-assistant"; + if (cmd.includes("sandbox list")) return "my-assistant Ready"; + if (cmd.includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { + defaultCurlOutput: "ok", + }); + if (mockedCapture !== null) return mockedCapture; + } + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +sandboxState.backupSandboxState = () => { + events.push({ kind: "backup" }); + return { success: true, backedUpDirs: [], failedDirs: [], backedUpFiles: [], failedFiles: [] }; +}; +sandboxState.restoreRecreatedSandboxState = () => { + events.push({ kind: "restore" }); + return { success: true, restoredDirs: [], failedDirs: [], restoredFiles: [], failedFiles: [] }; +}; + +const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); +preflight.checkPortAvailable = async () => ({ ok: true }); + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4244; + events.push({ kind: "spawn", cmd: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]) }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; + process.env.NEMOCLAW_RECREATE_WITHOUT_BACKUP = "1"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, events })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + const events = payload.events as Array<{ kind: string }>; + assert.ok( + !events.some((e) => e.kind === "backup"), + "should not call backupSandboxState when NEMOCLAW_RECREATE_WITHOUT_BACKUP=1", + ); + assert.ok( + !events.some((e) => e.kind === "restore"), + "should not call restoreRecreatedSandboxState when no backup occurred", + ); + }); + + it("recreate-sandbox flag backs up and restores when existing sandbox is not ready", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-notready-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "recreate-notready.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const sandboxStatePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "sandbox.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const sandboxState = require(${sandboxStatePath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const events = []; +let sandboxDeleted = false; +runner.run = (command) => { + const cmd = _n(command); + events.push({ kind: "run", cmd }); + if (cmd.includes("sandbox delete")) sandboxDeleted = true; + return { status: 0 }; +}; +runner.runCapture = (command) => { + const cmd = _n(command); + if (cmd.includes("sandbox get my-assistant")) return "my-assistant"; + if (cmd.includes("sandbox list")) { + return sandboxDeleted ? "my-assistant Ready" : "my-assistant NotReady"; + } + if (cmd.includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { + defaultCurlOutput: "ok", + }); + if (mockedCapture !== null) return mockedCapture; + } + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +sandboxState.backupSandboxState = (name) => { + events.push({ kind: "backup", name }); + return { + success: true, + backedUpDirs: ["workspace"], + failedDirs: [], + backedUpFiles: ["UPGRADE_MARKER.md"], + failedFiles: [], + manifest: { backupPath: "/tmp/fake-backup-notready", timestamp: "2026-05-25T00:00:00Z" }, + }; +}; +sandboxState.restoreRecreatedSandboxState = (name, backupPath) => { + events.push({ kind: "restore", name, backupPath }); + return { + success: true, + restoredDirs: ["workspace"], + failedDirs: [], + restoredFiles: ["UPGRADE_MARKER.md"], + failedFiles: [], + }; +}; + +const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); +preflight.checkPortAvailable = async () => ({ ok: true }); + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4245; + events.push({ kind: "spawn", cmd: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]) }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, events })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + + const events = payload.events as Array<{ + kind: string; + cmd?: string; + name?: string; + backupPath?: string; + }>; + const backupIndex = events.findIndex((e) => e.kind === "backup"); + const deleteIndex = events.findIndex( + (e) => e.kind === "run" && (e.cmd || "").includes("sandbox delete"), + ); + const restoreIndex = events.findIndex((e) => e.kind === "restore"); + + assert.ok(backupIndex >= 0, "should call backupSandboxState for not-ready sandbox"); + assert.ok(deleteIndex > backupIndex, "backup must happen before sandbox delete"); + assert.ok(restoreIndex > deleteIndex, "restore must happen after sandbox recreate"); + }); + + it("recreating a sandbox preserves the user's policy preset selections", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-preserves-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "recreate-preserves.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const sessionModulePath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const onboardSession = require(${sessionModulePath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const commands = []; +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { + defaultCurlOutput: "ok", + }); + if (mockedCapture !== null) return mockedCapture; + } + return ""; +}; + +// Existing sandbox has a custom preset selection: only "npm" (not the +// full "balanced" tier). Recreating the sandbox must preserve this +// customisation rather than reverting to the tier defaults. +registry.getSandbox = () => ({ + name: "my-assistant", + gpuEnabled: false, + policies: ["npm"], + policyTier: "balanced", +}); +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); +preflight.checkPortAvailable = async () => ({ ok: true }); + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; + process.env.NEMOCLAW_RECREATE_WITHOUT_BACKUP = "1"; + await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + const session = onboardSession.loadSession(); + console.log(JSON.stringify({ policyPresets: session && session.policyPresets })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + + assert.deepEqual( + payload.policyPresets, + ["npm"], + "createSandbox should write the previous sandbox's policy presets to the onboard session before destroying it so they can be reapplied after recreation", + ); + }); + + it("interactive mode prompts before reusing an existing ready sandbox", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-interactive-reuse-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "interactive-reuse.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); +const fs = require("node:fs"); +const path = require("node:path"); + +const commands = []; +runner.run = (command, opts = {}) => { + const commandString = Array.isArray(command) ? command.join(" ") : String(command); + if (_n(command).includes("sandbox download")) { + const parts = commandString.match(/'([^']*)'/g) || []; + const downloadDir = Array.isArray(command) + ? String(command[command.length - 1] || "") + : parts.length + ? parts[parts.length - 1].slice(1, -1) + : null; + if (downloadDir) { + fs.mkdirSync(downloadDir, { recursive: true }); + fs.writeFileSync( + path.join(downloadDir, "config.json"), + JSON.stringify({ provider: "nvidia-prod", model: "gpt-5.4" }), + ); + } + } + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runFile = (file, args = [], opts = {}) => { + commands.push({ type: "runFile", command: _n([file, ...args]), file, args, env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); + +// Mock prompt to return "y" (reuse) +credentials.prompt = async () => "y"; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, commands })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + // Run WITHOUT NEMOCLAW_NON_INTERACTIVE to exercise interactive path + const env: Record = { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + }; + delete env["NEMOCLAW_NON_INTERACTIVE"]; + delete env["NEMOCLAW_RECREATE_SANDBOX"]; + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + + assert.equal(payload.sandboxName, "my-assistant", "should reuse when user answers y"); + assert.ok( + payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox create")), + "should NOT recreate sandbox when user chooses to reuse", + ); + assert.ok( + payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox delete")), + "should NOT delete sandbox when user chooses to reuse", + ); + assert.ok( + result.stdout.includes("already exists"), + "should show 'already exists' message in interactive mode", + ); + }); + + it("interactive mode deletes and recreates sandbox when user confirms drift recreate", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-interactive-decline-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "interactive-decline.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); +const fs = require("node:fs"); +const path = require("node:path"); + +const commands = []; +runner.run = (command, opts = {}) => { + const commandString = Array.isArray(command) ? command.join(" ") : String(command); + if (_n(command).includes("sandbox download")) { + const parts = commandString.match(/'([^']*)'/g) || []; + const downloadDir = Array.isArray(command) + ? String(command[command.length - 1] || "") + : parts.length + ? parts[parts.length - 1].slice(1, -1) + : null; + if (downloadDir) { + fs.mkdirSync(downloadDir, { recursive: true }); + fs.writeFileSync( + path.join(downloadDir, "config.json"), + JSON.stringify({ provider: "openai-prod", model: "gpt-4o" }), + ); + } + } + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runFile = (file, args = [], opts = {}) => { + commands.push({ type: "runFile", command: _n([file, ...args]), file, args, env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; + if (_n(command).includes("sandbox list")) return "my-assistant Ready"; + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { + defaultCurlOutput: "ok", + }); + if (mockedCapture !== null) return mockedCapture; + } + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); +preflight.checkPortAvailable = async () => ({ ok: true }); + +// Mock prompt to return "y" (confirm recreate) +credentials.prompt = async () => "y"; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, commands })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + // Run WITHOUT NEMOCLAW_NON_INTERACTIVE to exercise interactive path + const env: Record = { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_RECREATE_WITHOUT_BACKUP: "1", + }; + delete env["NEMOCLAW_NON_INTERACTIVE"]; + delete env["NEMOCLAW_RECREATE_SANDBOX"]; + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + + assert.ok( + payload.commands.some((entry: CommandEntry) => /sandbox.*delete/.test(String(entry.command))), + "should delete existing sandbox when user confirms recreate", + ); + assert.ok( + payload.commands.some((entry: CommandEntry) => /sandbox.*create/.test(String(entry.command))), + "should create a new sandbox when user confirms recreate", + ); + assert.ok( + result.stdout.includes("requested inference selection changed"), + "should show drift warning before prompting", + ); + }); + + it("interactive mode auto-recreates when existing sandbox is not ready", { + timeout: 60_000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-interactive-notready-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "interactive-notready.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); + +const commands = []; +let sandboxDeleted = false; +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + if (_n(command).includes("sandbox delete")) sandboxDeleted = true; + return { status: 0 }; +}; +runner.runCapture = (command) => { + // Existing sandbox that is NOT ready initially, becomes Ready after recreation + if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; + if (_n(command).includes("sandbox list")) { + return sandboxDeleted ? "my-assistant Ready" : "my-assistant NotReady"; + } + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { + defaultCurlOutput: "ok", + }); + if (mockedCapture !== null) return mockedCapture; + } + return ""; +}; +registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; + +const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); +preflight.checkPortAvailable = async () => ({ ok: true }); + +// User confirms recreation when prompted +credentials.prompt = async () => "y"; + +const fakeSpawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + child.emit("close", 0); + }); + return child; +}; +childProcess.spawn = fakeSpawn; + +// Also patch spawn inside the compiled sandbox-create-stream module. +// It imports spawn at load time from "node:child_process", so patching the +// childProcess object above does not reach it. Patch the cached module +// directly so streamSandboxCreate (called by createSandbox) doesn't spawn +// a real bash process that tries to hit a live gateway. +const sandboxCreateStreamMod = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "sandbox", "create-stream.ts"))}); +const _origStreamCreate = sandboxCreateStreamMod.streamSandboxCreate; +sandboxCreateStreamMod.streamSandboxCreate = (command, env, options = {}) => { + return _origStreamCreate(command, env, { ...options, spawnImpl: fakeSpawn }); +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, commands })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + // Run WITHOUT NEMOCLAW_NON_INTERACTIVE to exercise interactive path + const env: Record = { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_RECREATE_WITHOUT_BACKUP: "1", + }; + delete env["NEMOCLAW_NON_INTERACTIVE"]; + delete env["NEMOCLAW_RECREATE_SANDBOX"]; + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env, + }); + + assert.equal(result.status, 0, result.stderr); + const payloadLine = result.stdout + .trim() + .split("\n") + .slice() + .reverse() + .find((line) => line.startsWith("{") && line.endsWith("}")); + assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); + const payload = JSON.parse(payloadLine); + + assert.ok( + payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox delete")), + "should delete not-ready sandbox after user confirms", + ); + assert.ok( + payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox create")), + "should recreate sandbox when existing one is not ready", + ); + assert.ok(result.stdout.includes("not ready"), "should mention sandbox is not ready"); + }); + it("continues once the sandbox is Ready even if the create stream never closes", { + timeout: 20000, + }, async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-create-ready-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "create-sandbox-ready-check.js"); + const payloadPath = path.join(tmpDir, "payload.json"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); + const preflightPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), + ); + const credentialsPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "credentials", "store.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const preflight = require(${preflightPath}); +const credentials = require(${credentialsPath}); +const childProcess = require("node:child_process"); +const { EventEmitter } = require("node:events"); +const fs = require("node:fs"); + +const commands = []; +let sandboxListCalls = 0; +const keepAlive = setInterval(() => {}, 1000); +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + if (_n(command).includes("sandbox get my-assistant")) return ""; + if (_n(command).includes("sandbox list")) { + sandboxListCalls += 1; + return sandboxListCalls >= 2 ? "my-assistant Ready" : "my-assistant Pending"; + } + { + const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); + if (mockedCapture !== null) return mockedCapture; + } + if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; + return ""; +}; +registry.registerSandbox = () => true; +registry.updateSandbox = () => true; +registry.setDefault = () => true; +registry.removeSandbox = () => true; +preflight.checkPortAvailable = async () => ({ ok: true }); +credentials.prompt = async () => ""; + +childProcess.spawn = (...args) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + child.unref = () => {}; + child.pid = 4242; + child.killCalls = []; + child.unrefCalls = 0; + child.stdout.destroyCalls = 0; + child.stderr.destroyCalls = 0; + child.stdout.destroy = () => { + child.stdout.destroyCalls += 1; + }; + child.stderr.destroy = () => { + child.stderr.destroyCalls += 1; + }; + child.unref = () => { + child.unrefCalls += 1; + }; + child.kill = (signal) => { + child.killCalls.push(signal); + process.nextTick(() => child.emit("close", signal === "SIGTERM" ? 0 : 1)); + return true; + }; + commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null, child }); + process.nextTick(() => { + child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); + }); + return child; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + const sandboxName = await createSandbox(null, "gpt-5.4"); + const createCommand = commands.find((entry) => entry.command.includes("sandbox create")); + fs.writeFileSync(${JSON.stringify(payloadPath)}, JSON.stringify({ + sandboxName, + sandboxListCalls, + killCalls: createCommand.child.killCalls, + unrefCalls: createCommand.child.unrefCalls, + stdoutDestroyCalls: createCommand.child.stdout.destroyCalls, + stderrDestroyCalls: createCommand.child.stderr.destroyCalls, + })); + clearInterval(keepAlive); +})().catch((error) => { + clearInterval(keepAlive); + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + OPENSHELL_DRIVERS: "docker", + }, + timeout: 15000, + }); + + assert.equal(result.status, 0, result.stderr); + const payload = JSON.parse(fs.readFileSync(payloadPath, "utf8")); + assert.equal(payload.sandboxName, "my-assistant"); + assert.ok(payload.sandboxListCalls >= 2); + assert.deepEqual(payload.killCalls, ["SIGTERM"]); + assert.equal(payload.unrefCalls, 1); + assert.equal(payload.stdoutDestroyCalls, 1); + assert.equal(payload.stderrDestroyCalls, 1); + }); +}); diff --git a/test/onboard.test.ts b/test/onboard.test.ts index faaac2649a4..3c6adb498fc 100644 --- a/test/onboard.test.ts +++ b/test/onboard.test.ts @@ -6,7 +6,7 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import { appendHostProxyEnvArgs } from "../src/lib/onboard/host-proxy-env.js"; import { isValidInferenceInputsOverride, @@ -14,13 +14,11 @@ import { shouldPromptForInferenceInputCapability, } from "../src/lib/onboard/inference-input-capability.js"; import { createInferenceRouteHelpers } from "../src/lib/onboard/inference-route.js"; -import { createLocalInferenceRouteApplier } from "../src/lib/onboard/local-inference-route.js"; import type { SetupInference, SetupInferenceDeps } from "../src/lib/onboard/setup-inference.js"; import { stageOptimizedSandboxBuildContext } from "../src/lib/sandbox/build-context.js"; import { writeOkOpenshell } from "./helpers/onboard-openshell-fixture"; import { testTimeoutOptions } from "./helpers/timeouts"; import { - createDirectCommandRouter, createDirectSetupInferenceHarnessFactory, runProductionSetupInferenceCredentialBoundary, withProcessEnv, @@ -66,16 +64,6 @@ function parseStdoutJson(stdout: string): T { return JSON.parse(line); } -function stripMessagingEnv(source: NodeJS.ProcessEnv): Record { - const env = { ...source } as Record; - for (const key of Object.keys(env)) { - if (key.startsWith("DISCORD_") || key.startsWith("TELEGRAM_")) { - delete env[key]; - } - } - return env; -} - type OnboardTestInternalsCandidate = Partial | null; function isOnboardTestInternals( @@ -106,16 +94,9 @@ const { SANDBOX_BASE_IMAGE, } = onboardTestInternals; -const bedrockRuntimeOnboard = - require("../src/lib/onboard/bedrock-runtime") as typeof import("../src/lib/onboard/bedrock-runtime.js"); const createDirectSetupInferenceHarness = createDirectSetupInferenceHarnessFactory(createSetupInference); -const repoRoot = path.join(import.meta.dirname, ".."); -const onboardScriptMocksPath = JSON.stringify( - path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), -); - describe("onboard helpers", () => { it("adds host proxy variables to sandbox startup env args", () => { const envArgs = ["CHAT_UI_URL=http://127.0.0.1:18789"]; @@ -735,3046 +716,6 @@ startGateway(null).catch(() => {}); assert.equal(evidence.parentCredentialUnchanged, true); }); - it("reuses a registered Hermes Provider without re-collecting host credentials", async () => { - await withProcessEnv( - { - NOUS_API_KEY: "nous-host-secret", - OPENAI_API_KEY: "openai-host-secret", - }, - async () => { - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: "Provider: hermes-provider", stderr: "" } - : undefined, - overrides: { isNonInteractive: () => true }, - }); - - await harness.setupInference( - "test-box", - "moonshotai/kimi-k2.6", - "hermes-provider", - "https://8.8.8.8/v1", - "OPENAI_API_KEY", - "oauth", - ); - - const commands = harness.commands; - assert.equal(commands.length, 3); - assert.equal(commands[0].command, "provider list -g nemoclaw"); - assert.equal(commands[1].command, "provider get -g nemoclaw hermes-provider"); - assert.match( - commands[2].command, - /inference set -g nemoclaw --no-verify --provider hermes-provider/, - ); - assert.ok(!commands.some((entry) => entry.command.startsWith("gateway select"))); - assert.ok(!commands.some((entry) => /provider (create|update)/.test(entry.command))); - assert.ok(!commands.some((entry) => entry.env?.NOUS_API_KEY || entry.env?.OPENAI_API_KEY)); - assert.ok( - !commands.some((entry) => /nous-host-secret|openai-host-secret/.test(entry.command)), - "host credential values must not appear in argv", - ); - }, - ); - }); - it("routes Bedrock Runtime custom Anthropic endpoints through the hidden OpenAI adapter", async () => { - await withProcessEnv({ COMPATIBLE_ANTHROPIC_API_KEY: "bedrock-bearer" }, async () => { - const updateSandbox = vi.fn(() => true); - const ensureAdapter = vi.fn(async () => ({ - baseUrl: "http://host.openshell.internal:11436/v1", - localBaseUrl: "http://127.0.0.1:11436/v1", - credentialEnv: "NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN", - token: "adapter-token", - region: "us-east-1", - logPath: "/tmp/bedrock-adapter.log", - })); - const setupBedrockRuntimeInference = bedrockRuntimeOnboard.setupBedrockRuntimeInference; - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.join(" ") === "provider get -g nemoclaw compatible-anthropic-endpoint" - ? { status: 1, stdout: "", stderr: "" } - : undefined, - overrides: { - updateSandbox, - bedrockRuntimeOnboard: { - setupBedrockRuntimeInference: ( - input: Parameters[0], - ) => setupBedrockRuntimeInference({ ...input, ensureAdapter }), - }, - }, - }); - const consoleOutput: string[] = []; - const captureConsole = (...args: unknown[]) => consoleOutput.push(args.map(String).join(" ")); - const error = vi.spyOn(console, "error").mockImplementation(captureConsole); - const log = vi.spyOn(console, "log").mockImplementation(captureConsole); - try { - await harness.setupInference( - "test-box", - "anthropic.claude-3-5-sonnet-20240620-v1:0", - "compatible-anthropic-endpoint", - "https://bedrock-runtime.us-east-1.amazonaws.com", - "COMPATIBLE_ANTHROPIC_API_KEY", - ); - } finally { - error.mockRestore(); - log.mockRestore(); - } - - const commands = harness.commands; - const providerCommand = commands.find((entry) => /provider create/.test(entry.command)); - assert.ok(providerCommand, "expected hidden adapter provider registration"); - assert.match(providerCommand.command, /--name compatible-anthropic-endpoint/); - assert.match(providerCommand.command, /--type openai/); - assert.match(providerCommand.command, /--credential NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN/); - assert.match( - providerCommand.command, - /OPENAI_BASE_URL=http:\/\/host\.openshell\.internal:11436\/v1/, - ); - assert.equal(providerCommand.env?.NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN, "adapter-token"); - assert.ok( - !JSON.stringify(commands).includes("bedrock-bearer"), - "Bedrock bearer token must not appear in OpenShell argv or env", - ); - assert.deepEqual(harness.errors, []); - assert.deepEqual(harness.logs, [ - " Bedrock Runtime adapter ready: region us-east-1, sandbox route http://host.openshell.internal:11436/v1, host log /tmp/bedrock-adapter.log", - " ✓ Inference route set: compatible-anthropic-endpoint / anthropic.claude-3-5-sonnet-20240620-v1:0", - ]); - assert.doesNotMatch( - [...harness.logs, ...harness.errors, ...consoleOutput].join("\n"), - /bedrock-bearer|adapter-token/, - "Bedrock tokens must not appear in onboarding console output", - ); - const sandboxCommands = commands.filter((entry) => /\bsandbox\b/.test(entry.command)); - assert.ok( - !sandboxCommands.some((entry) => - JSON.stringify(entry).includes("NEMOCLAW_BEDROCK_RUNTIME_ADAPTER_TOKEN"), - ), - "adapter credential env must not be passed to sandbox commands", - ); - assert.ok( - !sandboxCommands.some((entry) => JSON.stringify(entry).includes("adapter-token")), - "adapter token must not be passed to sandbox commands", - ); - assert.match( - commands.at(-1)?.command || "", - /inference set -g nemoclaw --no-verify --provider compatible-anthropic-endpoint --model anthropic\.claude-3-5-sonnet-20240620-v1:0/, - ); - // biome-ignore format: keep the complete route reservation assertion within this legacy file's enforced budget. - expect(updateSandbox).toHaveBeenCalledWith("test-box", { model: "anthropic.claude-3-5-sonnet-20240620-v1:0", provider: "compatible-anthropic-endpoint", endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", preferredInferenceApi: null, gatewayName: "nemoclaw" }); - }); - }); - it("resolves a sandbox name before reconciling Hermes Provider on resume", { - timeout: 60_000, - }, () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-hermes-resume-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "hermes-resume-sandbox-name-check.js"); - const openshellPath = JSON.stringify(path.join(fakeBin, "openshell")); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const sessionPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), - ); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - const nimPath = JSON.stringify(path.join(repoRoot, "src", "lib", "inference", "nim.ts")); - const gatewayStatePath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "gateway.ts"), - ); - const dockerDriverPlatformPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "docker-driver-platform.ts"), - ); - const gatewayGpuPassthroughPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "gateway-gpu-passthrough.ts"), - ); - const onboardProbesPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "inference", "onboard-probes.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const registry = require(${registryPath}); -const onboardSession = require(${sessionPath}); -const credentials = require(${credentialsPath}); -const nim = require(${nimPath}); -const gatewayState = require(${gatewayStatePath}); -const dockerDriverPlatform = require(${dockerDriverPlatformPath}); -const gatewayGpuPassthrough = require(${gatewayGpuPassthroughPath}); -const onboardProbes = require(${onboardProbesPath}); - -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const commands = []; -const prompts = []; -const registryUpdates = []; -const done = new Error("INFERENCE_STEP_DONE"); -let inferenceSessionSnapshot = null; - -delete process.env.NEMOCLAW_NON_INTERACTIVE; -delete process.env.NEMOCLAW_SANDBOX_NAME; -delete process.env.NOUS_API_KEY; -for (const key of Object.keys(process.env)) { - if (key.startsWith("DISCORD_") || key.startsWith("TELEGRAM_")) { - delete process.env[key]; - } -} -process.env.NEMOCLAW_OPENSHELL_BIN = ${openshellPath}; -process.env.OPENSHELL_GATEWAY = "nemoclaw"; - -try { - Object.defineProperty(process.stdin, "isTTY", { value: true, configurable: true }); - Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true }); -} catch { - process.stdin.isTTY = true; - process.stdout.isTTY = true; -} - -runner.run = (command, opts = {}) => { - const normalized = _n(command); - commands.push({ command: normalized, env: opts.env || null }); - return { status: 0, stdout: "", stderr: "" }; -}; -runner.runCapture = (command) => { - const normalized = _n(command); - if (normalized.includes("inference get")) { - return [ - "Gateway inference:", - "", - " Route: inference.local", - " Provider: hermes-provider", - " Model: moonshotai/kimi-k2.6", - " Version: 1", - ].join("\n"); - } - return ""; -}; - -registry.getSandbox = (name) => - name === "hermes-resume" - ? { - name, - gpuEnabled: false, - provider: "hermes-provider", - model: "moonshotai/kimi-k2.6", - hermesToolGateways: [], - policies: ["nous-web"], - } - : null; -registry.reserveSandboxInferenceRoute = (name, updates) => { - registryUpdates.push({ name, updates }); - return true; -}; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -credentials.prompt = async (question) => { - prompts.push(String(question)); - if (String(question).includes("Sandbox name")) return "hermes-resume"; - return "yes"; -}; - -nim.detectGpu = () => null; -gatewayState.getGatewayReuseState = () => "healthy"; -gatewayState.shouldSelectNamedGatewayForReuse = () => false; -gatewayState.getSandboxStateFromOutputs = () => "ready"; -gatewayState.isGatewayHealthy = () => true; -dockerDriverPlatform.isLinuxDockerDriverGatewayEnabled = () => false; -gatewayGpuPassthrough.reconcileGatewayGpuReuseForGpuIntent = ({ gatewayReuseState }) => gatewayReuseState; -onboardProbes.verifyOnboardInferenceSmoke = () => {}; - -const complete = () => ({ - status: "complete", - startedAt: new Date().toISOString(), - completedAt: new Date().toISOString(), - error: null, -}); -onboardSession.saveSession( - onboardSession.createSession({ - mode: "interactive", - agent: "hermes", - sandboxName: null, - provider: "hermes-provider", - model: "moonshotai/kimi-k2.6", - endpointUrl: "https://8.8.8.8/v1", - credentialEnv: "NOUS_API_KEY", - hermesAuthMethod: "api_key", - hermesToolGateways: [], - policyPresets: ["nous-web"], - metadata: { gatewayName: "nemoclaw", fromDockerfile: null }, - steps: { - preflight: complete(), - gateway: complete(), - provider_selection: complete(), - }, - }), -); - -const originalMarkStepComplete = onboardSession.markStepComplete; -onboardSession.markStepComplete = (stepName, updates = {}) => { - const result = originalMarkStepComplete(stepName, updates); - if (stepName === "inference") { - inferenceSessionSnapshot = result; - throw done; - } - return result; -}; - -const { onboard } = require(${onboardPath}); - -(async () => { - try { - await onboard({ resume: true, agent: "hermes", acceptThirdPartySoftware: true, noGpu: true }); - throw new Error("Expected onboarding to reach the inference step"); - } catch (error) { - if (error === done || error?.message === done.message) { - console.log(JSON.stringify({ - commands, - prompts, - registryUpdates, - inferenceSessionSandboxName: inferenceSessionSnapshot?.sandboxName ?? null, - })); - return; - } - console.error(error); - process.exit(1); - } -})(); -`; - fs.writeFileSync(scriptPath, script); - - const env: Record = { - ...stripMessagingEnv(process.env), - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_OPENSHELL_BIN: path.join(fakeBin, "openshell"), - }; - delete env.NEMOCLAW_NON_INTERACTIVE; - delete env.NEMOCLAW_SANDBOX_NAME; - delete env.NOUS_API_KEY; - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env, - }); - - assert.equal(result.status, 0, result.stderr); - assert.doesNotMatch( - `${result.stderr}\n${result.stdout}`, - /Hermes Provider requires a sandbox name/, - ); - const payload = parseStdoutJson<{ - commands: CommandEntry[]; - prompts: string[]; - registryUpdates: Array<{ name: string; updates: Record }>; - inferenceSessionSandboxName: string | null; - }>(result.stdout); - - assert.ok( - payload.prompts.some((question) => question.includes("Sandbox name")), - "resume should prompt for the missing sandbox name before Hermes inference reconciliation", - ); - assert.ok( - payload.commands.some((entry) => - /inference set -g nemoclaw --no-verify --provider hermes-provider/.test(entry.command), - ), - "resume should reach openshell inference set", - ); - assert.ok(!payload.commands.some((entry) => /provider (create|update)/.test(entry.command))); - assert.equal( - payload.inferenceSessionSandboxName, - null, - "resume inference must not persist sandboxName before sandbox creation", - ); - assert.ok( - payload.registryUpdates.some( - (call) => - call.name === "hermes-resume" && - call.updates.provider === "hermes-provider" && - call.updates.model === "moonshotai/kimi-k2.6", - ), - "Hermes setup should reconcile inference against the resolved sandbox name", - ); - }); - - it("reconciles a registered Hermes Provider when a fresh shell Nous key is selected", async () => { - await withProcessEnv( - { - NOUS_API_KEY: "nous-host-secret", - OPENAI_API_KEY: undefined, - }, - async () => { - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: "Provider: hermes-provider", stderr: "" } - : undefined, - overrides: { isNonInteractive: () => true }, - }); - - await harness.setupInference( - "test-box", - "moonshotai/kimi-k2.6", - "hermes-provider", - "https://8.8.8.8/v1", - "NOUS_API_KEY", - "api_key", - ); - - const update = harness.commands.find((entry) => - /provider update -g nemoclaw hermes-provider/.test(entry.command), - ); - assert.ok(update); - assert.match(update.command, /--credential NOUS_API_KEY/); - assert.equal(update.env?.NOUS_API_KEY, "nous-host-secret"); - assert.ok( - !harness.commands.some((entry) => /nous-host-secret/.test(entry.command)), - "shell credential value must not appear in argv", - ); - assert.match( - harness.commands.at(-1)?.command || "", - /inference set -g nemoclaw --no-verify --provider hermes-provider/, - ); - }, - ); - }); - it("does not delete saved OpenAI credentials when configuring local vLLM", async () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-local-vllm-")); - const credentials = require("../src/lib/credentials/store") as { - saveCredential(key: string, value: string): void; - getCredential(key: string): string | null; - }; - try { - await withProcessEnv({ HOME: tmpDir, OPENAI_API_KEY: undefined }, async () => { - credentials.saveCredential("OPENAI_API_KEY", "sk-existing"); - let harness: ReturnType; - const applyLocalInferenceRoute = createLocalInferenceRouteApplier({ - runOpenshell: (args, options) => harness.runOpenshell(args, options), - isNonInteractive: () => false, - promptValidationRecovery: async () => "selection", - classifyApplyFailure: () => ({}) as never, - compactText: (value) => value.trim(), - redact: (value) => value, - localInferenceTimeoutSecs: 120, - error: vi.fn(), - exitProcess: () => assert.fail("unexpected exit"), - }); - harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 1, stdout: "", stderr: "" } - : undefined, - overrides: { applyLocalInferenceRoute }, - }); - await harness.setupInference("test-box", "meta-llama", "vllm-local"); - const providerCommand = harness.commands.find((entry) => - entry.command.includes("provider create"), - ); - assert.ok(providerCommand, "expected local vLLM provider create command"); - assert.match(providerCommand.command, /--credential NEMOCLAW_VLLM_LOCAL_TOKEN/); - assert.doesNotMatch(providerCommand.command, /--credential OPENAI_API_KEY/); - assert.equal(providerCommand.env?.NEMOCLAW_VLLM_LOCAL_TOKEN, "dummy"); - assert.equal(credentials.getCredential("OPENAI_API_KEY"), "sk-existing"); - }); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - it("recovers the Ollama auth proxy on WSL when the sandbox needs proxy fronting", async () => { - const proxyCalls: string[] = []; - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 1, stdout: "", stderr: "" } - : undefined, - overrides: { - validateLocalProvider: () => ({ - ok: false, - message: "container cannot reach Ollama", - diagnostic: "simulated WSL native Docker reachability failure", - }), - shouldFrontOllamaWithProxy: () => true, - ensureOllamaAuthProxy: () => proxyCalls.push("ensure"), - isProxyHealthy: () => { - proxyCalls.push("healthy"); - return true; - }, - getOllamaProxyToken: () => "proxy-token", - persistAndProbeOllamaProxy: async (token: string) => { - proxyCalls.push(`persist:${token}`); - }, - applyLocalInferenceRoute: undefined, - }, - }); - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - try { - await harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"); - } finally { - warn.mockRestore(); - } - assert.deepEqual(proxyCalls, ["ensure", "healthy", "persist:proxy-token"]); - const providerCommand = harness.commands.find( - (entry) => - entry.command.includes("provider create") && entry.command.includes("ollama-local"), - ); - assert.ok(providerCommand, "expected ollama-local provider create command"); - assert.match(providerCommand.command, /--credential NEMOCLAW_OLLAMA_PROXY_TOKEN/); - assert.equal(providerCommand.env?.NEMOCLAW_OLLAMA_PROXY_TOKEN, "proxy-token"); - assert.doesNotMatch(providerCommand.command, /proxy-token/); - assert.ok( - harness.commands.some((entry) => - entry.command.includes("inference set -g nemoclaw --no-verify --provider ollama-local"), - ), - "expected ollama-local inference route to be selected", - ); - }); - it("surfaces a contextual error and exits when ollama-local inference set fails after the proxy-ready warning (#4257)", async () => { - const error = vi.fn(); - const exitProcess = vi.fn((code: number): never => { - throw Object.assign(new Error(`EXIT_CALLED:${code}`), { __exit: true }); - }); - const commandRouter = createDirectCommandRouter([ - { - name: "provider-get", - matches: (command) => command.startsWith("provider get"), - results: [{ status: 1, stdout: "", stderr: "" }], - }, - { - name: "ollama-inference-set", - matches: (command) => command.includes("inference set") && command.includes("ollama-local"), - results: [{ status: 7, stdout: "", stderr: "openshell: route apply failed" }], - }, - ]); - const harness = createDirectSetupInferenceHarness({ - runOpenshell: commandRouter.runOpenshell, - overrides: { - isNonInteractive: () => true, - validateLocalProvider: () => ({ - ok: false, - message: "container cannot reach Ollama", - diagnostic: "simulated WSL native Docker reachability failure", - }), - shouldFrontOllamaWithProxy: () => true, - ensureOllamaAuthProxy: () => {}, - isProxyHealthy: () => true, - getOllamaProxyToken: () => "proxy-token", - persistAndProbeOllamaProxy: async () => {}, - applyLocalInferenceRoute: undefined, - error, - exitProcess, - }, - }); - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - try { - await assert.rejects( - harness.setupInference("test-box", "qwen3.5:9b", "ollama-local"), - (error: Error & { __exit?: boolean }) => error.__exit === true, - ); - } finally { - warn.mockRestore(); - } - const setCmd = harness.commands.find((entry) => - entry.command.includes("inference set -g nemoclaw --no-verify --provider ollama-local"), - ); - assert.ok(setCmd, "expected ollama-local inference set command to be issued"); - assert.equal( - setCmd.ignoreError, - true, - "ollama-local inference set must use ignoreError so onboard can recover", - ); - const combinedErr = error.mock.calls.flat().join("\n"); - assert.equal(exitProcess.mock.calls.length, 1); - assert.equal(exitProcess.mock.calls[0]?.[0], 7); - assert.match(combinedErr, /No sandbox was created/); - assert.match(combinedErr, /nemoclaw onboard --resume/); - }); - it("surfaces a contextual error and exits when vllm-local inference set fails (#4257)", async () => { - const exitProcess = vi.fn((code: number): never => { - throw Object.assign(new Error(`EXIT_CALLED:${code}`), { __exit: true }); - }); - const commandRouter = createDirectCommandRouter([ - { - name: "provider-get", - matches: (command) => command.startsWith("provider get"), - results: [{ status: 1, stdout: "", stderr: "" }], - }, - { - name: "vllm-inference-set", - matches: (command) => command.includes("inference set") && command.includes("vllm-local"), - results: [{ status: 13, stdout: "", stderr: "openshell: vllm route apply failed" }], - }, - ]); - const harness = createDirectSetupInferenceHarness({ - runOpenshell: commandRouter.runOpenshell, - overrides: { - isNonInteractive: () => true, - applyLocalInferenceRoute: undefined, - exitProcess, - }, - }); - - await assert.rejects( - harness.setupInference("test-box", "meta-llama", "vllm-local"), - (error: Error & { __exit?: boolean }) => error.__exit === true, - ); - - const setCmd = harness.commands.find((entry) => - entry.command.includes("inference set -g nemoclaw --no-verify --provider vllm-local"), - ); - assert.ok(setCmd, "expected vllm-local inference set command to be issued"); - assert.equal( - setCmd.ignoreError, - true, - "vllm-local inference set must use ignoreError so onboard can recover", - ); - const combinedErr = harness.errors.join("\n"); - assert.equal(exitProcess.mock.calls.length, 1); - assert.equal(exitProcess.mock.calls[0]?.[0], 13); - assert.match(combinedErr, /No sandbox was created/); - assert.match(combinedErr, /nemoclaw onboard --resume/); - }); - it("detects when the live inference route already matches the requested provider and model", () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-inference-ready-")); - const fakeOpenshell = path.join(tmpDir, "openshell"); - const scriptPath = path.join(tmpDir, "inference-ready-check.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - - fs.writeFileSync( - fakeOpenshell, - `#!/usr/bin/env bash -if [ "$1" = "inference" ] && [ "$2" = "get" ] && [ "$3" = "-g" ] && [ "$4" = "team-gateway" ]; then - cat <<'EOF' -Gateway inference: - - Route: inference.local - Provider: nvidia-prod - Model: nvidia/nemotron-3-super-120b-a12b - Version: 1 -EOF - exit 0 -fi -exit 1 -`, - { mode: 0o755 }, - ); - - fs.writeFileSync( - scriptPath, - ` -const { isInferenceRouteReady } = require(${onboardPath}); -console.log(JSON.stringify({ - same: isInferenceRouteReady("team-gateway", "nvidia-prod", "nvidia/nemotron-3-super-120b-a12b"), - otherModel: isInferenceRouteReady("team-gateway", "nvidia-prod", "nvidia/other-model"), - otherProvider: isInferenceRouteReady("team-gateway", "openai-api", "nvidia/nemotron-3-super-120b-a12b"), -})); -`, - ); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - PATH: `${tmpDir}:${process.env.PATH || ""}`, - }, - }); - - try { - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout.trim())).toEqual({ - same: true, - otherModel: false, - otherProvider: false, - }); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("detects when OpenClaw is already configured inside the sandbox", () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-ready-")); - const fakeOpenshell = path.join(tmpDir, "openshell"); - const scriptPath = path.join(tmpDir, "openclaw-ready-check.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - - fs.writeFileSync( - fakeOpenshell, - `#!/usr/bin/env bash -if [ "$1" = "sandbox" ] && [ "$2" = "download" ]; then - dest="\${@: -1}" - mkdir -p "$dest/sandbox/.openclaw" - cat > "$dest/sandbox/.openclaw/openclaw.json" <<'EOF' -{"gateway":{"auth":{"token":"test-token"}}} -EOF - exit 0 -fi -exit 1 -`, - { mode: 0o755 }, - ); - - fs.writeFileSync( - scriptPath, - ` -const { isOpenclawReady } = require(${onboardPath}); -console.log(JSON.stringify({ - ready: isOpenclawReady("my-assistant"), -})); -`, - ); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - PATH: `${tmpDir}:${process.env.PATH || ""}`, - }, - }); - - try { - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout.trim())).toEqual({ ready: true }); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("detects when recorded policy presets are already applied", () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-ready-")); - const registryDir = path.join(tmpDir, ".nemoclaw"); - const registryFile = path.join(registryDir, "sandboxes.json"); - const scriptPath = path.join(tmpDir, "policy-ready-check.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - - fs.mkdirSync(registryDir, { recursive: true }); - fs.writeFileSync( - registryFile, - JSON.stringify( - { - sandboxes: { - "my-assistant": { - name: "my-assistant", - policies: ["pypi", "npm"], - }, - }, - defaultSandbox: "my-assistant", - }, - null, - 2, - ), - ); - - fs.writeFileSync( - scriptPath, - ` -const { arePolicyPresetsApplied } = require(${onboardPath}); -console.log(JSON.stringify({ - ready: arePolicyPresetsApplied("my-assistant", ["pypi", "npm"]), - missing: arePolicyPresetsApplied("my-assistant", ["pypi", "slack"]), - empty: arePolicyPresetsApplied("my-assistant", []), -})); -`, - ); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - }, - }); - - try { - expect(result.status).toBe(0); - const payload = JSON.parse(result.stdout.trim()); - expect(payload).toEqual({ - ready: true, - missing: false, - empty: false, - }); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - - it("uses native Anthropic provider creation without embedding the secret in argv", async () => { - await withProcessEnv({ ANTHROPIC_API_KEY: "sk-ant-TEST-NOT-A-REAL-VALUE" }, async () => { - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 1, stdout: "", stderr: "" } - : undefined, - }); - - await harness.setupInference( - "test-box", - "claude-sonnet-4-5", - "anthropic-prod", - "https://api.anthropic.com", - "ANTHROPIC_API_KEY", - ); - - const commands = harness.commands; - assert.equal(commands.length, 3); - assert.match(commands[0].command, /^provider get -g nemoclaw /); - assert.match(commands[1].command, /^provider create -g nemoclaw /); - assert.match(commands[1].command, /--type anthropic/); - assert.match(commands[1].command, /--credential ANTHROPIC_API_KEY/); - assert.doesNotMatch(commands[1].command, /sk-ant-TEST-NOT-A-REAL-VALUE/); - assert.match(commands[2].command, /^inference set -g nemoclaw /); - assert.match(commands[2].command, /--provider anthropic-prod/); - }); - }); - it("updates OpenAI-compatible providers without passing an unsupported --type flag", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: "", stderr: "" } - : undefined, - }); - - await harness.setupInference( - "test-box", - "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", - ); - - const commands = harness.commands; - assert.equal(commands.length, 3); - assert.match(commands[0].command, /^provider get -g nemoclaw /); - assert.match(commands[1].command, /^provider update -g nemoclaw openai-api/); - assert.doesNotMatch(commands[1].command, /--type/); - assert.match(commands[2].command, /^inference set -g nemoclaw --no-verify/); - }); - }); - it("re-prompts for credentials when openshell inference set fails with authorization errors", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-bad" }, async () => { - const commandRouter = createDirectCommandRouter([ - { - name: "provider-get", - matches: (command) => command.startsWith("provider get"), - results: [{ status: 0, stdout: "", stderr: "" }], - }, - { - name: "inference-set", - matches: (command) => command.includes("inference set"), - results: [{ status: 1, stdout: "", stderr: "HTTP 403: forbidden" }, undefined], - }, - ]); - const harness = createDirectSetupInferenceHarness({ - runOpenshell: commandRouter.runOpenshell, - overrides: { - promptValidationRecovery: async () => { - process.env.OPENAI_API_KEY = "sk-good"; - return "retry"; - }, - }, - }); - const error = vi.spyOn(console, "error").mockImplementation(() => {}); - try { - await harness.setupInference( - "test-box", - "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", - ); - } finally { - error.mockRestore(); - } - - assert.equal(process.env.OPENAI_API_KEY, "sk-good"); - assert.equal(commandRouter.callCount("inference-set"), 2); - const providerEnvs = harness.commands - .filter((entry) => entry.command.includes("provider")) - .map((entry) => entry.env?.OPENAI_API_KEY) - .filter(Boolean); - assert.deepEqual(providerEnvs, ["sk-bad", "sk-good"]); - }); - }); - it("returns control to provider selection when inference apply recovery chooses back", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { - const commandRouter = createDirectCommandRouter([ - { - name: "provider-get", - matches: (command) => command.startsWith("provider get"), - results: [{ status: 0, stdout: "", stderr: "" }], - }, - { - name: "inference-set", - matches: (command) => command.includes("inference set"), - results: [{ status: 1, stdout: "", stderr: "HTTP 404: model not found" }], - }, - ]); - const harness = createDirectSetupInferenceHarness({ - runOpenshell: commandRouter.runOpenshell, - overrides: { promptValidationRecovery: async () => "selection" }, - }); - const error = vi.spyOn(console, "error").mockImplementation(() => {}); - let result: Awaited>; - try { - result = await harness.setupInference( - "test-box", - "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", - ); - } finally { - error.mockRestore(); - } - - assert.deepEqual(result, { retry: "selection" }); - assert.equal( - harness.commands.filter((entry) => entry.command.includes("inference set")).length, - 1, - ); - }); - }); - it("migrates a legacy credentials.json into env so setupInference can register the provider", async () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-resume-cred-")); - const legacyDir = path.join(tmpDir, ".nemoclaw"); - const legacyFile = path.join(legacyDir, "credentials.json"); - fs.mkdirSync(legacyDir, { recursive: true, mode: 0o700 }); - fs.writeFileSync( - legacyFile, - JSON.stringify({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-STORED-KEY" }), - { mode: 0o600 }, - ); - const credentialEnv = - require("../src/lib/onboard/credential-env") as typeof import("../src/lib/onboard/credential-env.js"); - try { - await withProcessEnv({ HOME: tmpDir, OPENAI_API_KEY: undefined }, async () => { - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: "", stderr: "" } - : undefined, - overrides: { hydrateCredentialEnv: credentialEnv.hydrateCredentialEnv }, - }); - - await harness.setupInference( - "test-box", - "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", - ); - - assert.equal(process.env.OPENAI_API_KEY, "sk-TEST-NOT-A-REAL-STORED-KEY"); - assert.equal( - fs.existsSync(legacyFile), - true, - "legacy credentials.json must survive the staging-only hydrate path", - ); - const providerUpdate = harness.commands.find((entry) => - entry.command.includes("provider update -g nemoclaw openai-api"), - ); - assert.ok(providerUpdate, "expected provider update command"); - assert.equal(providerUpdate.env?.OPENAI_API_KEY, "sk-TEST-NOT-A-REAL-STORED-KEY"); - assert.doesNotMatch(providerUpdate.command, /sk-TEST-NOT-A-REAL-STORED-KEY/); - }); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - }); - it("drops stale local sandbox registry entries when the live sandbox is gone", () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-stale-sandbox-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "stale-sandbox-check.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const registry = require(${registryPath}); -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -runner.runCapture = (command) => (_n(command).includes("sandbox get my-assistant") ? "" : ""); - -registry.registerSandbox({ name: "my-assistant" }); - -const { pruneStaleSandboxEntry } = require(${onboardPath}); - -const liveExists = pruneStaleSandboxEntry("my-assistant"); -console.log(JSON.stringify({ liveExists, sandbox: registry.getSandbox("my-assistant") })); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - assert.equal(payload.liveExists, false); - assert.equal(payload.sandbox, null); - }); - - it("builds the sandbox without uploading an external OpenClaw config file", { - timeout: 90_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-create-sandbox-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "create-sandbox-check.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const preflightPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), - ); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const preflight = require(${preflightPath}); -const credentials = require(${credentialsPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const commands = []; -const registerCalls = []; -const updateCalls = []; -const defaultCalls = []; -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return ""; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); - if (mockedCapture !== null) return mockedCapture; - } - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - return ""; -}; -registry.registerSandbox = (entry) => { - registerCalls.push(entry); - return true; -}; -registry.updateSandbox = (name, updates) => { - updateCalls.push({ name, updates }); - return true; -}; -registry.setDefault = (name) => { - defaultCalls.push(name); - return true; -}; -registry.removeSandbox = () => true; -preflight.checkPortAvailable = async () => ({ ok: true }); -credentials.prompt = async () => ""; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - const sandboxName = await createSandbox(null, "gpt-5.4"); - console.log(JSON.stringify({ sandboxName, commands, registerCalls, updateCalls, defaultCalls })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - assert.equal(payload.sandboxName, "my-assistant"); - // createSandbox no longer marks the sandbox default — that is deferred to the - // finalization step so a cancel at policy presets can't leave an unconfigured - // sandbox as default (#4614). - assert.deepEqual(payload.defaultCalls, []); - assert.ok( - payload.registerCalls.some( - (entry: Record) => - entry.name === "my-assistant" && - entry.model === "gpt-5.4" && - Object.prototype.hasOwnProperty.call(entry, "agentVersion"), - ), - "expected registry metadata for created sandbox", - ); - assert.ok( - payload.updateCalls.every( - (call: { name: string; updates: Record }) => - call.name === "my-assistant" && call.updates, - ), - "expected any registry metadata updates to target the created sandbox", - ); - const createCommand = payload.commands.find((entry: CommandEntry) => - entry.command.includes("sandbox create"), - ); - assert.ok(createCommand, "expected sandbox create command"); - assert.match(createCommand.command, /nemoclaw-start/); - assert.doesNotMatch(createCommand.command, /--upload/); - assert.doesNotMatch(createCommand.command, /OPENCLAW_CONFIG_PATH/); - assert.doesNotMatch(createCommand.command, /NVIDIA_INFERENCE_API_KEY=/); - assert.doesNotMatch(createCommand.command, /DISCORD_BOT_TOKEN=/); - assert.doesNotMatch(createCommand.command, /SLACK_BOT_TOKEN=/); - assert.ok( - payload.commands.some( - (entry: CommandEntry) => - entry.command.includes("forward start --background 18789 my-assistant") || - entry.command.includes("forward start --background 0.0.0.0:18789 my-assistant"), - ), - "expected dashboard forward (loopback or WSL 0.0.0.0)", - ); - }); - - it("skips OpenClaw sandbox-base resolution for agent-staged Dockerfiles", async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-agent-base-skip-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "agent-base-skip.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const preflightPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), - ); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - const agentOnboardPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "agent", "onboard.ts"), - ); - const sandboxBaseImagePath = JSON.stringify( - path.join(repoRoot, "src", "lib", "sandbox-base-image.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const preflight = require(${preflightPath}); -const credentials = require(${credentialsPath}); -const agentOnboard = require(${agentOnboardPath}); -const sandboxBaseImage = require(${sandboxBaseImagePath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); -require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "docker-driver-platform.ts"))}).isLinuxDockerDriverGatewayEnabled = () => false; -const commands = []; -const logs = []; -const warnings = []; -const baseResolutionCalls = []; -const originalLog = console.log; -const originalWarn = console.warn; -console.log = (...args) => { - logs.push(args.join(" ")); - originalLog(...args); -}; -console.warn = (...args) => { - warnings.push(args.join(" ")); - originalWarn(...args); -}; - -sandboxBaseImage.resolveSandboxBaseImage = (options) => { - baseResolutionCalls.push(options); - return { - ref: "ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - digest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - source: "latest", - glibcVersion: "2.39", - }; -}; - -agentOnboard.createAgentSandbox = () => { - const buildCtx = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-agent-build-")); - const stagedDockerfile = path.join(buildCtx, "Dockerfile"); - fs.writeFileSync( - stagedDockerfile, - [ - "ARG BASE_IMAGE=nemoclaw-hermes-sandbox-base-local:test", - "FROM \${BASE_IMAGE}", - "ARG NEMOCLAW_MODEL=nvidia/nemotron-3-super-120b-a12b", - "ARG NEMOCLAW_PROVIDER_KEY=custom", - "ARG NEMOCLAW_PRIMARY_MODEL_REF=nvidia/nemotron-3-super-120b-a12b", - "ARG CHAT_UI_URL=http://127.0.0.1:18789", - "ARG NEMOCLAW_INFERENCE_BASE_URL=https://inference.local/v1", - "ARG NEMOCLAW_INFERENCE_API=openai-completions", - "ARG NEMOCLAW_INFERENCE_COMPAT_B64=e30=", - "ARG NEMOCLAW_MESSAGING_PLAN_B64=", - "ARG NEMOCLAW_HERMES_TOOL_GATEWAY_BROKER=0", - "ARG NEMOCLAW_HERMES_TOOL_GATEWAY_PRESETS_B64=W10=", - "ARG NEMOCLAW_BUILD_ID=default", - "ARG NEMOCLAW_DARWIN_VM_COMPAT=0", - "CMD [\"/bin/bash\"]", - ].join("\\n"), - ); - return { buildCtx, stagedDockerfile }; -}; - -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runFile = (file, args = [], opts = {}) => { - commands.push({ command: _n([file, ...args]), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get hermes-sandbox")) return ""; - if (_n(command).includes("sandbox list")) return "hermes-sandbox Ready"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); - if (mockedCapture !== null) return mockedCapture; - } - if (_n(command).includes("forward list")) return "hermes-sandbox 127.0.0.1 18789 12345 running\nhermes-sandbox 127.0.0.1 8642 12346 running"; - return ""; -}; -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; -registry.getSandbox = () => null; -preflight.checkPortAvailable = async () => ({ ok: true }); -credentials.prompt = async () => ""; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: hermes-sandbox\\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - const agent = { - name: "hermes", - displayName: "Hermes Agent", - forwardPort: 18789, - forward_ports: [18789, 8642], - healthProbe: { url: "http://127.0.0.1:8642/health", port: 8642, timeout_seconds: 90 }, - dashboard: { kind: "ui", label: "Dashboard", path: "/", healthPath: "/api/status", auth: "session" }, - expectedVersion: "2026.4.23", - policyAdditionsPath: null, - }; - await createSandbox( - null, - "gpt-5.4", - "nvidia-prod", - null, - "hermes-sandbox", - null, - [], - null, - agent, - null, - null, - null, - ["nous-web"], - ); - console.log(JSON.stringify({ commands, logs, warnings, baseResolutionCalls })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...stripMessagingEnv(process.env), - HOME: tmpDir, - NEMOCLAW_HOME: path.join(tmpDir, ".nemoclaw"), - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payload = parseStdoutJson<{ - commands: CommandEntry[]; - logs: string[]; - warnings: string[]; - baseResolutionCalls: unknown[]; - }>(result.stdout); - assert.equal(payload.baseResolutionCalls.length, 0); - const createCommand = payload.commands.find((entry) => - entry.command.includes("sandbox create"), - ); - assert.ok(createCommand, "expected sandbox create command"); - assert.match(createCommand.command, /--provider hermes-sandbox-hermes-tool-gateway/); - assert.doesNotMatch(createCommand.command, /TOOL_GATEWAY_USER_TOKEN=/); - assert.doesNotMatch(createCommand.command, /NEMOCLAW_HERMES_TOOL_GATEWAY_REFRESH_TOKEN=/); - assert.ok( - !payload.logs.some((line) => line.includes("Using sandbox base image")), - "Hermes agent Dockerfile path should not log OpenClaw sandbox-base usage", - ); - assert.ok( - !payload.warnings.some((line) => line.includes("base image")), - "Hermes agent Dockerfile path should not warn about OpenClaw sandbox-base availability", - ); - }); - - it("keeps resolving the OpenClaw sandbox base image on the default Dockerfile path", async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-base-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "openclaw-base-resolve.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const preflightPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), - ); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - const buildContextPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "sandbox", "build-context.ts"), - ); - const sandboxBaseImagePath = JSON.stringify( - path.join(repoRoot, "src", "lib", "sandbox-base-image.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const preflight = require(${preflightPath}); -const credentials = require(${credentialsPath}); -const buildContext = require(${buildContextPath}); -const sandboxBaseImage = require(${sandboxBaseImagePath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const commands = []; -const logs = []; -const baseResolutionCalls = []; -const originalLog = console.log; -console.log = (...args) => { - logs.push(args.join(" ")); - originalLog(...args); -}; - -sandboxBaseImage.resolveSandboxBaseImage = (options) => { - baseResolutionCalls.push(options); - return { - ref: "ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - digest: "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - source: "latest", - glibcVersion: "2.39", - }; -}; -buildContext.stageOptimizedSandboxBuildContext = () => { - const buildCtx = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-build-")); - const stagedDockerfile = path.join(buildCtx, "Dockerfile"); - fs.writeFileSync( - stagedDockerfile, - [ - "ARG BASE_IMAGE=ghcr.io/nvidia/nemoclaw/sandbox-base:latest", - "FROM \${BASE_IMAGE}", - "ARG NEMOCLAW_MODEL=nvidia/nemotron-3-super-120b-a12b", - "ARG NEMOCLAW_PROVIDER_KEY=nvidia", - "ARG NEMOCLAW_PRIMARY_MODEL_REF=nvidia/nemotron-3-super-120b-a12b", - "ARG CHAT_UI_URL=http://127.0.0.1:18789", - "ARG NEMOCLAW_INFERENCE_BASE_URL=https://inference.local/v1", - "ARG NEMOCLAW_INFERENCE_API=openai-completions", - "ARG NEMOCLAW_INFERENCE_COMPAT_B64=e30=", - "ARG NEMOCLAW_MESSAGING_PLAN_B64=", - "ARG NEMOCLAW_BUILD_ID=default", - "ARG NEMOCLAW_DARWIN_VM_COMPAT=0", - "CMD [\"/bin/bash\"]", - ].join("\\n"), - ); - return { buildCtx, stagedDockerfile }; -}; - -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runFile = (file, args = [], opts = {}) => { - commands.push({ command: _n([file, ...args]), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return ""; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); - if (mockedCapture !== null) return mockedCapture; - } - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - return ""; -}; -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; -registry.getSandbox = () => null; -preflight.checkPortAvailable = async () => ({ ok: true }); -credentials.prompt = async () => ""; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ commands, logs, baseResolutionCalls })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...stripMessagingEnv(process.env), - HOME: tmpDir, - NEMOCLAW_HOME: path.join(tmpDir, ".nemoclaw"), - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payload = parseStdoutJson<{ - logs: string[]; - baseResolutionCalls: Array<{ imageName?: string }>; - }>(result.stdout); - assert.equal(payload.baseResolutionCalls.length, 1); - assert.equal(payload.baseResolutionCalls[0]?.imageName, "ghcr.io/nvidia/nemoclaw/sandbox-base"); - assert.ok( - payload.logs.some((line) => line.includes("Pinning base image to sha256:bbbbbbbbbbbb")), - "default OpenClaw path should still log base-image pinning", - ); - }); - - it("binds the dashboard forward to 0.0.0.0 when CHAT_UI_URL points to a remote host", async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-remote-forward-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "create-sandbox-remote-forward.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const preflightPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), - ); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const preflight = require(${preflightPath}); -const credentials = require(${credentialsPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const commands = []; -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return ""; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); - if (mockedCapture !== null) return mockedCapture; - } - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - return ""; -}; -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; -preflight.checkPortAvailable = async () => ({ ok: true }); -credentials.prompt = async () => ""; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.CHAT_UI_URL = "https://chat.example.com"; - await createSandbox(null, "gpt-5.4"); - console.log(JSON.stringify(commands)); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const commands = parseStdoutJson(result.stdout); - assert.ok( - commands.some((entry: CommandEntry) => - entry.command.includes("forward start --background 0.0.0.0:18789 my-assistant"), - ), - "expected remote dashboard forward target", - ); - }); - - it("injects NEMOCLAW_DASHBOARD_PORT into sandbox create envArgs when set (#1925)", async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-dashboard-port-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "dashboard-port-envargs.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const preflightPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), - ); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const preflight = require(${preflightPath}); -const credentials = require(${credentialsPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const commands = []; -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runFile = (file, args = [], opts = {}) => { - commands.push({ command: _n([file, ...args]), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return ""; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - // Custom port: dashboard readiness curl uses 19000 (DASHBOARD_PORT from env) - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); - if (mockedCapture !== null) return mockedCapture; - } - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 19000 12345 running"; - return ""; -}; -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; -preflight.checkPortAvailable = async () => ({ ok: true }); -credentials.prompt = async () => ""; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - const sandboxName = await createSandbox(null, "gpt-5.4"); - console.log(JSON.stringify({ sandboxName, commands })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - // Strip CHAT_UI_URL so createSandbox falls back to http://127.0.0.1:19000. - // Without this, a CHAT_UI_URL set in the developer's shell or CI would be - // inherited, causing chatUiUrl to use the wrong port and making the forward - // command assertion below fail spuriously. - const { - CHAT_UI_URL: _stripped, - HTTP_PROXY: _httpProxy, - HTTPS_PROXY: _httpsProxy, - NO_PROXY: _noProxy, - http_proxy: _lowerHttpProxy, - https_proxy: _lowerHttpsProxy, - no_proxy: _lowerNoProxy, - ...inheritedEnv - } = process.env; - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...inheritedEnv, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - NEMOCLAW_DASHBOARD_PORT: "19000", - HTTP_PROXY: "http://127.0.0.1:8888", - HTTPS_PROXY: "http://127.0.0.1:8888", - NO_PROXY: "corp.internal", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - const createCommand = payload.commands.find((entry: CommandEntry) => - entry.command.includes("sandbox create"), - ); - assert.ok(createCommand, "expected sandbox create command"); - // Part 1 of fix (#1925): NEMOCLAW_DASHBOARD_PORT must be in envArgs so - // nemoclaw-start.sh can unconditionally override CHAT_UI_URL at runtime, - // overriding whatever value the Docker image had baked in. - assert.match(createCommand.command, /NEMOCLAW_DASHBOARD_PORT=19000/); - assert.match(createCommand.command, /HTTP_PROXY=http:\/\/127\.0\.0\.1:8888/); - assert.match(createCommand.command, /HTTPS_PROXY=http:\/\/127\.0\.0\.1:8888/); - // OpenClaw home/state/workspace dirs must be pinned in the sandbox env so - // `openclaw skills install` and `openclaw skills list` resolve the same - // paths. Without this, the upstream skill loader can fall back to a - // hardcoded DEFAULT_AGENT_WORKSPACE_DIR that drifts from the install path - // and hides workspace-installed skills from `skills list`. - assert.match(createCommand.command, /OPENCLAW_HOME=\/sandbox(?:\s|$)/); - assert.match(createCommand.command, /OPENCLAW_STATE_DIR=\/sandbox\/\.openclaw(?:\s|$)/); - assert.match( - createCommand.command, - /OPENCLAW_WORKSPACE_DIR=\/sandbox\/\.openclaw\/workspace(?:\s|$)/, - ); - const noProxyMatch = createCommand.command.match(/(?:^|\s)NO_PROXY=([^\s]+)/); - assert.ok( - noProxyMatch, - `expected NO_PROXY in sandbox create command:\n${createCommand.command}`, - ); - const noProxyEntries = noProxyMatch[1].split(","); - assert.ok(noProxyEntries.includes("corp.internal")); - assert.ok(noProxyEntries.includes("localhost")); - assert.ok(noProxyEntries.includes("127.0.0.1")); - assert.ok(noProxyEntries.includes("host.docker.internal")); - // Forward must use same-port mapping (openshell does not support asymmetric) - assert.ok( - payload.commands.some( - (entry: CommandEntry) => - entry.command.includes("forward start --background 19000 my-assistant") || - entry.command.includes("forward start --background 0.0.0.0:19000 my-assistant"), - ), - "expected dashboard forward for port 19000", - ); - assert.ok( - !payload.commands.some((entry: CommandEntry) => entry.command.includes("19000:18789")), - "forward must not use asymmetric 19000:18789 mapping", - ); - assert.ok( - !payload.commands.some((entry: CommandEntry) => entry.command.includes("19000:19000")), - "forward must not use port:port form (openshell does not support it)", - ); - }); - - it("non-interactive exits with error when existing sandbox is not ready", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync( - path.join(os.tmpdir(), "nemoclaw-onboard-noninteractive-notready-"), - ); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "noninteractive-notready.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const childProcess = require("node:child_process"); - -runner.run = (command) => { - if (_n(command).includes("sandbox delete")) { - throw new Error("unexpected sandbox delete"); - } - return { status: 0 }; -}; -runner.runCapture = (command) => { - // Existing sandbox that is NOT ready - if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; - if (_n(command).includes("sandbox list")) return "my-assistant NotReady"; - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); -childProcess.spawn = () => { - throw new Error("unexpected sandbox create"); -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log("ERROR_DID_NOT_EXIT"); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const env: Record = { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }; - delete env["NEMOCLAW_RECREATE_SANDBOX"]; - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env, - }); - - assert.notEqual(result.status, 0, "expected non-zero exit for not-ready sandbox"); - assert.ok( - !result.stdout.includes("ERROR_DID_NOT_EXIT"), - "should have exited before reaching sandbox create", - ); - const output = (result.stdout || "") + (result.stderr || ""); - assert.ok( - output.includes("--recreate-sandbox") || output.includes("NEMOCLAW_RECREATE_SANDBOX"), - "should hint about --recreate-sandbox flag", - ); - }); - - it("recreate-sandbox flag forces deletion and recreation of a ready sandbox", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-flag-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "recreate-flag.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const commands = []; let registeredSandbox = null; -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { - defaultCurlOutput: "ok", - }); - if (mockedCapture !== null) return mockedCapture; - } - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); -registry.registerSandbox = (entry) => { registeredSandbox = entry; return true; }; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); -preflight.checkPortAvailable = async () => ({ ok: true }); - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; - process.env.NEMOCLAW_RECREATE_WITHOUT_BACKUP = "1"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, commands, registeredSandbox })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - NEMOCLAW_POLICY_TIER: "restricted", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - assert.ok( - payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox delete")), - "should delete existing sandbox when --recreate-sandbox is set", - ); - assert.ok( - payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox create")) && - payload.registeredSandbox?.policyTier === "restricted", - "should create a sandbox and persist its tier before policy finalization", - ); - }); - it("recreate-sandbox flag backs up and restores workspace state", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-backup-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "recreate-backup.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const sandboxStatePath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "sandbox.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const sandboxState = require(${sandboxStatePath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const events = []; -runner.run = (command) => { - events.push({ kind: "run", cmd: _n(command) }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - const cmd = _n(command); - if (cmd.includes("sandbox get my-assistant")) return "my-assistant"; - if (cmd.includes("sandbox list")) return "my-assistant Ready"; - if (cmd.includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { - defaultCurlOutput: "ok", - }); - if (mockedCapture !== null) return mockedCapture; - } - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -sandboxState.backupSandboxState = (name) => { - events.push({ kind: "backup", name }); - return { - success: true, - backedUpDirs: ["workspace", "skills"], - failedDirs: [], - backedUpFiles: ["UPGRADE_MARKER.md"], - failedFiles: [], - manifest: { backupPath: "/tmp/fake-backup-path", timestamp: "2026-05-25T00:00:00Z" }, - }; -}; -sandboxState.restoreRecreatedSandboxState = (name, backupPath, options) => { - events.push({ kind: "restore", name, backupPath, options }); - return { - success: true, - restoredDirs: ["workspace", "skills"], - failedDirs: [], - restoredFiles: ["UPGRADE_MARKER.md"], - failedFiles: [], - }; -}; - -const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); -preflight.checkPortAvailable = async () => ({ ok: true }); - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4243; - events.push({ kind: "spawn", cmd: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]) }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, events })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - - const events = payload.events as Array<{ - kind: string; - cmd?: string; - name?: string; - backupPath?: string; - options?: { targetAgentType?: string; freshOpenClawImagePluginInstalls?: unknown[] }; - }>; - const backupIndex = events.findIndex((e) => e.kind === "backup"); - const deleteIndex = events.findIndex( - (e) => e.kind === "run" && (e.cmd || "").includes("sandbox delete"), - ); - const restoreIndex = events.findIndex((e) => e.kind === "restore"); - - assert.ok(backupIndex >= 0, "should call backupSandboxState before delete"); - assert.ok(deleteIndex > backupIndex, "backup must happen before sandbox delete"); - assert.ok(restoreIndex > deleteIndex, "restore must happen after sandbox recreate"); - const backupEvent = events[backupIndex]; - assert.equal(backupEvent?.name, "my-assistant", "backup target must match sandbox name"); - const restoreEvent = events[restoreIndex]; - assert.equal(restoreEvent?.backupPath, "/tmp/fake-backup-path", "restore must use backup path"); - assert.equal(restoreEvent?.options?.targetAgentType, "openclaw"); - assert.equal(restoreEvent?.options?.freshOpenClawImagePluginInstalls, undefined); - }); - - it("recreate-sandbox with NEMOCLAW_RECREATE_WITHOUT_BACKUP=1 skips backup", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-skip-backup-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "recreate-skip-backup.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const sandboxStatePath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "sandbox.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const sandboxState = require(${sandboxStatePath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const events = []; -runner.run = (command) => { - events.push({ kind: "run", cmd: _n(command) }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - const cmd = _n(command); - if (cmd.includes("sandbox get my-assistant")) return "my-assistant"; - if (cmd.includes("sandbox list")) return "my-assistant Ready"; - if (cmd.includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { - defaultCurlOutput: "ok", - }); - if (mockedCapture !== null) return mockedCapture; - } - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -sandboxState.backupSandboxState = () => { - events.push({ kind: "backup" }); - return { success: true, backedUpDirs: [], failedDirs: [], backedUpFiles: [], failedFiles: [] }; -}; -sandboxState.restoreRecreatedSandboxState = () => { - events.push({ kind: "restore" }); - return { success: true, restoredDirs: [], failedDirs: [], restoredFiles: [], failedFiles: [] }; -}; - -const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); -preflight.checkPortAvailable = async () => ({ ok: true }); - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4244; - events.push({ kind: "spawn", cmd: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]) }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; - process.env.NEMOCLAW_RECREATE_WITHOUT_BACKUP = "1"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, events })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - const events = payload.events as Array<{ kind: string }>; - assert.ok( - !events.some((e) => e.kind === "backup"), - "should not call backupSandboxState when NEMOCLAW_RECREATE_WITHOUT_BACKUP=1", - ); - assert.ok( - !events.some((e) => e.kind === "restore"), - "should not call restoreRecreatedSandboxState when no backup occurred", - ); - }); - - it("recreate-sandbox flag backs up and restores when existing sandbox is not ready", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-notready-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "recreate-notready.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const sandboxStatePath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "sandbox.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const sandboxState = require(${sandboxStatePath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const events = []; -let sandboxDeleted = false; -runner.run = (command) => { - const cmd = _n(command); - events.push({ kind: "run", cmd }); - if (cmd.includes("sandbox delete")) sandboxDeleted = true; - return { status: 0 }; -}; -runner.runCapture = (command) => { - const cmd = _n(command); - if (cmd.includes("sandbox get my-assistant")) return "my-assistant"; - if (cmd.includes("sandbox list")) { - return sandboxDeleted ? "my-assistant Ready" : "my-assistant NotReady"; - } - if (cmd.includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { - defaultCurlOutput: "ok", - }); - if (mockedCapture !== null) return mockedCapture; - } - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", gpuEnabled: false }); -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -sandboxState.backupSandboxState = (name) => { - events.push({ kind: "backup", name }); - return { - success: true, - backedUpDirs: ["workspace"], - failedDirs: [], - backedUpFiles: ["UPGRADE_MARKER.md"], - failedFiles: [], - manifest: { backupPath: "/tmp/fake-backup-notready", timestamp: "2026-05-25T00:00:00Z" }, - }; -}; -sandboxState.restoreRecreatedSandboxState = (name, backupPath) => { - events.push({ kind: "restore", name, backupPath }); - return { - success: true, - restoredDirs: ["workspace"], - failedDirs: [], - restoredFiles: ["UPGRADE_MARKER.md"], - failedFiles: [], - }; -}; - -const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); -preflight.checkPortAvailable = async () => ({ ok: true }); - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4245; - events.push({ kind: "spawn", cmd: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]) }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, events })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - - const events = payload.events as Array<{ - kind: string; - cmd?: string; - name?: string; - backupPath?: string; - }>; - const backupIndex = events.findIndex((e) => e.kind === "backup"); - const deleteIndex = events.findIndex( - (e) => e.kind === "run" && (e.cmd || "").includes("sandbox delete"), - ); - const restoreIndex = events.findIndex((e) => e.kind === "restore"); - - assert.ok(backupIndex >= 0, "should call backupSandboxState for not-ready sandbox"); - assert.ok(deleteIndex > backupIndex, "backup must happen before sandbox delete"); - assert.ok(restoreIndex > deleteIndex, "restore must happen after sandbox recreate"); - }); - - it("recreating a sandbox preserves the user's policy preset selections", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-recreate-preserves-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "recreate-preserves.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const sessionModulePath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "onboard-session.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const onboardSession = require(${sessionModulePath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const commands = []; -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { - defaultCurlOutput: "ok", - }); - if (mockedCapture !== null) return mockedCapture; - } - return ""; -}; - -// Existing sandbox has a custom preset selection: only "npm" (not the -// full "balanced" tier). Recreating the sandbox must preserve this -// customisation rather than reverting to the tier defaults. -registry.getSandbox = () => ({ - name: "my-assistant", - gpuEnabled: false, - policies: ["npm"], - policyTier: "balanced", -}); -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); -preflight.checkPortAvailable = async () => ({ ok: true }); - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.NEMOCLAW_RECREATE_SANDBOX = "1"; - process.env.NEMOCLAW_RECREATE_WITHOUT_BACKUP = "1"; - await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - const session = onboardSession.loadSession(); - console.log(JSON.stringify({ policyPresets: session && session.policyPresets })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - - assert.deepEqual( - payload.policyPresets, - ["npm"], - "createSandbox should write the previous sandbox's policy presets to the onboard session before destroying it so they can be reapplied after recreation", - ); - }); - - it("interactive mode prompts before reusing an existing ready sandbox", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-interactive-reuse-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "interactive-reuse.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const credentials = require(${credentialsPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); -const fs = require("node:fs"); -const path = require("node:path"); - -const commands = []; -runner.run = (command, opts = {}) => { - const commandString = Array.isArray(command) ? command.join(" ") : String(command); - if (_n(command).includes("sandbox download")) { - const parts = commandString.match(/'([^']*)'/g) || []; - const downloadDir = Array.isArray(command) - ? String(command[command.length - 1] || "") - : parts.length - ? parts[parts.length - 1].slice(1, -1) - : null; - if (downloadDir) { - fs.mkdirSync(downloadDir, { recursive: true }); - fs.writeFileSync( - path.join(downloadDir, "config.json"), - JSON.stringify({ provider: "nvidia-prod", model: "gpt-5.4" }), - ); - } - } - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runFile = (file, args = [], opts = {}) => { - commands.push({ type: "runFile", command: _n([file, ...args]), file, args, env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); - -// Mock prompt to return "y" (reuse) -credentials.prompt = async () => "y"; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, commands })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - // Run WITHOUT NEMOCLAW_NON_INTERACTIVE to exercise interactive path - const env: Record = { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - }; - delete env["NEMOCLAW_NON_INTERACTIVE"]; - delete env["NEMOCLAW_RECREATE_SANDBOX"]; - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - - assert.equal(payload.sandboxName, "my-assistant", "should reuse when user answers y"); - assert.ok( - payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox create")), - "should NOT recreate sandbox when user chooses to reuse", - ); - assert.ok( - payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox delete")), - "should NOT delete sandbox when user chooses to reuse", - ); - assert.ok( - result.stdout.includes("already exists"), - "should show 'already exists' message in interactive mode", - ); - }); - - it("interactive mode deletes and recreates sandbox when user confirms drift recreate", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-interactive-decline-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "interactive-decline.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const credentials = require(${credentialsPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); -const fs = require("node:fs"); -const path = require("node:path"); - -const commands = []; -runner.run = (command, opts = {}) => { - const commandString = Array.isArray(command) ? command.join(" ") : String(command); - if (_n(command).includes("sandbox download")) { - const parts = commandString.match(/'([^']*)'/g) || []; - const downloadDir = Array.isArray(command) - ? String(command[command.length - 1] || "") - : parts.length - ? parts[parts.length - 1].slice(1, -1) - : null; - if (downloadDir) { - fs.mkdirSync(downloadDir, { recursive: true }); - fs.writeFileSync( - path.join(downloadDir, "config.json"), - JSON.stringify({ provider: "openai-prod", model: "gpt-4o" }), - ); - } - } - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runFile = (file, args = [], opts = {}) => { - commands.push({ type: "runFile", command: _n([file, ...args]), file, args, env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; - if (_n(command).includes("sandbox list")) return "my-assistant Ready"; - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { - defaultCurlOutput: "ok", - }); - if (mockedCapture !== null) return mockedCapture; - } - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); -preflight.checkPortAvailable = async () => ({ ok: true }); - -// Mock prompt to return "y" (confirm recreate) -credentials.prompt = async () => "y"; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, commands })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - // Run WITHOUT NEMOCLAW_NON_INTERACTIVE to exercise interactive path - const env: Record = { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_RECREATE_WITHOUT_BACKUP: "1", - }; - delete env["NEMOCLAW_NON_INTERACTIVE"]; - delete env["NEMOCLAW_RECREATE_SANDBOX"]; - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - - assert.ok( - payload.commands.some((entry: CommandEntry) => /sandbox.*delete/.test(String(entry.command))), - "should delete existing sandbox when user confirms recreate", - ); - assert.ok( - payload.commands.some((entry: CommandEntry) => /sandbox.*create/.test(String(entry.command))), - "should create a new sandbox when user confirms recreate", - ); - assert.ok( - result.stdout.includes("requested inference selection changed"), - "should show drift warning before prompting", - ); - }); - - it("interactive mode auto-recreates when existing sandbox is not ready", { - timeout: 60_000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-interactive-notready-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "interactive-notready.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const credentials = require(${credentialsPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); - -const commands = []; -let sandboxDeleted = false; -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - if (_n(command).includes("sandbox delete")) sandboxDeleted = true; - return { status: 0 }; -}; -runner.runCapture = (command) => { - // Existing sandbox that is NOT ready initially, becomes Ready after recreation - if (_n(command).includes("sandbox get my-assistant")) return "my-assistant"; - if (_n(command).includes("sandbox list")) { - return sandboxDeleted ? "my-assistant Ready" : "my-assistant NotReady"; - } - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command, { - defaultCurlOutput: "ok", - }); - if (mockedCapture !== null) return mockedCapture; - } - return ""; -}; -registry.getSandbox = () => ({ name: "my-assistant", toolDisclosure: "progressive" }); -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; - -const preflight = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}); -preflight.checkPortAvailable = async () => ({ ok: true }); - -// User confirms recreation when prompted -credentials.prompt = async () => "y"; - -const fakeSpawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - child.emit("close", 0); - }); - return child; -}; -childProcess.spawn = fakeSpawn; - -// Also patch spawn inside the compiled sandbox-create-stream module. -// It imports spawn at load time from "node:child_process", so patching the -// childProcess object above does not reach it. Patch the cached module -// directly so streamSandboxCreate (called by createSandbox) doesn't spawn -// a real bash process that tries to hit a live gateway. -const sandboxCreateStreamMod = require(${JSON.stringify(path.join(repoRoot, "src", "lib", "sandbox", "create-stream.ts"))}); -const _origStreamCreate = sandboxCreateStreamMod.streamSandboxCreate; -sandboxCreateStreamMod.streamSandboxCreate = (command, env, options = {}) => { - return _origStreamCreate(command, env, { ...options, spawnImpl: fakeSpawn }); -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, commands })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - // Run WITHOUT NEMOCLAW_NON_INTERACTIVE to exercise interactive path - const env: Record = { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_RECREATE_WITHOUT_BACKUP: "1", - }; - delete env["NEMOCLAW_NON_INTERACTIVE"]; - delete env["NEMOCLAW_RECREATE_SANDBOX"]; - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env, - }); - - assert.equal(result.status, 0, result.stderr); - const payloadLine = result.stdout - .trim() - .split("\n") - .slice() - .reverse() - .find((line) => line.startsWith("{") && line.endsWith("}")); - assert.ok(payloadLine, `expected JSON payload in stdout:\n${result.stdout}`); - const payload = JSON.parse(payloadLine); - - assert.ok( - payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox delete")), - "should delete not-ready sandbox after user confirms", - ); - assert.ok( - payload.commands.some((entry: CommandEntry) => entry.command.includes("sandbox create")), - "should recreate sandbox when existing one is not ready", - ); - assert.ok(result.stdout.includes("not ready"), "should mention sandbox is not ready"); - }); - it("continues once the sandbox is Ready even if the create stream never closes", { - timeout: 20000, - }, async () => { - const repoRoot = path.join(import.meta.dirname, ".."); - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-create-ready-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "create-sandbox-ready-check.js"); - const payloadPath = path.join(tmpDir, "payload.json"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify(path.join(repoRoot, "src", "lib", "state", "registry.ts")); - const preflightPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"), - ); - const credentialsPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "credentials", "store.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const preflight = require(${preflightPath}); -const credentials = require(${credentialsPath}); -const childProcess = require("node:child_process"); -const { EventEmitter } = require("node:events"); -const fs = require("node:fs"); - -const commands = []; -let sandboxListCalls = 0; -const keepAlive = setInterval(() => {}, 1000); -runner.run = (command, opts = {}) => { - commands.push({ command: _n(command), env: opts.env || null }); - return { status: 0 }; -}; -runner.runCapture = (command) => { - if (_n(command).includes("sandbox get my-assistant")) return ""; - if (_n(command).includes("sandbox list")) { - sandboxListCalls += 1; - return sandboxListCalls >= 2 ? "my-assistant Ready" : "my-assistant Pending"; - } - { - const mockedCapture = require(${onboardScriptMocksPath}).mockOnboardRunCapture(command); - if (mockedCapture !== null) return mockedCapture; - } - if (_n(command).includes("forward list")) return "my-assistant 127.0.0.1 18789 12345 running"; - return ""; -}; -registry.registerSandbox = () => true; -registry.updateSandbox = () => true; -registry.setDefault = () => true; -registry.removeSandbox = () => true; -preflight.checkPortAvailable = async () => ({ ok: true }); -credentials.prompt = async () => ""; - -childProcess.spawn = (...args) => { - const child = new EventEmitter(); - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); - child.unref = () => {}; - child.pid = 4242; - child.killCalls = []; - child.unrefCalls = 0; - child.stdout.destroyCalls = 0; - child.stderr.destroyCalls = 0; - child.stdout.destroy = () => { - child.stdout.destroyCalls += 1; - }; - child.stderr.destroy = () => { - child.stderr.destroyCalls += 1; - }; - child.unref = () => { - child.unrefCalls += 1; - }; - child.kill = (signal) => { - child.killCalls.push(signal); - process.nextTick(() => child.emit("close", signal === "SIGTERM" ? 0 : 1)); - return true; - }; - commands.push({ command: _n([args[0], ...(Array.isArray(args[1]) ? args[1] : [])]), env: args[2]?.env || null, child }); - process.nextTick(() => { - child.stdout.emit("data", Buffer.from("Created sandbox: my-assistant\n")); - }); - return child; -}; - -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - const sandboxName = await createSandbox(null, "gpt-5.4"); - const createCommand = commands.find((entry) => entry.command.includes("sandbox create")); - fs.writeFileSync(${JSON.stringify(payloadPath)}, JSON.stringify({ - sandboxName, - sandboxListCalls, - killCalls: createCommand.child.killCalls, - unrefCalls: createCommand.child.unrefCalls, - stdoutDestroyCalls: createCommand.child.stdout.destroyCalls, - stderrDestroyCalls: createCommand.child.stderr.destroyCalls, - })); - clearInterval(keepAlive); -})().catch((error) => { - clearInterval(keepAlive); - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - OPENSHELL_DRIVERS: "docker", - }, - timeout: 15000, - }); - - assert.equal(result.status, 0, result.stderr); - const payload = JSON.parse(fs.readFileSync(payloadPath, "utf8")); - assert.equal(payload.sandboxName, "my-assistant"); - assert.ok(payload.sandboxListCalls >= 2); - assert.deepEqual(payload.killCalls, ["SIGTERM"]); - assert.equal(payload.unrefCalls, 1); - assert.equal(payload.stdoutDestroyCalls, 1); - assert.equal(payload.stderrDestroyCalls, 1); - }); - it("restores the dashboard forward when onboarding reuses an existing ready sandbox", async () => { const repoRoot = path.join(import.meta.dirname, ".."); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-reuse-forward-")); diff --git a/test/openclaw-integrity-pin-base.test.ts b/test/openclaw-integrity-pin-base.test.ts new file mode 100644 index 00000000000..15cf6edeb21 --- /dev/null +++ b/test/openclaw-integrity-pin-base.test.ts @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { registerOpenClawIntegrityPinTests } from "./openclaw-integrity-pin-suite"; + +registerOpenClawIntegrityPinTests("base"); diff --git a/test/openclaw-integrity-pin-contract.test.ts b/test/openclaw-integrity-pin-contract.test.ts new file mode 100644 index 00000000000..1b02f2b4eb9 --- /dev/null +++ b/test/openclaw-integrity-pin-contract.test.ts @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { registerOpenClawIntegrityPinTests } from "./openclaw-integrity-pin-suite"; + +registerOpenClawIntegrityPinTests("contract"); diff --git a/test/openclaw-integrity-pin-plugin-install.test.ts b/test/openclaw-integrity-pin-plugin-install.test.ts new file mode 100644 index 00000000000..eee9143ae88 --- /dev/null +++ b/test/openclaw-integrity-pin-plugin-install.test.ts @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { registerOpenClawIntegrityPinTests } from "./openclaw-integrity-pin-suite"; + +registerOpenClawIntegrityPinTests("plugin-install"); diff --git a/test/openclaw-integrity-pin-suite.ts b/test/openclaw-integrity-pin-suite.ts new file mode 100644 index 00000000000..d8789d4a5c8 --- /dev/null +++ b/test/openclaw-integrity-pin-suite.ts @@ -0,0 +1,1403 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { createBuiltInChannelManifestRegistry } from "../src/lib/messaging"; +import { reviewedOpenClawPluginIntegrityByPackageSpec } from "../src/lib/messaging/applier/build/messaging-build-applier.mts"; + +const REPO_ROOT = path.join(import.meta.dirname, ".."); +const DOCKERFILE = path.join(REPO_ROOT, "Dockerfile"); +const DOCKERFILE_BASE = path.join(REPO_ROOT, "Dockerfile.base"); +const PRODUCTION_DOCKERFILES = [ + DOCKERFILE, + DOCKERFILE_BASE, + path.join(REPO_ROOT, "agents", "hermes", "Dockerfile"), + path.join(REPO_ROOT, "agents", "hermes", "Dockerfile.base"), + path.join(REPO_ROOT, "agents", "langchain-deepagents-code", "Dockerfile"), + path.join(REPO_ROOT, "agents", "langchain-deepagents-code", "Dockerfile.base"), +]; +const BLUEPRINT = path.join(REPO_ROOT, "nemoclaw-blueprint", "blueprint.yaml"); +const DEPENDENCY_REVIEW_NOTE = path.join( + REPO_ROOT, + "docs", + "security", + "openclaw-2026.6.10-dependency-review.md", +); +const PRODUCTION_BUILD_ARG_GUARD = path.join( + REPO_ROOT, + "scripts", + "check-production-build-args.sh", +); +const UNPINNED_OPENCLAW_VERSION = "2026.6.11"; +const PINNED_OPENCLAW_VERSION = "2026.6.10"; +const PINNED_OPENCLAW_INTEGRITY = + "sha512-LcooND2tBQw8A+kc1Ujltu3lg30bJ0w7XaeRy7eYzobb8BBdcW6DOGbwJL4vpj1vl9+gjRceOtlh5nh9OARcug=="; +const PINNED_OPENCLAW_TARBALL = "https://registry.npmjs.org/openclaw/-/openclaw-2026.6.10.tgz"; +const PINNED_CODEX_ACP_VERSION = "0.11.1"; +const PINNED_CODEX_ACP_TARBALL = + "https://registry.npmjs.org/@zed-industries/codex-acp/-/codex-acp-0.11.1.tgz"; +const PINNED_CODEX_ACP_INTEGRITY = + "sha512-My2VSlBtvJipJhImHjFDej2ut/p00QqOISRnZgLgLrSIzjgvdcQvAhaZviWj7XPhk4UIdIb0OoA+Lrls824uiQ=="; +const PINNED_MCPORTER_VERSION = "0.7.3"; +const PINNED_MCPORTER_INTEGRITY = + "sha512-egoPVYqTnWb3NjRIxo+xc8OrAI0dlPrJm9pAiZx0pImuNIV5rKhGtTnIfH/Y1ldGPVu74ibj3KR5c9U/QSdQFA=="; +const MCPORTER_LOCKFILE = path.join( + REPO_ROOT, + "agents", + "openclaw", + "mcporter-runtime", + "package-lock.json", +); +const PINNED_MCPORTER_LOCK_SHA256 = createHash("sha256") + .update(fs.readFileSync(MCPORTER_LOCKFILE)) + .digest("hex"); +const PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY = + "sha512-EJt0fjk4bcR3N/9u00f1pL0BJYG5yfC09DV3l6rWDmytpE2vUeBZWpx4pOmFDreGV+7DKxhCbQDgDAmvZGjLag=="; +const PINNED_OPENCLAW_DIAGNOSTICS_OTEL_TARBALL = + "https://registry.npmjs.org/@openclaw/diagnostics-otel/-/diagnostics-otel-2026.6.10.tgz"; +const PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY = + "sha512-DDRnb4reL99O8kbISNbRFyk/xoUPYHsXG3UGikKAsVs+zIldYYA0hY0d3Z2aWoE+0vfda27mJUByCo7Xr15qdw=="; +const PINNED_OPENCLAW_BRAVE_PLUGIN_TARBALL = + "https://registry.npmjs.org/@openclaw/brave-plugin/-/brave-plugin-2026.6.10.tgz"; +const PINNED_OPENCLAW_DISCORD_INTEGRITY = + "sha512-NKp/j00l+rk5PC0Lv/0fOIiiQJ1c/OpG9471zqXUDKQie6pQ1Fi9KUZUouyoTMmfLh/n4S0CkEMqrON40eBKXA=="; +const PINNED_OPENCLAW_SLACK_INTEGRITY = + "sha512-OOsMLjPcbWhQRM5XDwfdrACjJmKqavFtpuIlhHAXWrLrd/p7SyIVE9AoKS0yxOx6bqGDIMJ9+knzdViHMLgBdA=="; +const PINNED_OPENCLAW_WHATSAPP_INTEGRITY = + "sha512-k/XrRdZY77SHrdaRwJOEB7/JRbjp4yVgGD/ZNyakjTMqo32XRVtwPBUnj7726rW8Kl5yyOMQQLKFiD9MDfhmPQ=="; +const PINNED_OPENCLAW_MSTEAMS_INTEGRITY = + "sha512-GjHnCPvjbnI0C7mEFcdT2uKDH4/WwOe2dZBfQiWxBtkE76m6TNG0J9dJjD4mc8/pk8rXSO0cWw+KV9jzWtF9VA=="; +const PINNED_WECHAT_PLUGIN_INTEGRITY = + "sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw=="; +const LEGACY_REBUILD_OPENCLAW_VERSION = "2026.3.11"; +const LEGACY_REBUILD_OPENCLAW_INTEGRITY = + "sha512-bxwiBmHPakwfpY5tqC9lrV5TCu5PKf0c1bHNc3nhrb+pqKcPEWV4zOjDVFLQUHr98ihgWA+3pacy4b3LQ8wduQ=="; +const LEGACY_REBUILD_OPENCLAW_TARBALL = + "https://registry.npmjs.org/openclaw/-/openclaw-2026.3.11.tgz"; +const LEGACY_GATEWAY_UPGRADE_OPENCLAW_VERSION = "2026.4.24"; +const LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY = + "sha512-W6u4XeIIP4+uG4DYV9G3JeS6QNuKwfhQIej1GIoL4BdcnUFgrnB8kHYNXL3MxiHRKuhZB9OYwUMGs8jKFZR/Vg=="; +const LEGACY_GATEWAY_UPGRADE_OPENCLAW_TARBALL = + "https://registry.npmjs.org/openclaw/-/openclaw-2026.4.24.tgz"; +const OPENCLAW_BASE_PROVENANCE_PATH = "/usr/local/share/nemoclaw/openclaw-base-provenance-v1"; + +function openClawBaseProvenance( + version = PINNED_OPENCLAW_VERSION, + integrity = PINNED_OPENCLAW_INTEGRITY, + tarball = PINNED_OPENCLAW_TARBALL, +): string { + return [ + "schema=2", + `package=openclaw@${version}`, + `integrity=${integrity}`, + `tarball=${tarball}`, + "recipe=ignore-scripts+reviewed-lifecycle-v1", + `mcporter-package=mcporter@${PINNED_MCPORTER_VERSION}`, + `mcporter-integrity=${PINNED_MCPORTER_INTEGRITY}`, + `mcporter-lock-sha256=${PINNED_MCPORTER_LOCK_SHA256}`, + "mcporter-recipe=locked-ci+audit-signatures-v1", + "", + ].join("\n"); +} + +function extractRunBlock(file: string, startMarker: string, endMarker: string): string { + const source = fs.readFileSync(file, "utf-8"); + const start = source.indexOf(startMarker); + const end = source.indexOf(endMarker, start); + expect(start, `Expected start marker in ${file}: ${startMarker}`).toBeGreaterThanOrEqual(0); + expect(end, `Expected end marker in ${file}: ${endMarker}`).toBeGreaterThan(start); + const runIndex = source.indexOf("RUN ", start); + expect(runIndex, `Expected RUN instruction after ${startMarker}`).toBeGreaterThanOrEqual(0); + expect(runIndex, `Expected RUN instruction before ${endMarker}`).toBeLessThanOrEqual(end); + return source + .slice(runIndex, end) + .trim() + .replace(/^RUN\s+--mount=[^\n]+\\\n\s*/, "") + .replace(/^RUN\s+/, "") + .split("\n") + .filter((line) => !line.trimStart().startsWith("#")) + .join("\n") + .replace(/\\\n/g, " ") + .replace(/\\\s*$/, ""); +} + +function runInstallBlock( + command: string, + options: { + openclawVersion?: string; + committedIntegrity?: string; + registryIntegrity?: string; + registryTarball?: string; + packIntegrity?: string; + codexAcpCommittedIntegrity?: string; + codexAcpRegistryIntegrity?: string; + codexAcpRegistryTarball?: string; + codexAcpPackIntegrity?: string; + packFilename?: string | null; + allowLegacyFixture?: boolean; + installedOpenClawVersion?: string; + installedMcporterVersion?: string; + baseImage?: string; + baseProvenance?: string | null; + baseProvenanceMetadata?: string; + baseProvenanceSymlink?: boolean; + } = {}, +) { + const { + openclawVersion = UNPINNED_OPENCLAW_VERSION, + committedIntegrity = "sha512-reviewed-pin", + registryIntegrity = committedIntegrity, + registryTarball = PINNED_OPENCLAW_TARBALL, + packIntegrity = committedIntegrity, + codexAcpCommittedIntegrity = PINNED_CODEX_ACP_INTEGRITY, + codexAcpRegistryIntegrity = codexAcpCommittedIntegrity, + codexAcpRegistryTarball = PINNED_CODEX_ACP_TARBALL, + codexAcpPackIntegrity = codexAcpCommittedIntegrity, + packFilename, + allowLegacyFixture = false, + installedOpenClawVersion = LEGACY_REBUILD_OPENCLAW_VERSION, + installedMcporterVersion = PINNED_MCPORTER_VERSION, + baseImage = "ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + baseProvenance = null, + baseProvenanceMetadata = "0:0:444", + baseProvenanceSymlink = false, + } = options; + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-integrity-")); + const blueprint = path.join(tmp, "blueprint.yaml"); + const log = path.join(tmp, "calls.log"); + const provenancePath = path.join(tmp, "openclaw-base-provenance-v1"); + const mcporterRuntime = path.join(tmp, "mcporter-runtime"); + const mcporterBin = path.join(tmp, "bin", "mcporter"); + fs.mkdirSync(path.dirname(mcporterBin), { recursive: true }); + fs.mkdirSync(mcporterRuntime, { recursive: true }); + fs.copyFileSync(MCPORTER_LOCKFILE, path.join(mcporterRuntime, "package-lock.json")); + fs.writeFileSync(blueprint, fs.readFileSync(BLUEPRINT, "utf-8")); + const writeProvenanceFile = () => { + fs.writeFileSync(provenancePath, baseProvenance as string, { mode: 0o444 }); + }; + const writeProvenanceSymlink = () => { + const target = path.join(tmp, "openclaw-base-provenance-target"); + fs.writeFileSync(target, baseProvenance as string); + fs.symlinkSync(target, provenancePath); + }; + const writePresentProvenance = baseProvenanceSymlink + ? writeProvenanceSymlink + : writeProvenanceFile; + const setupProvenance = baseProvenance === null ? () => undefined : writePresentProvenance; + setupProvenance(); + const script = [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `call_log=${JSON.stringify(log)}`, + `real_node=${JSON.stringify(process.execPath)}`, + `OPENCLAW_VERSION=${JSON.stringify(openclawVersion)}`, + `BASE_IMAGE=${JSON.stringify(baseImage)}`, + `openclaw_provenance_path=${JSON.stringify(provenancePath)}`, + `openclaw_provenance_metadata=${JSON.stringify(baseProvenanceMetadata)}`, + `OPENCLAW_2026_6_10_INTEGRITY=${JSON.stringify(committedIntegrity)}`, + `OPENCLAW_2026_6_10_TARBALL=${JSON.stringify(PINNED_OPENCLAW_TARBALL)}`, + `NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=${allowLegacyFixture ? "1" : "0"}`, + `OPENCLAW_2026_3_11_INTEGRITY=${JSON.stringify(LEGACY_REBUILD_OPENCLAW_INTEGRITY)}`, + `OPENCLAW_2026_3_11_TARBALL=${JSON.stringify(LEGACY_REBUILD_OPENCLAW_TARBALL)}`, + `OPENCLAW_2026_4_24_INTEGRITY=${JSON.stringify(LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY)}`, + `OPENCLAW_2026_4_24_TARBALL=${JSON.stringify(LEGACY_GATEWAY_UPGRADE_OPENCLAW_TARBALL)}`, + `CODEX_ACP_0_11_1_INTEGRITY=${JSON.stringify(codexAcpCommittedIntegrity)}`, + `MCPORTER_VERSION=${JSON.stringify(PINNED_MCPORTER_VERSION)}`, + `MCPORTER_0_7_3_INTEGRITY=${JSON.stringify(PINNED_MCPORTER_INTEGRITY)}`, + `installed_openclaw_version=${JSON.stringify(installedOpenClawVersion)}`, + `installed_mcporter_version=${JSON.stringify(installedMcporterVersion)}`, + "node() {", + ' if [ "${1:-}" = "/usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs" ]; then printf "node %s\\n" "$*" >> "$call_log"; return 0; fi', + ' "$real_node" "$@"', + "}", + `openclaw() { if [ "\${1:-}" = "--version" ]; then printf 'openclaw %s\\n' "$installed_openclaw_version"; else return 127; fi; }`, + 'mcporter() { if [ "${1:-}" = "--version" ]; then printf "%s\\n" "$installed_mcporter_version"; else return 127; fi; }', + "codex-acp() { :; }", + "stat() {", + ' if [ "${1:-}" = "-c" ] && [ "${3:-}" = "$openclaw_provenance_path" ]; then printf "%s\\n" "$openclaw_provenance_metadata"; return 0; fi', + ' command stat "$@"', + "}", + "npm() {", + ' printf "npm %s\\n" "$*" >> "$call_log";', + ' [ "${1:-}" != "--prefix" ] || [ "${3:-}" != "ci" ] || installed_mcporter_version="$MCPORTER_VERSION"', + ' if [ "${1:-}" = "view" ] && [ "${3:-}" = "version" ]; then printf "%s\\n" "$OPENCLAW_VERSION"; return 0; fi', + ` if [ "\${1:-}" = "view" ] && [ "\${2:-}" = "@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION}" ] && [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(codexAcpRegistryIntegrity)}; return 0; fi`, + ` if [ "\${1:-}" = "view" ] && [ "\${2:-}" = "@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION}" ] && [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(codexAcpRegistryTarball)}; return 0; fi`, + ` if [ "\${1:-}" = "view" ] && [ "\${2:-}" = "mcporter@${PINNED_MCPORTER_VERSION}" ] && [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(PINNED_MCPORTER_INTEGRITY)}; return 0; fi`, + ` if [ "\${1:-}" = "view" ] && [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(registryIntegrity)}; return 0; fi`, + ` if [ "\${1:-}" = "view" ] && [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(registryTarball)}; return 0; fi`, + ' if [ "${1:-}" = "pack" ]; then', + ' pack_spec="${2:-}"; pack_dir="";', + ' while [ "$#" -gt 0 ]; do', + ' if [ "${1:-}" = "--pack-destination" ]; then pack_dir="${2:-}"; shift 2; continue; fi', + " shift", + " done", + ' test -n "$pack_dir";', + ' pack_file="$(basename "$pack_spec")";', + ' case "$pack_file" in *.tgz) ;; *) pack_file="${pack_file}.tgz" ;; esac', + ` reported_pack_file=${JSON.stringify(packFilename ?? "")}`, + ...(packFilename === null + ? [] + : [' reported_pack_file="${reported_pack_file:-$pack_file}"']), + ' printf "fake tarball" > "$pack_dir/$pack_file";', + ` case "$pack_spec" in *"codex-acp"*) pack_integrity=${JSON.stringify(codexAcpPackIntegrity)} ;; *) pack_integrity=${JSON.stringify(packIntegrity)} ;; esac`, + ' printf \'[{"filename":"%s","integrity":"%s"}]\\n\' "$reported_pack_file" "$pack_integrity";', + " return 0", + " fi", + ' if [ "${1:-}" = "install" ] && printf "%s\\n" "$*" | grep -q "openclaw-"; then installed_openclaw_version="$OPENCLAW_VERSION"; fi', + "}", + "pip3() { return 0; }", + command + .replaceAll("/opt/nemoclaw-blueprint/blueprint.yaml", blueprint) + .replaceAll("/tmp/blueprint.yaml", blueprint) + .replaceAll(OPENCLAW_BASE_PROVENANCE_PATH, provenancePath) + .replaceAll("/usr/local/lib/nemoclaw/mcporter-runtime", mcporterRuntime) + .replaceAll("/usr/local/bin/mcporter", mcporterBin), + ].join("\n"); + const scriptPath = path.join(tmp, "run.sh"); + fs.writeFileSync(scriptPath, script, { mode: 0o700 }); + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 10000 }); + const calls = fs.existsSync(log) ? fs.readFileSync(log, "utf-8") : ""; + const provenanceExists = fs.existsSync(provenancePath); + const provenanceContent = provenanceExists ? fs.readFileSync(provenancePath, "utf-8") : null; + const provenanceMode = provenanceExists ? fs.statSync(provenancePath).mode & 0o777 : null; + fs.rmSync(tmp, { recursive: true, force: true }); + return { result, calls, provenanceExists, provenanceContent, provenanceMode }; +} + +function runProductionBuildArgGuard( + args: string[], + env: Record = {}, +): ReturnType { + return spawnSync("bash", [PRODUCTION_BUILD_ARG_GUARD, ...args], { + cwd: REPO_ROOT, + encoding: "utf-8", + env: { ...process.env, ...env }, + }); +} + +function declaredProductionPinArgNames(): string[] { + const names = PRODUCTION_DOCKERFILES.flatMap((dockerfile) => + fs + .readFileSync(dockerfile, "utf-8") + .split("\n") + .flatMap((line) => { + const match = /^ARG ([A-Z_][A-Z0-9_]*(?:_INTEGRITY|_TARBALL))(?:=|$)/.exec(line); + return match?.[1] ? [match[1]] : []; + }), + ); + return [...new Set(names)].sort(); +} + +function runOptionalOpenClawPluginBlock( + options: { + openclawVersion?: string; + otel?: boolean; + webSearch?: boolean; + diagnosticsRegistryIntegrity?: string; + diagnosticsRegistryTarball?: string; + braveRegistryIntegrity?: string; + braveRegistryTarball?: string; + pluginPackFilename?: string; + } = {}, +) { + const { + openclawVersion = PINNED_OPENCLAW_VERSION, + otel = true, + webSearch = true, + diagnosticsRegistryIntegrity = PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY, + diagnosticsRegistryTarball = PINNED_OPENCLAW_DIAGNOSTICS_OTEL_TARBALL, + braveRegistryIntegrity = PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY, + braveRegistryTarball = PINNED_OPENCLAW_BRAVE_PLUGIN_TARBALL, + pluginPackFilename = "", + } = options; + const command = extractRunBlock( + DOCKERFILE, + "# Install non-messaging OpenClaw plugins that need to match the runtime.", + 'RUN OPENCLAW_VERSION="${OPENCLAW_VERSION}" node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier.mts', + ); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-plugin-integrity-")); + const log = path.join(tmp, "calls.log"); + const script = [ + "#!/usr/bin/env bash", + "set -euo pipefail", + `call_log=${JSON.stringify(log)}`, + `OPENCLAW_VERSION=${JSON.stringify(openclawVersion)}`, + `OPENCLAW_DIAGNOSTICS_OTEL_2026_6_10_INTEGRITY=${JSON.stringify(PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY)}`, + `OPENCLAW_BRAVE_PLUGIN_2026_6_10_INTEGRITY=${JSON.stringify(PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY)}`, + `NEMOCLAW_OPENCLAW_OTEL=${otel ? "1" : "0"}`, + `NEMOCLAW_WEB_SEARCH_ENABLED=${webSearch ? "1" : "0"}`, + 'openclaw() { printf \'openclaw %s\\nopenclaw-env %s %s\\n\' "$*" "${NPM_CONFIG_IGNORE_SCRIPTS:-}" "${npm_config_ignore_scripts:-}" >> "$call_log"; }', + "npm() {", + ' printf "npm %s\\n" "$*" >> "$call_log";', + ' if [ "${1:-}" = "pack" ]; then', + ' pack_spec="${2:-}"; pack_dir="";', + ' while [ "$#" -gt 0 ]; do', + ' if [ "${1:-}" = "--pack-destination" ]; then pack_dir="${2:-}"; shift 2; continue; fi', + " shift", + " done", + ' test -n "$pack_dir"; pack_file="$(basename "$pack_spec")";', + ` reported_pack_file=${JSON.stringify(pluginPackFilename)}`, + ' reported_pack_file="${reported_pack_file:-$pack_file}"', + ' printf "fake plugin tarball" > "$pack_dir/$pack_file";', + ' case "$pack_spec" in', + ` *"diagnostics-otel"*) printf '[{"filename":"%s","integrity":"%s"}]\\n' "$reported_pack_file" ${JSON.stringify(diagnosticsRegistryIntegrity)}; return 0 ;;`, + ` *"brave-plugin"*) printf '[{"filename":"%s","integrity":"%s"}]\\n' "$reported_pack_file" ${JSON.stringify(braveRegistryIntegrity)}; return 0 ;;`, + " esac", + " return 1", + " fi", + ' if [ "${1:-}" != "view" ]; then exit 1; fi', + ' case "${2:-}" in', + ` "@openclaw/diagnostics-otel@${PINNED_OPENCLAW_VERSION}") if [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(diagnosticsRegistryIntegrity)}; return 0; fi; if [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(diagnosticsRegistryTarball)}; return 0; fi ;;`, + ` "@openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION}") if [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(braveRegistryIntegrity)}; return 0; fi; if [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(braveRegistryTarball)}; return 0; fi ;;`, + " esac", + " return 1", + "}", + command, + ].join("\n"); + const scriptPath = path.join(tmp, "run.sh"); + fs.writeFileSync(scriptPath, script, { mode: 0o700 }); + const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 10000 }); + const calls = fs.existsSync(log) ? fs.readFileSync(log, "utf-8") : ""; + fs.rmSync(tmp, { recursive: true, force: true }); + return { result, calls }; +} + +export type OpenClawIntegrityPinTestGroup = "base" | "contract" | "plugin-install"; + +export function registerOpenClawIntegrityPinTests(group: OpenClawIntegrityPinTestGroup): void { + describe("OpenClaw npm integrity pins", () => { + if (group === "contract") { + it("keeps the advisory review note aligned with the committed OpenClaw pin", () => { + const reviewNote = fs.readFileSync(DEPENDENCY_REVIEW_NOTE, "utf-8"); + + expect(reviewNote).toContain(`openclaw@${PINNED_OPENCLAW_VERSION}`); + expect(reviewNote).toContain(PINNED_OPENCLAW_INTEGRITY); + expect(reviewNote).toContain(PINNED_OPENCLAW_TARBALL); + expect(reviewNote).toContain(`@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION}`); + expect(reviewNote).toContain(PINNED_CODEX_ACP_TARBALL); + expect(reviewNote).toContain(PINNED_CODEX_ACP_INTEGRITY); + expect(reviewNote).toContain("@openclaw/diagnostics-otel@2026.6.10"); + expect(reviewNote).toContain(PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY); + expect(reviewNote).toContain("@openclaw/brave-plugin@2026.6.10"); + expect(reviewNote).toContain(PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY); + expect(reviewNote).toContain("@openclaw/discord@2026.6.10"); + expect(reviewNote).toContain(PINNED_OPENCLAW_DISCORD_INTEGRITY); + expect(reviewNote).toContain("@openclaw/slack@2026.6.10"); + expect(reviewNote).toContain(PINNED_OPENCLAW_SLACK_INTEGRITY); + expect(reviewNote).toContain("@openclaw/whatsapp@2026.6.10"); + expect(reviewNote).toContain(PINNED_OPENCLAW_WHATSAPP_INTEGRITY); + expect(reviewNote).toContain("@openclaw/msteams@2026.6.10"); + expect(reviewNote).toContain(PINNED_OPENCLAW_MSTEAMS_INTEGRITY); + expect(reviewNote).toContain("@tencent-weixin/openclaw-weixin@2.4.3"); + expect(reviewNote).toContain(PINNED_WECHAT_PLUGIN_INTEGRITY); + expect(reviewNote).toContain("downloaded tarball integrity"); + expect(reviewNote).toContain("bind reviewed npm installs to verified local archives"); + expect(reviewNote).toContain("npm pack --json"); + expect(reviewNote).toContain("reject reported archive filenames"); + expect(reviewNote).toContain("unsafe reported archive filenames"); + expect(reviewNote).toContain("each reviewed npm plugin registry integrity"); + expect(reviewNote).toContain("install the verified archive path"); + expect(reviewNote).toContain("OpenClaw Compiled-Dist Patch Runtime Boundary"); + expect(reviewNote).toContain( + "The long-term source of truth for these behaviors remains upstream OpenClaw", + ); + expect(reviewNote).toContain("test/openclaw-real-patched-dist-harness.test.ts"); + expect(reviewNote).toContain("NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1"); + expect(reviewNote).toContain("not a substitute for focused nightly E2E proof"); + expect(reviewNote).toContain("OpenClaw Diagnostics OTEL Host Gateway Boundary"); + expect(reviewNote).toContain("openclaw-diagnostics-otel-local"); + expect(reviewNote).toContain("imports `OTLPTraceExporter`"); + expect(reviewNote).toContain("contains no `web_fetch`, `fetchWithSsrFGuard`"); + expect(reviewNote).toContain("@openclaw/diagnostics-otel@2026.6.10"); + expect(reviewNote).toContain("@openclaw/brave-plugin@2026.6.10"); + expect(reviewNote).toContain("@tencent-weixin/openclaw-weixin@2.4.3"); + expect(reviewNote).toContain("`0` high"); + expect(reviewNote).toContain("`0` critical"); + expect(reviewNote).toContain("`763` total dependencies"); + expect(reviewNote).toContain( + "`dist/pipeline.runtime-*.js`, which exports `prepareSlackMessage`", + ); + expect(reviewNote).toContain( + "imports the hashed pipeline runtime for `prepareSlackMessage`", + ); + expect(reviewNote).toContain( + "only reports `openclaw-pipeline-runtime` after allowed prepare", + ); + expect(reviewNote).toContain("`dist/extensions/telegram/runtime-api.js`"); + expect(reviewNote).toContain("which exports `sendMessageTelegram`"); + expect(reviewNote).toContain("fails closed if the installed runtime file is missing"); + expect(reviewNote).toContain("NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"); + expect(reviewNote).toContain("scripts/check-production-build-args.sh"); + expect(reviewNote).toContain("production build args"); + expect(reviewNote).toContain("claiming `openclaw-pipeline-runtime` inbound proof"); + expect(reviewNote).toContain("imports `dist/extensions/telegram/test-api.js`"); + expect(reviewNote).toContain("gateway/upstream reporting layer"); + expect(reviewNote).toContain("scripts/patch-openclaw-issue-4434-diagnostics.ts"); + expect(reviewNote).toContain("scripts/patch-openclaw-device-self-approval.ts"); + expect(reviewNote).toContain("approveDevicePairing"); + expect(reviewNote).toContain( + "Recovery hint: check sandbox egress and provider reachability, then retry.", + ); + expect(reviewNote).toContain("default 180-second timeout"); + }); + + it("keeps the Teams OpenClaw plugin manifest pinned to the reviewed 2026.6.10 integrity", () => { + const teamsManifest = createBuiltInChannelManifestRegistry().get("teams"); + const teamsPackage = teamsManifest?.agentPackages?.find( + (agentPackage) => + agentPackage.agent === "openclaw" && + agentPackage.manager === "openclaw-plugin" && + agentPackage.id === "openclawPluginPackage", + ); + + expect(teamsPackage).toMatchObject({ + spec: "npm:@openclaw/msteams@{{openclaw.version}}", + pin: true, + integrityByVersion: { + [PINNED_OPENCLAW_VERSION]: PINNED_OPENCLAW_MSTEAMS_INTEGRITY, + }, + }); + }); + + it("keeps reviewed OpenClaw messaging plugin integrity pins aligned with built-in manifests", () => { + const registry = createBuiltInChannelManifestRegistry(); + const expectedEntries: [string, string][] = registry.list().flatMap((manifest) => + (manifest.agentPackages ?? []) + .filter( + (agentPackage) => + agentPackage.agent === "openclaw" && agentPackage.manager === "openclaw-plugin", + ) + .map((agentPackage) => { + const packageSpec = agentPackage.spec + .replace(/^npm:/, "") + .replaceAll("{{openclaw.version}}", PINNED_OPENCLAW_VERSION); + const integrity = + agentPackage.integrity ?? + agentPackage.integrityByVersion?.[PINNED_OPENCLAW_VERSION]; + + expect(agentPackage.pin, `${manifest.id}:${agentPackage.id}`).toBe(true); + expect(integrity, `${manifest.id}:${packageSpec}`).toBeDefined(); + return [packageSpec, integrity as string] as [string, string]; + }), + ); + + const sortedEntries = (entries: [string, string][]) => + Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right))); + + expect( + sortedEntries( + Object.entries( + reviewedOpenClawPluginIntegrityByPackageSpec({ + OPENCLAW_VERSION: PINNED_OPENCLAW_VERSION, + }), + ), + ), + ).toEqual(sortedEntries(expectedEntries)); + }); + + it.each([ + "latest", + "^2026.6.10", + ])("rejects a trusted OpenClaw plugin manifest with non-exact version %s", (version) => { + const slackManifest = createBuiltInChannelManifestRegistry().get("slack"); + expect(slackManifest).toBeDefined(); + const nonExactManifest = { + ...slackManifest!, + agentPackages: slackManifest!.agentPackages?.map((agentPackage) => + agentPackage.agent === "openclaw" && agentPackage.manager === "openclaw-plugin" + ? { + ...agentPackage, + spec: `npm:@openclaw/slack@${version}`, + integrity: PINNED_OPENCLAW_SLACK_INTEGRITY, + integrityByVersion: undefined, + } + : agentPackage, + ), + }; + + expect(() => + reviewedOpenClawPluginIntegrityByPackageSpec( + { OPENCLAW_VERSION: PINNED_OPENCLAW_VERSION }, + [nonExactManifest], + ), + ).toThrow( + `must use an exact-version OpenClaw plugin package: npm:@openclaw/slack@${version}`, + ); + }); + } + + if (group === "plugin-install") { + it("verifies optional non-messaging OpenClaw plugin integrity before install", () => { + const { result, calls } = runOptionalOpenClawPluginBlock(); + + expect(result.status, `${result.stdout}${result.stderr}`).toBe(0); + expect(calls).toContain( + `npm view @openclaw/diagnostics-otel@${PINNED_OPENCLAW_VERSION} dist.integrity`, + ); + expect(calls).toContain( + `npm view @openclaw/diagnostics-otel@${PINNED_OPENCLAW_VERSION} dist.tarball`, + ); + expect(calls).toContain( + "npm pack https://registry.npmjs.org/@openclaw/diagnostics-otel/-/diagnostics-otel-2026.6.10.tgz --pack-destination", + ); + expect(calls).toMatch( + /openclaw plugins install npm-pack:\S*\/diagnostics-otel-2026\.6\.10\.tgz\n/, + ); + expect(calls).toContain( + `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.integrity`, + ); + expect(calls).toContain( + `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.tarball`, + ); + expect(calls).toContain( + "npm pack https://registry.npmjs.org/@openclaw/brave-plugin/-/brave-plugin-2026.6.10.tgz --pack-destination", + ); + expect(calls).toMatch( + /openclaw plugins install npm-pack:\S*\/brave-plugin-2026\.6\.10\.tgz\n/, + ); + expect(calls).toContain("openclaw-env true true"); + }); + + it("fails closed before optional OpenClaw plugin install when registry integrity drifts", () => { + const { result, calls } = runOptionalOpenClawPluginBlock({ + otel: false, + braveRegistryIntegrity: "sha512-brave-drift", + }); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `OpenClaw plugin @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} npm integrity mismatch`, + ); + expect(`${result.stdout}${result.stderr}`).toContain( + `Expected: ${PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY}`, + ); + expect(`${result.stdout}${result.stderr}`).toContain("Actual: sha512-brave-drift"); + expect(calls).toContain( + `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.integrity`, + ); + expect(calls).not.toContain("openclaw plugins install"); + }); + + it("fails closed before optional OpenClaw plugin install when the registry tarball URL drifts", () => { + const driftedTarball = + "https://registry.npmjs.org/@openclaw/brave-plugin/-/brave-plugin-2026.6.11.tgz"; + const { result, calls } = runOptionalOpenClawPluginBlock({ + otel: false, + braveRegistryTarball: driftedTarball, + }); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `OpenClaw plugin @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} npm tarball URL mismatch`, + ); + expect(`${result.stdout}${result.stderr}`).toContain( + `Expected: ${PINNED_OPENCLAW_BRAVE_PLUGIN_TARBALL}`, + ); + expect(`${result.stdout}${result.stderr}`).toContain(`Actual: ${driftedTarball}`); + expect(calls).toContain( + `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.tarball`, + ); + expect(calls).not.toContain("npm pack"); + expect(calls).not.toContain("openclaw plugins install"); + }); + + it("fails closed for optional OpenClaw plugin version overrides without committed pins", () => { + const { result, calls } = runOptionalOpenClawPluginBlock({ + openclawVersion: UNPINNED_OPENCLAW_VERSION, + webSearch: false, + }); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `OpenClaw plugin @openclaw/diagnostics-otel@${UNPINNED_OPENCLAW_VERSION} has no committed npm integrity pin`, + ); + expect(calls).not.toContain("openclaw plugins install"); + }); + + it("installs the reviewed pin when registry integrity matches the committed pin", () => { + const production = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + }, + ); + const codexAcp = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# Pre-install the codex-acp package", + "# Upgrade OpenClaw if the base image is stale.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + }, + ); + const base = runInstallBlock( + extractRunBlock( + DOCKERFILE_BASE, + "# Install OpenClaw CLI + PyYAML.", + "# Baseline health check.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + }, + ); + + expect(production.result.status).toBe(0); + expect(codexAcp.result.status).toBe(0); + expect(base.result.status).toBe(0); + expect(production.calls).toContain( + `npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`, + ); + expect(production.calls).toContain( + `npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`, + ); + expect(production.calls).toContain( + `npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`, + ); + expect(codexAcp.calls).toContain( + `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.integrity`, + ); + expect(codexAcp.calls).toContain( + `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.tarball`, + ); + expect(codexAcp.calls).toContain(`npm pack ${PINNED_CODEX_ACP_TARBALL} --pack-destination`); + expect(production.calls).toContain( + "npm install -g --no-audit --no-fund --no-progress --ignore-scripts ", + ); + expect(production.calls).toContain( + "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", + ); + expect(production.calls).toContain(`openclaw-${PINNED_OPENCLAW_VERSION}.tgz`); + expect(codexAcp.calls).toContain( + "npm install -g --no-audit --no-fund --no-progress --ignore-scripts ", + ); + expect(codexAcp.calls).toContain(`codex-acp-${PINNED_CODEX_ACP_VERSION}.tgz`); + expect(base.calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} version`); + expect(base.calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); + expect(base.calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`); + expect(base.calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); + expect(base.calls).toContain("npm install -g --ignore-scripts "); + expect(base.calls).toContain( + "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", + ); + expect(base.calls).toContain(`openclaw-${PINNED_OPENCLAW_VERSION}.tgz`); + expect(base.provenanceContent).toBe(openClawBaseProvenance()); + expect(base.provenanceMode).toBe(0o444); + }); + } + + if (group === "base") { + it("reuses exact protected OpenClaw and mcporter base provenance without registry work", () => { + const { result, calls, provenanceExists } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + installedOpenClawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + baseProvenance: openClawBaseProvenance(), + }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).toContain( + `Reusing reviewed base OpenClaw ${PINNED_OPENCLAW_VERSION} with exact provenance`, + ); + expect(calls).not.toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); + expect(calls).not.toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`); + expect(calls).not.toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); + expect(calls).not.toContain( + "npm install -g --no-audit --no-fund --no-progress --ignore-scripts ", + ); + expect(calls).not.toContain( + "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", + ); + expect(result.stdout).toContain( + `Reusing reviewed base mcporter ${PINNED_MCPORTER_VERSION} with exact lock provenance`, + ); + expect(calls).not.toContain(`npm view mcporter@${PINNED_MCPORTER_VERSION} dist.integrity`); + expect(calls).not.toContain("npm --prefix "); + expect(provenanceExists).toBe(false); + }); + + it.each([ + ["missing marker", { baseProvenance: null }], + [ + "wrong schema", + { baseProvenance: openClawBaseProvenance().replace("schema=2", "schema=1") }, + ], + [ + "wrong version", + { + baseProvenance: openClawBaseProvenance().replace( + `package=openclaw@${PINNED_OPENCLAW_VERSION}`, + "package=openclaw@2026.6.9", + ), + }, + ], + [ + "wrong integrity", + { + baseProvenance: openClawBaseProvenance().replace( + `integrity=${PINNED_OPENCLAW_INTEGRITY}`, + "integrity=sha512-drift", + ), + }, + ], + [ + "wrong tarball", + { + baseProvenance: openClawBaseProvenance().replace( + `tarball=${PINNED_OPENCLAW_TARBALL}`, + "tarball=https://registry.npmjs.org/openclaw/-/openclaw-drift.tgz", + ), + }, + ], + [ + "wrong lifecycle recipe", + { + baseProvenance: openClawBaseProvenance().replace( + "recipe=ignore-scripts+reviewed-lifecycle-v1", + "recipe=ignore-scripts-only-v1", + ), + }, + ], + [ + "wrong mcporter package", + { + baseProvenance: openClawBaseProvenance().replace( + `mcporter-package=mcporter@${PINNED_MCPORTER_VERSION}`, + "mcporter-package=mcporter@0.7.2", + ), + }, + ], + [ + "wrong mcporter integrity", + { + baseProvenance: openClawBaseProvenance().replace( + `mcporter-integrity=${PINNED_MCPORTER_INTEGRITY}`, + "mcporter-integrity=sha512-drift", + ), + }, + ], + [ + "wrong mcporter lock", + { + baseProvenance: openClawBaseProvenance().replace( + `mcporter-lock-sha256=${PINNED_MCPORTER_LOCK_SHA256}`, + `mcporter-lock-sha256=${"0".repeat(64)}`, + ), + }, + ], + [ + "wrong mcporter recipe", + { + baseProvenance: openClawBaseProvenance().replace( + "mcporter-recipe=locked-ci+audit-signatures-v1", + "mcporter-recipe=locked-ci-only-v1", + ), + }, + ], + [ + "writable marker", + { baseProvenance: openClawBaseProvenance(), baseProvenanceMetadata: "0:0:644" }, + ], + [ + "symlink marker", + { baseProvenance: openClawBaseProvenance(), baseProvenanceSymlink: true }, + ], + [ + "wrong installed version", + { + baseProvenance: openClawBaseProvenance(), + installedOpenClawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, + }, + ], + [ + "wrong installed mcporter version", + { + baseProvenance: openClawBaseProvenance(), + installedOpenClawVersion: PINNED_OPENCLAW_VERSION, + installedMcporterVersion: "0.7.2", + }, + ], + [ + "custom base reference", + { baseProvenance: openClawBaseProvenance(), baseImage: "registry.example/base:custom" }, + ], + ])("falls back to the reviewed archive for %s", (_label, overrides) => { + const { result, calls, provenanceExists } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + installedOpenClawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + ...overrides, + }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).toContain("lacks exact reviewed provenance"); + expect(calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); + expect(calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`); + expect(calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); + expect(calls).toContain( + "npm install -g --no-audit --no-fund --no-progress --ignore-scripts ", + ); + expect(calls).toContain( + "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", + ); + expect(provenanceExists).toBe(false); + }); + + it("keeps a newer unreviewed base fail-closed even when its marker claims the target", () => { + const { result, calls, provenanceExists } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + installedOpenClawVersion: "2026.6.11", + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + baseProvenance: openClawBaseProvenance(), + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `Base image has OpenClaw 2026.6.11, which is newer than reviewed target ${PINNED_OPENCLAW_VERSION}`, + ); + expect(calls).not.toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); + expect(calls).not.toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); + expect(provenanceExists).toBe(false); + }); + + it("rejects npm pack filenames outside the fresh pack directories", () => { + const production = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + packFilename: "../openclaw-2026.6.10.tgz", + }, + ); + const codexAcp = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# Pre-install the codex-acp package", + "# Upgrade OpenClaw if the base image is stale.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + packFilename: "../codex-acp-0.11.1.tgz", + }, + ); + const base = runInstallBlock( + extractRunBlock( + DOCKERFILE_BASE, + "# Install OpenClaw CLI + PyYAML.", + "# Baseline health check.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + packFilename: "../openclaw-2026.6.10.tgz", + }, + ); + const optionalPlugin = runOptionalOpenClawPluginBlock({ + pluginPackFilename: "../diagnostics-otel-2026.6.10.tgz", + }); + + for (const item of [ + { + label: "production Dockerfile", + outcome: production, + unsafeFilename: "../openclaw-2026.6.10.tgz", + blockedCommand: "npm install -g", + }, + { + label: "codex-acp Dockerfile", + outcome: codexAcp, + unsafeFilename: "../codex-acp-0.11.1.tgz", + blockedCommand: "npm install -g", + }, + { + label: "base Dockerfile", + outcome: base, + unsafeFilename: "../openclaw-2026.6.10.tgz", + blockedCommand: "npm install -g", + }, + { + label: "optional OpenClaw plugin Dockerfile", + outcome: optionalPlugin, + unsafeFilename: "../diagnostics-otel-2026.6.10.tgz", + blockedCommand: "openclaw plugins install", + }, + ]) { + expect(item.outcome.result.status, item.label).not.toBe(0); + expect( + `${item.outcome.result.stdout}${item.outcome.result.stderr}`, + item.label, + ).toContain(`npm pack reported unsafe archive filename: ${item.unsafeFilename}`); + expect(item.outcome.calls, item.label).toContain("npm pack"); + expect(item.outcome.calls, item.label).not.toContain(item.blockedCommand); + } + }); + + it("reports missing base-image npm pack filenames on stderr", () => { + const { result, calls } = runInstallBlock( + extractRunBlock( + DOCKERFILE_BASE, + "# Install OpenClaw CLI + PyYAML.", + "# Baseline health check.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + packFilename: null, + }, + ); + const diagnostic = `OpenClaw ${PINNED_OPENCLAW_VERSION} npm pack did not report filename and integrity`; + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain(diagnostic); + expect(result.stdout).not.toContain(diagnostic); + expect(calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); + expect(calls).not.toContain("npm install -g"); + }); + } + + if (group === "contract") { + it("rejects legacy fixture pins unless stale-upgrade fixture mode is explicit", () => { + const production = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + { + openclawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, + registryIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, + registryTarball: LEGACY_REBUILD_OPENCLAW_TARBALL, + packIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, + }, + ); + const base = runInstallBlock( + extractRunBlock( + DOCKERFILE_BASE, + "# Install OpenClaw CLI + PyYAML.", + "# Baseline health check.", + ), + { + openclawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, + registryIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, + registryTarball: LEGACY_REBUILD_OPENCLAW_TARBALL, + packIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, + }, + ); + const fixtureBase = runInstallBlock( + extractRunBlock( + DOCKERFILE_BASE, + "# Install OpenClaw CLI + PyYAML.", + "# Baseline health check.", + ), + { + openclawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, + registryIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, + registryTarball: LEGACY_REBUILD_OPENCLAW_TARBALL, + packIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, + allowLegacyFixture: true, + }, + ); + const gatewayFixtureBase = runInstallBlock( + extractRunBlock( + DOCKERFILE_BASE, + "# Install OpenClaw CLI + PyYAML.", + "# Baseline health check.", + ), + { + openclawVersion: LEGACY_GATEWAY_UPGRADE_OPENCLAW_VERSION, + registryIntegrity: LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY, + registryTarball: LEGACY_GATEWAY_UPGRADE_OPENCLAW_TARBALL, + packIntegrity: LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY, + allowLegacyFixture: true, + }, + ); + + for (const rejected of [production, base]) { + expect(rejected.result.status).not.toBe(0); + expect(`${rejected.result.stdout}${rejected.result.stderr}`).toContain( + `OpenClaw ${LEGACY_REBUILD_OPENCLAW_VERSION} is a legacy E2E fixture pin`, + ); + expect(rejected.calls).not.toContain("npm install -g"); + } + expect(fixtureBase.result.status).toBe(0); + expect(fixtureBase.calls).toContain( + `npm view openclaw@${LEGACY_REBUILD_OPENCLAW_VERSION} version`, + ); + expect(fixtureBase.calls).toContain( + `npm view openclaw@${LEGACY_REBUILD_OPENCLAW_VERSION} dist.integrity`, + ); + expect(fixtureBase.calls).toContain( + `npm view openclaw@${LEGACY_REBUILD_OPENCLAW_VERSION} dist.tarball`, + ); + expect(fixtureBase.calls).toContain( + `npm pack ${LEGACY_REBUILD_OPENCLAW_TARBALL} --pack-destination`, + ); + expect(fixtureBase.calls).toContain(`openclaw-${LEGACY_REBUILD_OPENCLAW_VERSION}.tgz`); + expect(fixtureBase.calls).toContain("npm install -g --ignore-scripts "); + expect(fixtureBase.calls).not.toContain("postinstall-bundled-plugins.mjs"); + expect(gatewayFixtureBase.result.status).toBe(0); + expect(gatewayFixtureBase.calls).toContain("npm install -g --ignore-scripts "); + expect(gatewayFixtureBase.calls).toContain( + "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", + ); + }); + + it("guards production Docker build args from legacy OpenClaw fixture inputs", () => { + expect(runProductionBuildArgGuard(["--build-arg", "BASE_IMAGE=base"]).status).toBe(0); + expect( + runProductionBuildArgGuard(["--build-arg=NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=0"]).status, + ).toBe(0); + expect( + runProductionBuildArgGuard(["--build-arg", `OPENCLAW_VERSION=${PINNED_OPENCLAW_VERSION}`]) + .status, + ).toBe(0); + + for (const args of [ + ["--build-arg", "NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"], + ["--build-arg=NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"], + ["NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"], + ]) { + const result = runProductionBuildArgGuard(args); + expect(result.status, args.join(" ")).toBe(1); + expect(result.stderr).toContain( + "only allowed in explicit stale-upgrade E2E fixture builds", + ); + } + + const envResult = runProductionBuildArgGuard([], { + NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW: "1", + }); + expect(envResult.status).toBe(1); + expect(envResult.stderr).toContain("production Docker image build args"); + + for (const args of [ + ["--build-arg", `OPENCLAW_VERSION=${LEGACY_REBUILD_OPENCLAW_VERSION}`], + ["--build-arg=OPENCLAW_VERSION=2026.4.24"], + ["OPENCLAW_2026_3_11_INTEGRITY=sha512-fixture"], + ["--build-arg=OPENCLAW_2026_4_24_TARBALL=https://fixture.invalid/package.tgz"], + ]) { + const result = runProductionBuildArgGuard(args); + expect(result.status, args.join(" ")).toBe(1); + expect(result.stderr).toContain("not allowed in production image builds"); + } + + const legacyEnvCases: ReadonlyArray> = [ + { OPENCLAW_VERSION: LEGACY_REBUILD_OPENCLAW_VERSION }, + { OPENCLAW_VERSION: "2026.4.24" }, + { OPENCLAW_2026_3_11_TARBALL: LEGACY_REBUILD_OPENCLAW_TARBALL }, + { OPENCLAW_2026_4_24_INTEGRITY: LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY }, + ]; + for (const env of legacyEnvCases) { + const result = runProductionBuildArgGuard([], env); + expect(result.status, JSON.stringify(env)).toBe(1); + expect(result.stderr).toContain("not allowed in production image builds"); + } + + for (const args of [ + [ + "--build-arg", + `OPENCLAW_VERSION=${PINNED_OPENCLAW_VERSION}\nNEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\nOPENCLAW_VERSION=2026.4.24`, + ], + [`--build-arg=OPENCLAW_VERSION=${PINNED_OPENCLAW_VERSION}\r`], + ["BASE_IMAGE=base\nINJECTED=value"], + ["--build-arg\r"], + ]) { + const result = runProductionBuildArgGuard(args); + expect(result.status, JSON.stringify(args)).toBe(1); + expect(result.stderr).toContain("must not contain CR or LF characters"); + } + }); + + it("production build arg guard rejects current reviewed pin overrides", () => { + const currentPinArgNames = declaredProductionPinArgNames(); + expect(currentPinArgNames).toEqual([ + "CODEX_ACP_0_11_1_INTEGRITY", + "HERMES_NPM_INTEGRITY", + "MCPORTER_0_7_3_INTEGRITY", + "OPENCLAW_2026_3_11_INTEGRITY", + "OPENCLAW_2026_3_11_TARBALL", + "OPENCLAW_2026_4_24_INTEGRITY", + "OPENCLAW_2026_4_24_TARBALL", + "OPENCLAW_2026_6_10_INTEGRITY", + "OPENCLAW_2026_6_10_TARBALL", + "OPENCLAW_BRAVE_PLUGIN_2026_6_10_INTEGRITY", + "OPENCLAW_DIAGNOSTICS_OTEL_2026_6_10_INTEGRITY", + ]); + + const futurePinArgNames = [ + "OPENCLAW_FUTURE_PLUGIN_2099_1_1_INTEGRITY", + "FUTURE_DEPENDENCY_2099_1_1_TARBALL", + ]; + for (const pinArgName of [...currentPinArgNames, ...futurePinArgNames]) { + for (const args of [ + [`${pinArgName}=attacker-controlled`], + [`--build-arg=${pinArgName}=attacker-controlled`], + ["--build-arg", `${pinArgName}=attacker-controlled`], + ["--build-arg", pinArgName], + ]) { + const result = runProductionBuildArgGuard(args); + expect(result.status, args.join(" ")).toBe(1); + expect(result.stderr).toContain("pin overrides are not allowed"); + } + } + + for (const pinArgName of currentPinArgNames) { + const envResult = runProductionBuildArgGuard([], { [pinArgName]: "attacker-controlled" }); + expect(envResult.status, pinArgName).toBe(1); + expect(envResult.stderr).toContain("pin overrides are not allowed"); + } + + expect(runProductionBuildArgGuard([], { RELEASE_INTEGRITY: "verified" }).status).toBe(0); + expect(runProductionBuildArgGuard([], { SOURCE_TARBALL: "source.tgz" }).status).toBe(0); + }); + } + + if (group === "plugin-install") { + it("fails closed before npm install when the registry integrity drifts", () => { + const installBlocks = [ + { + label: "production Dockerfile", + file: DOCKERFILE, + startMarker: "# OPENCLAW_VERSION is the NemoClaw runtime build target", + endMarker: "# Patch OpenClaw media fetch", + }, + { + label: "base Dockerfile", + file: DOCKERFILE_BASE, + startMarker: "# Install OpenClaw CLI + PyYAML.", + endMarker: "# Baseline health check.", + }, + ]; + + for (const block of installBlocks) { + const { result, calls } = runInstallBlock( + extractRunBlock(block.file, block.startMarker, block.endMarker), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: "sha512-registry-drift", + }, + ); + const output = `${result.stdout}${result.stderr}`; + + expect(result.status, block.label).not.toBe(0); + expect(output, block.label).toContain( + `OpenClaw ${PINNED_OPENCLAW_VERSION} npm integrity mismatch`, + ); + expect(output, block.label).toContain(`Expected: ${PINNED_OPENCLAW_INTEGRITY}`); + expect(output, block.label).toContain("Actual: sha512-registry-drift"); + expect(calls, block.label).toContain( + `npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`, + ); + expect(calls, block.label).not.toContain("npm install -g"); + } + }); + + it("fails closed before npm install when the downloaded OpenClaw tarball integrity drifts", () => { + const { result, calls } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + packIntegrity: "sha512-downloaded-drift", + }, + ); + const output = `${result.stdout}${result.stderr}`; + + expect(result.status).not.toBe(0); + expect(output).toContain( + `OpenClaw ${PINNED_OPENCLAW_VERSION} downloaded tarball integrity mismatch`, + ); + expect(output).toContain(`Expected: ${PINNED_OPENCLAW_INTEGRITY}`); + expect(output).toContain("Actual: sha512-downloaded-drift"); + expect(calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); + expect(calls).not.toContain("npm install -g"); + }); + + it("fails closed before npm install for unpinned production Dockerfile overrides", () => { + const { result, calls } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# OPENCLAW_VERSION is the NemoClaw runtime build target", + "# Patch OpenClaw media fetch", + ), + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `OpenClaw ${UNPINNED_OPENCLAW_VERSION} has no committed npm integrity pin`, + ); + expect(calls).not.toContain("npm install -g"); + }); + + it("fails closed before installing codex-acp when its registry integrity drifts", () => { + const { result, calls } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# Pre-install the codex-acp package", + "# Upgrade OpenClaw if the base image is stale.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + codexAcpCommittedIntegrity: PINNED_CODEX_ACP_INTEGRITY, + codexAcpRegistryIntegrity: "sha512-codex-acp-drift", + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} npm integrity mismatch`, + ); + expect(`${result.stdout}${result.stderr}`).toContain( + `Expected: ${PINNED_CODEX_ACP_INTEGRITY}`, + ); + expect(`${result.stdout}${result.stderr}`).toContain("Actual: sha512-codex-acp-drift"); + expect(calls).toContain( + `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.integrity`, + ); + expect(calls).not.toContain( + `npm install -g --no-audit --no-fund --no-progress ${PINNED_CODEX_ACP_TARBALL}`, + ); + }); + + it("fails closed before installing codex-acp when its registry tarball URL drifts", () => { + const { result, calls } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# Pre-install the codex-acp package", + "# Upgrade OpenClaw if the base image is stale.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + codexAcpCommittedIntegrity: PINNED_CODEX_ACP_INTEGRITY, + codexAcpRegistryIntegrity: PINNED_CODEX_ACP_INTEGRITY, + codexAcpRegistryTarball: + "https://registry.npmjs.org/@zed-industries/codex-acp/-/codex-acp-0.11.2.tgz", + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} npm tarball URL mismatch`, + ); + expect(`${result.stdout}${result.stderr}`).toContain( + `Expected: ${PINNED_CODEX_ACP_TARBALL}`, + ); + expect(`${result.stdout}${result.stderr}`).toContain( + "Actual: https://registry.npmjs.org/@zed-industries/codex-acp/-/codex-acp-0.11.2.tgz", + ); + expect(calls).toContain( + `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.tarball`, + ); + expect(calls).not.toContain( + `npm install -g --no-audit --no-fund --no-progress ${PINNED_CODEX_ACP_TARBALL}`, + ); + }); + + it("fails closed before installing codex-acp when its downloaded tarball integrity drifts", () => { + const { result, calls } = runInstallBlock( + extractRunBlock( + DOCKERFILE, + "# Pre-install the codex-acp package", + "# Upgrade OpenClaw if the base image is stale.", + ), + { + openclawVersion: PINNED_OPENCLAW_VERSION, + committedIntegrity: PINNED_OPENCLAW_INTEGRITY, + registryIntegrity: PINNED_OPENCLAW_INTEGRITY, + codexAcpCommittedIntegrity: PINNED_CODEX_ACP_INTEGRITY, + codexAcpRegistryIntegrity: PINNED_CODEX_ACP_INTEGRITY, + codexAcpPackIntegrity: "sha512-codex-downloaded-drift", + }, + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} downloaded tarball integrity mismatch`, + ); + expect(`${result.stdout}${result.stderr}`).toContain( + `Expected: ${PINNED_CODEX_ACP_INTEGRITY}`, + ); + expect(`${result.stdout}${result.stderr}`).toContain( + "Actual: sha512-codex-downloaded-drift", + ); + expect(calls).toContain(`npm pack ${PINNED_CODEX_ACP_TARBALL} --pack-destination`); + expect(calls).not.toContain("npm install -g"); + }); + + it("fails closed before npm install for unpinned base Dockerfile overrides", () => { + const { result, calls } = runInstallBlock( + extractRunBlock( + DOCKERFILE_BASE, + "# Install OpenClaw CLI + PyYAML.", + "# Baseline health check.", + ), + ); + + expect(result.status).not.toBe(0); + expect(`${result.stdout}${result.stderr}`).toContain( + `OpenClaw ${UNPINNED_OPENCLAW_VERSION} has no committed npm integrity pin`, + ); + expect(calls).not.toContain("npm install -g"); + }); + } + }); +} diff --git a/test/openclaw-integrity-pin.test.ts b/test/openclaw-integrity-pin.test.ts deleted file mode 100644 index 2be4da0b21a..00000000000 --- a/test/openclaw-integrity-pin.test.ts +++ /dev/null @@ -1,1356 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { spawnSync } from "node:child_process"; -import { createHash } from "node:crypto"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { describe, expect, it } from "vitest"; -import { createBuiltInChannelManifestRegistry } from "../src/lib/messaging"; -import { reviewedOpenClawPluginIntegrityByPackageSpec } from "../src/lib/messaging/applier/build/messaging-build-applier.mts"; - -const REPO_ROOT = path.join(import.meta.dirname, ".."); -const DOCKERFILE = path.join(REPO_ROOT, "Dockerfile"); -const DOCKERFILE_BASE = path.join(REPO_ROOT, "Dockerfile.base"); -const PRODUCTION_DOCKERFILES = [ - DOCKERFILE, - DOCKERFILE_BASE, - path.join(REPO_ROOT, "agents", "hermes", "Dockerfile"), - path.join(REPO_ROOT, "agents", "hermes", "Dockerfile.base"), - path.join(REPO_ROOT, "agents", "langchain-deepagents-code", "Dockerfile"), - path.join(REPO_ROOT, "agents", "langchain-deepagents-code", "Dockerfile.base"), -]; -const BLUEPRINT = path.join(REPO_ROOT, "nemoclaw-blueprint", "blueprint.yaml"); -const DEPENDENCY_REVIEW_NOTE = path.join( - REPO_ROOT, - "docs", - "security", - "openclaw-2026.6.10-dependency-review.md", -); -const PRODUCTION_BUILD_ARG_GUARD = path.join( - REPO_ROOT, - "scripts", - "check-production-build-args.sh", -); -const UNPINNED_OPENCLAW_VERSION = "2026.6.11"; -const PINNED_OPENCLAW_VERSION = "2026.6.10"; -const PINNED_OPENCLAW_INTEGRITY = - "sha512-LcooND2tBQw8A+kc1Ujltu3lg30bJ0w7XaeRy7eYzobb8BBdcW6DOGbwJL4vpj1vl9+gjRceOtlh5nh9OARcug=="; -const PINNED_OPENCLAW_TARBALL = "https://registry.npmjs.org/openclaw/-/openclaw-2026.6.10.tgz"; -const PINNED_CODEX_ACP_VERSION = "0.11.1"; -const PINNED_CODEX_ACP_TARBALL = - "https://registry.npmjs.org/@zed-industries/codex-acp/-/codex-acp-0.11.1.tgz"; -const PINNED_CODEX_ACP_INTEGRITY = - "sha512-My2VSlBtvJipJhImHjFDej2ut/p00QqOISRnZgLgLrSIzjgvdcQvAhaZviWj7XPhk4UIdIb0OoA+Lrls824uiQ=="; -const PINNED_MCPORTER_VERSION = "0.7.3"; -const PINNED_MCPORTER_INTEGRITY = - "sha512-egoPVYqTnWb3NjRIxo+xc8OrAI0dlPrJm9pAiZx0pImuNIV5rKhGtTnIfH/Y1ldGPVu74ibj3KR5c9U/QSdQFA=="; -const MCPORTER_LOCKFILE = path.join( - REPO_ROOT, - "agents", - "openclaw", - "mcporter-runtime", - "package-lock.json", -); -const PINNED_MCPORTER_LOCK_SHA256 = createHash("sha256") - .update(fs.readFileSync(MCPORTER_LOCKFILE)) - .digest("hex"); -const PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY = - "sha512-EJt0fjk4bcR3N/9u00f1pL0BJYG5yfC09DV3l6rWDmytpE2vUeBZWpx4pOmFDreGV+7DKxhCbQDgDAmvZGjLag=="; -const PINNED_OPENCLAW_DIAGNOSTICS_OTEL_TARBALL = - "https://registry.npmjs.org/@openclaw/diagnostics-otel/-/diagnostics-otel-2026.6.10.tgz"; -const PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY = - "sha512-DDRnb4reL99O8kbISNbRFyk/xoUPYHsXG3UGikKAsVs+zIldYYA0hY0d3Z2aWoE+0vfda27mJUByCo7Xr15qdw=="; -const PINNED_OPENCLAW_BRAVE_PLUGIN_TARBALL = - "https://registry.npmjs.org/@openclaw/brave-plugin/-/brave-plugin-2026.6.10.tgz"; -const PINNED_OPENCLAW_DISCORD_INTEGRITY = - "sha512-NKp/j00l+rk5PC0Lv/0fOIiiQJ1c/OpG9471zqXUDKQie6pQ1Fi9KUZUouyoTMmfLh/n4S0CkEMqrON40eBKXA=="; -const PINNED_OPENCLAW_SLACK_INTEGRITY = - "sha512-OOsMLjPcbWhQRM5XDwfdrACjJmKqavFtpuIlhHAXWrLrd/p7SyIVE9AoKS0yxOx6bqGDIMJ9+knzdViHMLgBdA=="; -const PINNED_OPENCLAW_WHATSAPP_INTEGRITY = - "sha512-k/XrRdZY77SHrdaRwJOEB7/JRbjp4yVgGD/ZNyakjTMqo32XRVtwPBUnj7726rW8Kl5yyOMQQLKFiD9MDfhmPQ=="; -const PINNED_OPENCLAW_MSTEAMS_INTEGRITY = - "sha512-GjHnCPvjbnI0C7mEFcdT2uKDH4/WwOe2dZBfQiWxBtkE76m6TNG0J9dJjD4mc8/pk8rXSO0cWw+KV9jzWtF9VA=="; -const PINNED_WECHAT_PLUGIN_INTEGRITY = - "sha512-dPQbidUNWigC6V10vGW4i+GLH09x+6zUhafZRjuxkJ9GDu8o62WBsnUTojp4KqUH756hz+t2v9khiCRSi0dBDw=="; -const LEGACY_REBUILD_OPENCLAW_VERSION = "2026.3.11"; -const LEGACY_REBUILD_OPENCLAW_INTEGRITY = - "sha512-bxwiBmHPakwfpY5tqC9lrV5TCu5PKf0c1bHNc3nhrb+pqKcPEWV4zOjDVFLQUHr98ihgWA+3pacy4b3LQ8wduQ=="; -const LEGACY_REBUILD_OPENCLAW_TARBALL = - "https://registry.npmjs.org/openclaw/-/openclaw-2026.3.11.tgz"; -const LEGACY_GATEWAY_UPGRADE_OPENCLAW_VERSION = "2026.4.24"; -const LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY = - "sha512-W6u4XeIIP4+uG4DYV9G3JeS6QNuKwfhQIej1GIoL4BdcnUFgrnB8kHYNXL3MxiHRKuhZB9OYwUMGs8jKFZR/Vg=="; -const LEGACY_GATEWAY_UPGRADE_OPENCLAW_TARBALL = - "https://registry.npmjs.org/openclaw/-/openclaw-2026.4.24.tgz"; -const OPENCLAW_BASE_PROVENANCE_PATH = "/usr/local/share/nemoclaw/openclaw-base-provenance-v1"; - -function openClawBaseProvenance( - version = PINNED_OPENCLAW_VERSION, - integrity = PINNED_OPENCLAW_INTEGRITY, - tarball = PINNED_OPENCLAW_TARBALL, -): string { - return [ - "schema=2", - `package=openclaw@${version}`, - `integrity=${integrity}`, - `tarball=${tarball}`, - "recipe=ignore-scripts+reviewed-lifecycle-v1", - `mcporter-package=mcporter@${PINNED_MCPORTER_VERSION}`, - `mcporter-integrity=${PINNED_MCPORTER_INTEGRITY}`, - `mcporter-lock-sha256=${PINNED_MCPORTER_LOCK_SHA256}`, - "mcporter-recipe=locked-ci+audit-signatures-v1", - "", - ].join("\n"); -} - -function extractRunBlock(file: string, startMarker: string, endMarker: string): string { - const source = fs.readFileSync(file, "utf-8"); - const start = source.indexOf(startMarker); - const end = source.indexOf(endMarker, start); - expect(start, `Expected start marker in ${file}: ${startMarker}`).toBeGreaterThanOrEqual(0); - expect(end, `Expected end marker in ${file}: ${endMarker}`).toBeGreaterThan(start); - const runIndex = source.indexOf("RUN ", start); - expect(runIndex, `Expected RUN instruction after ${startMarker}`).toBeGreaterThanOrEqual(0); - expect(runIndex, `Expected RUN instruction before ${endMarker}`).toBeLessThanOrEqual(end); - return source - .slice(runIndex, end) - .trim() - .replace(/^RUN\s+--mount=[^\n]+\\\n\s*/, "") - .replace(/^RUN\s+/, "") - .split("\n") - .filter((line) => !line.trimStart().startsWith("#")) - .join("\n") - .replace(/\\\n/g, " ") - .replace(/\\\s*$/, ""); -} - -function runInstallBlock( - command: string, - options: { - openclawVersion?: string; - committedIntegrity?: string; - registryIntegrity?: string; - registryTarball?: string; - packIntegrity?: string; - codexAcpCommittedIntegrity?: string; - codexAcpRegistryIntegrity?: string; - codexAcpRegistryTarball?: string; - codexAcpPackIntegrity?: string; - packFilename?: string | null; - allowLegacyFixture?: boolean; - installedOpenClawVersion?: string; - installedMcporterVersion?: string; - baseImage?: string; - baseProvenance?: string | null; - baseProvenanceMetadata?: string; - baseProvenanceSymlink?: boolean; - } = {}, -) { - const { - openclawVersion = UNPINNED_OPENCLAW_VERSION, - committedIntegrity = "sha512-reviewed-pin", - registryIntegrity = committedIntegrity, - registryTarball = PINNED_OPENCLAW_TARBALL, - packIntegrity = committedIntegrity, - codexAcpCommittedIntegrity = PINNED_CODEX_ACP_INTEGRITY, - codexAcpRegistryIntegrity = codexAcpCommittedIntegrity, - codexAcpRegistryTarball = PINNED_CODEX_ACP_TARBALL, - codexAcpPackIntegrity = codexAcpCommittedIntegrity, - packFilename, - allowLegacyFixture = false, - installedOpenClawVersion = LEGACY_REBUILD_OPENCLAW_VERSION, - installedMcporterVersion = PINNED_MCPORTER_VERSION, - baseImage = "ghcr.io/nvidia/nemoclaw/sandbox-base@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - baseProvenance = null, - baseProvenanceMetadata = "0:0:444", - baseProvenanceSymlink = false, - } = options; - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-integrity-")); - const blueprint = path.join(tmp, "blueprint.yaml"); - const log = path.join(tmp, "calls.log"); - const provenancePath = path.join(tmp, "openclaw-base-provenance-v1"); - const mcporterRuntime = path.join(tmp, "mcporter-runtime"); - const mcporterBin = path.join(tmp, "bin", "mcporter"); - fs.mkdirSync(path.dirname(mcporterBin), { recursive: true }); - fs.mkdirSync(mcporterRuntime, { recursive: true }); - fs.copyFileSync(MCPORTER_LOCKFILE, path.join(mcporterRuntime, "package-lock.json")); - fs.writeFileSync(blueprint, fs.readFileSync(BLUEPRINT, "utf-8")); - const writeProvenanceFile = () => { - fs.writeFileSync(provenancePath, baseProvenance as string, { mode: 0o444 }); - }; - const writeProvenanceSymlink = () => { - const target = path.join(tmp, "openclaw-base-provenance-target"); - fs.writeFileSync(target, baseProvenance as string); - fs.symlinkSync(target, provenancePath); - }; - const writePresentProvenance = baseProvenanceSymlink - ? writeProvenanceSymlink - : writeProvenanceFile; - const setupProvenance = baseProvenance === null ? () => undefined : writePresentProvenance; - setupProvenance(); - const script = [ - "#!/usr/bin/env bash", - "set -euo pipefail", - `call_log=${JSON.stringify(log)}`, - `real_node=${JSON.stringify(process.execPath)}`, - `OPENCLAW_VERSION=${JSON.stringify(openclawVersion)}`, - `BASE_IMAGE=${JSON.stringify(baseImage)}`, - `openclaw_provenance_path=${JSON.stringify(provenancePath)}`, - `openclaw_provenance_metadata=${JSON.stringify(baseProvenanceMetadata)}`, - `OPENCLAW_2026_6_10_INTEGRITY=${JSON.stringify(committedIntegrity)}`, - `OPENCLAW_2026_6_10_TARBALL=${JSON.stringify(PINNED_OPENCLAW_TARBALL)}`, - `NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=${allowLegacyFixture ? "1" : "0"}`, - `OPENCLAW_2026_3_11_INTEGRITY=${JSON.stringify(LEGACY_REBUILD_OPENCLAW_INTEGRITY)}`, - `OPENCLAW_2026_3_11_TARBALL=${JSON.stringify(LEGACY_REBUILD_OPENCLAW_TARBALL)}`, - `OPENCLAW_2026_4_24_INTEGRITY=${JSON.stringify(LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY)}`, - `OPENCLAW_2026_4_24_TARBALL=${JSON.stringify(LEGACY_GATEWAY_UPGRADE_OPENCLAW_TARBALL)}`, - `CODEX_ACP_0_11_1_INTEGRITY=${JSON.stringify(codexAcpCommittedIntegrity)}`, - `MCPORTER_VERSION=${JSON.stringify(PINNED_MCPORTER_VERSION)}`, - `MCPORTER_0_7_3_INTEGRITY=${JSON.stringify(PINNED_MCPORTER_INTEGRITY)}`, - `installed_openclaw_version=${JSON.stringify(installedOpenClawVersion)}`, - `installed_mcporter_version=${JSON.stringify(installedMcporterVersion)}`, - "node() {", - ' if [ "${1:-}" = "/usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs" ]; then printf "node %s\\n" "$*" >> "$call_log"; return 0; fi', - ' "$real_node" "$@"', - "}", - `openclaw() { if [ "\${1:-}" = "--version" ]; then printf 'openclaw %s\\n' "$installed_openclaw_version"; else return 127; fi; }`, - 'mcporter() { if [ "${1:-}" = "--version" ]; then printf "%s\\n" "$installed_mcporter_version"; else return 127; fi; }', - "codex-acp() { :; }", - "stat() {", - ' if [ "${1:-}" = "-c" ] && [ "${3:-}" = "$openclaw_provenance_path" ]; then printf "%s\\n" "$openclaw_provenance_metadata"; return 0; fi', - ' command stat "$@"', - "}", - "npm() {", - ' printf "npm %s\\n" "$*" >> "$call_log";', - ' [ "${1:-}" != "--prefix" ] || [ "${3:-}" != "ci" ] || installed_mcporter_version="$MCPORTER_VERSION"', - ' if [ "${1:-}" = "view" ] && [ "${3:-}" = "version" ]; then printf "%s\\n" "$OPENCLAW_VERSION"; return 0; fi', - ` if [ "\${1:-}" = "view" ] && [ "\${2:-}" = "@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION}" ] && [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(codexAcpRegistryIntegrity)}; return 0; fi`, - ` if [ "\${1:-}" = "view" ] && [ "\${2:-}" = "@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION}" ] && [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(codexAcpRegistryTarball)}; return 0; fi`, - ` if [ "\${1:-}" = "view" ] && [ "\${2:-}" = "mcporter@${PINNED_MCPORTER_VERSION}" ] && [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(PINNED_MCPORTER_INTEGRITY)}; return 0; fi`, - ` if [ "\${1:-}" = "view" ] && [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(registryIntegrity)}; return 0; fi`, - ` if [ "\${1:-}" = "view" ] && [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(registryTarball)}; return 0; fi`, - ' if [ "${1:-}" = "pack" ]; then', - ' pack_spec="${2:-}"; pack_dir="";', - ' while [ "$#" -gt 0 ]; do', - ' if [ "${1:-}" = "--pack-destination" ]; then pack_dir="${2:-}"; shift 2; continue; fi', - " shift", - " done", - ' test -n "$pack_dir";', - ' pack_file="$(basename "$pack_spec")";', - ' case "$pack_file" in *.tgz) ;; *) pack_file="${pack_file}.tgz" ;; esac', - ` reported_pack_file=${JSON.stringify(packFilename ?? "")}`, - ...(packFilename === null - ? [] - : [' reported_pack_file="${reported_pack_file:-$pack_file}"']), - ' printf "fake tarball" > "$pack_dir/$pack_file";', - ` case "$pack_spec" in *"codex-acp"*) pack_integrity=${JSON.stringify(codexAcpPackIntegrity)} ;; *) pack_integrity=${JSON.stringify(packIntegrity)} ;; esac`, - ' printf \'[{"filename":"%s","integrity":"%s"}]\\n\' "$reported_pack_file" "$pack_integrity";', - " return 0", - " fi", - ' if [ "${1:-}" = "install" ] && printf "%s\\n" "$*" | grep -q "openclaw-"; then installed_openclaw_version="$OPENCLAW_VERSION"; fi', - "}", - "pip3() { return 0; }", - command - .replaceAll("/opt/nemoclaw-blueprint/blueprint.yaml", blueprint) - .replaceAll("/tmp/blueprint.yaml", blueprint) - .replaceAll(OPENCLAW_BASE_PROVENANCE_PATH, provenancePath) - .replaceAll("/usr/local/lib/nemoclaw/mcporter-runtime", mcporterRuntime) - .replaceAll("/usr/local/bin/mcporter", mcporterBin), - ].join("\n"); - const scriptPath = path.join(tmp, "run.sh"); - fs.writeFileSync(scriptPath, script, { mode: 0o700 }); - const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 10000 }); - const calls = fs.existsSync(log) ? fs.readFileSync(log, "utf-8") : ""; - const provenanceExists = fs.existsSync(provenancePath); - const provenanceContent = provenanceExists ? fs.readFileSync(provenancePath, "utf-8") : null; - const provenanceMode = provenanceExists ? fs.statSync(provenancePath).mode & 0o777 : null; - fs.rmSync(tmp, { recursive: true, force: true }); - return { result, calls, provenanceExists, provenanceContent, provenanceMode }; -} - -function runProductionBuildArgGuard( - args: string[], - env: Record = {}, -): ReturnType { - return spawnSync("bash", [PRODUCTION_BUILD_ARG_GUARD, ...args], { - cwd: REPO_ROOT, - encoding: "utf-8", - env: { ...process.env, ...env }, - }); -} - -function declaredProductionPinArgNames(): string[] { - const names = PRODUCTION_DOCKERFILES.flatMap((dockerfile) => - fs - .readFileSync(dockerfile, "utf-8") - .split("\n") - .flatMap((line) => { - const match = /^ARG ([A-Z_][A-Z0-9_]*(?:_INTEGRITY|_TARBALL))(?:=|$)/.exec(line); - return match?.[1] ? [match[1]] : []; - }), - ); - return [...new Set(names)].sort(); -} - -function runOptionalOpenClawPluginBlock( - options: { - openclawVersion?: string; - otel?: boolean; - webSearch?: boolean; - diagnosticsRegistryIntegrity?: string; - diagnosticsRegistryTarball?: string; - braveRegistryIntegrity?: string; - braveRegistryTarball?: string; - pluginPackFilename?: string; - } = {}, -) { - const { - openclawVersion = PINNED_OPENCLAW_VERSION, - otel = true, - webSearch = true, - diagnosticsRegistryIntegrity = PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY, - diagnosticsRegistryTarball = PINNED_OPENCLAW_DIAGNOSTICS_OTEL_TARBALL, - braveRegistryIntegrity = PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY, - braveRegistryTarball = PINNED_OPENCLAW_BRAVE_PLUGIN_TARBALL, - pluginPackFilename = "", - } = options; - const command = extractRunBlock( - DOCKERFILE, - "# Install non-messaging OpenClaw plugins that need to match the runtime.", - 'RUN OPENCLAW_VERSION="${OPENCLAW_VERSION}" node --experimental-strip-types /src/lib/messaging/applier/build/messaging-build-applier.mts', - ); - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-plugin-integrity-")); - const log = path.join(tmp, "calls.log"); - const script = [ - "#!/usr/bin/env bash", - "set -euo pipefail", - `call_log=${JSON.stringify(log)}`, - `OPENCLAW_VERSION=${JSON.stringify(openclawVersion)}`, - `OPENCLAW_DIAGNOSTICS_OTEL_2026_6_10_INTEGRITY=${JSON.stringify(PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY)}`, - `OPENCLAW_BRAVE_PLUGIN_2026_6_10_INTEGRITY=${JSON.stringify(PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY)}`, - `NEMOCLAW_OPENCLAW_OTEL=${otel ? "1" : "0"}`, - `NEMOCLAW_WEB_SEARCH_ENABLED=${webSearch ? "1" : "0"}`, - 'openclaw() { printf \'openclaw %s\\nopenclaw-env %s %s\\n\' "$*" "${NPM_CONFIG_IGNORE_SCRIPTS:-}" "${npm_config_ignore_scripts:-}" >> "$call_log"; }', - "npm() {", - ' printf "npm %s\\n" "$*" >> "$call_log";', - ' if [ "${1:-}" = "pack" ]; then', - ' pack_spec="${2:-}"; pack_dir="";', - ' while [ "$#" -gt 0 ]; do', - ' if [ "${1:-}" = "--pack-destination" ]; then pack_dir="${2:-}"; shift 2; continue; fi', - " shift", - " done", - ' test -n "$pack_dir"; pack_file="$(basename "$pack_spec")";', - ` reported_pack_file=${JSON.stringify(pluginPackFilename)}`, - ' reported_pack_file="${reported_pack_file:-$pack_file}"', - ' printf "fake plugin tarball" > "$pack_dir/$pack_file";', - ' case "$pack_spec" in', - ` *"diagnostics-otel"*) printf '[{"filename":"%s","integrity":"%s"}]\\n' "$reported_pack_file" ${JSON.stringify(diagnosticsRegistryIntegrity)}; return 0 ;;`, - ` *"brave-plugin"*) printf '[{"filename":"%s","integrity":"%s"}]\\n' "$reported_pack_file" ${JSON.stringify(braveRegistryIntegrity)}; return 0 ;;`, - " esac", - " return 1", - " fi", - ' if [ "${1:-}" != "view" ]; then exit 1; fi', - ' case "${2:-}" in', - ` "@openclaw/diagnostics-otel@${PINNED_OPENCLAW_VERSION}") if [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(diagnosticsRegistryIntegrity)}; return 0; fi; if [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(diagnosticsRegistryTarball)}; return 0; fi ;;`, - ` "@openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION}") if [ "\${3:-}" = "dist.integrity" ]; then printf "%s\\n" ${JSON.stringify(braveRegistryIntegrity)}; return 0; fi; if [ "\${3:-}" = "dist.tarball" ]; then printf "%s\\n" ${JSON.stringify(braveRegistryTarball)}; return 0; fi ;;`, - " esac", - " return 1", - "}", - command, - ].join("\n"); - const scriptPath = path.join(tmp, "run.sh"); - fs.writeFileSync(scriptPath, script, { mode: 0o700 }); - const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", timeout: 10000 }); - const calls = fs.existsSync(log) ? fs.readFileSync(log, "utf-8") : ""; - fs.rmSync(tmp, { recursive: true, force: true }); - return { result, calls }; -} - -describe("OpenClaw npm integrity pins", () => { - it("keeps the advisory review note aligned with the committed OpenClaw pin", () => { - const reviewNote = fs.readFileSync(DEPENDENCY_REVIEW_NOTE, "utf-8"); - - expect(reviewNote).toContain(`openclaw@${PINNED_OPENCLAW_VERSION}`); - expect(reviewNote).toContain(PINNED_OPENCLAW_INTEGRITY); - expect(reviewNote).toContain(PINNED_OPENCLAW_TARBALL); - expect(reviewNote).toContain(`@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION}`); - expect(reviewNote).toContain(PINNED_CODEX_ACP_TARBALL); - expect(reviewNote).toContain(PINNED_CODEX_ACP_INTEGRITY); - expect(reviewNote).toContain("@openclaw/diagnostics-otel@2026.6.10"); - expect(reviewNote).toContain(PINNED_OPENCLAW_DIAGNOSTICS_OTEL_INTEGRITY); - expect(reviewNote).toContain("@openclaw/brave-plugin@2026.6.10"); - expect(reviewNote).toContain(PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY); - expect(reviewNote).toContain("@openclaw/discord@2026.6.10"); - expect(reviewNote).toContain(PINNED_OPENCLAW_DISCORD_INTEGRITY); - expect(reviewNote).toContain("@openclaw/slack@2026.6.10"); - expect(reviewNote).toContain(PINNED_OPENCLAW_SLACK_INTEGRITY); - expect(reviewNote).toContain("@openclaw/whatsapp@2026.6.10"); - expect(reviewNote).toContain(PINNED_OPENCLAW_WHATSAPP_INTEGRITY); - expect(reviewNote).toContain("@openclaw/msteams@2026.6.10"); - expect(reviewNote).toContain(PINNED_OPENCLAW_MSTEAMS_INTEGRITY); - expect(reviewNote).toContain("@tencent-weixin/openclaw-weixin@2.4.3"); - expect(reviewNote).toContain(PINNED_WECHAT_PLUGIN_INTEGRITY); - expect(reviewNote).toContain("downloaded tarball integrity"); - expect(reviewNote).toContain("bind reviewed npm installs to verified local archives"); - expect(reviewNote).toContain("npm pack --json"); - expect(reviewNote).toContain("reject reported archive filenames"); - expect(reviewNote).toContain("unsafe reported archive filenames"); - expect(reviewNote).toContain("each reviewed npm plugin registry integrity"); - expect(reviewNote).toContain("install the verified archive path"); - expect(reviewNote).toContain("OpenClaw Compiled-Dist Patch Runtime Boundary"); - expect(reviewNote).toContain( - "The long-term source of truth for these behaviors remains upstream OpenClaw", - ); - expect(reviewNote).toContain("test/openclaw-real-patched-dist-harness.test.ts"); - expect(reviewNote).toContain("NEMOCLAW_REAL_OPENCLAW_DIST_HARNESS=1"); - expect(reviewNote).toContain("not a substitute for focused nightly E2E proof"); - expect(reviewNote).toContain("OpenClaw Diagnostics OTEL Host Gateway Boundary"); - expect(reviewNote).toContain("openclaw-diagnostics-otel-local"); - expect(reviewNote).toContain("imports `OTLPTraceExporter`"); - expect(reviewNote).toContain("contains no `web_fetch`, `fetchWithSsrFGuard`"); - expect(reviewNote).toContain("@openclaw/diagnostics-otel@2026.6.10"); - expect(reviewNote).toContain("@openclaw/brave-plugin@2026.6.10"); - expect(reviewNote).toContain("@tencent-weixin/openclaw-weixin@2.4.3"); - expect(reviewNote).toContain("`0` high"); - expect(reviewNote).toContain("`0` critical"); - expect(reviewNote).toContain("`763` total dependencies"); - expect(reviewNote).toContain( - "`dist/pipeline.runtime-*.js`, which exports `prepareSlackMessage`", - ); - expect(reviewNote).toContain("imports the hashed pipeline runtime for `prepareSlackMessage`"); - expect(reviewNote).toContain("only reports `openclaw-pipeline-runtime` after allowed prepare"); - expect(reviewNote).toContain("`dist/extensions/telegram/runtime-api.js`"); - expect(reviewNote).toContain("which exports `sendMessageTelegram`"); - expect(reviewNote).toContain("fails closed if the installed runtime file is missing"); - expect(reviewNote).toContain("NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"); - expect(reviewNote).toContain("scripts/check-production-build-args.sh"); - expect(reviewNote).toContain("production build args"); - expect(reviewNote).toContain("claiming `openclaw-pipeline-runtime` inbound proof"); - expect(reviewNote).toContain("imports `dist/extensions/telegram/test-api.js`"); - expect(reviewNote).toContain("gateway/upstream reporting layer"); - expect(reviewNote).toContain("scripts/patch-openclaw-issue-4434-diagnostics.ts"); - expect(reviewNote).toContain("scripts/patch-openclaw-device-self-approval.ts"); - expect(reviewNote).toContain("approveDevicePairing"); - expect(reviewNote).toContain( - "Recovery hint: check sandbox egress and provider reachability, then retry.", - ); - expect(reviewNote).toContain("default 180-second timeout"); - }); - - it("keeps the Teams OpenClaw plugin manifest pinned to the reviewed 2026.6.10 integrity", () => { - const teamsManifest = createBuiltInChannelManifestRegistry().get("teams"); - const teamsPackage = teamsManifest?.agentPackages?.find( - (agentPackage) => - agentPackage.agent === "openclaw" && - agentPackage.manager === "openclaw-plugin" && - agentPackage.id === "openclawPluginPackage", - ); - - expect(teamsPackage).toMatchObject({ - spec: "npm:@openclaw/msteams@{{openclaw.version}}", - pin: true, - integrityByVersion: { - [PINNED_OPENCLAW_VERSION]: PINNED_OPENCLAW_MSTEAMS_INTEGRITY, - }, - }); - }); - - it("keeps reviewed OpenClaw messaging plugin integrity pins aligned with built-in manifests", () => { - const registry = createBuiltInChannelManifestRegistry(); - const expectedEntries: [string, string][] = registry.list().flatMap((manifest) => - (manifest.agentPackages ?? []) - .filter( - (agentPackage) => - agentPackage.agent === "openclaw" && agentPackage.manager === "openclaw-plugin", - ) - .map((agentPackage) => { - const packageSpec = agentPackage.spec - .replace(/^npm:/, "") - .replaceAll("{{openclaw.version}}", PINNED_OPENCLAW_VERSION); - const integrity = - agentPackage.integrity ?? agentPackage.integrityByVersion?.[PINNED_OPENCLAW_VERSION]; - - expect(agentPackage.pin, `${manifest.id}:${agentPackage.id}`).toBe(true); - expect(integrity, `${manifest.id}:${packageSpec}`).toBeDefined(); - return [packageSpec, integrity as string] as [string, string]; - }), - ); - - const sortedEntries = (entries: [string, string][]) => - Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right))); - - expect( - sortedEntries( - Object.entries( - reviewedOpenClawPluginIntegrityByPackageSpec({ - OPENCLAW_VERSION: PINNED_OPENCLAW_VERSION, - }), - ), - ), - ).toEqual(sortedEntries(expectedEntries)); - }); - - it.each([ - "latest", - "^2026.6.10", - ])("rejects a trusted OpenClaw plugin manifest with non-exact version %s", (version) => { - const slackManifest = createBuiltInChannelManifestRegistry().get("slack"); - expect(slackManifest).toBeDefined(); - const nonExactManifest = { - ...slackManifest!, - agentPackages: slackManifest!.agentPackages?.map((agentPackage) => - agentPackage.agent === "openclaw" && agentPackage.manager === "openclaw-plugin" - ? { - ...agentPackage, - spec: `npm:@openclaw/slack@${version}`, - integrity: PINNED_OPENCLAW_SLACK_INTEGRITY, - integrityByVersion: undefined, - } - : agentPackage, - ), - }; - - expect(() => - reviewedOpenClawPluginIntegrityByPackageSpec({ OPENCLAW_VERSION: PINNED_OPENCLAW_VERSION }, [ - nonExactManifest, - ]), - ).toThrow(`must use an exact-version OpenClaw plugin package: npm:@openclaw/slack@${version}`); - }); - - it("verifies optional non-messaging OpenClaw plugin integrity before install", () => { - const { result, calls } = runOptionalOpenClawPluginBlock(); - - expect(result.status, `${result.stdout}${result.stderr}`).toBe(0); - expect(calls).toContain( - `npm view @openclaw/diagnostics-otel@${PINNED_OPENCLAW_VERSION} dist.integrity`, - ); - expect(calls).toContain( - `npm view @openclaw/diagnostics-otel@${PINNED_OPENCLAW_VERSION} dist.tarball`, - ); - expect(calls).toContain( - "npm pack https://registry.npmjs.org/@openclaw/diagnostics-otel/-/diagnostics-otel-2026.6.10.tgz --pack-destination", - ); - expect(calls).toMatch( - /openclaw plugins install npm-pack:\S*\/diagnostics-otel-2026\.6\.10\.tgz\n/, - ); - expect(calls).toContain( - `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.integrity`, - ); - expect(calls).toContain( - `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.tarball`, - ); - expect(calls).toContain( - "npm pack https://registry.npmjs.org/@openclaw/brave-plugin/-/brave-plugin-2026.6.10.tgz --pack-destination", - ); - expect(calls).toMatch(/openclaw plugins install npm-pack:\S*\/brave-plugin-2026\.6\.10\.tgz\n/); - expect(calls).toContain("openclaw-env true true"); - }); - - it("fails closed before optional OpenClaw plugin install when registry integrity drifts", () => { - const { result, calls } = runOptionalOpenClawPluginBlock({ - otel: false, - braveRegistryIntegrity: "sha512-brave-drift", - }); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `OpenClaw plugin @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} npm integrity mismatch`, - ); - expect(`${result.stdout}${result.stderr}`).toContain( - `Expected: ${PINNED_OPENCLAW_BRAVE_PLUGIN_INTEGRITY}`, - ); - expect(`${result.stdout}${result.stderr}`).toContain("Actual: sha512-brave-drift"); - expect(calls).toContain( - `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.integrity`, - ); - expect(calls).not.toContain("openclaw plugins install"); - }); - - it("fails closed before optional OpenClaw plugin install when the registry tarball URL drifts", () => { - const driftedTarball = - "https://registry.npmjs.org/@openclaw/brave-plugin/-/brave-plugin-2026.6.11.tgz"; - const { result, calls } = runOptionalOpenClawPluginBlock({ - otel: false, - braveRegistryTarball: driftedTarball, - }); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `OpenClaw plugin @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} npm tarball URL mismatch`, - ); - expect(`${result.stdout}${result.stderr}`).toContain( - `Expected: ${PINNED_OPENCLAW_BRAVE_PLUGIN_TARBALL}`, - ); - expect(`${result.stdout}${result.stderr}`).toContain(`Actual: ${driftedTarball}`); - expect(calls).toContain( - `npm view @openclaw/brave-plugin@${PINNED_OPENCLAW_VERSION} dist.tarball`, - ); - expect(calls).not.toContain("npm pack"); - expect(calls).not.toContain("openclaw plugins install"); - }); - - it("fails closed for optional OpenClaw plugin version overrides without committed pins", () => { - const { result, calls } = runOptionalOpenClawPluginBlock({ - openclawVersion: UNPINNED_OPENCLAW_VERSION, - webSearch: false, - }); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `OpenClaw plugin @openclaw/diagnostics-otel@${UNPINNED_OPENCLAW_VERSION} has no committed npm integrity pin`, - ); - expect(calls).not.toContain("openclaw plugins install"); - }); - - it("installs the reviewed pin when registry integrity matches the committed pin", () => { - const production = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - }, - ); - const codexAcp = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# Pre-install the codex-acp package", - "# Upgrade OpenClaw if the base image is stale.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - }, - ); - const base = runInstallBlock( - extractRunBlock( - DOCKERFILE_BASE, - "# Install OpenClaw CLI + PyYAML.", - "# Baseline health check.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - }, - ); - - expect(production.result.status).toBe(0); - expect(codexAcp.result.status).toBe(0); - expect(base.result.status).toBe(0); - expect(production.calls).toContain( - `npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`, - ); - expect(production.calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`); - expect(production.calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); - expect(codexAcp.calls).toContain( - `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.integrity`, - ); - expect(codexAcp.calls).toContain( - `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.tarball`, - ); - expect(codexAcp.calls).toContain(`npm pack ${PINNED_CODEX_ACP_TARBALL} --pack-destination`); - expect(production.calls).toContain( - "npm install -g --no-audit --no-fund --no-progress --ignore-scripts ", - ); - expect(production.calls).toContain( - "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", - ); - expect(production.calls).toContain(`openclaw-${PINNED_OPENCLAW_VERSION}.tgz`); - expect(codexAcp.calls).toContain( - "npm install -g --no-audit --no-fund --no-progress --ignore-scripts ", - ); - expect(codexAcp.calls).toContain(`codex-acp-${PINNED_CODEX_ACP_VERSION}.tgz`); - expect(base.calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} version`); - expect(base.calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); - expect(base.calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`); - expect(base.calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); - expect(base.calls).toContain("npm install -g --ignore-scripts "); - expect(base.calls).toContain( - "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", - ); - expect(base.calls).toContain(`openclaw-${PINNED_OPENCLAW_VERSION}.tgz`); - expect(base.provenanceContent).toBe(openClawBaseProvenance()); - expect(base.provenanceMode).toBe(0o444); - }); - - it("reuses exact protected OpenClaw and mcporter base provenance without registry work", () => { - const { result, calls, provenanceExists } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - installedOpenClawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - baseProvenance: openClawBaseProvenance(), - }, - ); - - expect(result.status).toBe(0); - expect(result.stdout).toContain( - `Reusing reviewed base OpenClaw ${PINNED_OPENCLAW_VERSION} with exact provenance`, - ); - expect(calls).not.toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); - expect(calls).not.toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`); - expect(calls).not.toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); - expect(calls).not.toContain( - "npm install -g --no-audit --no-fund --no-progress --ignore-scripts ", - ); - expect(calls).not.toContain( - "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", - ); - expect(result.stdout).toContain( - `Reusing reviewed base mcporter ${PINNED_MCPORTER_VERSION} with exact lock provenance`, - ); - expect(calls).not.toContain(`npm view mcporter@${PINNED_MCPORTER_VERSION} dist.integrity`); - expect(calls).not.toContain("npm --prefix "); - expect(provenanceExists).toBe(false); - }); - - it.each([ - ["missing marker", { baseProvenance: null }], - ["wrong schema", { baseProvenance: openClawBaseProvenance().replace("schema=2", "schema=1") }], - [ - "wrong version", - { - baseProvenance: openClawBaseProvenance().replace( - `package=openclaw@${PINNED_OPENCLAW_VERSION}`, - "package=openclaw@2026.6.9", - ), - }, - ], - [ - "wrong integrity", - { - baseProvenance: openClawBaseProvenance().replace( - `integrity=${PINNED_OPENCLAW_INTEGRITY}`, - "integrity=sha512-drift", - ), - }, - ], - [ - "wrong tarball", - { - baseProvenance: openClawBaseProvenance().replace( - `tarball=${PINNED_OPENCLAW_TARBALL}`, - "tarball=https://registry.npmjs.org/openclaw/-/openclaw-drift.tgz", - ), - }, - ], - [ - "wrong lifecycle recipe", - { - baseProvenance: openClawBaseProvenance().replace( - "recipe=ignore-scripts+reviewed-lifecycle-v1", - "recipe=ignore-scripts-only-v1", - ), - }, - ], - [ - "wrong mcporter package", - { - baseProvenance: openClawBaseProvenance().replace( - `mcporter-package=mcporter@${PINNED_MCPORTER_VERSION}`, - "mcporter-package=mcporter@0.7.2", - ), - }, - ], - [ - "wrong mcporter integrity", - { - baseProvenance: openClawBaseProvenance().replace( - `mcporter-integrity=${PINNED_MCPORTER_INTEGRITY}`, - "mcporter-integrity=sha512-drift", - ), - }, - ], - [ - "wrong mcporter lock", - { - baseProvenance: openClawBaseProvenance().replace( - `mcporter-lock-sha256=${PINNED_MCPORTER_LOCK_SHA256}`, - `mcporter-lock-sha256=${"0".repeat(64)}`, - ), - }, - ], - [ - "wrong mcporter recipe", - { - baseProvenance: openClawBaseProvenance().replace( - "mcporter-recipe=locked-ci+audit-signatures-v1", - "mcporter-recipe=locked-ci-only-v1", - ), - }, - ], - [ - "writable marker", - { baseProvenance: openClawBaseProvenance(), baseProvenanceMetadata: "0:0:644" }, - ], - ["symlink marker", { baseProvenance: openClawBaseProvenance(), baseProvenanceSymlink: true }], - [ - "wrong installed version", - { - baseProvenance: openClawBaseProvenance(), - installedOpenClawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, - }, - ], - [ - "wrong installed mcporter version", - { - baseProvenance: openClawBaseProvenance(), - installedOpenClawVersion: PINNED_OPENCLAW_VERSION, - installedMcporterVersion: "0.7.2", - }, - ], - [ - "custom base reference", - { baseProvenance: openClawBaseProvenance(), baseImage: "registry.example/base:custom" }, - ], - ])("falls back to the reviewed archive for %s", (_label, overrides) => { - const { result, calls, provenanceExists } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - installedOpenClawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - ...overrides, - }, - ); - - expect(result.status).toBe(0); - expect(result.stdout).toContain("lacks exact reviewed provenance"); - expect(calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); - expect(calls).toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.tarball`); - expect(calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); - expect(calls).toContain("npm install -g --no-audit --no-fund --no-progress --ignore-scripts "); - expect(calls).toContain( - "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", - ); - expect(provenanceExists).toBe(false); - }); - - it("keeps a newer unreviewed base fail-closed even when its marker claims the target", () => { - const { result, calls, provenanceExists } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - installedOpenClawVersion: "2026.6.11", - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - baseProvenance: openClawBaseProvenance(), - }, - ); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `Base image has OpenClaw 2026.6.11, which is newer than reviewed target ${PINNED_OPENCLAW_VERSION}`, - ); - expect(calls).not.toContain(`npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`); - expect(calls).not.toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); - expect(provenanceExists).toBe(false); - }); - - it("rejects npm pack filenames outside the fresh pack directories", () => { - const production = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - packFilename: "../openclaw-2026.6.10.tgz", - }, - ); - const codexAcp = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# Pre-install the codex-acp package", - "# Upgrade OpenClaw if the base image is stale.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - packFilename: "../codex-acp-0.11.1.tgz", - }, - ); - const base = runInstallBlock( - extractRunBlock( - DOCKERFILE_BASE, - "# Install OpenClaw CLI + PyYAML.", - "# Baseline health check.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - packFilename: "../openclaw-2026.6.10.tgz", - }, - ); - const optionalPlugin = runOptionalOpenClawPluginBlock({ - pluginPackFilename: "../diagnostics-otel-2026.6.10.tgz", - }); - - for (const item of [ - { - label: "production Dockerfile", - outcome: production, - unsafeFilename: "../openclaw-2026.6.10.tgz", - blockedCommand: "npm install -g", - }, - { - label: "codex-acp Dockerfile", - outcome: codexAcp, - unsafeFilename: "../codex-acp-0.11.1.tgz", - blockedCommand: "npm install -g", - }, - { - label: "base Dockerfile", - outcome: base, - unsafeFilename: "../openclaw-2026.6.10.tgz", - blockedCommand: "npm install -g", - }, - { - label: "optional OpenClaw plugin Dockerfile", - outcome: optionalPlugin, - unsafeFilename: "../diagnostics-otel-2026.6.10.tgz", - blockedCommand: "openclaw plugins install", - }, - ]) { - expect(item.outcome.result.status, item.label).not.toBe(0); - expect(`${item.outcome.result.stdout}${item.outcome.result.stderr}`, item.label).toContain( - `npm pack reported unsafe archive filename: ${item.unsafeFilename}`, - ); - expect(item.outcome.calls, item.label).toContain("npm pack"); - expect(item.outcome.calls, item.label).not.toContain(item.blockedCommand); - } - }); - - it("reports missing base-image npm pack filenames on stderr", () => { - const { result, calls } = runInstallBlock( - extractRunBlock( - DOCKERFILE_BASE, - "# Install OpenClaw CLI + PyYAML.", - "# Baseline health check.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - packFilename: null, - }, - ); - const diagnostic = `OpenClaw ${PINNED_OPENCLAW_VERSION} npm pack did not report filename and integrity`; - - expect(result.status).not.toBe(0); - expect(result.stderr).toContain(diagnostic); - expect(result.stdout).not.toContain(diagnostic); - expect(calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); - expect(calls).not.toContain("npm install -g"); - }); - - it("rejects legacy fixture pins unless stale-upgrade fixture mode is explicit", () => { - const production = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - { - openclawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, - registryIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, - registryTarball: LEGACY_REBUILD_OPENCLAW_TARBALL, - packIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, - }, - ); - const base = runInstallBlock( - extractRunBlock( - DOCKERFILE_BASE, - "# Install OpenClaw CLI + PyYAML.", - "# Baseline health check.", - ), - { - openclawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, - registryIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, - registryTarball: LEGACY_REBUILD_OPENCLAW_TARBALL, - packIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, - }, - ); - const fixtureBase = runInstallBlock( - extractRunBlock( - DOCKERFILE_BASE, - "# Install OpenClaw CLI + PyYAML.", - "# Baseline health check.", - ), - { - openclawVersion: LEGACY_REBUILD_OPENCLAW_VERSION, - registryIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, - registryTarball: LEGACY_REBUILD_OPENCLAW_TARBALL, - packIntegrity: LEGACY_REBUILD_OPENCLAW_INTEGRITY, - allowLegacyFixture: true, - }, - ); - const gatewayFixtureBase = runInstallBlock( - extractRunBlock( - DOCKERFILE_BASE, - "# Install OpenClaw CLI + PyYAML.", - "# Baseline health check.", - ), - { - openclawVersion: LEGACY_GATEWAY_UPGRADE_OPENCLAW_VERSION, - registryIntegrity: LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY, - registryTarball: LEGACY_GATEWAY_UPGRADE_OPENCLAW_TARBALL, - packIntegrity: LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY, - allowLegacyFixture: true, - }, - ); - - for (const rejected of [production, base]) { - expect(rejected.result.status).not.toBe(0); - expect(`${rejected.result.stdout}${rejected.result.stderr}`).toContain( - `OpenClaw ${LEGACY_REBUILD_OPENCLAW_VERSION} is a legacy E2E fixture pin`, - ); - expect(rejected.calls).not.toContain("npm install -g"); - } - expect(fixtureBase.result.status).toBe(0); - expect(fixtureBase.calls).toContain( - `npm view openclaw@${LEGACY_REBUILD_OPENCLAW_VERSION} version`, - ); - expect(fixtureBase.calls).toContain( - `npm view openclaw@${LEGACY_REBUILD_OPENCLAW_VERSION} dist.integrity`, - ); - expect(fixtureBase.calls).toContain( - `npm view openclaw@${LEGACY_REBUILD_OPENCLAW_VERSION} dist.tarball`, - ); - expect(fixtureBase.calls).toContain( - `npm pack ${LEGACY_REBUILD_OPENCLAW_TARBALL} --pack-destination`, - ); - expect(fixtureBase.calls).toContain(`openclaw-${LEGACY_REBUILD_OPENCLAW_VERSION}.tgz`); - expect(fixtureBase.calls).toContain("npm install -g --ignore-scripts "); - expect(fixtureBase.calls).not.toContain("postinstall-bundled-plugins.mjs"); - expect(gatewayFixtureBase.result.status).toBe(0); - expect(gatewayFixtureBase.calls).toContain("npm install -g --ignore-scripts "); - expect(gatewayFixtureBase.calls).toContain( - "node /usr/local/lib/node_modules/openclaw/scripts/postinstall-bundled-plugins.mjs", - ); - }); - - it("guards production Docker build args from legacy OpenClaw fixture inputs", () => { - expect(runProductionBuildArgGuard(["--build-arg", "BASE_IMAGE=base"]).status).toBe(0); - expect( - runProductionBuildArgGuard(["--build-arg=NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=0"]).status, - ).toBe(0); - expect( - runProductionBuildArgGuard(["--build-arg", `OPENCLAW_VERSION=${PINNED_OPENCLAW_VERSION}`]) - .status, - ).toBe(0); - - for (const args of [ - ["--build-arg", "NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"], - ["--build-arg=NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"], - ["NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1"], - ]) { - const result = runProductionBuildArgGuard(args); - expect(result.status, args.join(" ")).toBe(1); - expect(result.stderr).toContain("only allowed in explicit stale-upgrade E2E fixture builds"); - } - - const envResult = runProductionBuildArgGuard([], { - NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW: "1", - }); - expect(envResult.status).toBe(1); - expect(envResult.stderr).toContain("production Docker image build args"); - - for (const args of [ - ["--build-arg", `OPENCLAW_VERSION=${LEGACY_REBUILD_OPENCLAW_VERSION}`], - ["--build-arg=OPENCLAW_VERSION=2026.4.24"], - ["OPENCLAW_2026_3_11_INTEGRITY=sha512-fixture"], - ["--build-arg=OPENCLAW_2026_4_24_TARBALL=https://fixture.invalid/package.tgz"], - ]) { - const result = runProductionBuildArgGuard(args); - expect(result.status, args.join(" ")).toBe(1); - expect(result.stderr).toContain("not allowed in production image builds"); - } - - const legacyEnvCases: ReadonlyArray> = [ - { OPENCLAW_VERSION: LEGACY_REBUILD_OPENCLAW_VERSION }, - { OPENCLAW_VERSION: "2026.4.24" }, - { OPENCLAW_2026_3_11_TARBALL: LEGACY_REBUILD_OPENCLAW_TARBALL }, - { OPENCLAW_2026_4_24_INTEGRITY: LEGACY_GATEWAY_UPGRADE_OPENCLAW_INTEGRITY }, - ]; - for (const env of legacyEnvCases) { - const result = runProductionBuildArgGuard([], env); - expect(result.status, JSON.stringify(env)).toBe(1); - expect(result.stderr).toContain("not allowed in production image builds"); - } - - for (const args of [ - [ - "--build-arg", - `OPENCLAW_VERSION=${PINNED_OPENCLAW_VERSION}\nNEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW=1\nOPENCLAW_VERSION=2026.4.24`, - ], - [`--build-arg=OPENCLAW_VERSION=${PINNED_OPENCLAW_VERSION}\r`], - ["BASE_IMAGE=base\nINJECTED=value"], - ["--build-arg\r"], - ]) { - const result = runProductionBuildArgGuard(args); - expect(result.status, JSON.stringify(args)).toBe(1); - expect(result.stderr).toContain("must not contain CR or LF characters"); - } - }); - - it("production build arg guard rejects current reviewed pin overrides", () => { - const currentPinArgNames = declaredProductionPinArgNames(); - expect(currentPinArgNames).toEqual([ - "CODEX_ACP_0_11_1_INTEGRITY", - "HERMES_NPM_INTEGRITY", - "MCPORTER_0_7_3_INTEGRITY", - "OPENCLAW_2026_3_11_INTEGRITY", - "OPENCLAW_2026_3_11_TARBALL", - "OPENCLAW_2026_4_24_INTEGRITY", - "OPENCLAW_2026_4_24_TARBALL", - "OPENCLAW_2026_6_10_INTEGRITY", - "OPENCLAW_2026_6_10_TARBALL", - "OPENCLAW_BRAVE_PLUGIN_2026_6_10_INTEGRITY", - "OPENCLAW_DIAGNOSTICS_OTEL_2026_6_10_INTEGRITY", - ]); - - const futurePinArgNames = [ - "OPENCLAW_FUTURE_PLUGIN_2099_1_1_INTEGRITY", - "FUTURE_DEPENDENCY_2099_1_1_TARBALL", - ]; - for (const pinArgName of [...currentPinArgNames, ...futurePinArgNames]) { - for (const args of [ - [`${pinArgName}=attacker-controlled`], - [`--build-arg=${pinArgName}=attacker-controlled`], - ["--build-arg", `${pinArgName}=attacker-controlled`], - ["--build-arg", pinArgName], - ]) { - const result = runProductionBuildArgGuard(args); - expect(result.status, args.join(" ")).toBe(1); - expect(result.stderr).toContain("pin overrides are not allowed"); - } - } - - for (const pinArgName of currentPinArgNames) { - const envResult = runProductionBuildArgGuard([], { [pinArgName]: "attacker-controlled" }); - expect(envResult.status, pinArgName).toBe(1); - expect(envResult.stderr).toContain("pin overrides are not allowed"); - } - - expect(runProductionBuildArgGuard([], { RELEASE_INTEGRITY: "verified" }).status).toBe(0); - expect(runProductionBuildArgGuard([], { SOURCE_TARBALL: "source.tgz" }).status).toBe(0); - }); - - it("fails closed before npm install when the registry integrity drifts", () => { - const installBlocks = [ - { - label: "production Dockerfile", - file: DOCKERFILE, - startMarker: "# OPENCLAW_VERSION is the NemoClaw runtime build target", - endMarker: "# Patch OpenClaw media fetch", - }, - { - label: "base Dockerfile", - file: DOCKERFILE_BASE, - startMarker: "# Install OpenClaw CLI + PyYAML.", - endMarker: "# Baseline health check.", - }, - ]; - - for (const block of installBlocks) { - const { result, calls } = runInstallBlock( - extractRunBlock(block.file, block.startMarker, block.endMarker), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: "sha512-registry-drift", - }, - ); - const output = `${result.stdout}${result.stderr}`; - - expect(result.status, block.label).not.toBe(0); - expect(output, block.label).toContain( - `OpenClaw ${PINNED_OPENCLAW_VERSION} npm integrity mismatch`, - ); - expect(output, block.label).toContain(`Expected: ${PINNED_OPENCLAW_INTEGRITY}`); - expect(output, block.label).toContain("Actual: sha512-registry-drift"); - expect(calls, block.label).toContain( - `npm view openclaw@${PINNED_OPENCLAW_VERSION} dist.integrity`, - ); - expect(calls, block.label).not.toContain("npm install -g"); - } - }); - - it("fails closed before npm install when the downloaded OpenClaw tarball integrity drifts", () => { - const { result, calls } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - packIntegrity: "sha512-downloaded-drift", - }, - ); - const output = `${result.stdout}${result.stderr}`; - - expect(result.status).not.toBe(0); - expect(output).toContain( - `OpenClaw ${PINNED_OPENCLAW_VERSION} downloaded tarball integrity mismatch`, - ); - expect(output).toContain(`Expected: ${PINNED_OPENCLAW_INTEGRITY}`); - expect(output).toContain("Actual: sha512-downloaded-drift"); - expect(calls).toContain(`npm pack ${PINNED_OPENCLAW_TARBALL} --pack-destination`); - expect(calls).not.toContain("npm install -g"); - }); - - it("fails closed before npm install for unpinned production Dockerfile overrides", () => { - const { result, calls } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# OPENCLAW_VERSION is the NemoClaw runtime build target", - "# Patch OpenClaw media fetch", - ), - ); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `OpenClaw ${UNPINNED_OPENCLAW_VERSION} has no committed npm integrity pin`, - ); - expect(calls).not.toContain("npm install -g"); - }); - - it("fails closed before installing codex-acp when its registry integrity drifts", () => { - const { result, calls } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# Pre-install the codex-acp package", - "# Upgrade OpenClaw if the base image is stale.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - codexAcpCommittedIntegrity: PINNED_CODEX_ACP_INTEGRITY, - codexAcpRegistryIntegrity: "sha512-codex-acp-drift", - }, - ); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} npm integrity mismatch`, - ); - expect(`${result.stdout}${result.stderr}`).toContain(`Expected: ${PINNED_CODEX_ACP_INTEGRITY}`); - expect(`${result.stdout}${result.stderr}`).toContain("Actual: sha512-codex-acp-drift"); - expect(calls).toContain( - `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.integrity`, - ); - expect(calls).not.toContain( - `npm install -g --no-audit --no-fund --no-progress ${PINNED_CODEX_ACP_TARBALL}`, - ); - }); - - it("fails closed before installing codex-acp when its registry tarball URL drifts", () => { - const { result, calls } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# Pre-install the codex-acp package", - "# Upgrade OpenClaw if the base image is stale.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - codexAcpCommittedIntegrity: PINNED_CODEX_ACP_INTEGRITY, - codexAcpRegistryIntegrity: PINNED_CODEX_ACP_INTEGRITY, - codexAcpRegistryTarball: - "https://registry.npmjs.org/@zed-industries/codex-acp/-/codex-acp-0.11.2.tgz", - }, - ); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} npm tarball URL mismatch`, - ); - expect(`${result.stdout}${result.stderr}`).toContain(`Expected: ${PINNED_CODEX_ACP_TARBALL}`); - expect(`${result.stdout}${result.stderr}`).toContain( - "Actual: https://registry.npmjs.org/@zed-industries/codex-acp/-/codex-acp-0.11.2.tgz", - ); - expect(calls).toContain( - `npm view @zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} dist.tarball`, - ); - expect(calls).not.toContain( - `npm install -g --no-audit --no-fund --no-progress ${PINNED_CODEX_ACP_TARBALL}`, - ); - }); - - it("fails closed before installing codex-acp when its downloaded tarball integrity drifts", () => { - const { result, calls } = runInstallBlock( - extractRunBlock( - DOCKERFILE, - "# Pre-install the codex-acp package", - "# Upgrade OpenClaw if the base image is stale.", - ), - { - openclawVersion: PINNED_OPENCLAW_VERSION, - committedIntegrity: PINNED_OPENCLAW_INTEGRITY, - registryIntegrity: PINNED_OPENCLAW_INTEGRITY, - codexAcpCommittedIntegrity: PINNED_CODEX_ACP_INTEGRITY, - codexAcpRegistryIntegrity: PINNED_CODEX_ACP_INTEGRITY, - codexAcpPackIntegrity: "sha512-codex-downloaded-drift", - }, - ); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `@zed-industries/codex-acp@${PINNED_CODEX_ACP_VERSION} downloaded tarball integrity mismatch`, - ); - expect(`${result.stdout}${result.stderr}`).toContain(`Expected: ${PINNED_CODEX_ACP_INTEGRITY}`); - expect(`${result.stdout}${result.stderr}`).toContain("Actual: sha512-codex-downloaded-drift"); - expect(calls).toContain(`npm pack ${PINNED_CODEX_ACP_TARBALL} --pack-destination`); - expect(calls).not.toContain("npm install -g"); - }); - - it("fails closed before npm install for unpinned base Dockerfile overrides", () => { - const { result, calls } = runInstallBlock( - extractRunBlock( - DOCKERFILE_BASE, - "# Install OpenClaw CLI + PyYAML.", - "# Baseline health check.", - ), - ); - - expect(result.status).not.toBe(0); - expect(`${result.stdout}${result.stderr}`).toContain( - `OpenClaw ${UNPINNED_OPENCLAW_VERSION} has no committed npm integrity pin`, - ); - expect(calls).not.toContain("npm install -g"); - }); -}); diff --git a/test/vitest-developer-feedback.test.ts b/test/vitest-developer-feedback.test.ts new file mode 100644 index 00000000000..ff2378b78f3 --- /dev/null +++ b/test/vitest-developer-feedback.test.ts @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect } from "vitest"; + +import rootVitestConfig from "../vitest.config"; +import { test as it } from "./helpers/owned-test-resources"; +import { resolveVitestFeedback } from "./helpers/vitest-feedback"; +import { runVitestNpmScript } from "./helpers/vitest-npm-script"; + +type RootTestOptions = { + reporters?: unknown; + silent?: boolean | "passed-only"; +}; + +const focusedProjects = "--project cli --project plugin --project e2e-support"; + +describe("Vitest developer feedback", () => { + it("lets Vitest select reporters and preserves failed-test logs in CI (#6692)", () => { + const testOptions = rootVitestConfig.test as RootTestOptions; + + expect(testOptions).not.toHaveProperty("reporters"); + expect(resolveVitestFeedback({})).toEqual({ isCi: false, silent: false }); + expect(resolveVitestFeedback({ CI: "0" })).toEqual({ isCi: false, silent: false }); + expect(resolveVitestFeedback({ CI: "1" })).toEqual({ + isCi: true, + silent: "passed-only", + }); + expect(resolveVitestFeedback({ CI: "true" })).toEqual({ + isCi: true, + silent: "passed-only", + }); + expect(resolveVitestFeedback({ GITHUB_ACTIONS: "true" })).toEqual({ + isCi: true, + silent: "passed-only", + }); + expect(testOptions.silent).toBe(resolveVitestFeedback().silent); + }); + + it("runs changed and watch feedback on the focused source projects (#6692)", ({ resources }) => { + expect(runVitestNpmScript(resources, "test:changed")).toBe( + `vitest run --changed ${focusedProjects}`, + ); + expect(runVitestNpmScript(resources, "test:watch")).toBe(`vitest watch ${focusedProjects}`); + }); + + it("passes a reproducible seed to test-only shuffle diagnostics outside coverage (#6692)", ({ + resources, + }) => { + expect(runVitestNpmScript(resources, "test:shuffle", ["--", "--sequence.seed=6692"])).toBe( + `vitest run ${focusedProjects} --sequence.shuffle.tests --coverage=false --sequence.seed=6692`, + ); + }); + + it("runs opt-in async-leak diagnostics outside coverage (#6692)", ({ resources }) => { + expect(runVitestNpmScript(resources, "test:diagnose:leaks")).toBe( + `vitest run ${focusedProjects} --detectAsyncLeaks --coverage=false --reporter=default --reporter=hanging-process`, + ); + }); +}); diff --git a/test/vitest-watch-triggers.test.ts b/test/vitest-watch-triggers.test.ts new file mode 100644 index 00000000000..c07efd5c18a --- /dev/null +++ b/test/vitest-watch-triggers.test.ts @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import rootVitestConfig from "../vitest.config"; +import { + resolveVitestWatchTests, + vitestWatchTriggerPatterns, +} from "./helpers/vitest-watch-triggers"; + +const E2E_WORKFLOW_CONTRACTS = [ + "test/e2e/support/channels-add-remove-workflow-boundary.test.ts", + "test/e2e/support/dcode-profile-import-gate-workflow-boundary.test.ts", + "test/e2e/support/dockerhub-auth-workflow-boundary.test.ts", + "test/e2e/support/e2e-host-dependency-workflow-boundary.test.ts", + "test/e2e/support/e2e-operations-workflow-boundary.test.ts", + "test/e2e/support/e2e-report-to-pr-workflow-boundary.test.ts", + "test/e2e/support/e2e-workflow.test.ts", + "test/e2e/support/e2e-workflow-trace.test.ts", + "test/e2e/support/gateway-guard-workflow-boundary.test.ts", + "test/e2e/support/hermes-dashboard-workflow-boundary.test.ts", + "test/e2e/support/hermes-workflow-boundary.test.ts", + "test/e2e/support/inference-switch-workflow-boundary.test.ts", + "test/e2e/support/jetson-workflow-boundary.test.ts", + "test/e2e/support/mcp-workflow-boundary.test.ts", + "test/e2e/support/mcp-workflow-compatibility.test.ts", + "test/e2e/support/openclaw-discord-workflow-boundary.test.ts", + "test/e2e/support/openclaw-plugin-runtime-exdev-workflow-boundary.test.ts", + "test/e2e/support/openclaw-slack-workflow-boundary.test.ts", + "test/e2e/support/openshell-gateway-auth-contract-workflow-boundary.test.ts", + "test/e2e/support/openshell-gateway-upgrade-workflow-boundary.test.ts", + "test/e2e/support/overlayfs-autofix-workflow-boundary.test.ts", + "test/e2e/support/prepare-e2e-workflow-boundary.test.ts", + "test/e2e/support/rlimit-connect-workflow-boundary.test.ts", + "test/e2e/support/sandbox-images-workflow-boundary.test.ts", + "test/e2e/support/sandbox-operations-workflow-boundary.test.ts", + "test/e2e/support/security-posture-workflow-boundary.test.ts", + "test/e2e/support/shared-e2e-workflow-boundary.test.ts", + "test/e2e/support/spark-install-workflow-boundary.test.ts", + "test/e2e/support/tunnel-lifecycle-workflow-boundary.test.ts", + "test/e2e/support/upload-e2e-artifacts-workflow-boundary.test.ts", + "test/e2e/support/workflow-plan.test.ts", +] as const; + +const OPAQUE_INPUTS = [ + "agents/hermes/policy-additions.yaml", + "src/lib/messaging/channels/telegram/policy/openclaw.yaml", + "nemoclaw-blueprint/policies/presets/local-inference.yaml", + "agents/hermes/runtime-config-guard.py", + "agents/hermes/mcp-config-transaction.py", + "test/e2e/lib/ci-compatible-inference.sh", + "scripts/e2e/sanitize-trace-timing.py", + "test/e2e/manifests/openclaw-nvidia.yaml", + "test/e2e/docs/parity-inventory.generated.json", + ".github/workflows/e2e.yaml", +] as const; + +function triggeredBy(relativePath: string): string[] { + return resolveVitestWatchTests(path.resolve(relativePath)); +} + +describe("Vitest opaque-input watch triggers", () => { + it("registers the focused mappings at the root configuration boundary (#6692)", () => { + expect(rootVitestConfig.test?.watchTriggerPatterns).toBe(vitestWatchTriggerPatterns); + }); + + it("maps current opaque inputs to their direct contract tests (#6692)", () => { + expect(triggeredBy("agents/hermes/policy-additions.yaml")).toEqual([ + "src/lib/onboard/initial-policy-real-policy.test.ts", + "src/lib/onboard/initial-policy.test.ts", + ]); + expect(triggeredBy("src/lib/messaging/channels/telegram/policy/openclaw.yaml")).toEqual([ + "src/lib/messaging/channels/policy.test.ts", + ]); + expect(triggeredBy("nemoclaw-blueprint/policies/presets/local-inference.yaml")).toEqual([ + "src/lib/onboard/inference-providers/compatible-endpoint-gateway-route.test.ts", + ]); + expect(triggeredBy("agents/hermes/runtime-config-guard.py")).toEqual([ + "src/lib/actions/sandbox/gateway-restart-hermes-drift.test.ts", + ]); + expect(triggeredBy("agents/hermes/mcp-config-transaction.py")).toEqual([ + "src/lib/actions/sandbox/gateway-restart-hermes-drift.test.ts", + ]); + expect(triggeredBy("test/e2e/lib/ci-compatible-inference.sh")).toEqual([ + "test/e2e/support/hosted-inference.test.ts", + ]); + expect(triggeredBy("scripts/e2e/sanitize-trace-timing.py")).toEqual([ + "test/e2e/support/e2e-scorecard.test.ts", + "test/e2e/support/sanitize-trace-timing.test.ts", + ]); + expect(triggeredBy("test/e2e/manifests/openclaw-nvidia.yaml")).toEqual([ + "test/e2e/support/e2e-manifests.test.ts", + ]); + expect(triggeredBy("test/e2e/manifests/openclaw-nvidia.yml")).toEqual([]); + expect(triggeredBy("test/e2e/docs/parity-inventory.generated.json")).toEqual([ + "test/e2e/support/e2e-migration-policy.test.ts", + ]); + expect(triggeredBy(".github/workflows/e2e.yaml")).toEqual(E2E_WORKFLOW_CONTRACTS); + }); + + it("returns only concrete test files that exist (#6692)", () => { + const triggeredTests = new Set(OPAQUE_INPUTS.flatMap(triggeredBy)); + + expect(triggeredTests.size).toBeGreaterThan(0); + for (const testFile of triggeredTests) { + expect(testFile).toMatch(/\.test\.ts$/); + expect(testFile).not.toMatch(/[?*{}[\]]/); + expect(fs.existsSync(testFile), testFile).toBe(true); + } + for (const trigger of vitestWatchTriggerPatterns) { + expect(trigger.pattern.global).toBe(false); + expect(trigger.pattern.sticky).toBe(false); + } + }); + + it("leaves unrelated YAML, shell, Python, and workflow files alone (#6692)", () => { + expect(triggeredBy("notes/example.yaml")).toEqual([]); + expect(triggeredBy("scripts/unrelated.py")).toEqual([]); + expect(triggeredBy("test/e2e/lib/unrelated.sh")).toEqual([]); + expect(triggeredBy("agents/hermes/hermes-wrapper.py")).toEqual([]); + expect(triggeredBy(".github/workflows/regression-e2e.yaml")).toEqual([]); + }); + + it("normalizes Windows-style paths before matching (#6692)", () => { + expect( + resolveVitestWatchTests("C:\\workspace\\NemoClaw\\scripts\\e2e\\sanitize-trace-timing.py"), + ).toEqual([ + "test/e2e/support/e2e-scorecard.test.ts", + "test/e2e/support/sanitize-trace-timing.test.ts", + ]); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index 4659dee99c4..130a1b51929 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -15,10 +15,11 @@ import { CliCoverageSequencer } from "./test/helpers/cli-coverage-sequencer"; import { resolveIntegrationProjectScheduling } from "./test/helpers/integration-project-scheduling"; import { sourceLoaderNodeOptions } from "./test/helpers/source-loader-options"; import { testTimeout } from "./test/helpers/timeouts"; +import { resolveVitestFeedback } from "./test/helpers/vitest-feedback"; import { vitestStateIsolation } from "./test/helpers/vitest-state-isolation"; +import { vitestWatchTriggerPatterns } from "./test/helpers/vitest-watch-triggers"; -const isGithubActions = process.env.GITHUB_ACTIONS === "true"; -const isCi = isGithubActions || process.env.CI === "true" || process.env.CI === "1"; +const { isCi, silent } = resolveVitestFeedback(); const LIVE_E2E_PROJECT_TIMEOUT_MS = 30 * 60 * 1000; const runLiveE2E = shouldRunLiveE2E(); const runBranchValidationE2E = shouldRunBranchValidationE2E(); @@ -65,11 +66,12 @@ export default defineConfig({ description: "Runs without external credentials in the shared E2E job", }, ], - // CI logs are easiest to scan when test chatter stays quiet and failures - // surface as GitHub annotations at the relevant file and line. - reporters: isGithubActions ? ["github-actions"] : ["default"], - silent: isCi, + // Let Vitest select its environment-aware local reporter and add GitHub + // annotations in Actions. CI suppresses passed-test logs while replaying + // the console output attached to failures. + silent, hideSkippedTests: isCi, + watchTriggerPatterns: vitestWatchTriggerPatterns, sequence: { sequencer: CliCoverageSequencer }, projects: [ { @@ -213,11 +215,10 @@ export default defineConfig({ // runs the selected test suites. Only run when explicitly enabled: // NEMOCLAW_RUN_BRANCH_VALIDATION_E2E=1 npx vitest run --project e2e-branch-validation // - // Override the project-root `silent: isCi` setting — diagnostic - // output from createBrevInstance / waitForSsh / waitForLaunchableReady - // is essential for debugging Brev provisioning timing and the - // overall suite runs in a single `describe` block, so there's no - // test chatter to suppress anyway. + // The reusable workflow passes `--silent=false --reporter=default`: + // diagnostic output from createBrevInstance / waitForSsh / + // waitForLaunchableReady is essential for debugging provisioning + // timing, and the suite has no routine test chatter to suppress. // Gate on a workflow-owned sentinel or Brev auth env. Historically // this used BREV_API_TOKEN (short-lived refresh token); newer // workflows authenticate with BREV_API_KEY + BREV_ORG_ID before