From 0f6e6deb3457dd0a791a1ceef30c6f5ca89fd146 Mon Sep 17 00:00:00 2001 From: Abhimanyu Kumar Date: Sat, 4 Jul 2026 04:12:35 +0530 Subject: [PATCH 1/3] chore(architecture): map and characterize onboarding lifecycle contracts (#6225) Add the onboarding lifecycle contract map (src/lib/onboard/AGENTS.md): epic #6224 vocabulary, per-journey contract tables for create, rebuild, re-onboard, and runtime mutation, seven cross-journey divergences with code anchors, and a bug-to-contract-gap table for the epic's evidence issues, with pointers from machine/README.md and the root AGENTS.md. Pin current behavior as an executable characterization baseline before the #6226/#6227 refactors move it: - machine/transition-traces.test.ts: legal-transition surface and full event traces for fresh-run, resume, recreate, and mid-flow failure. Failed-state exit legality and the legacy step-mutation bridge are deliberately not pinned; PR #6253 owns those semantics. - test/onboard-lifecycle-invariants.test.ts: create-path ordering invariants (conflict guard before sandbox delete, deterministic validation before the destructive boundary, cleanup-before-upsert, resume identity per #2753). - test/onboard-session-secret-invariants.test.ts: session persistence secret boundary (credentialEnv name-only, endpointUrl redaction, sha256-only legacy hashes, unset/declined ambiguity pinned as a known #6224 contract gap). Zero production-code changes. Signed-off-by: Abhimanyu Kumar --- AGENTS.md | 1 + src/lib/onboard/AGENTS.md | 249 ++++++ src/lib/onboard/machine/README.md | 4 + .../onboard/machine/transition-traces.test.ts | 658 +++++++++++++++ test/onboard-lifecycle-invariants.test.ts | 769 ++++++++++++++++++ .../onboard-session-secret-invariants.test.ts | 361 ++++++++ 6 files changed, 2042 insertions(+) create mode 100644 src/lib/onboard/AGENTS.md create mode 100644 src/lib/onboard/machine/transition-traces.test.ts create mode 100644 test/onboard-lifecycle-invariants.test.ts create mode 100644 test/onboard-session-secret-invariants.test.ts diff --git a/AGENTS.md b/AGENTS.md index 4d99c7037a2..743110c8bac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,6 +36,7 @@ Load the `nemoclaw-skills-guide` skill for a full catalog and quick decision gui Package-specific guides: - Messaging architecture and channel migration guidance: [`src/lib/messaging/AGENTS.md`](src/lib/messaging/AGENTS.md) +- Onboarding and runtime lifecycle contract map: [`src/lib/onboard/AGENTS.md`](src/lib/onboard/AGENTS.md) ## Quick Reference diff --git a/src/lib/onboard/AGENTS.md b/src/lib/onboard/AGENTS.md new file mode 100644 index 00000000000..38eb893c9c0 --- /dev/null +++ b/src/lib/onboard/AGENTS.md @@ -0,0 +1,249 @@ + + + +# Agent Instructions for `src/lib/onboard` + +## Purpose + +This document is the lifecycle contract map required by issue #6225 (epic #6224). It records, for every onboarding and runtime-mutation journey, where desired state comes from, what is validated before effects, where the first externally visible and first destructive effects happen, what is checkpointed, where the credential boundary sits, and what compensation exists today. + +This is a characterization map. It describes current behavior, including behavior the epic considers a contract gap. Nothing in this file is a target design; target designs live in the child issues (#6226, #6227, #6228) and in `machine/README.md`. + +Companion documents: + +- `src/lib/onboard/README.md` covers file placement for the `onboard.ts` split. +- `src/lib/onboard/machine/README.md` covers the FSM target architecture, state vocabulary, and handler contract. +- `src/lib/messaging/AGENTS.md` covers the messaging package this map frequently crosses into. + +Line anchors below were verified against the tree this document was committed with. Symbol names are the stable reference; treat line numbers as hints that drift. + +## Shared Lifecycle Vocabulary + +### Epic terminology (from #6224, use verbatim) + +- **Lifecycle contribution.** An internal, data-first input to a NemoClaw plan: policy, provider, package, port-forward, resource, or runtime setup. Not a public SDK. +- **Managed agent package.** A package NemoClaw records as desired state for an agent runtime (OpenClaw, Hermes, Deep Agents Code). #5998 owns the narrow user-facing managed OpenClaw package lifecycle (CLI and desired-state MVP), not this epic. +- **Agent-native plugin.** A plugin interpreted by OpenClaw, Hermes, or another agent runtime. +- **NemoClaw plugin SDK.** Reserved for a future versioned external contract. Epic #6224 does not create one, and nothing in this package should be documented as one before the #6229 decision record exists. + +### Lifecycle verbs + +These definitions describe how the terms are used in this map. They are grounded in current code artifacts and in epic #6224's principles (plan before effects; persist data, bind capabilities at apply time; version and revalidate resumed plans; one vocabulary across create, rebuild, re-onboard, reconcile). + +| Term | Meaning in this map | Current code artifact | +|---|---|---| +| intent | Deterministic, serializable description of a desired outcome, derived from operator inputs and recorded selections before any effect runs. Contains logical bindings (credential env-var names, presence flags), never secret values, temp paths, callbacks, or process handles. | `SandboxCreateIntent` (`sandbox-create-intent-types.ts:41`), produced by the pure `resolveSandboxCreateIntent` (`sandbox-create-plan.ts:228`). Explicitly not a persistence, machine-event, or public API contract. | +| plan | The compiled form of an intent plus observed state, ready to execute. The codebase has two flavors today: serializable plans (`SandboxMessagingPlan`) and execution plans that carry temp paths and cleanup callbacks (the return value of `materializeSandboxCreatePlan`). | `MessagingWorkflowPlanner.buildPlan` (`src/lib/messaging/compiler/workflow-planner.ts:44`); `materializeSandboxCreatePlan` (`sandbox-create-plan.ts:334`). | +| apply | The effectful phase. Capabilities (credential values, live handles, gateway connections) are bound at apply time, not stored in intent or checkpoints. | `bindMessagingTokenDefs` (`sandbox-create-plan.ts:298`) rebinds real tokens at materialization and fails on drift; gateway upserts happen inside `materializeSandboxCreatePlan`. | +| checkpoint | Durable, secret-free record of progress that a later run can resume from. | The onboard session (`~/.nemoclaw/onboard-session.json`, `src/lib/state/onboard-session.ts:39`) with whole-step granularity plus the machine snapshot; pre-recreate workspace backups; the rebuild backup manifest. | +| result | The explicit outcome a state handler returns to the machine: advance, retry, branch, complete, or failed. | `OnboardStateResult` (`machine/result.ts`), applied through `OnboardRuntime.applyResult` and the `OnboardRuntimeBoundary` facade (`runtime-boundary.ts`). | +| compensation | Effects run after a failure or cancellation to undo or mitigate a partially applied journey. | Failed-create sandbox deletion (`onboard.ts:3052`); cancel rollback (`cancel-rollback.ts`); `rollbackChannelAdd` (`src/lib/actions/sandbox/policy-channel.ts:1079`); rebuild's recovery-registry restore (`rebuild-recreate-phase.ts:206`). | +| reconcile | Bringing recorded desired state and observed live state back into agreement without a full re-run. | Drift detection in `createSandbox` (`onboard.ts:2614-2635`); `reconcileSandboxMessaging` (`machine/handlers/sandbox-messaging.ts:253`); `mergeOpenClawRestoredConfig` ownership rules (`src/lib/state/openclaw-config-merge.ts:17`). | + +## Machine states and production owners + +The 13 machine states (`machine/definition.ts:12-65`) and their transition table (`machine/transitions.ts:11-29`: the linear advance chain, the `inference -> provider_selection` retry, the `sandbox -> openclaw | agent_setup` branch, and every non-terminal state `-> failed`). Every non-terminal state has exactly one production owner: + +| State | Production owner | +|---|---| +| `init` | Entered by session bootstrap; advanced to `preflight` directly by `onboard()` (`onboard.ts:4771`) before the first slice runs. | +| `preflight` | `machine/handlers/preflight.ts` | +| `gateway` | `machine/handlers/gateway.ts` | +| `provider_selection`, `inference` | `machine/handlers/provider-inference.ts` (composite handler with declared sequence ownership) | +| `sandbox` | `machine/handlers/sandbox.ts`, with the resume decision in `handlers/sandbox-resume.ts:50` and messaging reconciliation in `handlers/sandbox-messaging.ts:253` | +| `openclaw`, `agent_setup` | `machine/handlers/agent-setup.ts` (agent branch) | +| `policies` | `machine/handlers/policies.ts` | +| `finalizing`, `post_verify` | `machine/handlers/finalization.ts` | +| `complete`, `failed` | Terminal; no handler. | + +The FSM is deliberately step-granular. Mid-operation resume inside gateway startup, sandbox creation, credential upserts, model probes, or policy application is out of scope for the current machine (`machine/types.ts:4-10`). This is the root of several checkpoint gaps below. + +## Journey Contract Matrix + +Summary: + +| Journey | Entry point | Desired-state source | First destructive effect | Durable checkpoint | +|---|---|---|---|---| +| 1. Sandbox create (fresh onboard) | `onboard()` (`src/lib/onboard.ts:4610`) | Flags + env + prompts of the current run | None against prior state; creation itself at `streamSandboxCreate` (`onboard.ts:2968`) | Whole-step session + machine snapshot | +| 2. Rebuild / installer upgrade | `rebuildSandbox` (`rebuild-pipeline.ts:34` via the `rebuild.ts` facade) | Registry entry + matching session only; ambient env quarantined | `openshell sandbox delete` (`rebuild-destroy-phase.ts:81`) | Backup manifest + session rewritten as recreate contract + recovery registry snapshot | +| 3. Re-onboard / resume over existing sandbox | Same `onboard()`, live-sandbox block of `createSandbox` (`onboard.ts:2571`) | Current run's env/flags/prompts; registry and gateway used as drift baseline | Delete + `docker rmi` + registry removal (`onboard.ts:2836-2847`) | Pre-recreate workspace backup + session | +| 4. Runtime mutation (provider switch, config set, channels, plugin entries) | `inference-set.ts`, `sandbox/config.ts`, `policy-channel.ts` | CLI flags + registry/session metadata; per-channel delta plans | None in-place; channel changes defer destruction to a queued rebuild | Audit entries + registry plan persistence | + +### Journey 1: sandbox create (fresh onboard, interactive and non-interactive) + +| Contract dimension | Current behavior | +|---|---| +| Desired-state source | Flags, env, and TTY prompts resolved by `resolveOnboardEntryOptions` (`entry-options.ts:46`; auto-resume of an in-progress session at line 63). Provider/model/endpoint selected in the `provider_selection`/`inference` states. Messaging plan compiled by `MessagingWorkflowPlanner.buildPlan` and transported through process env `NEMOCLAW_MESSAGING_PLAN_B64` (`src/lib/messaging/applier/types.ts:20`). Create intent resolved by `resolveSandboxCreateIntent` (`sandbox-create-plan.ts:228`). | +| Deterministic planning/validation | `preflight()` host checks (`onboard.ts:1594`); early env validation and onboard lock (`onboard.ts:4659-4662`); messaging conflict guard inside `prepareSandboxMessagingPreflight` (`onboard.ts:2524` -> `sandbox-messaging-preflight.ts:63` -> `messaging-conflict-guard.ts:65`); `resolveSandboxCreateIntent` is pure and deterministic. | +| First externally visible effect | Gateway reuse/recover/start in the `gateway` state (`startGateway`, `onboard.ts:2276`). Inference-provider credential upserts to the gateway happen during `provider_selection`/`inference` (`upsertProvider`, `onboard.ts:898`), before any sandbox exists. | +| First destructive effect | None against pre-existing sandbox state on a truly fresh create. Gateway messaging-provider upserts run with `replaceExisting: true` inside `materializeSandboxCreatePlan` (`sandbox-create-plan.ts:372`), which overwrites same-name provider entries in shared gateway state. Creation itself is `streamSandboxCreate` (`onboard.ts:2968`). | +| Checkpoints | Whole-step session (`Session`, `onboard-session.ts:84`; 8 fixed steps; atomic tmp+rename save) plus machine snapshot, written through `OnboardRuntimeBoundary`. Registry registration is deferred until the sandbox is confirmed ready (`registerCreatedSandbox`, `onboard.ts:3108`) to prevent phantom entries. There is no sub-step checkpoint. | +| Credential/secret boundary | Session persists `credentialEnv` as an env-var name only (`onboard-session.ts:100`), `endpointUrl` redacted at save (`onboard-session.ts:492`), legacy credential migration as sha256 hashes only (`onboard-session.ts:122`). `SandboxCreateIntent` carries presence flags and env keys, never values; real tokens are rebound at apply time by `bindMessagingTokenDefs` (`sandbox-create-plan.ts:298`), which fails closed on availability or provider-type drift. | +| Retry/compensation/rollback | Readiness failure deletes the failed new sandbox (`onboard.ts:3052`) and exits with retry hints. Build-context temp dirs (which can hold env-arg API keys) are cleaned inline with a process-exit safety net (`onboard.ts:2856`, `2988`). Two-key cancel rollback is armed only for a brand-new sandbox (`onboard.ts:3175`) and clears the session when it fires (`cancel-rollback.ts:157`). Nonzero exit marks the last started step failed (`exit-step-failure.ts:19`, registered at `onboard.ts:4794`). | +| Extension assembly points | All current lifecycle contributions converge in `prepareSandboxCreatePlan` (`onboard.ts:2880`): messaging channel manifests (via token defs and the plan env), policy presets (`initialSandboxPolicy`), extra providers from the registry, Hermes tool gateways, GPU create args, resource-profile flags. Web-search reaches the create args only indirectly (BRAVE/TAVILY keys via `extra-placeholder-keys.ts` and the extra-provider registry); its plugin-entry/config rendering flows through the build patch and `web-search-flow.ts`, outside the create plan. | +| Existing tests / known-uncovered failure modes | Tests: `sandbox-create-plan.test.ts` (#6218 characterization), `machine/handlers/sandbox.test.ts`, the `machine/*.test.ts` suite, `test/onboard.test.ts`, `test/onboard-selection.test.ts`, `test/onboard-messaging.test.ts`. Uncovered: process death between gateway provider upserts and sandbox create leaves gateway credential state changed with no sandbox; no test pins gateway provider state after a mid-create failure; no mid-step resume (by design, `machine/types.ts:4-10`). | + +Interactive and non-interactive runs share this contract; non-interactive substitutes env defaults and hard aborts for prompts (`non-interactive-abort.ts`, and the `isNonInteractive()` branches in `createSandbox`). + +### Journey 2: rebuild, including installer-driven upgrade + +Installer batch upgrades call the same pipeline: `upgradeSandboxes` invokes `rebuildSandbox(name, ["--yes"], { recoveryManifest, ... })` (`src/lib/actions/upgrade-sandboxes.ts:310`). + +| Contract dimension | Current behavior | +|---|---| +| Desired-state source | Registry entry + matching session only, never ambient env: `prepareRebuildResumeConfig` (`rebuild-resume-config.ts:224`, the #5735 pre-delete trust boundary; custom-endpoint URLs fail closed if recorded only in another sandbox's session). Ambient `NEMOCLAW_*` selection env is quarantined for the recreate by `isolateAmbientRecreateEnv` (`rebuild-env-isolation.ts:116`, applied at `rebuild-recreate-phase.ts:177`). Messaging comes from the registry-persisted plan: `stageRebuildMessagingPlanOrBail` (`rebuild-messaging-phase.ts:81`) -> `buildRebuildPlanFromSandboxEntry` (`workflow-planner.ts:116`). | +| Deterministic planning/validation | All before destruction, in `runRebuildPreflightPhase` (`rebuild-preflight-phase.ts:68`): registry entry snapshot pinned and re-asserted unchanged after confirmation (`:77`, `:124`); gateway schema; recovery-manifest validation; confirmation; onboard lock; then `prepareRebuildTargetPreflights` (`rebuild-preflight-target-phase.ts:40`): target config, recreate options, messaging plan staged (`:81`), messaging conflict preflight (#5954) immediately after staging (`:90` -> `rebuild-messaging-conflict-preflight.ts:49`, forced non-interactive abort), authoritative runtime preflight, base image, target runtime. DCode rebuilds additionally prebuild and fingerprint the replacement image pre-delete (#6214): `prepareDcodeReplacementBeforeMutation` (`rebuild-dcode-preflight.ts:354`). Mutation-edge revalidation runs immediately before deletion: `revalidatePreparedRecoveryBeforeDelete` (`rebuild-pipeline.ts:119`) and `dcodePreflight.revalidateBeforeDelete` (`rebuild-pipeline.ts:146` -> `revalidateDcodeReplacementAtMutationEdge`, `rebuild-dcode-preflight.ts:415`). | +| First externally visible effect | Shields auto-unlock window (`runRebuildShieldsPhase`, `rebuild-pipeline.ts:104`) and the validated-target registry update at the end of preflight (`rebuild-preflight-target-phase.ts:135`). In the destroy phase, MCP adapter scrub/provider detach and NIM container stop precede deletion (`rebuild-destroy-phase.ts:57-70`). | +| First destructive effect | `openshell sandbox delete` (`rebuild-destroy-phase.ts:81`), then registry entry removal (`:113`; the entry is intentionally preserved when MCP entries exist, as the durable MCP rebuild transaction). | +| Checkpoints | Workspace backup manifest (`runRebuildBackupPhase`, `rebuild-backup-phase.ts:35`, or a validated installer `recoveryManifest`); session rewritten wholesale as the recreate contract with preflight/gateway pre-marked complete and provider/model/credential-env/endpoint pinned (`rebuild-recreate-phase.ts:103-149`); registry snapshot taken for recovery recreates (`rebuild-pipeline.ts:100`). | +| Credential/secret boundary | Credential preflight before any destruction (`rebuild-credential-preflight.ts`); session and registry carry env-var names and redacted endpoints only; the scoped-env facade saves and restores mutation-prone env keys around the whole pipeline (`rebuild-pipeline.ts:40-59`). | +| Retry/compensation/rollback | Recreate runs `onboard()` in-process with `process.exit` intercepted by a sentinel throw (`rebuild-recreate-phase.ts:163-196`). On failure: `markLastStartedStepFailed` (`:201`); registry snapshot restore only for recovery recreates (`:206-217`); backup path preserved and manual `snapshot restore` instructions printed (`:229-239`); MCP registry restore for retry (`:218`); shields relocked (`:242` and the pipeline `finally` at `rebuild-pipeline.ts:231`). On success: restore phase + post-restore phase reapply state, policy presets, and messaging hooks (`rebuild-pipeline.ts:206-229`). | +| Extension assembly points | Messaging plan restaged from manifests; policy presets restored from backup manifest and registry; MCP entries carried through the registry entry; `plugins.entries` merged under the ownership contract `OPENCLAW_CONFIG_RESTORE_OWNERSHIP` (`openclaw-config-merge.ts:17-23`: current generated entries win by id, backup-only user entries kept). | +| Existing tests / known-uncovered failure modes | Tests: `rebuild-flow.test.ts`, `rebuild-resume-config.test.ts`, `rebuild-dcode-flow.test.ts`, `rebuild-messaging-conflict-preflight.test.ts`, `rebuild-env-isolation.test.ts`, `rebuild-resume-snapshot.test.ts`, `rebuild-shields-finally.test.ts`. Uncovered: a plain (non-recovery) recreate failure leaves no registry entry, only a backup and printed instructions; non-DCode rebuilds build the replacement image only after deletion, so a build failure strands the operator on the recovery path. | + +### Journey 3: re-onboard and resume over an existing sandbox + +Two sub-modes share `onboard()`: (a) the live-sandbox block in `createSandbox` (`onboard.ts:2571-2848`), and (b) the `--resume` decision `decideSandboxResume` (`machine/handlers/sandbox-resume.ts:50`: create / reuse / recreate / repair-and-recreate), applied by `machine/handlers/sandbox.ts`. + +| Contract dimension | Current behavior | +|---|---| +| Desired-state source | The current run's env, flags, and prompts. Registry and gateway are only a drift baseline: agent drift (`onboard.ts:2574`), provider migration need (`:2614`), selection drift via live gateway probe (`:2617`), GPU drift (`:2619`), Hermes tool-gateway and dashboard drift (`:2624-2629`), messaging credential rotation (`:2635`). Restore intent (#6130) is keyed on installer env `NEMOCLAW_RESTORE_LATEST_BACKUP_ON_RECREATE=1` (`not-ready-recreate.ts:56`), consumed at `onboard.ts:2564` (`selectPreUpgradeBackupForCreate`) and `onboard.ts:2711` (`resolveNotReadyOutcome`; without the flag a non-interactive not-ready sandbox blocks with hints). | +| Deterministic planning/validation | Messaging conflict guard runs pre-delete (`onboard.ts:2524`), unlike pre-#5954 rebuild. CPU-sandbox-vs-GPU-request reuse guard (`:2655-2666`). Interactive confirm gates for recreate (`:2718-2762`). MCP-managed sandboxes refuse the generic recreate path and are redirected to `rebuild` (`:2804-2812`). Resume conflicts (`getResumeConfigConflicts`, `resume-config.ts:101`: sandbox name only counts if the sandbox step completed, #2753; provider/model hints; `--from` path equality) exit before any effect. Terminal machine snapshots are repaired only per `classifyResumeMachineRepair` (`resume-repair-policy.ts:34`: failed, or inconsistently reopened complete) by `repairResumeMachineSnapshot` (`resume-machine-repair.ts:52`). | +| First externally visible effect | Same as journey 1 (gateway state, provider upserts). On reuse fast paths, messaging providers are upserted without any deletion (`onboard.ts:2677`, `:2735`). | +| First destructive effect | `onboard.ts:2836-2847`: provider pre-delete cleanup, `openshell sandbox delete` (`:2837`), `docker rmi` of the previous image (`:2839`), `registry.removeSandbox` (`:2847`). | +| Checkpoints | `backupSandboxBeforeRecreate` (`onboard.ts:2770` for credential rotation, `:2824` general; `sandbox-backup-on-recreate.ts:25`). Fail-closed: a failed backup aborts the recreate unless `NEMOCLAW_RECREATE_WITHOUT_BACKUP=1`. Skipped when a pre-upgrade backup was already selected or a not-ready recreate is in progress (`:2817-2822`). | +| Credential/secret boundary | Same session redaction rules as journey 1. `migratedLegacyValueHashes` is trusted on resume only entry-by-entry when the sha256 of the currently staged legacy value matches. | +| Retry/compensation/rollback | Workspace restore after create (`onboard.ts:3128-3142`); default-sandbox restoration deferred to post-create (`:3126`, #4614); cancel rollback deliberately not armed for recreates (`:3175` gate). There is no registry snapshot restore on this path; a failed recreate relies on session + backup + `onboard --resume`. | +| Extension assembly points | Policy presets carried forward across recreate (`policyPresetCarry.applyRecreatePolicyCarryForward`, `onboard.ts:2815`); messaging channels re-resolved by `reconcileSandboxMessaging` (`handlers/sandbox-messaging.ts:253-269`) in the order: recorded channels, env plan, registry plan, then `session.messagingPlan`. | +| Existing tests / known-uncovered failure modes | Tests: `session-bootstrap.test.ts`, `resume-machine-repair.test.ts`, `entry-options.test.ts`, `machine/handlers/sandbox-resume.test.ts`, `machine/handlers/sandbox.test.ts`, `not-ready-recreate.test.ts`, `sandbox-backup-on-recreate.test.ts`. Uncovered: resume identity when the sandbox step never completed (session may lack `sandboxName`; #5961/#5783 territory); interrupted-run snapshot shapes outside the two repaired classes (#6040); no pinning of the delete-then-create window (process death there leaves neither sandbox nor registry entry). | + +### Journey 4: runtime mutation + +Four surfaces. The `nemoclaw` OpenClaw plugin's TUI commands are read-only; all mutation is host CLI. + +**4a. Provider/model switch** (`nemoclaw inference set` -> `runInferenceSet`, `src/lib/actions/inference-set.ts:826`, serialized by a timer-bound shields mutation lock at `:838`): + +- Intent: CLI flags plus optional explicit endpoint/credential metadata, merged with registry/session metadata. +- Validation before any write (`runInferenceSetWithoutHostLock`, `:593`): provider allowlist and model-id charset (`:599-605`), registered-agent match, shields-down requirement (`:622`), local-provider reachability (`:651-671`). +- Writes are ordered, layered, forward-only: gateway route (`:674`) -> registry (`:698`) -> registry API-family refresh (`:722`) -> in-sandbox config patch, non-fatal (`:762`; both degraded states are explicitly repaired by `rebuild`, comment at `:755-759`) -> session (`:786`) -> audit entry (`:795`). +- No rollback. Degraded states are reported; `rebuild` is the documented repair. + +**4b. Config change** (`nemoclaw config set` -> `configSet`, `src/lib/sandbox/config.ts:886`): + +- Validation: dotpath validation (`:903`), shields-down (`:914`), `gateway.*` refusal (`:937`), scalar-ancestor/array clobber refusal (`:955`), new-key confirmation gate (`:966`, #2400), SSRF validation with DNS-pinned URL rewrite (`:992`). +- Apply: under the sandbox mutation lock plus the shields transition lock, a re-read plus compare-and-swap on the config's sha256 (`:1004-1023`) then write, hash recompute, and audit (`:1027-1030`). Fail-closed CAS; no compensation needed. + +**4c. Messaging channel add/remove/start/stop** (`src/commands/sandbox/channels/*` -> `src/lib/actions/sandbox/policy-channel.ts`: `addSandboxChannel` `:924`, `removeSandboxChannel` `:1307`, `stopSandboxChannel`/`startSandboxChannel` `:1481`/`:1490` -> `sandboxChannelsSetEnabled` `:1407`): + +- Intent: per-channel delta plans built from the registry entry (`workflow-planner.ts:62-115`: add, stop, start, remove). +- Validation: agent support gate; a hand-rolled mirror of the onboard conflict guard, `checkChannelAddConflict` (`:389`), which uniquely offers `--force`; conflict-detection errors fail closed unless `--force` or an interactive override (`:423-442`); channel pre-enable hooks run next, with hook-registry read failures fail-soft, warn and proceed (`:483-490`). +- Apply: gateway provider upsert/detach, policy preset apply/remove, and registry plan persistence run immediately, but the destructive apply is deferred to a rebuild: `promptAndRebuild` (`:682`) -> `rebuildSandbox(name, ["--yes"])` (`:699`). Non-interactive runs queue the change and print the rebuild command. +- Compensation: `rollbackChannelAdd` (`:1079`) restores prior tokens on preset failure; `channels start` re-disables the plan if its preset fails (`:1463-1472`); QR-channel remove hard-stops before any registry mutation if in-sandbox state cannot be cleared (`:1370-1382`, #3998); session preset mirroring `syncSessionPolicyPresetsWithRegistry` (`:1224`) prevents a later rebuild resume from reverting presets. + +**4d. Plugin entries** (`plugins.entries.*` in agent config): + +- Written as manifest render targets at build/rebuild time (for example `plugins.entries.telegram`, `src/lib/messaging/channels/telegram/manifest.ts:130`) and by the web-search flow. +- Reconciled at rebuild restore by `OPENCLAW_CONFIG_RESTORE_OWNERSHIP` (`openclaw-config-merge.ts:17-23`): `currentGeneratedEntryMaps: ["plugins.entries"]`, so current generated entries win by id, backup-only user entries are kept, and stale web-search entries are never resurrected. +- Direct runtime edits go only through `config set` gates. There is no dedicated plugin CLI; the managed-package CLI is #5998's scope. + +### Agent differences + +- The FSM branches `sandbox -> openclaw` for OpenClaw and `sandbox -> agent_setup` for other agents; both rejoin at `policies`. +- Deep Agents Code (DCode) is the only agent with pre-delete replacement-image validation on rebuild (#6214). It is also excluded from messaging: no channel manifest lists it under `supportedAgents`, and `channels add` rejects it before any mutation (see `src/lib/messaging/AGENTS.md`). +- Hermes adds tool-gateway and dashboard drift axes to the re-onboard drift baseline and its own credential preflight on rebuild. + +## Persisted state and field ownership + +- `~/.nemoclaw/onboard-session.json` is owned by `src/lib/state/onboard-session.ts` and written through `OnboardRuntimeBoundary` during onboard; the rebuild pipeline rewrites it wholesale as the recreate contract (`rebuild-recreate-phase.ts:103`). Step helpers default to record-only (`RECORD_ONLY_STEP_MUTATION_OPTIONS`, `src/lib/state/onboard-step-mutation.ts:19`); `LEGACY_MACHINE_STEP_MUTATION_OPTIONS` (`:15`) remains the escape hatch that also moves the machine snapshot, used by the exit backstop and rebuild. +- The sandbox registry is owned by `src/lib/state/registry.ts`; the machine snapshot `{version, state, stateEnteredAt, revision}` is owned by `OnboardRuntime`. +- Known ambiguity (pinned, not endorsed): `null` is overloaded across several session fields to mean unset, declined, or explicitly cleared. Explicit-clear semantics exist only for the whitelisted updates in `filterSafeUpdates` (the #2625 null-vs-undefined contract in `onboard-session.ts`). Modeling `unset`/`declined`/`known value` explicitly is #6228's mandate; sandbox-identity nullability is tracked by #5783/PR #5860. + +## Create path sequence + +```mermaid +sequenceDiagram + autonumber + participant Op as Operator + participant On as onboard() (src/lib/onboard.ts) + participant FSM as Machine slices (machine/*) + participant GW as OpenShell gateway + participant CS as createSandbox (onboard.ts:2465) + participant Plan as sandbox-create-plan.ts + participant St as Session + registry (src/lib/state) + + Op->>On: nemoclaw onboard (flags, env, prompts) + On->>On: resolveOnboardEntryOptions, acquire onboard lock + On->>St: prepareOnboardSession (create or repair snapshot) + On->>FSM: record init to preflight (onboard.ts:4771) + FSM->>FSM: preflight state, host/GPU/CDI/DNS validation (data-only) + FSM->>GW: gateway state, reuse / recover / start gateway + Note over FSM,GW: first externally visible effect + FSM->>GW: provider_selection / inference, provider credential upserts + Note over FSM,GW: gateway writes before any sandbox exists + FSM->>CS: sandbox state + CS->>CS: prepareSandboxMessagingPreflight incl. conflict guard (2524) + CS->>CS: drift detection, reuse fast paths, confirm gates + CS->>St: backupSandboxBeforeRecreate (2770 / 2824, fail closed) + rect rgb(250, 225, 225) + Note over CS,St: destructive boundary (re-onboard only) + CS->>GW: provider pre-delete cleanup + sandbox delete (2836-2837) + CS->>CS: docker rmi previous image (2839) + CS->>St: registry.removeSandbox (2847) + end + CS->>Plan: prepareSandboxCreatePlan (2880) + Plan->>Plan: resolveSandboxCreateIntent, pure (228) + Plan->>GW: materializeSandboxCreatePlan, bind tokens + upsert messaging providers (372) + CS->>GW: streamSandboxCreate (2968) + CS->>CS: readiness wait (3032), on failure delete new sandbox (3052) and exit + CS->>St: registerCreatedSandbox only after ready (3108) + CS->>St: restore pending workspace backup (3128) + FSM->>FSM: openclaw or agent_setup, policies, finalizing, post_verify + FSM->>St: completeSession (terminal checkpoint) +``` + +Current-ordering facts this diagram pins (do not "fix" silently; they are #6226/#6228 targets): + +1. Gateway credential writes (inference providers, then messaging providers) precede sandbox existence and, on the recreate path, follow the deletion of the old sandbox. +2. `resolveSandboxCreateIntent` runs inside `prepareSandboxCreatePlan` at `onboard.ts:2880`, after the destructive boundary at `onboard.ts:2837`, not before it. +3. Registry registration is post-ready only; there is no durable record of the selected sandbox identity before the long-running create stream starts. + +## Duplicated decision points (divergences) and recommended owners + +Recommended owners name where a single decision should live. No refactor is implied here; alignment work belongs to the referenced child issues. + +1. **Messaging desired state has four sources by path.** First onboard compiles the plan from current selections and transports it via `NEMOCLAW_MESSAGING_PLAN_B64` (`MessagingSetupApplier.writePlanToEnv`, `applier/setup-applier.ts:45`); rebuild restages from the registry entry plan (`buildRebuildPlanFromSandboxEntry`, `workflow-planner.ts:116`); resume reuse resolves recorded channels, then env plan, then registry plan, then `session.messagingPlan` (`handlers/sandbox-messaging.ts:253-269`); channel mutations build single-channel deltas (`workflow-planner.ts:62-115`). Drift among env/session/registry yields different recreated states per path. Recommended owner: the registry-persisted plan via `MessagingHostStateApplier`, with env and session copies demoted to transport/cache; alignment via #6226 and #6228. +2. **Ambient env polarity is inverted between paths.** Onboard/re-onboard treat `NEMOCLAW_PROVIDER`/`MODEL`/`ENDPOINT_URL` as authoritative intent; rebuild quarantines exactly those (`isolateAmbientRecreateEnv`, `rebuild-env-isolation.ts:116`) and pins intent from registry + matching session (`prepareRebuildResumeConfig`, `rebuild-resume-config.ts:224`, #5735). The same environment produces opposite outcomes depending on the path. Recommended owner: one target-resolution module that decides when ambient env is intent versus contamination; alignment via #6226. +3. **One conflict-guard engine, three wirings with divergent semantics.** Onboard: `enforceMessagingChannelConflicts` (`messaging-conflict-guard.ts:65`) with an interactive "continue anyway" path. Rebuild: `preflightRebuildMessagingConflicts` (`rebuild-messaging-conflict-preflight.ts:49`, #5954) forcing non-interactive abort. `channels add`: the hand-rolled mirror `checkChannelAddConflict` (`policy-channel.ts:389`) uniquely offers `--force`; detection errors fail closed unless forced or interactively overridden (`:423-442`), while pre-enable hook registry-read failures remain fail-soft (`:483-490`). Recommended owner: `messaging-conflict-guard.ts` as the sole engine, taking per-path policy (interactive / abort / force) declaratively. +4. **Backup/restore intent differs per path.** Rebuild always backs up and auto-restores, including policy presets (`rebuild-backup-phase.ts`, `rebuild-pipeline.ts:206-229`); re-onboard backs up fail-closed but restores only workspace state (presets travel via carry-forward, `onboard.ts:2815`); the non-interactive not-ready path restores only under the installer flag (#6130, `not-ready-recreate.ts:56`); channel mutations create no checkpoint of their own and lean on the next rebuild's backup. Recommended owner: one backup/restore policy module consumed by both `createSandbox` and the rebuild pipeline; durable semantics belong to #6228. +5. **Registry lifecycle asymmetry.** Create registers only post-ready (`registerCreatedSandbox`, `onboard.ts:3108`); rebuild removes the entry at the destroy phase (`rebuild-destroy-phase.ts:113`, retained only for MCP-bearing entries) and restores a snapshot only for recovery recreates (`rebuild-recreate-phase.ts:206-217`); re-onboard recreate removes at `onboard.ts:2847` with no snapshot restore at all. A plain failed recreate leaves no registry entry on either path. Recommended owner: `sandbox-registration.ts` as the registration contract; durable pre-create identity belongs to #6228. +6. **Pre-delete replacement validation exists only for DCode rebuilds** (#6214): image prebuilt and fingerprinted (`rebuild-dcode-preflight.ts:354`) and revalidated at the mutation edge (`:415`). Non-DCode rebuilds validate base image, credentials, and runtime pre-delete but build the real image after deletion; onboard/re-onboard build entirely post-delete. Recommended owner: the `rebuild-dcode-orchestrator` pattern as the documented precedent; full same-name build-verify-swap atomicity is #5801's scope, explicitly outside this epic. +7. **Policy-preset reconciliation exists only on rebuild.** The restore/post-restore phases reapply presets and reconcile the registry; onboard writes `appliedPolicies` once at registration (`onboard.ts:3115`); channel commands mutate presets one at a time and mirror them into the session (`syncSessionPolicyPresetsWithRegistry`, `policy-channel.ts:1224`) specifically so a later rebuild resume does not revert them. The paths reconverge only via ad-hoc mirrors. Recommended owner: the `policy-preset-persistence`/`policy-preset-sync` modules as the single reconciliation point. + +## Bug to contract-gap map + +| Issue | Symptom | Contract gap | Status | +|---|---|---|---| +| #5961 | Interrupted non-interactive onboard cannot resume safely | Checkpoint gap: whole-step session with no durable sandbox identity or effect-group metadata before the interruptible create step, so resume cannot distinguish never-started, in-flight, and created | Open; targeted by #6227/#6228 | +| #6040 | `onboard --resume` aborts on macOS/DGX Spark | Recovery gap: only `failed` and inconsistently-reopened-`complete` snapshots are repaired (`classifyResumeMachineRepair`, `resume-repair-policy.ts:34`); other interrupted snapshot shapes have no explicit recovery transition | Open; targeted by #6227 | +| #6179 | Invalid FSM transition attempted after successful sandbox creation | Transition-graph gap: handlers can emit results whose source state no longer matches; stale results are skipped by `recordStateResultWithStepCompatibility` (`runtime-boundary.ts:204`, reasons `already_at_target`/`source_state_mismatch`) instead of being rejected or recomputed under an enforced legal-transition rule | Open; targeted by #6227 | +| #5954 | Rebuild detected a messaging credential conflict only after destroying the sandbox | Plan-before-effects gap in rebuild preflight ordering | Fixed by PR #5955 (`9e583ed47`); the guard now runs at `rebuild-preflight-target-phase.ts:90`, before every destructive phase | +| #6099 | Healthy sandbox rolled back after a late dashboard-forward failure | Compensation-scope gap: post-ready, non-destructive failures sit inside a destructive rollback window (`ensureDashboardForward(..., { rollbackSandboxOnFailure: true })`, `onboard.ts:3092`) | Open; in-flight PR #6116 (`forward-start.ts`) | +| #6195 | Rebuild deleted a DCode sandbox before validating that recreation could succeed | Plan-before-effects gap at rebuild's destructive boundary | Fixed by PR #6214 (`2c4bf1944`); see divergence 6 | + +## Recently addressed by #6218 and #6214 + +- **PR #6218** (`2a68fbc7e`, merged 2026-07-03) separated the deterministic, serializable, secret-free `SandboxCreateIntent` (`resolveSandboxCreateIntent`, `sandbox-create-plan.ts:228`) from effectful materialization (`materializeSandboxCreatePlan`, `:334`), kept the `prepareSandboxCreatePlan` compatibility surface (`:400`), and extended the characterization coverage in `sandbox-create-plan.test.ts`. It deliberately did **not** move intent resolution ahead of the destructive boundary (still invoked at `onboard.ts:2880`, after the delete at `:2837`), did not persist intent, and did not define a machine-event or public contract. Those are exactly #6226, #6228, and #6229. +- **PR #6214** (`2c4bf1944`, merged 2026-07-03) made DCode rebuilds prepare, fingerprint, and mutation-edge-revalidate the replacement before deletion (`rebuild-dcode-preflight.ts:354`, `:415`), closing #6195's ordering gap for DCode. Non-DCode rebuild ordering is unchanged. +- **PR #5955** (`9e583ed47`, merged 2026-07-03) moved the rebuild messaging conflict check before destruction, closing #5954. + +## In-flight work + +Do not treat recovery and resume semantics in this package as frozen: + +- **PR #6253** (open) is the recovery-path refactor toward #6227. The recovery/resume surface (`resume-machine-repair.ts`, `session-bootstrap.ts`, `machine/transitions.ts`, `exit-step-failure.ts`, and neighbors) is claimed by open PRs in this area; coordinate before touching those files. +- **PR #6116** (open) reworks the dashboard-forward rollback scope for #6099 (`forward-start.ts`). +- **PR #5860** (open) addresses null sandbox identity and coarse checkpoints for #5783. + +## Characterization tests + +The machine event/transition traces for fresh, resume, recreate, success, and failure paths are pinned by `machine/transition-traces.test.ts` (see the "Characterization traces" section of `machine/README.md`). Together with the per-journey tests listed in the matrix above, they form the regression baseline for #6225: they assert current behavior, including orderings this document flags as gaps. When #6226/#6227/#6228 intentionally change an ordering, update the pinned trace in the same PR and reference the child issue in the test title. diff --git a/src/lib/onboard/machine/README.md b/src/lib/onboard/machine/README.md index b4bd0f10279..4cf3d8e4f2e 100644 --- a/src/lib/onboard/machine/README.md +++ b/src/lib/onboard/machine/README.md @@ -119,3 +119,7 @@ The FSM migration is considered complete when: 4. the runner applies all handler results through `OnboardRuntime`; 5. step helpers no longer implicitly own machine transitions; 6. `src/lib/onboard.ts` contains entrypoint setup and dependency wiring rather than state sequencing. + +## Characterization traces + +`transition-traces.test.ts` in this directory pins the machine event and transition traces for the fresh, resume, recreate, success, and failure paths as they behave today (#6225). Those traces are a regression baseline: update them deliberately, in the same PR as an intentional behavior change (for example #6226, #6227, or #6228), never as a side effect. The journey-level lifecycle contract map, shared vocabulary, and destructive-boundary inventory live in `../AGENTS.md` (`src/lib/onboard/AGENTS.md`). diff --git a/src/lib/onboard/machine/transition-traces.test.ts b/src/lib/onboard/machine/transition-traces.test.ts new file mode 100644 index 00000000000..7359e4f0f32 --- /dev/null +++ b/src/lib/onboard/machine/transition-traces.test.ts @@ -0,0 +1,658 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * Characterization traces for the onboarding machine (#6225). + * + * These tests pin CURRENT behavior on main as a regression baseline for the + * lifecycle-contract mapping in epic #6224. They are descriptive, not + * aspirational: when a pinned ordering changes intentionally, update the pin + * in the same PR that changes the behavior. + * + * Deliberately OUT of scope here: the recovery-path semantics that open PR + * #6253 is rewriting. This file does not pin the legality of transitions + * leaving the terminal `failed` state (for example `failed -> ` + * repair edges) and does not pin the legacy step-mutation compatibility + * bridge (`LEGACY_MACHINE_STEP_MUTATION_OPTIONS` or the runtime-boundary + * stale-result skip rules) — #6253 pins those in its own tests. The exact + * full-table equality pin also stays in `transitions.test.ts`; this file + * asserts the canonical edges positively so additive recovery edges do not + * invalidate the trace baseline. + */ + +import { describe, expect, it, vi } from "vitest"; + +import { + createSession, + filterSafeUpdates, + MACHINE_SNAPSHOT_VERSION, + normalizeSession, + type OnboardMachineSnapshot, + type Session, + type SessionUpdates, + type StepState, + sanitizeFailure, +} from "../../state/onboard-session"; +import type { OnboardMachineEvent } from "./events"; +import { + advanceTo, + branchTo, + completeOnboardMachine, + failOnboardMachine, + retryTo, + transitionTo, +} from "./result"; +import { type OnboardStateHandlers, runOnboardMachine } from "./runner"; +import { OnboardRuntime, type OnboardRuntimeDeps } from "./runtime"; +import { + assertValidOnboardMachineTransition, + canTransitionOnboardMachineState, + getOnboardMachineTransition, + InvalidOnboardMachineTransitionError, + ONBOARD_MACHINE_DIRECT_TRANSITIONS, + ONBOARD_MACHINE_TRANSITIONS, +} from "./transitions"; +import { + ONBOARD_MACHINE_STATES, + ONBOARD_NON_TERMINAL_MACHINE_STATES, + type OnboardMachineState, + type OnboardMachineTransition, +} from "./types"; + +const NOW = "2026-07-04T00:00:00.000Z"; + +interface TraceContext { + attempts: number; + visited: string[]; +} + +function traceContext(): TraceContext { + return { attempts: 0, visited: [] }; +} + +function cloneSession(session: Session): Session { + return normalizeSession(JSON.parse(JSON.stringify(session))) ?? session; +} + +function machineAt(state: OnboardMachineState, revision = 0): OnboardMachineSnapshot { + return { version: MACHINE_SNAPSHOT_VERSION, state, stateEnteredAt: NOW, revision }; +} + +function completedStep(): StepState { + return { status: "complete", startedAt: NOW, completedAt: NOW, error: null }; +} + +function createTracedRuntime(initialSession: Session = createSession()) { + let session = cloneSession(initialSession); + const events: OnboardMachineEvent[] = []; + const updateSession = (mutator: (value: Session) => Session | void): Session => { + const next = mutator(cloneSession(session)) ?? session; + session = cloneSession(next); + return cloneSession(session); + }; + const deps: OnboardRuntimeDeps = { + loadSession: () => cloneSession(session), + createSession, + saveSession: (next) => { + session = cloneSession(next); + return cloneSession(session); + }, + updateSession, + markStepStarted: () => cloneSession(session), + markStepComplete: (_stepName, updates: SessionUpdates = {}) => + updateSession((current) => { + Object.assign(current, filterSafeUpdates(updates)); + return current; + }), + markStepCompleteRecordOnly: (_stepName, updates: SessionUpdates = {}) => + updateSession((current) => { + Object.assign(current, filterSafeUpdates(updates)); + return current; + }), + markStepSkipped: () => cloneSession(session), + markStepFailed: (stepName, message) => + updateSession((current) => { + current.status = "failed"; + current.failure = sanitizeFailure({ step: stepName, message, recordedAt: NOW }); + return current; + }), + markStepFailedRecordOnly: () => cloneSession(session), + completeSession: (updates: SessionUpdates = {}) => + updateSession((current) => { + Object.assign(current, filterSafeUpdates(updates)); + current.status = "complete"; + current.resumable = false; + return current; + }), + filterSafeUpdates, + emitEvent: (event) => { + events.push(event); + }, + now: () => NOW, + }; + return { runtime: new OnboardRuntime(deps), events }; +} + +function traceOf(events: readonly OnboardMachineEvent[]): string[] { + return events.map((event) => `${event.type}:${event.state}`); +} + +const recordVisited = ({ + context, + state, +}: { + context: TraceContext; + state: OnboardMachineState; +}): TraceContext => ({ + attempts: state === "inference" ? context.attempts + 1 : context.attempts, + visited: [...context.visited, state], +}); + +function fullRunHandlers( + overrides: Partial> = {}, +): OnboardStateHandlers { + return { + init: () => advanceTo("preflight"), + preflight: () => advanceTo("gateway"), + gateway: () => advanceTo("provider_selection"), + provider_selection: () => advanceTo("inference"), + inference: () => advanceTo("sandbox"), + sandbox: () => branchTo("openclaw", { updates: { sandboxName: "my-assistant" } }), + openclaw: () => advanceTo("policies"), + agent_setup: () => advanceTo("policies"), + policies: () => advanceTo("finalizing"), + finalizing: () => advanceTo("post_verify"), + post_verify: () => completeOnboardMachine(), + ...overrides, + }; +} + +const CANONICAL_DIRECT_TRANSITIONS = [ + ["init", "preflight", "advance"], + ["preflight", "gateway", "advance"], + ["gateway", "provider_selection", "advance"], + ["provider_selection", "inference", "advance"], + ["inference", "provider_selection", "retry"], + ["inference", "sandbox", "advance"], + ["sandbox", "openclaw", "branch"], + ["sandbox", "agent_setup", "branch"], + ["openclaw", "policies", "advance"], + ["agent_setup", "policies", "advance"], + ["policies", "finalizing", "advance"], + ["finalizing", "post_verify", "advance"], + ["post_verify", "complete", "advance"], +] as const; + +// Each tuple skips exactly one live state ahead of the canonical chain. +const ONE_STATE_FORWARD_JUMPS = [ + ["init", "gateway"], + ["preflight", "provider_selection"], + ["gateway", "inference"], + ["provider_selection", "sandbox"], + ["inference", "openclaw"], + ["inference", "agent_setup"], + ["sandbox", "policies"], + ["openclaw", "finalizing"], + ["agent_setup", "finalizing"], + ["policies", "post_verify"], + ["finalizing", "complete"], +] as const; + +describe("onboard machine transition surface (#6225)", () => { + it.each( + CANONICAL_DIRECT_TRANSITIONS, + )("allows %s to reach %s through a %s transition (#6225)", (from, to, kind) => { + expect(canTransitionOnboardMachineState(from, to)).toBe(true); + expect(getOnboardMachineTransition(from, to)).toEqual({ from, to, kind }); + expect(assertValidOnboardMachineTransition(from, to).kind).toBe(kind); + }); + + it.each([ + ...ONBOARD_NON_TERMINAL_MACHINE_STATES, + ])("allows %s to take the shared failure edge (#6225)", (state) => { + expect(canTransitionOnboardMachineState(state, "failed")).toBe(true); + expect(getOnboardMachineTransition(state, "failed")).toEqual({ + from: state, + to: "failed", + kind: "failure", + }); + }); + + it.each( + ONE_STATE_FORWARD_JUMPS, + )("rejects jumping from %s past the next step to %s (#6225)", (from, to) => { + expect(canTransitionOnboardMachineState(from, to)).toBe(false); + expect(getOnboardMachineTransition(from, to)).toBeNull(); + expect(() => assertValidOnboardMachineTransition(from, to)).toThrow( + InvalidOnboardMachineTransitionError, + ); + expect(() => assertValidOnboardMachineTransition(from, to)).toThrow( + `Invalid onboarding machine transition: ${from} -> ${to}`, + ); + }); + + it("keeps the inference retry as the only backward edge among live states (#6225)", () => { + const directTransitions: readonly OnboardMachineTransition[] = + ONBOARD_MACHINE_DIRECT_TRANSITIONS; + const stateIndex = (state: OnboardMachineState): number => + ONBOARD_MACHINE_STATES.indexOf(state); + const backwardEdges = directTransitions.filter( + (transition) => + transition.from !== "failed" && stateIndex(transition.to) < stateIndex(transition.from), + ); + + expect(backwardEdges).toEqual([{ from: "inference", to: "provider_selection", kind: "retry" }]); + }); + + it("includes every canonical direct edge in the combined transition table (#6225)", () => { + expect(ONBOARD_MACHINE_TRANSITIONS).toEqual( + expect.arrayContaining( + CANONICAL_DIRECT_TRANSITIONS.map(([from, to, kind]) => ({ from, to, kind })), + ), + ); + }); +}); + +describe("fresh onboarding run trace (#6225)", () => { + it("advances through the openclaw branch to completion in canonical order (#6225)", async () => { + const { runtime, events } = createTracedRuntime(); + await runtime.start(); + + const run = await runOnboardMachine({ + context: traceContext(), + runtime, + handlers: fullRunHandlers(), + updateContext: recordVisited, + }); + + expect(run.context.visited).toEqual([ + "init", + "preflight", + "gateway", + "provider_selection", + "inference", + "sandbox", + "openclaw", + "policies", + "finalizing", + "post_verify", + ]); + expect(run.session).toMatchObject({ + status: "complete", + resumable: false, + sandboxName: "my-assistant", + machine: { state: "complete", revision: 10 }, + }); + expect(traceOf(events)).toEqual([ + "onboard.started:init", + "state.exited:init", + "state.entered:preflight", + "state.exited:preflight", + "state.entered:gateway", + "state.exited:gateway", + "state.entered:provider_selection", + "state.exited:provider_selection", + "state.entered:inference", + "state.exited:inference", + "state.entered:sandbox", + "context.updated:sandbox", + "state.exited:sandbox", + "state.entered:openclaw", + "state.exited:openclaw", + "state.entered:policies", + "state.exited:policies", + "state.entered:finalizing", + "state.exited:finalizing", + "state.entered:post_verify", + "state.completed:post_verify", + "state.entered:complete", + "onboard.completed:complete", + ]); + + // Context updates are applied and announced from the source state before + // the state transition itself is recorded. + const contextUpdates = events.filter((event) => event.type === "context.updated"); + expect(contextUpdates).toHaveLength(1); + expect(contextUpdates[0]).toMatchObject({ + state: "sandbox", + metadata: { fields: ["sandboxName"] }, + }); + expect(events[events.length - 1]).toMatchObject({ + type: "onboard.completed", + context: { sandboxName: "my-assistant" }, + }); + }); + + it("routes the agent branch through agent_setup instead of openclaw (#6225)", async () => { + const { runtime } = createTracedRuntime(); + const openclawHandler = vi.fn(() => advanceTo("policies")); + + const run = await runOnboardMachine({ + context: traceContext(), + runtime, + handlers: fullRunHandlers({ + sandbox: () => branchTo("agent_setup", { updates: { sandboxName: "my-agent" } }), + openclaw: openclawHandler, + }), + updateContext: recordVisited, + }); + + expect(openclawHandler).not.toHaveBeenCalled(); + expect(run.context.visited).toEqual([ + "init", + "preflight", + "gateway", + "provider_selection", + "inference", + "sandbox", + "agent_setup", + "policies", + "finalizing", + "post_verify", + ]); + expect(run.session).toMatchObject({ + status: "complete", + sandboxName: "my-agent", + machine: { state: "complete", revision: 10 }, + }); + }); + + it("returns from inference to provider selection on retry before advancing to sandbox (#6225)", async () => { + const { runtime, events } = createTracedRuntime( + createSession({ machine: machineAt("provider_selection") }), + ); + + // The runner pauses at a stop state without requiring a handler for it — + // the same handoff mechanism the production flow slices use between the + // initial, core, and final slices. + const run = await runOnboardMachine({ + context: traceContext(), + runtime, + handlers: { + provider_selection: () => advanceTo("inference"), + inference: (context) => + context.attempts === 0 ? retryTo("provider_selection") : advanceTo("sandbox"), + }, + stopStates: ["sandbox"], + updateContext: recordVisited, + }); + + expect(run.context.visited).toEqual([ + "provider_selection", + "inference", + "provider_selection", + "inference", + ]); + expect(run.context.attempts).toBe(2); + expect(traceOf(events)).toEqual([ + "state.exited:provider_selection", + "state.entered:inference", + "state.exited:inference", + "state.entered:provider_selection", + "state.exited:provider_selection", + "state.entered:inference", + "state.exited:inference", + "state.entered:sandbox", + ]); + expect(run.session).toMatchObject({ + status: "in_progress", + machine: { state: "sandbox", revision: 4 }, + }); + }); +}); + +describe("resume trace with a completed sandbox step (#6225)", () => { + it("resumes at openclaw and never re-invokes handlers for completed states (#6225)", async () => { + const resumedSession = createSession({ + sandboxName: "my-assistant", + provider: "nvidia", + model: "model", + lastCompletedStep: "sandbox", + machine: machineAt("openclaw", 6), + steps: { + preflight: completedStep(), + gateway: completedStep(), + provider_selection: completedStep(), + inference: completedStep(), + sandbox: completedStep(), + }, + }); + const { runtime, events } = createTracedRuntime(resumedSession); + const priorStateHandlers = { + init: vi.fn(() => advanceTo("preflight")), + preflight: vi.fn(() => advanceTo("gateway")), + gateway: vi.fn(() => advanceTo("provider_selection")), + provider_selection: vi.fn(() => advanceTo("inference")), + inference: vi.fn(() => advanceTo("sandbox")), + sandbox: vi.fn(() => branchTo("openclaw")), + }; + + await runtime.start({ resumed: true }); + const run = await runOnboardMachine({ + context: traceContext(), + runtime, + handlers: { + ...priorStateHandlers, + openclaw: () => advanceTo("policies"), + policies: () => advanceTo("finalizing"), + finalizing: () => advanceTo("post_verify"), + post_verify: () => completeOnboardMachine(), + }, + updateContext: recordVisited, + }); + + for (const handler of Object.values(priorStateHandlers)) { + expect(handler).not.toHaveBeenCalled(); + } + expect(run.context.visited).toEqual(["openclaw", "policies", "finalizing", "post_verify"]); + expect(traceOf(events)).toEqual([ + "onboard.resumed:openclaw", + "state.exited:openclaw", + "state.entered:policies", + "state.exited:policies", + "state.entered:finalizing", + "state.exited:finalizing", + "state.entered:post_verify", + "state.completed:post_verify", + "state.entered:complete", + "onboard.completed:complete", + ]); + expect(events[0]).toMatchObject({ + type: "onboard.resumed", + context: { sandboxName: "my-assistant", provider: "nvidia", model: "model" }, + }); + expect(run.session).toMatchObject({ + status: "complete", + resumable: false, + sandboxName: "my-assistant", + lastCompletedStep: "sandbox", + machine: { state: "complete", revision: 10 }, + }); + expect(run.session.steps.sandbox.status).toBe("complete"); + }); +}); + +describe("sandbox recreate trace (#6225)", () => { + it("re-runs the sandbox state with repair events around recreate before branching (#6225)", async () => { + // Machine snapshot back at `sandbox` while the recorded sandbox step is + // still marked complete: the shape a resumed session has when the + // recorded sandbox exists but is not ready and must be recreated. The + // repair-event vocabulary mirrors the sandbox handler's + // repair-and-recreate sequence (state.repair.started/completed with a + // recorded-sandbox-cleanup marker). + const staleSession = createSession({ + sandboxName: "my-assistant", + lastCompletedStep: "sandbox", + machine: machineAt("sandbox", 5), + steps: { sandbox: completedStep() }, + }); + const { runtime, events } = createTracedRuntime(staleSession); + const repairMetadata = { repair: "recorded-sandbox-cleanup", sandboxName: "my-assistant" }; + + const run = await runOnboardMachine({ + context: traceContext(), + runtime, + handlers: { + sandbox: async () => { + await runtime.emitRepairEvent("state.repair.started", { + state: "sandbox", + metadata: repairMetadata, + }); + await runtime.emitRepairEvent("state.repair.completed", { + state: "sandbox", + metadata: repairMetadata, + }); + return branchTo("openclaw", { updates: { sandboxName: "my-assistant" } }); + }, + }, + stopStates: ["openclaw"], + updateContext: recordVisited, + }); + + expect(traceOf(events)).toEqual([ + "state.repair.started:sandbox", + "state.repair.completed:sandbox", + "context.updated:sandbox", + "state.exited:sandbox", + "state.entered:openclaw", + ]); + expect(events[0].metadata).toEqual(repairMetadata); + expect(run.context.visited).toEqual(["sandbox"]); + expect(run.session).toMatchObject({ + status: "in_progress", + sandboxName: "my-assistant", + machine: { state: "openclaw", revision: 6 }, + }); + }); +}); + +describe("mid-flow failure trace (#6225)", () => { + it("stops at the failing inference step and records the failure envelope (#6225)", async () => { + const { runtime, events } = createTracedRuntime(); + const sandboxHandler = vi.fn(() => branchTo("openclaw")); + + const run = await runOnboardMachine({ + context: traceContext(), + runtime, + handlers: fullRunHandlers({ + inference: () => failOnboardMachine("model probe failed", { step: "inference" }), + sandbox: sandboxHandler, + }), + updateContext: recordVisited, + }); + + expect(sandboxHandler).not.toHaveBeenCalled(); + expect(run.context.visited).toEqual([ + "init", + "preflight", + "gateway", + "provider_selection", + "inference", + ]); + // A failed run stays resumable — `onboard --resume` recovery relies on + // the failure transition leaving `resumable` untouched. + expect(run.session).toMatchObject({ + status: "failed", + resumable: true, + failure: { step: "inference", message: "model probe failed", recordedAt: NOW }, + machine: { state: "failed", revision: 5 }, + }); + expect(traceOf(events)).toEqual([ + "state.exited:init", + "state.entered:preflight", + "state.exited:preflight", + "state.entered:gateway", + "state.exited:gateway", + "state.entered:provider_selection", + "state.exited:provider_selection", + "state.entered:inference", + "state.failed:inference", + "onboard.failed:failed", + ]); + expect(events[events.length - 2]).toMatchObject({ + type: "state.failed", + state: "inference", + step: "inference", + error: "model probe failed", + }); + }); +}); + +describe("runtime transition-kind enforcement (#6225)", () => { + const KIND_MISMATCH_CASES = [ + { + from: "inference", + edge: "inference -> provider_selection", + result: advanceTo("provider_selection"), + expected: "advance", + actual: "retry", + }, + { + from: "inference", + edge: "inference -> sandbox", + result: retryTo("sandbox"), + expected: "retry", + actual: "advance", + }, + { + from: "sandbox", + edge: "sandbox -> openclaw", + result: advanceTo("openclaw"), + expected: "advance", + actual: "branch", + }, + { + from: "provider_selection", + edge: "provider_selection -> inference", + result: branchTo("inference"), + expected: "branch", + actual: "advance", + }, + ] as const; + + it.each( + KIND_MISMATCH_CASES, + )("rejects the mistyped result for $edge without touching the session (#6225)", async ({ + from, + edge, + result, + expected, + actual, + }) => { + const { runtime, events } = createTracedRuntime(createSession({ machine: machineAt(from) })); + + await expect(runtime.applyResult(result)).rejects.toThrow( + `Invalid onboarding machine transition kind: ${edge} expected ${expected}, got ${actual}`, + ); + await expect(runtime.session()).resolves.toMatchObject({ + machine: { state: from, revision: 0 }, + }); + expect(events).toEqual([]); + }); + + it("accepts an undeclared-kind transition result on any legal edge (#6225)", async () => { + const { runtime, events } = createTracedRuntime( + createSession({ machine: machineAt("inference") }), + ); + + await runtime.applyResult(transitionTo("provider_selection")); + + expect(traceOf(events)).toEqual(["state.exited:inference", "state.entered:provider_selection"]); + await expect(runtime.session()).resolves.toMatchObject({ + machine: { state: "provider_selection", revision: 1 }, + }); + }); + + it("validates the transition before applying any context updates (#6225)", async () => { + const { runtime, events } = createTracedRuntime(); + + await expect( + runtime.applyResult(advanceTo("sandbox", { updates: { sandboxName: "never-created" } })), + ).rejects.toThrow(InvalidOnboardMachineTransitionError); + + const session = await runtime.session(); + expect(session.sandboxName).toBeNull(); + expect(session.machine).toMatchObject({ state: "init", revision: 0 }); + expect(events).toEqual([]); + }); +}); diff --git a/test/onboard-lifecycle-invariants.test.ts b/test/onboard-lifecycle-invariants.test.ts new file mode 100644 index 00000000000..e627f54c41e --- /dev/null +++ b/test/onboard-lifecycle-invariants.test.ts @@ -0,0 +1,769 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Characterization baseline for the onboarding create-path lifecycle (#6225, +// epic #6224). These tests pin CURRENT main behavior — including orderings the +// epic flags as contract gaps (e.g. gateway messaging credential upserts run +// AFTER the destructive sandbox delete, and credential-binding validation only +// happens at plan materialization time, which is also after the delete). They +// are a regression baseline, not an endorsement: later children (#6226/#6227/ +// #6228) are expected to change some of these pins deliberately. +// +// The `createSandbox` orchestration in src/lib/onboard.ts cannot run +// hermetically (it shells out to OpenShell/Docker), so its cross-module +// ordering is pinned as a source-order characterization over the function +// body, while every decision that lives in an injectable module +// (sandbox-messaging-preflight, sandbox-create-plan, sandbox-resume, +// resume-config) is pinned with direct unit-level calls. + +import fs from "node:fs"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { SandboxMessagingPlan } from "../src/lib/messaging/manifest/types.js"; +import type { SandboxResumeDecision } from "../src/lib/onboard/machine/handlers/sandbox-resume.js"; +import { + applySandboxResumeDecision, + decideSandboxResume, + type SandboxResumeDeps, + type SandboxResumeSignals, +} from "../src/lib/onboard/machine/handlers/sandbox-resume.js"; +import type { MessagingConflictGuardDeps } from "../src/lib/onboard/messaging-conflict-guard.js"; +import type { + CreateSandboxMessagingPrepResult, + MessagingTokenDef, +} from "../src/lib/onboard/messaging-prep.js"; +import { + getResumeConfigConflicts, + getResumeSandboxConflict, +} from "../src/lib/onboard/resume-config.js"; +import { + materializeSandboxCreatePlan, + prepareSandboxCreatePlan, + resolveSandboxCreateIntent, + resolveSandboxCreateMessagingProviderRequests, +} from "../src/lib/onboard/sandbox-create-plan.js"; +import type { SandboxGpuCreateConfig } from "../src/lib/onboard/sandbox-gpu-create.js"; +import { + prepareSandboxMessagingPreflight, + type SandboxMessagingPreflightDeps, + type SandboxMessagingPreflightInput, +} from "../src/lib/onboard/sandbox-messaging-preflight.js"; + +// ── Shared fixtures ───────────────────────────────────────────────────────── + +const telegramChannel = { + name: "telegram", + envKey: "TELEGRAM_BOT_TOKEN", + label: "Telegram", + description: "Telegram", + help: "Telegram", +}; + +const telegramTokenDef: MessagingTokenDef = { + name: "sandbox-telegram-bridge", + envKey: "TELEGRAM_BOT_TOKEN", + token: "telegram-token", +}; + +const sandboxGpuConfig: SandboxGpuCreateConfig = { + sandboxGpuEnabled: true, + sandboxGpuDevice: "nvidia.com/gpu=0", +}; + +class OnboardAbortError extends Error { + constructor(readonly code: number) { + super(`onboard aborted with exit code ${code}`); + } +} + +// ── 1. Source-order characterization of createSandbox ────────────────────── +// +// Pins which deterministic validations and checkpoints complete before the +// first destructive effect (the `openshell sandbox delete` of a pre-existing +// sandbox) and which effects run after it. The markers are call-site snippets +// inside `async function createSandbox(` in src/lib/onboard.ts, verified at +// HEAD: messaging preflight (which hosts the #5954-shared conflict guard), +// fail-closed pre-recreate backup, the delete boundary, the create plan whose +// materialization performs the gateway messaging upsert, the create stream, +// the readiness gate, and post-ready registration. + +const repoRoot = path.join(import.meta.dirname, ".."); +const onboardSource = fs.readFileSync(path.join(repoRoot, "src", "lib", "onboard.ts"), "utf8"); +const createSandboxStart = onboardSource.indexOf("async function createSandbox("); +const createSandboxEnd = onboardSource.indexOf("\nasync function ", createSandboxStart + 1); +const createSandboxBody = onboardSource.slice(createSandboxStart, createSandboxEnd); + +const DELETE_SNIPPET = 'runOpenshell(["sandbox", "delete", sandboxName], { ignoreError: true });'; + +const CREATE_LIFECYCLE_MARKERS = [ + { label: "sandbox name validation", snippet: "const sandboxName = validateName(" }, + { + label: "messaging preflight with the conflict guard", + snippet: "sandboxMessagingPreflight.prepareSandboxMessagingPreflight(", + }, + { + label: "pre-upgrade backup selection", + snippet: "notReadyRecreate.selectPreUpgradeBackupForCreate(", + }, + { + label: "fail-closed pre-recreate workspace backup", + snippet: "backupSandboxBeforeRecreate({ sandboxName });", + }, + { + label: "provider pre-delete cleanup", + snippet: "runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact });", + }, + { label: "destructive sandbox delete", snippet: DELETE_SNIPPET }, + { label: "previous image removal", snippet: "dockerRmi(previousEntry.imageTag" }, + { label: "registry entry removal", snippet: "registry.removeSandbox(sandboxName);" }, + { + label: "create plan preparation with the gateway messaging upsert", + snippet: "sandboxCreatePlan.prepareSandboxCreatePlan({", + }, + { label: "sandbox create stream", snippet: "await streamSandboxCreate(" }, + { label: "readiness gate", snippet: "waitForCreatedSandboxReadyWithTrace({" }, + { + label: "post-ready registry registration", + snippet: "sandboxRegistration.registerCreatedSandbox({", + }, +] as const; + +const markerIndex = (snippet: string): number => createSandboxBody.indexOf(snippet); + +const consecutiveMarkerPairs = CREATE_LIFECYCLE_MARKERS.slice(1).map((later, index) => ({ + earlierLabel: CREATE_LIFECYCLE_MARKERS[index].label, + earlierSnippet: CREATE_LIFECYCLE_MARKERS[index].snippet, + laterLabel: later.label, + laterSnippet: later.snippet, +})); + +describe("createSandbox source ordering on the onboard create path (#6225)", () => { + it("bounds the createSandbox body for source scanning (#6225)", () => { + expect(createSandboxStart).toBeGreaterThanOrEqual(0); + expect(createSandboxEnd).toBeGreaterThan(createSandboxStart); + }); + + it.each([ + ...CREATE_LIFECYCLE_MARKERS, + ])("locates the $label call site inside createSandbox (#6225)", ({ snippet }) => { + expect(markerIndex(snippet)).toBeGreaterThanOrEqual(0); + }); + + it.each(consecutiveMarkerPairs)("keeps the $earlierLabel ahead of the $laterLabel (#6225)", ({ + earlierSnippet, + laterSnippet, + }) => { + expect(markerIndex(earlierSnippet)).toBeLessThan(markerIndex(laterSnippet)); + }); + + it("returns from the reuse fast paths before reaching the destructive sandbox delete (#6225)", () => { + const firstReuseReturn = createSandboxBody.indexOf("return sandboxName;"); + expect(firstReuseReturn).toBeGreaterThanOrEqual(0); + expect(firstReuseReturn).toBeLessThan(markerIndex(DELETE_SNIPPET)); + }); + + it("issues exactly two sandbox delete commands with the failed-create cleanup after the create stream (#6225)", () => { + expect(createSandboxBody.split(DELETE_SNIPPET).length - 1).toBe(2); + const streamIndex = markerIndex("await streamSandboxCreate("); + expect(createSandboxBody.indexOf(DELETE_SNIPPET, streamIndex)).toBeGreaterThan(streamIndex); + }); + + // Divergence pinned for #6225: the create plan's provider cleanup re-run is + // the tolerant variant (the sandbox is already gone) and the gateway + // messaging credential upsert is wired into the plan, i.e. it executes only + // after the destructive delete and before the create stream. + it("wires the tolerant cleanup re-run and the gateway messaging upsert into the post-delete create plan (#6225)", () => { + const planRegion = createSandboxBody.slice( + markerIndex("sandboxCreatePlan.prepareSandboxCreatePlan({"), + markerIndex("await streamSandboxCreate("), + ); + expect(planRegion).toContain("tolerateMissingSandbox: true"); + expect(planRegion).toContain("upsertMessagingProviders,"); + }); +}); + +// ── 2. Messaging conflict guard wiring inside the sandbox messaging preflight ── +// +// The preflight is the injectable module the create path runs before any +// destructive effect (see the source-order pins above). It hosts the shared +// messaging conflict guard (#5954) with the onboard-specific interactive +// wiring: a "Continue anyway?" prompt is allowed here, unlike the rebuild +// preflight's forced non-interactive abort. + +function buildMessagingPrepResult( + overrides: Partial = {}, +): CreateSandboxMessagingPrepResult { + return { + disabledChannelNames: new Set(), + messagingTokenDefs: [], + extraPlaceholderKeys: [], + hasMessagingTokens: false, + reusableMessagingProviders: [], + reusableMessagingChannels: [], + missingWebSearchCredentialEnv: null, + ...overrides, + }; +} + +function buildPreflightHarness({ + planSandboxName = "sandbox-a", + prepResult = buildMessagingPrepResult(), +}: { + planSandboxName?: string; + prepResult?: CreateSandboxMessagingPrepResult; +} = {}) { + const events: string[] = []; + const exits: number[] = []; + const errorLines: string[] = []; + const guardDepsSeen: MessagingConflictGuardDeps[] = []; + const envPlan = { + schemaVersion: 1, + sandboxName: planSandboxName, + disabledChannels: [], + } as unknown as SandboxMessagingPlan; + const promptYesNoOrDefault = vi.fn(async () => true); + const deps: SandboxMessagingPreflightDeps = { + readMessagingPlanFromEnv: vi.fn(() => envPlan), + resolveDisabledChannels: vi.fn(() => { + events.push("resolve-disabled-channels"); + return ["slack"]; + }), + gatewayName: "nemoclaw", + registry: {} as SandboxMessagingPreflightDeps["registry"], + providerExistsInGateway: vi.fn(() => true), + isNonInteractive: () => false, + promptYesNoOrDefault, + cliName: () => "nemoclaw", + log: vi.fn(), + error: vi.fn((message: string) => { + errorLines.push(message); + }), + exitProcess: (code: number): never => { + exits.push(code); + throw new OnboardAbortError(code); + }, + getValidatedMessagingTokenByEnvKey: vi.fn(() => null), + getCredential: vi.fn(() => null), + normalizeCredentialValue: (value: unknown) => String(value ?? ""), + registerExtraPlaceholderProviders: vi.fn(() => []), + getMessagingChannelForEnvKey: vi.fn(() => null), + prepareCreateSandboxMessaging: vi.fn(() => { + events.push("prepare-messaging"); + return prepResult; + }), + enforceMessagingChannelConflicts: vi.fn(async (guardDeps: MessagingConflictGuardDeps) => { + events.push("conflict-guard"); + guardDepsSeen.push(guardDeps); + }), + }; + const input: SandboxMessagingPreflightInput = { + sandboxName: "sandbox-a", + agentName: "openclaw", + channels: [telegramChannel], + enabledChannels: ["telegram"], + webSearchConfig: null, + env: {}, + }; + return { deps, input, events, exits, errorLines, guardDepsSeen, promptYesNoOrDefault, envPlan }; +} + +describe("messaging conflict guard wiring in prepareSandboxMessagingPreflight (#6225)", () => { + it("runs the conflict guard against the matching env plan before preparing messaging state (#6225)", async () => { + const harness = buildPreflightHarness(); + + const result = await prepareSandboxMessagingPreflight(harness.input, harness.deps); + + expect(harness.events).toEqual([ + "resolve-disabled-channels", + "conflict-guard", + "prepare-messaging", + ]); + expect(harness.guardDepsSeen[0]?.sandboxName).toBe("sandbox-a"); + expect(harness.guardDepsSeen[0]?.gatewayName).toBe("nemoclaw"); + expect(harness.guardDepsSeen[0]?.currentPlan).toBe(harness.envPlan); + expect(harness.guardDepsSeen[0]?.currentSandboxDisabledChannels).toEqual(["slack"]); + expect(result.disabledChannels).toEqual(["slack"]); + }); + + it("skips the conflict guard when the env plan belongs to a different sandbox (#6225)", async () => { + const harness = buildPreflightHarness({ planSandboxName: "other-sandbox" }); + + await prepareSandboxMessagingPreflight(harness.input, harness.deps); + + expect(harness.events).toEqual(["resolve-disabled-channels", "prepare-messaging"]); + expect(harness.guardDepsSeen).toEqual([]); + }); + + // Onboard-vs-rebuild divergence pinned for #6225: this path hands the guard + // an interactive continue prompt; the rebuild preflight (#5954) forces a + // non-interactive abort instead. + it("wires an interactive continue prompt and the onboard exit into the conflict guard (#6225)", async () => { + const harness = buildPreflightHarness(); + + await prepareSandboxMessagingPreflight(harness.input, harness.deps); + const guardDeps = harness.guardDepsSeen[0] as MessagingConflictGuardDeps; + const continueAnswer = await guardDeps.promptContinue(); + + expect(continueAnswer).toBe(true); + expect(harness.promptYesNoOrDefault).toHaveBeenCalledWith(" Continue anyway?", null, false); + expect(guardDeps.exit).toBe(harness.deps.exitProcess); + }); + + it("aborts with exit code 1 when the web search credential is missing from the process (#6225)", async () => { + const harness = buildPreflightHarness({ + prepResult: buildMessagingPrepResult({ missingWebSearchCredentialEnv: "BRAVE_API_KEY" }), + }); + + await expect(prepareSandboxMessagingPreflight(harness.input, harness.deps)).rejects.toThrow( + OnboardAbortError, + ); + + expect(harness.exits).toEqual([1]); + expect(harness.errorLines[0]).toContain("BRAVE_API_KEY is not available in this process"); + expect(harness.errorLines[1]).toContain("disable web search before recreating the sandbox"); + }); +}); + +// ── 3. Gateway messaging upsert ordering inside the create plan ──────────── +// +// On the create path this module runs AFTER the destructive delete (pinned in +// section 1). Inside the plan itself, deterministic intent resolution and +// credential-binding validation complete before any gateway effect, and the +// tolerant cleanup re-run precedes the credential upsert. + +describe("gateway messaging upsert ordering in the sandbox create plan (#6225)", () => { + it("re-runs provider cleanup before upserting messaging credentials with replaceExisting (#6225)", () => { + const events: string[] = []; + const upsertMessagingProviders = vi.fn( + (_tokenDefs: MessagingTokenDef[], _options: { replaceExisting: true }) => { + events.push("gateway-upsert"); + return ["sandbox-telegram-bridge"]; + }, + ); + + const result = prepareSandboxCreatePlan({ + basePolicyPath: "/repo/policy.yaml", + buildCtx: "/tmp/nemoclaw-build-1", + sandboxName: "sandbox", + channels: [telegramChannel], + enabledChannels: ["telegram"], + disabledChannelNames: new Set(), + messagingTokenDefs: [telegramTokenDef], + reusableMessagingChannels: [], + reusableMessagingProviders: [], + hermesToolGateways: [], + sandboxGpuConfig, + dockerDriverGateway: true, + appendResourceFlags: (args) => { + events.push("resource-flags"); + args.push("--memory", "16g"); + }, + runProviderPreDeleteCleanup: () => { + events.push("pre-delete-cleanup-re-run"); + }, + upsertMessagingProviders, + getMessagingChannelForEnvKey: (envKey) => + envKey === "TELEGRAM_BOT_TOKEN" ? "telegram" : null, + getHermesToolGatewayProviderName: vi.fn(), + policyTier: null, + deps: { + resolveDockerGpuSandboxCreatePlan: vi.fn(() => ({ + useDockerGpuPatch: false, + logMessage: null, + })), + prepareInitialSandboxCreatePolicy: vi.fn(() => ({ + policyPath: "/tmp/policy.yaml", + appliedPresets: [], + })), + buildSandboxGpuCreateArgs: vi.fn(() => []), + }, + }); + + expect(events).toEqual(["resource-flags", "pre-delete-cleanup-re-run", "gateway-upsert"]); + expect(upsertMessagingProviders).toHaveBeenCalledWith([telegramTokenDef], { + replaceExisting: true, + }); + expect(result.messagingProviders).toEqual(["sandbox-telegram-bridge"]); + }); + + // Pinned gap for #6225: this validation is deterministic and fail-closed, + // but on the recreate path it only runs after the old sandbox was deleted — + // a binding drift halts gateway writes yet cannot restore the sandbox. + it("rejects a drifted credential binding before any gateway effect runs (#6225)", () => { + const intent = resolveSandboxCreateIntent({ + basePolicyPath: "/repo/policy.yaml", + sandboxName: "sandbox", + channels: [telegramChannel], + enabledChannels: ["telegram"], + disabledChannelNames: new Set(), + messagingProviderRequests: resolveSandboxCreateMessagingProviderRequests( + [telegramTokenDef], + () => "telegram", + ), + primaryMessagingCredentialEnvKeys: ["TELEGRAM_BOT_TOKEN"], + reusableMessagingChannels: [], + reusableMessagingProviders: [], + hermesToolGateways: [], + sandboxGpuConfig, + gpuCreateArgs: [], + useDockerGpuPatch: false, + sandboxGpuLogMessage: null, + policyTier: null, + }); + const preparePolicy = vi.fn(() => ({ policyPath: "/tmp/policy.yaml", appliedPresets: [] })); + const appendResourceFlags = vi.fn(); + const runProviderPreDeleteCleanup = vi.fn(); + const upsertMessagingProviders = vi.fn(() => []); + + expect(() => + materializeSandboxCreatePlan({ + intent, + buildCtx: "/tmp/nemoclaw-build-1", + messagingTokenDefs: [{ ...telegramTokenDef, token: null }], + prepareInitialSandboxCreatePolicy: preparePolicy, + appendResourceFlags, + runProviderPreDeleteCleanup, + upsertMessagingProviders, + getHermesToolGatewayProviderName: vi.fn(), + }), + ).toThrow("credential availability changed for provider 'sandbox-telegram-bridge'"); + expect(preparePolicy).not.toHaveBeenCalled(); + expect(appendResourceFlags).not.toHaveBeenCalled(); + expect(runProviderPreDeleteCleanup).not.toHaveBeenCalled(); + expect(upsertMessagingProviders).not.toHaveBeenCalled(); + }); +}); + +// ── 4. Resume identity: recorded sandbox name and the sandbox step gate ──── +// +// The deciding functions behind the #2753 contract: the recorded sandbox name +// is trusted (as resume identity and as a conflict source) only when the +// session's sandbox step actually completed. onboard() applies the same +// predicate when it seeds `recordedSandboxName` for the flow context, and +// `decideSandboxResume` collapses to a plain create when the step is +// incomplete. + +describe("resume identity honors the recorded sandbox name only after the sandbox step completed (#2753)", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it.each([ + { status: "pending" }, + { status: "in_progress" }, + { status: "failed" }, + { status: "skipped" }, + ])("ignores the recorded sandbox name while the sandbox step is $status (#2753)", ({ + status, + }) => { + const conflict = getResumeSandboxConflict( + { sandboxName: "recorded-sandbox", steps: { sandbox: { status } } }, + { sandboxName: "requested-sandbox" }, + ); + + expect(conflict).toBeNull(); + }); + + it("reports a conflict between requested and recorded names once the sandbox step is complete (#2753)", () => { + const conflict = getResumeSandboxConflict( + { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, + { sandboxName: "requested-sandbox" }, + ); + + expect(conflict).toEqual({ + requestedSandboxName: "requested-sandbox", + recordedSandboxName: "recorded-sandbox", + }); + }); + + it("normalizes the requested name before comparing it to the recorded name (#2753)", () => { + const conflict = getResumeSandboxConflict( + { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, + { sandboxName: " Recorded-Sandbox " }, + ); + + expect(conflict).toBeNull(); + }); + + it("reports no conflict without a requested override name even for a completed step (#2753)", () => { + const conflict = getResumeSandboxConflict( + { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, + {}, + ); + + expect(conflict).toBeNull(); + }); + + it("omits the sandbox conflict for an incomplete session so a new name can recover a phantom (#2753)", () => { + const conflicts = getResumeConfigConflicts( + { sandboxName: "phantom-sandbox", steps: { sandbox: { status: "in_progress" } } }, + { sandboxName: "fresh-name" }, + ); + + expect(conflicts).toEqual([]); + }); + + it("keeps the sandbox conflict for a completed session in the full conflict list (#2753)", () => { + const conflicts = getResumeConfigConflicts( + { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, + { sandboxName: "fresh-name" }, + ); + + expect(conflicts).toEqual([ + { field: "sandbox", requested: "fresh-name", recorded: "recorded-sandbox" }, + ]); + }); + + it("ignores provider and model env hints during interactive resume conflict checks (#6225)", () => { + vi.stubEnv("NEMOCLAW_PROVIDER", "cloud"); + vi.stubEnv("NEMOCLAW_MODEL", "meta/llama-3.3-70b-instruct"); + + const conflicts = getResumeConfigConflicts( + { provider: "nvidia-nim", model: "recorded-model" }, + {}, + ); + + expect(conflicts).toEqual([]); + }); + + it("resolves Dockerfile paths before comparing resume intent with the recorded session (#6225)", () => { + const recordedOnly = getResumeConfigConflicts( + { metadata: { fromDockerfile: "fixtures/Dockerfile.recorded" } }, + {}, + ); + const equivalentSpelling = getResumeConfigConflicts( + { metadata: { fromDockerfile: "./fixtures/Dockerfile.recorded" } }, + { fromDockerfile: "fixtures/Dockerfile.recorded" }, + ); + + expect(recordedOnly).toEqual([ + { + field: "fromDockerfile", + requested: null, + recorded: path.resolve("fixtures/Dockerfile.recorded"), + }, + ]); + expect(equivalentSpelling).toEqual([]); + }); +}); + +// ── 5. decideSandboxResume: the pure reuse/recreate policy ───────────────── + +const READY_RESUME_SIGNALS: SandboxResumeSignals = { + resume: true, + resumeAgentChanged: false, + sandboxStepComplete: true, + sandboxReuseState: "ready", + webSearchConfigChanged: false, + sandboxGpuConfigChanged: false, + messagingChannelConfigChanged: false, + hermesToolGatewayConfigChanged: false, +}; + +const resumeSignals = (overrides: Partial = {}): SandboxResumeSignals => ({ + ...READY_RESUME_SIGNALS, + ...overrides, +}); + +describe("decideSandboxResume pins the sandbox reuse contract (#6225)", () => { + it("decides create when the sandbox step never completed even with a ready recorded sandbox (#2753)", () => { + expect(decideSandboxResume(resumeSignals({ sandboxStepComplete: false }))).toEqual({ + kind: "create", + }); + expect( + decideSandboxResume( + resumeSignals({ + sandboxStepComplete: false, + resumeAgentChanged: true, + webSearchConfigChanged: true, + sandboxReuseState: "not_ready", + }), + ), + ).toEqual({ kind: "create" }); + }); + + it("decides create when the run is not a resume (#6225)", () => { + expect(decideSandboxResume(resumeSignals({ resume: false }))).toEqual({ kind: "create" }); + }); + + it("decides reuse only for a ready driftless resume with a completed sandbox step (#6225)", () => { + expect(decideSandboxResume(resumeSignals())).toEqual({ kind: "reuse" }); + }); + + it.each([ + { + flag: "resumeAgentChanged", + note: " [resume] Agent selection changed; revalidating sandbox compatibility.", + removeRegistryEntry: false, + }, + { + flag: "webSearchConfigChanged", + note: " [resume] Web Search configuration changed; recreating sandbox.", + removeRegistryEntry: true, + }, + { + flag: "sandboxGpuConfigChanged", + note: " [resume] Sandbox GPU settings changed; recreating sandbox.", + removeRegistryEntry: true, + }, + { + flag: "messagingChannelConfigChanged", + note: " [resume] Messaging channel configuration changed; recreating sandbox.", + removeRegistryEntry: true, + }, + { + flag: "hermesToolGatewayConfigChanged", + note: " [resume] Hermes managed tool gateway selection changed; recreating sandbox.", + removeRegistryEntry: true, + }, + ])("recreates on $flag drift and pins its note and registry removal policy (#6225)", ({ + flag, + note, + removeRegistryEntry, + }) => { + const decision = decideSandboxResume({ + ...READY_RESUME_SIGNALS, + [flag]: true, + } as SandboxResumeSignals); + + expect(decision).toEqual({ kind: "recreate", note, removeRegistryEntry }); + }); + + it("prefers the agent drift decision when every drift flag is set (#6225)", () => { + const decision = decideSandboxResume( + resumeSignals({ + resumeAgentChanged: true, + webSearchConfigChanged: true, + sandboxGpuConfigChanged: true, + messagingChannelConfigChanged: true, + hermesToolGatewayConfigChanged: true, + }), + ); + + expect(decision).toEqual({ + kind: "recreate", + note: " [resume] Agent selection changed; revalidating sandbox compatibility.", + removeRegistryEntry: false, + }); + }); + + it("repairs and recreates a recorded sandbox that is not ready (#6225)", () => { + expect(decideSandboxResume(resumeSignals({ sandboxReuseState: "not_ready" }))).toEqual({ + kind: "repair-and-recreate", + }); + }); + + it("recreates with registry removal when the recorded sandbox state is unavailable (#6225)", () => { + expect(decideSandboxResume(resumeSignals({ sandboxReuseState: "unknown" }))).toEqual({ + kind: "recreate", + note: " [resume] Recorded sandbox state is unavailable; recreating it.", + removeRegistryEntry: true, + }); + }); +}); + +// ── 6. applySandboxResumeDecision: the side-effect contract ──────────────── + +function buildResumeDecisionHarness({ repairError = null }: { repairError?: Error | null } = {}) { + const events: string[] = []; + const deps: SandboxResumeDeps = { + note: vi.fn((message: string) => { + events.push(`note:${message.trim()}`); + }), + removeSandboxFromRegistry: vi.fn((sandboxName: string) => { + events.push(`remove-registry:${sandboxName}`); + }), + repairRecordedSandbox: vi.fn((sandboxName: string | null) => { + events.push(`repair:${sandboxName}`); + const failure = [repairError].filter((error): error is Error => error !== null); + failure.forEach((error) => { + throw error; + }); + }), + recordRepairEvent: vi.fn(async (type: string) => { + events.push(type); + return null; + }), + }; + return { deps, events }; +} + +describe("applySandboxResumeDecision side effect contract (#6225)", () => { + it("removes the registry entry only when the recreate decision says so (#6225)", async () => { + const harness = buildResumeDecisionHarness(); + const decision: SandboxResumeDecision = { + kind: "recreate", + note: " [resume] Web Search configuration changed; recreating sandbox.", + removeRegistryEntry: true, + }; + + await applySandboxResumeDecision(decision, "sandbox-a", harness.deps); + + expect(harness.events).toEqual([ + "note:[resume] Web Search configuration changed; recreating sandbox.", + "remove-registry:sandbox-a", + ]); + }); + + it("keeps the registry entry for an agent change recreate (#6225)", async () => { + const harness = buildResumeDecisionHarness(); + const decision: SandboxResumeDecision = { + kind: "recreate", + note: " [resume] Agent selection changed; revalidating sandbox compatibility.", + removeRegistryEntry: false, + }; + + await applySandboxResumeDecision(decision, "sandbox-a", harness.deps); + + expect(harness.deps.removeSandboxFromRegistry).not.toHaveBeenCalled(); + expect(harness.events).toEqual([ + "note:[resume] Agent selection changed; revalidating sandbox compatibility.", + ]); + }); + + it.each([ + { kind: "create" as const }, + { kind: "reuse" as const }, + ])("performs no side effects for a $kind decision (#6225)", async ({ kind }) => { + const harness = buildResumeDecisionHarness(); + + await applySandboxResumeDecision({ kind }, "sandbox-a", harness.deps); + + expect(harness.events).toEqual([]); + }); + + it("emits repair started and completed events around the recorded sandbox cleanup (#6225)", async () => { + const harness = buildResumeDecisionHarness(); + + await applySandboxResumeDecision({ kind: "repair-and-recreate" }, "sandbox-a", harness.deps); + + expect(harness.events).toEqual([ + "note:[resume] Recorded sandbox 'sandbox-a' exists but is not ready; recreating it.", + "state.repair.started", + "repair:sandbox-a", + "state.repair.completed", + ]); + expect(harness.deps.recordRepairEvent).toHaveBeenCalledWith("state.repair.started", { + state: "sandbox", + metadata: { repair: "recorded-sandbox-cleanup", sandboxName: "sandbox-a" }, + }); + }); + + it("emits a repair failed event and rethrows when the recorded sandbox cleanup throws (#6225)", async () => { + const harness = buildResumeDecisionHarness({ repairError: new Error("cleanup exploded") }); + + await expect( + applySandboxResumeDecision({ kind: "repair-and-recreate" }, "sandbox-a", harness.deps), + ).rejects.toThrow("cleanup exploded"); + + expect(harness.events).toContain("state.repair.failed"); + expect(harness.events).not.toContain("state.repair.completed"); + expect(harness.deps.recordRepairEvent).toHaveBeenCalledWith("state.repair.failed", { + state: "sandbox", + error: "cleanup exploded", + metadata: { repair: "recorded-sandbox-cleanup", sandboxName: "sandbox-a" }, + }); + }); +}); diff --git a/test/onboard-session-secret-invariants.test.ts b/test/onboard-session-secret-invariants.test.ts new file mode 100644 index 00000000000..da7bcef6a91 --- /dev/null +++ b/test/onboard-session-secret-invariants.test.ts @@ -0,0 +1,361 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * Characterization of the onboarding session persistence SECRET BOUNDARY + * (#6225, epic #6224). + * + * ~/.nemoclaw/onboard-session.json is the durable artifact `onboard --resume` + * trusts, so its contract is that credential VALUES never reach disk: + * + * - `credentialEnv` persists the env-var NAME only; the secret value stays + * in the process environment and is re-hydrated on resume + * (src/lib/state/onboard-session.ts). + * - `endpointUrl` is passed through redactUrl() (src/lib/security/redact.ts) + * both in filterSafeUpdates() and again in normalizeSession() on every + * save and load: userinfo stripped, sensitive-named query params masked, + * fragment removed; non-URL values fall back to redactSensitiveText(). + * - `migratedLegacyValueHashes` stores sha256 hex digests keyed by env + * name, mirroring legacyValueHash() in src/lib/onboard.ts, never the + * migrated plaintext. + * - failure messages and per-step errors pass through redactSensitiveText(). + * + * These tests PIN current behavior as a regression baseline. Sessions are + * built through the real mutation/serialization functions (createSession, + * saveSession, markStep*, loadSession) — never hand-written JSON — then the + * raw persisted text is scanned for sentinel leakage and deserialized back. + * Known gaps (the unset-vs-declined null ambiguity, benign-named query + * params) are pinned as-is and annotated, deliberately not fixed here. + */ + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import os from "node:os"; +import path from "node:path"; + +import { afterAll, beforeEach, describe, expect, it } from "vitest"; + +import type { Session } from "../src/lib/state/onboard-session"; + +const require = createRequire(import.meta.url); + +// SESSION_DIR/SESSION_FILE are derived from HOME at module-load time, so the +// temp HOME must be in place before the session module loads. These CJS +// requires (via the integration project's source-require hook) execute here, +// after the assignment — unlike a hoisted static import. +const originalHome = process.env.HOME; +const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-session-secret-")); +process.env.HOME = tempHome; + +const session: typeof import("../src/lib/state/onboard-session") = require("../src/lib/state/onboard-session"); +const stepMutation: typeof import("../src/lib/state/onboard-step-mutation") = require("../src/lib/state/onboard-step-mutation"); + +const restoreHome = + originalHome === undefined + ? () => { + delete process.env.HOME; + } + : () => { + process.env.HOME = originalHome; + }; + +const originalCredentialValue = process.env.NVIDIA_API_KEY; +const restoreCredentialValue = + originalCredentialValue === undefined + ? () => { + delete process.env.NVIDIA_API_KEY; + } + : () => { + process.env.NVIDIA_API_KEY = originalCredentialValue; + }; + +// Distinctive marker embedded in the sentinel so raw-text scans catch partial +// leakage, not just the intact token. +const SENTINEL_MARKER = "sentinel6225zqx"; +// nvapi-shaped so every redactor tier (TOKEN_PREFIX_PATTERNS in +// src/lib/security/secret-patterns.ts) recognizes it as a secret wherever +// redaction is expected to fire. +const SENTINEL_SECRET = `nvapi-${SENTINEL_MARKER}-secret-value-do-not-persist`; +const SENTINEL_SHA256 = createHash("sha256").update(SENTINEL_SECRET).digest("hex"); + +const REDACTED_FAILURE_MESSAGE = + "sandbox create failed: NVIDIA_API_KEY= and Bearer "; + +function readRawSessionText(): string { + return fs.readFileSync(session.SESSION_FILE, "utf8"); +} + +function requireLoadedSession(): Session { + const loaded = session.loadSession(); + expect(loaded).not.toBeNull(); + return loaded ?? session.createSession(); +} + +beforeEach(() => { + session.clearSession(); + // The real secret value lives in the process environment during onboarding + // (credential hydration reads it from there on resume). Keeping it staged + // for every test proves the session layer never captures it ambiently. + process.env.NVIDIA_API_KEY = SENTINEL_SECRET; +}); + +afterAll(() => { + session.clearSession(); + restoreCredentialValue(); + restoreHome(); + fs.rmSync(tempHome, { recursive: true, force: true }); +}); + +describe("onboard session persistence secret boundary (#6225)", () => { + it("persists the credential env-var name only while the secret value stays in process.env", () => { + // Guard: the module-scope HOME redirect must have taken effect, or the + // scans below would read a session file outside the temp sandbox. + expect(session.SESSION_DIR).toBe(path.join(tempHome, ".nemoclaw")); + + session.saveSession(session.createSession()); + session.markStepCompleteRecordOnly("provider_selection", { + provider: "nvidia-prod", + model: "nvidia/llama-3.1-nemotron-70b-instruct", + }); + session.markStepCompleteRecordOnly("inference", { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + }); + + const raw = readRawSessionText(); + expect(raw).toContain('"credentialEnv": "NVIDIA_API_KEY"'); + expect(raw).not.toContain(SENTINEL_SECRET); + expect(raw).not.toContain(SENTINEL_MARKER); + + const loaded = requireLoadedSession(); + expect(loaded.credentialEnv).toBe("NVIDIA_API_KEY"); + expect(loaded.provider).toBe("nvidia-prod"); + expect(loaded.endpointUrl).toBe("https://integrate.api.nvidia.com/v1"); + }); + + it("keeps the sentinel secret out of every persisted field across a failed-run round-trip", () => { + session.saveSession(session.createSession()); + session.markStepStartedRecordOnly("preflight"); + session.markStepCompleteRecordOnly("preflight"); + session.markStepStartedRecordOnly("gateway"); + session.markStepCompleteRecordOnly("gateway"); + session.markStepCompleteRecordOnly("provider_selection", { + provider: "nvidia-prod", + model: "nemotron-test", + }); + session.markStepCompleteRecordOnly("inference", { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: `https://svc:${SENTINEL_SECRET}@api.example.com/v1?access_token=${SENTINEL_SECRET}`, + migratedLegacyValueHashes: { NVIDIA_API_KEY: SENTINEL_SHA256 }, + }); + session.markStepStartedRecordOnly("sandbox"); + // The process-exit backstop (markLastStartedStepFailed in + // src/lib/onboard/exit-step-failure.ts) records failures with the legacy + // machine-updating options; mirror that exact write here. + session.markStepFailed( + "sandbox", + `sandbox create failed: NVIDIA_API_KEY=${SENTINEL_SECRET} and Bearer ${SENTINEL_SECRET}`, + stepMutation.LEGACY_MACHINE_STEP_MUTATION_OPTIONS, + ); + + const raw = readRawSessionText(); + expect(raw).not.toContain(SENTINEL_SECRET); + expect(raw).not.toContain(SENTINEL_MARKER); + expect(raw).toContain("NVIDIA_API_KEY="); + + const loaded = requireLoadedSession(); + expect(loaded.credentialEnv).toBe("NVIDIA_API_KEY"); + expect(loaded.endpointUrl).toBe("https://api.example.com/v1?access_token=%3CREDACTED%3E"); + expect(loaded.migratedLegacyValueHashes).toEqual({ NVIDIA_API_KEY: SENTINEL_SHA256 }); + expect(loaded.failure?.step).toBe("sandbox"); + expect(loaded.failure?.message).toBe(REDACTED_FAILURE_MESSAGE); + expect(loaded.steps.sandbox.error).toBe(REDACTED_FAILURE_MESSAGE); + expect(loaded.lastStepStarted).toBe("sandbox"); + expect(loaded.status).toBe("failed"); + expect(loaded.machine.state).toBe("failed"); + + // The persisted form is a fixed point of normalizeSession: deserializing + // and re-normalizing yields the identical session, so a resume never + // re-redacts fields into a different shape. + expect(session.normalizeSession(JSON.parse(raw))).toEqual(loaded); + }); +}); + +describe("endpointUrl persistence stores the redactUrl() form only (#6225)", () => { + const endpointCases = [ + { + label: "a plain https endpoint verbatim", + input: "https://api.example.com/v1", + stored: "https://api.example.com/v1", + }, + { + label: "a bare origin with URL normalization applied", + input: "https://api.example.com", + stored: "https://api.example.com/", + }, + { + label: "an endpoint with basic-auth userinfo with the credentials stripped", + input: `https://svc:${SENTINEL_SECRET}@api.example.com/v1`, + stored: "https://api.example.com/v1", + }, + { + label: "a sensitive api_token query parameter as a percent-encoded REDACTED marker", + input: `https://api.example.com/v1?api_token=${SENTINEL_SECRET}`, + stored: "https://api.example.com/v1?api_token=%3CREDACTED%3E", + }, + { + label: "a sensitive access_token parameter masked while benign neighbors survive", + input: `https://api.example.com/v1?access_token=${SENTINEL_SECRET}&model=nemotron-mini`, + stored: "https://api.example.com/v1?access_token=%3CREDACTED%3E&model=nemotron-mini", + }, + { + label: "an endpoint with the URL fragment removed", + input: `https://api.example.com/v1#${SENTINEL_SECRET}`, + stored: "https://api.example.com/v1", + }, + { + label: "a local http endpoint untouched", + input: "http://localhost:11434/v1", + stored: "http://localhost:11434/v1", + }, + { + label: "a non-URL value through the sensitive-text fallback unchanged", + input: "ollama runs locally without an endpoint", + stored: "ollama runs locally without an endpoint", + }, + { + label: "a bearer token inside a non-URL value as a REDACTED marker", + input: `endpoint auth uses Bearer ${SENTINEL_SECRET}`, + stored: "endpoint auth uses Bearer ", + }, + ] as const; + + it.each(endpointCases)("stores $label", ({ input, stored }) => { + session.saveSession(session.createSession()); + session.markStepCompleteRecordOnly("inference", { endpointUrl: input }); + + const persisted = JSON.parse(readRawSessionText()) as { endpointUrl: string | null }; + expect(persisted.endpointUrl).toBe(stored); + expect(requireLoadedSession().endpointUrl).toBe(stored); + }); + + it("persists token-shaped values under benign query parameter names verbatim", () => { + // KNOWN GAP pinned as-is (#6224): redactUrl() only masks userinfo and + // query parameters whose NAME matches signature|sig|token|auth| + // access_token. The parseable-URL branch never applies the token-prefix + // patterns, so a secret-shaped value under a benign parameter name is + // persisted verbatim. Characterization only — do not fix here. + const gapSentinel = "nvapi-gap6224param-value-persisted-verbatim"; + session.saveSession(session.createSession()); + session.markStepCompleteRecordOnly("inference", { + endpointUrl: `https://api.example.com/v1?model=${gapSentinel}`, + }); + + expect(readRawSessionText()).toContain(gapSentinel); + expect(requireLoadedSession().endpointUrl).toBe( + `https://api.example.com/v1?model=${gapSentinel}`, + ); + }); +}); + +describe("migratedLegacyValueHashes persistence (#6225)", () => { + it("defaults to null on a fresh session", () => { + session.saveSession(session.createSession()); + const persisted = JSON.parse(readRawSessionText()) as { + migratedLegacyValueHashes: unknown; + }; + expect(persisted.migratedLegacyValueHashes).toBeNull(); + }); + + it("stores 64-char sha256 hex digests keyed by env-var name, never the legacy plaintext", () => { + // Digest shape mirrors legacyValueHash() in src/lib/onboard.ts, the only + // production writer of this map (via persistMigratedLegacyKeys()). + const otherLegacyValue = `sk-${SENTINEL_MARKER}-legacy-openai-value`; + const otherDigest = createHash("sha256").update(otherLegacyValue).digest("hex"); + session.saveSession(session.createSession()); + session.markStepCompleteRecordOnly("inference", { + migratedLegacyValueHashes: { + NVIDIA_API_KEY: SENTINEL_SHA256, + OPENAI_API_KEY: otherDigest, + }, + }); + + const raw = readRawSessionText(); + expect(raw).not.toContain(SENTINEL_SECRET); + expect(raw).not.toContain(SENTINEL_MARKER); + expect(raw).not.toContain(otherLegacyValue); + + const loaded = requireLoadedSession(); + const hashes = loaded.migratedLegacyValueHashes ?? {}; + expect(Object.keys(hashes).sort()).toEqual(["NVIDIA_API_KEY", "OPENAI_API_KEY"]); + for (const digest of Object.values(hashes)) { + expect(digest).toMatch(/^[0-9a-f]{64}$/); + } + expect(hashes.NVIDIA_API_KEY).toBe(SENTINEL_SHA256); + expect(hashes.OPENAI_API_KEY).toBe(otherDigest); + }); + + it("drops non-string entries from migratedLegacyValueHashes updates", () => { + session.saveSession(session.createSession()); + session.markStepCompleteRecordOnly("inference", { + migratedLegacyValueHashes: { + NVIDIA_API_KEY: SENTINEL_SHA256, + BROKEN_NUMERIC: 123, + BROKEN_NULL: null, + } as unknown as Record, + }); + + expect(requireLoadedSession().migratedLegacyValueHashes).toEqual({ + NVIDIA_API_KEY: SENTINEL_SHA256, + }); + }); +}); + +describe("credentialEnv tri-state serialization (#6225)", () => { + // The SessionUpdates contract (GH #2625) distinguishes three intents: + // undefined -> leave unchanged, null -> explicit clear, string -> set. + // On disk, however, "never prompted" and "explicitly declined/cleared" + // both serialize to `"credentialEnv": null` — the persisted form cannot + // distinguish the two. This unset/declined ambiguity is a KNOWN CONTRACT + // GAP tracked by epic #6224; it is pinned as-is here, deliberately unfixed. + + it("serializes a never-recorded credential as null", () => { + session.saveSession(session.createSession()); + + const raw = readRawSessionText(); + expect(raw).toContain('"credentialEnv": null'); + expect((JSON.parse(raw) as { credentialEnv: string | null }).credentialEnv).toBeNull(); + expect(requireLoadedSession().credentialEnv).toBeNull(); + }); + + it("leaves the recorded name unchanged when an update omits credentialEnv", () => { + session.saveSession(session.createSession()); + session.markStepCompleteRecordOnly("inference", { credentialEnv: "NVIDIA_API_KEY" }); + session.markStepCompleteRecordOnly("openclaw", { credentialEnv: undefined }); + + expect(requireLoadedSession().credentialEnv).toBe("NVIDIA_API_KEY"); + }); + + it("serializes an explicit decline identically to never-recorded (#6224)", () => { + session.saveSession(session.createSession()); + const rawUnset = readRawSessionText(); + + session.markStepCompleteRecordOnly("provider_selection", { credentialEnv: "NVIDIA_API_KEY" }); + expect(readRawSessionText()).toContain('"credentialEnv": "NVIDIA_API_KEY"'); + + session.markStepCompleteRecordOnly("inference", { credentialEnv: null }); + const rawDeclined = readRawSessionText(); + + const unsetValue = (JSON.parse(rawUnset) as { credentialEnv: string | null }).credentialEnv; + const declinedValue = (JSON.parse(rawDeclined) as { credentialEnv: string | null }) + .credentialEnv; + expect(unsetValue).toBeNull(); + expect(declinedValue).toBeNull(); + expect(rawDeclined).toContain('"credentialEnv": null'); + // Ambiguity pin: both histories collapse to the same persisted value, so + // a resumed run cannot tell "user declined" apart from "never asked". + expect(declinedValue).toBe(unsetValue); + expect(requireLoadedSession().credentialEnv).toBeNull(); + }); +}); From ab988dd246563d17a5d332d3c1b8800e539bb368 Mon Sep 17 00:00:00 2001 From: Abhimanyu Kumar Date: Sat, 4 Jul 2026 15:28:34 +0530 Subject: [PATCH 2/3] chore(architecture): compact lifecycle map and reduce characterization surface (#6225) Address review: replace the nested AGENTS.md inventory with a compact symbol-referenced map at src/lib/onboard/lifecycle-contracts.md and revert the root AGENTS.md registration; reduce transition-traces to the five ordered event-trace pins no existing machine suite covers; drop all raw-source scanning from the lifecycle invariants (the create-path ordering contract is now prose in the map); consolidate the genuinely missing session-security cases into src/lib/state/onboard-session.test.ts, encoding token-shaped-value persistence as pending desired behavior via it.fails rather than an accepted pin; fix the trace-harness updateSession fallback to return the cloned draft so void-returning mutators persist. Signed-off-by: Abhimanyu Kumar --- AGENTS.md | 1 - src/lib/onboard/AGENTS.md | 249 ---------- src/lib/onboard/README.md | 2 + src/lib/onboard/lifecycle-contracts.md | 92 ++++ src/lib/onboard/machine/README.md | 2 +- .../onboard/machine/transition-traces.test.ts | 454 ++---------------- src/lib/state/onboard-session.test.ts | 61 +++ test/onboard-lifecycle-invariants.test.ts | 435 ++--------------- .../onboard-session-secret-invariants.test.ts | 361 -------------- 9 files changed, 236 insertions(+), 1421 deletions(-) delete mode 100644 src/lib/onboard/AGENTS.md create mode 100644 src/lib/onboard/lifecycle-contracts.md delete mode 100644 test/onboard-session-secret-invariants.test.ts diff --git a/AGENTS.md b/AGENTS.md index 743110c8bac..4d99c7037a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,6 @@ Load the `nemoclaw-skills-guide` skill for a full catalog and quick decision gui Package-specific guides: - Messaging architecture and channel migration guidance: [`src/lib/messaging/AGENTS.md`](src/lib/messaging/AGENTS.md) -- Onboarding and runtime lifecycle contract map: [`src/lib/onboard/AGENTS.md`](src/lib/onboard/AGENTS.md) ## Quick Reference diff --git a/src/lib/onboard/AGENTS.md b/src/lib/onboard/AGENTS.md deleted file mode 100644 index 38eb893c9c0..00000000000 --- a/src/lib/onboard/AGENTS.md +++ /dev/null @@ -1,249 +0,0 @@ - - - -# Agent Instructions for `src/lib/onboard` - -## Purpose - -This document is the lifecycle contract map required by issue #6225 (epic #6224). It records, for every onboarding and runtime-mutation journey, where desired state comes from, what is validated before effects, where the first externally visible and first destructive effects happen, what is checkpointed, where the credential boundary sits, and what compensation exists today. - -This is a characterization map. It describes current behavior, including behavior the epic considers a contract gap. Nothing in this file is a target design; target designs live in the child issues (#6226, #6227, #6228) and in `machine/README.md`. - -Companion documents: - -- `src/lib/onboard/README.md` covers file placement for the `onboard.ts` split. -- `src/lib/onboard/machine/README.md` covers the FSM target architecture, state vocabulary, and handler contract. -- `src/lib/messaging/AGENTS.md` covers the messaging package this map frequently crosses into. - -Line anchors below were verified against the tree this document was committed with. Symbol names are the stable reference; treat line numbers as hints that drift. - -## Shared Lifecycle Vocabulary - -### Epic terminology (from #6224, use verbatim) - -- **Lifecycle contribution.** An internal, data-first input to a NemoClaw plan: policy, provider, package, port-forward, resource, or runtime setup. Not a public SDK. -- **Managed agent package.** A package NemoClaw records as desired state for an agent runtime (OpenClaw, Hermes, Deep Agents Code). #5998 owns the narrow user-facing managed OpenClaw package lifecycle (CLI and desired-state MVP), not this epic. -- **Agent-native plugin.** A plugin interpreted by OpenClaw, Hermes, or another agent runtime. -- **NemoClaw plugin SDK.** Reserved for a future versioned external contract. Epic #6224 does not create one, and nothing in this package should be documented as one before the #6229 decision record exists. - -### Lifecycle verbs - -These definitions describe how the terms are used in this map. They are grounded in current code artifacts and in epic #6224's principles (plan before effects; persist data, bind capabilities at apply time; version and revalidate resumed plans; one vocabulary across create, rebuild, re-onboard, reconcile). - -| Term | Meaning in this map | Current code artifact | -|---|---|---| -| intent | Deterministic, serializable description of a desired outcome, derived from operator inputs and recorded selections before any effect runs. Contains logical bindings (credential env-var names, presence flags), never secret values, temp paths, callbacks, or process handles. | `SandboxCreateIntent` (`sandbox-create-intent-types.ts:41`), produced by the pure `resolveSandboxCreateIntent` (`sandbox-create-plan.ts:228`). Explicitly not a persistence, machine-event, or public API contract. | -| plan | The compiled form of an intent plus observed state, ready to execute. The codebase has two flavors today: serializable plans (`SandboxMessagingPlan`) and execution plans that carry temp paths and cleanup callbacks (the return value of `materializeSandboxCreatePlan`). | `MessagingWorkflowPlanner.buildPlan` (`src/lib/messaging/compiler/workflow-planner.ts:44`); `materializeSandboxCreatePlan` (`sandbox-create-plan.ts:334`). | -| apply | The effectful phase. Capabilities (credential values, live handles, gateway connections) are bound at apply time, not stored in intent or checkpoints. | `bindMessagingTokenDefs` (`sandbox-create-plan.ts:298`) rebinds real tokens at materialization and fails on drift; gateway upserts happen inside `materializeSandboxCreatePlan`. | -| checkpoint | Durable, secret-free record of progress that a later run can resume from. | The onboard session (`~/.nemoclaw/onboard-session.json`, `src/lib/state/onboard-session.ts:39`) with whole-step granularity plus the machine snapshot; pre-recreate workspace backups; the rebuild backup manifest. | -| result | The explicit outcome a state handler returns to the machine: advance, retry, branch, complete, or failed. | `OnboardStateResult` (`machine/result.ts`), applied through `OnboardRuntime.applyResult` and the `OnboardRuntimeBoundary` facade (`runtime-boundary.ts`). | -| compensation | Effects run after a failure or cancellation to undo or mitigate a partially applied journey. | Failed-create sandbox deletion (`onboard.ts:3052`); cancel rollback (`cancel-rollback.ts`); `rollbackChannelAdd` (`src/lib/actions/sandbox/policy-channel.ts:1079`); rebuild's recovery-registry restore (`rebuild-recreate-phase.ts:206`). | -| reconcile | Bringing recorded desired state and observed live state back into agreement without a full re-run. | Drift detection in `createSandbox` (`onboard.ts:2614-2635`); `reconcileSandboxMessaging` (`machine/handlers/sandbox-messaging.ts:253`); `mergeOpenClawRestoredConfig` ownership rules (`src/lib/state/openclaw-config-merge.ts:17`). | - -## Machine states and production owners - -The 13 machine states (`machine/definition.ts:12-65`) and their transition table (`machine/transitions.ts:11-29`: the linear advance chain, the `inference -> provider_selection` retry, the `sandbox -> openclaw | agent_setup` branch, and every non-terminal state `-> failed`). Every non-terminal state has exactly one production owner: - -| State | Production owner | -|---|---| -| `init` | Entered by session bootstrap; advanced to `preflight` directly by `onboard()` (`onboard.ts:4771`) before the first slice runs. | -| `preflight` | `machine/handlers/preflight.ts` | -| `gateway` | `machine/handlers/gateway.ts` | -| `provider_selection`, `inference` | `machine/handlers/provider-inference.ts` (composite handler with declared sequence ownership) | -| `sandbox` | `machine/handlers/sandbox.ts`, with the resume decision in `handlers/sandbox-resume.ts:50` and messaging reconciliation in `handlers/sandbox-messaging.ts:253` | -| `openclaw`, `agent_setup` | `machine/handlers/agent-setup.ts` (agent branch) | -| `policies` | `machine/handlers/policies.ts` | -| `finalizing`, `post_verify` | `machine/handlers/finalization.ts` | -| `complete`, `failed` | Terminal; no handler. | - -The FSM is deliberately step-granular. Mid-operation resume inside gateway startup, sandbox creation, credential upserts, model probes, or policy application is out of scope for the current machine (`machine/types.ts:4-10`). This is the root of several checkpoint gaps below. - -## Journey Contract Matrix - -Summary: - -| Journey | Entry point | Desired-state source | First destructive effect | Durable checkpoint | -|---|---|---|---|---| -| 1. Sandbox create (fresh onboard) | `onboard()` (`src/lib/onboard.ts:4610`) | Flags + env + prompts of the current run | None against prior state; creation itself at `streamSandboxCreate` (`onboard.ts:2968`) | Whole-step session + machine snapshot | -| 2. Rebuild / installer upgrade | `rebuildSandbox` (`rebuild-pipeline.ts:34` via the `rebuild.ts` facade) | Registry entry + matching session only; ambient env quarantined | `openshell sandbox delete` (`rebuild-destroy-phase.ts:81`) | Backup manifest + session rewritten as recreate contract + recovery registry snapshot | -| 3. Re-onboard / resume over existing sandbox | Same `onboard()`, live-sandbox block of `createSandbox` (`onboard.ts:2571`) | Current run's env/flags/prompts; registry and gateway used as drift baseline | Delete + `docker rmi` + registry removal (`onboard.ts:2836-2847`) | Pre-recreate workspace backup + session | -| 4. Runtime mutation (provider switch, config set, channels, plugin entries) | `inference-set.ts`, `sandbox/config.ts`, `policy-channel.ts` | CLI flags + registry/session metadata; per-channel delta plans | None in-place; channel changes defer destruction to a queued rebuild | Audit entries + registry plan persistence | - -### Journey 1: sandbox create (fresh onboard, interactive and non-interactive) - -| Contract dimension | Current behavior | -|---|---| -| Desired-state source | Flags, env, and TTY prompts resolved by `resolveOnboardEntryOptions` (`entry-options.ts:46`; auto-resume of an in-progress session at line 63). Provider/model/endpoint selected in the `provider_selection`/`inference` states. Messaging plan compiled by `MessagingWorkflowPlanner.buildPlan` and transported through process env `NEMOCLAW_MESSAGING_PLAN_B64` (`src/lib/messaging/applier/types.ts:20`). Create intent resolved by `resolveSandboxCreateIntent` (`sandbox-create-plan.ts:228`). | -| Deterministic planning/validation | `preflight()` host checks (`onboard.ts:1594`); early env validation and onboard lock (`onboard.ts:4659-4662`); messaging conflict guard inside `prepareSandboxMessagingPreflight` (`onboard.ts:2524` -> `sandbox-messaging-preflight.ts:63` -> `messaging-conflict-guard.ts:65`); `resolveSandboxCreateIntent` is pure and deterministic. | -| First externally visible effect | Gateway reuse/recover/start in the `gateway` state (`startGateway`, `onboard.ts:2276`). Inference-provider credential upserts to the gateway happen during `provider_selection`/`inference` (`upsertProvider`, `onboard.ts:898`), before any sandbox exists. | -| First destructive effect | None against pre-existing sandbox state on a truly fresh create. Gateway messaging-provider upserts run with `replaceExisting: true` inside `materializeSandboxCreatePlan` (`sandbox-create-plan.ts:372`), which overwrites same-name provider entries in shared gateway state. Creation itself is `streamSandboxCreate` (`onboard.ts:2968`). | -| Checkpoints | Whole-step session (`Session`, `onboard-session.ts:84`; 8 fixed steps; atomic tmp+rename save) plus machine snapshot, written through `OnboardRuntimeBoundary`. Registry registration is deferred until the sandbox is confirmed ready (`registerCreatedSandbox`, `onboard.ts:3108`) to prevent phantom entries. There is no sub-step checkpoint. | -| Credential/secret boundary | Session persists `credentialEnv` as an env-var name only (`onboard-session.ts:100`), `endpointUrl` redacted at save (`onboard-session.ts:492`), legacy credential migration as sha256 hashes only (`onboard-session.ts:122`). `SandboxCreateIntent` carries presence flags and env keys, never values; real tokens are rebound at apply time by `bindMessagingTokenDefs` (`sandbox-create-plan.ts:298`), which fails closed on availability or provider-type drift. | -| Retry/compensation/rollback | Readiness failure deletes the failed new sandbox (`onboard.ts:3052`) and exits with retry hints. Build-context temp dirs (which can hold env-arg API keys) are cleaned inline with a process-exit safety net (`onboard.ts:2856`, `2988`). Two-key cancel rollback is armed only for a brand-new sandbox (`onboard.ts:3175`) and clears the session when it fires (`cancel-rollback.ts:157`). Nonzero exit marks the last started step failed (`exit-step-failure.ts:19`, registered at `onboard.ts:4794`). | -| Extension assembly points | All current lifecycle contributions converge in `prepareSandboxCreatePlan` (`onboard.ts:2880`): messaging channel manifests (via token defs and the plan env), policy presets (`initialSandboxPolicy`), extra providers from the registry, Hermes tool gateways, GPU create args, resource-profile flags. Web-search reaches the create args only indirectly (BRAVE/TAVILY keys via `extra-placeholder-keys.ts` and the extra-provider registry); its plugin-entry/config rendering flows through the build patch and `web-search-flow.ts`, outside the create plan. | -| Existing tests / known-uncovered failure modes | Tests: `sandbox-create-plan.test.ts` (#6218 characterization), `machine/handlers/sandbox.test.ts`, the `machine/*.test.ts` suite, `test/onboard.test.ts`, `test/onboard-selection.test.ts`, `test/onboard-messaging.test.ts`. Uncovered: process death between gateway provider upserts and sandbox create leaves gateway credential state changed with no sandbox; no test pins gateway provider state after a mid-create failure; no mid-step resume (by design, `machine/types.ts:4-10`). | - -Interactive and non-interactive runs share this contract; non-interactive substitutes env defaults and hard aborts for prompts (`non-interactive-abort.ts`, and the `isNonInteractive()` branches in `createSandbox`). - -### Journey 2: rebuild, including installer-driven upgrade - -Installer batch upgrades call the same pipeline: `upgradeSandboxes` invokes `rebuildSandbox(name, ["--yes"], { recoveryManifest, ... })` (`src/lib/actions/upgrade-sandboxes.ts:310`). - -| Contract dimension | Current behavior | -|---|---| -| Desired-state source | Registry entry + matching session only, never ambient env: `prepareRebuildResumeConfig` (`rebuild-resume-config.ts:224`, the #5735 pre-delete trust boundary; custom-endpoint URLs fail closed if recorded only in another sandbox's session). Ambient `NEMOCLAW_*` selection env is quarantined for the recreate by `isolateAmbientRecreateEnv` (`rebuild-env-isolation.ts:116`, applied at `rebuild-recreate-phase.ts:177`). Messaging comes from the registry-persisted plan: `stageRebuildMessagingPlanOrBail` (`rebuild-messaging-phase.ts:81`) -> `buildRebuildPlanFromSandboxEntry` (`workflow-planner.ts:116`). | -| Deterministic planning/validation | All before destruction, in `runRebuildPreflightPhase` (`rebuild-preflight-phase.ts:68`): registry entry snapshot pinned and re-asserted unchanged after confirmation (`:77`, `:124`); gateway schema; recovery-manifest validation; confirmation; onboard lock; then `prepareRebuildTargetPreflights` (`rebuild-preflight-target-phase.ts:40`): target config, recreate options, messaging plan staged (`:81`), messaging conflict preflight (#5954) immediately after staging (`:90` -> `rebuild-messaging-conflict-preflight.ts:49`, forced non-interactive abort), authoritative runtime preflight, base image, target runtime. DCode rebuilds additionally prebuild and fingerprint the replacement image pre-delete (#6214): `prepareDcodeReplacementBeforeMutation` (`rebuild-dcode-preflight.ts:354`). Mutation-edge revalidation runs immediately before deletion: `revalidatePreparedRecoveryBeforeDelete` (`rebuild-pipeline.ts:119`) and `dcodePreflight.revalidateBeforeDelete` (`rebuild-pipeline.ts:146` -> `revalidateDcodeReplacementAtMutationEdge`, `rebuild-dcode-preflight.ts:415`). | -| First externally visible effect | Shields auto-unlock window (`runRebuildShieldsPhase`, `rebuild-pipeline.ts:104`) and the validated-target registry update at the end of preflight (`rebuild-preflight-target-phase.ts:135`). In the destroy phase, MCP adapter scrub/provider detach and NIM container stop precede deletion (`rebuild-destroy-phase.ts:57-70`). | -| First destructive effect | `openshell sandbox delete` (`rebuild-destroy-phase.ts:81`), then registry entry removal (`:113`; the entry is intentionally preserved when MCP entries exist, as the durable MCP rebuild transaction). | -| Checkpoints | Workspace backup manifest (`runRebuildBackupPhase`, `rebuild-backup-phase.ts:35`, or a validated installer `recoveryManifest`); session rewritten wholesale as the recreate contract with preflight/gateway pre-marked complete and provider/model/credential-env/endpoint pinned (`rebuild-recreate-phase.ts:103-149`); registry snapshot taken for recovery recreates (`rebuild-pipeline.ts:100`). | -| Credential/secret boundary | Credential preflight before any destruction (`rebuild-credential-preflight.ts`); session and registry carry env-var names and redacted endpoints only; the scoped-env facade saves and restores mutation-prone env keys around the whole pipeline (`rebuild-pipeline.ts:40-59`). | -| Retry/compensation/rollback | Recreate runs `onboard()` in-process with `process.exit` intercepted by a sentinel throw (`rebuild-recreate-phase.ts:163-196`). On failure: `markLastStartedStepFailed` (`:201`); registry snapshot restore only for recovery recreates (`:206-217`); backup path preserved and manual `snapshot restore` instructions printed (`:229-239`); MCP registry restore for retry (`:218`); shields relocked (`:242` and the pipeline `finally` at `rebuild-pipeline.ts:231`). On success: restore phase + post-restore phase reapply state, policy presets, and messaging hooks (`rebuild-pipeline.ts:206-229`). | -| Extension assembly points | Messaging plan restaged from manifests; policy presets restored from backup manifest and registry; MCP entries carried through the registry entry; `plugins.entries` merged under the ownership contract `OPENCLAW_CONFIG_RESTORE_OWNERSHIP` (`openclaw-config-merge.ts:17-23`: current generated entries win by id, backup-only user entries kept). | -| Existing tests / known-uncovered failure modes | Tests: `rebuild-flow.test.ts`, `rebuild-resume-config.test.ts`, `rebuild-dcode-flow.test.ts`, `rebuild-messaging-conflict-preflight.test.ts`, `rebuild-env-isolation.test.ts`, `rebuild-resume-snapshot.test.ts`, `rebuild-shields-finally.test.ts`. Uncovered: a plain (non-recovery) recreate failure leaves no registry entry, only a backup and printed instructions; non-DCode rebuilds build the replacement image only after deletion, so a build failure strands the operator on the recovery path. | - -### Journey 3: re-onboard and resume over an existing sandbox - -Two sub-modes share `onboard()`: (a) the live-sandbox block in `createSandbox` (`onboard.ts:2571-2848`), and (b) the `--resume` decision `decideSandboxResume` (`machine/handlers/sandbox-resume.ts:50`: create / reuse / recreate / repair-and-recreate), applied by `machine/handlers/sandbox.ts`. - -| Contract dimension | Current behavior | -|---|---| -| Desired-state source | The current run's env, flags, and prompts. Registry and gateway are only a drift baseline: agent drift (`onboard.ts:2574`), provider migration need (`:2614`), selection drift via live gateway probe (`:2617`), GPU drift (`:2619`), Hermes tool-gateway and dashboard drift (`:2624-2629`), messaging credential rotation (`:2635`). Restore intent (#6130) is keyed on installer env `NEMOCLAW_RESTORE_LATEST_BACKUP_ON_RECREATE=1` (`not-ready-recreate.ts:56`), consumed at `onboard.ts:2564` (`selectPreUpgradeBackupForCreate`) and `onboard.ts:2711` (`resolveNotReadyOutcome`; without the flag a non-interactive not-ready sandbox blocks with hints). | -| Deterministic planning/validation | Messaging conflict guard runs pre-delete (`onboard.ts:2524`), unlike pre-#5954 rebuild. CPU-sandbox-vs-GPU-request reuse guard (`:2655-2666`). Interactive confirm gates for recreate (`:2718-2762`). MCP-managed sandboxes refuse the generic recreate path and are redirected to `rebuild` (`:2804-2812`). Resume conflicts (`getResumeConfigConflicts`, `resume-config.ts:101`: sandbox name only counts if the sandbox step completed, #2753; provider/model hints; `--from` path equality) exit before any effect. Terminal machine snapshots are repaired only per `classifyResumeMachineRepair` (`resume-repair-policy.ts:34`: failed, or inconsistently reopened complete) by `repairResumeMachineSnapshot` (`resume-machine-repair.ts:52`). | -| First externally visible effect | Same as journey 1 (gateway state, provider upserts). On reuse fast paths, messaging providers are upserted without any deletion (`onboard.ts:2677`, `:2735`). | -| First destructive effect | `onboard.ts:2836-2847`: provider pre-delete cleanup, `openshell sandbox delete` (`:2837`), `docker rmi` of the previous image (`:2839`), `registry.removeSandbox` (`:2847`). | -| Checkpoints | `backupSandboxBeforeRecreate` (`onboard.ts:2770` for credential rotation, `:2824` general; `sandbox-backup-on-recreate.ts:25`). Fail-closed: a failed backup aborts the recreate unless `NEMOCLAW_RECREATE_WITHOUT_BACKUP=1`. Skipped when a pre-upgrade backup was already selected or a not-ready recreate is in progress (`:2817-2822`). | -| Credential/secret boundary | Same session redaction rules as journey 1. `migratedLegacyValueHashes` is trusted on resume only entry-by-entry when the sha256 of the currently staged legacy value matches. | -| Retry/compensation/rollback | Workspace restore after create (`onboard.ts:3128-3142`); default-sandbox restoration deferred to post-create (`:3126`, #4614); cancel rollback deliberately not armed for recreates (`:3175` gate). There is no registry snapshot restore on this path; a failed recreate relies on session + backup + `onboard --resume`. | -| Extension assembly points | Policy presets carried forward across recreate (`policyPresetCarry.applyRecreatePolicyCarryForward`, `onboard.ts:2815`); messaging channels re-resolved by `reconcileSandboxMessaging` (`handlers/sandbox-messaging.ts:253-269`) in the order: recorded channels, env plan, registry plan, then `session.messagingPlan`. | -| Existing tests / known-uncovered failure modes | Tests: `session-bootstrap.test.ts`, `resume-machine-repair.test.ts`, `entry-options.test.ts`, `machine/handlers/sandbox-resume.test.ts`, `machine/handlers/sandbox.test.ts`, `not-ready-recreate.test.ts`, `sandbox-backup-on-recreate.test.ts`. Uncovered: resume identity when the sandbox step never completed (session may lack `sandboxName`; #5961/#5783 territory); interrupted-run snapshot shapes outside the two repaired classes (#6040); no pinning of the delete-then-create window (process death there leaves neither sandbox nor registry entry). | - -### Journey 4: runtime mutation - -Four surfaces. The `nemoclaw` OpenClaw plugin's TUI commands are read-only; all mutation is host CLI. - -**4a. Provider/model switch** (`nemoclaw inference set` -> `runInferenceSet`, `src/lib/actions/inference-set.ts:826`, serialized by a timer-bound shields mutation lock at `:838`): - -- Intent: CLI flags plus optional explicit endpoint/credential metadata, merged with registry/session metadata. -- Validation before any write (`runInferenceSetWithoutHostLock`, `:593`): provider allowlist and model-id charset (`:599-605`), registered-agent match, shields-down requirement (`:622`), local-provider reachability (`:651-671`). -- Writes are ordered, layered, forward-only: gateway route (`:674`) -> registry (`:698`) -> registry API-family refresh (`:722`) -> in-sandbox config patch, non-fatal (`:762`; both degraded states are explicitly repaired by `rebuild`, comment at `:755-759`) -> session (`:786`) -> audit entry (`:795`). -- No rollback. Degraded states are reported; `rebuild` is the documented repair. - -**4b. Config change** (`nemoclaw config set` -> `configSet`, `src/lib/sandbox/config.ts:886`): - -- Validation: dotpath validation (`:903`), shields-down (`:914`), `gateway.*` refusal (`:937`), scalar-ancestor/array clobber refusal (`:955`), new-key confirmation gate (`:966`, #2400), SSRF validation with DNS-pinned URL rewrite (`:992`). -- Apply: under the sandbox mutation lock plus the shields transition lock, a re-read plus compare-and-swap on the config's sha256 (`:1004-1023`) then write, hash recompute, and audit (`:1027-1030`). Fail-closed CAS; no compensation needed. - -**4c. Messaging channel add/remove/start/stop** (`src/commands/sandbox/channels/*` -> `src/lib/actions/sandbox/policy-channel.ts`: `addSandboxChannel` `:924`, `removeSandboxChannel` `:1307`, `stopSandboxChannel`/`startSandboxChannel` `:1481`/`:1490` -> `sandboxChannelsSetEnabled` `:1407`): - -- Intent: per-channel delta plans built from the registry entry (`workflow-planner.ts:62-115`: add, stop, start, remove). -- Validation: agent support gate; a hand-rolled mirror of the onboard conflict guard, `checkChannelAddConflict` (`:389`), which uniquely offers `--force`; conflict-detection errors fail closed unless `--force` or an interactive override (`:423-442`); channel pre-enable hooks run next, with hook-registry read failures fail-soft, warn and proceed (`:483-490`). -- Apply: gateway provider upsert/detach, policy preset apply/remove, and registry plan persistence run immediately, but the destructive apply is deferred to a rebuild: `promptAndRebuild` (`:682`) -> `rebuildSandbox(name, ["--yes"])` (`:699`). Non-interactive runs queue the change and print the rebuild command. -- Compensation: `rollbackChannelAdd` (`:1079`) restores prior tokens on preset failure; `channels start` re-disables the plan if its preset fails (`:1463-1472`); QR-channel remove hard-stops before any registry mutation if in-sandbox state cannot be cleared (`:1370-1382`, #3998); session preset mirroring `syncSessionPolicyPresetsWithRegistry` (`:1224`) prevents a later rebuild resume from reverting presets. - -**4d. Plugin entries** (`plugins.entries.*` in agent config): - -- Written as manifest render targets at build/rebuild time (for example `plugins.entries.telegram`, `src/lib/messaging/channels/telegram/manifest.ts:130`) and by the web-search flow. -- Reconciled at rebuild restore by `OPENCLAW_CONFIG_RESTORE_OWNERSHIP` (`openclaw-config-merge.ts:17-23`): `currentGeneratedEntryMaps: ["plugins.entries"]`, so current generated entries win by id, backup-only user entries are kept, and stale web-search entries are never resurrected. -- Direct runtime edits go only through `config set` gates. There is no dedicated plugin CLI; the managed-package CLI is #5998's scope. - -### Agent differences - -- The FSM branches `sandbox -> openclaw` for OpenClaw and `sandbox -> agent_setup` for other agents; both rejoin at `policies`. -- Deep Agents Code (DCode) is the only agent with pre-delete replacement-image validation on rebuild (#6214). It is also excluded from messaging: no channel manifest lists it under `supportedAgents`, and `channels add` rejects it before any mutation (see `src/lib/messaging/AGENTS.md`). -- Hermes adds tool-gateway and dashboard drift axes to the re-onboard drift baseline and its own credential preflight on rebuild. - -## Persisted state and field ownership - -- `~/.nemoclaw/onboard-session.json` is owned by `src/lib/state/onboard-session.ts` and written through `OnboardRuntimeBoundary` during onboard; the rebuild pipeline rewrites it wholesale as the recreate contract (`rebuild-recreate-phase.ts:103`). Step helpers default to record-only (`RECORD_ONLY_STEP_MUTATION_OPTIONS`, `src/lib/state/onboard-step-mutation.ts:19`); `LEGACY_MACHINE_STEP_MUTATION_OPTIONS` (`:15`) remains the escape hatch that also moves the machine snapshot, used by the exit backstop and rebuild. -- The sandbox registry is owned by `src/lib/state/registry.ts`; the machine snapshot `{version, state, stateEnteredAt, revision}` is owned by `OnboardRuntime`. -- Known ambiguity (pinned, not endorsed): `null` is overloaded across several session fields to mean unset, declined, or explicitly cleared. Explicit-clear semantics exist only for the whitelisted updates in `filterSafeUpdates` (the #2625 null-vs-undefined contract in `onboard-session.ts`). Modeling `unset`/`declined`/`known value` explicitly is #6228's mandate; sandbox-identity nullability is tracked by #5783/PR #5860. - -## Create path sequence - -```mermaid -sequenceDiagram - autonumber - participant Op as Operator - participant On as onboard() (src/lib/onboard.ts) - participant FSM as Machine slices (machine/*) - participant GW as OpenShell gateway - participant CS as createSandbox (onboard.ts:2465) - participant Plan as sandbox-create-plan.ts - participant St as Session + registry (src/lib/state) - - Op->>On: nemoclaw onboard (flags, env, prompts) - On->>On: resolveOnboardEntryOptions, acquire onboard lock - On->>St: prepareOnboardSession (create or repair snapshot) - On->>FSM: record init to preflight (onboard.ts:4771) - FSM->>FSM: preflight state, host/GPU/CDI/DNS validation (data-only) - FSM->>GW: gateway state, reuse / recover / start gateway - Note over FSM,GW: first externally visible effect - FSM->>GW: provider_selection / inference, provider credential upserts - Note over FSM,GW: gateway writes before any sandbox exists - FSM->>CS: sandbox state - CS->>CS: prepareSandboxMessagingPreflight incl. conflict guard (2524) - CS->>CS: drift detection, reuse fast paths, confirm gates - CS->>St: backupSandboxBeforeRecreate (2770 / 2824, fail closed) - rect rgb(250, 225, 225) - Note over CS,St: destructive boundary (re-onboard only) - CS->>GW: provider pre-delete cleanup + sandbox delete (2836-2837) - CS->>CS: docker rmi previous image (2839) - CS->>St: registry.removeSandbox (2847) - end - CS->>Plan: prepareSandboxCreatePlan (2880) - Plan->>Plan: resolveSandboxCreateIntent, pure (228) - Plan->>GW: materializeSandboxCreatePlan, bind tokens + upsert messaging providers (372) - CS->>GW: streamSandboxCreate (2968) - CS->>CS: readiness wait (3032), on failure delete new sandbox (3052) and exit - CS->>St: registerCreatedSandbox only after ready (3108) - CS->>St: restore pending workspace backup (3128) - FSM->>FSM: openclaw or agent_setup, policies, finalizing, post_verify - FSM->>St: completeSession (terminal checkpoint) -``` - -Current-ordering facts this diagram pins (do not "fix" silently; they are #6226/#6228 targets): - -1. Gateway credential writes (inference providers, then messaging providers) precede sandbox existence and, on the recreate path, follow the deletion of the old sandbox. -2. `resolveSandboxCreateIntent` runs inside `prepareSandboxCreatePlan` at `onboard.ts:2880`, after the destructive boundary at `onboard.ts:2837`, not before it. -3. Registry registration is post-ready only; there is no durable record of the selected sandbox identity before the long-running create stream starts. - -## Duplicated decision points (divergences) and recommended owners - -Recommended owners name where a single decision should live. No refactor is implied here; alignment work belongs to the referenced child issues. - -1. **Messaging desired state has four sources by path.** First onboard compiles the plan from current selections and transports it via `NEMOCLAW_MESSAGING_PLAN_B64` (`MessagingSetupApplier.writePlanToEnv`, `applier/setup-applier.ts:45`); rebuild restages from the registry entry plan (`buildRebuildPlanFromSandboxEntry`, `workflow-planner.ts:116`); resume reuse resolves recorded channels, then env plan, then registry plan, then `session.messagingPlan` (`handlers/sandbox-messaging.ts:253-269`); channel mutations build single-channel deltas (`workflow-planner.ts:62-115`). Drift among env/session/registry yields different recreated states per path. Recommended owner: the registry-persisted plan via `MessagingHostStateApplier`, with env and session copies demoted to transport/cache; alignment via #6226 and #6228. -2. **Ambient env polarity is inverted between paths.** Onboard/re-onboard treat `NEMOCLAW_PROVIDER`/`MODEL`/`ENDPOINT_URL` as authoritative intent; rebuild quarantines exactly those (`isolateAmbientRecreateEnv`, `rebuild-env-isolation.ts:116`) and pins intent from registry + matching session (`prepareRebuildResumeConfig`, `rebuild-resume-config.ts:224`, #5735). The same environment produces opposite outcomes depending on the path. Recommended owner: one target-resolution module that decides when ambient env is intent versus contamination; alignment via #6226. -3. **One conflict-guard engine, three wirings with divergent semantics.** Onboard: `enforceMessagingChannelConflicts` (`messaging-conflict-guard.ts:65`) with an interactive "continue anyway" path. Rebuild: `preflightRebuildMessagingConflicts` (`rebuild-messaging-conflict-preflight.ts:49`, #5954) forcing non-interactive abort. `channels add`: the hand-rolled mirror `checkChannelAddConflict` (`policy-channel.ts:389`) uniquely offers `--force`; detection errors fail closed unless forced or interactively overridden (`:423-442`), while pre-enable hook registry-read failures remain fail-soft (`:483-490`). Recommended owner: `messaging-conflict-guard.ts` as the sole engine, taking per-path policy (interactive / abort / force) declaratively. -4. **Backup/restore intent differs per path.** Rebuild always backs up and auto-restores, including policy presets (`rebuild-backup-phase.ts`, `rebuild-pipeline.ts:206-229`); re-onboard backs up fail-closed but restores only workspace state (presets travel via carry-forward, `onboard.ts:2815`); the non-interactive not-ready path restores only under the installer flag (#6130, `not-ready-recreate.ts:56`); channel mutations create no checkpoint of their own and lean on the next rebuild's backup. Recommended owner: one backup/restore policy module consumed by both `createSandbox` and the rebuild pipeline; durable semantics belong to #6228. -5. **Registry lifecycle asymmetry.** Create registers only post-ready (`registerCreatedSandbox`, `onboard.ts:3108`); rebuild removes the entry at the destroy phase (`rebuild-destroy-phase.ts:113`, retained only for MCP-bearing entries) and restores a snapshot only for recovery recreates (`rebuild-recreate-phase.ts:206-217`); re-onboard recreate removes at `onboard.ts:2847` with no snapshot restore at all. A plain failed recreate leaves no registry entry on either path. Recommended owner: `sandbox-registration.ts` as the registration contract; durable pre-create identity belongs to #6228. -6. **Pre-delete replacement validation exists only for DCode rebuilds** (#6214): image prebuilt and fingerprinted (`rebuild-dcode-preflight.ts:354`) and revalidated at the mutation edge (`:415`). Non-DCode rebuilds validate base image, credentials, and runtime pre-delete but build the real image after deletion; onboard/re-onboard build entirely post-delete. Recommended owner: the `rebuild-dcode-orchestrator` pattern as the documented precedent; full same-name build-verify-swap atomicity is #5801's scope, explicitly outside this epic. -7. **Policy-preset reconciliation exists only on rebuild.** The restore/post-restore phases reapply presets and reconcile the registry; onboard writes `appliedPolicies` once at registration (`onboard.ts:3115`); channel commands mutate presets one at a time and mirror them into the session (`syncSessionPolicyPresetsWithRegistry`, `policy-channel.ts:1224`) specifically so a later rebuild resume does not revert them. The paths reconverge only via ad-hoc mirrors. Recommended owner: the `policy-preset-persistence`/`policy-preset-sync` modules as the single reconciliation point. - -## Bug to contract-gap map - -| Issue | Symptom | Contract gap | Status | -|---|---|---|---| -| #5961 | Interrupted non-interactive onboard cannot resume safely | Checkpoint gap: whole-step session with no durable sandbox identity or effect-group metadata before the interruptible create step, so resume cannot distinguish never-started, in-flight, and created | Open; targeted by #6227/#6228 | -| #6040 | `onboard --resume` aborts on macOS/DGX Spark | Recovery gap: only `failed` and inconsistently-reopened-`complete` snapshots are repaired (`classifyResumeMachineRepair`, `resume-repair-policy.ts:34`); other interrupted snapshot shapes have no explicit recovery transition | Open; targeted by #6227 | -| #6179 | Invalid FSM transition attempted after successful sandbox creation | Transition-graph gap: handlers can emit results whose source state no longer matches; stale results are skipped by `recordStateResultWithStepCompatibility` (`runtime-boundary.ts:204`, reasons `already_at_target`/`source_state_mismatch`) instead of being rejected or recomputed under an enforced legal-transition rule | Open; targeted by #6227 | -| #5954 | Rebuild detected a messaging credential conflict only after destroying the sandbox | Plan-before-effects gap in rebuild preflight ordering | Fixed by PR #5955 (`9e583ed47`); the guard now runs at `rebuild-preflight-target-phase.ts:90`, before every destructive phase | -| #6099 | Healthy sandbox rolled back after a late dashboard-forward failure | Compensation-scope gap: post-ready, non-destructive failures sit inside a destructive rollback window (`ensureDashboardForward(..., { rollbackSandboxOnFailure: true })`, `onboard.ts:3092`) | Open; in-flight PR #6116 (`forward-start.ts`) | -| #6195 | Rebuild deleted a DCode sandbox before validating that recreation could succeed | Plan-before-effects gap at rebuild's destructive boundary | Fixed by PR #6214 (`2c4bf1944`); see divergence 6 | - -## Recently addressed by #6218 and #6214 - -- **PR #6218** (`2a68fbc7e`, merged 2026-07-03) separated the deterministic, serializable, secret-free `SandboxCreateIntent` (`resolveSandboxCreateIntent`, `sandbox-create-plan.ts:228`) from effectful materialization (`materializeSandboxCreatePlan`, `:334`), kept the `prepareSandboxCreatePlan` compatibility surface (`:400`), and extended the characterization coverage in `sandbox-create-plan.test.ts`. It deliberately did **not** move intent resolution ahead of the destructive boundary (still invoked at `onboard.ts:2880`, after the delete at `:2837`), did not persist intent, and did not define a machine-event or public contract. Those are exactly #6226, #6228, and #6229. -- **PR #6214** (`2c4bf1944`, merged 2026-07-03) made DCode rebuilds prepare, fingerprint, and mutation-edge-revalidate the replacement before deletion (`rebuild-dcode-preflight.ts:354`, `:415`), closing #6195's ordering gap for DCode. Non-DCode rebuild ordering is unchanged. -- **PR #5955** (`9e583ed47`, merged 2026-07-03) moved the rebuild messaging conflict check before destruction, closing #5954. - -## In-flight work - -Do not treat recovery and resume semantics in this package as frozen: - -- **PR #6253** (open) is the recovery-path refactor toward #6227. The recovery/resume surface (`resume-machine-repair.ts`, `session-bootstrap.ts`, `machine/transitions.ts`, `exit-step-failure.ts`, and neighbors) is claimed by open PRs in this area; coordinate before touching those files. -- **PR #6116** (open) reworks the dashboard-forward rollback scope for #6099 (`forward-start.ts`). -- **PR #5860** (open) addresses null sandbox identity and coarse checkpoints for #5783. - -## Characterization tests - -The machine event/transition traces for fresh, resume, recreate, success, and failure paths are pinned by `machine/transition-traces.test.ts` (see the "Characterization traces" section of `machine/README.md`). Together with the per-journey tests listed in the matrix above, they form the regression baseline for #6225: they assert current behavior, including orderings this document flags as gaps. When #6226/#6227/#6228 intentionally change an ordering, update the pinned trace in the same PR and reference the child issue in the test title. diff --git a/src/lib/onboard/README.md b/src/lib/onboard/README.md index 407498f67b4..821688d6803 100644 --- a/src/lib/onboard/README.md +++ b/src/lib/onboard/README.md @@ -5,6 +5,8 @@ `src/lib/onboard` is the transitional home for onboarding support modules while the large legacy `src/lib/onboard.ts` flow is split over time. +The lifecycle contract map for the onboarding and runtime-mutation journeys (desired-state sources, destructive boundaries, checkpoints, divergences) lives in [`lifecycle-contracts.md`](lifecycle-contracts.md) (#6225). + Good candidates: ```text diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md new file mode 100644 index 00000000000..9329ceb3557 --- /dev/null +++ b/src/lib/onboard/lifecycle-contracts.md @@ -0,0 +1,92 @@ + + + +# Onboarding lifecycle contract map (#6225, epic #6224) + +Characterization map of the onboarding and runtime-mutation journeys: where desired state comes from, what is validated before effects, where the first visible and first destructive effects happen, what is checkpointed, where the credential boundary sits, and what compensation exists today. It records current behavior, including behavior the epic flags as a contract gap; nothing here is a target design — targets live in #6226/#6227/#6228 and `machine/README.md`. References are stable symbol + module names, never line numbers. + +Companions: `README.md` (file placement for the `onboard.ts` split), `machine/README.md` (FSM architecture and handler contract), `src/lib/messaging/AGENTS.md` (the messaging package these journeys cross into). + +## Vocabulary + +Epic terminology (from #6224, use verbatim): a **lifecycle contribution** is an internal, data-first input to a plan (policy, provider, package, port-forward, resource, runtime setup), not a public SDK. A **managed agent package** is a package recorded as desired state for an agent runtime; the user-facing managed OpenClaw package lifecycle is #5998's scope, not this epic's. An **agent-native plugin** is interpreted by OpenClaw/Hermes/another agent runtime. **NemoClaw plugin SDK** is reserved for a future versioned external contract that must not be claimed before the #6229 decision record. + +| Verb | Meaning | Current artifact | +|---|---|---| +| intent | Deterministic, serializable desired outcome recorded before any effect; logical bindings (env-var names, presence flags), never secret values, temp paths, or handles | `SandboxCreateIntent` (`sandbox-create-intent-types.ts`), produced by the pure `resolveSandboxCreateIntent` (`sandbox-create-plan.ts`) | +| plan | Intent plus observed state, ready to execute; serializable (`SandboxMessagingPlan`) or execution-bound (temp paths, callbacks) | `MessagingWorkflowPlanner.buildPlan` (`src/lib/messaging/compiler/workflow-planner.ts`); `materializeSandboxCreatePlan` (`sandbox-create-plan.ts`) | +| apply | The effectful phase; capabilities (credential values, live handles) bound at apply time, never stored in intent or checkpoints | `bindMessagingTokenDefs` (`sandbox-create-plan.ts`) rebinds real tokens at materialization and fails on drift | +| checkpoint | Durable, secret-free record a later run can resume from | Onboard session (`~/.nemoclaw/onboard-session.json`, `src/lib/state/onboard-session.ts`) + machine snapshot; pre-recreate workspace backups; rebuild backup manifest | +| result | Explicit handler outcome: advance, retry, branch, complete, failed | `OnboardStateResult` (`machine/result.ts`), applied via `OnboardRuntime.applyResult` and the `OnboardRuntimeBoundary` facade (`runtime-boundary.ts`) | +| compensation | Effects after failure/cancel that undo a partial journey | Failed-create sandbox deletion in `createSandbox`; `cancel-rollback.ts`; `rollbackChannelAdd` (`src/lib/actions/sandbox/policy-channel.ts`); rebuild recovery-registry restore (`rebuild-recreate-phase.ts`) | +| reconcile | Re-aligning recorded and live state without a full re-run | Drift detection in `createSandbox`; `reconcileSandboxMessaging` (`machine/handlers/sandbox-messaging.ts`); `mergeOpenClawRestoredConfig` (`src/lib/state/openclaw-config-merge.ts`) | + +## Machine states + +13 states (`machine/definition.ts`); the transition table (`machine/transitions.ts`) is the linear advance chain plus the `inference -> provider_selection` retry, the `sandbox -> openclaw | agent_setup` branch, and every non-terminal state `-> failed`. One production owner per non-terminal state: `machine/handlers/preflight.ts`, `gateway.ts`, `provider-inference.ts` (composite for `provider_selection` + `inference`), `sandbox.ts` (resume decision in `sandbox-resume.ts`, messaging reconciliation in `sandbox-messaging.ts`), `agent-setup.ts` (`openclaw` + `agent_setup`), `policies.ts`, `finalization.ts` (`finalizing` + `post_verify`). `init` is advanced by `onboard()` before the first slice; `complete`/`failed` are terminal. The FSM is deliberately step-granular (`machine/types.ts`): mid-operation resume inside gateway startup, sandbox creation, credential upserts, or policy application is out of scope — the root of several checkpoint gaps below. + +## Journey contracts + +| Journey | Entry point | Desired-state source | First destructive effect | Durable checkpoint | +|---|---|---|---|---| +| 1. Sandbox create (fresh onboard) | `onboard()` (`src/lib/onboard.ts`) | Flags + env + prompts of the current run | None against prior state; creation itself at `streamSandboxCreate` | Whole-step session + machine snapshot | +| 2. Rebuild / installer upgrade | `rebuildSandbox` (`rebuild-pipeline.ts` via the `rebuild.ts` facade) | Registry entry + matching session only; ambient env quarantined | `openshell sandbox delete` (`rebuild-destroy-phase.ts`) | Backup manifest + session rewritten as recreate contract + recovery registry snapshot | +| 3. Re-onboard / resume over existing sandbox | Same `onboard()`, live-sandbox block of `createSandbox` | Current run's env/flags/prompts; registry + gateway as drift baseline | Delete + `docker rmi` + registry removal inside `createSandbox` | Pre-recreate workspace backup + session | +| 4. Runtime mutation (provider switch, config set, channels, plugin entries) | `inference-set.ts`, `sandbox/config.ts`, `policy-channel.ts` | CLI flags + registry/session metadata; per-channel delta plans | None in-place; channel changes defer destruction to a queued rebuild | Audit entries + registry plan persistence | + +**Journey 1 — fresh create.** Options resolved by `resolveOnboardEntryOptions` (`entry-options.ts`, auto-resumes an in-progress session); messaging plan compiled by `MessagingWorkflowPlanner.buildPlan` and transported via env `NEMOCLAW_MESSAGING_PLAN_B64` (`MessagingSetupApplier.writePlanToEnv`, `applier/setup-applier.ts`). First externally visible effect: gateway reuse/recover/start (`startGateway`); inference-provider credential upserts (`upsertProvider`) run in `provider_selection`/`inference`, before any sandbox exists. Messaging-provider upserts run with `replaceExisting: true` inside `materializeSandboxCreatePlan`, overwriting same-name entries in shared gateway state. Checkpoints: whole-step session (8 fixed steps, atomic tmp+rename save) plus machine snapshot via `OnboardRuntimeBoundary`; registry registration deferred to post-ready (`registerCreatedSandbox`, `sandbox-registration.ts`) to prevent phantom entries; no sub-step checkpoint. Credential boundary: session stores `credentialEnv` as a name only, redacts `endpointUrl` at save, keeps legacy credential migration as sha256 hashes; intent carries presence flags and env keys, never values; real tokens rebound at apply by `bindMessagingTokenDefs`, fail-closed on availability or provider-type drift. Compensation: readiness failure deletes the failed new sandbox; build-context temp dirs (which can hold env-arg API keys) are cleaned inline with a process-exit safety net; two-key cancel rollback is armed only for a brand-new sandbox and clears the session when it fires (`cancel-rollback.ts`); nonzero exit marks the last started step failed (`exit-step-failure.ts`). Known gap: process death between gateway provider upserts and sandbox create leaves gateway credential state changed with no sandbox. Non-interactive runs share this contract, substituting env defaults and hard aborts (`non-interactive-abort.ts`) for prompts. + +**Journey 2 — rebuild, including installer upgrade** (`upgradeSandboxes` in `src/lib/actions/upgrade-sandboxes.ts` calls `rebuildSandbox(name, ["--yes"], { recoveryManifest, ... })`). Desired state comes from the registry entry + matching session only (`prepareRebuildResumeConfig`, `rebuild-resume-config.ts` — the #5735 pre-delete trust boundary; custom-endpoint URLs fail closed if recorded only in another sandbox's session); ambient `NEMOCLAW_*` selection env is quarantined by `isolateAmbientRecreateEnv` (`rebuild-env-isolation.ts`); messaging is restaged from the registry-persisted plan (`stageRebuildMessagingPlanOrBail` in `rebuild-messaging-phase.ts` -> `buildRebuildPlanFromSandboxEntry` in `workflow-planner.ts`). All validation precedes destruction: `runRebuildPreflightPhase` (`rebuild-preflight-phase.ts`: registry snapshot pinned and re-asserted after confirmation, gateway schema, recovery-manifest validation, confirmation, onboard lock), then `prepareRebuildTargetPreflights` (`rebuild-preflight-target-phase.ts`: target config, recreate options, messaging plan staging, then the #5954 conflict preflight `preflightRebuildMessagingConflicts` with forced non-interactive abort, runtime and base-image checks). DCode rebuilds additionally prebuild and fingerprint the replacement image pre-delete (#6214, `prepareDcodeReplacementBeforeMutation` in `rebuild-dcode-preflight.ts`); mutation-edge revalidation runs immediately before deletion (`revalidatePreparedRecoveryBeforeDelete` in `rebuild-pipeline.ts`; `revalidateDcodeReplacementAtMutationEdge`). First destructive effect: `openshell sandbox delete` in the destroy phase (`rebuild-destroy-phase.ts`), then registry entry removal (entry kept when MCP entries exist, as the durable MCP rebuild transaction). Checkpoints: workspace backup manifest (`runRebuildBackupPhase`, `rebuild-backup-phase.ts`, or a validated installer manifest); session rewritten wholesale as the recreate contract with preflight/gateway pre-marked complete (`rebuild-recreate-phase.ts`); registry snapshot for recovery recreates. On a failed recreate: `markLastStartedStepFailed`, registry-snapshot restore for recovery recreates only, backup path preserved with manual `snapshot restore` instructions, MCP registry restore, shields relocked in the pipeline `finally`. Known gaps: a plain (non-recovery) recreate failure leaves no registry entry; non-DCode rebuilds build the replacement image only after deletion. + +**Journey 3 — re-onboard / resume.** Two sub-modes share `onboard()`: the live-sandbox block of `createSandbox`, and the `--resume` decision `decideSandboxResume` (`machine/handlers/sandbox-resume.ts`: create / reuse / recreate / repair-and-recreate). Desired state is the current run's env/flags/prompts; registry and gateway are only a drift baseline (agent, provider migration, live-probe selection, GPU, Hermes tool-gateway and dashboard, messaging credential rotation). Restore intent (#6130) is keyed on installer env `NEMOCLAW_RESTORE_LATEST_BACKUP_ON_RECREATE=1` (`selectPreUpgradeBackupForCreate` / `resolveNotReadyOutcome`, `not-ready-recreate.ts`); without it a non-interactive not-ready sandbox blocks with hints. Pre-delete validation: the messaging conflict guard, a CPU-sandbox-vs-GPU-request reuse guard, interactive confirm gates, redirection of MCP-managed sandboxes to `rebuild`, and resume conflicts (`getResumeConfigConflicts`, `resume-config.ts` — the recorded sandbox name counts only when the sandbox step completed, #2753) which exit before any effect. Terminal machine snapshots are repaired only per `classifyResumeMachineRepair` (`resume-repair-policy.ts`: failed, or inconsistently reopened complete) by `repairResumeMachineSnapshot` (`resume-machine-repair.ts`). Checkpoint: fail-closed `backupSandboxBeforeRecreate` (`sandbox-backup-on-recreate.ts`; a failed backup aborts unless `NEMOCLAW_RECREATE_WITHOUT_BACKUP=1`; skipped when a pre-upgrade backup is already selected or a not-ready recreate is in progress). Compensation: workspace restore after create; default-sandbox restoration deferred to post-create (#4614); cancel rollback deliberately not armed for recreates; no registry snapshot restore — a failed recreate relies on session + backup + `onboard --resume`. Known gaps: resume identity when the sandbox step never completed (#5961/#5783); interrupted snapshot shapes outside the two repaired classes (#6040); the delete-then-create window below. + +**Journey 4 — runtime mutation.** All mutation is host CLI; the `nemoclaw` OpenClaw plugin TUI is read-only. (4a) Provider/model switch: `runInferenceSet` (`src/lib/actions/inference-set.ts`), serialized by a timer-bound shields mutation lock; validates provider allowlist, model-id charset, registered-agent match, shields-down, and local-provider reachability before any write; writes are ordered and forward-only — gateway route -> registry -> API-family refresh -> in-sandbox config patch (non-fatal) -> session -> audit; no rollback, `rebuild` is the documented repair for degraded states. (4b) Config change: `configSet` (`src/lib/sandbox/config.ts`); dotpath validation, shields-down, `gateway.*` refusal, scalar-ancestor/array clobber refusal, new-key confirmation (#2400), and SSRF validation with DNS-pinned rewrite, then a sha256 compare-and-swap write under the sandbox mutation + shields locks; fail-closed CAS, no compensation needed. (4c) Channels add/remove/start/stop (`addSandboxChannel`, `removeSandboxChannel`, `sandboxChannelsSetEnabled` in `policy-channel.ts`): per-channel delta plans from the registry entry (`workflow-planner.ts`); `checkChannelAddConflict` is a hand-rolled mirror of the onboard conflict guard that uniquely offers `--force` (detection errors fail closed unless forced; pre-enable hook registry-read failures fail soft); gateway upsert/detach, preset apply, and registry plan persistence run immediately but destructive apply is deferred to a queued rebuild (`promptAndRebuild`); compensation via `rollbackChannelAdd`, re-disable on a failed `channels start` preset, a QR-channel remove hard-stop before registry mutation (#3998), and `syncSessionPolicyPresetsWithRegistry` so a later rebuild resume does not revert presets. (4d) Plugin entries (`plugins.entries.*`): written by manifest render targets and the web-search flow at build/rebuild; reconciled at restore by `OPENCLAW_CONFIG_RESTORE_OWNERSHIP` (`openclaw-config-merge.ts`: current generated entries win by id, backup-only user entries kept); direct edits go only through `config set` gates; no plugin CLI (#5998's scope). + +**Agent differences.** The FSM branches `sandbox -> openclaw` for OpenClaw and `sandbox -> agent_setup` for other agents; both rejoin at `policies`. DCode is the only agent with pre-delete replacement-image validation on rebuild (#6214) and is excluded from messaging (no channel manifest supports it; `channels add` rejects it pre-mutation). Hermes adds tool-gateway and dashboard drift axes plus its own rebuild credential preflight. + +## Create-path ordering contract + +Inside `createSandbox` (`src/lib/onboard.ts`), on the shared create/recreate path. This prose is the authoritative record of the ordering; per cv review of PR #6259 it deliberately has no source-scanning test — executable coverage belongs to the issue that introduces a behavioral seam (#6226/#6228). + +1. **Validation order (all deterministic work before any destructive effect):** `validateName` fixes the sandbox name; `prepareSandboxMessagingPreflight` (`sandbox-messaging-preflight.ts`) resolves disabled channels, runs the shared conflict guard `enforceMessagingChannelConflicts` (`messaging-conflict-guard.ts`) against the env plan (only when that plan names this sandbox) with the onboard-specific interactive "Continue anyway?" wiring, and aborts when a selected web-search credential is missing from the process; drift detection, reuse fast paths (which return before the destructive boundary — a reused sandbox is never deleted), and interactive confirm gates follow; then `selectPreUpgradeBackupForCreate` (`not-ready-recreate.ts`) and the fail-closed `backupSandboxBeforeRecreate` (`sandbox-backup-on-recreate.ts`). +2. **Conflict guard before delete:** the messaging conflict guard is the #5954 contract on this path — it completes before the destructive boundary, unlike pre-#5955 rebuild. +3. **Destructive boundary (recreate only), strictly ordered:** `runSandboxProviderPreDeleteCleanup` -> `openshell sandbox delete` -> `docker rmi` of the previous image -> `registry.removeSandbox`. +4. **Cleanup before upsert, post-delete:** `prepareSandboxCreatePlan` (`sandbox-create-plan.ts`) runs after the delete, so the pure `resolveSandboxCreateIntent` and the fail-closed credential-binding check in `materializeSandboxCreatePlan` (`bindMessagingTokenDefs`) validate only after the old sandbox is gone — a binding drift halts all gateway writes but cannot restore the sandbox (pinned gap, #6226). Inside materialization the tolerant provider-cleanup re-run (`tolerateMissingSandbox: true`; the sandbox no longer exists) precedes the gateway messaging upsert (`replaceExisting: true`). Then `streamSandboxCreate`, the readiness gate (`waitForCreatedSandboxReadyWithTrace`; failure deletes the new sandbox — the only other delete call site — and exits with retry hints), post-ready `registerCreatedSandbox`, and the pending workspace-backup restore. +5. **Delete-then-create window:** between `registry.removeSandbox` and post-ready `registerCreatedSandbox` there is no durable record of the selected sandbox identity; process death in this window leaves neither a sandbox nor a registry entry (checkpoint gap; #6228). + +## Persisted state and field ownership + +`~/.nemoclaw/onboard-session.json` is owned by `src/lib/state/onboard-session.ts` and written through `OnboardRuntimeBoundary` during onboard; rebuild rewrites it wholesale as the recreate contract. Step helpers default to record-only (`RECORD_ONLY_STEP_MUTATION_OPTIONS`, `src/lib/state/onboard-step-mutation.ts`); `LEGACY_MACHINE_STEP_MUTATION_OPTIONS` remains the escape hatch that also moves the machine snapshot (exit backstop, rebuild). The registry is owned by `src/lib/state/registry.ts`; the machine snapshot `{version, state, stateEnteredAt, revision}` by `OnboardRuntime`. Pinned ambiguity, not endorsed: `null` is overloaded across session fields (unset vs declined vs cleared); explicit-clear semantics exist only for the `filterSafeUpdates` whitelist (the #2625 null-vs-undefined contract in `onboard-session.ts`); explicit modeling is #6228's mandate, sandbox-identity nullability is #5783/PR #5860. + +## Divergences (duplicated decision points) + +Recommended owners name where a single decision should live; alignment belongs to the referenced child issues. + +1. **Messaging desired state has four sources by path** — onboard env plan (`MessagingSetupApplier.writePlanToEnv`), rebuild registry plan (`buildRebuildPlanFromSandboxEntry`), resume-reuse fallback chain in `reconcileSandboxMessaging` (recorded channels -> env plan -> registry plan -> `session.messagingPlan`), single-channel deltas for mutations; owner: the registry-persisted plan (#6226/#6228). +2. **Ambient env polarity is inverted** — onboard treats `NEMOCLAW_PROVIDER`/`MODEL`/`ENDPOINT_URL` as intent; rebuild quarantines exactly those (`isolateAmbientRecreateEnv`) and pins intent from registry + session (`prepareRebuildResumeConfig`, #5735); owner: one target-resolution module (#6226). +3. **One conflict-guard engine, three wirings** — onboard interactive continue (`enforceMessagingChannelConflicts`), rebuild forced non-interactive abort (`preflightRebuildMessagingConflicts`, #5954), channels' hand-rolled `checkChannelAddConflict` with `--force`; owner: `messaging-conflict-guard.ts` taking per-path policy declaratively. +4. **Backup/restore intent differs per path** — rebuild always backs up and auto-restores including presets; re-onboard backs up fail-closed but restores only workspace state; the not-ready path restores only under the installer flag (#6130); channel mutations checkpoint nothing; owner: one backup/restore policy module (#6228). +5. **Registry lifecycle asymmetry** — create registers post-ready only; rebuild removes at destroy and snapshot-restores only for recovery recreates; re-onboard removes with no snapshot restore; owner: `sandbox-registration.ts`; durable pre-create identity is #6228. +6. **Pre-delete replacement validation exists only for DCode rebuilds** (#6214, `rebuild-dcode-preflight.ts`); non-DCode rebuilds build the real image after deletion, onboard/re-onboard entirely post-delete; full build-verify-swap atomicity is #5801's scope, outside this epic. +7. **Policy-preset reconciliation exists only on rebuild** — onboard writes `appliedPolicies` once at registration; channel commands mirror presets via `syncSessionPolicyPresetsWithRegistry`; owner: the `policy-preset-persistence`/`policy-preset-sync` modules. + +## Bug to contract-gap map + +| Issue | Symptom | Contract gap | Status | +|---|---|---|---| +| #5961 | Interrupted non-interactive onboard cannot resume safely | Checkpoint gap: no durable sandbox identity or effect-group metadata before the interruptible create step | Open; targeted by #6227/#6228 | +| #6040 | `onboard --resume` aborts on macOS/DGX Spark | Recovery gap: only `failed` and inconsistently-reopened-`complete` snapshots are repaired (`classifyResumeMachineRepair`) | Open; targeted by #6227 | +| #6179 | Invalid FSM transition attempted after successful sandbox creation | Transition-graph gap: stale handler results are skipped by `recordStateResultWithStepCompatibility` (`runtime-boundary.ts`) instead of rejected or recomputed | Open; targeted by #6227 | +| #5954 | Rebuild detected a messaging credential conflict only after destroying the sandbox | Plan-before-effects gap in rebuild preflight ordering | Fixed by PR #5955; guard now runs in `rebuild-preflight-target-phase.ts`, before every destructive phase | +| #6099 | Healthy sandbox rolled back after a late dashboard-forward failure | Compensation-scope gap: post-ready, non-destructive failures sit inside a destructive rollback window (`ensureDashboardForward` with `rollbackSandboxOnFailure`) | Open; in-flight PR #6116 (`forward-start.ts`) | +| #6195 | Rebuild deleted a DCode sandbox before validating that recreation could succeed | Plan-before-effects gap at rebuild's destructive boundary | Fixed by PR #6214; see divergence 6 | + +## Merged and in-flight work + +- **PR #6218** (merged) separated the secret-free `SandboxCreateIntent` from effectful materialization and kept the `prepareSandboxCreatePlan` compatibility surface; it deliberately did not move intent resolution ahead of the destructive boundary, persist intent, or define a machine-event/public contract — those are #6226, #6228, #6229. +- **PR #6214** (merged) added DCode pre-delete replacement validation (#6195); **PR #5955** (merged) moved the rebuild messaging conflict check before destruction (#5954). +- In flight — do not treat recovery/resume semantics as frozen: **PR #6253** (recovery-path refactor toward #6227; coordinate before touching `resume-machine-repair.ts`, `session-bootstrap.ts`, `machine/transitions.ts`, `exit-step-failure.ts`), **PR #6116** (dashboard-forward rollback scope, #6099), **PR #5860** (null sandbox identity, #5783). + +## Characterization tests + +Path-level machine transition traces are pinned by `machine/transition-traces.test.ts` (see the "Characterization traces" section of `machine/README.md`). They assert current behavior, including orderings this document flags as gaps; when #6226/#6227/#6228 intentionally change an ordering, update the pinned trace in the same PR and reference the child issue in the test title. diff --git a/src/lib/onboard/machine/README.md b/src/lib/onboard/machine/README.md index 4cf3d8e4f2e..c2fcd0d8bae 100644 --- a/src/lib/onboard/machine/README.md +++ b/src/lib/onboard/machine/README.md @@ -122,4 +122,4 @@ The FSM migration is considered complete when: ## Characterization traces -`transition-traces.test.ts` in this directory pins the machine event and transition traces for the fresh, resume, recreate, success, and failure paths as they behave today (#6225). Those traces are a regression baseline: update them deliberately, in the same PR as an intentional behavior change (for example #6226, #6227, or #6228), never as a side effect. The journey-level lifecycle contract map, shared vocabulary, and destructive-boundary inventory live in `../AGENTS.md` (`src/lib/onboard/AGENTS.md`). +`transition-traces.test.ts` in this directory pins a small set of path-level machine traces that the unit suites (`transitions.test.ts`, `runtime.test.ts`, `runner.test.ts`) do not already cover (#6225). Update a pinned trace only in the same PR as an intentional behavior change (for example #6226, #6227, or #6228), never as a side effect. The journey-level lifecycle contract map lives in [`../lifecycle-contracts.md`](../lifecycle-contracts.md). diff --git a/src/lib/onboard/machine/transition-traces.test.ts b/src/lib/onboard/machine/transition-traces.test.ts index 7359e4f0f32..7cbc3193c9b 100644 --- a/src/lib/onboard/machine/transition-traces.test.ts +++ b/src/lib/onboard/machine/transition-traces.test.ts @@ -2,22 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 /** - * Characterization traces for the onboarding machine (#6225). - * - * These tests pin CURRENT behavior on main as a regression baseline for the - * lifecycle-contract mapping in epic #6224. They are descriptive, not - * aspirational: when a pinned ordering changes intentionally, update the pin - * in the same PR that changes the behavior. - * - * Deliberately OUT of scope here: the recovery-path semantics that open PR - * #6253 is rewriting. This file does not pin the legality of transitions - * leaving the terminal `failed` state (for example `failed -> ` - * repair edges) and does not pin the legacy step-mutation compatibility - * bridge (`LEGACY_MACHINE_STEP_MUTATION_OPTIONS` or the runtime-boundary - * stale-result skip rules) — #6253 pins those in its own tests. The exact - * full-table equality pin also stays in `transitions.test.ts`; this file - * asserts the canonical edges positively so additive recovery edges do not - * invalidate the trace baseline. + * Path-level characterization traces for the onboarding machine (#6225): the + * ORDERED event streams a runner-driven pass emits — coverage the unit suites + * lack (`transitions.test.ts` owns the legal-transition table, + * `runtime.test.ts` pins per-operation event shapes, `runner.test.ts` pins + * handler sequencing without observing events). Descriptive, not + * aspirational: update a pin in the same PR that changes the ordering. + * Recovery-path semantics (edges leaving terminal `failed`, the legacy + * step-mutation bridge) stay out of scope — PR #6253 pins those. */ import { describe, expect, it, vi } from "vitest"; @@ -34,42 +26,13 @@ import { sanitizeFailure, } from "../../state/onboard-session"; import type { OnboardMachineEvent } from "./events"; -import { - advanceTo, - branchTo, - completeOnboardMachine, - failOnboardMachine, - retryTo, - transitionTo, -} from "./result"; +import { advanceTo, branchTo, completeOnboardMachine, failOnboardMachine } from "./result"; import { type OnboardStateHandlers, runOnboardMachine } from "./runner"; import { OnboardRuntime, type OnboardRuntimeDeps } from "./runtime"; -import { - assertValidOnboardMachineTransition, - canTransitionOnboardMachineState, - getOnboardMachineTransition, - InvalidOnboardMachineTransitionError, - ONBOARD_MACHINE_DIRECT_TRANSITIONS, - ONBOARD_MACHINE_TRANSITIONS, -} from "./transitions"; -import { - ONBOARD_MACHINE_STATES, - ONBOARD_NON_TERMINAL_MACHINE_STATES, - type OnboardMachineState, - type OnboardMachineTransition, -} from "./types"; +import type { OnboardMachineState } from "./types"; const NOW = "2026-07-04T00:00:00.000Z"; -interface TraceContext { - attempts: number; - visited: string[]; -} - -function traceContext(): TraceContext { - return { attempts: 0, visited: [] }; -} - function cloneSession(session: Session): Session { return normalizeSession(JSON.parse(JSON.stringify(session))) ?? session; } @@ -86,10 +49,17 @@ function createTracedRuntime(initialSession: Session = createSession()) { let session = cloneSession(initialSession); const events: OnboardMachineEvent[] = []; const updateSession = (mutator: (value: Session) => Session | void): Session => { - const next = mutator(cloneSession(session)) ?? session; + // Fall back to the mutated draft, never the outer `session`: void-returning + // mutators edit the draft in place and their edits must persist. + const draft = cloneSession(session); + const next = mutator(draft) ?? draft; session = cloneSession(next); return cloneSession(session); }; + const applySafeUpdates = (updates: SessionUpdates = {}): Session => + updateSession((current) => { + Object.assign(current, filterSafeUpdates(updates)); + }); const deps: OnboardRuntimeDeps = { loadSession: () => cloneSession(session), createSession, @@ -99,22 +69,13 @@ function createTracedRuntime(initialSession: Session = createSession()) { }, updateSession, markStepStarted: () => cloneSession(session), - markStepComplete: (_stepName, updates: SessionUpdates = {}) => - updateSession((current) => { - Object.assign(current, filterSafeUpdates(updates)); - return current; - }), - markStepCompleteRecordOnly: (_stepName, updates: SessionUpdates = {}) => - updateSession((current) => { - Object.assign(current, filterSafeUpdates(updates)); - return current; - }), + markStepComplete: (_stepName, updates) => applySafeUpdates(updates), + markStepCompleteRecordOnly: (_stepName, updates) => applySafeUpdates(updates), markStepSkipped: () => cloneSession(session), markStepFailed: (stepName, message) => updateSession((current) => { current.status = "failed"; current.failure = sanitizeFailure({ step: stepName, message, recordedAt: NOW }); - return current; }), markStepFailedRecordOnly: () => cloneSession(session), completeSession: (updates: SessionUpdates = {}) => @@ -122,35 +83,21 @@ function createTracedRuntime(initialSession: Session = createSession()) { Object.assign(current, filterSafeUpdates(updates)); current.status = "complete"; current.resumable = false; - return current; }), filterSafeUpdates, - emitEvent: (event) => { - events.push(event); - }, + emitEvent: (event) => events.push(event), now: () => NOW, }; - return { runtime: new OnboardRuntime(deps), events }; + return { runtime: new OnboardRuntime(deps), events, updateSession }; } function traceOf(events: readonly OnboardMachineEvent[]): string[] { return events.map((event) => `${event.type}:${event.state}`); } -const recordVisited = ({ - context, - state, -}: { - context: TraceContext; - state: OnboardMachineState; -}): TraceContext => ({ - attempts: state === "inference" ? context.attempts + 1 : context.attempts, - visited: [...context.visited, state], -}); - function fullRunHandlers( - overrides: Partial> = {}, -): OnboardStateHandlers { + overrides: Partial> = {}, +): OnboardStateHandlers { return { init: () => advanceTo("preflight"), preflight: () => advanceTo("gateway"), @@ -159,7 +106,6 @@ function fullRunHandlers( inference: () => advanceTo("sandbox"), sandbox: () => branchTo("openclaw", { updates: { sandboxName: "my-assistant" } }), openclaw: () => advanceTo("policies"), - agent_setup: () => advanceTo("policies"), policies: () => advanceTo("finalizing"), finalizing: () => advanceTo("post_verify"), post_verify: () => completeOnboardMachine(), @@ -167,122 +113,31 @@ function fullRunHandlers( }; } -const CANONICAL_DIRECT_TRANSITIONS = [ - ["init", "preflight", "advance"], - ["preflight", "gateway", "advance"], - ["gateway", "provider_selection", "advance"], - ["provider_selection", "inference", "advance"], - ["inference", "provider_selection", "retry"], - ["inference", "sandbox", "advance"], - ["sandbox", "openclaw", "branch"], - ["sandbox", "agent_setup", "branch"], - ["openclaw", "policies", "advance"], - ["agent_setup", "policies", "advance"], - ["policies", "finalizing", "advance"], - ["finalizing", "post_verify", "advance"], - ["post_verify", "complete", "advance"], -] as const; - -// Each tuple skips exactly one live state ahead of the canonical chain. -const ONE_STATE_FORWARD_JUMPS = [ - ["init", "gateway"], - ["preflight", "provider_selection"], - ["gateway", "inference"], - ["provider_selection", "sandbox"], - ["inference", "openclaw"], - ["inference", "agent_setup"], - ["sandbox", "policies"], - ["openclaw", "finalizing"], - ["agent_setup", "finalizing"], - ["policies", "post_verify"], - ["finalizing", "complete"], -] as const; - -describe("onboard machine transition surface (#6225)", () => { - it.each( - CANONICAL_DIRECT_TRANSITIONS, - )("allows %s to reach %s through a %s transition (#6225)", (from, to, kind) => { - expect(canTransitionOnboardMachineState(from, to)).toBe(true); - expect(getOnboardMachineTransition(from, to)).toEqual({ from, to, kind }); - expect(assertValidOnboardMachineTransition(from, to).kind).toBe(kind); - }); +describe("onboard machine lifecycle traces (#6225)", () => { + it("persists in-place edits from a void-returning session mutator (#6225)", async () => { + const { runtime, updateSession } = createTracedRuntime(); - it.each([ - ...ONBOARD_NON_TERMINAL_MACHINE_STATES, - ])("allows %s to take the shared failure edge (#6225)", (state) => { - expect(canTransitionOnboardMachineState(state, "failed")).toBe(true); - expect(getOnboardMachineTransition(state, "failed")).toEqual({ - from: state, - to: "failed", - kind: "failure", + updateSession((draft) => { + draft.sandboxName = "void-mutated"; }); - }); - - it.each( - ONE_STATE_FORWARD_JUMPS, - )("rejects jumping from %s past the next step to %s (#6225)", (from, to) => { - expect(canTransitionOnboardMachineState(from, to)).toBe(false); - expect(getOnboardMachineTransition(from, to)).toBeNull(); - expect(() => assertValidOnboardMachineTransition(from, to)).toThrow( - InvalidOnboardMachineTransitionError, - ); - expect(() => assertValidOnboardMachineTransition(from, to)).toThrow( - `Invalid onboarding machine transition: ${from} -> ${to}`, - ); - }); - - it("keeps the inference retry as the only backward edge among live states (#6225)", () => { - const directTransitions: readonly OnboardMachineTransition[] = - ONBOARD_MACHINE_DIRECT_TRANSITIONS; - const stateIndex = (state: OnboardMachineState): number => - ONBOARD_MACHINE_STATES.indexOf(state); - const backwardEdges = directTransitions.filter( - (transition) => - transition.from !== "failed" && stateIndex(transition.to) < stateIndex(transition.from), - ); - expect(backwardEdges).toEqual([{ from: "inference", to: "provider_selection", kind: "retry" }]); + await expect(runtime.session()).resolves.toMatchObject({ sandboxName: "void-mutated" }); }); - it("includes every canonical direct edge in the combined transition table (#6225)", () => { - expect(ONBOARD_MACHINE_TRANSITIONS).toEqual( - expect.arrayContaining( - CANONICAL_DIRECT_TRANSITIONS.map(([from, to, kind]) => ({ from, to, kind })), - ), - ); - }); -}); - -describe("fresh onboarding run trace (#6225)", () => { - it("advances through the openclaw branch to completion in canonical order (#6225)", async () => { + it("emits the fresh-run lifecycle event stream in canonical order (#6225)", async () => { const { runtime, events } = createTracedRuntime(); await runtime.start(); - const run = await runOnboardMachine({ - context: traceContext(), - runtime, - handlers: fullRunHandlers(), - updateContext: recordVisited, - }); + const run = await runOnboardMachine({ context: null, runtime, handlers: fullRunHandlers() }); - expect(run.context.visited).toEqual([ - "init", - "preflight", - "gateway", - "provider_selection", - "inference", - "sandbox", - "openclaw", - "policies", - "finalizing", - "post_verify", - ]); expect(run.session).toMatchObject({ status: "complete", resumable: false, sandboxName: "my-assistant", machine: { state: "complete", revision: 10 }, }); + // Context updates are announced from the source state before the state + // transition itself (`context.updated:sandbox` precedes `state.exited:sandbox`). expect(traceOf(events)).toEqual([ "onboard.started:init", "state.exited:init", @@ -308,143 +163,33 @@ describe("fresh onboarding run trace (#6225)", () => { "state.entered:complete", "onboard.completed:complete", ]); - - // Context updates are applied and announced from the source state before - // the state transition itself is recorded. - const contextUpdates = events.filter((event) => event.type === "context.updated"); - expect(contextUpdates).toHaveLength(1); - expect(contextUpdates[0]).toMatchObject({ - state: "sandbox", - metadata: { fields: ["sandboxName"] }, - }); expect(events[events.length - 1]).toMatchObject({ type: "onboard.completed", context: { sandboxName: "my-assistant" }, }); }); - it("routes the agent branch through agent_setup instead of openclaw (#6225)", async () => { - const { runtime } = createTracedRuntime(); - const openclawHandler = vi.fn(() => advanceTo("policies")); - - const run = await runOnboardMachine({ - context: traceContext(), - runtime, - handlers: fullRunHandlers({ - sandbox: () => branchTo("agent_setup", { updates: { sandboxName: "my-agent" } }), - openclaw: openclawHandler, - }), - updateContext: recordVisited, - }); - - expect(openclawHandler).not.toHaveBeenCalled(); - expect(run.context.visited).toEqual([ - "init", - "preflight", - "gateway", - "provider_selection", - "inference", - "sandbox", - "agent_setup", - "policies", - "finalizing", - "post_verify", - ]); - expect(run.session).toMatchObject({ - status: "complete", - sandboxName: "my-agent", - machine: { state: "complete", revision: 10 }, - }); - }); - - it("returns from inference to provider selection on retry before advancing to sandbox (#6225)", async () => { - const { runtime, events } = createTracedRuntime( - createSession({ machine: machineAt("provider_selection") }), - ); - - // The runner pauses at a stop state without requiring a handler for it — - // the same handoff mechanism the production flow slices use between the - // initial, core, and final slices. - const run = await runOnboardMachine({ - context: traceContext(), - runtime, - handlers: { - provider_selection: () => advanceTo("inference"), - inference: (context) => - context.attempts === 0 ? retryTo("provider_selection") : advanceTo("sandbox"), - }, - stopStates: ["sandbox"], - updateContext: recordVisited, - }); - - expect(run.context.visited).toEqual([ - "provider_selection", - "inference", - "provider_selection", - "inference", - ]); - expect(run.context.attempts).toBe(2); - expect(traceOf(events)).toEqual([ - "state.exited:provider_selection", - "state.entered:inference", - "state.exited:inference", - "state.entered:provider_selection", - "state.exited:provider_selection", - "state.entered:inference", - "state.exited:inference", - "state.entered:sandbox", - ]); - expect(run.session).toMatchObject({ - status: "in_progress", - machine: { state: "sandbox", revision: 4 }, - }); - }); -}); - -describe("resume trace with a completed sandbox step (#6225)", () => { - it("resumes at openclaw and never re-invokes handlers for completed states (#6225)", async () => { + it("resumes at openclaw without re-entering completed states (#6225)", async () => { const resumedSession = createSession({ sandboxName: "my-assistant", provider: "nvidia", model: "model", lastCompletedStep: "sandbox", machine: machineAt("openclaw", 6), - steps: { - preflight: completedStep(), - gateway: completedStep(), - provider_selection: completedStep(), - inference: completedStep(), - sandbox: completedStep(), - }, + steps: { sandbox: completedStep() }, }); const { runtime, events } = createTracedRuntime(resumedSession); - const priorStateHandlers = { - init: vi.fn(() => advanceTo("preflight")), - preflight: vi.fn(() => advanceTo("gateway")), - gateway: vi.fn(() => advanceTo("provider_selection")), - provider_selection: vi.fn(() => advanceTo("inference")), - inference: vi.fn(() => advanceTo("sandbox")), - sandbox: vi.fn(() => branchTo("openclaw")), - }; + const { openclaw, policies, finalizing, post_verify } = fullRunHandlers(); await runtime.start({ resumed: true }); + // No handlers exist for the already-completed states — the runner would + // throw MissingOnboardStateHandlerError if it re-entered any of them. const run = await runOnboardMachine({ - context: traceContext(), + context: null, runtime, - handlers: { - ...priorStateHandlers, - openclaw: () => advanceTo("policies"), - policies: () => advanceTo("finalizing"), - finalizing: () => advanceTo("post_verify"), - post_verify: () => completeOnboardMachine(), - }, - updateContext: recordVisited, + handlers: { openclaw, policies, finalizing, post_verify }, }); - for (const handler of Object.values(priorStateHandlers)) { - expect(handler).not.toHaveBeenCalled(); - } - expect(run.context.visited).toEqual(["openclaw", "policies", "finalizing", "post_verify"]); expect(traceOf(events)).toEqual([ "onboard.resumed:openclaw", "state.exited:openclaw", @@ -457,6 +202,7 @@ describe("resume trace with a completed sandbox step (#6225)", () => { "state.entered:complete", "onboard.completed:complete", ]); + // The resume announcement carries the sanitized session context. expect(events[0]).toMatchObject({ type: "onboard.resumed", context: { sandboxName: "my-assistant", provider: "nvidia", model: "model" }, @@ -470,16 +216,11 @@ describe("resume trace with a completed sandbox step (#6225)", () => { }); expect(run.session.steps.sandbox.status).toBe("complete"); }); -}); -describe("sandbox recreate trace (#6225)", () => { it("re-runs the sandbox state with repair events around recreate before branching (#6225)", async () => { // Machine snapshot back at `sandbox` while the recorded sandbox step is - // still marked complete: the shape a resumed session has when the - // recorded sandbox exists but is not ready and must be recreated. The - // repair-event vocabulary mirrors the sandbox handler's - // repair-and-recreate sequence (state.repair.started/completed with a - // recorded-sandbox-cleanup marker). + // still marked complete: the shape a resumed session has when the recorded + // sandbox exists but is not ready and must be recreated. const staleSession = createSession({ sandboxName: "my-assistant", lastCompletedStep: "sandbox", @@ -488,25 +229,20 @@ describe("sandbox recreate trace (#6225)", () => { }); const { runtime, events } = createTracedRuntime(staleSession); const repairMetadata = { repair: "recorded-sandbox-cleanup", sandboxName: "my-assistant" }; + const repair = (type: "state.repair.started" | "state.repair.completed") => + runtime.emitRepairEvent(type, { state: "sandbox", metadata: repairMetadata }); const run = await runOnboardMachine({ - context: traceContext(), + context: null, runtime, handlers: { sandbox: async () => { - await runtime.emitRepairEvent("state.repair.started", { - state: "sandbox", - metadata: repairMetadata, - }); - await runtime.emitRepairEvent("state.repair.completed", { - state: "sandbox", - metadata: repairMetadata, - }); + await repair("state.repair.started"); + await repair("state.repair.completed"); return branchTo("openclaw", { updates: { sandboxName: "my-assistant" } }); }, }, stopStates: ["openclaw"], - updateContext: recordVisited, }); expect(traceOf(events)).toEqual([ @@ -517,38 +253,27 @@ describe("sandbox recreate trace (#6225)", () => { "state.entered:openclaw", ]); expect(events[0].metadata).toEqual(repairMetadata); - expect(run.context.visited).toEqual(["sandbox"]); expect(run.session).toMatchObject({ status: "in_progress", sandboxName: "my-assistant", machine: { state: "openclaw", revision: 6 }, }); }); -}); -describe("mid-flow failure trace (#6225)", () => { it("stops at the failing inference step and records the failure envelope (#6225)", async () => { const { runtime, events } = createTracedRuntime(); const sandboxHandler = vi.fn(() => branchTo("openclaw")); const run = await runOnboardMachine({ - context: traceContext(), + context: null, runtime, handlers: fullRunHandlers({ inference: () => failOnboardMachine("model probe failed", { step: "inference" }), sandbox: sandboxHandler, }), - updateContext: recordVisited, }); expect(sandboxHandler).not.toHaveBeenCalled(); - expect(run.context.visited).toEqual([ - "init", - "preflight", - "gateway", - "provider_selection", - "inference", - ]); // A failed run stays resumable — `onboard --resume` recovery relies on // the failure transition leaving `resumable` untouched. expect(run.session).toMatchObject({ @@ -577,82 +302,3 @@ describe("mid-flow failure trace (#6225)", () => { }); }); }); - -describe("runtime transition-kind enforcement (#6225)", () => { - const KIND_MISMATCH_CASES = [ - { - from: "inference", - edge: "inference -> provider_selection", - result: advanceTo("provider_selection"), - expected: "advance", - actual: "retry", - }, - { - from: "inference", - edge: "inference -> sandbox", - result: retryTo("sandbox"), - expected: "retry", - actual: "advance", - }, - { - from: "sandbox", - edge: "sandbox -> openclaw", - result: advanceTo("openclaw"), - expected: "advance", - actual: "branch", - }, - { - from: "provider_selection", - edge: "provider_selection -> inference", - result: branchTo("inference"), - expected: "branch", - actual: "advance", - }, - ] as const; - - it.each( - KIND_MISMATCH_CASES, - )("rejects the mistyped result for $edge without touching the session (#6225)", async ({ - from, - edge, - result, - expected, - actual, - }) => { - const { runtime, events } = createTracedRuntime(createSession({ machine: machineAt(from) })); - - await expect(runtime.applyResult(result)).rejects.toThrow( - `Invalid onboarding machine transition kind: ${edge} expected ${expected}, got ${actual}`, - ); - await expect(runtime.session()).resolves.toMatchObject({ - machine: { state: from, revision: 0 }, - }); - expect(events).toEqual([]); - }); - - it("accepts an undeclared-kind transition result on any legal edge (#6225)", async () => { - const { runtime, events } = createTracedRuntime( - createSession({ machine: machineAt("inference") }), - ); - - await runtime.applyResult(transitionTo("provider_selection")); - - expect(traceOf(events)).toEqual(["state.exited:inference", "state.entered:provider_selection"]); - await expect(runtime.session()).resolves.toMatchObject({ - machine: { state: "provider_selection", revision: 1 }, - }); - }); - - it("validates the transition before applying any context updates (#6225)", async () => { - const { runtime, events } = createTracedRuntime(); - - await expect( - runtime.applyResult(advanceTo("sandbox", { updates: { sandboxName: "never-created" } })), - ).rejects.toThrow(InvalidOnboardMachineTransitionError); - - const session = await runtime.session(); - expect(session.sandboxName).toBeNull(); - expect(session.machine).toMatchObject({ state: "init", revision: 0 }); - expect(events).toEqual([]); - }); -}); diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index 14601738181..491420f4dd7 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -1,6 +1,7 @@ // 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 { createRequire } from "node:module"; import os from "node:os"; @@ -531,6 +532,66 @@ describe("onboard session", () => { expect(loaded.provider).toBe("openai"); }); + // ── Session secret boundary, consolidated from #6225 (epic #6224) ── + + it("persists migratedLegacyValueHashes as sha256 hex digests only, dropping non-string entries (#6225)", () => { + // Digest shape mirrors legacyValueHash() in src/lib/onboard.ts, the only + // production writer of this map. Only the digest may reach disk. + const legacyValue = "nvapi-sentinel6225-legacy-value-do-not-persist"; + const digest = createHash("sha256").update(legacyValue).digest("hex"); + session.saveSession(session.createSession()); + expect( + JSON.parse(fs.readFileSync(session.SESSION_FILE, "utf8")).migratedLegacyValueHashes, + ).toBeNull(); + + markStepCompleteLegacy(session, stepMutation, "provider_selection", { + migratedLegacyValueHashes: { + NVIDIA_API_KEY: digest, + BROKEN_NUMERIC: 123, + BROKEN_NULL: null, + } as unknown as Record, + }); + + const raw = fs.readFileSync(session.SESSION_FILE, "utf8"); + expect(raw).not.toContain(legacyValue); + expect(raw).not.toContain("BROKEN_NUMERIC"); + const loaded = requireLoadedSession(session.loadSession()); + expect(loaded.migratedLegacyValueHashes).toEqual({ NVIDIA_API_KEY: digest }); + expect(loaded.migratedLegacyValueHashes?.NVIDIA_API_KEY).toMatch(/^[0-9a-f]{64}$/); + }); + + it("serializes unset and explicitly-declined credentialEnv identically as null (#6224)", () => { + // #6224 contract gap: on disk, "never prompted" and "user declined" both + // collapse to credentialEnv: null, so a resume cannot tell them apart. + session.saveSession(session.createSession()); + const unset = JSON.parse(fs.readFileSync(session.SESSION_FILE, "utf8")).credentialEnv; + + markStepCompleteLegacy(session, stepMutation, "provider_selection", { + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + }); + markStepCompleteLegacy(session, stepMutation, "provider_selection", { credentialEnv: null }); + const declined = JSON.parse(fs.readFileSync(session.SESSION_FILE, "utf8")).credentialEnv; + + expect(unset).toBeNull(); + expect(declined).toBeNull(); + expect(declined).toBe(unset); + expect(requireLoadedSession(session.loadSession()).credentialEnv).toBeNull(); + }); + + it.fails("redacts token-shaped values under benign endpoint query param names (#6224)", () => { + // DESIRED behavior, not yet implemented: redactUrl() only masks + // sensitive-NAMED query params, so a token-shaped value under a benign + // name persists verbatim today. Flip to a plain `it` once epic #6224 + // adds value-shape redaction for parseable URLs. + const tokenValue = "nvapi-pending6224-token-shaped-value"; + session.saveSession(session.createSession()); + markStepCompleteLegacy(session, stepMutation, "provider_selection", { + endpointUrl: `https://api.example.com/v1?model=${tokenValue}`, + }); + + expect(fs.readFileSync(session.SESSION_FILE, "utf8")).not.toContain(tokenValue); + }); + it("only persists known Hermes auth methods", () => { session.saveSession(session.createSession()); markStepCompleteLegacy(session, stepMutation, "provider_selection", { diff --git a/test/onboard-lifecycle-invariants.test.ts b/test/onboard-lifecycle-invariants.test.ts index e627f54c41e..f7256b087ec 100644 --- a/test/onboard-lifecycle-invariants.test.ts +++ b/test/onboard-lifecycle-invariants.test.ts @@ -2,33 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 // // Characterization baseline for the onboarding create-path lifecycle (#6225, -// epic #6224). These tests pin CURRENT main behavior — including orderings the -// epic flags as contract gaps (e.g. gateway messaging credential upserts run -// AFTER the destructive sandbox delete, and credential-binding validation only -// happens at plan materialization time, which is also after the delete). They -// are a regression baseline, not an endorsement: later children (#6226/#6227/ -// #6228) are expected to change some of these pins deliberately. +// epic #6224). Pins CURRENT main behavior at the injectable decision seams: +// the sandbox messaging preflight (hosting the #5954-shared conflict guard), +// the sandbox create plan (whose materialization performs the gateway +// messaging upsert), and the resume identity predicate behind #2753. A +// regression baseline, not an endorsement: later children (#6226/#6227/#6228) +// are expected to change some pins deliberately. // -// The `createSandbox` orchestration in src/lib/onboard.ts cannot run -// hermetically (it shells out to OpenShell/Docker), so its cross-module -// ordering is pinned as a source-order characterization over the function -// body, while every decision that lives in an injectable module -// (sandbox-messaging-preflight, sandbox-create-plan, sandbox-resume, -// resume-config) is pinned with direct unit-level calls. +// The cross-module ordering of the non-hermetic `createSandbox` orchestration +// in src/lib/onboard.ts has no behavioral seam today; it is documented in +// src/lib/onboard/lifecycle-contracts.md, with executable coverage deferred +// to the issue that introduces the seam. -import fs from "node:fs"; -import path from "node:path"; - -import { afterEach, describe, expect, it, vi } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { SandboxMessagingPlan } from "../src/lib/messaging/manifest/types.js"; -import type { SandboxResumeDecision } from "../src/lib/onboard/machine/handlers/sandbox-resume.js"; -import { - applySandboxResumeDecision, - decideSandboxResume, - type SandboxResumeDeps, - type SandboxResumeSignals, -} from "../src/lib/onboard/machine/handlers/sandbox-resume.js"; import type { MessagingConflictGuardDeps } from "../src/lib/onboard/messaging-conflict-guard.js"; import type { CreateSandboxMessagingPrepResult, @@ -78,119 +66,12 @@ class OnboardAbortError extends Error { } } -// ── 1. Source-order characterization of createSandbox ────────────────────── -// -// Pins which deterministic validations and checkpoints complete before the -// first destructive effect (the `openshell sandbox delete` of a pre-existing -// sandbox) and which effects run after it. The markers are call-site snippets -// inside `async function createSandbox(` in src/lib/onboard.ts, verified at -// HEAD: messaging preflight (which hosts the #5954-shared conflict guard), -// fail-closed pre-recreate backup, the delete boundary, the create plan whose -// materialization performs the gateway messaging upsert, the create stream, -// the readiness gate, and post-ready registration. - -const repoRoot = path.join(import.meta.dirname, ".."); -const onboardSource = fs.readFileSync(path.join(repoRoot, "src", "lib", "onboard.ts"), "utf8"); -const createSandboxStart = onboardSource.indexOf("async function createSandbox("); -const createSandboxEnd = onboardSource.indexOf("\nasync function ", createSandboxStart + 1); -const createSandboxBody = onboardSource.slice(createSandboxStart, createSandboxEnd); - -const DELETE_SNIPPET = 'runOpenshell(["sandbox", "delete", sandboxName], { ignoreError: true });'; - -const CREATE_LIFECYCLE_MARKERS = [ - { label: "sandbox name validation", snippet: "const sandboxName = validateName(" }, - { - label: "messaging preflight with the conflict guard", - snippet: "sandboxMessagingPreflight.prepareSandboxMessagingPreflight(", - }, - { - label: "pre-upgrade backup selection", - snippet: "notReadyRecreate.selectPreUpgradeBackupForCreate(", - }, - { - label: "fail-closed pre-recreate workspace backup", - snippet: "backupSandboxBeforeRecreate({ sandboxName });", - }, - { - label: "provider pre-delete cleanup", - snippet: "runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact });", - }, - { label: "destructive sandbox delete", snippet: DELETE_SNIPPET }, - { label: "previous image removal", snippet: "dockerRmi(previousEntry.imageTag" }, - { label: "registry entry removal", snippet: "registry.removeSandbox(sandboxName);" }, - { - label: "create plan preparation with the gateway messaging upsert", - snippet: "sandboxCreatePlan.prepareSandboxCreatePlan({", - }, - { label: "sandbox create stream", snippet: "await streamSandboxCreate(" }, - { label: "readiness gate", snippet: "waitForCreatedSandboxReadyWithTrace({" }, - { - label: "post-ready registry registration", - snippet: "sandboxRegistration.registerCreatedSandbox({", - }, -] as const; - -const markerIndex = (snippet: string): number => createSandboxBody.indexOf(snippet); - -const consecutiveMarkerPairs = CREATE_LIFECYCLE_MARKERS.slice(1).map((later, index) => ({ - earlierLabel: CREATE_LIFECYCLE_MARKERS[index].label, - earlierSnippet: CREATE_LIFECYCLE_MARKERS[index].snippet, - laterLabel: later.label, - laterSnippet: later.snippet, -})); - -describe("createSandbox source ordering on the onboard create path (#6225)", () => { - it("bounds the createSandbox body for source scanning (#6225)", () => { - expect(createSandboxStart).toBeGreaterThanOrEqual(0); - expect(createSandboxEnd).toBeGreaterThan(createSandboxStart); - }); - - it.each([ - ...CREATE_LIFECYCLE_MARKERS, - ])("locates the $label call site inside createSandbox (#6225)", ({ snippet }) => { - expect(markerIndex(snippet)).toBeGreaterThanOrEqual(0); - }); - - it.each(consecutiveMarkerPairs)("keeps the $earlierLabel ahead of the $laterLabel (#6225)", ({ - earlierSnippet, - laterSnippet, - }) => { - expect(markerIndex(earlierSnippet)).toBeLessThan(markerIndex(laterSnippet)); - }); - - it("returns from the reuse fast paths before reaching the destructive sandbox delete (#6225)", () => { - const firstReuseReturn = createSandboxBody.indexOf("return sandboxName;"); - expect(firstReuseReturn).toBeGreaterThanOrEqual(0); - expect(firstReuseReturn).toBeLessThan(markerIndex(DELETE_SNIPPET)); - }); - - it("issues exactly two sandbox delete commands with the failed-create cleanup after the create stream (#6225)", () => { - expect(createSandboxBody.split(DELETE_SNIPPET).length - 1).toBe(2); - const streamIndex = markerIndex("await streamSandboxCreate("); - expect(createSandboxBody.indexOf(DELETE_SNIPPET, streamIndex)).toBeGreaterThan(streamIndex); - }); - - // Divergence pinned for #6225: the create plan's provider cleanup re-run is - // the tolerant variant (the sandbox is already gone) and the gateway - // messaging credential upsert is wired into the plan, i.e. it executes only - // after the destructive delete and before the create stream. - it("wires the tolerant cleanup re-run and the gateway messaging upsert into the post-delete create plan (#6225)", () => { - const planRegion = createSandboxBody.slice( - markerIndex("sandboxCreatePlan.prepareSandboxCreatePlan({"), - markerIndex("await streamSandboxCreate("), - ); - expect(planRegion).toContain("tolerateMissingSandbox: true"); - expect(planRegion).toContain("upsertMessagingProviders,"); - }); -}); - -// ── 2. Messaging conflict guard wiring inside the sandbox messaging preflight ── +// ── 1. Messaging conflict guard wiring inside the sandbox messaging preflight ── // // The preflight is the injectable module the create path runs before any -// destructive effect (see the source-order pins above). It hosts the shared -// messaging conflict guard (#5954) with the onboard-specific interactive -// wiring: a "Continue anyway?" prompt is allowed here, unlike the rebuild -// preflight's forced non-interactive abort. +// destructive effect. It hosts the shared messaging conflict guard (#5954) +// with the onboard-specific interactive wiring: a "Continue anyway?" prompt is +// allowed here, unlike the rebuild preflight's forced non-interactive abort. function buildMessagingPrepResult( overrides: Partial = {}, @@ -326,12 +207,13 @@ describe("messaging conflict guard wiring in prepareSandboxMessagingPreflight (# }); }); -// ── 3. Gateway messaging upsert ordering inside the create plan ──────────── +// ── 2. Gateway messaging upsert ordering inside the create plan ──────────── // -// On the create path this module runs AFTER the destructive delete (pinned in -// section 1). Inside the plan itself, deterministic intent resolution and -// credential-binding validation complete before any gateway effect, and the -// tolerant cleanup re-run precedes the credential upsert. +// On the create path this module runs AFTER the destructive delete (see +// src/lib/onboard/lifecycle-contracts.md). Inside the plan itself, +// deterministic intent resolution and credential-binding validation complete +// before any gateway effect, and the tolerant cleanup re-run precedes the +// credential upsert. describe("gateway messaging upsert ordering in the sandbox create plan (#6225)", () => { it("re-runs provider cleanup before upserting messaging credentials with replaceExisting (#6225)", () => { @@ -436,28 +318,22 @@ describe("gateway messaging upsert ordering in the sandbox create plan (#6225)", }); }); -// ── 4. Resume identity: recorded sandbox name and the sandbox step gate ──── +// ── 3. Resume identity: recorded sandbox name and the sandbox step gate ──── // // The deciding functions behind the #2753 contract: the recorded sandbox name // is trusted (as resume identity and as a conflict source) only when the // session's sandbox step actually completed. onboard() applies the same -// predicate when it seeds `recordedSandboxName` for the flow context, and -// `decideSandboxResume` collapses to a plain create when the step is -// incomplete. +// predicate when it seeds `recordedSandboxName` for the flow context, and the +// resume decision collapses to a plain create when the step is incomplete +// (see sandbox-resume.test.ts for the decision-side coverage). describe("resume identity honors the recorded sandbox name only after the sandbox step completed (#2753)", () => { - afterEach(() => { - vi.unstubAllEnvs(); - }); - it.each([ - { status: "pending" }, - { status: "in_progress" }, - { status: "failed" }, - { status: "skipped" }, - ])("ignores the recorded sandbox name while the sandbox step is $status (#2753)", ({ - status, - }) => { + "pending", + "in_progress", + "failed", + "skipped", + ])("ignores the recorded sandbox name while the sandbox step is %s (#2753)", (status) => { const conflict = getResumeSandboxConflict( { sandboxName: "recorded-sandbox", steps: { sandbox: { status } } }, { sandboxName: "requested-sandbox" }, @@ -515,255 +391,4 @@ describe("resume identity honors the recorded sandbox name only after the sandbo { field: "sandbox", requested: "fresh-name", recorded: "recorded-sandbox" }, ]); }); - - it("ignores provider and model env hints during interactive resume conflict checks (#6225)", () => { - vi.stubEnv("NEMOCLAW_PROVIDER", "cloud"); - vi.stubEnv("NEMOCLAW_MODEL", "meta/llama-3.3-70b-instruct"); - - const conflicts = getResumeConfigConflicts( - { provider: "nvidia-nim", model: "recorded-model" }, - {}, - ); - - expect(conflicts).toEqual([]); - }); - - it("resolves Dockerfile paths before comparing resume intent with the recorded session (#6225)", () => { - const recordedOnly = getResumeConfigConflicts( - { metadata: { fromDockerfile: "fixtures/Dockerfile.recorded" } }, - {}, - ); - const equivalentSpelling = getResumeConfigConflicts( - { metadata: { fromDockerfile: "./fixtures/Dockerfile.recorded" } }, - { fromDockerfile: "fixtures/Dockerfile.recorded" }, - ); - - expect(recordedOnly).toEqual([ - { - field: "fromDockerfile", - requested: null, - recorded: path.resolve("fixtures/Dockerfile.recorded"), - }, - ]); - expect(equivalentSpelling).toEqual([]); - }); -}); - -// ── 5. decideSandboxResume: the pure reuse/recreate policy ───────────────── - -const READY_RESUME_SIGNALS: SandboxResumeSignals = { - resume: true, - resumeAgentChanged: false, - sandboxStepComplete: true, - sandboxReuseState: "ready", - webSearchConfigChanged: false, - sandboxGpuConfigChanged: false, - messagingChannelConfigChanged: false, - hermesToolGatewayConfigChanged: false, -}; - -const resumeSignals = (overrides: Partial = {}): SandboxResumeSignals => ({ - ...READY_RESUME_SIGNALS, - ...overrides, -}); - -describe("decideSandboxResume pins the sandbox reuse contract (#6225)", () => { - it("decides create when the sandbox step never completed even with a ready recorded sandbox (#2753)", () => { - expect(decideSandboxResume(resumeSignals({ sandboxStepComplete: false }))).toEqual({ - kind: "create", - }); - expect( - decideSandboxResume( - resumeSignals({ - sandboxStepComplete: false, - resumeAgentChanged: true, - webSearchConfigChanged: true, - sandboxReuseState: "not_ready", - }), - ), - ).toEqual({ kind: "create" }); - }); - - it("decides create when the run is not a resume (#6225)", () => { - expect(decideSandboxResume(resumeSignals({ resume: false }))).toEqual({ kind: "create" }); - }); - - it("decides reuse only for a ready driftless resume with a completed sandbox step (#6225)", () => { - expect(decideSandboxResume(resumeSignals())).toEqual({ kind: "reuse" }); - }); - - it.each([ - { - flag: "resumeAgentChanged", - note: " [resume] Agent selection changed; revalidating sandbox compatibility.", - removeRegistryEntry: false, - }, - { - flag: "webSearchConfigChanged", - note: " [resume] Web Search configuration changed; recreating sandbox.", - removeRegistryEntry: true, - }, - { - flag: "sandboxGpuConfigChanged", - note: " [resume] Sandbox GPU settings changed; recreating sandbox.", - removeRegistryEntry: true, - }, - { - flag: "messagingChannelConfigChanged", - note: " [resume] Messaging channel configuration changed; recreating sandbox.", - removeRegistryEntry: true, - }, - { - flag: "hermesToolGatewayConfigChanged", - note: " [resume] Hermes managed tool gateway selection changed; recreating sandbox.", - removeRegistryEntry: true, - }, - ])("recreates on $flag drift and pins its note and registry removal policy (#6225)", ({ - flag, - note, - removeRegistryEntry, - }) => { - const decision = decideSandboxResume({ - ...READY_RESUME_SIGNALS, - [flag]: true, - } as SandboxResumeSignals); - - expect(decision).toEqual({ kind: "recreate", note, removeRegistryEntry }); - }); - - it("prefers the agent drift decision when every drift flag is set (#6225)", () => { - const decision = decideSandboxResume( - resumeSignals({ - resumeAgentChanged: true, - webSearchConfigChanged: true, - sandboxGpuConfigChanged: true, - messagingChannelConfigChanged: true, - hermesToolGatewayConfigChanged: true, - }), - ); - - expect(decision).toEqual({ - kind: "recreate", - note: " [resume] Agent selection changed; revalidating sandbox compatibility.", - removeRegistryEntry: false, - }); - }); - - it("repairs and recreates a recorded sandbox that is not ready (#6225)", () => { - expect(decideSandboxResume(resumeSignals({ sandboxReuseState: "not_ready" }))).toEqual({ - kind: "repair-and-recreate", - }); - }); - - it("recreates with registry removal when the recorded sandbox state is unavailable (#6225)", () => { - expect(decideSandboxResume(resumeSignals({ sandboxReuseState: "unknown" }))).toEqual({ - kind: "recreate", - note: " [resume] Recorded sandbox state is unavailable; recreating it.", - removeRegistryEntry: true, - }); - }); -}); - -// ── 6. applySandboxResumeDecision: the side-effect contract ──────────────── - -function buildResumeDecisionHarness({ repairError = null }: { repairError?: Error | null } = {}) { - const events: string[] = []; - const deps: SandboxResumeDeps = { - note: vi.fn((message: string) => { - events.push(`note:${message.trim()}`); - }), - removeSandboxFromRegistry: vi.fn((sandboxName: string) => { - events.push(`remove-registry:${sandboxName}`); - }), - repairRecordedSandbox: vi.fn((sandboxName: string | null) => { - events.push(`repair:${sandboxName}`); - const failure = [repairError].filter((error): error is Error => error !== null); - failure.forEach((error) => { - throw error; - }); - }), - recordRepairEvent: vi.fn(async (type: string) => { - events.push(type); - return null; - }), - }; - return { deps, events }; -} - -describe("applySandboxResumeDecision side effect contract (#6225)", () => { - it("removes the registry entry only when the recreate decision says so (#6225)", async () => { - const harness = buildResumeDecisionHarness(); - const decision: SandboxResumeDecision = { - kind: "recreate", - note: " [resume] Web Search configuration changed; recreating sandbox.", - removeRegistryEntry: true, - }; - - await applySandboxResumeDecision(decision, "sandbox-a", harness.deps); - - expect(harness.events).toEqual([ - "note:[resume] Web Search configuration changed; recreating sandbox.", - "remove-registry:sandbox-a", - ]); - }); - - it("keeps the registry entry for an agent change recreate (#6225)", async () => { - const harness = buildResumeDecisionHarness(); - const decision: SandboxResumeDecision = { - kind: "recreate", - note: " [resume] Agent selection changed; revalidating sandbox compatibility.", - removeRegistryEntry: false, - }; - - await applySandboxResumeDecision(decision, "sandbox-a", harness.deps); - - expect(harness.deps.removeSandboxFromRegistry).not.toHaveBeenCalled(); - expect(harness.events).toEqual([ - "note:[resume] Agent selection changed; revalidating sandbox compatibility.", - ]); - }); - - it.each([ - { kind: "create" as const }, - { kind: "reuse" as const }, - ])("performs no side effects for a $kind decision (#6225)", async ({ kind }) => { - const harness = buildResumeDecisionHarness(); - - await applySandboxResumeDecision({ kind }, "sandbox-a", harness.deps); - - expect(harness.events).toEqual([]); - }); - - it("emits repair started and completed events around the recorded sandbox cleanup (#6225)", async () => { - const harness = buildResumeDecisionHarness(); - - await applySandboxResumeDecision({ kind: "repair-and-recreate" }, "sandbox-a", harness.deps); - - expect(harness.events).toEqual([ - "note:[resume] Recorded sandbox 'sandbox-a' exists but is not ready; recreating it.", - "state.repair.started", - "repair:sandbox-a", - "state.repair.completed", - ]); - expect(harness.deps.recordRepairEvent).toHaveBeenCalledWith("state.repair.started", { - state: "sandbox", - metadata: { repair: "recorded-sandbox-cleanup", sandboxName: "sandbox-a" }, - }); - }); - - it("emits a repair failed event and rethrows when the recorded sandbox cleanup throws (#6225)", async () => { - const harness = buildResumeDecisionHarness({ repairError: new Error("cleanup exploded") }); - - await expect( - applySandboxResumeDecision({ kind: "repair-and-recreate" }, "sandbox-a", harness.deps), - ).rejects.toThrow("cleanup exploded"); - - expect(harness.events).toContain("state.repair.failed"); - expect(harness.events).not.toContain("state.repair.completed"); - expect(harness.deps.recordRepairEvent).toHaveBeenCalledWith("state.repair.failed", { - state: "sandbox", - error: "cleanup exploded", - metadata: { repair: "recorded-sandbox-cleanup", sandboxName: "sandbox-a" }, - }); - }); }); diff --git a/test/onboard-session-secret-invariants.test.ts b/test/onboard-session-secret-invariants.test.ts deleted file mode 100644 index da7bcef6a91..00000000000 --- a/test/onboard-session-secret-invariants.test.ts +++ /dev/null @@ -1,361 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -/** - * Characterization of the onboarding session persistence SECRET BOUNDARY - * (#6225, epic #6224). - * - * ~/.nemoclaw/onboard-session.json is the durable artifact `onboard --resume` - * trusts, so its contract is that credential VALUES never reach disk: - * - * - `credentialEnv` persists the env-var NAME only; the secret value stays - * in the process environment and is re-hydrated on resume - * (src/lib/state/onboard-session.ts). - * - `endpointUrl` is passed through redactUrl() (src/lib/security/redact.ts) - * both in filterSafeUpdates() and again in normalizeSession() on every - * save and load: userinfo stripped, sensitive-named query params masked, - * fragment removed; non-URL values fall back to redactSensitiveText(). - * - `migratedLegacyValueHashes` stores sha256 hex digests keyed by env - * name, mirroring legacyValueHash() in src/lib/onboard.ts, never the - * migrated plaintext. - * - failure messages and per-step errors pass through redactSensitiveText(). - * - * These tests PIN current behavior as a regression baseline. Sessions are - * built through the real mutation/serialization functions (createSession, - * saveSession, markStep*, loadSession) — never hand-written JSON — then the - * raw persisted text is scanned for sentinel leakage and deserialized back. - * Known gaps (the unset-vs-declined null ambiguity, benign-named query - * params) are pinned as-is and annotated, deliberately not fixed here. - */ - -import { createHash } from "node:crypto"; -import fs from "node:fs"; -import { createRequire } from "node:module"; -import os from "node:os"; -import path from "node:path"; - -import { afterAll, beforeEach, describe, expect, it } from "vitest"; - -import type { Session } from "../src/lib/state/onboard-session"; - -const require = createRequire(import.meta.url); - -// SESSION_DIR/SESSION_FILE are derived from HOME at module-load time, so the -// temp HOME must be in place before the session module loads. These CJS -// requires (via the integration project's source-require hook) execute here, -// after the assignment — unlike a hoisted static import. -const originalHome = process.env.HOME; -const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-session-secret-")); -process.env.HOME = tempHome; - -const session: typeof import("../src/lib/state/onboard-session") = require("../src/lib/state/onboard-session"); -const stepMutation: typeof import("../src/lib/state/onboard-step-mutation") = require("../src/lib/state/onboard-step-mutation"); - -const restoreHome = - originalHome === undefined - ? () => { - delete process.env.HOME; - } - : () => { - process.env.HOME = originalHome; - }; - -const originalCredentialValue = process.env.NVIDIA_API_KEY; -const restoreCredentialValue = - originalCredentialValue === undefined - ? () => { - delete process.env.NVIDIA_API_KEY; - } - : () => { - process.env.NVIDIA_API_KEY = originalCredentialValue; - }; - -// Distinctive marker embedded in the sentinel so raw-text scans catch partial -// leakage, not just the intact token. -const SENTINEL_MARKER = "sentinel6225zqx"; -// nvapi-shaped so every redactor tier (TOKEN_PREFIX_PATTERNS in -// src/lib/security/secret-patterns.ts) recognizes it as a secret wherever -// redaction is expected to fire. -const SENTINEL_SECRET = `nvapi-${SENTINEL_MARKER}-secret-value-do-not-persist`; -const SENTINEL_SHA256 = createHash("sha256").update(SENTINEL_SECRET).digest("hex"); - -const REDACTED_FAILURE_MESSAGE = - "sandbox create failed: NVIDIA_API_KEY= and Bearer "; - -function readRawSessionText(): string { - return fs.readFileSync(session.SESSION_FILE, "utf8"); -} - -function requireLoadedSession(): Session { - const loaded = session.loadSession(); - expect(loaded).not.toBeNull(); - return loaded ?? session.createSession(); -} - -beforeEach(() => { - session.clearSession(); - // The real secret value lives in the process environment during onboarding - // (credential hydration reads it from there on resume). Keeping it staged - // for every test proves the session layer never captures it ambiently. - process.env.NVIDIA_API_KEY = SENTINEL_SECRET; -}); - -afterAll(() => { - session.clearSession(); - restoreCredentialValue(); - restoreHome(); - fs.rmSync(tempHome, { recursive: true, force: true }); -}); - -describe("onboard session persistence secret boundary (#6225)", () => { - it("persists the credential env-var name only while the secret value stays in process.env", () => { - // Guard: the module-scope HOME redirect must have taken effect, or the - // scans below would read a session file outside the temp sandbox. - expect(session.SESSION_DIR).toBe(path.join(tempHome, ".nemoclaw")); - - session.saveSession(session.createSession()); - session.markStepCompleteRecordOnly("provider_selection", { - provider: "nvidia-prod", - model: "nvidia/llama-3.1-nemotron-70b-instruct", - }); - session.markStepCompleteRecordOnly("inference", { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - }); - - const raw = readRawSessionText(); - expect(raw).toContain('"credentialEnv": "NVIDIA_API_KEY"'); - expect(raw).not.toContain(SENTINEL_SECRET); - expect(raw).not.toContain(SENTINEL_MARKER); - - const loaded = requireLoadedSession(); - expect(loaded.credentialEnv).toBe("NVIDIA_API_KEY"); - expect(loaded.provider).toBe("nvidia-prod"); - expect(loaded.endpointUrl).toBe("https://integrate.api.nvidia.com/v1"); - }); - - it("keeps the sentinel secret out of every persisted field across a failed-run round-trip", () => { - session.saveSession(session.createSession()); - session.markStepStartedRecordOnly("preflight"); - session.markStepCompleteRecordOnly("preflight"); - session.markStepStartedRecordOnly("gateway"); - session.markStepCompleteRecordOnly("gateway"); - session.markStepCompleteRecordOnly("provider_selection", { - provider: "nvidia-prod", - model: "nemotron-test", - }); - session.markStepCompleteRecordOnly("inference", { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: `https://svc:${SENTINEL_SECRET}@api.example.com/v1?access_token=${SENTINEL_SECRET}`, - migratedLegacyValueHashes: { NVIDIA_API_KEY: SENTINEL_SHA256 }, - }); - session.markStepStartedRecordOnly("sandbox"); - // The process-exit backstop (markLastStartedStepFailed in - // src/lib/onboard/exit-step-failure.ts) records failures with the legacy - // machine-updating options; mirror that exact write here. - session.markStepFailed( - "sandbox", - `sandbox create failed: NVIDIA_API_KEY=${SENTINEL_SECRET} and Bearer ${SENTINEL_SECRET}`, - stepMutation.LEGACY_MACHINE_STEP_MUTATION_OPTIONS, - ); - - const raw = readRawSessionText(); - expect(raw).not.toContain(SENTINEL_SECRET); - expect(raw).not.toContain(SENTINEL_MARKER); - expect(raw).toContain("NVIDIA_API_KEY="); - - const loaded = requireLoadedSession(); - expect(loaded.credentialEnv).toBe("NVIDIA_API_KEY"); - expect(loaded.endpointUrl).toBe("https://api.example.com/v1?access_token=%3CREDACTED%3E"); - expect(loaded.migratedLegacyValueHashes).toEqual({ NVIDIA_API_KEY: SENTINEL_SHA256 }); - expect(loaded.failure?.step).toBe("sandbox"); - expect(loaded.failure?.message).toBe(REDACTED_FAILURE_MESSAGE); - expect(loaded.steps.sandbox.error).toBe(REDACTED_FAILURE_MESSAGE); - expect(loaded.lastStepStarted).toBe("sandbox"); - expect(loaded.status).toBe("failed"); - expect(loaded.machine.state).toBe("failed"); - - // The persisted form is a fixed point of normalizeSession: deserializing - // and re-normalizing yields the identical session, so a resume never - // re-redacts fields into a different shape. - expect(session.normalizeSession(JSON.parse(raw))).toEqual(loaded); - }); -}); - -describe("endpointUrl persistence stores the redactUrl() form only (#6225)", () => { - const endpointCases = [ - { - label: "a plain https endpoint verbatim", - input: "https://api.example.com/v1", - stored: "https://api.example.com/v1", - }, - { - label: "a bare origin with URL normalization applied", - input: "https://api.example.com", - stored: "https://api.example.com/", - }, - { - label: "an endpoint with basic-auth userinfo with the credentials stripped", - input: `https://svc:${SENTINEL_SECRET}@api.example.com/v1`, - stored: "https://api.example.com/v1", - }, - { - label: "a sensitive api_token query parameter as a percent-encoded REDACTED marker", - input: `https://api.example.com/v1?api_token=${SENTINEL_SECRET}`, - stored: "https://api.example.com/v1?api_token=%3CREDACTED%3E", - }, - { - label: "a sensitive access_token parameter masked while benign neighbors survive", - input: `https://api.example.com/v1?access_token=${SENTINEL_SECRET}&model=nemotron-mini`, - stored: "https://api.example.com/v1?access_token=%3CREDACTED%3E&model=nemotron-mini", - }, - { - label: "an endpoint with the URL fragment removed", - input: `https://api.example.com/v1#${SENTINEL_SECRET}`, - stored: "https://api.example.com/v1", - }, - { - label: "a local http endpoint untouched", - input: "http://localhost:11434/v1", - stored: "http://localhost:11434/v1", - }, - { - label: "a non-URL value through the sensitive-text fallback unchanged", - input: "ollama runs locally without an endpoint", - stored: "ollama runs locally without an endpoint", - }, - { - label: "a bearer token inside a non-URL value as a REDACTED marker", - input: `endpoint auth uses Bearer ${SENTINEL_SECRET}`, - stored: "endpoint auth uses Bearer ", - }, - ] as const; - - it.each(endpointCases)("stores $label", ({ input, stored }) => { - session.saveSession(session.createSession()); - session.markStepCompleteRecordOnly("inference", { endpointUrl: input }); - - const persisted = JSON.parse(readRawSessionText()) as { endpointUrl: string | null }; - expect(persisted.endpointUrl).toBe(stored); - expect(requireLoadedSession().endpointUrl).toBe(stored); - }); - - it("persists token-shaped values under benign query parameter names verbatim", () => { - // KNOWN GAP pinned as-is (#6224): redactUrl() only masks userinfo and - // query parameters whose NAME matches signature|sig|token|auth| - // access_token. The parseable-URL branch never applies the token-prefix - // patterns, so a secret-shaped value under a benign parameter name is - // persisted verbatim. Characterization only — do not fix here. - const gapSentinel = "nvapi-gap6224param-value-persisted-verbatim"; - session.saveSession(session.createSession()); - session.markStepCompleteRecordOnly("inference", { - endpointUrl: `https://api.example.com/v1?model=${gapSentinel}`, - }); - - expect(readRawSessionText()).toContain(gapSentinel); - expect(requireLoadedSession().endpointUrl).toBe( - `https://api.example.com/v1?model=${gapSentinel}`, - ); - }); -}); - -describe("migratedLegacyValueHashes persistence (#6225)", () => { - it("defaults to null on a fresh session", () => { - session.saveSession(session.createSession()); - const persisted = JSON.parse(readRawSessionText()) as { - migratedLegacyValueHashes: unknown; - }; - expect(persisted.migratedLegacyValueHashes).toBeNull(); - }); - - it("stores 64-char sha256 hex digests keyed by env-var name, never the legacy plaintext", () => { - // Digest shape mirrors legacyValueHash() in src/lib/onboard.ts, the only - // production writer of this map (via persistMigratedLegacyKeys()). - const otherLegacyValue = `sk-${SENTINEL_MARKER}-legacy-openai-value`; - const otherDigest = createHash("sha256").update(otherLegacyValue).digest("hex"); - session.saveSession(session.createSession()); - session.markStepCompleteRecordOnly("inference", { - migratedLegacyValueHashes: { - NVIDIA_API_KEY: SENTINEL_SHA256, - OPENAI_API_KEY: otherDigest, - }, - }); - - const raw = readRawSessionText(); - expect(raw).not.toContain(SENTINEL_SECRET); - expect(raw).not.toContain(SENTINEL_MARKER); - expect(raw).not.toContain(otherLegacyValue); - - const loaded = requireLoadedSession(); - const hashes = loaded.migratedLegacyValueHashes ?? {}; - expect(Object.keys(hashes).sort()).toEqual(["NVIDIA_API_KEY", "OPENAI_API_KEY"]); - for (const digest of Object.values(hashes)) { - expect(digest).toMatch(/^[0-9a-f]{64}$/); - } - expect(hashes.NVIDIA_API_KEY).toBe(SENTINEL_SHA256); - expect(hashes.OPENAI_API_KEY).toBe(otherDigest); - }); - - it("drops non-string entries from migratedLegacyValueHashes updates", () => { - session.saveSession(session.createSession()); - session.markStepCompleteRecordOnly("inference", { - migratedLegacyValueHashes: { - NVIDIA_API_KEY: SENTINEL_SHA256, - BROKEN_NUMERIC: 123, - BROKEN_NULL: null, - } as unknown as Record, - }); - - expect(requireLoadedSession().migratedLegacyValueHashes).toEqual({ - NVIDIA_API_KEY: SENTINEL_SHA256, - }); - }); -}); - -describe("credentialEnv tri-state serialization (#6225)", () => { - // The SessionUpdates contract (GH #2625) distinguishes three intents: - // undefined -> leave unchanged, null -> explicit clear, string -> set. - // On disk, however, "never prompted" and "explicitly declined/cleared" - // both serialize to `"credentialEnv": null` — the persisted form cannot - // distinguish the two. This unset/declined ambiguity is a KNOWN CONTRACT - // GAP tracked by epic #6224; it is pinned as-is here, deliberately unfixed. - - it("serializes a never-recorded credential as null", () => { - session.saveSession(session.createSession()); - - const raw = readRawSessionText(); - expect(raw).toContain('"credentialEnv": null'); - expect((JSON.parse(raw) as { credentialEnv: string | null }).credentialEnv).toBeNull(); - expect(requireLoadedSession().credentialEnv).toBeNull(); - }); - - it("leaves the recorded name unchanged when an update omits credentialEnv", () => { - session.saveSession(session.createSession()); - session.markStepCompleteRecordOnly("inference", { credentialEnv: "NVIDIA_API_KEY" }); - session.markStepCompleteRecordOnly("openclaw", { credentialEnv: undefined }); - - expect(requireLoadedSession().credentialEnv).toBe("NVIDIA_API_KEY"); - }); - - it("serializes an explicit decline identically to never-recorded (#6224)", () => { - session.saveSession(session.createSession()); - const rawUnset = readRawSessionText(); - - session.markStepCompleteRecordOnly("provider_selection", { credentialEnv: "NVIDIA_API_KEY" }); - expect(readRawSessionText()).toContain('"credentialEnv": "NVIDIA_API_KEY"'); - - session.markStepCompleteRecordOnly("inference", { credentialEnv: null }); - const rawDeclined = readRawSessionText(); - - const unsetValue = (JSON.parse(rawUnset) as { credentialEnv: string | null }).credentialEnv; - const declinedValue = (JSON.parse(rawDeclined) as { credentialEnv: string | null }) - .credentialEnv; - expect(unsetValue).toBeNull(); - expect(declinedValue).toBeNull(); - expect(rawDeclined).toContain('"credentialEnv": null'); - // Ambiguity pin: both histories collapse to the same persisted value, so - // a resumed run cannot tell "user declined" apart from "never asked". - expect(declinedValue).toBe(unsetValue); - expect(requireLoadedSession().credentialEnv).toBeNull(); - }); -}); From 7ae4ed6a202c47c763cc5e6bcebf38be1be71148 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Tue, 7 Jul 2026 12:08:38 -0700 Subject: [PATCH 3/3] refactor(onboard): streamline lifecycle characterization Remove duplicate coverage and exercise recreate through the real sandbox handler. Align the lifecycle map with current main behavior. Co-authored-by: Abhimanyu Kumar Signed-off-by: Apurv Kumaria --- src/lib/onboard/lifecycle-contracts.md | 222 ++++++---- src/lib/onboard/machine/README.md | 2 +- .../onboard/machine/transition-traces.test.ts | 54 +-- src/lib/state/onboard-session.test.ts | 29 +- test/onboard-lifecycle-invariants.test.ts | 394 ------------------ 5 files changed, 188 insertions(+), 513 deletions(-) delete mode 100644 test/onboard-lifecycle-invariants.test.ts diff --git a/src/lib/onboard/lifecycle-contracts.md b/src/lib/onboard/lifecycle-contracts.md index 9329ceb3557..fa18520c4cc 100644 --- a/src/lib/onboard/lifecycle-contracts.md +++ b/src/lib/onboard/lifecycle-contracts.md @@ -3,90 +3,164 @@ # Onboarding lifecycle contract map (#6225, epic #6224) -Characterization map of the onboarding and runtime-mutation journeys: where desired state comes from, what is validated before effects, where the first visible and first destructive effects happen, what is checkpointed, where the credential boundary sits, and what compensation exists today. It records current behavior, including behavior the epic flags as a contract gap; nothing here is a target design — targets live in #6226/#6227/#6228 and `machine/README.md`. References are stable symbol + module names, never line numbers. +This is a behavior-preserving inventory of onboarding and runtime-mutation journeys. It records current ownership, effect boundaries, checkpoints, secret handling, recovery, and known gaps; it is not a target design. Target refactors belong to #6226, #6227, and #6228. References use stable symbols and modules rather than line numbers. -Companions: `README.md` (file placement for the `onboard.ts` split), `machine/README.md` (FSM architecture and handler contract), `src/lib/messaging/AGENTS.md` (the messaging package these journeys cross into). +Related guides: [`README.md`](README.md) describes package placement, [`machine/README.md`](machine/README.md) describes the FSM, and [`../messaging/AGENTS.md`](../messaging/AGENTS.md) describes manifest-first messaging. -## Vocabulary +## Shared vocabulary -Epic terminology (from #6224, use verbatim): a **lifecycle contribution** is an internal, data-first input to a plan (policy, provider, package, port-forward, resource, runtime setup), not a public SDK. A **managed agent package** is a package recorded as desired state for an agent runtime; the user-facing managed OpenClaw package lifecycle is #5998's scope, not this epic's. An **agent-native plugin** is interpreted by OpenClaw/Hermes/another agent runtime. **NemoClaw plugin SDK** is reserved for a future versioned external contract that must not be claimed before the #6229 decision record. - -| Verb | Meaning | Current artifact | +| Term | Contract | Current artifact | |---|---|---| -| intent | Deterministic, serializable desired outcome recorded before any effect; logical bindings (env-var names, presence flags), never secret values, temp paths, or handles | `SandboxCreateIntent` (`sandbox-create-intent-types.ts`), produced by the pure `resolveSandboxCreateIntent` (`sandbox-create-plan.ts`) | -| plan | Intent plus observed state, ready to execute; serializable (`SandboxMessagingPlan`) or execution-bound (temp paths, callbacks) | `MessagingWorkflowPlanner.buildPlan` (`src/lib/messaging/compiler/workflow-planner.ts`); `materializeSandboxCreatePlan` (`sandbox-create-plan.ts`) | -| apply | The effectful phase; capabilities (credential values, live handles) bound at apply time, never stored in intent or checkpoints | `bindMessagingTokenDefs` (`sandbox-create-plan.ts`) rebinds real tokens at materialization and fails on drift | -| checkpoint | Durable, secret-free record a later run can resume from | Onboard session (`~/.nemoclaw/onboard-session.json`, `src/lib/state/onboard-session.ts`) + machine snapshot; pre-recreate workspace backups; rebuild backup manifest | -| result | Explicit handler outcome: advance, retry, branch, complete, failed | `OnboardStateResult` (`machine/result.ts`), applied via `OnboardRuntime.applyResult` and the `OnboardRuntimeBoundary` facade (`runtime-boundary.ts`) | -| compensation | Effects after failure/cancel that undo a partial journey | Failed-create sandbox deletion in `createSandbox`; `cancel-rollback.ts`; `rollbackChannelAdd` (`src/lib/actions/sandbox/policy-channel.ts`); rebuild recovery-registry restore (`rebuild-recreate-phase.ts`) | -| reconcile | Re-aligning recorded and live state without a full re-run | Drift detection in `createSandbox`; `reconcileSandboxMessaging` (`machine/handlers/sandbox-messaging.ts`); `mergeOpenClawRestoredConfig` (`src/lib/state/openclaw-config-merge.ts`) | - -## Machine states - -13 states (`machine/definition.ts`); the transition table (`machine/transitions.ts`) is the linear advance chain plus the `inference -> provider_selection` retry, the `sandbox -> openclaw | agent_setup` branch, and every non-terminal state `-> failed`. One production owner per non-terminal state: `machine/handlers/preflight.ts`, `gateway.ts`, `provider-inference.ts` (composite for `provider_selection` + `inference`), `sandbox.ts` (resume decision in `sandbox-resume.ts`, messaging reconciliation in `sandbox-messaging.ts`), `agent-setup.ts` (`openclaw` + `agent_setup`), `policies.ts`, `finalization.ts` (`finalizing` + `post_verify`). `init` is advanced by `onboard()` before the first slice; `complete`/`failed` are terminal. The FSM is deliberately step-granular (`machine/types.ts`): mid-operation resume inside gateway startup, sandbox creation, credential upserts, or policy application is out of scope — the root of several checkpoint gaps below. - -## Journey contracts - -| Journey | Entry point | Desired-state source | First destructive effect | Durable checkpoint | +| **intent** | Deterministic, serializable desired outcome; carries logical bindings, never secret values or live handles | `SandboxCreateIntent` in `sandbox-create-intent-types.ts`, produced by `resolveSandboxCreateIntent` | +| **plan** | Intent plus observed state, ready to apply | `MessagingWorkflowPlanner.buildPlan`; `materializeSandboxCreatePlan` | +| **apply** | Effectful phase that binds credentials and live capabilities | `bindMessagingTokenDefs`; create, rebuild, and mutation executors | +| **checkpoint** | Durable, secret-minimized state from which a later process can continue | onboard session and machine snapshot; registry; backup/recovery manifests | +| **result** | Handler outcome: advance, retry, branch, complete, or fail | `OnboardStateResult`, applied by `OnboardRuntime` through `OnboardRuntimeBoundary` | +| **compensation** | Effect that undoes or limits a partial apply | failed-create deletion, `cancel-rollback.ts`, `rollbackChannelAdd`, recovery-registry restore | +| **reconcile** | Align recorded and live state without replaying the full journey | sandbox drift checks, `reconcileSandboxMessaging`, `mergeOpenClawRestoredConfig` | + +A **lifecycle contribution** is an internal, data-first plan input such as a policy preset, provider binding, package, host forward, resource profile, or runtime setup entry. It is not a public SDK. A **managed agent package** is recorded desired state for an agent runtime. An **agent-native plugin** is interpreted by the selected agent. “NemoClaw plugin SDK” remains reserved for the #6229 decision. + +## Machine ownership + +The 13 states are defined in `machine/definition.ts`; legal edges are defined in `machine/transitions.ts`. + +```text +init -> preflight -> gateway -> provider_selection -> inference +inference --retry--> provider_selection +inference --advance--> sandbox +sandbox --branch--> openclaw -> policies -> finalizing -> post_verify -> complete +sandbox --branch--> agent_setup -> policies -> finalizing -> post_verify -> complete +each nonterminal state --failure--> failed +``` + +Every nonterminal state has one production owner or an explicit internal designation: + +| State | Production owner | +|---|---| +| `init` | Internal entry state advanced by `onboard()` before the first flow slice | +| `preflight` | `machine/handlers/preflight.ts` | +| `gateway` | `machine/handlers/gateway.ts` | +| `provider_selection`, `inference` | `machine/handlers/provider-inference.ts` | +| `sandbox` | `machine/handlers/sandbox.ts`, with resume and messaging decisions delegated to `sandbox-resume.ts` and `sandbox-messaging.ts` | +| `openclaw`, `agent_setup` | `machine/handlers/agent-setup.ts` | +| `policies` | `machine/handlers/policies.ts` | +| `finalizing`, `post_verify` | `machine/handlers/finalization.ts` | +| `complete`, `failed` | Terminal; no handler | + +The FSM checkpoint is step-granular. It cannot resume inside gateway startup, credential upserts, sandbox creation, policy application, or another handler-owned effect group. + +## Effect-order flows + +`*` marks a durable checkpoint and `!` marks the sandbox-delete boundary. In-place destructive effects that occur earlier are called out in the matrix. + +```text +fresh onboard + resolve entry options -> save session/machine* -> host preflight + -> gateway/provider effects -> sandbox-create preflight + -> materialize create plan -> create -> ready -> live validation -> register* + -> finalize session* + +--fresh entry reset + clear prior session (local destructive reset) -> save new session* + -> force base-image resolution -> follow new-onboard or live-recreate flow + +ordinary live recreate + resolve drift/conflicts -> conditional backup* -> provider cleanup -> ! delete + -> remove registry -> materialize plan -> create -> ready -> restore/validate -> register* + +resume drift + load session* -> reject hint conflicts -> validate replacement credential + -> optional early registry removal -> ordinary path conditional backup* -> ! delete + -> remove registry -> materialize plan -> create -> ready -> restore/validate -> register* + +not-ready repair + load session* -> repair event -> ! delete -> remove registry + -> materialize plan -> create -> ready -> validate -> register* + +rebuild / installer upgrade + registry (+ guarded session fallback) -> preflight -> optional backup/recovery manifest* + -> mutation-edge recheck + -> ! delete -> recreate session* -> inner onboard create+register/session* + -> outer restore -> post-restore registry/policy/MCP reconciliation* + +runtime mutation + load registry/session -> command-specific validation+applicable locks + -> mutate gateway/config/registry -> session/audit* + -> optional queued rebuild for changes that require image recreation +``` + +## Journey matrix + +| Journey and entry | Desired state, planning, and assembly | Visible and destructive boundaries | Checkpoint and secret boundary | Compensation, coverage, and gaps | |---|---|---|---|---| -| 1. Sandbox create (fresh onboard) | `onboard()` (`src/lib/onboard.ts`) | Flags + env + prompts of the current run | None against prior state; creation itself at `streamSandboxCreate` | Whole-step session + machine snapshot | -| 2. Rebuild / installer upgrade | `rebuildSandbox` (`rebuild-pipeline.ts` via the `rebuild.ts` facade) | Registry entry + matching session only; ambient env quarantined | `openshell sandbox delete` (`rebuild-destroy-phase.ts`) | Backup manifest + session rewritten as recreate contract + recovery registry snapshot | -| 3. Re-onboard / resume over existing sandbox | Same `onboard()`, live-sandbox block of `createSandbox` | Current run's env/flags/prompts; registry + gateway as drift baseline | Delete + `docker rmi` + registry removal inside `createSandbox` | Pre-recreate workspace backup + session | -| 4. Runtime mutation (provider switch, config set, channels, plugin entries) | `inference-set.ts`, `sandbox/config.ts`, `policy-channel.ts` | CLI flags + registry/session metadata; per-channel delta plans | None in-place; channel changes defer destruction to a queued rebuild | Audit entries + registry plan persistence | - -**Journey 1 — fresh create.** Options resolved by `resolveOnboardEntryOptions` (`entry-options.ts`, auto-resumes an in-progress session); messaging plan compiled by `MessagingWorkflowPlanner.buildPlan` and transported via env `NEMOCLAW_MESSAGING_PLAN_B64` (`MessagingSetupApplier.writePlanToEnv`, `applier/setup-applier.ts`). First externally visible effect: gateway reuse/recover/start (`startGateway`); inference-provider credential upserts (`upsertProvider`) run in `provider_selection`/`inference`, before any sandbox exists. Messaging-provider upserts run with `replaceExisting: true` inside `materializeSandboxCreatePlan`, overwriting same-name entries in shared gateway state. Checkpoints: whole-step session (8 fixed steps, atomic tmp+rename save) plus machine snapshot via `OnboardRuntimeBoundary`; registry registration deferred to post-ready (`registerCreatedSandbox`, `sandbox-registration.ts`) to prevent phantom entries; no sub-step checkpoint. Credential boundary: session stores `credentialEnv` as a name only, redacts `endpointUrl` at save, keeps legacy credential migration as sha256 hashes; intent carries presence flags and env keys, never values; real tokens rebound at apply by `bindMessagingTokenDefs`, fail-closed on availability or provider-type drift. Compensation: readiness failure deletes the failed new sandbox; build-context temp dirs (which can hold env-arg API keys) are cleaned inline with a process-exit safety net; two-key cancel rollback is armed only for a brand-new sandbox and clears the session when it fires (`cancel-rollback.ts`); nonzero exit marks the last started step failed (`exit-step-failure.ts`). Known gap: process death between gateway provider upserts and sandbox create leaves gateway credential state changed with no sandbox. Non-interactive runs share this contract, substituting env defaults and hard aborts (`non-interactive-abort.ts`) for prompts. - -**Journey 2 — rebuild, including installer upgrade** (`upgradeSandboxes` in `src/lib/actions/upgrade-sandboxes.ts` calls `rebuildSandbox(name, ["--yes"], { recoveryManifest, ... })`). Desired state comes from the registry entry + matching session only (`prepareRebuildResumeConfig`, `rebuild-resume-config.ts` — the #5735 pre-delete trust boundary; custom-endpoint URLs fail closed if recorded only in another sandbox's session); ambient `NEMOCLAW_*` selection env is quarantined by `isolateAmbientRecreateEnv` (`rebuild-env-isolation.ts`); messaging is restaged from the registry-persisted plan (`stageRebuildMessagingPlanOrBail` in `rebuild-messaging-phase.ts` -> `buildRebuildPlanFromSandboxEntry` in `workflow-planner.ts`). All validation precedes destruction: `runRebuildPreflightPhase` (`rebuild-preflight-phase.ts`: registry snapshot pinned and re-asserted after confirmation, gateway schema, recovery-manifest validation, confirmation, onboard lock), then `prepareRebuildTargetPreflights` (`rebuild-preflight-target-phase.ts`: target config, recreate options, messaging plan staging, then the #5954 conflict preflight `preflightRebuildMessagingConflicts` with forced non-interactive abort, runtime and base-image checks). DCode rebuilds additionally prebuild and fingerprint the replacement image pre-delete (#6214, `prepareDcodeReplacementBeforeMutation` in `rebuild-dcode-preflight.ts`); mutation-edge revalidation runs immediately before deletion (`revalidatePreparedRecoveryBeforeDelete` in `rebuild-pipeline.ts`; `revalidateDcodeReplacementAtMutationEdge`). First destructive effect: `openshell sandbox delete` in the destroy phase (`rebuild-destroy-phase.ts`), then registry entry removal (entry kept when MCP entries exist, as the durable MCP rebuild transaction). Checkpoints: workspace backup manifest (`runRebuildBackupPhase`, `rebuild-backup-phase.ts`, or a validated installer manifest); session rewritten wholesale as the recreate contract with preflight/gateway pre-marked complete (`rebuild-recreate-phase.ts`); registry snapshot for recovery recreates. On a failed recreate: `markLastStartedStepFailed`, registry-snapshot restore for recovery recreates only, backup path preserved with manual `snapshot restore` instructions, MCP registry restore, shields relocked in the pipeline `finally`. Known gaps: a plain (non-recovery) recreate failure leaves no registry entry; non-DCode rebuilds build the replacement image only after deletion. - -**Journey 3 — re-onboard / resume.** Two sub-modes share `onboard()`: the live-sandbox block of `createSandbox`, and the `--resume` decision `decideSandboxResume` (`machine/handlers/sandbox-resume.ts`: create / reuse / recreate / repair-and-recreate). Desired state is the current run's env/flags/prompts; registry and gateway are only a drift baseline (agent, provider migration, live-probe selection, GPU, Hermes tool-gateway and dashboard, messaging credential rotation). Restore intent (#6130) is keyed on installer env `NEMOCLAW_RESTORE_LATEST_BACKUP_ON_RECREATE=1` (`selectPreUpgradeBackupForCreate` / `resolveNotReadyOutcome`, `not-ready-recreate.ts`); without it a non-interactive not-ready sandbox blocks with hints. Pre-delete validation: the messaging conflict guard, a CPU-sandbox-vs-GPU-request reuse guard, interactive confirm gates, redirection of MCP-managed sandboxes to `rebuild`, and resume conflicts (`getResumeConfigConflicts`, `resume-config.ts` — the recorded sandbox name counts only when the sandbox step completed, #2753) which exit before any effect. Terminal machine snapshots are repaired only per `classifyResumeMachineRepair` (`resume-repair-policy.ts`: failed, or inconsistently reopened complete) by `repairResumeMachineSnapshot` (`resume-machine-repair.ts`). Checkpoint: fail-closed `backupSandboxBeforeRecreate` (`sandbox-backup-on-recreate.ts`; a failed backup aborts unless `NEMOCLAW_RECREATE_WITHOUT_BACKUP=1`; skipped when a pre-upgrade backup is already selected or a not-ready recreate is in progress). Compensation: workspace restore after create; default-sandbox restoration deferred to post-create (#4614); cancel rollback deliberately not armed for recreates; no registry snapshot restore — a failed recreate relies on session + backup + `onboard --resume`. Known gaps: resume identity when the sandbox step never completed (#5961/#5783); interrupted snapshot shapes outside the two repaired classes (#6040); the delete-then-create window below. - -**Journey 4 — runtime mutation.** All mutation is host CLI; the `nemoclaw` OpenClaw plugin TUI is read-only. (4a) Provider/model switch: `runInferenceSet` (`src/lib/actions/inference-set.ts`), serialized by a timer-bound shields mutation lock; validates provider allowlist, model-id charset, registered-agent match, shields-down, and local-provider reachability before any write; writes are ordered and forward-only — gateway route -> registry -> API-family refresh -> in-sandbox config patch (non-fatal) -> session -> audit; no rollback, `rebuild` is the documented repair for degraded states. (4b) Config change: `configSet` (`src/lib/sandbox/config.ts`); dotpath validation, shields-down, `gateway.*` refusal, scalar-ancestor/array clobber refusal, new-key confirmation (#2400), and SSRF validation with DNS-pinned rewrite, then a sha256 compare-and-swap write under the sandbox mutation + shields locks; fail-closed CAS, no compensation needed. (4c) Channels add/remove/start/stop (`addSandboxChannel`, `removeSandboxChannel`, `sandboxChannelsSetEnabled` in `policy-channel.ts`): per-channel delta plans from the registry entry (`workflow-planner.ts`); `checkChannelAddConflict` is a hand-rolled mirror of the onboard conflict guard that uniquely offers `--force` (detection errors fail closed unless forced; pre-enable hook registry-read failures fail soft); gateway upsert/detach, preset apply, and registry plan persistence run immediately but destructive apply is deferred to a queued rebuild (`promptAndRebuild`); compensation via `rollbackChannelAdd`, re-disable on a failed `channels start` preset, a QR-channel remove hard-stop before registry mutation (#3998), and `syncSessionPolicyPresetsWithRegistry` so a later rebuild resume does not revert presets. (4d) Plugin entries (`plugins.entries.*`): written by manifest render targets and the web-search flow at build/rebuild; reconciled at restore by `OPENCLAW_CONFIG_RESTORE_OWNERSHIP` (`openclaw-config-merge.ts`: current generated entries win by id, backup-only user entries kept); direct edits go only through `config set` gates; no plugin CLI (#5998's scope). - -**Agent differences.** The FSM branches `sandbox -> openclaw` for OpenClaw and `sandbox -> agent_setup` for other agents; both rejoin at `policies`. DCode is the only agent with pre-delete replacement-image validation on rebuild (#6214) and is excluded from messaging (no channel manifest supports it; `channels add` rejects it pre-mutation). Hermes adds tool-gateway and dashboard drift axes plus its own rebuild credential preflight. +| **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. 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; registry registration is deferred until readiness and live validation. The session stores credential environment names, redacted endpoint metadata, and legacy-value digests; real values are rebound from the process at apply time. | 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` 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. Recorded `sandboxName` is trusted only after the sandbox step completed. Replacement web-search credentials are checked before `applySandboxResumeDecision`; other create-plan validation can still occur later. | Ordinary live recreation conditionally backs up before provider cleanup, **delete**, image removal, and registry removal. A selected pre-upgrade backup suppresses a new one; an explicit override permits recreation without backup. Some resume-drift decisions remove the registry row earlier. `repair-and-recreate` deletes the not-ready sandbox and row before the normal create path, without the generic backup. Create-plan materialization follows deletion (#6226 gap). | Resume continues the recorded session/machine snapshot; non-resume re-onboard writes a new session first. Backup is fail-closed only when the ordinary path requires a new backup and no bypass is set; it does not protect early repair cleanup. Registration follows readiness, restore, and live validation. Raw credentials remain process/gateway inputs. | Restore failures warn and can still publish the replacement; managed-DCode live-selection failure leaves a running, unregistered sandbox with manual-delete guidance. Cancel rollback is not armed and there is no rebuild-style receipt rollback. Coverage: transition traces and sandbox handler tests. Gaps: #5961/#5783, #6040, early removal/backup asymmetry, and delete-to-register window (#6228). | +| **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/atomic swap (#5801). | +| **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. | +| **Provider, model, or credential-binding change** — `runInferenceSet` | CLI intent plus registry/session metadata. Target resolution and OpenShell preparation occur before locking. The target is re-resolved in the mutating phase under the sandbox lifecycle and timer-bound shields locks; that phase validates provider/model syntax, selected agent, shields state, and local reachability before the first write. | First mutation is the gateway route, then a minimal registry write, API-family/config resolution, registry refresh, best-effort config/hash sync, matching-session update, and audit. An OpenClaw API-family change can then restart the managed gateway after the shields lock is released but while the outer sandbox lock remains held. No sandbox deletion. | Registry and matching session store logical provider/model/credential-environment metadata. Audit records the action, sandbox, and reason rather than credentials; raw values remain gateway-bound. | Forward-only; no rollback. `rebuild` is the repair path for degraded state. Covered by `inference-set*.test.ts`. Gap: several stores can diverge after a mid-sequence failure. | +| **Credential rotation** — `configRotateToken` in `src/lib/sandbox/config.ts` | A session with `credentialEnv` selects the provider and binding. A non-null different `sandboxName` is rejected, but a legacy/null session name is accepted for the requested sandbox. The new value comes from a named environment variable, stdin, or a secret prompt; it is trimmed, then rejected when empty or still containing internal whitespace. | `saveCredential` first stages the value in the current process. OpenShell provider update is the first external mutation, with provider create as a fallback; audit follows. No sandbox deletion. | The logical binding is unchanged, so session and registry are not rewritten. The raw value exists only in process memory/environment and the gateway provider; audit records action/sandbox/reason without the value. | No rollback after a successful provider update; an audit failure can report failure after the credential is already active. Covered by the rotate-token cases in `test/config-set-nested-ssrf.test.ts`. Gap: a null-name legacy session is not strongly bound to the requested sandbox. | +| **Config, policy, resource, port-forward, and runtime setup contributions** — `configSet`; `prepareInitialSandboxCreatePolicy`; `selectResourceProfileForSandbox`; manifest compiler/runtime appliers; dashboard and channel forward helpers | Config uses validated dotpaths and SSRF-safe URL rewriting. Create/rebuild contributions are assembled by `sandbox-create-plan.ts` and `MessagingWorkflowPlanner`: policy presets/keys, resource flags, package/build steps, `hostForward`, runtime node preloads, env aliases, and secret scans. | Config’s first effect is a compare-and-swap sandbox write. Build-time contributions inherit the enclosing create/recreate boundary. Forward helpers can stop an existing forward and start its replacement in place after readiness, without recreating the sandbox. | Durable owners are compact registry messaging/policy/inference metadata, current manifests used for plan rehydration, onboard session, sandbox config/hash, gateway provider state, and shields audit. Resource-profile selection is only a create-time argument, not durable state. Logical bindings are serializable; raw provider values are not. | CAS rejects stale config writes; OpenClaw/Hermes commit config and integrity hashes together, while other agents may refresh a path hash afterward. Audit and optional restart are post-commit and forward-only. Forward recovery can re-establish declared forwards. Gaps: no cross-contribution transaction/checkpoint, and resource choice is not persisted. | -## Create-path ordering contract +## Agent-specific differences -Inside `createSandbox` (`src/lib/onboard.ts`), on the shared create/recreate path. This prose is the authoritative record of the ordering; per cv review of PR #6259 it deliberately has no source-scanning test — executable coverage belongs to the issue that introduces a behavioral seam (#6226/#6228). +| Agent | Lifecycle difference | +|---|---| +| OpenClaw | `sandbox -> openclaw`; supports messaging render targets and OpenClaw config/plugin reconciliation. | +| Hermes | `sandbox -> agent_setup`; adds auth method, tool-gateway, dashboard, and credential-preflight drift axes. | +| Deep Agents Code (DCode) | `sandbox -> agent_setup`. Onboard filters unsupported channel selections, rebuild clears/skips messaging state, and `channels add` rejects DCode. Its specialized preflight replaces the generic image preflight; a normal live rebuild proves managed context and selected route at the delete edge, while recovery skips the live-route proof (`rebuild-dcode-preflight.ts`, #6214). | -1. **Validation order (all deterministic work before any destructive effect):** `validateName` fixes the sandbox name; `prepareSandboxMessagingPreflight` (`sandbox-messaging-preflight.ts`) resolves disabled channels, runs the shared conflict guard `enforceMessagingChannelConflicts` (`messaging-conflict-guard.ts`) against the env plan (only when that plan names this sandbox) with the onboard-specific interactive "Continue anyway?" wiring, and aborts when a selected web-search credential is missing from the process; drift detection, reuse fast paths (which return before the destructive boundary — a reused sandbox is never deleted), and interactive confirm gates follow; then `selectPreUpgradeBackupForCreate` (`not-ready-recreate.ts`) and the fail-closed `backupSandboxBeforeRecreate` (`sandbox-backup-on-recreate.ts`). -2. **Conflict guard before delete:** the messaging conflict guard is the #5954 contract on this path — it completes before the destructive boundary, unlike pre-#5955 rebuild. -3. **Destructive boundary (recreate only), strictly ordered:** `runSandboxProviderPreDeleteCleanup` -> `openshell sandbox delete` -> `docker rmi` of the previous image -> `registry.removeSandbox`. -4. **Cleanup before upsert, post-delete:** `prepareSandboxCreatePlan` (`sandbox-create-plan.ts`) runs after the delete, so the pure `resolveSandboxCreateIntent` and the fail-closed credential-binding check in `materializeSandboxCreatePlan` (`bindMessagingTokenDefs`) validate only after the old sandbox is gone — a binding drift halts all gateway writes but cannot restore the sandbox (pinned gap, #6226). Inside materialization the tolerant provider-cleanup re-run (`tolerateMissingSandbox: true`; the sandbox no longer exists) precedes the gateway messaging upsert (`replaceExisting: true`). Then `streamSandboxCreate`, the readiness gate (`waitForCreatedSandboxReadyWithTrace`; failure deletes the new sandbox — the only other delete call site — and exits with retry hints), post-ready `registerCreatedSandbox`, and the pending workspace-backup restore. -5. **Delete-then-create window:** between `registry.removeSandbox` and post-ready `registerCreatedSandbox` there is no durable record of the selected sandbox identity; process death in this window leaves neither a sandbox nor a registry entry (checkpoint gap; #6228). +## Persisted field ownership -## Persisted state and field ownership +The schema and sanitation authority is `Session` plus `normalizeSession`/`filterSafeUpdates` in `src/lib/state/onboard-session.ts`. `undefined` in an update means “leave unchanged”; accepted `null` means “clear.” On disk, many nullable fields still collapse never selected, explicitly declined, and explicitly cleared into the same `null` representation. That ambiguity is a #6228 contract gap, not an endorsed target. -`~/.nemoclaw/onboard-session.json` is owned by `src/lib/state/onboard-session.ts` and written through `OnboardRuntimeBoundary` during onboard; rebuild rewrites it wholesale as the recreate contract. Step helpers default to record-only (`RECORD_ONLY_STEP_MUTATION_OPTIONS`, `src/lib/state/onboard-step-mutation.ts`); `LEGACY_MACHINE_STEP_MUTATION_OPTIONS` remains the escape hatch that also moves the machine snapshot (exit backstop, rebuild). The registry is owned by `src/lib/state/registry.ts`; the machine snapshot `{version, state, stateEnteredAt, revision}` by `OnboardRuntime`. Pinned ambiguity, not endorsed: `null` is overloaded across session fields (unset vs declined vs cleared); explicit-clear semantics exist only for the `filterSafeUpdates` whitelist (the #2625 null-vs-undefined contract in `onboard-session.ts`); explicit modeling is #6228's mandate, sandbox-identity nullability is #5783/PR #5860. - -## Divergences (duplicated decision points) - -Recommended owners name where a single decision should live; alignment belongs to the referenced child issues. - -1. **Messaging desired state has four sources by path** — onboard env plan (`MessagingSetupApplier.writePlanToEnv`), rebuild registry plan (`buildRebuildPlanFromSandboxEntry`), resume-reuse fallback chain in `reconcileSandboxMessaging` (recorded channels -> env plan -> registry plan -> `session.messagingPlan`), single-channel deltas for mutations; owner: the registry-persisted plan (#6226/#6228). -2. **Ambient env polarity is inverted** — onboard treats `NEMOCLAW_PROVIDER`/`MODEL`/`ENDPOINT_URL` as intent; rebuild quarantines exactly those (`isolateAmbientRecreateEnv`) and pins intent from registry + session (`prepareRebuildResumeConfig`, #5735); owner: one target-resolution module (#6226). -3. **One conflict-guard engine, three wirings** — onboard interactive continue (`enforceMessagingChannelConflicts`), rebuild forced non-interactive abort (`preflightRebuildMessagingConflicts`, #5954), channels' hand-rolled `checkChannelAddConflict` with `--force`; owner: `messaging-conflict-guard.ts` taking per-path policy declaratively. -4. **Backup/restore intent differs per path** — rebuild always backs up and auto-restores including presets; re-onboard backs up fail-closed but restores only workspace state; the not-ready path restores only under the installer flag (#6130); channel mutations checkpoint nothing; owner: one backup/restore policy module (#6228). -5. **Registry lifecycle asymmetry** — create registers post-ready only; rebuild removes at destroy and snapshot-restores only for recovery recreates; re-onboard removes with no snapshot restore; owner: `sandbox-registration.ts`; durable pre-create identity is #6228. -6. **Pre-delete replacement validation exists only for DCode rebuilds** (#6214, `rebuild-dcode-preflight.ts`); non-DCode rebuilds build the real image after deletion, onboard/re-onboard entirely post-delete; full build-verify-swap atomicity is #5801's scope, outside this epic. -7. **Policy-preset reconciliation exists only on rebuild** — onboard writes `appliedPolicies` once at registration; channel commands mirror presets via `syncSessionPolicyPresetsWithRegistry`; owner: the `policy-preset-persistence`/`policy-preset-sync` modules. - -## Bug to contract-gap map - -| Issue | Symptom | Contract gap | Status | -|---|---|---|---| -| #5961 | Interrupted non-interactive onboard cannot resume safely | Checkpoint gap: no durable sandbox identity or effect-group metadata before the interruptible create step | Open; targeted by #6227/#6228 | -| #6040 | `onboard --resume` aborts on macOS/DGX Spark | Recovery gap: only `failed` and inconsistently-reopened-`complete` snapshots are repaired (`classifyResumeMachineRepair`) | Open; targeted by #6227 | -| #6179 | Invalid FSM transition attempted after successful sandbox creation | Transition-graph gap: stale handler results are skipped by `recordStateResultWithStepCompatibility` (`runtime-boundary.ts`) instead of rejected or recomputed | Open; targeted by #6227 | -| #5954 | Rebuild detected a messaging credential conflict only after destroying the sandbox | Plan-before-effects gap in rebuild preflight ordering | Fixed by PR #5955; guard now runs in `rebuild-preflight-target-phase.ts`, before every destructive phase | -| #6099 | Healthy sandbox rolled back after a late dashboard-forward failure | Compensation-scope gap: post-ready, non-destructive failures sit inside a destructive rollback window (`ensureDashboardForward` with `rollbackSandboxOnFailure`) | Open; in-flight PR #6116 (`forward-start.ts`) | -| #6195 | Rebuild deleted a DCode sandbox before validating that recreation could succeed | Plan-before-effects gap at rebuild's destructive boundary | Fixed by PR #6214; see divergence 6 | - -## Merged and in-flight work +| Field group | Fields | Writer/owner and state meaning | +|---|---|---| +| Session envelope | `version`, `sessionId`, `mode`, `startedAt`, `updatedAt`, `status`, `resumable` | `createSession`, save/update helpers, and completion/failure paths. Values are always known after creation. | +| Progress and recovery | `lastStepStarted`, `lastCompletedStep`, `failure`, `steps`, `machine` | Step-mutation helpers and `OnboardRuntime`; nullable progress fields mean no recorded value, not a separately modeled decline. | +| Target identity | `agent`, `sandboxName`, `metadata.gatewayName`, `metadata.fromDockerfile` | Onboard selection, sandbox handler/registration, and rebuild session preparation. Nullable identity currently conflates unset/cleared; a completed sandbox step is the trust gate for recorded name. | +| Inference intent | `provider`, `model`, `endpointUrl`, `credentialEnv`, `preferredInferenceApi`, `compatibleEndpointReasoning`, `nimContainer`, `webSearchConfig` | Provider/inference handlers and `runInferenceSet`. Known credential state is an environment-variable name or presence metadata, never the value. `redactUrl` masks userinfo, fragments, and sensitive-named parameters, but token-shaped values under benign parameter names remain a pending #6224 gap. | +| Agent and policy intent | `hermesAuthMethod`, `toolDisclosure`, `hermesToolGateways`, `policyPresets` | Agent setup and policy handling. Channel commands update matching-session `policyPresets` only best-effort. Nullable fields conflate unset, declined, and cleared where the CLI makes those distinctions. | +| Messaging intent | `messagingPlan`, `telegramConfig`, `wechatConfig` | Onboard/rebuild write the session plan; channel commands instead own the compact registry plan. `telegramConfig` and `wechatConfig` are legacy fallback/preserved fields, while current channel input comes from the plan/manifests. Tokens stay outside the session. | +| Runtime metadata | `routerPid`, `routerCredentialHash`, `gpuPassthrough` | Router and sandbox setup/recovery. PID is a live-process hint; credential hash is a digest; GPU is a concrete boolean. | +| Legacy migration proof | `migratedLegacyValueHashes` | Onboard legacy migration writes SHA-256 digests keyed by environment name; session filtering guarantees string records but does not independently validate digest shape. | + +The registry is separately owned by `src/lib/state/registry.ts`; backup/recovery manifests are owned by their rebuild and recreate modules. Step helpers normally use `RECORD_ONLY_STEP_MUTATION_OPTIONS`; `LEGACY_MACHINE_STEP_MUTATION_OPTIONS` is the compatibility path that also moves the machine snapshot. + +## Duplicated decision points + +1. **Messaging intent source:** onboard environment plan, rebuild registry plan, resume fallback chain, and channel delta plans. Recommended owner: registry-persisted plan (#6226/#6228). +2. **Ambient environment policy:** onboard treats provider/model variables as intent; rebuild quarantines ambient selection except for narrowly target-scoped legacy recovery. Recommended owner: one target-resolution module (#6226). +3. **Conflict policy:** onboard and rebuild share `enforceMessagingChannelConflicts` with different prompt/abort policies; channel add uses the separate hand-built `checkChannelAddConflict` with `--force`. Recommended owner: one declarative conflict policy. +4. **Backup/restore policy:** rebuild and ordinary live recreate back up, while not-ready resume repair deletes before the generic backup; installer restore and channel mutation checkpoint different state again. Recommended owner: one backup/restore policy module (#6228). +5. **Registry lifecycle:** create registers post-ready; rebuild records removals and restores retry metadata through `rebuild-registry-rollback.ts`; some resume decisions remove the row before backup/create preparation and have no receipt-based compensation. Recommended owner: `sandbox-registration.ts` plus durable pre-create identity (#6228). +6. **Replacement validation:** generic rebuild retains and fingerprints a successfully built context; normal live DCode rebuild adds route and managed-context proofs; re-onboard still stages the replacement after delete. Health-before-delete and atomic swap remain #5801. +7. **Policy reconciliation:** registration records create-time presets, `handlePoliciesState` later persists the reconciled live set, and channel mutations synchronize their own plan/session preset state. Recommended owner: policy preset persistence/sync modules. + +## Bug-to-contract-gap map + +| Issue | Gap | Current status | +|---|---|---| +| #5961 | Interrupted onboard lacks durable sandbox identity/effect-group metadata | Open; #6227/#6228 | +| #6040 | Only selected malformed terminal snapshots are repaired | Open; #6227 | +| #6179 | Stale handler results can reach an invalid transition | Open; #6227 | +| #5954 | Rebuild conflict was discovered after delete | Fixed by #5955 | +| #6099 | Late dashboard-forward failure could roll back a healthy sandbox | Open; #6116 | +| #6195 | DCode rebuild deleted before replacement validation | Fixed by #6214 | -- **PR #6218** (merged) separated the secret-free `SandboxCreateIntent` from effectful materialization and kept the `prepareSandboxCreatePlan` compatibility surface; it deliberately did not move intent resolution ahead of the destructive boundary, persist intent, or define a machine-event/public contract — those are #6226, #6228, #6229. -- **PR #6214** (merged) added DCode pre-delete replacement validation (#6195); **PR #5955** (merged) moved the rebuild messaging conflict check before destruction (#5954). -- In flight — do not treat recovery/resume semantics as frozen: **PR #6253** (recovery-path refactor toward #6227; coordinate before touching `resume-machine-repair.ts`, `session-bootstrap.ts`, `machine/transitions.ts`, `exit-step-failure.ts`), **PR #6116** (dashboard-forward rollback scope, #6099), **PR #5860** (null sandbox identity, #5783). +PR #6218 separated secret-free create intent from effectful materialization. PR #6214 added DCode-specific pre-delete replacement validation; generic rebuild now also retains and revalidates a prebuilt context. PR #5955 moved the rebuild messaging conflict check before destruction. The remaining ownership and recovery changes belong to the open child issues and should update this map and its focused traces when behavior intentionally changes. -## Characterization tests +## Characterization coverage -Path-level machine transition traces are pinned by `machine/transition-traces.test.ts` (see the "Characterization traces" section of `machine/README.md`). They assert current behavior, including orderings this document flags as gaps; when #6226/#6227/#6228 intentionally change an ordering, update the pinned trace in the same PR and reference the child issue in the test title. +| Contract | Executable evidence | Uncovered boundary | +|---|---|---| +| Fresh, resumed, recreate, successful, and failed machine event order | `machine/transition-traces.test.ts` | Sub-step crash recovery and end-to-end delete-to-register effects | +| Detailed recreate decisions and repair branches | `machine/handlers/sandbox-resume.test.ts`, `machine/handlers/sandbox.test.ts` | Cross-handler effect transaction | +| Legal edges, result kinds, runtime event shapes, runner sequencing | `machine/transitions.test.ts`, `machine/runtime.test.ts`, `machine/runner*.test.ts` | None at the unit boundary | +| Create intent/provider ordering and fail-closed credential drift | `sandbox-create-plan.test.ts` | Cross-module pre-delete ordering has no behavioral seam | +| Messaging conflict validation before recreate | `sandbox-messaging-preflight.test.ts`, rebuild preflight tests | One shared declarative policy across all callers | +| Resume identity | `test/onboard.test.ts`, `handlers/sandbox-resume.test.ts` | Interrupted live-flow identity (#5961) | +| Session sanitation and no-secret persistence | `src/lib/state/onboard-session.test.ts` | Benign-name token-shaped URL values (#6224); unset/declined/cleared modeling (#6228) | + +When a child issue changes one of these contracts, update the map and the narrow owning test in that same PR. Do not add source-text scans or production scaffolding solely to preserve current orchestration order. diff --git a/src/lib/onboard/machine/README.md b/src/lib/onboard/machine/README.md index c2fcd0d8bae..1b11fb02765 100644 --- a/src/lib/onboard/machine/README.md +++ b/src/lib/onboard/machine/README.md @@ -122,4 +122,4 @@ The FSM migration is considered complete when: ## Characterization traces -`transition-traces.test.ts` in this directory pins a small set of path-level machine traces that the unit suites (`transitions.test.ts`, `runtime.test.ts`, `runner.test.ts`) do not already cover (#6225). Update a pinned trace only in the same PR as an intentional behavior change (for example #6226, #6227, or #6228), never as a side effect. The journey-level lifecycle contract map lives in [`../lifecycle-contracts.md`](../lifecycle-contracts.md). +`transition-traces.test.ts` in this directory pins fresh, resumed, recreate, and failed path-level event streams that the unit suites (`transitions.test.ts`, `runtime.test.ts`, `runner.test.ts`) do not already cover (#6225). The recreate trace composes the runner with the real sandbox handler seam; detailed selection and repair cases remain in `handlers/sandbox-resume.test.ts` and `handlers/sandbox.test.ts`. Update a pinned trace only in the same PR as an intentional behavior change (for example #6226, #6227, or #6228), never as a side effect. The journey-level lifecycle contract map lives in [`../lifecycle-contracts.md`](../lifecycle-contracts.md). diff --git a/src/lib/onboard/machine/transition-traces.test.ts b/src/lib/onboard/machine/transition-traces.test.ts index 7cbc3193c9b..e4234ac64af 100644 --- a/src/lib/onboard/machine/transition-traces.test.ts +++ b/src/lib/onboard/machine/transition-traces.test.ts @@ -9,7 +9,7 @@ * handler sequencing without observing events). Descriptive, not * aspirational: update a pin in the same PR that changes the ordering. * Recovery-path semantics (edges leaving terminal `failed`, the legacy - * step-mutation bridge) stay out of scope — PR #6253 pins those. + * step-mutation bridge) stay out of scope and are owned by #6227. */ import { describe, expect, it, vi } from "vitest"; @@ -26,6 +26,8 @@ import { sanitizeFailure, } from "../../state/onboard-session"; import type { OnboardMachineEvent } from "./events"; +import { handleSandboxState } from "./handlers/sandbox"; +import { baseOptions, createDeps } from "./handlers/sandbox-test-fixtures"; import { advanceTo, branchTo, completeOnboardMachine, failOnboardMachine } from "./result"; import { type OnboardStateHandlers, runOnboardMachine } from "./runner"; import { OnboardRuntime, type OnboardRuntimeDeps } from "./runtime"; @@ -114,16 +116,6 @@ function fullRunHandlers( } describe("onboard machine lifecycle traces (#6225)", () => { - it("persists in-place edits from a void-returning session mutator (#6225)", async () => { - const { runtime, updateSession } = createTracedRuntime(); - - updateSession((draft) => { - draft.sandboxName = "void-mutated"; - }); - - await expect(runtime.session()).resolves.toMatchObject({ sandboxName: "void-mutated" }); - }); - it("emits the fresh-run lifecycle event stream in canonical order (#6225)", async () => { const { runtime, events } = createTracedRuntime(); await runtime.start(); @@ -217,42 +209,52 @@ describe("onboard machine lifecycle traces (#6225)", () => { expect(run.session.steps.sandbox.status).toBe("complete"); }); - it("re-runs the sandbox state with repair events around recreate before branching (#6225)", async () => { - // Machine snapshot back at `sandbox` while the recorded sandbox step is - // still marked complete: the shape a resumed session has when the recorded - // sandbox exists but is not ready and must be recreated. - const staleSession = createSession({ + it("repairs and recreates through the sandbox handler before branching (#6225)", async () => { + const resumedSession = createSession({ sandboxName: "my-assistant", lastCompletedStep: "sandbox", machine: machineAt("sandbox", 5), steps: { sandbox: completedStep() }, }); - const { runtime, events } = createTracedRuntime(staleSession); - const repairMetadata = { repair: "recorded-sandbox-cleanup", sandboxName: "my-assistant" }; - const repair = (type: "state.repair.started" | "state.repair.completed") => - runtime.emitRepairEvent(type, { state: "sandbox", metadata: repairMetadata }); + const { runtime, events, updateSession } = createTracedRuntime(resumedSession); + const { calls, deps } = createDeps({ + getSandboxReuseState: () => "not_ready", + updateSession, + recordRepairEvent: (type, options) => runtime.emitRepairEvent(type, options), + recordStepComplete: async (_stepName, updates) => + updateSession((current) => { + Object.assign(current, filterSafeUpdates(updates)); + }), + }); + await runtime.start({ resumed: true }); + const session = await runtime.session(); const run = await runOnboardMachine({ context: null, runtime, handlers: { sandbox: async () => { - await repair("state.repair.started"); - await repair("state.repair.completed"); - return branchTo("openclaw", { updates: { sandboxName: "my-assistant" } }); + const handled = await handleSandboxState({ + ...baseOptions(deps, session), + resume: true, + session, + sandboxName: "my-assistant", + }); + return handled.stateResult; }, }, stopStates: ["openclaw"], }); + expect(calls.repairSandbox).toHaveBeenCalledWith("my-assistant"); + expect(calls.createSandbox).toHaveBeenCalledOnce(); expect(traceOf(events)).toEqual([ + "onboard.resumed:sandbox", "state.repair.started:sandbox", "state.repair.completed:sandbox", - "context.updated:sandbox", "state.exited:sandbox", "state.entered:openclaw", ]); - expect(events[0].metadata).toEqual(repairMetadata); expect(run.session).toMatchObject({ status: "in_progress", sandboxName: "my-assistant", @@ -263,6 +265,7 @@ describe("onboard machine lifecycle traces (#6225)", () => { it("stops at the failing inference step and records the failure envelope (#6225)", async () => { const { runtime, events } = createTracedRuntime(); const sandboxHandler = vi.fn(() => branchTo("openclaw")); + await runtime.start(); const run = await runOnboardMachine({ context: null, @@ -283,6 +286,7 @@ describe("onboard machine lifecycle traces (#6225)", () => { machine: { state: "failed", revision: 5 }, }); expect(traceOf(events)).toEqual([ + "onboard.started:init", "state.exited:init", "state.entered:preflight", "state.exited:preflight", diff --git a/src/lib/state/onboard-session.test.ts b/src/lib/state/onboard-session.test.ts index 491420f4dd7..1664ac1b0d9 100644 --- a/src/lib/state/onboard-session.test.ts +++ b/src/lib/state/onboard-session.test.ts @@ -534,9 +534,10 @@ describe("onboard session", () => { // ── Session secret boundary, consolidated from #6225 (epic #6224) ── - it("persists migratedLegacyValueHashes as sha256 hex digests only, dropping non-string entries (#6225)", () => { + it("round-trips writer-shaped legacy migration hashes and drops non-string entries (#6225)", () => { // Digest shape mirrors legacyValueHash() in src/lib/onboard.ts, the only - // production writer of this map. Only the digest may reach disk. + // production writer of this map. This test covers session filtering and + // persistence; the writer owns converting credential values to digests. const legacyValue = "nvapi-sentinel6225-legacy-value-do-not-persist"; const digest = createHash("sha256").update(legacyValue).digest("hex"); session.saveSession(session.createSession()); @@ -553,16 +554,16 @@ describe("onboard session", () => { }); const raw = fs.readFileSync(session.SESSION_FILE, "utf8"); - expect(raw).not.toContain(legacyValue); + expect(raw).toContain(digest); expect(raw).not.toContain("BROKEN_NUMERIC"); const loaded = requireLoadedSession(session.loadSession()); expect(loaded.migratedLegacyValueHashes).toEqual({ NVIDIA_API_KEY: digest }); expect(loaded.migratedLegacyValueHashes?.NVIDIA_API_KEY).toMatch(/^[0-9a-f]{64}$/); }); - it("serializes unset and explicitly-declined credentialEnv identically as null (#6224)", () => { - // #6224 contract gap: on disk, "never prompted" and "user declined" both - // collapse to credentialEnv: null, so a resume cannot tell them apart. + it("serializes missing and explicit-null credentialEnv identically (#6224)", () => { + // #6224 contract gap: the schema cannot distinguish "never prompted", + // "user declined", and "explicitly cleared" once they become null. session.saveSession(session.createSession()); const unset = JSON.parse(fs.readFileSync(session.SESSION_FILE, "utf8")).credentialEnv; @@ -578,19 +579,9 @@ describe("onboard session", () => { expect(requireLoadedSession(session.loadSession()).credentialEnv).toBeNull(); }); - it.fails("redacts token-shaped values under benign endpoint query param names (#6224)", () => { - // DESIRED behavior, not yet implemented: redactUrl() only masks - // sensitive-NAMED query params, so a token-shaped value under a benign - // name persists verbatim today. Flip to a plain `it` once epic #6224 - // adds value-shape redaction for parseable URLs. - const tokenValue = "nvapi-pending6224-token-shaped-value"; - session.saveSession(session.createSession()); - markStepCompleteLegacy(session, stepMutation, "provider_selection", { - endpointUrl: `https://api.example.com/v1?model=${tokenValue}`, - }); - - expect(fs.readFileSync(session.SESSION_FILE, "utf8")).not.toContain(tokenValue); - }); + // Desired behavior tracked by #6224. redactUrl() currently masks sensitive + // parameter names but not token-shaped values under otherwise benign names. + it.todo("redacts token-shaped values under benign endpoint query param names (#6224)"); it("only persists known Hermes auth methods", () => { session.saveSession(session.createSession()); diff --git a/test/onboard-lifecycle-invariants.test.ts b/test/onboard-lifecycle-invariants.test.ts deleted file mode 100644 index f7256b087ec..00000000000 --- a/test/onboard-lifecycle-invariants.test.ts +++ /dev/null @@ -1,394 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 -// -// Characterization baseline for the onboarding create-path lifecycle (#6225, -// epic #6224). Pins CURRENT main behavior at the injectable decision seams: -// the sandbox messaging preflight (hosting the #5954-shared conflict guard), -// the sandbox create plan (whose materialization performs the gateway -// messaging upsert), and the resume identity predicate behind #2753. A -// regression baseline, not an endorsement: later children (#6226/#6227/#6228) -// are expected to change some pins deliberately. -// -// The cross-module ordering of the non-hermetic `createSandbox` orchestration -// in src/lib/onboard.ts has no behavioral seam today; it is documented in -// src/lib/onboard/lifecycle-contracts.md, with executable coverage deferred -// to the issue that introduces the seam. - -import { describe, expect, it, vi } from "vitest"; - -import type { SandboxMessagingPlan } from "../src/lib/messaging/manifest/types.js"; -import type { MessagingConflictGuardDeps } from "../src/lib/onboard/messaging-conflict-guard.js"; -import type { - CreateSandboxMessagingPrepResult, - MessagingTokenDef, -} from "../src/lib/onboard/messaging-prep.js"; -import { - getResumeConfigConflicts, - getResumeSandboxConflict, -} from "../src/lib/onboard/resume-config.js"; -import { - materializeSandboxCreatePlan, - prepareSandboxCreatePlan, - resolveSandboxCreateIntent, - resolveSandboxCreateMessagingProviderRequests, -} from "../src/lib/onboard/sandbox-create-plan.js"; -import type { SandboxGpuCreateConfig } from "../src/lib/onboard/sandbox-gpu-create.js"; -import { - prepareSandboxMessagingPreflight, - type SandboxMessagingPreflightDeps, - type SandboxMessagingPreflightInput, -} from "../src/lib/onboard/sandbox-messaging-preflight.js"; - -// ── Shared fixtures ───────────────────────────────────────────────────────── - -const telegramChannel = { - name: "telegram", - envKey: "TELEGRAM_BOT_TOKEN", - label: "Telegram", - description: "Telegram", - help: "Telegram", -}; - -const telegramTokenDef: MessagingTokenDef = { - name: "sandbox-telegram-bridge", - envKey: "TELEGRAM_BOT_TOKEN", - token: "telegram-token", -}; - -const sandboxGpuConfig: SandboxGpuCreateConfig = { - sandboxGpuEnabled: true, - sandboxGpuDevice: "nvidia.com/gpu=0", -}; - -class OnboardAbortError extends Error { - constructor(readonly code: number) { - super(`onboard aborted with exit code ${code}`); - } -} - -// ── 1. Messaging conflict guard wiring inside the sandbox messaging preflight ── -// -// The preflight is the injectable module the create path runs before any -// destructive effect. It hosts the shared messaging conflict guard (#5954) -// with the onboard-specific interactive wiring: a "Continue anyway?" prompt is -// allowed here, unlike the rebuild preflight's forced non-interactive abort. - -function buildMessagingPrepResult( - overrides: Partial = {}, -): CreateSandboxMessagingPrepResult { - return { - disabledChannelNames: new Set(), - messagingTokenDefs: [], - extraPlaceholderKeys: [], - hasMessagingTokens: false, - reusableMessagingProviders: [], - reusableMessagingChannels: [], - missingWebSearchCredentialEnv: null, - ...overrides, - }; -} - -function buildPreflightHarness({ - planSandboxName = "sandbox-a", - prepResult = buildMessagingPrepResult(), -}: { - planSandboxName?: string; - prepResult?: CreateSandboxMessagingPrepResult; -} = {}) { - const events: string[] = []; - const exits: number[] = []; - const errorLines: string[] = []; - const guardDepsSeen: MessagingConflictGuardDeps[] = []; - const envPlan = { - schemaVersion: 1, - sandboxName: planSandboxName, - disabledChannels: [], - } as unknown as SandboxMessagingPlan; - const promptYesNoOrDefault = vi.fn(async () => true); - const deps: SandboxMessagingPreflightDeps = { - readMessagingPlanFromEnv: vi.fn(() => envPlan), - resolveDisabledChannels: vi.fn(() => { - events.push("resolve-disabled-channels"); - return ["slack"]; - }), - gatewayName: "nemoclaw", - registry: {} as SandboxMessagingPreflightDeps["registry"], - providerExistsInGateway: vi.fn(() => true), - isNonInteractive: () => false, - promptYesNoOrDefault, - cliName: () => "nemoclaw", - log: vi.fn(), - error: vi.fn((message: string) => { - errorLines.push(message); - }), - exitProcess: (code: number): never => { - exits.push(code); - throw new OnboardAbortError(code); - }, - getValidatedMessagingTokenByEnvKey: vi.fn(() => null), - getCredential: vi.fn(() => null), - normalizeCredentialValue: (value: unknown) => String(value ?? ""), - registerExtraPlaceholderProviders: vi.fn(() => []), - getMessagingChannelForEnvKey: vi.fn(() => null), - prepareCreateSandboxMessaging: vi.fn(() => { - events.push("prepare-messaging"); - return prepResult; - }), - enforceMessagingChannelConflicts: vi.fn(async (guardDeps: MessagingConflictGuardDeps) => { - events.push("conflict-guard"); - guardDepsSeen.push(guardDeps); - }), - }; - const input: SandboxMessagingPreflightInput = { - sandboxName: "sandbox-a", - agentName: "openclaw", - channels: [telegramChannel], - enabledChannels: ["telegram"], - webSearchConfig: null, - env: {}, - }; - return { deps, input, events, exits, errorLines, guardDepsSeen, promptYesNoOrDefault, envPlan }; -} - -describe("messaging conflict guard wiring in prepareSandboxMessagingPreflight (#6225)", () => { - it("runs the conflict guard against the matching env plan before preparing messaging state (#6225)", async () => { - const harness = buildPreflightHarness(); - - const result = await prepareSandboxMessagingPreflight(harness.input, harness.deps); - - expect(harness.events).toEqual([ - "resolve-disabled-channels", - "conflict-guard", - "prepare-messaging", - ]); - expect(harness.guardDepsSeen[0]?.sandboxName).toBe("sandbox-a"); - expect(harness.guardDepsSeen[0]?.gatewayName).toBe("nemoclaw"); - expect(harness.guardDepsSeen[0]?.currentPlan).toBe(harness.envPlan); - expect(harness.guardDepsSeen[0]?.currentSandboxDisabledChannels).toEqual(["slack"]); - expect(result.disabledChannels).toEqual(["slack"]); - }); - - it("skips the conflict guard when the env plan belongs to a different sandbox (#6225)", async () => { - const harness = buildPreflightHarness({ planSandboxName: "other-sandbox" }); - - await prepareSandboxMessagingPreflight(harness.input, harness.deps); - - expect(harness.events).toEqual(["resolve-disabled-channels", "prepare-messaging"]); - expect(harness.guardDepsSeen).toEqual([]); - }); - - // Onboard-vs-rebuild divergence pinned for #6225: this path hands the guard - // an interactive continue prompt; the rebuild preflight (#5954) forces a - // non-interactive abort instead. - it("wires an interactive continue prompt and the onboard exit into the conflict guard (#6225)", async () => { - const harness = buildPreflightHarness(); - - await prepareSandboxMessagingPreflight(harness.input, harness.deps); - const guardDeps = harness.guardDepsSeen[0] as MessagingConflictGuardDeps; - const continueAnswer = await guardDeps.promptContinue(); - - expect(continueAnswer).toBe(true); - expect(harness.promptYesNoOrDefault).toHaveBeenCalledWith(" Continue anyway?", null, false); - expect(guardDeps.exit).toBe(harness.deps.exitProcess); - }); - - it("aborts with exit code 1 when the web search credential is missing from the process (#6225)", async () => { - const harness = buildPreflightHarness({ - prepResult: buildMessagingPrepResult({ missingWebSearchCredentialEnv: "BRAVE_API_KEY" }), - }); - - await expect(prepareSandboxMessagingPreflight(harness.input, harness.deps)).rejects.toThrow( - OnboardAbortError, - ); - - expect(harness.exits).toEqual([1]); - expect(harness.errorLines[0]).toContain("BRAVE_API_KEY is not available in this process"); - expect(harness.errorLines[1]).toContain("disable web search before recreating the sandbox"); - }); -}); - -// ── 2. Gateway messaging upsert ordering inside the create plan ──────────── -// -// On the create path this module runs AFTER the destructive delete (see -// src/lib/onboard/lifecycle-contracts.md). Inside the plan itself, -// deterministic intent resolution and credential-binding validation complete -// before any gateway effect, and the tolerant cleanup re-run precedes the -// credential upsert. - -describe("gateway messaging upsert ordering in the sandbox create plan (#6225)", () => { - it("re-runs provider cleanup before upserting messaging credentials with replaceExisting (#6225)", () => { - const events: string[] = []; - const upsertMessagingProviders = vi.fn( - (_tokenDefs: MessagingTokenDef[], _options: { replaceExisting: true }) => { - events.push("gateway-upsert"); - return ["sandbox-telegram-bridge"]; - }, - ); - - const result = prepareSandboxCreatePlan({ - basePolicyPath: "/repo/policy.yaml", - buildCtx: "/tmp/nemoclaw-build-1", - sandboxName: "sandbox", - channels: [telegramChannel], - enabledChannels: ["telegram"], - disabledChannelNames: new Set(), - messagingTokenDefs: [telegramTokenDef], - reusableMessagingChannels: [], - reusableMessagingProviders: [], - hermesToolGateways: [], - sandboxGpuConfig, - dockerDriverGateway: true, - appendResourceFlags: (args) => { - events.push("resource-flags"); - args.push("--memory", "16g"); - }, - runProviderPreDeleteCleanup: () => { - events.push("pre-delete-cleanup-re-run"); - }, - upsertMessagingProviders, - getMessagingChannelForEnvKey: (envKey) => - envKey === "TELEGRAM_BOT_TOKEN" ? "telegram" : null, - getHermesToolGatewayProviderName: vi.fn(), - policyTier: null, - deps: { - resolveDockerGpuSandboxCreatePlan: vi.fn(() => ({ - useDockerGpuPatch: false, - logMessage: null, - })), - prepareInitialSandboxCreatePolicy: vi.fn(() => ({ - policyPath: "/tmp/policy.yaml", - appliedPresets: [], - })), - buildSandboxGpuCreateArgs: vi.fn(() => []), - }, - }); - - expect(events).toEqual(["resource-flags", "pre-delete-cleanup-re-run", "gateway-upsert"]); - expect(upsertMessagingProviders).toHaveBeenCalledWith([telegramTokenDef], { - replaceExisting: true, - }); - expect(result.messagingProviders).toEqual(["sandbox-telegram-bridge"]); - }); - - // Pinned gap for #6225: this validation is deterministic and fail-closed, - // but on the recreate path it only runs after the old sandbox was deleted — - // a binding drift halts gateway writes yet cannot restore the sandbox. - it("rejects a drifted credential binding before any gateway effect runs (#6225)", () => { - const intent = resolveSandboxCreateIntent({ - basePolicyPath: "/repo/policy.yaml", - sandboxName: "sandbox", - channels: [telegramChannel], - enabledChannels: ["telegram"], - disabledChannelNames: new Set(), - messagingProviderRequests: resolveSandboxCreateMessagingProviderRequests( - [telegramTokenDef], - () => "telegram", - ), - primaryMessagingCredentialEnvKeys: ["TELEGRAM_BOT_TOKEN"], - reusableMessagingChannels: [], - reusableMessagingProviders: [], - hermesToolGateways: [], - sandboxGpuConfig, - gpuCreateArgs: [], - useDockerGpuPatch: false, - sandboxGpuLogMessage: null, - policyTier: null, - }); - const preparePolicy = vi.fn(() => ({ policyPath: "/tmp/policy.yaml", appliedPresets: [] })); - const appendResourceFlags = vi.fn(); - const runProviderPreDeleteCleanup = vi.fn(); - const upsertMessagingProviders = vi.fn(() => []); - - expect(() => - materializeSandboxCreatePlan({ - intent, - buildCtx: "/tmp/nemoclaw-build-1", - messagingTokenDefs: [{ ...telegramTokenDef, token: null }], - prepareInitialSandboxCreatePolicy: preparePolicy, - appendResourceFlags, - runProviderPreDeleteCleanup, - upsertMessagingProviders, - getHermesToolGatewayProviderName: vi.fn(), - }), - ).toThrow("credential availability changed for provider 'sandbox-telegram-bridge'"); - expect(preparePolicy).not.toHaveBeenCalled(); - expect(appendResourceFlags).not.toHaveBeenCalled(); - expect(runProviderPreDeleteCleanup).not.toHaveBeenCalled(); - expect(upsertMessagingProviders).not.toHaveBeenCalled(); - }); -}); - -// ── 3. Resume identity: recorded sandbox name and the sandbox step gate ──── -// -// The deciding functions behind the #2753 contract: the recorded sandbox name -// is trusted (as resume identity and as a conflict source) only when the -// session's sandbox step actually completed. onboard() applies the same -// predicate when it seeds `recordedSandboxName` for the flow context, and the -// resume decision collapses to a plain create when the step is incomplete -// (see sandbox-resume.test.ts for the decision-side coverage). - -describe("resume identity honors the recorded sandbox name only after the sandbox step completed (#2753)", () => { - it.each([ - "pending", - "in_progress", - "failed", - "skipped", - ])("ignores the recorded sandbox name while the sandbox step is %s (#2753)", (status) => { - const conflict = getResumeSandboxConflict( - { sandboxName: "recorded-sandbox", steps: { sandbox: { status } } }, - { sandboxName: "requested-sandbox" }, - ); - - expect(conflict).toBeNull(); - }); - - it("reports a conflict between requested and recorded names once the sandbox step is complete (#2753)", () => { - const conflict = getResumeSandboxConflict( - { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, - { sandboxName: "requested-sandbox" }, - ); - - expect(conflict).toEqual({ - requestedSandboxName: "requested-sandbox", - recordedSandboxName: "recorded-sandbox", - }); - }); - - it("normalizes the requested name before comparing it to the recorded name (#2753)", () => { - const conflict = getResumeSandboxConflict( - { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, - { sandboxName: " Recorded-Sandbox " }, - ); - - expect(conflict).toBeNull(); - }); - - it("reports no conflict without a requested override name even for a completed step (#2753)", () => { - const conflict = getResumeSandboxConflict( - { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, - {}, - ); - - expect(conflict).toBeNull(); - }); - - it("omits the sandbox conflict for an incomplete session so a new name can recover a phantom (#2753)", () => { - const conflicts = getResumeConfigConflicts( - { sandboxName: "phantom-sandbox", steps: { sandbox: { status: "in_progress" } } }, - { sandboxName: "fresh-name" }, - ); - - expect(conflicts).toEqual([]); - }); - - it("keeps the sandbox conflict for a completed session in the full conflict list (#2753)", () => { - const conflicts = getResumeConfigConflicts( - { sandboxName: "recorded-sandbox", steps: { sandbox: { status: "complete" } } }, - { sandboxName: "fresh-name" }, - ); - - expect(conflicts).toEqual([ - { field: "sandbox", requested: "fresh-name", recorded: "recorded-sandbox" }, - ]); - }); -});