Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
f8a9a58
refactor(onboard): lower cognitive complexity ratchet to 245
cv Jun 14, 2026
65d7578
refactor(rebuild): lower cognitive complexity ratchet to 244
cv Jun 14, 2026
433ba8a
refactor(rebuild): lower cognitive complexity ratchet to 243
cv Jun 14, 2026
30e2b10
refactor(onboard): move setupNim validation helpers
cv Jun 14, 2026
bd07191
Merge branch 'ratchet/245-setup-nim-cognitive-complexity' into ratche…
cv Jun 14, 2026
fda1c05
Merge branch 'ratchet/244-rebuild-cognitive-complexity' into ratchet/…
cv Jun 14, 2026
cdc58d7
test(rebuild): cover interactive confirmation
cv Jun 14, 2026
2879093
refactor(rebuild): lower cognitive complexity ratchet to 225
cv Jun 15, 2026
df63d1a
refactor(rebuild): lower cognitive complexity ratchet to 224
cv Jun 15, 2026
494c641
refactor(rebuild): lower cognitive complexity ratchet to 215
cv Jun 15, 2026
2f250de
refactor(rebuild): lower cognitive complexity ratchet to 186
cv Jun 15, 2026
7778b05
Merge branch 'main' into ratchet/245-setup-nim-cognitive-complexity
cv Jun 15, 2026
b451a5b
fix(onboard): preserve local NIM fallback state
cv Jun 15, 2026
9e3ddf5
Merge branch 'ratchet/245-setup-nim-cognitive-complexity' into ratche…
cv Jun 15, 2026
08743b0
Merge branch 'ratchet/244-rebuild-cognitive-complexity' into ratchet/…
cv Jun 15, 2026
17913db
Merge branch 'ratchet/243-rebuild-confirm-cognitive-complexity' into …
cv Jun 15, 2026
18a4325
Merge branch 'ratchet/225-rebuild-single-agent-guard' into ratchet/22…
cv Jun 15, 2026
cf9cc11
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
f26ffe1
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
ed3170a
test(onboard): cover setupNim selection validator state
cv Jun 15, 2026
4ef8d6f
Merge branch 'ratchet/245-setup-nim-cognitive-complexity' into ratche…
cv Jun 15, 2026
3df8744
Merge branch 'ratchet/244-rebuild-cognitive-complexity' into ratchet/…
cv Jun 15, 2026
8d3daaa
Merge branch 'ratchet/243-rebuild-confirm-cognitive-complexity' into …
cv Jun 15, 2026
c8f5794
Merge branch 'ratchet/225-rebuild-single-agent-guard' into ratchet/22…
cv Jun 15, 2026
4499f83
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
463e1d7
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
9194819
Merge remote-tracking branch 'origin/main' into ratchet/244-rebuild-c…
cv Jun 15, 2026
00724d3
Merge branch 'ratchet/244-rebuild-cognitive-complexity' into ratchet/…
cv Jun 15, 2026
57dafc8
Merge branch 'ratchet/243-rebuild-confirm-cognitive-complexity' into …
cv Jun 15, 2026
374e4a8
Merge branch 'ratchet/225-rebuild-single-agent-guard' into ratchet/22…
cv Jun 15, 2026
6758a6d
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
e6b39bb
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
ebe72ba
test(onboard): align sandbox registration fixture
cv Jun 15, 2026
a23904d
Merge branch 'ratchet/244-rebuild-cognitive-complexity' into ratchet/…
cv Jun 15, 2026
af81f07
Merge branch 'ratchet/243-rebuild-confirm-cognitive-complexity' into …
cv Jun 15, 2026
d9ad1a0
Merge branch 'ratchet/225-rebuild-single-agent-guard' into ratchet/22…
cv Jun 15, 2026
b2ab482
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
56b891e
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
cb69607
test(rebuild): cover active session warning
cv Jun 15, 2026
86b83a0
Merge branch 'ratchet/244-rebuild-cognitive-complexity' into ratchet/…
cv Jun 15, 2026
7b61d67
Merge branch 'ratchet/243-rebuild-confirm-cognitive-complexity' into …
cv Jun 15, 2026
e512f8f
Merge branch 'ratchet/225-rebuild-single-agent-guard' into ratchet/22…
cv Jun 15, 2026
3926914
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
bcddede
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
94402c3
Merge remote-tracking branch 'origin/main' into ratchet/243-rebuild-c…
cv Jun 15, 2026
98902a7
Merge branch 'ratchet/243-rebuild-confirm-cognitive-complexity' into …
cv Jun 15, 2026
e28e8e7
Merge branch 'ratchet/225-rebuild-single-agent-guard' into ratchet/22…
cv Jun 15, 2026
ac58322
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
fccda94
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
04da8e5
Merge remote-tracking branch 'origin/main' into ratchet/225-rebuild-s…
cv Jun 15, 2026
d066d12
Merge branch 'ratchet/225-rebuild-single-agent-guard' into ratchet/22…
cv Jun 15, 2026
3fe883f
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
17320b6
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
d6d5bfe
Merge remote-tracking branch 'origin/main' into ratchet/224-rebuild-r…
cv Jun 15, 2026
a679c21
Merge branch 'ratchet/224-rebuild-registry-guard' into ratchet/215-re…
cv Jun 15, 2026
cf2e341
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
51492b1
Merge remote-tracking branch 'origin/main' into ratchet/215-rebuild-v…
cv Jun 15, 2026
af54450
Merge branch 'ratchet/215-rebuild-version-header' into ratchet/186-re…
cv Jun 15, 2026
8ec4bd6
fix(rebuild): target legacy local credential bypass
cv Jun 15, 2026
dfe58bf
test(rebuild): cover messaging staging preflight
cv Jun 15, 2026
6d17d33
Merge remote-tracking branch 'origin/main' into ratchet/186-rebuild-c…
cv Jun 15, 2026
8eca2e2
chore(rebuild): apply formatter
cv Jun 15, 2026
1d8239e
fix(rebuild): fail closed on missing remote session credential
cv Jun 15, 2026
804dc16
fix(rebuild): use registry provider for credential preflight
cv Jun 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
"noExcessiveCognitiveComplexity": {
"level": "error",
"options": {
"maxAllowedComplexity": 215
"maxAllowedComplexity": 186
}
}
},
Expand Down
29 changes: 29 additions & 0 deletions src/lib/actions/sandbox/rebuild-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type RebuildFlowOverrides = {
failedDirs: string[];
failedFiles: string[];
};
buildMessagingRebuildPlan?: () => Promise<unknown> | unknown;
};

type RebuildFlowHarness = {
Expand All @@ -38,6 +39,7 @@ type RebuildFlowHarness = {
relockSpy: MockInstance;
restoreSandboxStateSpy: MockInstance;
runOpenshellSpy: MockInstance;
messagingRebuildPlanSpy: MockInstance;
};

const originalSandboxName = process.env.NEMOCLAW_SANDBOX_NAME;
Expand Down Expand Up @@ -66,6 +68,7 @@ function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): Rebuild
const nim = requireDist("../../../../dist/lib/inference/nim.js");
const policies = requireDist("../../../../dist/lib/policy/index.js");
const processRecovery = requireDist("../../../../dist/lib/actions/sandbox/process-recovery.js");
const messaging = requireDist("../../../../dist/lib/messaging/index.js");
const shields = requireDist("../../../../dist/lib/shields/index.js");

const session = {
Expand Down Expand Up @@ -167,6 +170,9 @@ function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): Rebuild
vi.spyOn(shields, "repairMutableConfigPerms").mockImplementation(
overrides.repairMutableConfigPerms ?? (() => ({ applied: true, verified: true, errors: [] })),
);
const messagingRebuildPlanSpy = vi
.spyOn(messaging.MessagingWorkflowPlanner.prototype, "buildRebuildPlanFromSandboxEntry")
.mockImplementation(overrides.buildMessagingRebuildPlan ?? (() => null));

errorSpy.mockClear();
logSpy.mockClear();
Expand All @@ -184,6 +190,7 @@ function createRebuildFlowHarness(overrides: RebuildFlowOverrides = {}): Rebuild
relockSpy,
restoreSandboxStateSpy,
runOpenshellSpy,
messagingRebuildPlanSpy,
};
}

Expand Down Expand Up @@ -240,6 +247,28 @@ describe("rebuildSandbox flow", () => {
);
});

it("aborts before backup/delete when messaging manifest staging fails", async () => {
const harness = createRebuildFlowHarness({
buildMessagingRebuildPlan: () => {
throw new Error("manifest boom");
},
});

await expect(
harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }),
).rejects.toThrow("manifest boom");

const errors = harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n");
expect(errors).toContain("messaging manifest plan could not be staged");
expect(errors).toContain("Sandbox is untouched");
expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled();
expect(harness.runOpenshellSpy).not.toHaveBeenCalledWith(
["sandbox", "delete", "alpha"],
expect.anything(),
);
expect(harness.onboardSpy).not.toHaveBeenCalled();
});

it("finishes the rebuild while surfacing incomplete post-restore work", async () => {
const harness = createRebuildFlowHarness({
executeSandboxCommand: () => ({ status: 1, stdout: "", stderr: "hash refresh failed" }),
Expand Down
262 changes: 135 additions & 127 deletions src/lib/actions/sandbox/rebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,12 @@ function _rebuildLog(msg: string) {
/**
* Resolve the credential environment variable required to recreate a sandbox.
*/
function isLocalInferenceProvider(provider: string | null | undefined): provider is string {
return Boolean(provider && LOCAL_INFERENCE_PROVIDERS.includes(provider));
}

function getRebuildCredentialEnvFromRegistry(provider: string | null | undefined): string | null {
if (!provider || LOCAL_INFERENCE_PROVIDERS.includes(provider)) {
if (!provider || isLocalInferenceProvider(provider)) {
return null;
}
const remoteConfig =
Expand Down Expand Up @@ -384,6 +388,125 @@ function isSingleAgentRebuildSupported(
return true;
}

async function stageRebuildMessagingPlanOrBail(
sandboxName: string,
sb: RebuildSandboxEntry,
rebuildAgent: string | null,
log: (msg: string) => void,
bail: (msg: string, code?: number) => never,
): Promise<SandboxMessagingPlan | null> {
try {
return await stageMessagingManifestPlanForRebuild(sandboxName, sb, rebuildAgent, log);
} catch (err) {
// Source boundary: registry messaging plans and agent manifests are durable
// host-side inputs from prior onboarding. If they drift or become invalid,
// rebuild must fail here before backup/delete; remove this boundary only if
// manifest staging becomes total over all persisted registry states.
const message = err instanceof Error ? err.message : String(err);
console.error("");
console.error(
` ${_RD}Rebuild preflight failed:${R} messaging manifest plan could not be staged.`,
);
console.error(` ${message}`);
console.error("");
console.error(" Sandbox is untouched — no data was lost.");
bail(message);
return null;
}
}

function preflightRebuildCredentials(
sandboxName: string,
sb: RebuildSandboxEntry,
log: (msg: string) => void,
bail: (msg: string, code?: number) => never,
): boolean {
const session = onboardSession.loadSession();
const sessionMatchesTarget = session?.sandboxName === sandboxName;
// The target registry entry is authoritative when a matching legacy session
// omitted credentialEnv; rebuild rewrites provider/model from this entry later,
// so remote registry providers must still fail closed before backup/delete.
let rebuildCredentialEnv = sessionMatchesTarget
? session?.credentialEnv || getRebuildCredentialEnvFromRegistry(sb.provider)
: getRebuildCredentialEnvFromRegistry(sb.provider);
if (!sessionMatchesTarget && session?.sandboxName) {
log(
`Preflight warning: session belongs to '${session.sandboxName}', not '${sandboxName}' — using registry credential env ${rebuildCredentialEnv || "(none)"}`,
);
console.log(
` ${D}Note: onboard session belongs to '${session.sandboxName}', not '${sandboxName}'. ` +
`Using the '${sandboxName}' registry entry for credential preflight.${R}`,
);
}

const rebuildProvider = sb.provider;
// Compatibility boundary for GH #2519: pre-fix local-provider sessions could
// persist credentialEnv="OPENAI_API_KEY" even though current local-provider
// write paths persist null. Only a session for this sandbox plus a local
// target registry provider may bypass the key; keep until legacy sessions are
// no longer supported by rebuild migration tests.
if (
sessionMatchesTarget &&
isLocalInferenceProvider(sb.provider) &&
rebuildCredentialEnv === "OPENAI_API_KEY"
) {
console.log(
` ${D}Note: migrating ${sb.provider} sandbox off OPENAI_API_KEY (GH #2519). ` +
`Local inference does not require a host API key.${R}`,
);
log(
`Preflight: legacy ${sb.provider} sandbox detected (credentialEnv=OPENAI_API_KEY) — clearing for rebuild`,
);
rebuildCredentialEnv = null;
}

if (rebuildProvider === hermesProviderAuth.HERMES_PROVIDER_NAME) {
if (
!preflightHermesProviderCredentials(
sessionMatchesTarget ? session : null,
rebuildCredentialEnv,
log,
)
) {
bail("Missing Hermes Provider credentials");
return false;
}
rebuildCredentialEnv = null;
}

if (!rebuildCredentialEnv) {
log(
"Preflight credential check: no credentialEnv in session (local inference or missing session)",
);
return true;
}

const credentialValue = hydrateCredentialEnv(rebuildCredentialEnv);
log(
`Preflight credential check: ${rebuildCredentialEnv} → ${credentialValue ? "present" : "MISSING"}`,
);
if (credentialValue) return true;
if (rebuildProvider && providerExistsInGateway(rebuildProvider, runOpenshell)) {
log(
`Preflight credential check: provider '${rebuildProvider}' registered in gateway — skipping env check for ${rebuildCredentialEnv}`,
);
return true;
}

console.error("");
console.error(` ${_RD}Rebuild preflight failed:${R} provider credential not found.`);
console.error(` The non-interactive recreate step requires ${rebuildCredentialEnv},`);
console.error(" but it is not set in the environment.");
console.error("");
console.error(" To fix, do one of:");
console.error(` export ${rebuildCredentialEnv}=<your-key>`);
console.error(` ${CLI_NAME} onboard # re-enter the key interactively`);
console.error("");
console.error(" Sandbox is untouched — no data was lost.");
bail(`Missing credential: ${rebuildCredentialEnv}`);
return false;
}

function printRebuildVersionSummary(
sandboxName: string,
agentName: string,
Expand Down Expand Up @@ -495,133 +618,18 @@ export async function rebuildSandbox(
if (!rebuildConfirmed) return;

// Step 0: Preflight — verify recreate preconditions BEFORE destroying
// anything. The most common rebuild failure is a missing provider
// credential when onboard runs in non-interactive mode. Checking now
// lets us abort with the sandbox still intact. See #2273.
const session = onboardSession.loadSession();
const sessionMatchesTarget = session?.sandboxName === sandboxName;
let rebuildCredentialEnv: string | null = null;
if (!sessionMatchesTarget) {
// Session belongs to a different sandbox — its credentialEnv may be
// wrong (e.g. hermes session while rebuilding openclaw). Resolve the
// target sandbox provider from the registry instead so destructive
// operations still get a credential preflight for the sandbox being rebuilt.
rebuildCredentialEnv = getRebuildCredentialEnvFromRegistry(sb.provider);
if (session?.sandboxName) {
log(
`Preflight warning: session belongs to '${session.sandboxName}', not '${sandboxName}' — using registry credential env ${rebuildCredentialEnv || "(none)"}`,
);
console.log(
` ${D}Note: onboard session belongs to '${session.sandboxName}', not '${sandboxName}'. ` +
`Using the '${sandboxName}' registry entry for credential preflight.${R}`,
);
}
} else {
rebuildCredentialEnv = session?.credentialEnv || null;
}
const rebuildProvider = sessionMatchesTarget ? session?.provider || sb.provider : sb.provider;
// Legacy migration: pre-fix local-inference sandboxes (GH #2519, GH #2625)
// recorded credentialEnv="OPENAI_API_KEY" in onboard-session.json even
// though the sandbox does not actually need a host OpenAI key (ollama-local
// uses an auth proxy with an internal token; vllm-local accepts a static
// dummy bearer). Treat the legacy value as null so rebuild does not demand
// a credential that was never actually used.
//
// Post-#2625 the write path persists credentialEnv=null directly when the
// wizard selects a local provider, so fresh sessions no longer need this
// migration. We retain it for users whose session.json on disk predates
// the fix.
if (
(session?.provider === "ollama-local" || session?.provider === "vllm-local") &&
rebuildCredentialEnv === "OPENAI_API_KEY"
) {
console.log(
` ${D}Note: migrating ${session.provider} sandbox off OPENAI_API_KEY (GH #2519). ` +
`Local inference does not require a host API key.${R}`,
);
log(
`Preflight: legacy ${session.provider} sandbox detected (credentialEnv=OPENAI_API_KEY) — clearing for rebuild`,
);
rebuildCredentialEnv = null;
}
if (rebuildProvider === hermesProviderAuth.HERMES_PROVIDER_NAME) {
if (
!preflightHermesProviderCredentials(
sessionMatchesTarget ? session : null,
rebuildCredentialEnv,
log,
)
) {
bail("Missing Hermes Provider credentials");
return;
}
// Hermes Provider credentials belong to OpenShell provider storage. Do not
// fall through to the generic env-var preflight, which would incorrectly
// demand OPENAI_API_KEY/NOUS_API_KEY after the provider is registered.
rebuildCredentialEnv = null;
}
if (rebuildCredentialEnv) {
// hydrateCredentialEnv migrates any pre-fix legacy credentials.json
// into process.env once, so users upgrading from a release that wrote
// the plaintext file can still rebuild without re-entering keys.
const credentialValue = hydrateCredentialEnv(rebuildCredentialEnv);
log(
`Preflight credential check: ${rebuildCredentialEnv} → ${credentialValue ? "present" : "MISSING"}`,
);
if (!credentialValue) {
// When the inference provider is already registered in the OpenShell
// gateway, the recreate step does not need a host env value — the
// gateway is the source of truth for the secret. Skip the env-only
// preflight in that case so flows like `channels add` + rebuild keep
// working when the user has logged out of the original shell.
if (rebuildProvider && providerExistsInGateway(rebuildProvider, runOpenshell)) {
log(
`Preflight credential check: provider '${rebuildProvider}' registered in gateway — skipping env check for ${rebuildCredentialEnv}`,
);
} else {
console.error("");
console.error(` ${_RD}Rebuild preflight failed:${R} provider credential not found.`);
console.error(` The non-interactive recreate step requires ${rebuildCredentialEnv},`);
console.error(" but it is not set in the environment.");
console.error("");
console.error(" To fix, do one of:");
console.error(` export ${rebuildCredentialEnv}=<your-key>`);
console.error(` ${CLI_NAME} onboard # re-enter the key interactively`);
console.error("");
console.error(" Sandbox is untouched — no data was lost.");
bail(`Missing credential: ${rebuildCredentialEnv}`);
return;
}
}
} else {
// No credentialEnv in session — local inference (Ollama/vLLM) or
// session was lost. Either way, skip the credential preflight;
// onboard will handle it.
log(
"Preflight credential check: no credentialEnv in session (local inference or missing session)",
);
}
// anything. The most common rebuild failure is a missing provider credential
// when onboard runs in non-interactive mode. Checking now lets us abort with
// the sandbox still intact. See #2273.
if (!preflightRebuildCredentials(sandboxName, sb, log, bail)) return;

let rebuildMessagingPlan: SandboxMessagingPlan | null = null;
try {
rebuildMessagingPlan = await stageMessagingManifestPlanForRebuild(
sandboxName,
sb,
rebuildAgent,
log,
);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error("");
console.error(
` ${_RD}Rebuild preflight failed:${R} messaging manifest plan could not be staged.`,
);
console.error(` ${message}`);
console.error("");
console.error(" Sandbox is untouched — no data was lost.");
bail(message);
return;
}
const rebuildMessagingPlan = await stageRebuildMessagingPlanOrBail(
sandboxName,
sb,
rebuildAgent,
log,
bail,
);

// Step 1: Ensure sandbox is live for backup
const recordedGateway = resolveSandboxGatewayName(sb);
Expand Down
Loading