diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index 4e3f1dacd40..dc2d40b9100 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -27,7 +27,7 @@ "src/lib/runner.ts": 88, "src/lib/security/redact.ts": 51, "src/lib/state/onboard-session.ts": 36, - "src/lib/state/registry.ts": 99, + "src/lib/state/registry.ts": 98, "src/lib/state/state-root.ts": 22, "src/lib/subprocess-env.ts": 24, "src/lib/validation.ts": 25 @@ -47,7 +47,7 @@ "src/lib/actions/uninstall/run-plan.ts": 26, "src/lib/inference/onboard-probes.ts": 21, "src/lib/inference/vllm.ts": 21, - "src/lib/onboard.ts": 222, + "src/lib/onboard.ts": 219, "src/lib/onboard/machine/handlers/sandbox.ts": 21, "src/lib/sandbox/config.ts": 22, "src/lib/shields/index.ts": 23 @@ -55,7 +55,7 @@ }, "allowedCycles": [], "maxRootFiles": { - "src/lib/onboard": 308, + "src/lib/onboard": 307, "src/lib/actions": 19, "src/lib/actions/sandbox": 184, "src/lib/state": 37, diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index a99e3c62e35..00d53144795 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -119,7 +119,7 @@ runtime mutation |---|---|---|---|---| | **New interactive or non-interactive onboard** — `onboard()` and `resolveOnboardEntryOptions` | Current flags, environment, and prompts. `MessagingWorkflowPlanner.buildPlan`, `prepareSandboxMessagingPreflight`, resource-profile selection, `resolveSandboxCreateIntent`, and `materializeSandboxCreatePlan` assemble policy, provider, package, resource, host-forward, and runtime-setup contributions. Non-interactive mode replaces prompts with defaults or hard aborts. | Consent/session/lock setup and preflight can persist local state, install OpenShell, or clean stale gateway artifacts before the gateway handler. Gateway reuse/recovery/start is the first provider-routing effect; inference-provider upserts follow. For OpenClaw, messaging selection and plan reconciliation complete before web-search or messaging provider registration. Each validated provider group is then created or updated and checkpointed before resource selection. A name with no live sandbox has no sandbox-destructive boundary; an existing target enters the recreate contract below. | Whole-step session plus machine snapshot. OpenClaw adds narrow checkpoints after each completed secret-free sandbox prompt group; sandbox registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, legacy-value digests, and non-secret names of web-search and messaging providers registered for resume; real values remain process- or gateway-bound. | A non-Docker-GPU readiness failure attempts to delete the failed sandbox; the Docker-GPU patch path preserves it and emits patch-specific recovery diagnostics. Temp build-context cleanup is attempted inline with an exit-handler fallback; cancel rollback applies only to a brand-new sandbox. Coverage: `transition-traces.test.ts`, `sandbox-create-intent-boundary.test.ts`, and `sandbox-create-plan.test.ts`. Gap: gateway upserts can outlive a failed/interrupted create. | | **`--fresh` onboard** — `resolveOnboardEntryOptions`, `prepareFreshSession`, `createBaseImageResolutionContext` | Current flags/environment/prompts replace resumable intent. `--fresh` disables auto-resume and forces base-image resolution; it does not prove that the selected sandbox name is unused. | The first destructive effect is local: the prior onboard session is cleared before a new session is saved. A matching live sandbox can later reuse or recreate through the normal sandbox decision; `--fresh` does not itself delete it. | The new session and machine snapshot replace the old resume checkpoint. Credential and effect boundaries then match new onboard or live recreate. | The discarded resume checkpoint is not restored on later failure. Covered by `entry-options.test.ts`, `session-bootstrap.test.ts`, and base-image resolution tests. | -| **Resume, re-onboard, or recreate** — `onboard()`, `prepareOnboardSession`, `decideSandboxResume`, live-sandbox handling in `createSandbox` | For `--resume`, the recorded session is authoritative and conflicting current name/provider/model/image/tool-disclosure hints are rejected. A new re-onboard run takes current flags, environment, and prompts as intent while registry/gateway state provides drift evidence. The machine resolves a complete secret-free create intent, including policy, messaging/provider, GPU, resource, disabled-channel, and agent inputs, before repair/removal or live recreation. | Ordinary live recreation conditionally backs up before provider cleanup, **delete**, and image removal. The recreate journal preserves the source registry row after deletion. Replacement registration commits the new row after readiness and validation. A selected pre-upgrade backup suppresses a new one; an explicit override permits recreation without backup. Resume registry removal and `repair-and-recreate` now follow complete intent validation. Temporary policy/build artifacts remain materialization effects after the delete boundary. | Resume continues the recorded session/machine snapshot; non-resume re-onboard writes a new session first. OpenClaw records completed sandbox name, web search, messaging, and resource choices with explicit progress markers, including explicit `null` choices, while the complete create intent stays process-local and is not persisted or emitted. Raw credential values remain outside the session. A missing process value can be rebound only when the same OpenClaw session recorded successfully registering that provider and its live provider name, provider type, and credential key still match; otherwise interactive resume requests it again and non-interactive resume exits with environment-variable guidance. Credentials are checked before mutation and again immediately before materialization. | A failed replacement keeps the source registry row. Restore failures warn and can still publish the replacement; managed-DCode live-selection failure leaves a running, unregistered sandbox with manual-delete guidance. Checkpoint replay reuses an exact live sandbox after an interrupted create and backfills missing create/register receipts. Cancel rollback is not armed and there is no rebuild-style receipt rollback. Coverage: transition traces, create-intent characterization, checkpoint replay and resume guards, and sandbox-handler crash recovery. Gaps: early backup asymmetry and no rebuild-style cross-effect rollback. | +| **Resume, re-onboard, or recreate** — `onboard()`, `prepareOnboardSession`, `decideSandboxResume`, live-sandbox handling in `createSandbox` | For `--resume`, the recorded session is authoritative and conflicting current name/provider/model/image/tool-disclosure hints are rejected. A new re-onboard run takes current flags, environment, and prompts as intent while registry/gateway state provides drift evidence. The machine resolves a complete secret-free create intent, including policy, messaging/provider, GPU, resource, disabled-channel, and agent inputs, before repair/removal or live recreation. | Ordinary live recreation conditionally backs up before provider cleanup, **delete**, and image removal. The recreate journal preserves the source registry row after deletion. Replacement registration commits the new row after readiness and validation. A selected pre-upgrade backup suppresses a new one; an explicit override permits recreation without backup. Resume registry removal and `repair-and-recreate` occur only after complete intent validation. Temporary policy/build artifacts remain materialization effects after the delete boundary. | Resume continues the recorded session/machine snapshot; non-resume re-onboard writes a new session first. OpenClaw records completed sandbox name, web search, messaging, and resource choices with explicit progress markers, including explicit `null` choices, while the complete create intent stays process-local and is not persisted or emitted. Raw credential values remain outside the session. A missing process value can be rebound only when the same OpenClaw session recorded successfully registering that provider and its live provider name, provider type, and credential key still match; otherwise interactive resume requests it again and non-interactive resume exits with environment-variable guidance. Credentials are checked before mutation and again immediately before materialization. | A failed replacement keeps the source registry row. Restore failures warn and can still publish the replacement; managed-DCode live-selection failure leaves a running, unregistered sandbox with manual-delete guidance. Checkpoint replay reuses an exact live sandbox after an interrupted create and backfills missing create/register receipts. Cancel rollback is not armed and there is no rebuild-style receipt rollback. Coverage: transition traces, create-intent characterization, checkpoint replay and resume guards, and sandbox-handler crash recovery. Gaps: early backup asymmetry and no rebuild-style cross-effect rollback. | | **Rebuild or installer-driven upgrade** — `rebuildSandbox` in `rebuild-pipeline.ts`; `upgradeSandboxes` | Registry state is authoritative. A matching session may fill guarded legacy gaps only when its selection agrees; an unrelated/global session is never used. Ambient provider/model selection is quarantined by `isolateAmbientRecreateEnv`, apart from narrowly scoped legacy recovery. Preflight assembles target config, messaging/policy/runtime inputs, recovery inputs, and a retained replacement context. Generic agents use `preflightRebuildImage`; DCode uses its specialized managed-context preflight instead and proves the live route only for normal live rebuild. Resource profile is not part of preflight. | Consent persistence, target-gateway selection/recovery, and target-preflight registry updates can precede disposable image build/probes. Backup is the first durable recovery checkpoint when available. Shields unlock, MCP detach/scrub, and NIM stop are destructive in-place effects before the **sandbox delete** boundary. Prepared context and mutation-edge conditions are rechecked before delete, proving buildability/input identity but not replacement health or atomic swap. | Durable checkpoints are the backup/recovery manifest when one exists and the rewritten recreate session; stale recovery can reach deletion without a manifest, making that session its first new durable checkpoint. Rollback receipts/snapshots are process-local. Credential metadata comes from the target or guarded fallback; raw credentials/providers are checked against current process/gateway state, while prepared installer recovery may reconstruct a missing gateway provider from a validated host credential. | In-process rollback best-effort restores registry/MCP retry metadata, but process death after non-MCP delete can still lose it. The inner onboard selects resource profile after deletion from non-quarantined ambient input. Covered by rebuild, image-preflight, DCode, and messaging tests. Gaps: post-delete resource intent plus health-before-delete and atomic swap. Closed issue #5801 records the original gap; #6835 fixed only the printed recovery path. | | **Managed snapshot clone handoff and provider transaction (internal and dormant)** — `prepareManagedWorkloadCloneHandoff`; `prepareManagedCloneProviderTransaction` | The current source registry row owns mutable operator intent; the selected snapshot owns immutable managed-workload and provider-runtime history. Handoff preparation proves the selected runtime provider and its `clone` capability, exact current registry generation and live-identity fingerprint, snapshot/source workload equivalence, snapshot runtime generation, and the state layer's selected-manifest/payload digest. It rebinds the secret-free startup profile, messaging intent, dashboard identity, and provider-owned contributions for OpenClaw, Hermes, or DCode without a central Podman-specific switch. Provider preparation then resolves active application bindings plus provider-contributed bindings, treating a live exact provider as reusable only when the destination registry independently proves that same logical binding. | The handoff and provider plan are inert. The internal materializer can create only bindings proven absent at preflight; it never updates or deletes an existing destination-owned provider. Immediately before each create it revalidates the source and optional destination registry rows plus the exact `SnapshotRestoreAuthority`. Production snapshot restore does not invoke this transaction and continues to reject cross-sandbox managed-image restore through `rejectManagedSnapshotCloneUntilRebind`; no user-visible clone support is advertised. | Both plans are deeply frozen and secret-free. A successful create produces an exact process-local ownership receipt; a non-zero create reconciled to an exact provider remains ambiguous and unowned. The receipt ledger remembers completed cleanup so a repeated cleanup cannot delete a later same-name provider. Raw credentials exist only in the explicit apply environment and one OpenShell child environment. | Failure rolls back only providers confirmed created by the exact in-process receipt, preserves collisions and ambiguous creates, reports incomplete cleanup for retry, and never rewrites a reused provider. `src/lib/onboard/managed-workload-clone-handoff.test.ts`, `src/lib/onboard/managed-startup-clone-rebinder.test.ts`, and `src/lib/actions/sandbox/snapshot-managed-clone-handoff-dormancy.test.ts` cover the all-agent, Docker/MXC-style provider, canonical-name, and fail-closed boundaries; provider transaction tests cover race, force-replace, disappearing-credential, rollback, and idempotent cleanup. This PR intentionally covers only the dormant contract. Epic [#7744](https://github.com/NVIDIA/NemoClaw/issues/7744) tracks destination creation/bootstrap, filesystem mutation-edge invocation, Hermes broker activation, durable recovery, protected E2E, and user-visible activation. | | **Channel add/remove/start/stop** — `addSandboxChannel`, `removeSandboxChannel`, `sandboxChannelsSetEnabled` in `policy-channel.ts` | Add compiles and merges a manifest-derived channel delta with `MessagingWorkflowPlanner`. Start, stop, and remove transform the registry plan and rehydrate executable render/build/runtime/forward details from current manifests. | Token-backed add can mutate gateway credentials before policy and plan persistence; QR/in-sandbox-auth add skips that credential upsert. Start persists the enabled plan before policy; stop persists the disabled plan before the rebuild prompt. Remove clears QR-backed durable state when applicable, detaches gateway/bridge state, removes policy, then persists the plan. A queued rebuild has a separate delete boundary. | The compact registry messaging plan is authoritative; render/build/runtime/state/health entries and nested host-forward details are rehydrated rather than persisted. Session policy-preset sync is best-effort, and channel mutations do not rewrite `Session.messagingPlan`. Raw tokens stay in process/gateway bindings. | `rollbackChannelAdd`, re-disable after failed start, and fail-closed QR-state cleanup provide partial compensation. Covered by `policy-channel*.test.ts`, `workflow-planner.test.ts`, and channel integration tests. Gaps: channel add has a separate `--force` conflict policy; add/remove effects can precede plan persistence, and persistence failures are not fully rolled back. | diff --git a/src/lib/onboard/machine/resume-provider-shim.ts b/src/lib/onboard/machine/resume-provider-shim.ts index 7ef41e25b91..d5035d533c1 100644 --- a/src/lib/onboard/machine/resume-provider-shim.ts +++ b/src/lib/onboard/machine/resume-provider-shim.ts @@ -1,8 +1,5 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// -// Connects provider recovery to the core onboarding flow. - import { runOpenshell } from "../../adapters/openshell/runtime"; import { D, R } from "../../cli/terminal-style"; import { isBedrockRuntimeEndpoint } from "../../inference/bedrock-runtime"; diff --git a/test/package-contract/helpers/package-fixture.ts b/test/package-contract/helpers/package-fixture.ts new file mode 100644 index 00000000000..1f3ba50df7c --- /dev/null +++ b/test/package-contract/helpers/package-fixture.ts @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { copyFileSync, cpSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const REPOSITORY_ROOT = path.join(import.meta.dirname, "..", "..", ".."); + +export function createPackageFixture(options: { + readonly prefix: string; + readonly entries: readonly string[]; +}): string { + const fixtureRoot = mkdtempSync(path.join(tmpdir(), options.prefix)); + const packageJson = JSON.parse( + readFileSync(path.join(REPOSITORY_ROOT, "package.json"), "utf8"), + ) as { scripts?: Record }; + + // npm runs `prepare` when it packs a local directory, even with + // `--ignore-scripts`. Remove package scripts so parallel package-contract + // workers only read `dist`. + packageJson.scripts = {}; + writeFileSync( + path.join(fixtureRoot, "package.json"), + `${JSON.stringify(packageJson, null, 2)}\n`, + ); + copyFileSync(path.join(REPOSITORY_ROOT, ".gitignore"), path.join(fixtureRoot, ".gitignore")); + + for (const entry of options.entries) { + const destination = path.join(fixtureRoot, entry); + mkdirSync(path.dirname(destination), { recursive: true }); + cpSync(path.join(REPOSITORY_ROOT, entry), destination, { recursive: true }); + } + + return fixtureRoot; +} diff --git a/test/package-contract/managed-image-registry-transport.test.ts b/test/package-contract/managed-image-registry-transport.test.ts index 0b3e2621718..2b780c1e2ad 100644 --- a/test/package-contract/managed-image-registry-transport.test.ts +++ b/test/package-contract/managed-image-registry-transport.test.ts @@ -8,6 +8,8 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; +import { createPackageFixture } from "./helpers/package-fixture"; + const repoRoot = path.join(import.meta.dirname, "..", ".."); describe("managed image registry transport package contract", () => { @@ -35,12 +37,16 @@ describe("managed image registry transport package contract", () => { }; expect(productionDependencies.dependencies?.undici?.version).toBe("8.10.0"); + const fixtureRoot = createPackageFixture({ + prefix: "nemoclaw-managed-registry-pack-", + entries: ["dist"], + }); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-registry-package-")); try { const packed = spawnSync( "npm", ["pack", "--ignore-scripts", "--silent", "--pack-destination", tempDir], - { cwd: repoRoot, encoding: "utf8", timeout: 120_000 }, + { cwd: fixtureRoot, encoding: "utf8", timeout: 120_000 }, ); expect(packed.status, `${packed.stdout}${packed.stderr}`).toBe(0); const archives = fs.readdirSync(tempDir).filter((entry) => entry.endsWith(".tgz")); @@ -105,6 +111,7 @@ session.close().then( expect(probe.status, `${probe.stdout}${probe.stderr}`).toBe(0); expect(probe.stdout).toBe("constructed"); } finally { + fs.rmSync(fixtureRoot, { recursive: true, force: true }); fs.rmSync(tempDir, { recursive: true, force: true }); } }); diff --git a/test/package-contract/managed-inference-catalog.test.ts b/test/package-contract/managed-inference-catalog.test.ts index 23976654e7d..d57c00092ec 100644 --- a/test/package-contract/managed-inference-catalog.test.ts +++ b/test/package-contract/managed-inference-catalog.test.ts @@ -2,16 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { execFileSync } from "node:child_process"; -import { - copyFileSync, - cpSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, rmSync } from "node:fs"; import path from "node:path"; import { describe, expect, it } from "vitest"; @@ -21,36 +12,10 @@ import catalogSchema from "../../managed-inference/schemas/catalog.schema.json" }; import presetSchema from "../../managed-inference/schemas/preset.schema.json" with { type: "json" }; import recipeSchema from "../../managed-inference/schemas/recipe.schema.json" with { type: "json" }; +import { createPackageFixture } from "./helpers/package-fixture"; const REPOSITORY_ROOT = path.join(import.meta.dirname, "..", ".."); -function createPackFixture(): string { - const fixtureRoot = mkdtempSync(path.join(tmpdir(), "nemoclaw-serving-catalog-pack-")); - const packageJson = JSON.parse( - readFileSync(path.join(REPOSITORY_ROOT, "package.json"), "utf8"), - ) as { scripts?: Record }; - // Local-directory packs always prepare first; keep this fixture scoped to packlist behavior. - packageJson.scripts = {}; - - writeFileSync( - path.join(fixtureRoot, "package.json"), - `${JSON.stringify(packageJson, null, 2)}\n`, - ); - copyFileSync(path.join(REPOSITORY_ROOT, ".gitignore"), path.join(fixtureRoot, ".gitignore")); - mkdirSync(path.join(fixtureRoot, "dist"), { recursive: true }); - cpSync( - path.join(REPOSITORY_ROOT, "dist", "managed-inference"), - path.join(fixtureRoot, "dist", "managed-inference"), - { recursive: true }, - ); - cpSync( - path.join(REPOSITORY_ROOT, "managed-inference"), - path.join(fixtureRoot, "managed-inference"), - { recursive: true }, - ); - return fixtureRoot; -} - describe("compiled managed inference serving catalog", () => { it("build output contains a schema-valid catalog with a source revision and matching digest (#8144)", () => { const source = readFileSync( @@ -65,7 +30,10 @@ describe("compiled managed inference serving catalog", () => { }); it("includes the compiled catalog in the npm package (#8144)", () => { - const fixtureRoot = createPackFixture(); + const fixtureRoot = createPackageFixture({ + prefix: "nemoclaw-serving-catalog-pack-", + entries: ["dist/managed-inference", "managed-inference"], + }); try { const result = JSON.parse( execFileSync("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], { diff --git a/test/package-contract/openshell-policy-boundary.test.ts b/test/package-contract/openshell-policy-boundary.test.ts index 5cb1809f531..5743dd49329 100644 --- a/test/package-contract/openshell-policy-boundary.test.ts +++ b/test/package-contract/openshell-policy-boundary.test.ts @@ -12,6 +12,7 @@ import { describe, expect, it } from "vitest"; import YAML from "yaml"; import { auditOpenShellPolicyBoundaryDependencies } from "../../scripts/checks/verify-openshell-policy-boundary-dependencies.mts"; +import { createPackageFixture } from "./helpers/package-fixture"; const repoRoot = path.join(import.meta.dirname, "..", ".."); const require = createRequire(import.meta.url); @@ -227,13 +228,17 @@ describe("OpenShell policy boundary package contract", () => { }; expect(productionDependencies.dependencies?.ajv?.version).toMatch(/^8\./u); + const fixtureRoot = createPackageFixture({ + prefix: "nemoclaw-policy-pack-", + entries: ["dist", "schemas"], + }); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-package-")); try { const packed = spawnSync( "npm", ["pack", "--ignore-scripts", "--silent", "--pack-destination", tempDir], { - cwd: repoRoot, + cwd: fixtureRoot, encoding: "utf8", env: { ...process.env, npm_config_cache: path.join(tempDir, "npm-cache") }, }, @@ -319,6 +324,7 @@ process.stdout.write("validated"); expect(probe.status, `${probe.stdout}${probe.stderr}`).toBe(0); expect(probe.stdout).toBe("validated"); } finally { + fs.rmSync(fixtureRoot, { recursive: true, force: true }); fs.rmSync(tempDir, { recursive: true, force: true }); } });