diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 85c95422fcd..53b6a27e795 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -127,7 +127,7 @@ Si OpenCodex no puede confirmar que un envoltorio terminó porque no dispone de de objeto de proceso (handle), como puede ocurrir en ARM64, compruébalo en el Administrador de tareas desde la sesión de su propietario, detenlo si sigue en ejecución y vuelve a intentarlo. -Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy, deja intacta la configuración del cliente y falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`: +Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy ni continúa con la restauración nativa compartida. En un Child de Remote Link, el prevuelo puede haber eliminado ya las integraciones de archivos propiedad del Link y pausado la sincronización; repara la parada del servicio y vuelve a ejecutar `ocx stop`. El comando falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`: | `serviceStopReason` | Significado | Qué hacer | |---|---|---| diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index 2cea913f521..a2567b88b82 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -198,9 +198,11 @@ eligible for termination, stop it from its owning Windows session using Task Man If OpenCodex cannot confirm a wrapper's exit without a process handle, as can happen on ARM64, check it in Task Manager from its owning session, stop it if it is still running, and retry. -When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy, leaves -your client configuration alone, and fails. With `--json` the summary keeps `outcome: "failed"` -and `proxy: "unknown"`, and adds `serviceStopReason`: +When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy and +does not proceed to shared native restoration. On a Remote Link Child, preflight may already have +removed Link-owned file integrations and paused sync; repair the service stop and retry `ocx stop`. +The command fails. With `--json` the summary keeps `outcome: "failed"` and `proxy: "unknown"`, +and adds `serviceStopReason`: | `serviceStopReason` | Meaning | What to do | |---|---|---| diff --git a/scripts/test-layout/layout-clients.json b/scripts/test-layout/layout-clients.json index 4a4eda1f781..3c2d9e34d62 100644 --- a/scripts/test-layout/layout-clients.json +++ b/scripts/test-layout/layout-clients.json @@ -179,6 +179,9 @@ "client-link-runtime.test.ts": "clients", "client-link-stop.test.ts": "clients", "client-link-stop-recovery.test.ts": "clients", + "windows-stop-owner-identity.test.ts": "windows", + "client-recycle-exclusion.test.ts": "clients", + "client-restart-rollback-lock.test.ts": "clients", "client-link-stop-sibling.test.ts": "clients", "link-routes.test.ts": "clients", "client-link-state.test.ts": "clients", diff --git a/src/client/runtime-recycle.ts b/src/client/runtime-recycle.ts new file mode 100644 index 00000000000..e0fb65498b3 --- /dev/null +++ b/src/client/runtime-recycle.ts @@ -0,0 +1,29 @@ +import { withConfigMutationLockSync } from "../config"; +import type { OcxClientConnectionConfig } from "../types"; +import { withLinkApply } from "./link-home"; +import { clientConnectionEnded } from "./runtime-restart"; +import { pendingClientConnectMayOwnToken, readClientConnectionStateWithEvidence } from "./state"; + +/** + * Called outside L: Link apply exclusion is outermost in the apply -> N -> L -> C order. + * Once admitted, keep it through all teardown awaits; a new connect cannot commit halfway. + */ +export async function runClientRecycleWithAdmission( + served: OcxClientConnectionConfig, + allowed: () => boolean, + teardown: () => Promise, +): Promise { + let admitted = false; + try { + return await withLinkApply(async () => { + admitted = withConfigMutationLockSync(() => allowed() && !pendingClientConnectMayOwnToken() + && clientConnectionEnded(served, readClientConnectionStateWithEvidence())); + if (!admitted) return false; + await teardown(); + return true; + }); + } catch (error) { + if (admitted) throw error; // A started teardown must not masquerade as an admission refusal. + return false; + } +} diff --git a/src/client/runtime-rollback.ts b/src/client/runtime-rollback.ts new file mode 100644 index 00000000000..f2e0380377b --- /dev/null +++ b/src/client/runtime-rollback.ts @@ -0,0 +1,29 @@ +import { ConfigMutationLockError } from "../config"; +import { CLIENT_RESTART_REBIND_WAIT_MS } from "../lib/system-restart-contract"; + +export type ClientRollbackAttempt = "published" | "busy" | "refused"; + +export function retryableClientRollbackLock(error: unknown): boolean { + if (error && typeof error === "object" && "code" in error && error.code === "client_lifecycle_busy") return true; + const cause = error instanceof ConfigMutationLockError ? error.cause : undefined; + const code = cause && typeof cause === "object" && "code" in cause ? cause.code : undefined; + return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED"; +} + +/** Each busy attempt must close its unpublished listener before this helper may yield. */ +export async function retryClientRollback( + attempt: (remainingMs: number) => Promise, + io: { now?: () => number; sleep?: (ms: number) => Promise; budgetMs?: number } = {}, +): Promise { + const now = io.now ?? (() => performance.now()); + const deadline = now() + (io.budgetMs ?? CLIENT_RESTART_REBIND_WAIT_MS); + while (now() < deadline) { + const result = await attempt(Math.max(0, deadline - now())); + if (result === "published") return true; + if (result !== "busy") return false; + const remaining = deadline - now(); + if (remaining <= 0) return false; + await (io.sleep ?? Bun.sleep)(Math.min(50, remaining)); + } + return false; +} diff --git a/src/client/runtime.ts b/src/client/runtime.ts index dde66d08d9d..ace5c261520 100644 --- a/src/client/runtime.ts +++ b/src/client/runtime.ts @@ -15,7 +15,6 @@ import { createLocalAttestationSecret } from "../lib/local-management-attestatio import { loadServiceTokenFromFile, serviceApiTokenFingerprint } from "../lib/service-secrets"; import { handledSignalExitCode } from "../lib/handled-signal-exit"; import { - CLIENT_RESTART_REBIND_WAIT_MS, DESKTOP_RESTART_EXIT_CODE, DESKTOP_SUPERVISED_ENV, DESKTOP_SUPERVISED_PORT_WAIT_MS, @@ -39,9 +38,11 @@ import { createLinkParityReporter, type LinkParityReporter } from "./link-parity import { restoreLinkClientRoutingBeforeExit } from "./stop-routing"; import { observeClientStopOwner } from "./stop-teardown-owner"; import { SUPERVISOR_MARKER_ENVS } from "../lib/supervisor-markers"; -import { markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime"; +import { isPublishedRuntimeStopping, markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime"; import { startRouteIntentTick, type RouteIntentTick } from "../integrations/route-intent-tick"; import { startRouteIntentWatch, type RouteIntentRuntimeWatch } from "./route-intent-watch"; +import { runClientRecycleWithAdmission } from "./runtime-recycle"; +import { retryClientRollback, retryableClientRollbackLock, type ClientRollbackAttempt } from "./runtime-rollback"; let activeServer: Server | null = null; let activePort: number | null = null; @@ -60,6 +61,7 @@ let clientStopping = false; let explicitClientStopRequested: boolean | undefined; let explicitClientStopOwner: ClientStopOwner | undefined; let standaloneRecycleAllowed = () => !clientStopping; +let activeLinkForRecycle: OcxClientConnectionConfig | undefined; /** * When this runtime's process started (OCX-6, P5): what `/healthz` reports as `startedAt` and the @@ -90,6 +92,8 @@ const LINK_BIND_ATTEMPTS = 3; export interface ClientRuntimeIo { /** Link-mode port budget; defaults to {@link LINK_PORT_WAIT_MS}. */ portWaitMs?: number; + /** Rollback bind attempts share one deadline instead of restarting the port wait. */ + bindDeadlineAt?: number; startListener?: typeof startMachineListener; /** Which supervisor owns this process for a bound restart; tests replace the production check. */ restartSupervisor?: () => Promise<"service" | "desktop" | null>; @@ -200,27 +204,36 @@ export async function recycleStandalone( const exit = io.exitProcess ?? ((code: number) => { process.exit(code); }); // Capture the one-use sibling handoff before this process removes its runtime record. const serviceSupervised = (io.serviceSupervised ?? (() => process.env.OCX_SERVICE === "1"))(); - const replacementEnv = port && !serviceSupervised - ? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff) - : null; - activeCredentialObservation?.stop(); activeCredentialObservation = null; - activeHubRelayRefresh?.stop(); activeHubRelayRefresh = null; - activeReporter?.stop(); activeReporter = null; - activeRouteWatch?.stop(); activeRouteWatch = null; - activeRouteSync?.stop(); activeRouteSync = null; - try { - await activeSupervisor?.stop(); - } catch (error) { - console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`); - } - activeSupervisor = null; - try { - activeServer?.stop(true); - } catch (error) { - console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`); - } - cleanup(); - await flushLinkDiagnostics(); + let replacementEnv: NodeJS.ProcessEnv | null = null; + const teardown = async () => { + replacementEnv = port && !serviceSupervised + ? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff) + : null; + activeCredentialObservation?.stop(); activeCredentialObservation = null; + activeHubRelayRefresh?.stop(); activeHubRelayRefresh = null; + activeReporter?.stop(); activeReporter = null; + activeRouteWatch?.stop(); activeRouteWatch = null; + activeRouteSync?.stop(); activeRouteSync = null; + try { + await activeSupervisor?.stop(); + } catch (error) { + console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`); + } + activeSupervisor = null; + try { + await activeServer?.stop(true); + } catch (error) { + console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`); + } + cleanup(); + await flushLinkDiagnostics(); + }; + if (activeLinkForRecycle) { + if (!(await runClientRecycleWithAdmission(activeLinkForRecycle, standaloneRecycleAllowed, teardown))) { + recycleScheduled = false; + return; + } + } else await teardown(); // Recycling back to standalone after `ocx disconnect` must actually bring a standalone // proxy back, under every launch shape. // @@ -289,17 +302,19 @@ export async function bindClientListener( ): Promise<{ server: Server; port: number }> { const { linkMode } = request; const portWaitMs = io.portWaitMs ?? (linkMode ? linkPortWaitMs() : LINK_PORT_WAIT_MS); - const deadline = Date.now() + portWaitMs; + const deadline = io.bindDeadlineAt ?? Date.now() + portWaitMs; + const remaining = () => Math.max(0, deadline - Date.now()); const busy = (cause: unknown) => new Error( `link mode needs port ${request.configuredPort}; free it or change port`, { cause }, ); let port: number; try { + if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired"); if (linkMode) { const { reclaimListenPort } = await import("../server/port-reclaim"); await reclaimListenPort(request.configuredPort, "127.0.0.1", { - timeoutMs: portWaitMs, + timeoutMs: io.bindDeadlineAt === undefined ? portWaitMs : Math.min(portWaitMs, remaining()), intervalMs: 100, scanIntervalMs: 500, killOcxHolders: false, @@ -307,7 +322,8 @@ export async function bindClientListener( }); } port = await findAvailablePort(request.preferred, "127.0.0.1", { - preferRetryMs: request.explicitPort ? PINNED_PREFER_RETRY_MS : 750, + preferRetryMs: Math.min(request.explicitPort ? PINNED_PREFER_RETRY_MS : 750, + io.bindDeadlineAt === undefined ? Infinity : remaining()), preferRetryIntervalMs: 50, allowEphemeralFallback: linkMode ? false : !request.explicitPort, }); @@ -318,6 +334,7 @@ export async function bindClientListener( const startListener = io.startListener ?? startMachineListener; for (let attempt = 1; ; attempt += 1) { try { + if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired"); const server = startListener(port, { state: request.state, machineApi: { scheduleStandaloneRecycle }, @@ -332,8 +349,8 @@ export async function bindClientListener( } catch (error) { // Check-then-bind: the port can be taken between the probe and Bun.serve. if (!linkMode || !isAddrInUse(error)) throw error; - const waitMs = Math.max(1_000, deadline - Date.now()); - if (attempt >= LINK_BIND_ATTEMPTS + const waitMs = io.bindDeadlineAt === undefined ? Math.max(1_000, remaining()) : remaining(); + if (attempt >= LINK_BIND_ATTEMPTS || waitMs <= 0 || !(await waitForPortAvailable(port, "127.0.0.1", { timeoutMs: waitMs, intervalMs: 100 }))) { throw busy(error); } @@ -384,7 +401,7 @@ export async function startClientRuntime( && (!explicitClientStopOwner || observeClientStopOwner(explicitClientStopOwner) !== "confirmed-stale"); }; // An unpublishable rollback closes the new listener before the caller considers a recycle. - const serve = async (rollback?: { port: number; portWaitMs: number }): Promise => { + const serve = async (rollback?: { port: number; portWaitMs: number }): Promise => { const supervisor = supervised ? createClientLinkSupervisor({ diagnostic: recordLinkDiagnostic, @@ -413,17 +430,20 @@ export async function startClientRuntime( ...(linkReadiness ? { linkReadiness } : {}), ...(supervisor ? { linkConnectionGeneration: () => supervisor.connectionGeneration() } : homeInitiated && link ? { linkConnectionGeneration: () => verifiedHomeConnection(link.linkId) } : {}), - }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs }); + }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs, bindDeadlineAt: Date.now() + rollback.portWaitMs }); + let servingGeneration: string; const publishRecord = (): void => { // A parent stop can arrive after restart admission. Never clear its fence on rollback; // a fresh process has another attestation identity and cannot inherit this request. if (rollback) observeExplicitStop(); writePid(process.pid); // A new generation refuses commits from syncs admitted before the failed restart. - writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration: randomUUID(), + servingGeneration = randomUUID(); + writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration, clientLinkOwner }); }; const activate = (): void => { + activeLinkForRecycle = linkMode ? state.value : undefined; activeServer = server; activePort = boundPort; servedPort = boundPort; @@ -437,7 +457,10 @@ export async function startClientRuntime( if (linkMode && state.value.link && linkKey) { activeReporter = createLinkParityReporter({ connection: state.value, linkKey, runtimeStartedAt: CLIENT_RUNTIME_STARTED_AT }); activeReporter.start(); - const scheduler = startRouteIntentTick(state.value, { onApplied: () => activeReporter?.requestReport() }); + const scheduler = startRouteIntentTick(state.value, { + deferPeriodic: () => isPublishedRuntimeStopping({ pid: process.pid, port: boundPort, attestationSecret, servingGeneration }), + onApplied: () => activeReporter?.requestReport(), + }); activeRouteSync = scheduler; activeRouteWatch = startRouteIntentWatch(state.value, linkKey, { requestSync: () => scheduler.requestSync() }); } @@ -445,7 +468,7 @@ export async function startClientRuntime( if (!rollback) { publishRecord(); activate(); - return true; + return "published"; } // Admission and publication are synchronous after bind. A busy lock must close the // rebound listener before yielding. Link takes C to preserve an explicit stop fence. @@ -454,15 +477,16 @@ export async function startClientRuntime( publishRecord(); return true; }; - let published = false; + let published = false, busy = false; try { published = withClientLifecycleSync(() => linkMode ? withConfigMutationLockSync(publishIfOwned) : publishIfOwned()); - } catch { /* failed admission */ } + } catch (error) { busy = retryableClientRollbackLock(error); } if (published) activate(); else { - try { await server.stop(true); } catch { /* never published */ } + // Do not retain an unrecorded listener across the contention retry's await. + await server.stop(true); } - return published; + return published ? "published" : busy ? "busy" : "refused"; }; // Stop everything this process serves, giving in-flight requests up to `drainMs`. @@ -553,7 +577,11 @@ export async function startClientRuntime( await recycleAfterRollback(); return; } - if (!(await serve({ port: servedPort, portWaitMs: CLIENT_RESTART_REBIND_WAIT_MS }))) { + if (!(await retryClientRollback(async remainingMs => { + observeExplicitStop(); + if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return "refused"; + return serve({ port: servedPort, portWaitMs: remainingMs }); + }))) { await recycleAfterRollback(); } }, diff --git a/src/client/stop-teardown-owner.ts b/src/client/stop-teardown-owner.ts index e0c3085e814..f1ae8cc87ed 100644 --- a/src/client/stop-teardown-owner.ts +++ b/src/client/stop-teardown-owner.ts @@ -1,21 +1,46 @@ -import { execFileSync } from "node:child_process"; import { readlinkSync, statSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; import { NODE_LAUNCH_PROOF_PREFIX } from "../cli/launcher-context"; import { parseStopApproval } from "../cli/stop-approval"; -import { tokenizeCommandLine } from "../codex/app-server-processes"; import { readProcessCommandLine, type ClientStopOwner } from "../config/process-state"; import { readBoundedRegularFileSync } from "../lib/bounded-file-read"; -import { resolveTrustedWindowsPowerShellExe } from "../lib/windows-elevation"; -import { windowsProcessNative, windowsProcessPlatform, windowsProcessPlatformSimulated } from "../service/windows-process-native"; +import { windowsProcessNative, windowsProcessPlatform } from "../service/windows-process-native"; import { readDarwinStopArgv, readDarwinStopCwd, readDarwinStopEnvironment, readDarwinStopStart } from "./stop-darwin-process"; const basename = (value: string) => value.toLowerCase().replace(/\\/g, "/").split("/").pop() ?? ""; +/** Windows native argv rules: apostrophes are literal; only double quotes group arguments. */ +function windowsArgv(commandLine: string): string[] { + if (commandLine.length > 64 * 1024 || /[\0\r\n]/.test(commandLine)) return []; + const argv: string[] = []; + let offset = 0; + while (offset < commandLine.length) { + while (/[ \t]/.test(commandLine[offset] ?? "")) offset++; + if (offset === commandLine.length) break; + let value = "", quoted = false; + while (offset < commandLine.length) { + const character = commandLine[offset]!; + if (!quoted && /[ \t]/.test(character)) break; + // argv[0] is a pathname: its backslashes are literal, including before a closing quote. + if (argv.length > 0 && character === "\\") { + let count = 0; + while (commandLine[offset] === "\\") { count++; offset++; } + if (commandLine[offset] !== '"') { value += "\\".repeat(count); continue; } + value += "\\".repeat(Math.floor(count / 2)); + if (count % 2) { value += '"'; offset++; continue; } + } else if (character !== '"') { value += character; offset++; continue; } + if (argv.length > 0 && quoted && commandLine[offset + 1] === '"') { value += '"'; offset += 2; } + else { quoted = !quoted; offset++; } + } + argv.push(value); + } + return argv; +} + /** Recognize the invocation that sets the native Child's explicit-stop fence, not any ocx. */ export function isClientStopCommandLine(commandLine: string): boolean { if (commandLine.length > 64 * 1024) return false; - return isClientStopArgv(tokenizeCommandLine(commandLine)); + return isClientStopArgv(windowsArgv(commandLine)); } export function isClientStopArgv(argv: readonly string[]): boolean { @@ -25,7 +50,7 @@ export function isClientStopArgv(argv: readonly string[]): boolean { export function isLegacyWindowsStartCommandLine(commandLine: string): boolean { if (commandLine.length > 64 * 1024) return false; - const argv = tokenizeCommandLine(commandLine); + const argv = windowsArgv(commandLine); const command = ocxCommandIndex(argv); return command !== undefined && argv[command] === "start"; } @@ -62,18 +87,8 @@ export function readClientStopProcessStart(pid: number): string | undefined { if (ticks && /^\d+$/.test(ticks) && /^[a-f0-9-]{36}$/.test(boot)) return `linux:${boot}:${ticks}`; } if (platform === "win32") { - const native = windowsProcessNative(); - if (native) { - const identity = native.sameUserIdentity(pid); - return identity ? `win32:${identity.ticks}` : undefined; - } - if (windowsProcessPlatformSimulated()) return; - // The fallback also binds the SID to this incarnation by refreshing CreationDate. - const script = `$ErrorActionPreference='Stop'; $p=Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; $owner=Invoke-CimMethod -InputObject $p -MethodName GetOwnerSid; if ($owner.ReturnValue -eq 0 -and $owner.Sid -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value -and $p.CreationDate) { $after=Get-CimInstance -InputObject $p; if ($after.CreationDate -eq $p.CreationDate) { $p.CreationDate.ToUniversalTime().Ticks } }`; - const ticks = execFileSync(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NoLogo", "-NonInteractive", "-Command", script], { - encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, maxBuffer: 1024, windowsHide: true, - }).trim(); - if (/^\d{1,20}$/.test(ticks)) return `win32:${ticks}`; + const ticks = windowsProcessNative()?.sameUserIdentity(pid)?.ticks; + if (typeof ticks === "bigint" && ticks > 0n && ticks <= 3155378975999999999n) return `win32:${ticks}`; } } catch { /* unreadable ownership cannot authorize a native restoration handoff */ } } diff --git a/src/client/sync-runtime.ts b/src/client/sync-runtime.ts index 8aca45421ec..ab9500e0eeb 100644 --- a/src/client/sync-runtime.ts +++ b/src/client/sync-runtime.ts @@ -24,6 +24,14 @@ export function readSyncRuntime(): RuntimePortState | null { } catch { throw new ClientSyncRuntimeError("client_runtime_unverified"); } } +export function isPublishedRuntimeStopping( + expected: Required>, +): boolean { + const current = readSyncRuntime(); + return current?.clientStopping === true && current.pid === expected.pid && current.port === expected.port + && current.attestationSecret === expected.attestationSecret && current.servingGeneration === expected.servingGeneration; +} + /** Capture and recheck under C. Proven no-runtime sync keeps its existing offline behavior. */ export function clientSyncRuntimeGuard(): () => void { const expected = readSyncRuntime(); diff --git a/src/integrations/route-intent-tick.ts b/src/integrations/route-intent-tick.ts index 3469351c00f..69b2376bc88 100644 --- a/src/integrations/route-intent-tick.ts +++ b/src/integrations/route-intent-tick.ts @@ -3,6 +3,8 @@ import type { OcxClientConnectionConfig } from "../types"; export interface RouteIntentTickDeps { sync?: () => Promise; onApplied?: () => void | Promise; + /** True when this listener's stop fence already rules out a periodic apply. */ + deferPeriodic?: () => boolean; setTimer?: (callback: () => void, ms: number) => unknown; clearTimer?: (timer: unknown) => void; } @@ -32,6 +34,11 @@ export function startRouteIntentTick(connection: OcxClientConnectionConfig, deps do { queued = false; const batch = waiters.splice(0); + if (batch.length === 0 && deps.deferPeriodic) { + let deferred = false; + try { deferred = deps.deferPeriodic(); } catch { /* Let normal sync check uncertain state. */ } + if (deferred) { delay = 5_000; continue; } + } try { const result = await sync(); await deps.onApplied?.(); diff --git a/src/service/windows-process-native.ts b/src/service/windows-process-native.ts index 94658ff1a56..797bae67c22 100644 --- a/src/service/windows-process-native.ts +++ b/src/service/windows-process-native.ts @@ -88,6 +88,29 @@ export function fileTimeToEpochMs(fileTime: bigint): number | null { return ms > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(ms); } +/** Keep owner, lifetime and creation evidence on one process handle; never cache a PID proof. */ +export function readSameUserWindowsStart(pid: number, io: { + open: (pid: number) => number | bigint; + close: (handle: number | bigint) => void; + fileTime: (handle: number | bigint) => bigint | null; + exited: (handle: number | bigint) => boolean | null; + ownerSid: (handle: number | bigint) => string; + currentSid: () => string; +}): bigint | null { + if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff) return null; + const handle = io.open(pid); + if (!handle) return null; + try { + const created = io.fileTime(handle); + if (created === null || created <= FILETIME_UNIX_EPOCH || io.exited(handle) !== false) return null; + const owner = io.ownerSid(handle); + if (!/^S-1-\d+(?:-\d+)+$/.test(owner) || owner !== io.currentSid() || io.exited(handle) !== false) return null; + // Preserve the creation identity already stored by the CIM-based stop owner protocol. + return (created + FILETIME_DOTNET_EPOCH) / 10n * 10n; + } catch { return null; } + finally { io.close(handle); } +} + /** Decode SERVICE_STATUS_PROCESS: the PID only while the service reports RUNNING. */ export function decodeServiceStatusProcess(buffer: Uint8Array): number | null { if (buffer.byteLength < SERVICE_STATUS_PROCESS_BYTES) return null; @@ -224,21 +247,24 @@ function loadNativeApi(): WindowsProcessNativeApi | null { } }, sameUserIdentity(pid, withCommandLine, expectedUserSid) { - const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); - if (!handle) return null; - try { - const fileTime = handleFileTime(handle); - if (fileTime === null) return null; - const userSid = handleUserSid(handle); - if (userSid !== handleUserSid(k.GetCurrentProcess()) || (expectedUserSid !== undefined && userSid !== expectedUserSid)) return null; - const commandLine = withCommandLine ? readWindowsProcessCommandLineFromHandle(handle) : undefined; - if (handleExited(handle) !== false) return null; - return { ticks: fileTimeToCimTicks(fileTime), commandLine }; - } catch { - return null; - } finally { - k.CloseHandle(handle); - } + let commandLine: string | undefined; + const ticks = readSameUserWindowsStart(pid, { + open: target => k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, target), + close: handle => { k.CloseHandle(handle); }, + fileTime: handle => { + const created = handleFileTime(handle); + if (withCommandLine) commandLine = readWindowsProcessCommandLineFromHandle(handle); + return created; + }, + exited: handleExited, + ownerSid: handleUserSid, + // #9027: a caller that names the account requires exactly that account as well as the caller's. + currentSid: () => { + const current = handleUserSid(k.GetCurrentProcess()); + return expectedUserSid === undefined || expectedUserSid === current ? current : ""; + }, + }); + return ticks === null ? null : { ticks, commandLine }; }, terminate(pid, boundStartTime) { const handle = k.OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); diff --git a/structure/INDEX.md b/structure/INDEX.md index ecd299a0e70..b51f1fa798c 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -304,7 +304,9 @@ A source area can be described by more than one doc, because these docs are orga | `src/client/link-management-relay.ts` | [`usage-client-attribution.md`](usage-client-attribution.md) | | `src/client/link-parity-reporter.ts` | [`remote-link.md`](remote-link.md) | | `src/client/machine-listener.ts` | [`remote-link.md`](remote-link.md) | +| `src/client/runtime-recycle.ts` | [`remote-link.md`](remote-link.md) | | `src/client/runtime-restart.ts` | [`remote-link.md`](remote-link.md) | +| `src/client/runtime-rollback.ts` | [`remote-link.md`](remote-link.md) | | `src/clients/` | [`clients/integrations.md`](clients/integrations.md)
[`clients/qoder.md`](clients/qoder.md)
[`clients/client-support-matrix.md`](clients/client-support-matrix.md)
[`clients/t3code.md`](clients/t3code.md) | | `src/clients/config-export.ts` | [`transports/timeouts.md`](transports/timeouts.md)
[`clients/export-model-names.md`](clients/export-model-names.md)
[`clients/omo-export-dialect.md`](clients/omo-export-dialect.md) | | `src/clients/config-export/` | [`clients/export-model-names.md`](clients/export-model-names.md) | diff --git a/structure/manifest.json b/structure/manifest.json index 2e14b6b2bf2..89416290a4c 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -1569,7 +1569,9 @@ "src/client/machine-listener.ts", "src/client/link-home.ts", "src/client/link-parity-reporter.ts", + "src/client/runtime-recycle.ts", "src/client/runtime-restart.ts", + "src/client/runtime-rollback.ts", "src/cli/link-apply-restart.ts", "src/cli/status-codex-settings.ts", "src/cli/status-link.ts", diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 64186822d47..9f34c3e11fc 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -28,7 +28,7 @@ lazily, caches a failed load as unavailable, and closes every handle in a `final - an exit watch: a handle opened at bind time and polled with `WaitForSingleObject(handle, 0)`; - the Task Scheduler service host PID through `QueryServiceStatusEx` on `Schedule`, only while it runs. -Link stop reads a live process’s creation time and token user through one handle. To verify a stop owner, it also reads the command line through that handle using `src/config/windows-process-command-line.ts`. The creation time uses .NET ticks truncated to CIM’s microsecond precision so existing receipts and runtime records still match. If the native API is unavailable, a bounded CIM probe refreshes the creation time after reading the SID. A failed native read leaves the identity unverified. Forced Link termination requires the native handle and compares the saved creation time and token user on that handle before ending the process. +The Link Child reads its live same-user creation proof in-process on one native handle, using `GetProcessTimes` and the token user SID; stop-owner argv is read through that same handle by `src/config/windows-process-command-line.ts`. It preserves the existing .NET tick identity at microsecond precision without spawning PowerShell or caching a PID proof. The process fallback compares that identity on the same handle used for termination. Unavailable native identity or handle binding refuses promptly; it does not fall back to repeated CIM subprocesses. `tests/windows/windows-stop-owner-identity.test.ts` covers handle ownership, stale identities and an actual-Windows-only repeated-read budget. Windows ARM64, other platforms and any test that simulates a platform get no native API. `src/service/windows-process-evidence.ts` is the facade the operations use. Its process snapshot is diff --git a/structure/remote-link.md b/structure/remote-link.md index 151eb9c6d9c..a129e65454e 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -13,13 +13,15 @@ Signal fencing uses the configuration mutation lock (`C`), yielding 50 ms betwee `src/client/sync-runtime.ts` fences Link sync against the local runtime record. Signal shutdown marks its own PID/port/attestation generation as `clientStopping` under C before restoration, and retains that mark through its last await. Sync captures the record at admission and rechecks it under C before catalog, injection, settings-record and cache commits. A stopping, replaced, removed or unreadable record refuses the write; a stale operation cannot reinject after the Child exits. Failure to mark the runtime refuses restoration while service, Desktop and sibling preservation retain their own exclusions; a native teardown receipt never waives the file-route fence. No-runtime sync remains an explicit offline operation: it reapplies routing even though no Child listener is serving it. A stale stopping record is reconciled by the existing start/stop recovery paths, not by guessing PID ownership. A bound restart marks the record the same way before it drains the listener, and abandons the restart with the runtime still serving when the mark cannot be written; and every publication of the runtime record carries a fresh `servingGeneration`, so a sync admitted before a restart whose replacement failed is refused by the record the rollback publishes, while syncs admitted afterwards proceed (`tests/clients/client-restart-sync-fence.test.ts`). The separate-process catalog/settings-response holds in `tests/clients/client-link-stop.test.ts` cover late commits, fresh sync during shutdown and the completed-sync control. -Orderly signals in an unsupervised Link Child await file-route cleanup in `src/client/stop-routing.ts` before releasing the listener, then reuse native Codex config/catalog/history restoration and managed Grok removal. The saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. Only `catalogFingerprint` and `catalogSyncedAt`, updated by normal catalog sync, are excluded from this restore-specific comparison; `priorCatalog` remains guarded and the shared full-snapshot CAS for asynchronous connection work is unchanged. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership and accepted restart/recycle handoff preserve integrations for their existing owners. Native teardown receipts never skip unsupervised file-route cleanup or the sync fence. `src/client/stop-native-handoff.ts` defers native Codex/Grok only when a bounded, no-follow receipt names the exact loopback endpoint, the current PID/port/attestation record binds its nonce to the PID and creation identity of a distinct live same-user stop invocation, and the receipt names that same owner. `src/client/stop-teardown-owner.ts` reads Linux NUL-separated argv and uses `src/client/stop-darwin-process.ts` for native macOS argv and microsecond process creation time. On Windows x64 it binds the creation time, token SID and argv to one live process handle. It accepts the supported compiled, source and npm stop forms, including installation paths containing spaces. Update workers launch a separate stop child. The Child rechecks the receipt bytes and runtime identity after inspecting the owner. The current claim can coexist with stale exact claims for this endpoint and quarantined obligations. For other endpoints, the current claim must carry the digest of the exact receipt bytes verified by the parent. A missing or changed snapshot, a malformed receipt or a guessed endpoint refuses signal deferral. Without that current owner, outstanding or unreadable receipt evidence refuses native restoration and retains the listener. Unreadable owner evidence blocks restart and recycle, as does a verified active stop. Both rollback paths that would recycle use the same admission check as scheduled recycle and bound restart. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start alone does not reapply routing; the operator steps live in the public CLI lifecycle reference. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`. +Orderly signals in an unsupervised Link Child await file-route cleanup in `src/client/stop-routing.ts` before releasing the listener, then reuse native Codex config/catalog/history restoration and managed Grok removal. The saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. Only `catalogFingerprint` and `catalogSyncedAt`, updated by normal catalog sync, are excluded from this restore-specific comparison; `priorCatalog` remains guarded and the shared full-snapshot CAS for asynchronous connection work is unchanged. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership and accepted restart/recycle handoff preserve integrations for their existing owners. Native teardown receipts never skip unsupervised file-route cleanup or the sync fence. `src/client/stop-native-handoff.ts` defers native Codex/Grok only when a bounded, no-follow receipt names the exact loopback endpoint, the current PID/port/attestation record binds its nonce to the PID and creation identity of a distinct live same-user stop invocation, and the receipt names that same owner. `src/client/stop-teardown-owner.ts` reads Linux NUL-separated argv and uses `src/client/stop-darwin-process.ts` for native macOS argv and microsecond process creation time. On Windows x64, the same-user creation proof uses `GetProcessTimes`, the process token and stop-owner argv on one live native handle, without PowerShell/CIM subprocesses or cached PID proofs; unavailable native evidence refuses promptly. The stored .NET tick identity retains its existing microsecond precision. Windows command lines follow native double-quote/backslash rules and treat apostrophes literally. It accepts the supported compiled, source and npm stop forms, including installation paths containing spaces. Update workers launch a separate stop child. The Child rechecks the receipt bytes and runtime identity after inspecting the owner. The current claim can coexist with stale exact claims for this endpoint and quarantined obligations. For other endpoints, the current claim must carry the digest of the exact receipt bytes verified by the parent. A missing or changed snapshot, a malformed receipt or a guessed endpoint refuses signal deferral. Without that current owner, outstanding or unreadable receipt evidence refuses native restoration and retains the listener. Unreadable owner evidence blocks restart and recycle, as does a verified active stop. Both rollback paths that would recycle use the same admission check as scheduled recycle and bound restart. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start alone does not reapply routing; the operator steps live in the public CLI lifecycle reference. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`. -`src/client/stop-file-routing.ts` shares the receipt-driven file cleanup in `src/integrations/route-intent-disconnect.ts` without disconnecting the Child. It removes only Link-created file integrations, preserves pre-link standalone integrations and local opt-outs, and retains connection/recovery records. After the runtime fence, strict receipt and on-disk absence inspection may prove no file cleanup is needed without acquiring L or requiring a token; the connection, configured port and runtime boundary are still checked. Each actual writer acquires L and repeats the immutable connection, configured port and physical token checks under C immediately before committing; a partial cleanup invalidates the earlier Home apply proof. A conflicting file, changed owner or unverified receipt refuses cleanup without overwriting the conflict. Signal shutdown keeps the listener bound with sync fenced and background watchers stopped; another signal or `ocx stop` retries after repair. For an explicit stop, `src/cli/stop-restore.ts` requires the runtime's attested Link fence capability, exact PID/port/runtime generation and the serving Link ownership fingerprint. The fingerprint must match the saved connection, and the configured port must match the serving port. Invalid or mismatched connection state refuses before manager or process mutation. Saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health trigger preflight. It requires the protected runtime record and attested health for both tracked and discovered live targets before service-manager mutation. Missing or unreadable identity refuses those targets even if saved state reads disconnected. Standalone stop uses the ordinary manager and restore path. Link stop captures the same-user OS creation identity before attestation, checks the pinned runtime record afterwards, and rechecks the process identity at mutation boundaries. The fenced record and connection are checked before manager or process stop, including escalation and port reclaim. Linux requires a verified pidfd for both TERM and KILL. Windows checks creation time on the same handle used to terminate. macOS sends one orderly SIGTERM and returns a refusal if the Child stays up. That signal targets a numeric PID, so a same-user replacement can still receive it if the PID is reused between the final creation-time check and the signal syscall. Preflight checks the bounded inherited-teardown snapshot captured by `src/cli/index.ts`. Malformed/unscannable or guessed inherited evidence refuses before any manager or process stop. An exact receipt for this attested endpoint may be settled by this stop. For a different endpoint, the parent must prove absence and bind that receipt snapshot to its own claim. The parent still probes the inherited endpoints after shutdown before restoring or discharging receipts. Quarantine-only evidence and live concurrent/self-owned claims retain their existing recovery exclusions. The inherited-receipt scan reuses the owner observation for receipts naming the same PID and creation identity. Preflight marks the sync fence and drains these files before any service-manager stop, new teardown receipt or kill fallback. Each busy-lock retry takes a fresh guard and verifies the exact runtime inside C. The CLI revalidates the fenced record and connection immediately before invoking the manager or stopping the process, including forced fallback. A failed preflight returns without stopping a process. When all known concrete endpoints are dead and the manager is inactive, preflight returns `already-stopped`. For a saved Link on Linux with an unreadable manager, the offline path requires `lstat` to report `ENOENT` for the installer unit and every service installation record path. It runs without runtime attestation, fencing or file cleanup; the later parent restoration path attempts file cleanup. A surviving Link receipt without a matching saved Link refuses post-stop restoration and retains the evidence. An attested legacy native listener with saved Link ownership and neither a published owner nor a fence is refused with the ordered transition in the CLI lifecycle reference. The initial absence of file routes never skips the fence: an already-admitted Home update can enable its first file integration. Failure to establish the fence retains an unsupervised signal listener too. During unsupervised signal cleanup, a native Codex/Grok restoration refusal after file cleanup also retains the listener and sync fence. During explicit stop, native restoration is attempted by the parent after the Child exits; refusal retains recovery evidence and reports incomplete restoration with the listener already stopped. Successful native restoration and the supervised/sibling/handoff exclusions keep their existing owners. Coverage: `tests/clients/client-link-stop.test.ts` (file writers, listener release and late materializer commits) and `tests/clients/client-link-stop-sibling.test.ts` (CLI stop ordering, process identity and native handoff). +`src/client/stop-file-routing.ts` shares the receipt-driven file cleanup in `src/integrations/route-intent-disconnect.ts` without disconnecting the Child. It removes only Link-created file integrations, preserves pre-link standalone integrations and local opt-outs, and retains connection/recovery records. After the runtime fence, strict receipt and on-disk absence inspection may prove no file cleanup is needed without acquiring L or requiring a token; the connection, configured port and runtime boundary are still checked. Each actual writer acquires L and repeats the immutable connection, configured port and physical token checks under C immediately before committing; a partial cleanup invalidates the earlier Home apply proof. A conflicting file, changed owner or unverified receipt refuses cleanup without overwriting the conflict. Signal shutdown keeps the listener bound with sync fenced and background watchers stopped; another signal or `ocx stop` retries after repair. For an explicit stop, `src/cli/stop-restore.ts` requires the runtime's attested Link fence capability, exact PID/port/runtime generation and the serving Link ownership fingerprint. The fingerprint must match the saved connection, and the configured port must match the serving port. Invalid or mismatched connection state refuses before manager or process mutation. Saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health trigger preflight. It requires the protected runtime record and attested health for both tracked and discovered live targets before service-manager mutation. Missing or unreadable identity refuses those targets even if saved state reads disconnected. Standalone stop uses the ordinary manager and restore path. Link stop captures the same-user OS creation identity before attestation, checks the pinned runtime record afterwards, and rechecks process identity at mutation boundaries. The fenced record and connection are checked before manager or process stop, including escalation and port reclaim. Linux requires a verified pidfd for both TERM and KILL. Windows checks creation time on the same handle used to terminate. macOS sends one orderly SIGTERM and returns a refusal if the Child stays up. That signal targets a numeric PID, so a same-user replacement can still receive it if the PID is reused between the final creation-time check and the signal syscall. Preflight checks the bounded inherited-teardown snapshot captured by `src/cli/index.ts`. Malformed/unscannable or guessed inherited evidence refuses before any manager or process stop. An exact receipt for this attested endpoint may be settled by this stop. For a different endpoint, the parent must prove absence and bind that receipt snapshot to its own claim. The parent still probes the inherited endpoints after shutdown before restoring or discharging receipts. Quarantine-only evidence and live concurrent/self-owned claims retain their existing recovery exclusions. The inherited-receipt scan reuses the owner observation for receipts naming the same PID and creation identity. Preflight marks the sync fence and drains these files before any service-manager stop, new teardown receipt or kill fallback. Each busy-lock retry takes a fresh guard and verifies the exact runtime inside C. The CLI revalidates the fenced record and connection immediately before invoking the manager or stopping the process, including forced fallback. A failed preflight returns without stopping a process. When all known concrete endpoints are dead and the manager is inactive, preflight returns `already-stopped`. For a saved Link on Linux with an unreadable manager, the offline path requires `lstat` to report `ENOENT` for the installer unit and every service installation record path. It runs without runtime attestation, fencing or file cleanup; the later parent restoration path attempts file cleanup. A surviving Link receipt without a matching saved Link refuses post-stop restoration and retains the evidence. An attested legacy native listener with saved Link ownership and neither a published owner nor a fence is refused with the ordered transition in the CLI lifecycle reference. The initial absence of file routes never skips the fence: an already-admitted Home update can enable its first file integration. Failure to establish the fence retains an unsupervised signal listener too. During unsupervised signal cleanup, a native Codex/Grok restoration refusal after file cleanup also retains the listener and sync fence. During explicit stop, native restoration is attempted by the parent after the Child exits; refusal retains recovery evidence and reports incomplete restoration with the listener already stopped. Successful native restoration and the supervised/sibling/handoff exclusions keep their existing owners. Coverage: `tests/clients/client-link-stop.test.ts` (file writers, listener release and late materializer commits) and `tests/clients/client-link-stop-sibling.test.ts` (CLI stop ordering, process identity and native handoff). A discovery miss requires independent standalone proof or a matching manager registration bound to the PID. The [standalone stop rules](runtime.md#lifecycle) describe the runtime-record fallback. With neither proof, `ocx stop` refuses before the service stop and signal ladder, preserving the Child's ability to refuse an unsafe shutdown. -An explicit parent stop sets `clientStopRequested: true` and writes its nonce, owner PID and process creation identity in the same exact-runtime C transaction. A deferred-teardown receipt with that nonce and creation identity must be written before manager or process stop. `src/config/process-state.ts` accepts both boolean values only with `clientStopping: true`. Before releasing its ownership mutation lease, the CLI finalizer clears only the matching request and retains the sync fence. A finalization refusal keeps the fence and preserves the original stop result. The runtime observes it only for its own PID/port/attestation, rejects further restart admission and the pre-fence stage of an already-admitted restart, and preserves both active and finished states under C when publishing a failed-restart rollback. A retained fence blocks unchanged, pending, new or unverified connections. Only a validated disconnected config and a complete disconnect receipt for the served owner and token, checked together under C with no pending connect, admit a serialized standalone recycle after the parent stop finishes. A verified active or unverified parent stop blocks recovery, as does signal shutdown. Only a dead PID or a positively different creation identity is confirmed stale. A malformed identity or an unrecognized invocation at the same incarnation is unverified. A receipt whose owner cannot be verified remains outstanding and blocks parent recovery. The check covers a previously scheduled timer and a restart awaiting its final supervisor check. After a completed disconnect, a finished request or confirmed-stale owner permits recovery. Signal shutdown cancels a pending recycle timer and frees its scheduling slot for eligible recovery if the listener is retained. Shutdown still waits for a recycle already in flight. A fresh process has a new attestation and does not inherit a stale request. The owning runtime passes `linkStopFence: true` to `src/client/machine-listener.ts`, which advertises it in attested health. Link preflight requires that capability before writing the marker or files; older or unknown running builds refuse with supervisor update/restart guidance. A Hub stop does not require the Link fence. A native listener that does not report a Link fence must publish its Hub identity and still have a saved Hub connection. Older native listeners without a published owner refuse until updated and restarted through their supervisor. Ordinary restart has no explicit-stop marker, so a failed replacement still publishes a new generation and admits fresh sync. Rollback holds the rebound listener during bounded config-lock retries and starts the tunnel supervisor and credential observer after publication. The overlap and ordinary-rollback control use real runtime records and file writers in `tests/clients/client-link-stop-recovery.test.ts`. +An explicit parent stop sets `clientStopRequested: true` and writes its nonce, owner PID and process creation identity in the same exact-runtime C transaction. A deferred-teardown receipt with that nonce and creation identity must be written before manager or process stop. `src/config/process-state.ts` accepts both boolean values only with `clientStopping: true`. Before releasing its ownership mutation lease, the CLI finalizer clears only the matching request and retains the sync fence. A finalization refusal keeps the fence and preserves the original stop result. The runtime observes it only for its own PID/port/attestation, rejects further restart admission and the pre-fence stage of an already-admitted restart, and preserves both active and finished states under C when publishing a failed-restart rollback. A retained fence blocks unchanged, pending, new or unverified connections. Only a validated disconnected config and a complete disconnect receipt for the served owner and token, checked together under C with no pending connect, admit a serialized standalone recycle after the parent stop finishes. A verified active or unverified parent stop blocks recovery, as does signal shutdown. Only a dead PID or a positively different creation identity is confirmed stale. A malformed identity or an unrecognized invocation at the same incarnation is unverified. A receipt whose owner cannot be verified remains outstanding and blocks parent recovery. The check covers a previously scheduled timer and a restart awaiting its final supervisor check. After a completed disconnect, a finished request or confirmed-stale owner permits recovery. Signal shutdown cancels a pending recycle timer and frees its scheduling slot for eligible recovery if the listener is retained. Shutdown still waits for a recycle already in flight. A fresh process has a new attestation and does not inherit a stale request. The owning runtime passes `linkStopFence: true` to `src/client/machine-listener.ts`, which advertises it in attested health. Link preflight requires that capability before writing the marker or files; older or unknown running builds refuse with supervisor update/restart guidance. A Hub stop does not require the Link fence. A native listener that does not report a Link fence must publish its Hub identity and still have a saved Hub connection. Older native listeners without a published owner refuse until updated and restarted through their supervisor. Ordinary restart has no explicit-stop marker, so a failed replacement still publishes a new generation and admits fresh sync. Rollback closes an unpublished rebound listener before yielding on lifecycle/configuration lock contention, retries within one shared rebind deadline, and rechecks connection ownership and explicit-stop evidence before each new bind and publication. It starts the tunnel supervisor and credential observer only after publication. The overlap and ordinary-rollback control use real runtime records and file writers in `tests/clients/client-link-stop-recovery.test.ts`. + +`src/client/runtime-recycle.ts` holds the Link apply exclusion from admission through listener drain and routing cleanup. Admission rechecks the served connection and explicit-stop policy under the configuration mutation lock; a pending transition, unchanged connection or retained stop obligation refuses teardown. The exclusion is released before replacement startup. `src/client/runtime-rollback.ts` retries only proven lifecycle or SQLite lock contention, with at most 50 ms between attempts and one remaining-time budget shared with listener rebinding. Coverage: `tests/clients/client-recycle-exclusion.test.ts`, `tests/clients/client-restart-rollback-lock.test.ts`, and the rollback controls in `tests/clients/client-link-stop-recovery.test.ts`. `src/link/ssh-argv.ts` and `src/link/remote-windows.ts` build every gated Child command through `remoteGatedOcxArgv` and `windowsGatedOcxArgv`: the script selects one executable, reads its version inside the remote script, refuses below the command's minimum with a named `ocx-fanout:` marker and exit 121, and only then runs the arguments. Every gated script exports `OCX_NO_DESKTOP_HANDOFF=1` before the version probe and the run, so a package launcher answers for itself and a Desktop handoff cannot pass the gate on behalf of an older launcher. The pinned sync is the 2.93.0 instance and executes `sync --expect-link`; the Home adds `--restart-app-server-only` or `--restart-codex` only for a restarting sync (the Child operation runners below and `ocx sync --restart-children`), never on Windows (the builder refuses it, `unsupported:windows-restart`) or for a link recorded as `ocx-child`, and withholds it for a link whose relayed model traffic is in flight (`src/cli/sync-fanout.ts`, `src/link/sync-then-restart.ts`). A link whose `childKind` is not recorded can receive the flag on that second sync, which is how the selected-kind marker reports `ocx-child`; `ocx-child` ignores it. The update builders in `src/link/child-gated-ocx.ts` require 2.97.0 inside the script, so the Home never sends `update` to an ocx that reports an older version; they refuse a selected `ocx-child` by file name (`ocx-fanout:child-ocx-ephemeral`) and on POSIX report `ocx-fanout:entry:pair|binary` (Windows reads no census, so its script prints no entry marker and the Home infers `binary`); the plan probe also reports the Child's clock, and the shipped builders refuse Windows apply. A Windows command that would exceed the encoded command-line budget throws `windows-command-too-long`; the plan probe fits a Home version of at least 40 characters. `src/link/child-update-contract.ts` is the Home's own strict copy of the Child's `update.orchestrated/1` plan and result documents and maps every apply exit to a closed verdict. `src/link/child-observations.ts` keeps a tolerant per-link cache in `/link/child-observations.json` beside the strict `links.json`: it drops unknown keys, prunes removed links on write and reads damage as empty. The per-Child sync classifier lives in `src/link/sync-fanout-classify.ts`. The plan probe is wired to the observe operation (`src/link/child-observe.ts`, below), which always passes the resolved platform to `classifyUpdatePlanProbe`; the apply builder and the sync restart flag are called from the Child operation runners (below) and `ocx sync --restart-children`; nothing runs on a timer except the Child-ops scheduler (below), which submits no-restart `sync` jobs and restarts app-servers only for idle Children under `childCodexRestart: "app-server-when-idle"`. The relay, not `onAuthenticatedCatalog` (which fires on admission and keeps driving the supervisor and the enrollment wait), records each Child's catalog pulls. Coverage: `tests/clients/link-gated-ocx-argv.test.ts`, `tests/clients/link-child-update-contract.test.ts`, `tests/clients/link-child-observations.test.ts`. Fan-out platform discovery in `src/link/remote-platform.ts` accepts a Windows marker on any stdout line or one framed uname line, so login-shell output cannot decide the platform. The Home requires one valid selection marker on stderr and one stdout delimiter, and classifies only the text after that delimiter; login-shell output before them is ignored. Oversized version probes are skipped. POSIX version capture and watchdog readiness use a private temporary directory, removed before execution or on refusal. The Home's `src/cli/sync-command.ts` fans out only after its catalog is current; the Child may still restart its own OpenCodex client runtime after applying changed Home settings. With `--overwrite-conflict` the pinned sync gate requires 2.100.0 and refuses ephemeral Children before executing; explicit client selection is forwarded. Known ephemeral links receive plain catalog sync. Coverage: `tests/clients/link-pinned-sync-overwrite.test.ts`, `tests/cli/cli-sync-fanout-ephemeral.test.ts`. @@ -337,7 +339,7 @@ When sync preserves an external Codex provider without applying configuration, i `ocx status --json` reports `appliedCodexSettingsDigest` on every device (a Child's record, or a Home's own projection, which is what it serves), and on a Child `lastApplyAt` and `runtimeStartedAt` as epoch ms (`src/cli/status-codex-settings.ts`). The client runtime's `/healthz` reports `startedAt`. After `ocx sync` records an apply, `src/cli/link-apply-restart.ts` restarts the client runtime through `handleProxyRestart`, the `ocx restart` path, only when the live client runtime started before `appliedAt` or reports no start; its start callback starts nothing unless an accepted restart left no runtime, which takes the ordinary recovery start. An explicit Desktop or service supervised refusal defers that restart without failing the applied sync; the notice directs Desktop users to Quit from the tray menu and reopen OpenCodex, or service users to `ocx service restart`. The next sync retries until the runtime starts after the apply. Other restart failures remain failures, and any earlier sync error is retained. The Child's JSON shape stays unchanged so existing Home fan-out parsers accept the successful result. -The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. If the relaunch command cannot be identified, `src/client/runtime.ts` omits it from the runtime record; update admission treats the identity as unproven, while client startup and shutdown continue. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". That refusal applies only while the durable connection is still the one the runtime serves: after `ocx disconnect` or a newer connect there is nothing to keep, so the restart is accepted and hands off to the standalone recycle (desktop exit 75, a viable service exit 1, otherwise a spawned replacement carrying no supervisor marker). "Ended" needs evidence (`readClientConnectionStateWithEvidence`, one snapshot of config.json): a saved file that validates and records no client, or another connection; missing, unreadable or invalid is invalid. Ownership and relaunch are separate (`classifyClientRestartSupervisor`): manager-launched evidence is the current markers in the environment only (`isMarkedSupervisedServiceChild`: the managed marker or the Windows wrapper marker); a legacy Windows registration recognised only from its parent's command line counts as a bare OCX_SERVICE=1; relaunch needs the service diagnostic to be viable and running. Manager-launched without that is `service-unproven`. `service-unproven` keeps the runtime and is refused at admission even when the connection ended; on this PR's recycle path only a process whose owner is proven to be none detaches, carrying no supervisor marker. A bare OCX_SERVICE=1 is outside that path and is always refused as `legacy-flag` (#8545, owner decision 2026-11-16): its owner is never inferred, not from the service diagnostic and not from the parent's command line, so nothing is stopped, replaced or recycled. A marker proves only that the process was started with it, so no supervisor marker may reach a process that supervisor did not launch: `src/lib/supervisor-markers.ts` holds the one list, and every detached runtime launch (companions, recycle, replacement, detached and post-update starts) and every shell a runtime hands to a tool clears it. The ended-connection recycle needs positive ownership evidence (`restartOwnerProven`: the desktop app, a manager's marker, or no OCX_SERVICE at all). A bare OCX_SERVICE=1 (a service registered before v2.49, or the proxy of ocx claude, ocx codex or ocx opencode) cannot be told apart, so its client runtime refuses `ocx restart` with 409 `restart_supervised` and supervisor `legacy-flag` whatever the service state and whether or not the connection ended, and records `restartOwner: legacy-flag`. The refusal text (`LEGACY_FLAG_OWNER_ADVICE` in `src/cli/restart-failure.ts`) tells the user to re-register the service once with `ocx service repair`, which writes the current ownership marker, or, for a companion's proxy, to `ocx stop` and start it again; `ocx sync` defers with the same text. `ocx disconnect` restarts only a runtime whose record states an owner it handles (`restartOwner`: desktop, service-manager or none); for `legacy-flag` it sends no restart request, prints the advice on stderr and exits 0, because the disconnect itself completed and a later `ocx restart` refuses with the same advice. A runtime started before this field existed, or an unknown value, gets origin/dev's disconnect: no restart request, exit 0. An inconclusive liveness probe or an unreadable record still exits 1 before any request, the one deliberate difference from origin/dev (no runtime is stopped, and the Home's leave stops before its own `ocx restart`). Owner evidence for those runtimes is a separate design (follow-up issue). `ocx disconnect` (`src/cli/disconnect-runtime.ts`) runs that restart itself when a client runtime is still live, bound to the runtime generation it observed: it captures that runtime's record (pid, port, per-process attestation secret) and the bound restart attests and derives its capability from the captured record, so another process at a reused pid is refused. It reads the client state once after its observation; when no runtime or a non-client runtime answered, that read decides alone (exit 0 only if disconnected). When it restarted a client runtime, it reads the state again after the restart: exit 0 needs that read to be disconnected and a live non-client runtime answering, and every exit-1 outcome takes its advice from one function (`recoveryAdvice`) given the state read at that point and whether the captured runtime, a different one or nothing answers: a plain restart is advised only for the captured runtime under a disconnected state (or a start when nothing answers), and a connected or unreadable state gets `ocx status` inspection only. Every other outcome exits 1, so a Home-driven leave stops before its own `ocx restart`. No read fences a process that runs after the command has exited. Each `ocx disconnect` attempt holds its own lock D (`withClientDisconnectAttempt` in `src/client/lifecycle-lock.ts`, outermost and taken by nothing else), so a second attempt refuses with `client_disconnect_busy` instead of sharing the first one's receipt while Codex is restored outside L. A disconnect refused before its receipt reaches `desktop_restored` (in practice, by the Codex journal restore, which keeps Codex's own later edits through `preserveConfigEdits`) removes that `prepared` receipt (and an otherwise empty `desktop-remote/` folder) when this attempt wrote it, or when an earlier run's receipt finds the Desktop store with no restore started (`absent`, `active` or `legacy_current_connection`); otherwise the receipt is kept, because that run may have stopped inside the Desktop restore. On a link Child the route-intent drain has already run by then; the rollback leaves it, and the runtime's next route-intent apply restores the routed file integrations. A pending receipt makes client startup refuse with `client_disconnect_pending`; that startup refusal names `ocx disconnect` as the way to finish or roll back (`src/client/connect.ts`, `src/client/state.ts`). `inspectRemoteDesktopStore` reports which step failed and the path it read, and `src/client/desktop-refusal.ts` turns that into the refusal. Coverage: `tests/clients/client-disconnect-recovery.test.ts`, `tests/clients/client-disconnect-desktop-refusals.test.ts`. Right after its connection commits, `connectClient` (and each connected `ocx sync` injection) takes over a Codex journal another owner wrote (`adoptJournalForClient` in `src/codex/journal.ts`), keeping the original snapshot; before the commit the journal stays its live writer's, so a runtime starting mid-connect leaves it alone, and after it a supervisor relaunch does not read the standalone owner as a crashed session and restore native Codex. Only a disconnected state or a different committed connection counts as ended for a supervised restart; unreadable or mismatched state keeps the refusal, and the controller rechecks after its supervisor lookup, immediately before recycling, handing the recycle the same supervisor verdict (a service only when viable). Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; Link rollback takes C inside the lifecycle lock to preserve any explicit stop fence. Ownership change, lock contention or publication failure closes the rebound listener in the binding turn, before the existing recycle admission check. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. +The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. If the relaunch command cannot be identified, `src/client/runtime.ts` omits it from the runtime record; update admission treats the identity as unproven, while client startup and shutdown continue. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". That refusal applies only while the durable connection is still the one the runtime serves: after `ocx disconnect` or a newer connect there is nothing to keep, so the restart is accepted and hands off to the standalone recycle (desktop exit 75, a viable service exit 1, otherwise a spawned replacement carrying no supervisor marker). "Ended" needs evidence (`readClientConnectionStateWithEvidence`, one snapshot of config.json): a saved file that validates and records no client, or another connection; missing, unreadable or invalid is invalid. Ownership and relaunch are separate (`classifyClientRestartSupervisor`): manager-launched evidence is the current markers in the environment only (`isMarkedSupervisedServiceChild`: the managed marker or the Windows wrapper marker); a legacy Windows registration recognised only from its parent's command line counts as a bare OCX_SERVICE=1; relaunch needs the service diagnostic to be viable and running. Manager-launched without that is `service-unproven`. `service-unproven` keeps the runtime and is refused at admission even when the connection ended; on this PR's recycle path only a process whose owner is proven to be none detaches, carrying no supervisor marker. A bare OCX_SERVICE=1 is outside that path and is always refused as `legacy-flag` (#8545, owner decision 2026-11-16): its owner is never inferred, not from the service diagnostic and not from the parent's command line, so nothing is stopped, replaced or recycled. A marker proves only that the process was started with it, so no supervisor marker may reach a process that supervisor did not launch: `src/lib/supervisor-markers.ts` holds the one list, and every detached runtime launch (companions, recycle, replacement, detached and post-update starts) and every shell a runtime hands to a tool clears it. The ended-connection recycle needs positive ownership evidence (`restartOwnerProven`: the desktop app, a manager's marker, or no OCX_SERVICE at all). A bare OCX_SERVICE=1 (a service registered before v2.49, or the proxy of ocx claude, ocx codex or ocx opencode) cannot be told apart, so its client runtime refuses `ocx restart` with 409 `restart_supervised` and supervisor `legacy-flag` whatever the service state and whether or not the connection ended, and records `restartOwner: legacy-flag`. The refusal text (`LEGACY_FLAG_OWNER_ADVICE` in `src/cli/restart-failure.ts`) tells the user to re-register the service once with `ocx service repair`, which writes the current ownership marker, or, for a companion's proxy, to `ocx stop` and start it again; `ocx sync` defers with the same text. `ocx disconnect` restarts only a runtime whose record states an owner it handles (`restartOwner`: desktop, service-manager or none); for `legacy-flag` it sends no restart request, prints the advice on stderr and exits 0, because the disconnect itself completed and a later `ocx restart` refuses with the same advice. A runtime started before this field existed, or an unknown value, gets origin/dev's disconnect: no restart request, exit 0. An inconclusive liveness probe or an unreadable record still exits 1 before any request, the one deliberate difference from origin/dev (no runtime is stopped, and the Home's leave stops before its own `ocx restart`). Owner evidence for those runtimes is a separate design (follow-up issue). `ocx disconnect` (`src/cli/disconnect-runtime.ts`) runs that restart itself when a client runtime is still live, bound to the runtime generation it observed: it captures that runtime's record (pid, port, per-process attestation secret) and the bound restart attests and derives its capability from the captured record, so another process at a reused pid is refused. It reads the client state once after its observation; when no runtime or a non-client runtime answered, that read decides alone (exit 0 only if disconnected). When it restarted a client runtime, it reads the state again after the restart: exit 0 needs that read to be disconnected and a live non-client runtime answering, and every exit-1 outcome takes its advice from one function (`recoveryAdvice`) given the state read at that point and whether the captured runtime, a different one or nothing answers: a plain restart is advised only for the captured runtime under a disconnected state (or a start when nothing answers), and a connected or unreadable state gets `ocx status` inspection only. Every other outcome exits 1, so a Home-driven leave stops before its own `ocx restart`. No read fences a process that runs after the command has exited. Each `ocx disconnect` attempt holds its own lock D (`withClientDisconnectAttempt` in `src/client/lifecycle-lock.ts`, outermost and taken by nothing else), so a second attempt refuses with `client_disconnect_busy` instead of sharing the first one's receipt while Codex is restored outside L. A disconnect refused before its receipt reaches `desktop_restored` (in practice, by the Codex journal restore, which keeps Codex's own later edits through `preserveConfigEdits`) removes that `prepared` receipt (and an otherwise empty `desktop-remote/` folder) when this attempt wrote it, or when an earlier run's receipt finds the Desktop store with no restore started (`absent`, `active` or `legacy_current_connection`); otherwise the receipt is kept, because that run may have stopped inside the Desktop restore. On a link Child the route-intent drain has already run by then; the rollback leaves it, and the runtime's next route-intent apply restores the routed file integrations. A pending receipt makes client startup refuse with `client_disconnect_pending`; that startup refusal names `ocx disconnect` as the way to finish or roll back (`src/client/connect.ts`, `src/client/state.ts`). `inspectRemoteDesktopStore` reports which step failed and the path it read, and `src/client/desktop-refusal.ts` turns that into the refusal. Coverage: `tests/clients/client-disconnect-recovery.test.ts`, `tests/clients/client-disconnect-desktop-refusals.test.ts`. Right after its connection commits, `connectClient` (and each connected `ocx sync` injection) takes over a Codex journal another owner wrote (`adoptJournalForClient` in `src/codex/journal.ts`), keeping the original snapshot; before the commit the journal stays its live writer's, so a runtime starting mid-connect leaves it alone, and after it a supervisor relaunch does not read the standalone owner as a crashed session and restore native Codex. Only a disconnected state or a different committed connection counts as ended for a supervised restart; unreadable or mismatched state keeps the refusal, and the controller rechecks after its supervisor lookup, immediately before recycling, handing the recycle the same supervisor verdict (a service only when viable). Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; Link rollback takes C inside the lifecycle lock to preserve any explicit stop fence. An unsuccessful publication closes the rebound listener in the binding turn. Only proved lifecycle or config SQLite contention retries, yielding with that listener closed and rechecking the durable owner and stop fence before a fresh bind/publication. All attempts share the existing 10 s rollback budget; ownership, storage and other failures do not retry. Link recycle takes the outer apply exclusion before its final C-protected owner/stop-receipt/pending-connect admission, outside L, and retains it through supervisor stop, listener closure, record cleanup and diagnostic drain. Once teardown begins it finishes under that exclusion instead of abandoning a partially stopped runtime. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. The Home learns a Child's apply from the Child (`src/link/child-parity.ts`, `src/client/link-parity-reporter.ts`). The linked client runtime POSTs `{linkId, lastApplyAt, runtimeStartedAt, appliedCodexSettingsDigest, sequence}` to `/v1/link-management/child-parity` through the connection-bound relay, shortly after start with backoff and then once a minute; a 404 stops it. On the Home the hub-link listener admits exactly that POST beside the read table, and `src/server/index/link-management.ts` handles it before the passive-read dispatch: the admitting key must own the named link, the body is capped at 8 KiB and 5 s, the parse is strict, and the only effect is an in-memory entry pruned to current links. Entries are ordered by `runtimeStartedAt`, then by `sequence` (process-wide, so a rollback keeps counting), and an older report is ignored, so a late POST from a replaced runtime or an earlier send never moves the row backward. `GET /api/link/status` and `ocx link status --json` carry `lastApplyAt`, `runtimeStartedAt`, `appliedCodexSettingsDigest` and `reportedAt` (epoch ms) on every link row, null without a report; the CLI accepts their absence from an older runtime. Coverage: `tests/server/link-child-parity.test.ts`, `tests/clients/link-parity-reporter.test.ts`. @@ -398,7 +400,7 @@ The authenticated `GET /v1/link-management/route-intent` is separate from the ma `src/server/index/route-intent-watch.ts` adds optional closed headers on that same GET: `x-ocx-route-intent-watch: 1` and an optional `x-ocx-route-intent-after` lowercase SHA-256 digest. A differing or absent digest returns immediately. A matching digest waits for a Home notification or at most 30 seconds, then repeats the listener's link-key admission against current policy (`serve-options.ts` passes a `readmit` callback; a key revoked during the wait is refused with 403 `link_key_required`), rechecks current link ownership and projects fresh policy. Successful reads advertise watch support in the same watch header; watch responses identify `changed`, `notified` or `timeout` in `x-ocx-route-intent-wake`. An unchanged timeout needs no apply, but an explicit notification and a changed digest still request sync. A peer without the new response header retains the previous conservative behavior. `src/link/route-intent-watch.ts` holds at most one waiter per link and 256 total in process memory; duplicate/capacity admission refuses, cancellation removes the waiter, and notification neither persists state nor acknowledges an apply. Home device mutations notify that link, default mutations notify every linked device, and Child-initiated explicit sync notifies an active waiter while returning `pending`; without a watcher it directs the caller to the Child or the next periodic tick. Conflict overwrite still requires explicit local Child authority. -`src/client/route-intent-watch.ts` exposes `startRouteIntentWatch(connection, key, { requestSync })` and `stop()`. Each GET uses the existing connection-bound relay, resolves a key getter afresh for rotation, pins the starting connection identity, refuses redirects and consumes at most 64 KiB with an 8 KiB response-header bound and a 40-second total read budget. A Home without watch support leaves reconciliation to the existing periodic tick. Failed reads retry after five seconds; immediately returning supported peers cannot create a tight loop. Watch notifications retain one pending apply while `requestSync` is busy and retry rejected applies. The runtime owner supplies the same serialized scheduler used by periodic sync, reports successful applies through the existing parity reporter, and stops the watcher with the runtime. Standalone recycle also stops the reporter, watch and tick before listener shutdown or replacement handoff; watch cancellation releases the outstanding Home read. The watch itself writes no client files or receipts and adds no Child-to-Home mutation endpoint. The periodic tick (`src/integrations/route-intent-tick.ts`) runs a full `syncConnectedClient` every 60 seconds even when nothing changed. Each apply first clears the Home proof record and writes a withdrawn receipt, because a failed or interrupted apply must not leave an earlier proof current, then rewrites both; unchanged writers make no client-file change, but the receipt and record are rewritten, and a parity report sent during that window carries the withdrawal until the next report. Avoiding the rewrite would mean knowing an apply changes nothing before running it, which the withdraw-first rule forbids. Native switches on a Child follow the Home: a local `ocx restore` is reverted by the next tick unless the person records `ocx route to codex off --local`. A tick can change the saved `selectedClients`, so `/api/machine/clients` reports the saved selection while it still belongs to the served connection (`src/client/machine-api.ts`). The tick does not restart the runtime after it applies changed Home Codex settings: the parity report keeps the runtime's real start time, so status shows that the runtime predates the apply, and `ocx sync` (or the Home fan-out) restarts it as before. +`src/client/route-intent-watch.ts` exposes `startRouteIntentWatch(connection, key, { requestSync })` and `stop()`. Each GET uses the existing connection-bound relay, resolves a key getter afresh for rotation, pins the starting connection identity, refuses redirects and consumes at most 64 KiB with an 8 KiB response-header bound and a 40-second total read budget. A Home without watch support leaves reconciliation to the existing periodic tick. A periodic tick defers for five seconds when its own published listener is marked stopping. Home-requested syncs still enter the normal queue and receive the result of the guarded sync. Failed reads retry after five seconds; immediately returning supported peers cannot create a tight loop. Watch notifications retain one pending apply while `requestSync` is busy and retry rejected applies. The runtime owner supplies the same serialized scheduler used by periodic sync, reports successful applies through the existing parity reporter, and stops the watcher with the runtime. Standalone recycle also stops the reporter, watch and tick before listener shutdown or replacement handoff; watch cancellation releases the outstanding Home read. The watch itself writes no client files or receipts and adds no Child-to-Home mutation endpoint. The periodic tick (`src/integrations/route-intent-tick.ts`) runs a full `syncConnectedClient` every 60 seconds even when nothing changed. Each apply first clears the Home proof record and writes a withdrawn receipt, because a failed or interrupted apply must not leave an earlier proof current, then rewrites both; unchanged writers make no client-file change, but the receipt and record are rewritten, and a parity report sent during that window carries the withdrawal until the next report. Avoiding the rewrite would mean knowing an apply changes nothing before running it, which the withdraw-first rule forbids. Native switches on a Child follow the Home: a local `ocx restore` is reverted by the next tick unless the person records `ocx route to codex off --local`. A tick can change the saved `selectedClients`, so `/api/machine/clients` reports the saved selection while it still belongs to the served connection (`src/client/machine-api.ts`). The tick does not restart the runtime after it applies changed Home Codex settings: the parity report keeps the runtime's real start time, so status shows that the runtime predates the apply, and `ocx sync` (or the Home fan-out) restarts it as before. The served roster a connected Child materializes from is the Home's own `GET /v1/models` list, so `loadConnectedRouteModels` (`src/integrations/route-intent-connected.ts`) reads each row's capability fields there — `capabilities.input_modalities`, `capabilities.context_length`/`max_output_tokens`, `supports_reasoning`, `supports_thinking_toggle`, `supports_reasoning_effort`, `default_thinking_enabled`, the `reasoning_effort` ladder (bare values or Grok's `{value, default}` options) and the top-level `context_window`/`context_length`/`max_output_tokens` mirrors — and maps them into `ExportModel`, the same projection `toExportModel` makes for `/api/models`. The row is remote input, so every value is validated: an integer window, a boolean axis, a modality from the exporters' vocabulary or a declared effort, with malformed entries dropped individually and nothing synthesized for a field the row omits. Without this the file integrations a Child materializes from Home intent (Pi, OpenCode and the rest) fell back to text-only with no reasoning controls. Fields the served row does not carry — `maxInputTokens`, `supports_reasoning_summaries` and `supports_tools` — stay absent and the exporters apply their own rules. The Grok adapter carries the ladder and its declared default into the Grok config, and the Desktop adapter passes each routed window, which decides `supports1m`. A combo row the route catalog does not list is accepted only as an expanded selector of a listed one, `--fast` or `--` as the Home's `/v1/models` publishes them, and takes that base's canonical key; an expanded selector whose base is unlisted is left out on its own, while any other unlisted combo still rejects the roster. Coverage: `tests/clients/route-intent-connected-capabilities.test.ts`. diff --git a/tests/cli/cli-client-start-fence.test.ts b/tests/cli/cli-client-start-fence.test.ts index 59902fa4319..872ca1ce09d 100644 --- a/tests/cli/cli-client-start-fence.test.ts +++ b/tests/cli/cli-client-start-fence.test.ts @@ -141,7 +141,7 @@ describe("connected-client start ownership fence", () => { // released only once the first serve() returned, i.e. after publication. const serve = runtime.slice(runtime.indexOf("const serve = async"), runtime.indexOf("const stopServing")); // Each publication also stamps a fresh servingGeneration (restart sync fence, #8416). - expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration: randomUUID\(\),\s+clientLinkOwner \}\);/); + expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*servingGeneration = randomUUID\(\);\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration,\s+clientLinkOwner \}\);/); expect(runtime).toMatch(/await serve\(\);\s*\n\s*options\.afterPublish\?\.\(\);/); }); }); diff --git a/tests/clients/client-link-stop-recovery.test.ts b/tests/clients/client-link-stop-recovery.test.ts index de7c39807c6..8cab87d947f 100644 --- a/tests/clients/client-link-stop-recovery.test.ts +++ b/tests/clients/client-link-stop-recovery.test.ts @@ -5,18 +5,49 @@ import { join } from "node:path"; import { fixturePath, repoPath } from "../helpers/repo-root"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { runStop } from "../helpers/client-link-stop"; +import { stopFixtureEnv, unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; -async function runRecovery(mode: string, scheduled = false, env = process.env) { +test("stop fixtures keep Home traffic and integration state separate across children", async () => { + const first = unavailableFixtureHome(), second = unavailableFixtureHome(); + try { + expect(first.port).not.toBe(second.port); + for (const home of [first, second]) { + expect(home.url.hostname).toBe("127.0.0.1"); + expect((await fetch(home.url)).status).toBe(503); + } + const root = join(tmpdir(), "fixture-child"); + const inherited = { ...process.env, GROK_HOME: "suite-grok", CLAUDE_CONFIG_DIR: "suite-claude", + XDG_CONFIG_HOME: "suite-config", OCX_OWNER_REGISTRY_DIR: "suite-registry", OCX_SERVICE: "1" }; + expect(stopFixtureEnv(root, inherited)).toMatchObject({ GROK_HOME: join(root, ".grok"), + CLAUDE_CONFIG_DIR: join(root, ".claude"), XDG_CONFIG_HOME: join(root, ".config"), + OCX_OWNER_REGISTRY_DIR: join(root, "ocx", "ocx-homes"), OCX_SERVICE: "" }); + } finally { await Promise.all([first.stop(true), second.stop(true)]); } +}); + +async function runRecovery(mode: string, scheduled = false, env = process.env, attempt = 0): Promise> { const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-recovery-")); const child = Bun.spawn([process.execPath, fixturePath("client-link-stop-recovery-runner.ts")], { cwd: repoPath(), stdin: new Blob([JSON.stringify({ mode, scheduled })]), stdout: "pipe", stderr: "pipe", - env: { ...env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), - OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }, + env: stopFixtureEnv(root, env), }); - const timeout = setTimeout(() => child.kill("SIGKILL"), 15_000); + let parentDeadlineReached = false; + const timeout = setTimeout(() => { + if (child.exitCode !== null) return; + parentDeadlineReached = true; + child.kill("SIGKILL"); + }, 15_000); try { const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); - expect(exit, stderr).toBe(0); + if (exit === 75 && stderr.trim() === "fixture-port-collision") { + if (attempt >= 2) throw new Error("recovery fixture port collided three times"); + return runRecovery(mode, scheduled, env, attempt + 1); + } + if (exit !== 0) { + const phases = stdout.split(/\r?\n/).filter(line => line.startsWith("recovery phase ")); + const status = parentDeadlineReached ? "parent requested termination at its 15s deadline" : "child exited"; + throw new Error([`Link recovery (${mode}): ${status}, exit ${exit}`, + ...(phases.length ? phases : ["no fixture phase reported"]), stderr.trimEnd()].filter(Boolean).join("\n")); + } expect(stderr).not.toContain("uncaughtException"); const line = stdout.split("\n").find(line => line.startsWith("{")); expect(line, stdout + stderr).toBeDefined(); @@ -64,7 +95,7 @@ test("a stale stop owner cannot block completed disconnect recovery", async () = test("a refused signal stop can reschedule a canceled recycle after disconnect recovery", async () => { const result = await runRecovery("signal-pending-recycle"); - expect(result).toMatchObject({ firstRecycleTimers: 1, beforeRecoveryAdmission: 409, recoveryRecycleTimers: 1, + expect(result).toMatchObject({ firstRecycleTimers: 1, firstRecycleCanceled: true, beforeRecoveryAdmission: 409, recoveryRecycleTimers: 1, role: "standalone", spawned: 1, file: { userSetting: "keep" }, state: "disconnected", phase: "complete", runtimePresent: false }); }, 20_000); @@ -103,6 +134,16 @@ test("restart rollback closes its unpublished listener in the binding turn when expect(report.fileAfter.pi).not.toContain("127.0.0.1"); }, 20_000); +for (const retryRollbackPublication of ["lifecycle", "config", "owner-changed"] as const) { + test("restart rollback rechecks its owner after " + retryRollbackPublication + " contention", async () => { + const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"], retryRollbackPublication }); + const resumed = retryRollbackPublication !== "owner-changed"; + expect(report.result).toEqual({ preflight: null, closedBeforeYield: true, published: resumed, bound: resumed, + rollbackBinds: resumed ? 2 : 1, replacementAttempts: 1, stopping: true, explicitStop: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + }, 20_000); +} + test("ordinary restart rollback keeps file routes and admits fresh sync", async () => { const report = await runStop({ mode: "file-restart-control", preserve: "restart-rollback", fileClients: ["pi"] }); expect(report.result).toEqual({ rolledBack: true, bound: true, stopping: false, explicitStop: false, sync: "accepted" }); diff --git a/tests/clients/client-recycle-exclusion.test.ts b/tests/clients/client-recycle-exclusion.test.ts new file mode 100644 index 00000000000..34359c711b7 --- /dev/null +++ b/tests/clients/client-recycle-exclusion.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { writeFileSync } from "node:fs"; +import { getDefaultConfig, saveConfig } from "../../src/config"; +import { prepareConfigMutationDatabasePathForWrite } from "../../src/config/mutation-lock"; +import { LinkApplyBusyError, withLinkApply } from "../../src/client/link-home"; +import { markClientConnectPending } from "../../src/client/state"; +import { runClientRecycleWithAdmission } from "../../src/client/runtime-recycle"; +import type { OcxClientConnectionConfig } from "../../src/types"; +import { createTempHome, type TempHome } from "../helpers/temp-home"; + +const served: OcxClientConnectionConfig = { + serverUrl: "http://127.0.0.1:34567", managementUrl: "http://127.0.0.1:34567", managementTransport: "direct", transport: "link", + link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" }, selectedClients: [], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", + apiKeyId: "fixture-client", tokenFingerprint: "c".repeat(64), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", +}; +let home: TempHome; +beforeEach(() => { home = createTempHome("recycle-exclusion-"); saveConfig(getDefaultConfig()); }); +afterEach(() => home.remove()); + +test("an in-flight Link apply refuses recycle before any teardown", async () => { + let stopped = 0; + await withLinkApply(async () => { + expect(await runClientRecycleWithAdmission(served, () => true, async () => { stopped++; })).toBe(false); + }); + expect(stopped).toBe(0); +}); + +test("recycle retains apply exclusion through every teardown await", async () => { + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const held = new Promise(resolve => { release = resolve; }); + let admissions = 0, completed = false; + const flight = runClientRecycleWithAdmission(served, () => { admissions++; return true; }, async () => { + entered(); await held; + await expect(withLinkApply(async () => {})).rejects.toBeInstanceOf(LinkApplyBusyError); + completed = true; + }); + await ready; + try { await expect(withLinkApply(async () => {})).rejects.toBeInstanceOf(LinkApplyBusyError); } + finally { release(); } + expect(await flight).toBe(true); + expect({ admissions, completed }).toEqual({ admissions: 1, completed: true }); + await withLinkApply(async () => {}); +}); + +for (const state of ["same-connection", "unreadable", "pending-connect", "stop-refused", "config-busy"] as const) { + test("recycle rechecks " + state + " inside apply exclusion", async () => { + let stopped = 0; + let lock: Database | undefined; + if (state === "same-connection") { + const config = getDefaultConfig(); config.runtimeRole = "client"; config.client = served; saveConfig(config); + } + if (state === "unreadable") writeFileSync(home.path("config.json"), "{"); + if (state === "pending-connect") markClientConnectPending("d".repeat(64)); + if (state === "config-busy") { lock = new Database(prepareConfigMutationDatabasePathForWrite()); lock.exec("BEGIN IMMEDIATE"); } + try { + expect(await runClientRecycleWithAdmission(served, () => state !== "stop-refused", async () => { stopped++; })).toBe(false); + expect(stopped).toBe(0); + } finally { lock?.close(); } + }); +} + +test("a failure after teardown begins is propagated instead of reported as an admission refusal", async () => { + await expect(runClientRecycleWithAdmission(served, () => true, async () => { throw new LinkApplyBusyError(); })) + .rejects.toBeInstanceOf(LinkApplyBusyError); +}); diff --git a/tests/clients/client-restart-rollback-lock.test.ts b/tests/clients/client-restart-rollback-lock.test.ts new file mode 100644 index 00000000000..50d1bc7807d --- /dev/null +++ b/tests/clients/client-restart-rollback-lock.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "bun:test"; +import { ConfigMutationLockError } from "../../src/config"; +import { retryClientRollback, retryableClientRollbackLock } from "../../src/client/runtime-rollback"; + +test("rollback retries only known lifecycle or configuration contention", () => { + expect(retryableClientRollbackLock({ code: "client_lifecycle_busy" })).toBe(true); + for (const code of ["SQLITE_BUSY", "SQLITE_LOCKED"]) { + expect(retryableClientRollbackLock(new ConfigMutationLockError("busy", { cause: { code } }))).toBe(true); + } + for (const error of [undefined, new Error("busy"), { code: "SQLITE_BUSY" }, { code: "client_lifecycle_lock_failed" }, + new ConfigMutationLockError("unavailable", { cause: { code: "SQLITE_CORRUPT" } })]) { + expect(retryableClientRollbackLock(error)).toBe(false); + } +}); + +test("rollback closes each busy attempt before yielding and keeps one remaining budget", async () => { + let clock = 0, calls = 0, listener = false; + const remaining: number[] = []; + expect(await retryClientRollback(async budget => { + remaining.push(budget); calls++; listener = true; clock += 10; + if (calls === 3) return "published"; + listener = false; return "busy"; + }, { budgetMs: 200, now: () => clock, sleep: async ms => { + expect(listener).toBe(false); clock += ms; + } })).toBe(true); + expect(remaining).toEqual([200, 140, 80]); + expect(listener).toBe(true); +}); + +test("rollback contention exhaustion never extends its budget", async () => { + let clock = 0, calls = 0; + expect(await retryClientRollback(async () => { calls++; clock += 20; return "busy"; }, { + budgetMs: 100, now: () => clock, sleep: async ms => { clock += ms; }, + })).toBe(false); + expect({ clock, calls }).toEqual({ clock: 100, calls: 2 }); +}); + +test("a changed owner or non-contention refusal stops rollback retries immediately", async () => { + let clock = 0, calls = 0; + expect(await retryClientRollback(async () => ++calls === 1 ? "busy" : "refused", { + now: () => clock, sleep: async ms => { clock += ms; }, + })).toBe(false); + expect(calls).toBe(2); +}); diff --git a/tests/clients/route-intent-runtime-stop.test.ts b/tests/clients/route-intent-runtime-stop.test.ts index 6de8b64e092..e68820f96b3 100644 --- a/tests/clients/route-intent-runtime-stop.test.ts +++ b/tests/clients/route-intent-runtime-stop.test.ts @@ -13,7 +13,7 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () writeFileSync(fixture, ` import { test, expect, spyOn } from 'bun:test'; test('isolated recycle', async () => { - const { writeFileSync } = await import('node:fs'); + const { readFileSync, writeFileSync, unlinkSync } = await import('node:fs'); const { join } = await import('node:path'); const configApi = await import(${JSON.stringify(repoPath("src/config.ts"))}); const { serviceApiTokenFingerprint } = await import(${JSON.stringify(repoPath("src/lib/service-secrets.ts"))}); @@ -38,6 +38,8 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () }), })); const runtime = await import(${JSON.stringify(repoPath("src/client/runtime.ts"))}); + const { clearClientConnection } = await import(${JSON.stringify(repoPath("src/client/state.ts"))}); + const { withLinkApply } = await import(${JSON.stringify(repoPath("src/client/link-home.ts"))}); const probe = Bun.serve({hostname:'127.0.0.1',port:0,fetch:()=>new Response(null)}); const port = probe.port; await probe.stop(true); const token = 'ocx_data_'+'c'.repeat(40); @@ -49,15 +51,41 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () configApi.saveConfig(config); writeFileSync(join(process.env.OPENCODEX_HOME,'service-api-token'), token); try { await runtime.startClientRuntime({block:false}, {restartSupervisor:async()=>null, - startListener: port => ({port,stop(){events.push('listener-stop');}})}); + startListener: port => ({port,async stop(){ + events.push('listener-stop'); + await withLinkApply(async()=>{events.push('apply-entered-during-stop');}) + .catch(error=>{if(error.code==='link_apply_busy')events.push('apply-blocked-during-stop');else throw error;}); + }})}); for(let i=0;i<100&&!active;i++)await Bun.sleep(5); expect(active).toBe(true); + const deferPeriodic = tick.mock.calls[0][1].deferPeriodic; + const file = join(process.env.OPENCODEX_HOME, 'runtime-port.json'); + const original = readFileSync(file); + const published = JSON.parse(original.toString()); + const stopping = { ...published, clientStopping: true }; + try { + expect(deferPeriodic()).toBe(false); + writeFileSync(file, JSON.stringify(stopping)); + expect(deferPeriodic()).toBe(true); + for (const change of [{ pid: published.pid + 1 }, { port: port === 1 ? 2 : 1 }, + { attestationSecret: 'A'.repeat(43) }, { servingGeneration: 'other' }, { servingGeneration: undefined }]) { + writeFileSync(file, JSON.stringify({ ...stopping, ...change })); + expect(deferPeriodic()).toBe(false); + } + writeFileSync(file, '{'); + expect(deferPeriodic).toThrow('client_runtime_unverified'); + unlinkSync(file); + expect(deferPeriodic()).toBe(false); + } finally { writeFileSync(file, original); } + expect(clearClientConnection(config.client)).toBe('committed'); await runtime.recycleStandalone(serviceApiTokenFingerprint(token), { isDesktopSupervised:()=>false, spawnReplacement:async()=>{expect(active).toBe(false);events.push('replacement');}, exitProcess:code=>events.push('exit:'+code), }); expect(events.indexOf('watch-cancelled')).toBeGreaterThanOrEqual(0); + expect(events).toContain('apply-blocked-during-stop'); + expect(events).not.toContain('apply-entered-during-stop'); expect(events.indexOf('tick-stop')).toBeGreaterThanOrEqual(0); expect(events.filter(event => event === 'credential-observation-stop')).toHaveLength(1); expect(events.indexOf('watch-cancelled')).toBeLessThan(events.indexOf('listener-stop')); diff --git a/tests/clients/route-intent-scheduler.test.ts b/tests/clients/route-intent-scheduler.test.ts index 7e98bb09103..2df566bcdc7 100644 --- a/tests/clients/route-intent-scheduler.test.ts +++ b/tests/clients/route-intent-scheduler.test.ts @@ -42,6 +42,51 @@ test("busy applies reject the request and retry on the short cadence without ove scheduler.stop(); }); +test("a retained stop defers periodic sync while Home requests keep their original result", async () => { + const timers: Array<{ run: () => void; ms: number }> = []; + let fenced = true, checks = 0, calls = 0, reports = 0; + const refusal = new Error("link_apply_busy"); + const scheduler = startRouteIntentTick(connection, { + deferPeriodic: () => { checks++; return fenced; }, + sync: async () => { calls++; if (fenced) throw refusal; }, + onApplied: () => { reports++; }, + setTimer: (run, ms) => { const timer = { run, ms }; timers.push(timer); return timer; }, + clearTimer: timer => { const i = timers.findIndex(entry => entry === timer); if (i >= 0) timers.splice(i, 1); }, + }); + const first = timers.shift()!; + expect(first.ms).toBe(2_000); + first.run(); await flush(); + expect([checks, calls, reports]).toEqual([1, 0, 0]); + expect(timers.map(timer => timer.ms)).toEqual([5_000]); + + await expect(scheduler.requestSync()).rejects.toBe(refusal); + await flush(); + expect([checks, calls, reports]).toEqual([1, 1, 0]); + expect(timers.map(timer => timer.ms)).toEqual([5_000]); + + fenced = false; + timers.shift()!.run(); await flush(); + expect([checks, calls, reports]).toEqual([2, 2, 1]); + expect(timers.map(timer => timer.ms)).toEqual([60_000]); + scheduler.stop(); + expect(timers).toHaveLength(0); +}); + +test("an inconclusive periodic fence check falls through to sync", async () => { + const timers: Array<{ run: () => void; ms: number }> = []; + let calls = 0, reports = 0; + const scheduler = startRouteIntentTick(connection, { + deferPeriodic: () => { throw new Error("runtime record unavailable"); }, + sync: async () => { calls++; }, + onApplied: () => { reports++; }, + setTimer: (run, ms) => { timers.push({ run, ms }); return timers.length; }, clearTimer: () => {}, + }); + timers.shift()!.run(); await flush(); + expect([calls, reports]).toEqual([1, 1]); + expect(timers.map(timer => timer.ms)).toEqual([60_000]); + scheduler.stop(); +}); + test("machine clients reports the saved selection a scheduled sync changed, only for the served connection", async () => { const { handleMachineApi } = await import("../../src/client/machine-api"); const state = { serverUrl: "http://127.0.0.1:22001", managementUrl: "http://127.0.0.1:22001", managementTransport: "direct" as const, diff --git a/tests/fixtures/client-link-stop-recovery-runner.ts b/tests/fixtures/client-link-stop-recovery-runner.ts index 6f831e890cf..1ecdac7d906 100644 --- a/tests/fixtures/client-link-stop-recovery-runner.ts +++ b/tests/fixtures/client-link-stop-recovery-runner.ts @@ -1,7 +1,8 @@ /** Real file recovery and bound restart; only replacement process launch is a loopback fixture. */ import { mock, spyOn } from "bun:test"; -import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; import { dirname, join } from "node:path"; +import { unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; import { getDefaultConfig, saveConfig } from "../../src/config"; import { serviceApiTokenFingerprint, writeServiceApiTokenFile, readServiceApiTokenState } from "../../src/lib/service-secrets"; import { readRuntimePort, type ClientStopOwner } from "../../src/config/process-state"; @@ -13,6 +14,13 @@ import { createSystemRestartCapability, SYSTEM_RESTART_CAPABILITY_HEADER, SYSTEM SYSTEM_RESTART_NONCE_HEADER, SYSTEM_RESTART_PATH } from "../../src/lib/system-restart-contract"; const options = JSON.parse(readFileSync(0, "utf8")) as { mode: string; scheduled?: boolean }; +let phase: string; +function enterPhase(name: string): void { + phase = name; + // Flush before synchronous filesystem work so a parent timeout retains the last transition. + writeSync(1, `recovery phase ${Math.round(performance.now())}ms: ${name}\n`); +} +enterPhase("fixture setup"); const home = process.env.OPENCODEX_HOME!; mkdirSync(home, { recursive: true }); const lifecycle = await import("../../src/client/lifecycle-lock"); @@ -26,10 +34,11 @@ mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, async function main() { const token = `ocx_data_${"c".repeat(40)}`; const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null) }); + const fixtureHome = unavailableFixtureHome(); const config = getDefaultConfig(); config.port = probe.port!; config.runtimeRole = "client"; - config.client = { serverUrl: "http://127.0.0.1:34567", managementUrl: "http://127.0.0.1:34567", managementTransport: "direct", transport: "link", - link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" }, selectedClients: ["pi"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", + config.client = { serverUrl: fixtureHome.url.origin, managementUrl: fixtureHome.url.origin, managementTransport: "direct", transport: "link", + link: { tunnelPort: fixtureHome.port!, linkId: "lnk_0123456789abcdef" }, selectedClients: ["pi"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z" }; saveConfig(config); writeServiceApiTokenFile(token); const expected = structuredClone(config.client); @@ -42,6 +51,7 @@ async function main() { const document = { version: 1 as const, home: { name: "fixture", version: "1" }, clients: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, { enabled: id === "pi" }])), sources: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, "default"])) } as import("../../src/link/route-intent").HomeRouteIntentDocument; + enterPhase("applying the file route"); const applied = await applyConnectedRouteIntent(expected, token, { document, stale: false, fetchedAt: "2026-11-16T00:00:00.000Z" }, { onlyClients: ["pi"], lifecycleLockDeps }, { fetchImpl: (async () => Response.json({ data: [{ id: "fixture/home-model" }] })) as typeof fetch }); if (applied?.outcomes.find(row => row.client === "pi")?.outcome !== "current") throw new Error("fixture apply failed"); @@ -72,6 +82,7 @@ async function main() { const replacement = await import("../../src/server/restart-replacement"); mock.module("../../src/server/restart-replacement", () => ({ ...replacement, spawnReplacementStart: async (request: { port: number }) => { spawned++; + enterPhase("binding the replacement listener"); // A successful bind proves the real Child listener released its port. No native coordinator, // provider request or external process participates in this replacement seam. const server = Bun.serve({ hostname: "127.0.0.1", port: request.port, fetch: () => Response.json({ role: "standalone" }) }); @@ -88,27 +99,48 @@ async function main() { const observeOwner = owner.observeClientStopOwner; mock.module("../../src/client/stop-teardown-owner", () => ({ ...owner, observeClientStopOwner: (proof: ClientStopOwner) => { - if (options.mode === "parent-unverified") return "unverified"; if (proof.nonce === "malformed" || proof.startTime === "malformed") return observeOwner(proof); - return owner.readClientStopProcessStart(proof.pid) === proof.startTime ? "active" : "confirmed-stale"; + const observedStart = options.mode === "parent-unverified" ? undefined : owner.readClientStopProcessStart(proof.pid); + if (observedStart === undefined) return "unverified"; + return observedStart === proof.startTime ? "active" : "confirmed-stale"; }, })); const { startClientRuntime, scheduleStandaloneRecycle } = await import("../../src/client/runtime"); + const { startMachineListener } = await import("../../src/client/machine-listener"); + const { isAddrInUse } = await import("../../src/server/ports"); + enterPhase("starting the Child listener"); // Keep the selected port reserved while preparing the fixture and loading the runtime. await probe.stop(true); - await startClientRuntime({ block: false }, { restartSupervisor: async () => null }); - // The parent watchdog bounds total time, including fixture setup. Give the - // stop and disconnect operations their own phase deadline once the Child serves. - let phase = "observing the refused stop"; + try { + await startClientRuntime({ block: false }, { restartSupervisor: async () => null, + startListener: (port, deps) => { + try { return startMachineListener(port, deps); } + catch (error) { + // Only a proven bind collision requests a fresh, fully owned fixture from the parent. + if (isAddrInUse(error)) throw new Error("fixture-port-collision"); + throw error; + } + }, + }); + } catch (error) { + if (error instanceof Error && error.message === "fixture-port-collision") { + console.error("fixture-port-collision"); process.exit(75); + } + throw error; + } + // The parent bounds setup; the existing phase watchdog starts only once the Child serves. setTimeout(() => { - console.error(`recovery fixture timed out (${options.mode}: ${phase})`); + console.error(`recovery fixture timed out 10s after listener startup (${options.mode}: ${phase})`); process.exit(1); }, 10_000).unref(); const pendingRecycle = options.mode === "signal-pending-recycle"; + let lastRecycleTimer: ReturnType | undefined; const scheduleAndCountTimers = () => { const timer = spyOn(globalThis, "setTimeout"); try { scheduleStandaloneRecycle(expected.tokenFingerprint); + const index = timer.mock.calls.findIndex(([, delay]) => delay === 50); + lastRecycleTimer = index < 0 ? undefined : timer.mock.results[index]!.value; return timer.mock.calls.filter(([, delay]) => delay === 50).length; } finally { timer.mockRestore(); } }; @@ -120,13 +152,24 @@ async function main() { [SYSTEM_RESTART_EXPECTED_PID_HEADER]: String(process.pid), [SYSTEM_RESTART_NONCE_HEADER]: nonce, [SYSTEM_RESTART_CAPABILITY_HEADER]: createSystemRestartCapability(runtime.attestationSecret!, nonce, "POST", SYSTEM_RESTART_PATH, process.pid, config.port), } }); - await response.arrayBuffer(); return response.status; + await response.arrayBuffer(); + if (response.status === 202) enterPhase("restart request accepted"); + return response.status; }; let finishStop: () => Promise = async () => {}; + enterPhase("observing the refused stop"); if (options.mode.startsWith("signal")) { // Queue and signal in one turn so the first timer is still pending at shutdown. - if (pendingRecycle) observations.firstRecycleTimers = scheduleAndCountTimers(); - process.emit("SIGTERM", "SIGTERM"); + if (pendingRecycle) { + observations.firstRecycleTimers = scheduleAndCountTimers(); + const original = lastRecycleTimer; + if (original === undefined) throw new Error("fixture did not create the first recycle timer"); + const cancel = spyOn(globalThis, "clearTimeout"); + try { + process.emit("SIGTERM", "SIGTERM"); + observations.firstRecycleCanceled = cancel.mock.calls.some(([timer]) => timer === original); + } finally { cancel.mockRestore(); } + } else process.emit("SIGTERM", "SIGTERM"); await (options.mode === "signal-active" ? entered : refused); } else { const { preflightConnectedClientStop } = await import("../../src/cli/stop-restore"); @@ -145,7 +188,7 @@ async function main() { } observations.beforeRecoveryAdmission = await restart(); observations.finishedMarker = readRuntimePort(process.pid)?.clientStopRequested; - phase = "disconnecting the Child"; + enterPhase("disconnecting the Child"); const { disconnectClient } = await import("../../src/client/connect"); await disconnectClient({ recoverConfig: true }, { lifecycleLockDeps }); const receiptPath = storePaths().disconnect; @@ -160,7 +203,7 @@ async function main() { if (options.mode === "missing-config") unlinkSync(join(home, "config.json")); if (options.mode === "new-connection") { config.client!.connectedAt = "2026-11-16T01:00:00.000Z"; saveConfig(config); } if (options.mode === "pending-connect") markClientConnectPending("b".repeat(64)); - phase = "observing restart or recycle after disconnect"; + enterPhase("observing restart or recycle after disconnect"); if (pendingRecycle) { observations.recoveryRecycleTimers = scheduleAndCountTimers(); if (observations.recoveryRecycleTimers === 0) { diff --git a/tests/fixtures/client-link-stop-runner.ts b/tests/fixtures/client-link-stop-runner.ts index 4a13bd8955d..0f55b317e81 100644 --- a/tests/fixtures/client-link-stop-runner.ts +++ b/tests/fixtures/client-link-stop-runner.ts @@ -3,6 +3,7 @@ import { mock } from "bun:test"; import { Database } from "bun:sqlite"; import { existsSync, mkdirSync, readFileSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; +import { unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; import { getDefaultConfig, prepareConfigMutationDatabasePathForWrite, saveConfig } from "../../src/config"; import { CODEX_CONFIG_PATH, CODEX_HOME, CODEX_PROFILE_PATH, DEFAULT_CATALOG_PATH } from "../../src/codex/paths"; import { JOURNAL_PATH, markJournalInjectedState, writeJournal } from "../../src/codex/journal"; @@ -46,6 +47,7 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { danglingServiceRecord?: boolean; busyStopFence?: boolean; busyRollbackPublication?: boolean; + retryRollbackPublication?: "lifecycle" | "config" | "owner-changed"; terminationPlatform?: "linux" | "darwin"; siblingEscalation?: "stopping" | "different-generation"; removeToken?: boolean; @@ -72,14 +74,15 @@ mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, const token = `ocx_data_${"c".repeat(40)}`; const config = getDefaultConfig(); const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null) }); +const fixtureHome = options.transport === "hub" ? undefined : unavailableFixtureHome(); config.port = probe.port!; await probe.stop(true); config.runtimeRole = "client"; config.client = { - serverUrl: options.transport === "hub" ? "https://hub.example.test" : "http://127.0.0.1:34567", - managementUrl: options.transport === "hub" ? "https://hub.example.test" : "http://127.0.0.1:34567", + serverUrl: fixtureHome?.url.origin ?? "https://hub.example.test", + managementUrl: fixtureHome?.url.origin ?? "https://hub.example.test", managementTransport: "direct", transport: options.transport ?? "link", - ...(options.transport === "hub" ? {} : { link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" } }), + ...(fixtureHome ? { link: { tunnelPort: fixtureHome.port!, linkId: "lnk_0123456789abcdef" } } : {}), selectedClients: ["codex", ...(options.deferFileApply ? [] : options.fileClients ?? [])], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", }; @@ -337,6 +340,7 @@ if (options.mode === "retry") { } })); } let replacementAttempts = 0; + let rollbackBinds = 0, publicationHeld = false; let observeRollback!: (closed: boolean) => void; const rollbackTurn = new Promise(resolve => { observeRollback = resolve; }); let restartSettled: (() => Promise) | undefined; @@ -345,7 +349,7 @@ if (options.mode === "retry") { saveConfig(config); protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); }; - if (options.failedRollback) { + if (options.failedRollback || options.retryRollbackPublication) { const controller = await import("../../src/client/runtime-restart"); const create = controller.createClientRestartController; mock.module("../../src/client/runtime-restart", () => ({ ...controller, createClientRestartController: (...args: Parameters) => { @@ -371,19 +375,25 @@ if (options.mode === "retry") { const restartStopping = new Promise(resolve => { restartStopEntered = resolve; }); const restartRelease = new Promise(resolve => { releaseRestartStop = resolve; }); await startClientRuntime({ block: false }, { restartSupervisor: () => options.preserve?.startsWith("restart-rollback") ? Promise.resolve(null) : new Promise(() => {}), startListener: (port, deps) => { + if (replacementAttempts === 1) rollbackBinds++; requestRestart = deps?.restart?.request; if (options.failedRollback === "during-rebind" && replacementAttempts === 1) replaceSavedConnection(); const server = startMachineListener(port, options.oldStopCapability && deps?.restart ? { ...deps, restart: { ...deps.restart, linkStopFence: undefined } } : deps); - if (options.busyRollbackPublication && replacementAttempts === 1) { - const lock = new Database(prepareConfigMutationDatabasePathForWrite()); + if ((options.busyRollbackPublication || options.retryRollbackPublication) && replacementAttempts === 1 && !publicationHeld) { + publicationHeld = true; + const lock = new Database(options.retryRollbackPublication === "lifecycle" + ? lifecycleLockDeps.lockPath : prepareConfigMutationDatabasePathForWrite()); lock.exec("BEGIN IMMEDIATE"); const stop = server.stop.bind(server); let closed = false; server.stop = ((force: boolean) => { const result = stop(force); closed = force; return result; }) as typeof server.stop; // The bind and failed admission complete before the next event-loop turn. Keep C // held until the observation, so a retry cannot publish in the meantime. - setImmediate(() => { observeRollback(closed); lock.close(); }); + setImmediate(() => { + observeRollback(closed); lock.close(); + if (options.retryRollbackPublication === "owner-changed") replaceSavedConnection(); + }); return server; } const stop = server.stop.bind(server); @@ -414,6 +424,16 @@ if (options.mode === "retry") { report({ preflight, closedBeforeYield, published: readRuntimePort(process.pid)?.servingGeneration !== before.servingGeneration, replacementAttempts }); process.exit(0); } + if (options.retryRollbackPublication) { + const closedBeforeYield = await rollbackTurn; + await restartSettled!(); + const after = readRuntimePort(process.pid)!; + const published = after.servingGeneration !== before.servingGeneration; + const bound = published && (await fetch(`http://127.0.0.1:${config.port}/healthz`)).ok; + report({ preflight, closedBeforeYield, published, bound, rollbackBinds, replacementAttempts, + stopping: after.clientStopping, explicitStop: after.clientStopRequested }); + process.exit(0); + } if (options.failedRollback) { await restartSettled!(); report({ preflight, replacementAttempts, runtimePresent: readRuntimePort(process.pid) !== null, diff --git a/tests/fixtures/parent-stop-runner.ts b/tests/fixtures/parent-stop-runner.ts index b220365cfac..0142e73eeb9 100644 --- a/tests/fixtures/parent-stop-runner.ts +++ b/tests/fixtures/parent-stop-runner.ts @@ -75,8 +75,8 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { windowsPartAReject?: boolean; }; if (options.legacyWindowsEvidence) { - // Fake Windows command output at the OS boundary. The production SID, argv - // and listener readers and the standalone proof all run in this subprocess. + // Fake Windows process evidence at the OS boundary. The production argv/listener + // readers and standalone proof run here without touching the host's process table. const evidence = options.legacyWindowsEvidence; const record = { pid: 4242, port: 10100, hostname: "127.0.0.1", ...(evidence === "client-role" ? { role: "client" as const } : {}), @@ -84,9 +84,19 @@ if (options.legacyWindowsEvidence) { }; const { proveStandaloneStopRecord } = await import("../../src/cli/stop-restore"); const { setProcessCommandLinePlatformForTests } = await import("../../src/config/process-state"); - const { setWindowsProcessNativeForTests } = await import("../../src/service/windows-process-native"); - setWindowsProcessNativeForTests(null); // Exercise the mocked CIM fallback on Windows too. setProcessCommandLinePlatformForTests("win32"); + const { readSameUserWindowsStart, setWindowsProcessNativeForTests } = await import("../../src/service/windows-process-native"); + setWindowsProcessNativeForTests({ creationTime: () => null, terminate: () => ({ status: "unavailable" }), + openWatch: () => ({ status: "unavailable" }), scheduleServicePid: () => null, + sameUserIdentity: pid => { + const ticks = readSameUserWindowsStart(pid, { + open: target => target === record.pid ? 1 : 0, close: () => {}, + fileTime: () => 134_088_768_000_000_000n, exited: () => false, + ownerSid: () => evidence === "foreign-sid" ? "S-1-5-21-2" : "S-1-5-21-1", currentSid: () => "S-1-5-21-1", + }); + return ticks === null ? null : { ticks }; + }, + }); const windows = await import("../../src/lib/windows-elevation"); mock.module("../../src/lib/windows-elevation", () => ({ ...windows, resolveTrustedWindowsSystemDirectory: () => "system", @@ -100,9 +110,6 @@ if (options.legacyWindowsEvidence) { const port = evidence === "wrong-port" ? record.port + 1 : record.port; return `TCP ${host}:${port} 0.0.0.0:0 LISTENING ${pid}\r\n`; } - if (args.at(-1)?.includes("GetOwnerSid")) { - return evidence === "foreign-sid" ? "" : "639000000000000000\r\n"; - } if (file.endsWith("WMIC.exe")) { const verb = evidence === "wrong-argv" ? 'status "start"' : "start"; return `CommandLine="C:\\Program Files\\Bun\\bun.exe" run "C:\\work tree\\src\\cli\\index.ts" ${verb}\r\n`; diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 805d38ac478..51290ce8f33 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1636,6 +1636,7 @@ "windows-atomic-replace.test.ts": "windows", "windows-codex-cli-job-store.test.ts": "windows", "windows-deploy-close-regressions.test.ts": "windows", + "windows-stop-owner-identity.test.ts": "windows", "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", @@ -1709,7 +1710,9 @@ "grok-47-build-fast-metadata.test.ts": "providers/xai", "grok-47-fast-model.test.ts": "providers/xai", "grok-47-fast-model-wire.test.ts": "providers/xai", "client-link-connect.test.ts": "clients", "client-link-relay.test.ts": "clients", "client-link-runtime.test.ts": "clients", "client-link-stop.test.ts": "clients", - "client-link-stop-recovery.test.ts": "clients", "client-link-stop-sibling.test.ts": "clients", + "client-link-stop-recovery.test.ts": "clients", + "client-recycle-exclusion.test.ts": "clients", + "client-restart-rollback-lock.test.ts": "clients", "client-link-stop-sibling.test.ts": "clients", "link-routes.test.ts": "clients", "client-link-state.test.ts": "clients", "client-link-status.test.ts": "clients", "client-link-teardown.test.ts": "clients", "client-disconnect-recovery.test.ts": "clients", "client-disconnect-desktop-refusals.test.ts": "clients", "client-link-tunnel.test.ts": "clients", "link-ports.test.ts": "clients", diff --git a/tests/helpers/client-link-stop.ts b/tests/helpers/client-link-stop.ts index 3559a871037..bc4084fe100 100644 --- a/tests/helpers/client-link-stop.ts +++ b/tests/helpers/client-link-stop.ts @@ -4,13 +4,12 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fixturePath, repoPath } from "./repo-root"; import { removeTreeWithRetry } from "./remove-tree"; +import { stopFixtureEnv } from "./client-stop-fixture-home"; export async function runStop(options: Record) { const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-")); const home = join(root, "ocx"); - const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, - CODEX_HOME: join(root, "codex"), OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), - OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }; + const env = stopFixtureEnv(root); let owner: Bun.Subprocess<"pipe", "pipe", "ignore"> | undefined; let child: Bun.Subprocess | undefined; const timeout = setTimeout(() => { diff --git a/tests/helpers/client-stop-fixture-home.ts b/tests/helpers/client-stop-fixture-home.ts new file mode 100644 index 00000000000..ce6cb4cdf70 --- /dev/null +++ b/tests/helpers/client-stop-fixture-home.ts @@ -0,0 +1,15 @@ +import { join } from "node:path"; + +export function stopFixtureEnv(root: string, inherited = process.env) { + return { ...inherited, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), + OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), CLAUDE_CONFIG_DIR: join(root, ".claude"), + GROK_HOME: join(root, ".grok"), XDG_CONFIG_HOME: join(root, ".config"), OCX_OWNER_REGISTRY_DIR: join(root, "ocx", "ocx-homes"), + OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }; +} + +export function unavailableFixtureHome() { + const home = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null, { status: 503 }) }); + // Runtime watch requests stay inside this fixture. The Home must not keep its child process alive. + home.unref(); + return home; +} diff --git a/tests/windows/windows-stop-owner-identity.test.ts b/tests/windows/windows-stop-owner-identity.test.ts new file mode 100644 index 00000000000..448f0ac80c0 --- /dev/null +++ b/tests/windows/windows-stop-owner-identity.test.ts @@ -0,0 +1,125 @@ +import { expect, spyOn, test } from "bun:test"; +import { readSameUserWindowsStart, setWindowsProcessNativeForTests, setWindowsProcessPlatformForTests } from "../../src/service/windows-process-native"; +import { isClientStopCommandLine, isLegacyWindowsStartCommandLine, observeClientStopOwner, readClientStopProcessStart } from "../../src/client/stop-teardown-owner"; + +const fileTime = 133_000_000_000_000_007n; +const ticks = 637_911_232_000_000_000n; +const sid = "S-1-5-21-100-200-300-1001"; + +function nativeRead(overrides: Partial[1]> = {}) { + const handles: Array = [], closed: Array = []; + const result = readSameUserWindowsStart(42, { + open: pid => { expect(pid).toBe(42); return 101n; }, + close: handle => { closed.push(handle); }, + fileTime: handle => { handles.push(handle); return fileTime; }, + exited: handle => { handles.push(handle); return false; }, + ownerSid: handle => { handles.push(handle); return sid; }, + currentSid: () => sid, + ...overrides, + }); + return { result, handles, closed }; +} + +test("Windows stop creation and same-user evidence use one live handle and preserve protocol precision", () => { + const result = nativeRead(); + expect(result.result).toBe(ticks); + expect(result.handles).toEqual([101n, 101n, 101n, 101n]); + expect(result.closed).toEqual([101n]); +}); + +test("Windows stop owner evidence fails closed and closes every opened handle", () => { + for (const overrides of [ + { fileTime: () => null }, + { exited: () => true }, + { exited: () => null }, + { ownerSid: () => "S-1-5-21-100-200-300-1002" }, + { ownerSid: () => "", currentSid: () => "" }, + { ownerSid: () => { throw new Error("access denied"); } }, + { currentSid: () => { throw new Error("token unreadable"); } }, + ]) { + const result = nativeRead(overrides); + expect(result.result).toBeNull(); + expect(result.closed).toEqual([101n]); + } + expect(nativeRead({ open: () => 0 }).closed).toEqual([]); + let reads = 0; + expect(nativeRead({ exited: () => ++reads === 1 ? false : true }).result).toBeNull(); +}); + +test("a reused PID gets a fresh handle and cannot inherit a prior creation proof", () => { + let opens = 0; + const io = { + open: () => ++opens, + close: () => {}, + fileTime: (handle: number | bigint) => fileTime + BigInt(handle) * 10n, + exited: () => false, + ownerSid: () => sid, + currentSid: () => sid, + }; + expect(readSameUserWindowsStart(42, io)).toBe(ticks + 10n); + expect(readSameUserWindowsStart(42, io)).toBe(ticks + 20n); + for (const pid of [0, -1, 1.5, 0x80000000]) expect(readSameUserWindowsStart(pid, io)).toBeNull(); + expect(opens).toBe(2); +}); + +test("native Windows owner observation binds argv to the same identity and refuses unavailable proof", () => { + const pid = process.pid + 1; + const owner = { pid, startTime: `win32:${ticks}`, nonce: "a".repeat(32) }; + const reads: Array<[number, boolean | undefined]> = []; + let identity = { ticks, commandLine: "C:\\Users\\O'Neil\\ocx.exe stop" }; + const alive = spyOn(process, "kill").mockImplementation(() => true); + setWindowsProcessPlatformForTests("win32"); + setWindowsProcessNativeForTests({ + creationTime: () => null, + sameUserIdentity: (target, withCommandLine) => { reads.push([target, withCommandLine]); return identity; }, + terminate: () => ({ status: "unavailable" }), + openWatch: () => ({ status: "unavailable" }), + scheduleServicePid: () => null, + }); + try { + expect(observeClientStopOwner(owner)).toBe("active"); + expect(reads).toEqual([[pid, true]]); + identity = { ...identity, ticks: ticks + 10n }; + expect(observeClientStopOwner(owner)).toBe("confirmed-stale"); + identity = { ticks, commandLine: "ocx.exe start" }; + expect(observeClientStopOwner(owner)).toBe("unverified"); + setWindowsProcessNativeForTests(null); + expect(readClientStopProcessStart(pid)).toBeUndefined(); + expect(observeClientStopOwner(owner)).toBe("unverified"); + } finally { + alive.mockRestore(); + setWindowsProcessPlatformForTests(null); + setWindowsProcessNativeForTests(undefined); + } +}); + +test("Windows stop and legacy start recognize apostrophes without shell quoting", () => { + for (const command of [ + "C:\\Users\\O'Neil\\ocx.exe stop", + '"C:\\Users\\O\'Neil\\Program Files\\ocx.exe" stop --json', + 'bun.exe "C:\\Users\\O\'Neil\\app\\src\\cli\\index.ts" stop --deadline-ms 5000', + '"C:\\Program Files\\ocx.exe"\tstop\t--json', + ]) expect(isClientStopCommandLine(command), command).toBe(true); + expect(isLegacyWindowsStartCommandLine("C:\\Users\\O'Neil\\ocx.exe start")).toBe(true); + expect(isLegacyWindowsStartCommandLine('bun.exe "C:\\Users\\O\'Neil\\app\\src\\cli.ts" start')).toBe(true); + for (const command of [ + "'C:\\Program Files\\ocx.exe' stop", "ocx.exe 'stop'", 'ocx.exe "stop --json"', + 'ocx.exe "st\\"op"', 'ocx.exe "st""op"', 'ocx.exe stop\0 --json', "ocx.exe start stop", + ]) expect(isClientStopCommandLine(command), command).toBe(false); +}); + +test("Windows stop approval preserves quoted backslashes and embedded quote boundaries", () => { + const approved = 'ocx.exe stop --json --expect-pid 12 --expect-port 10100 --expect-hostname 127.0.0.1 ' + + '--expect-config-home "C:\\Users\\O\'Neil\\Home Folder\\\\" --expect-cli-version 1.0.0 ' + + '--expect-compatibility-token ' + "a".repeat(64); + expect(isClientStopCommandLine(approved)).toBe(true); + expect(isClientStopCommandLine(approved.replace('Home Folder\\\\"', 'Home Folder\\"'))).toBe(false); +}); + +test.skipIf(process.platform !== "win32" || process.arch !== "x64")("Windows repeated stop proofs stay in-process and within the fixture budget", () => { + const expected = readClientStopProcessStart(process.pid); + expect(expected).toMatch(/^win32:\d+$/); + const started = performance.now(); + for (let attempt = 0; attempt < 30; attempt++) expect(readClientStopProcessStart(process.pid)).toBe(expected); + expect(performance.now() - started).toBeLessThan(3000); +});