diff --git a/src/lib/state/legacy-port-migration.test.ts b/src/lib/state/legacy-port-migration.test.ts index 1adfbc007b3..0b35e52a0c2 100644 --- a/src/lib/state/legacy-port-migration.test.ts +++ b/src/lib/state/legacy-port-migration.test.ts @@ -7,11 +7,16 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { - type OnboardEntryOptionsDeps, - resolveOnboardEntryOptions, -} from "../onboard/entry-options"; +const { observeOnboardLock } = vi.hoisted(() => ({ + observeOnboardLock: vi.fn<(lockPath: string) => 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 +92,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,41 +435,99 @@ 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: string): OnboardLockObservation => + fs.existsSync(lockPath) ? { kind: "busy", reason: "unverified" } : { kind: "absent" }, + ); expect(() => migrateLegacyPortState({ home, gatewayPort: 9123 })).toThrow( - /onboarding lock .* is present/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); }); - 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) => { + 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, "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 }); + 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(result.warnings).toEqual([]); + 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); + }); - expect(fs.existsSync(path.join(shared, entry))).toBe(true); - expect(fs.existsSync(path.join(selected, entry))).toBe(false); + 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(fs.existsSync(path.join(shared, "credentials.json"))).toBe(false); - expect(fs.existsSync(path.join(selected, "credentials.json"))).toBe(true); + 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) => { + 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 }); + + 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, "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", (gatewayPort) => { diff --git a/src/lib/state/legacy-port-migration.ts b/src/lib/state/legacy-port-migration.ts index be3c0017999..b106512d0a1 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,16 @@ 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)) { + assertGatewayStatePathSafe(home, activeLock); + const lock = observeOnboardLock(activeLock); + if (lock.kind === "busy") { + const owner = lock.owner ? ` recorded for PID ${String(lock.owner.pid)}` : ""; + 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} is present; finish or stop that run before migrating state`, + `onboarding lock ${activeLock}${owner} is ${lock.reason}; ${recovery}`, ); } } 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..5b7ae8243c8 --- /dev/null +++ b/src/lib/state/onboard-session/lock-observation.test.ts @@ -0,0 +1,223 @@ +// 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 { spawnSync } from "node:child_process"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + observeOnboardLock, + systemOnboardLockEvidence, + 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(() => { + vi.restoreAllMocks(); + 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("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); + 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" }); + }); + + 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); + 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 }); + expect(observeOnboardLock(lock, evidence)).toEqual({ + kind: "busy", + reason: "unverified", + }); + }); + + 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: "" }); + 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); + 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..bea81db4684 --- /dev/null +++ b/src/lib/state/onboard-session/lock-observation.ts @@ -0,0 +1,211 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +const MAX_LOCK_BYTES = 64 * 1024; +const MAX_PROCESS_ID = 0x7fffffff; + +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 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 errnoCode(error) !== "ESRCH"; + } +} + +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 ( + 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" || + 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 (errnoCode(error) === "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 || + length !== before.size || + 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); + } +}