From a399b0c78880483361808b3823855db5165c3281 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 2 Sep 2026 16:01:18 -0400 Subject: [PATCH 01/10] fix(state): observe stale onboarding locks Signed-off-by: Julie Yaunches --- src/lib/state/legacy-port-migration.test.ts | 45 +++- src/lib/state/legacy-port-migration.ts | 8 +- src/lib/state/onboard-session.ts | 5 +- src/lib/state/onboard-session/index.ts | 16 ++ .../onboard-session/lock-observation.test.ts | 105 ++++++++++ .../state/onboard-session/lock-observation.ts | 198 ++++++++++++++++++ 6 files changed, 372 insertions(+), 5 deletions(-) create mode 100644 src/lib/state/onboard-session/index.ts create mode 100644 src/lib/state/onboard-session/lock-observation.test.ts create mode 100644 src/lib/state/onboard-session/lock-observation.ts diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 1adfbc007b3..10f2f07bd26 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -7,11 +7,17 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +const { observeOnboardLock } = vi.hoisted(() => ({ + observeOnboardLock: vi.fn<() => OnboardLockObservation>(() => ({ kind: "absent" })), +})); +vi.mock("./onboard-session/lock-observation", () => ({ observeOnboardLock })); + import { type OnboardEntryOptionsDeps, resolveOnboardEntryOptions, } from "../onboard/entry-options"; import { migrateLegacyPortState } from "./legacy-port-migration"; +import type { OnboardLockObservation } from "./onboard-session/lock-observation"; import { listRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery, @@ -87,6 +93,8 @@ function expectRetainedNameBlocked( } afterEach(() => { + observeOnboardLock.mockReset(); + observeOnboardLock.mockReturnValue({ kind: "absent" }); vi.restoreAllMocks(); for (const home of homes.splice(0)) fs.rmSync(home, { recursive: true, force: true }); }); @@ -428,13 +436,48 @@ describe("legacy non-default gateway state migration", () => { fs.mkdirSync(root(shared, selected), { recursive: true }); fs.writeFileSync(path.join(root(shared, selected), "onboard.lock"), "active writer"); + observeOnboardLock.mockReturnValue({ kind: "busy", reason: "unverified" }); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - /onboarding lock .* is present/u, + /onboarding lock .* is unverified/u, ); expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); expect(fs.existsSync(path.join(selected, "retained-sandbox-recovery.json"))).toBe(false); }); + it("migrates past a proven-stale onboarding lock without removing it", () => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + const lock = path.join(shared, "onboard.lock"); + writeJson(path.join(shared, "sandboxes.json"), { + defaultSandbox: "port-box", + sandboxes: { + "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, + }, + }); + writeJson(path.join(shared, "onboard-session.json"), { + sandboxName: "port-box", + metadata: { gatewayName: "nemoclaw-9123" }, + }); + fs.writeFileSync(lock, "retained stale lock"); + observeOnboardLock.mockReturnValue({ + kind: "stale", + reason: "departed", + owner: { + pid: 123, + startedAt: null, + command: null, + processGeneration: "boot:10", + hostIdentity: "host-a", + pidNamespaceIdentity: "pid:[1]", + }, + }); + + expect(migrateLegacyPortState({ home, gatewayPort: 9123 }).migratedSession).toBe(true); + expect(fs.readFileSync(lock, "utf8")).toBe("retained stale lock"); + expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); + }); + it.each( ["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"], )("keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", (entry) => { diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index be3c0017999..37e23853457 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -15,6 +15,7 @@ import { readGatewayRegistryFile, registryEntryGatewayPort, } from "./gateway-registry"; +import { observeOnboardLock } from "./onboard-session/lock-observation"; import { listRetainedSandboxRecoveryRecords, retainedSandboxRecoveryFile, @@ -745,9 +746,12 @@ function acquireDirectoryLock(home: string, lock: string): string { function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]): void { for (const stateRoot of stateRoots) { const activeLock = path.join(stateRoot, "onboard.lock"); - if (lstatNoFollow(home, activeLock)) { + const lock = observeOnboardLock(activeLock); + if (lock.kind === "busy") { + const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; throw migrationError( - `onboarding lock ${activeLock} is present; finish or stop that run before migrating state`, + `onboarding lock ${activeLock}${owner} is ${lock.reason}; ` + + "finish that run or verify the lock owner before retrying", ); } } diff --git a/src/lib/state/onboard-session.ts b/src/lib/state/onboard-session.ts index 8398480f592..2a6667e807d 100644 --- a/src/lib/state/onboard-session.ts +++ b/src/lib/state/onboard-session.ts @@ -61,6 +61,7 @@ import { } from "./onboard-session-tool-disclosure"; import { nextMachineStateAfterCompletedStep } from "./onboard-step-state"; import { + createOnboardLockOwner, listRetainedSandboxRecoveryRecords as readRetainedSandboxRecoveryRecords, recordRetainedSandboxRecovery as writeRetainedSandboxRecovery, retainedSandboxRecoveryAuthorityIsCurrent, @@ -69,7 +70,7 @@ import { type RecordRetainedSandboxRecoveryInput, type RetainedSandboxRecoveryRecord, type RetainedSandboxRecoveryReason, -} from "./onboard-session/retained-sandbox-recovery"; +} from "./onboard-session/index"; import type { SandboxHostMount } from "./registry/types"; import { hasUnsafeHostMountTerminalText } from "./registry/host-mount"; import { nemoclawStateRoot } from "./state-root"; @@ -1489,7 +1490,7 @@ export function isOnboardLockHeldByCurrentProcess(): boolean { export function acquireOnboardLock(command: string | null = null): LockResult { ensureSessionDir(); const payload = JSON.stringify( - { + createOnboardLockOwner(typeof command === "string" ? command : null) ?? { pid: process.pid, startedAt: new Date().toISOString(), command: typeof command === "string" ? command : null, diff --git a/src/lib/state/onboard-session/index.ts b/src/lib/state/onboard-session/index.ts new file mode 100644 index 00000000000..5a9735c02ba --- /dev/null +++ b/src/lib/state/onboard-session/index.ts @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export { createOnboardLockOwner } from "./lock-observation"; +export { + listRetainedSandboxRecoveryRecords, + recordRetainedSandboxRecovery, + retainedSandboxRecoveryAuthorityIsCurrent, + retainedSandboxRecoveryFile, + resolveRetainedSandboxRecovery, +} from "./retained-sandbox-recovery"; +export type { + RecordRetainedSandboxRecoveryInput, + RetainedSandboxRecoveryRecord, + RetainedSandboxRecoveryReason, +} from "./retained-sandbox-recovery"; diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts new file mode 100644 index 00000000000..49344432527 --- /dev/null +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + observeOnboardLock, + type OnboardLockEvidence, + type OnboardLockOwner, +} from "./lock-observation"; + +const roots: string[] = []; + +function fixture(): { evidence: OnboardLockEvidence; lock: string; owner: OnboardLockOwner } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-observation-")); + roots.push(root); + const lock = path.join(root, "onboard.lock"); + const owner: OnboardLockOwner = { + pid: 123, + startedAt: "2026-09-02T00:00:00.000Z", + command: "nemoclaw onboard", + processGeneration: "boot:10", + hostIdentity: "host-a", + pidNamespaceIdentity: "pid:[1]", + }; + const evidence: OnboardLockEvidence = { + hostIdentity: () => "host-a", + pidNamespaceIdentity: () => "pid:[1]", + processGeneration: () => "boot:10", + processAlive: () => true, + }; + return { evidence, lock, owner }; +} + +function writeOwner(lock: string, owner: OnboardLockOwner): void { + fs.writeFileSync(lock, JSON.stringify(owner), { mode: 0o600 }); +} + +afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +describe("onboarding lock observation", () => { + it("reports a missing lock as absent", () => { + const { evidence, lock } = fixture(); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "absent" }); + }); + + it("reports only proven-local departed and reused owners as stale", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + expect(observeOnboardLock(lock, { ...evidence, processAlive: () => false })).toMatchObject({ + kind: "stale", + reason: "departed", + }); + expect( + observeOnboardLock(lock, { ...evidence, processGeneration: () => "boot:11" }), + ).toMatchObject({ kind: "stale", reason: "pid-reused" }); + }); + + it.each([ + ["active", {}], + ["unverified", { processGeneration: () => null }], + ["foreign", { hostIdentity: () => "host-b" }], + ["foreign", { pidNamespaceIdentity: () => "pid:[2]" }], + ] as const)("keeps %s owners busy", (reason, overrides) => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + expect(observeOnboardLock(lock, { ...evidence, ...overrides })).toMatchObject({ + kind: "busy", + reason, + }); + }); + + it("keeps legacy, oversized, linked, and non-regular state busy", () => { + const { evidence, lock } = fixture(); + fs.writeFileSync(lock, JSON.stringify({ pid: 123 })); + expect(observeOnboardLock(lock, evidence)).toMatchObject({ kind: "busy" }); + fs.writeFileSync(lock, "x".repeat(64 * 1024 + 1)); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + fs.rmSync(lock); + fs.mkdirSync(lock); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + }); + + it("does not consult the local PID table for a foreign owner", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + let probed = false; + const result = observeOnboardLock(lock, { + ...evidence, + hostIdentity: () => "host-b", + processAlive: () => { + probed = true; + return false; + }, + }); + expect(result).toMatchObject({ kind: "busy", reason: "foreign" }); + expect(probed).toBe(false); + }); +}); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts new file mode 100644 index 00000000000..d71e140d91e --- /dev/null +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +import { isErrnoException } from "../../core/errno"; + +const MAX_LOCK_BYTES = 64 * 1024; + +export interface OnboardLockOwner { + pid: number; + startedAt: string | null; + command: string | null; + processGeneration: string; + hostIdentity: string; + pidNamespaceIdentity: string; +} + +export interface OnboardLockEvidence { + hostIdentity(): string | null; + pidNamespaceIdentity(): string | null; + processGeneration(pid: number): string | null; + processAlive(pid: number): boolean; +} + +export type OnboardLockObservation = + | { kind: "absent" } + | { kind: "stale"; reason: "departed" | "pid-reused"; owner: OnboardLockOwner } + | { + kind: "busy"; + reason: "active" | "foreign" | "unverified" | "publishing" | "unsafe"; + owner?: OnboardLockOwner; + }; + +function readTrimmed(path: string): string | null { + try { + const value = fs.readFileSync(path, "utf8").trim(); + return value || null; + } catch { + return null; + } +} + +function defaultProcessAlive(pid: number): boolean { + if (!Number.isSafeInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return isErrnoException(error) && error.code === "EPERM"; + } +} + +function linuxProcessGeneration(pid: number): string | null { + try { + const stat = fs.readFileSync(`/proc/${String(pid)}/stat`, "utf8"); + const closeParen = stat.lastIndexOf(")"); + if (closeParen < 0) return null; + const fields = stat + .slice(closeParen + 2) + .trim() + .split(/\s+/); + const startTicks = fields[19]; + if (!startTicks || !/^[0-9]+$/.test(startTicks)) return null; + const bootIdentity = + readTrimmed("/proc/sys/kernel/random/boot_id") ?? + fs + .readFileSync("/proc/stat", "utf8") + .split("\n") + .find((line) => line.startsWith("btime ")) + ?.slice("btime ".length) + .trim(); + return bootIdentity ? `linux:${bootIdentity}:${startTicks}` : null; + } catch { + return null; + } +} + +export const systemOnboardLockEvidence: OnboardLockEvidence = { + hostIdentity: () => readTrimmed("/etc/machine-id"), + pidNamespaceIdentity: () => { + try { + return fs.readlinkSync("/proc/self/ns/pid"); + } catch { + return null; + } + }, + processGeneration: (pid) => (process.platform === "linux" ? linuxProcessGeneration(pid) : null), + processAlive: defaultProcessAlive, +}; + +export function createOnboardLockOwner( + command: string | null, + evidence: OnboardLockEvidence = systemOnboardLockEvidence, +): OnboardLockOwner | null { + const hostIdentity = evidence.hostIdentity(); + const pidNamespaceIdentity = evidence.pidNamespaceIdentity(); + const processGeneration = evidence.processGeneration(process.pid); + if (!hostIdentity || !pidNamespaceIdentity || !processGeneration) return null; + return { + pid: process.pid, + startedAt: new Date().toISOString(), + command, + processGeneration, + hostIdentity, + pidNamespaceIdentity, + }; +} + +function parseOwner(value: unknown): OnboardLockOwner | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const record = value as Record; + if ( + !Number.isSafeInteger(record.pid) || + typeof record.processGeneration !== "string" || + typeof record.hostIdentity !== "string" || + typeof record.pidNamespaceIdentity !== "string" + ) { + return null; + } + return { + pid: record.pid as number, + startedAt: typeof record.startedAt === "string" ? record.startedAt : null, + command: typeof record.command === "string" ? record.command : null, + processGeneration: record.processGeneration, + hostIdentity: record.hostIdentity, + pidNamespaceIdentity: record.pidNamespaceIdentity, + }; +} + +export function observeOnboardLock( + lockPath: string, + evidence: OnboardLockEvidence = systemOnboardLockEvidence, +): OnboardLockObservation { + let fd: number; + try { + fd = fs.openSync( + lockPath, + fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), + ); + } catch (error) { + if (isErrnoException(error) && error.code === "ENOENT") return { kind: "absent" }; + return { kind: "busy", reason: "unsafe" }; + } + + try { + const before = fs.fstatSync(fd); + const pathStat = fs.lstatSync(lockPath); + if ( + !before.isFile() || + before.nlink !== 1 || + before.size > MAX_LOCK_BYTES || + pathStat.isSymbolicLink() || + !pathStat.isFile() || + pathStat.nlink !== 1 || + pathStat.dev !== before.dev || + pathStat.ino !== before.ino + ) { + return { kind: "busy", reason: "unsafe" }; + } + const bytes = Buffer.alloc(Math.min(MAX_LOCK_BYTES + 1, before.size + 1)); + const length = fs.readSync(fd, bytes, 0, bytes.length, 0); + const after = fs.fstatSync(fd); + if ( + length > MAX_LOCK_BYTES || + before.dev !== after.dev || + before.ino !== after.ino || + before.size !== after.size || + before.mtimeMs !== after.mtimeMs || + before.ctimeMs !== after.ctimeMs + ) { + return { kind: "busy", reason: "publishing" }; + } + const owner = parseOwner(JSON.parse(bytes.subarray(0, length).toString("utf8"))); + if (!owner) return { kind: "busy", reason: "unverified" }; + + const hostIdentity = evidence.hostIdentity(); + const pidNamespaceIdentity = evidence.pidNamespaceIdentity(); + if (!hostIdentity || !pidNamespaceIdentity) + return { kind: "busy", reason: "unverified", owner }; + if ( + owner.hostIdentity !== hostIdentity || + owner.pidNamespaceIdentity !== pidNamespaceIdentity + ) { + return { kind: "busy", reason: "foreign", owner }; + } + if (!evidence.processAlive(owner.pid)) return { kind: "stale", reason: "departed", owner }; + const generation = evidence.processGeneration(owner.pid); + if (!generation) return { kind: "busy", reason: "unverified", owner }; + if (generation !== owner.processGeneration) + return { kind: "stale", reason: "pid-reused", owner }; + return { kind: "busy", reason: "active", owner }; + } catch { + return { kind: "busy", reason: "unverified" }; + } finally { + fs.closeSync(fd); + } +} From dacb6ddb6ec8f237325e7d82059cf9863c30c1ed Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 13:35:27 -0400 Subject: [PATCH 02/10] fix(state): reject malformed onboarding lock owners Signed-off-by: Julie Yaunches --- .../state/onboard-session/lock-observation.test.ts | 12 ++++++++++++ src/lib/state/onboard-session/lock-observation.ts | 13 ++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index 49344432527..7a1707461c2 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -87,6 +87,18 @@ describe("onboarding lock observation", () => { expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); }); + it.each([0, -1])("keeps a malformed PID %s unverified", (pid) => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, { ...owner, pid }); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unverified" }); + }); + + it("keeps an empty process generation unverified", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, { ...owner, processGeneration: "" }); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unverified" }); + }); + it("does not consult the local PID table for a foreign owner", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts index d71e140d91e..3be3d8170d0 100644 --- a/src/lib/state/onboard-session/lock-observation.ts +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -3,7 +3,6 @@ import fs from "node:fs"; -import { isErrnoException } from "../../core/errno"; const MAX_LOCK_BYTES = 64 * 1024; @@ -41,13 +40,18 @@ function readTrimmed(path: string): string | null { } } +function errnoCode(error: unknown): string | undefined { + if (!error || typeof error !== "object" || !("code" in error)) return undefined; + return typeof error.code === "string" ? error.code : undefined; +} + function defaultProcessAlive(pid: number): boolean { if (!Number.isSafeInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (error) { - return isErrnoException(error) && error.code === "EPERM"; + return errnoCode(error) === "EPERM"; } } @@ -111,8 +115,11 @@ function parseOwner(value: unknown): OnboardLockOwner | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const record = value as Record; if ( + typeof record.pid !== "number" || !Number.isSafeInteger(record.pid) || + record.pid <= 0 || typeof record.processGeneration !== "string" || + record.processGeneration.length === 0 || typeof record.hostIdentity !== "string" || typeof record.pidNamespaceIdentity !== "string" ) { @@ -139,7 +146,7 @@ export function observeOnboardLock( fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), ); } catch (error) { - if (isErrnoException(error) && error.code === "ENOENT") return { kind: "absent" }; + if (errnoCode(error) === "ENOENT") return { kind: "absent" }; return { kind: "busy", reason: "unsafe" }; } From d55a3667e1cd66567b2b0b8b20bed90b8af1167a Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 13:59:35 -0400 Subject: [PATCH 03/10] style(state): format lock observation changes Signed-off-by: Julie Yaunches --- .../onboard-session/lock-observation.test.ts | 46 +++++++++++++++---- .../state/onboard-session/lock-observation.ts | 24 +++++++--- 2 files changed, 53 insertions(+), 17 deletions(-) diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index 7a1707461c2..5fec6bcf3a0 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -15,8 +15,14 @@ import { const roots: string[] = []; -function fixture(): { evidence: OnboardLockEvidence; lock: string; owner: OnboardLockOwner } { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-observation-")); +function fixture(): { + evidence: OnboardLockEvidence; + lock: string; + owner: OnboardLockOwner; +} { + const root = fs.mkdtempSync( + path.join(os.tmpdir(), "nemoclaw-onboard-observation-"), + ); roots.push(root); const lock = path.join(root, "onboard.lock"); const owner: OnboardLockOwner = { @@ -41,7 +47,8 @@ function writeOwner(lock: string, owner: OnboardLockOwner): void { } afterEach(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); + for (const root of roots.splice(0)) + fs.rmSync(root, { recursive: true, force: true }); }); describe("onboarding lock observation", () => { @@ -53,12 +60,17 @@ describe("onboarding lock observation", () => { it("reports only proven-local departed and reused owners as stale", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); - expect(observeOnboardLock(lock, { ...evidence, processAlive: () => false })).toMatchObject({ + expect( + observeOnboardLock(lock, { ...evidence, processAlive: () => false }), + ).toMatchObject({ kind: "stale", reason: "departed", }); expect( - observeOnboardLock(lock, { ...evidence, processGeneration: () => "boot:11" }), + observeOnboardLock(lock, { + ...evidence, + processGeneration: () => "boot:11", + }), ).toMatchObject({ kind: "stale", reason: "pid-reused" }); }); @@ -70,7 +82,9 @@ describe("onboarding lock observation", () => { ] as const)("keeps %s owners busy", (reason, overrides) => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); - expect(observeOnboardLock(lock, { ...evidence, ...overrides })).toMatchObject({ + expect( + observeOnboardLock(lock, { ...evidence, ...overrides }), + ).toMatchObject({ kind: "busy", reason, }); @@ -81,22 +95,34 @@ describe("onboarding lock observation", () => { fs.writeFileSync(lock, JSON.stringify({ pid: 123 })); expect(observeOnboardLock(lock, evidence)).toMatchObject({ kind: "busy" }); fs.writeFileSync(lock, "x".repeat(64 * 1024 + 1)); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unsafe", + }); fs.rmSync(lock); fs.mkdirSync(lock); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unsafe", + }); }); it.each([0, -1])("keeps a malformed PID %s unverified", (pid) => { const { evidence, lock, owner } = fixture(); writeOwner(lock, { ...owner, pid }); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unverified" }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unverified", + }); }); it("keeps an empty process generation unverified", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, { ...owner, processGeneration: "" }); - expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unverified" }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unverified", + }); }); it("does not consult the local PID table for a foreign owner", () => { diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts index 3be3d8170d0..b9737db8432 100644 --- a/src/lib/state/onboard-session/lock-observation.ts +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -3,7 +3,6 @@ import fs from "node:fs"; - const MAX_LOCK_BYTES = 64 * 1024; export interface OnboardLockOwner { @@ -24,7 +23,11 @@ export interface OnboardLockEvidence { export type OnboardLockObservation = | { kind: "absent" } - | { kind: "stale"; reason: "departed" | "pid-reused"; owner: OnboardLockOwner } + | { + kind: "stale"; + reason: "departed" | "pid-reused"; + owner: OnboardLockOwner; + } | { kind: "busy"; reason: "active" | "foreign" | "unverified" | "publishing" | "unsafe"; @@ -41,7 +44,8 @@ function readTrimmed(path: string): string | null { } function errnoCode(error: unknown): string | undefined { - if (!error || typeof error !== "object" || !("code" in error)) return undefined; + if (!error || typeof error !== "object" || !("code" in error)) + return undefined; return typeof error.code === "string" ? error.code : undefined; } @@ -89,7 +93,8 @@ export const systemOnboardLockEvidence: OnboardLockEvidence = { return null; } }, - processGeneration: (pid) => (process.platform === "linux" ? linuxProcessGeneration(pid) : null), + processGeneration: (pid) => + process.platform === "linux" ? linuxProcessGeneration(pid) : null, processAlive: defaultProcessAlive, }; @@ -143,7 +148,9 @@ export function observeOnboardLock( try { fd = fs.openSync( lockPath, - fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), + fs.constants.O_RDONLY | + (fs.constants.O_NOFOLLOW ?? 0) | + (fs.constants.O_NONBLOCK ?? 0), ); } catch (error) { if (errnoCode(error) === "ENOENT") return { kind: "absent" }; @@ -178,7 +185,9 @@ export function observeOnboardLock( ) { return { kind: "busy", reason: "publishing" }; } - const owner = parseOwner(JSON.parse(bytes.subarray(0, length).toString("utf8"))); + const owner = parseOwner( + JSON.parse(bytes.subarray(0, length).toString("utf8")), + ); if (!owner) return { kind: "busy", reason: "unverified" }; const hostIdentity = evidence.hostIdentity(); @@ -191,7 +200,8 @@ export function observeOnboardLock( ) { return { kind: "busy", reason: "foreign", owner }; } - if (!evidence.processAlive(owner.pid)) return { kind: "stale", reason: "departed", owner }; + if (!evidence.processAlive(owner.pid)) + return { kind: "stale", reason: "departed", owner }; const generation = evidence.processGeneration(owner.pid); if (!generation) return { kind: "busy", reason: "unverified", owner }; if (generation !== owner.processGeneration) From a1b975a2e4af6898e605bf2b9c79e38d4de253be Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 14:44:35 -0400 Subject: [PATCH 04/10] style(state): apply repository formatter Signed-off-by: Julie Yaunches --- .../onboard-session/lock-observation.test.ts | 15 ++++----------- .../state/onboard-session/lock-observation.ts | 17 +++++------------ 2 files changed, 9 insertions(+), 23 deletions(-) diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index 5fec6bcf3a0..275f3f9436a 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -20,9 +20,7 @@ function fixture(): { lock: string; owner: OnboardLockOwner; } { - const root = fs.mkdtempSync( - path.join(os.tmpdir(), "nemoclaw-onboard-observation-"), - ); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-observation-")); roots.push(root); const lock = path.join(root, "onboard.lock"); const owner: OnboardLockOwner = { @@ -47,8 +45,7 @@ function writeOwner(lock: string, owner: OnboardLockOwner): void { } afterEach(() => { - for (const root of roots.splice(0)) - fs.rmSync(root, { recursive: true, force: true }); + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); describe("onboarding lock observation", () => { @@ -60,9 +57,7 @@ describe("onboarding lock observation", () => { it("reports only proven-local departed and reused owners as stale", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); - expect( - observeOnboardLock(lock, { ...evidence, processAlive: () => false }), - ).toMatchObject({ + expect(observeOnboardLock(lock, { ...evidence, processAlive: () => false })).toMatchObject({ kind: "stale", reason: "departed", }); @@ -82,9 +77,7 @@ describe("onboarding lock observation", () => { ] as const)("keeps %s owners busy", (reason, overrides) => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); - expect( - observeOnboardLock(lock, { ...evidence, ...overrides }), - ).toMatchObject({ + expect(observeOnboardLock(lock, { ...evidence, ...overrides })).toMatchObject({ kind: "busy", reason, }); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts index b9737db8432..dd6d03bcaa5 100644 --- a/src/lib/state/onboard-session/lock-observation.ts +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -44,8 +44,7 @@ function readTrimmed(path: string): string | null { } function errnoCode(error: unknown): string | undefined { - if (!error || typeof error !== "object" || !("code" in error)) - return undefined; + if (!error || typeof error !== "object" || !("code" in error)) return undefined; return typeof error.code === "string" ? error.code : undefined; } @@ -93,8 +92,7 @@ export const systemOnboardLockEvidence: OnboardLockEvidence = { return null; } }, - processGeneration: (pid) => - process.platform === "linux" ? linuxProcessGeneration(pid) : null, + processGeneration: (pid) => (process.platform === "linux" ? linuxProcessGeneration(pid) : null), processAlive: defaultProcessAlive, }; @@ -148,9 +146,7 @@ export function observeOnboardLock( try { fd = fs.openSync( lockPath, - fs.constants.O_RDONLY | - (fs.constants.O_NOFOLLOW ?? 0) | - (fs.constants.O_NONBLOCK ?? 0), + fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0), ); } catch (error) { if (errnoCode(error) === "ENOENT") return { kind: "absent" }; @@ -185,9 +181,7 @@ export function observeOnboardLock( ) { return { kind: "busy", reason: "publishing" }; } - const owner = parseOwner( - JSON.parse(bytes.subarray(0, length).toString("utf8")), - ); + const owner = parseOwner(JSON.parse(bytes.subarray(0, length).toString("utf8"))); if (!owner) return { kind: "busy", reason: "unverified" }; const hostIdentity = evidence.hostIdentity(); @@ -200,8 +194,7 @@ export function observeOnboardLock( ) { return { kind: "busy", reason: "foreign", owner }; } - if (!evidence.processAlive(owner.pid)) - return { kind: "stale", reason: "departed", owner }; + if (!evidence.processAlive(owner.pid)) return { kind: "stale", reason: "departed", owner }; const generation = evidence.processGeneration(owner.pid); if (!generation) return { kind: "busy", reason: "unverified", owner }; if (generation !== owner.processGeneration) From 86b51133b76b226c332d62cae35ee6aa77bef353 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 15:16:51 -0400 Subject: [PATCH 05/10] fix(state): explain unverified lock recovery Signed-off-by: Julie Yaunches --- src/lib/state/legacy-port-migration.test.ts | 61 +++++++++++---------- src/lib/state/legacy-port-migration.ts | 38 ++++--------- 2 files changed, 44 insertions(+), 55 deletions(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 10f2f07bd26..877fafbff8d 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -12,10 +12,7 @@ const { observeOnboardLock } = vi.hoisted(() => ({ })); vi.mock("./onboard-session/lock-observation", () => ({ observeOnboardLock })); -import { - type OnboardEntryOptionsDeps, - resolveOnboardEntryOptions, -} from "../onboard/entry-options"; +import { type OnboardEntryOptionsDeps, resolveOnboardEntryOptions } from "../onboard/entry-options"; import { migrateLegacyPortState } from "./legacy-port-migration"; import type { OnboardLockObservation } from "./onboard-session/lock-observation"; import { @@ -436,9 +433,14 @@ describe("legacy non-default gateway state migration", () => { fs.mkdirSync(root(shared, selected), { recursive: true }); fs.writeFileSync(path.join(root(shared, selected), "onboard.lock"), "active writer"); - observeOnboardLock.mockReturnValue({ kind: "busy", reason: "unverified" }); + observeOnboardLock.mockImplementation((lockPath) => + fs.existsSync(lockPath) ? { kind: "busy", reason: "unverified" } : { kind: "absent" }, + ); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - /onboarding lock .* is unverified/u, + new RegExp( + `onboarding lock .* is unverified; confirm no NemoClaw onboarding process .* then remove only ${path.join(root(shared, selected), "onboard.lock")} and retry; migration will not remove it automatically`, + "u", + ), ); expect(fs.readFileSync(recoveryFile, "utf8")).toBe(before); expect(fs.existsSync(path.join(selected, "retained-sandbox-recovery.json"))).toBe(false); @@ -478,33 +480,34 @@ describe("legacy non-default gateway state migration", () => { expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); }); - it.each( - ["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"], - )("keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", (entry) => { - const home = makeHome(); - const shared = path.join(home, ".nemoclaw"); - const selected = path.join(shared, "gateways", "9123"); - writeJson(path.join(shared, "sandboxes.json"), { - defaultSandbox: "port-box", - sandboxes: { - "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, - }, - }); - writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); - fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); - fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); - fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); + it.each(["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"])( + "keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", + (entry) => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + writeJson(path.join(shared, "sandboxes.json"), { + defaultSandbox: "port-box", + sandboxes: { + "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, + }, + }); + writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); + fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); + fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); + fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); - const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); + const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); - expect(result.warnings).toEqual([]); + expect(result.warnings).toEqual([]); - expect(fs.existsSync(path.join(shared, entry))).toBe(true); - expect(fs.existsSync(path.join(selected, entry))).toBe(false); + expect(fs.existsSync(path.join(shared, entry))).toBe(true); + expect(fs.existsSync(path.join(selected, entry))).toBe(false); - expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); - expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); - }); + expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); + expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); + }, + ); it.each([8080, 9123])( "removes only generated stale migration-intent directories for gateway port %i", diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index 37e23853457..4b359270622 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -492,10 +492,9 @@ function readMigrationIntent(home: string, sharedRoot: string): LegacyPortMigrat } if ( selectedRecovery === null && - readRetainedRecoveryDocument( - home, - retainedSandboxRecoveryFile(sharedRoot), - )?.unresolved.some((record) => record.gatewayPort === gatewayPort) + readRetainedRecoveryDocument(home, retainedSandboxRecoveryFile(sharedRoot))?.unresolved.some( + (record) => record.gatewayPort === gatewayPort, + ) ) { throw migrationError( "published migration intent predates retained recovery partitioning; retained recovery remains safely in the shared root", @@ -639,17 +638,9 @@ function applyMigrationIntent( } if (intent.selectedRecovery && intent.remainingRecovery) { - writeJsonAtomic( - home, - retainedSandboxRecoveryFile(selectedRoot), - intent.selectedRecovery, - ); + writeJsonAtomic(home, retainedSandboxRecoveryFile(selectedRoot), intent.selectedRecovery); if (intent.remainingRecovery.unresolved.length > 0) { - writeJsonAtomic( - home, - retainedSandboxRecoveryFile(sharedRoot), - intent.remainingRecovery, - ); + writeJsonAtomic(home, retainedSandboxRecoveryFile(sharedRoot), intent.remainingRecovery); } else { removeRetainedRecoveryFile(home, retainedSandboxRecoveryFile(sharedRoot)); } @@ -749,10 +740,11 @@ function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]) const lock = observeOnboardLock(activeLock); if (lock.kind === "busy") { const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; - throw migrationError( - `onboarding lock ${activeLock}${owner} is ${lock.reason}; ` + - "finish that run or verify the lock owner before retrying", - ); + const recovery = + lock.reason === "unverified" + ? `confirm no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${activeLock} and retry; migration will not remove it automatically` + : "finish that run or verify the lock owner before retrying"; + throw migrationError(`onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`); } } } @@ -870,9 +862,7 @@ export function migrateLegacyPortState( const remainingRecoveryRecords = recovery?.unresolved.filter((record) => record.gatewayPort !== gatewayPort) ?? []; const selectedRecovery = - selectedRecoveryRecords.length > 0 - ? retainedRecoveryDocument(selectedRecoveryRecords) - : null; + selectedRecoveryRecords.length > 0 ? retainedRecoveryDocument(selectedRecoveryRecords) : null; const remainingRecovery = selectedRecovery ? retainedRecoveryDocument(remainingRecoveryRecords) : null; @@ -913,11 +903,7 @@ export function migrateLegacyPortState( } } if (selectedRecovery) { - preflightMovePath( - home, - legacyRecoveryFile, - retainedSandboxRecoveryFile(selectedRoot), - ); + preflightMovePath(home, legacyRecoveryFile, retainedSandboxRecoveryFile(selectedRoot)); } registryLocks.push(acquireDirectoryLock(home, `${selectedRegistryFile}.lock`)); From a8ce1da554a5664a0ae0528bb2ea1818959c7fd1 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 15:18:52 -0400 Subject: [PATCH 06/10] style(state): minimize recovery guidance diff Signed-off-by: Julie Yaunches --- src/lib/state/legacy-port-migration.test.ts | 56 +++++++++++---------- src/lib/state/legacy-port-migration.ts | 33 +++++++++--- 2 files changed, 55 insertions(+), 34 deletions(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 877fafbff8d..68384d87069 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -12,7 +12,10 @@ const { observeOnboardLock } = vi.hoisted(() => ({ })); vi.mock("./onboard-session/lock-observation", () => ({ observeOnboardLock })); -import { type OnboardEntryOptionsDeps, resolveOnboardEntryOptions } from "../onboard/entry-options"; +import { + type OnboardEntryOptionsDeps, + resolveOnboardEntryOptions, +} from "../onboard/entry-options"; import { migrateLegacyPortState } from "./legacy-port-migration"; import type { OnboardLockObservation } from "./onboard-session/lock-observation"; import { @@ -434,7 +437,9 @@ describe("legacy non-default gateway state migration", () => { fs.writeFileSync(path.join(root(shared, selected), "onboard.lock"), "active writer"); observeOnboardLock.mockImplementation((lockPath) => - fs.existsSync(lockPath) ? { kind: "busy", reason: "unverified" } : { kind: "absent" }, + fs.existsSync(lockPath) + ? { kind: "busy", reason: "unverified" } + : { kind: "absent" }, ); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( new RegExp( @@ -480,34 +485,33 @@ describe("legacy non-default gateway state migration", () => { expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); }); - it.each(["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"])( - "keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", - (entry) => { - const home = makeHome(); - const shared = path.join(home, ".nemoclaw"); - const selected = path.join(shared, "gateways", "9123"); - writeJson(path.join(shared, "sandboxes.json"), { - defaultSandbox: "port-box", - sandboxes: { - "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, - }, - }); - writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); - fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); - fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); - fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); + it.each( + ["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"], + )("keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", (entry) => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + writeJson(path.join(shared, "sandboxes.json"), { + defaultSandbox: "port-box", + sandboxes: { + "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, + }, + }); + writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); + fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); + fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); + fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); - const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); + const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); - expect(result.warnings).toEqual([]); + expect(result.warnings).toEqual([]); - expect(fs.existsSync(path.join(shared, entry))).toBe(true); - expect(fs.existsSync(path.join(selected, entry))).toBe(false); + expect(fs.existsSync(path.join(shared, entry))).toBe(true); + expect(fs.existsSync(path.join(selected, entry))).toBe(false); - expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); - expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); - }, - ); + expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); + expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); + }); it.each([8080, 9123])( "removes only generated stale migration-intent directories for gateway port %i", diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index 4b359270622..27f3fca04cd 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -492,9 +492,10 @@ function readMigrationIntent(home: string, sharedRoot: string): LegacyPortMigrat } if ( selectedRecovery === null && - readRetainedRecoveryDocument(home, retainedSandboxRecoveryFile(sharedRoot))?.unresolved.some( - (record) => record.gatewayPort === gatewayPort, - ) + readRetainedRecoveryDocument( + home, + retainedSandboxRecoveryFile(sharedRoot), + )?.unresolved.some((record) => record.gatewayPort === gatewayPort) ) { throw migrationError( "published migration intent predates retained recovery partitioning; retained recovery remains safely in the shared root", @@ -638,9 +639,17 @@ function applyMigrationIntent( } if (intent.selectedRecovery && intent.remainingRecovery) { - writeJsonAtomic(home, retainedSandboxRecoveryFile(selectedRoot), intent.selectedRecovery); + writeJsonAtomic( + home, + retainedSandboxRecoveryFile(selectedRoot), + intent.selectedRecovery, + ); if (intent.remainingRecovery.unresolved.length > 0) { - writeJsonAtomic(home, retainedSandboxRecoveryFile(sharedRoot), intent.remainingRecovery); + writeJsonAtomic( + home, + retainedSandboxRecoveryFile(sharedRoot), + intent.remainingRecovery, + ); } else { removeRetainedRecoveryFile(home, retainedSandboxRecoveryFile(sharedRoot)); } @@ -744,7 +753,9 @@ function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]) lock.reason === "unverified" ? `confirm no NemoClaw onboarding process in any environment sharing this state root is active, then remove only ${activeLock} and retry; migration will not remove it automatically` : "finish that run or verify the lock owner before retrying"; - throw migrationError(`onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`); + throw migrationError( + `onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`, + ); } } } @@ -862,7 +873,9 @@ export function migrateLegacyPortState( const remainingRecoveryRecords = recovery?.unresolved.filter((record) => record.gatewayPort !== gatewayPort) ?? []; const selectedRecovery = - selectedRecoveryRecords.length > 0 ? retainedRecoveryDocument(selectedRecoveryRecords) : null; + selectedRecoveryRecords.length > 0 + ? retainedRecoveryDocument(selectedRecoveryRecords) + : null; const remainingRecovery = selectedRecovery ? retainedRecoveryDocument(remainingRecoveryRecords) : null; @@ -903,7 +916,11 @@ export function migrateLegacyPortState( } } if (selectedRecovery) { - preflightMovePath(home, legacyRecoveryFile, retainedSandboxRecoveryFile(selectedRoot)); + preflightMovePath( + home, + legacyRecoveryFile, + retainedSandboxRecoveryFile(selectedRoot), + ); } registryLocks.push(acquireDirectoryLock(home, `${selectedRegistryFile}.lock`)); From 44fc9ac6f5d6ddbde3dcd3c063d82e125d65b419 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 15:41:19 -0400 Subject: [PATCH 07/10] test(state): type lock observer mock Signed-off-by: Julie Yaunches --- src/lib/state/legacy-port-migration.test.ts | 62 ++++++++++----------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 68384d87069..3f2d510abfd 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -8,14 +8,13 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; const { observeOnboardLock } = vi.hoisted(() => ({ - observeOnboardLock: vi.fn<() => OnboardLockObservation>(() => ({ kind: "absent" })), + observeOnboardLock: vi.fn<(lockPath: string) => OnboardLockObservation>(() => ({ + kind: "absent", + })), })); vi.mock("./onboard-session/lock-observation", () => ({ observeOnboardLock })); -import { - type OnboardEntryOptionsDeps, - resolveOnboardEntryOptions, -} from "../onboard/entry-options"; +import { type OnboardEntryOptionsDeps, resolveOnboardEntryOptions } from "../onboard/entry-options"; import { migrateLegacyPortState } from "./legacy-port-migration"; import type { OnboardLockObservation } from "./onboard-session/lock-observation"; import { @@ -436,10 +435,8 @@ describe("legacy non-default gateway state migration", () => { fs.mkdirSync(root(shared, selected), { recursive: true }); fs.writeFileSync(path.join(root(shared, selected), "onboard.lock"), "active writer"); - observeOnboardLock.mockImplementation((lockPath) => - fs.existsSync(lockPath) - ? { kind: "busy", reason: "unverified" } - : { kind: "absent" }, + observeOnboardLock.mockImplementation((lockPath: string): OnboardLockObservation => + fs.existsSync(lockPath) ? { kind: "busy", reason: "unverified" } : { kind: "absent" }, ); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( new RegExp( @@ -485,33 +482,34 @@ describe("legacy non-default gateway state migration", () => { expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); }); - it.each( - ["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"], - )("keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", (entry) => { - const home = makeHome(); - const shared = path.join(home, ".nemoclaw"); - const selected = path.join(shared, "gateways", "9123"); - writeJson(path.join(shared, "sandboxes.json"), { - defaultSandbox: "port-box", - sandboxes: { - "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, - }, - }); - writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); - fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); - fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); - fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); + it.each(["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"])( + "keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", + (entry) => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + writeJson(path.join(shared, "sandboxes.json"), { + defaultSandbox: "port-box", + sandboxes: { + "port-box": { name: "port-box", gatewayName: "nemoclaw-9123", gatewayPort: 9123 }, + }, + }); + writeJson(path.join(shared, "credentials.json"), { NVIDIA_API_KEY: "selected-secret" }); + fs.writeFileSync(path.join(shared, "ollama-proxy-token"), "host-token\n"); + fs.writeFileSync(path.join(shared, "ollama-proxy-port"), "11435\n"); + fs.writeFileSync(path.join(shared, "ollama-auth-proxy.pid"), "4242\n"); - const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); + const result = migrateLegacyPortState({ home, gatewayPort: 9123 }); - expect(result.warnings).toEqual([]); + expect(result.warnings).toEqual([]); - expect(fs.existsSync(path.join(shared, entry))).toBe(true); - expect(fs.existsSync(path.join(selected, entry))).toBe(false); + expect(fs.existsSync(path.join(shared, entry))).toBe(true); + expect(fs.existsSync(path.join(selected, entry))).toBe(false); - expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); - expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); - }); + expect(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); + expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); + }, + ); it.each([8080, 9123])( "removes only generated stale migration-intent directories for gateway port %i", From 7af51b4005b8a992feac48dd43d5fd0f44aae4ba Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 16:05:40 -0400 Subject: [PATCH 08/10] test(state): cover unsafe onboarding lock paths Signed-off-by: Julie Yaunches --- .../onboard-session/lock-observation.test.ts | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index 275f3f9436a..9bdbd170d42 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -5,7 +5,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { spawnSync } from "node:child_process"; + +import { afterEach, describe, expect, it, vi } from "vitest"; import { observeOnboardLock, @@ -100,6 +102,49 @@ describe("onboarding lock observation", () => { }); }); + it("keeps symlink and hard-linked lock paths unsafe", () => { + const { evidence, lock, owner } = fixture(); + const target = `${lock}.target`; + writeOwner(target, owner); + fs.symlinkSync(target, lock); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + + fs.rmSync(lock); + fs.linkSync(target, lock); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + }); + + it.runIf(process.platform !== "win32")("keeps a FIFO lock path unsafe", () => { + const { evidence, lock } = fixture(); + expect(spawnSync("mkfifo", [lock]).status).toBe(0); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + }); + + it("keeps a lock changed during its stable read busy", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + const original = fs.fstatSync.bind(fs); + let calls = 0; + vi.spyOn(fs, "fstatSync").mockImplementation((fd) => { + calls += 1; + if (calls === 2) fs.appendFileSync(lock, " "); + return original(fd); + }); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); + }); + + it("keeps a lock replaced between descriptor and path checks unsafe", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + const original = fs.lstatSync.bind(fs); + vi.spyOn(fs, "lstatSync").mockImplementation((path) => { + fs.renameSync(lock, `${lock}.old`); + writeOwner(lock, owner); + return original(path); + }); + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "unsafe" }); + }); + it.each([0, -1])("keeps a malformed PID %s unverified", (pid) => { const { evidence, lock, owner } = fixture(); writeOwner(lock, { ...owner, pid }); From 13c2036f3e02ad8dcbca1897cb38991b44016c02 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Thu, 3 Sep 2026 16:31:26 -0400 Subject: [PATCH 09/10] test(state): avoid conditional safety setup Signed-off-by: Julie Yaunches --- .../state/onboard-session/lock-observation.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index 9bdbd170d42..c3500700aa1 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -124,12 +124,12 @@ describe("onboarding lock observation", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); const original = fs.fstatSync.bind(fs); - let calls = 0; - vi.spyOn(fs, "fstatSync").mockImplementation((fd) => { - calls += 1; - if (calls === 2) fs.appendFileSync(lock, " "); - return original(fd); - }); + vi.spyOn(fs, "fstatSync") + .mockImplementationOnce((fd) => original(fd)) + .mockImplementationOnce((fd) => { + fs.appendFileSync(lock, " "); + return original(fd); + }); expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); }); From 2fabbe18e934877536faf9889617d26084854d72 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Fri, 4 Sep 2026 00:30:38 -0700 Subject: [PATCH 10/10] fix(state): fail closed on unsafe onboarding locks Signed-off-by: Prekshi Vyas --- src/lib/state/legacy-port-migration.test.ts | 17 ++++++++ src/lib/state/legacy-port-migration.ts | 1 + .../onboard-session/lock-observation.test.ts | 42 +++++++++++++++++++ .../state/onboard-session/lock-observation.ts | 5 ++- 4 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 3f2d510abfd..0b35e52a0c2 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -482,6 +482,23 @@ describe("legacy non-default gateway state migration", () => { expect(fs.existsSync(path.join(selected, "onboard-session.json"))).toBe(true); }); + it("refuses an onboarding lock below a symbolic-link state root", () => { + const home = makeHome(); + const shared = path.join(home, ".nemoclaw"); + const selected = path.join(shared, "gateways", "9123"); + const outside = path.join(home, "outside"); + recordRecovery(path.join(shared, "retained-sandbox-recovery.json"), "port-box", 9123, "d"); + fs.mkdirSync(path.dirname(selected), { recursive: true }); + fs.mkdirSync(outside); + fs.writeFileSync(path.join(outside, "onboard.lock"), "outside lock"); + fs.symlinkSync(outside, selected, "dir"); + + expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow(/symbolic link/); + expect(observeOnboardLock).toHaveBeenCalledOnce(); + expect(observeOnboardLock).toHaveBeenCalledWith(path.join(shared, "onboard.lock")); + expect(fs.readFileSync(path.join(outside, "onboard.lock"), "utf8")).toBe("outside lock"); + }); + it.each(["ollama-proxy-token", "ollama-proxy-port", "ollama-auth-proxy.pid"])( "keeps host-shared Ollama proxy state out of a non-default gateway migration [%s]", (entry) => { diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index 27f3fca04cd..b106512d0a1 100644 --- a/src/lib/state/legacy-port-migration.ts +++ b/src/lib/state/legacy-port-migration.ts @@ -746,6 +746,7 @@ function acquireDirectoryLock(home: string, lock: string): string { function assertOnboardStateUnlocked(home: string, stateRoots: readonly string[]): void { for (const stateRoot of stateRoots) { const activeLock = path.join(stateRoot, "onboard.lock"); + assertGatewayStatePathSafe(home, activeLock); const lock = observeOnboardLock(activeLock); if (lock.kind === "busy") { const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; diff --git a/src/lib/state/onboard-session/lock-observation.test.ts b/src/lib/state/onboard-session/lock-observation.test.ts index c3500700aa1..5b7ae8243c8 100644 --- a/src/lib/state/onboard-session/lock-observation.test.ts +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -11,6 +11,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { observeOnboardLock, + systemOnboardLockEvidence, type OnboardLockEvidence, type OnboardLockOwner, } from "./lock-observation"; @@ -47,6 +48,7 @@ function writeOwner(lock: string, owner: OnboardLockOwner): void { } afterEach(() => { + vi.restoreAllMocks(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); @@ -133,6 +135,22 @@ describe("onboarding lock observation", () => { expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); }); + it("keeps a short lock read busy", () => { + const { evidence, lock, owner } = fixture(); + const ownerBytes = Buffer.from(JSON.stringify(owner)); + fs.writeFileSync(lock, Buffer.concat([ownerBytes, Buffer.from(" invalid")]), { mode: 0o600 }); + vi.spyOn(fs, "readSync").mockImplementation((( + _fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + ) => { + ownerBytes.copy(buffer as Buffer, offset); + return ownerBytes.length; + }) as typeof fs.readSync); + + expect(observeOnboardLock(lock, evidence)).toEqual({ kind: "busy", reason: "publishing" }); + }); + it("keeps a lock replaced between descriptor and path checks unsafe", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, owner); @@ -154,6 +172,30 @@ describe("onboarding lock observation", () => { }); }); + it("keeps an out-of-range PID unverified", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, { ...owner, pid: Number.MAX_SAFE_INTEGER }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unverified", + }); + }); + + it("does not report departure when the process probe fails without ESRCH", () => { + const { evidence, lock, owner } = fixture(); + writeOwner(lock, owner); + vi.spyOn(process, "kill").mockImplementation(() => { + throw Object.assign(new Error("probe failed"), { code: "EIO" }); + }); + + expect( + observeOnboardLock(lock, { + ...evidence, + processAlive: systemOnboardLockEvidence.processAlive, + }), + ).toEqual({ kind: "busy", reason: "active", owner }); + }); + it("keeps an empty process generation unverified", () => { const { evidence, lock, owner } = fixture(); writeOwner(lock, { ...owner, processGeneration: "" }); diff --git a/src/lib/state/onboard-session/lock-observation.ts b/src/lib/state/onboard-session/lock-observation.ts index dd6d03bcaa5..bea81db4684 100644 --- a/src/lib/state/onboard-session/lock-observation.ts +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -4,6 +4,7 @@ import fs from "node:fs"; const MAX_LOCK_BYTES = 64 * 1024; +const MAX_PROCESS_ID = 0x7fffffff; export interface OnboardLockOwner { pid: number; @@ -54,7 +55,7 @@ function defaultProcessAlive(pid: number): boolean { process.kill(pid, 0); return true; } catch (error) { - return errnoCode(error) === "EPERM"; + return errnoCode(error) !== "ESRCH"; } } @@ -121,6 +122,7 @@ function parseOwner(value: unknown): OnboardLockOwner | null { typeof record.pid !== "number" || !Number.isSafeInteger(record.pid) || record.pid <= 0 || + record.pid > MAX_PROCESS_ID || typeof record.processGeneration !== "string" || record.processGeneration.length === 0 || typeof record.hostIdentity !== "string" || @@ -173,6 +175,7 @@ export function observeOnboardLock( const after = fs.fstatSync(fd); if ( length > MAX_LOCK_BYTES || + length !== before.size || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size ||