diff --git a/bin/ocx.mjs b/bin/ocx.mjs index 2be5336d9b5..7c69900a36e 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -12,6 +12,7 @@ import { guardedRun, guardedSpawn, guardedSpawnSync, guardedExit, probeProcessAl import { probeSpawn, probeSpawnSync } from "../src/update/mutation-guard.mjs"; import { createSupervisionLatch, inspectDesktopSupervision } from "../src/service/desktop-supervision.mjs"; import { planDesktopCliHandoff, runDesktopCliHandoff } from "../src/lib/desktop-cli-handoff.mjs"; +import { acquireSyncGuard } from "../src/update/sync-update-mutex.mjs"; import { desktopCliRecordPath } from "../src/lib/desktop-cli-record.mjs"; import { STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "../src/update/stop-contract.mjs"; import { probeProxyLiveness } from "../src/update/proxy-liveness-probe.mjs"; @@ -43,9 +44,14 @@ import { isRealBunBinary } from "../src/lib/bun-binary-validator.mjs"; import { scopeTranspilerCacheToRuntime } from "../src/lib/bun-transpiler-cache-scope.mjs"; import { findDesktopCli, findPathBun } from "../src/lib/bun-path-runtime.mjs"; import { npmInvocation } from "../src/update/npm-invocation.mjs"; -import { runNpmInstall } from "../src/update/npm-install.mjs"; +import { runNpmInstall, runWindowsInstallerSync } from "../src/update/npm-install.mjs"; +import { runPosixInstallerSync } from "../src/update/posix-install-supervisor.mjs"; import { pnpmInvocationForPath, resolvePnpmCommands } from "../src/update/pnpm-invocation.mjs"; import { detectInstallOwnershipFromPath } from "../src/update/install-detection.mjs"; +import { isOrchestratedUpdateArgv, parseOrchestratedUpdateArgs, parseOrchestratedChildArgs } from "../src/update/orchestrated-arguments.mjs"; +import { createLegacyUpdateSession, createOrchestratedChildSession, decodeOrchestratedExpect } from "../src/update/orchestrated-session.mjs"; +import { createUpdatePlanToken } from "../src/update/orchestrated-token.mjs"; +import { applyNodeOrchestratedUpdate } from "../src/update/orchestrated-node-driver.mjs"; import { pnpmOwnerInvocation, resolvePnpmGlobalOwner, @@ -232,7 +238,48 @@ function runningPnpmShimPath() { return resolve(invoked); } -async function runPackageManagerSelfUpdate(manager) { +async function runPackageManagerSelfUpdate(manager, child) { + let session, enteredMutation = false; + let childOutcome = { phase: "failed", rollbackPerformed: false }; + if (child) { + try { + const expected = decodeOrchestratedExpect(child.expect); + session = createOrchestratedChildSession({ home: configDir(), resultPath: child.resultPath, resultCapability: child.resultCapability, expect: expected, + notAfter: child.notAfter, verifyIdentity: () => { + const bun = resolveBun({ allowInstall: false, allowMissing: true }); + if (!bun) return false; + const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], { + encoding: "utf8", timeout: 8000, maxBuffer: 8192, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], + env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }), + OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: manager, OCX_IDENTITY_TARGET: child.version }, + }); + if (probe.status !== 0 || probe.error || probe.signal || typeof probe.stdout !== "string") return false; + const observed = JSON.parse(probe.stdout); + return observed.permits === true && observed.cliRoot === expected.cliRoot && observed.planToken === expected.planToken + && (observed.kind === "absent" ? expected.servingRoot === null && expected.runtimePid === null + : observed.kind === "live" && observed.servingRoot === expected.servingRoot && observed.runtime?.pid === expected.runtimePid); + } }); + if (!session.start().ok) process.exit(10); + // The parent may forward a signal while a synchronous installer is running. Keep the + // owner alive through its transaction and recovery so the mutex cannot outlive us. + for (const signal of ["SIGINT", "SIGTERM", ...(process.platform === "win32" ? [] : ["SIGHUP"])]) process.on(signal, () => {}); + process.once("exit", () => { + try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); } + catch (error) { console.error(`Orchestrated outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; } + }); + } catch (error) { + console.error(`Orchestrated update preflight failed: ${error?.message ?? error}`); + process.exit(1); + } + } else { + session = createLegacyUpdateSession({ home: configDir() }); + const started = session.start(); + if (!started.ok) { console.error(`opencodex: ${started.error}`); process.exit(1); } + process.once("exit", () => { + try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); } + catch (error) { console.error(`Update outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; } + }); + } const current = currentPackageVersion(); const tag = updateTag(current); let owner; @@ -279,17 +326,18 @@ async function runPackageManagerSelfUpdate(manager) { : invocation.env ? { env: invocation.env } : {}), ...invocation.options, }); - const latestInvocation = managerInvocation(["view", `${PKG}@${tag}`, "version"]); + const selector = child?.version ?? tag; + const latestInvocation = managerInvocation(["view", `${PKG}@${selector}`, "version"]); const installArgs = manager === "pnpm" - ? ["add", "-g", "--allow-build=bun", `${PKG}@${tag}`] - : ["install", "-g", `${PKG}@${tag}`]; + ? ["add", "-g", "--allow-build=bun", `${PKG}@${selector}`] + : ["install", "-g", `${PKG}@${selector}`]; const installInvocation = managerInvocation(installArgs); if (!latestInvocation || !installInvocation) { console.error(`opencodex: could not resolve ${manager} from a trusted absolute PATH entry; aborting before stopping the proxy.`); process.exit(1); } const latestResult = probeSpawnSync(latestInvocation.file, latestInvocation.args, readProbeOptions(latestInvocation)); - const latest = latestResult.status === 0 && typeof latestResult.stdout === "string" ? latestResult.stdout.trim() : ""; + const latest = child?.version ?? (latestResult.status === 0 && typeof latestResult.stdout === "string" ? latestResult.stdout.trim() : ""); console.log(`opencodex v${current} (installed via ${manager}, tag ${tag})`); if (latest && latest === current) { @@ -752,6 +800,12 @@ async function runPackageManagerSelfUpdate(manager) { runtimePlan = lockedPlan; const stoppedOwnershipIdentity = ownershipIdentity(lockedOwnership); + if (session) { + const entered = await session.enterMutation(); + if (!entered.ok) { releaseUpdateLease(); process.exit(10); } + enteredMutation = true; + } + // Never replace package files under a live proxy — stop it first (full `ocx stop` // semantics: graceful drain, service stop, native Codex restore). Gate on the service // and the runtime-port record too: a service-managed or orphaned proxy can be live @@ -940,7 +994,7 @@ async function runPackageManagerSelfUpdate(manager) { try { if (manager === "npm") { const packageDir = resolve(here, ".."); - const transactionalNpmUpdate = process.platform === "win32" ? transactionalNpmUpdateAsync : transactionalNpmUpdateSync; + const transactionalNpmUpdate = session ? transactionalNpmUpdateAsync : transactionalNpmUpdateSync; if (!homePolicy.authorizeMutation("package")) throw new Error("Automatic package update refused."); const tx = await transactionalNpmUpdate({ packageDir, @@ -958,12 +1012,31 @@ async function runPackageManagerSelfUpdate(manager) { runNpm: (args) => { const invocation = npmInvocation(args); if (!homePolicy.authorizeMutation("package")) return { status: 1 }; - if (process.platform === "win32") return runNpmInstall(invocation, { - authorizeMutation: homePolicy.authorizeMutation, - env: unprivilegedOwnershipMutationEnvironment(invocation?.options?.env ?? process.env), - }); + if (process.platform === "win32") { + if (session) session.noteUntrackedInstaller(); + return runNpmInstall(invocation, { + authorizeMutation: homePolicy.authorizeMutation, + env: unprivilegedOwnershipMutationEnvironment(invocation?.options?.env ?? process.env), + }).then(result => { + if (session && result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit(); + else if (session) { session.retainInstallerFence(); return { ...result, processTreeExited: false }; } + return result; + }); + } if (!invocation) return { status: 1 }; if (!homePolicy.authorizeMutation("package")) return { status: 1 }; + if (session) { + try { + const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args, + markerPath: join(configDir(), "update-orchestrated.json"), authorizeMutation: homePolicy.authorizeMutation, + env: unprivilegedOwnershipMutationEnvironment(invocation.options?.env ?? process.env) }); + if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) { + session.retainInstallerFence(); + return { ...result, processTreeExited: false }; + } + return { ...result, processTreeExited: true }; + } catch (error) { session.retainInstallerFence(); throw error; } + } return guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, { ...invocation.options, stdio: "inherit", @@ -974,6 +1047,9 @@ async function runPackageManagerSelfUpdate(manager) { }, log: (line) => console.log(line), }); + if (session) childOutcome = tx.ok ? { phase: "installed", activeRoot: packageDir } + : { phase: "failed", rollbackPerformed: tx.rolledBack === true, + ...(tx.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) }; postUpdateLauncherUsable = launcherUsableAfterNpmUpdate(tx); if (!tx.ok) npmFailure = tx; if (tx.ok) { @@ -998,6 +1074,25 @@ async function runPackageManagerSelfUpdate(manager) { runPnpm: (args, capture = false) => { const invocation = pnpmOwnerInvocation(owner, args); if (!invocation) return { status: 1 }; + if (session && !capture) return withPnpmCommandCwd(args, cwd => { + const env = pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)); + if (process.platform === "win32") { + session.noteUntrackedInstaller(); + const result = runWindowsInstallerSync(invocation, { cwd, env, authorizeMutation: homePolicy.authorizeMutation }); + if (result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit(); + else { session.retainInstallerFence(); return { ...result, processTreeExited: false }; } + return result; + } + try { + const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args, cwd, markerPath: join(configDir(), "update-orchestrated.json"), + authorizeMutation: homePolicy.authorizeMutation, env }); + if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) { + session.retainInstallerFence(); + return { ...result, processTreeExited: false }; + } + return { ...result, processTreeExited: true }; + } catch (error) { session.retainInstallerFence(); throw error; } + }); return withPnpmCommandCwd(args, cwd => homePolicy.authorizeMutation("package") ? guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, { ...invocation.options, stdio: capture ? "pipe" : "inherit", @@ -1012,6 +1107,9 @@ async function runPackageManagerSelfUpdate(manager) { }, log: line => console.log(line), }); + if (session) childOutcome = update.ok ? { phase: "installed", activeRoot: update.path } + : { phase: "failed", rollbackPerformed: update.rollbackPerformed === true, + ...(update.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) }; if (update.ok) { // pnpm switches the active global group and updates its shim. Continue recovery // through that fresh package tree, not the old group whose launcher is still @@ -1037,12 +1135,13 @@ async function runPackageManagerSelfUpdate(manager) { `Run 'ocx update' again or follow the manual recovery steps below.`); res = { status: 1 }; } - if (res.status !== 0) recoverStoppedRuntimeAfterFailure("update failed"); + if (res.status !== 0 && childOutcome.error !== "installer-termination-unconfirmed") recoverStoppedRuntimeAfterFailure("update failed"); } finally { // Expected aborts release before process.exit(); this covers every thrown or newly-added // path and keeps token restoration coupled to the lease itself. releaseUpdateLease(); } + if (childOutcome.error === "installer-termination-unconfirmed") process.exit(1); const postInstallPlan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: serviceWasInstalled, supervision: observeSupervision() }); if (res.status === 0) { authorityLauncher = postUpdateLauncher; @@ -1218,10 +1317,10 @@ function resolveBun({ allowInstall = true, launcherPath, allowMissing = false } // intercepts `update` before the Bun CLI starts, so the help short-circuit must live // here too — otherwise --help runs the real self-update, stops the proxy, and drops // in-flight routed streams (issue #168). -const updateHelpRequested = process.argv[2] === "update" && +const updateHelpRequested = process.argv[2] === "update" && !isOrchestratedUpdateArgv(process.argv.slice(3)) && process.argv.slice(3).some(a => a === "--help" || a === "-h" || a === "help"); if (updateHelpRequested) { - console.log("Usage: ocx update [--tag latest|preview]\n\nUpdate opencodex. Preview installs stay on the preview tag unless overridden."); + console.log("Usage: ocx update [--tag latest|preview]\n ocx update --plan --json [--tag latest|preview | --version ]\n ocx update --yes --json [--tag latest|preview | --version ] [--expect-plan ] [--not-after ]\n\nPreview with --plan; apply with --yes. --expect-plan binds apply to the planToken; --not-after sets a Unix millisecond mutation deadline.\nOrchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 failed with previous version verified; 12 unverified or still running; 64 invalid usage.\nPreview installs stay on the preview tag unless overridden."); process.exit(0); } @@ -1237,7 +1336,59 @@ if (process.argv[2] === "__update-home-probe") { console.log(JSON.stringify({ schemaVersion: 1, ...readNodeUpdateHome(fileURLToPath(import.meta.url)), launcherProtocolVersion: UPDATE_HOME_LAUNCHER_PROTOCOL })); process.exit(0); } +if (process.argv[2] === "__update-orchestrated-identity") { + if (process.argv.length !== 3) process.exit(1); + const bun = resolveBun({ allowInstall: false, allowMissing: true }); + if (!bun) process.exit(1); + const result = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), process.argv[2]], { + stdio: "inherit", timeout: 8000, windowsHide: true, env: { ...process.env, OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" }, + }); + process.exit(result.status ?? 1); +} +const orchestratedUpdate = process.argv[2] === "update" && isOrchestratedUpdateArgv(process.argv.slice(3)); +const childArgs = orchestratedUpdate && process.env.OCX_UPDATE_ORCHESTRATED_CHILD === "1" + ? parseOrchestratedChildArgs(process.argv.slice(3), process.env) : null; +const orchestratedArgs = orchestratedUpdate && !childArgs?.ok ? parseOrchestratedUpdateArgs(process.argv.slice(3)) : null; +if (orchestratedArgs && !orchestratedArgs.ok) { + console.log(JSON.stringify({ error: "usage" })); + console.error("Usage: ocx update (--plan | --yes) --json [--tag latest|preview | --version ]"); + process.exit(64); +} +if (childArgs?.ok && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) { + await runPackageManagerSelfUpdate(installMethod, childArgs); +} +if (orchestratedArgs?.ok && orchestratedArgs.mode === "apply" && process.env.OCX_UPDATE_ORCHESTRATED_CHILD !== "1" + && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) { + const result = await applyNodeOrchestratedUpdate(orchestratedArgs, { + installer: installMethod, currentVersion: String(currentPackageVersion()), cliRoot: resolve(here, ".."), + home: configDir(), launcher: fileURLToPath(import.meta.url), resolveBun: () => resolveBun({ allowInstall: false, allowMissing: true }), + plan: (bun, version, tag) => probeSpawnSync(bun.path, ["--no-env-file", cliPath, "update", "--plan", "--json", + ...(version ? ["--version", version] : tag ? ["--tag", tag] : [])], { encoding: "utf8", maxBuffer: 65536, timeout: 60000, windowsHide: true, + stdio: ["ignore", "pipe", 2], env: process.env }), + identity: bun => { + const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], { + encoding: "utf8", maxBuffer: 8192, timeout: 8000, windowsHide: true, stdio: ["ignore", "pipe", 2], + env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }), + OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" }, + }); + if (probe.status !== 0 || probe.error || probe.signal) throw Error("identity unavailable"); + return JSON.parse(probe.stdout); + }, + pnpmCommands: resolvePnpmCommands(), runningShimPath: runningPnpmShimPath(), + runPnpm: (commandPath, args, capture = false) => { + const invocation = pnpmInvocationForPath(commandPath, args); + if (!invocation) return { status: 1 }; + return probeSpawnSync(invocation.file, invocation.args, { stdio: capture ? "pipe" : "ignore", encoding: "utf8", + timeout: 20000, windowsHide: true, cwd: PNPM_READ_CWD, + env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(process.env)), ...invocation.options }); + }, + spawn: probeSpawn, + }); + await new Promise(resolveOutput => process.stdout.write(`${JSON.stringify(result.result)}\n`, resolveOutput)); + process.exit(result.exitCode); +} +const passiveCapabilities = process.argv[2] === "capabilities"; const codexCliUpdateInspection = isCodexCliUpdateInspectionArgv(process.argv); // Windows inspection currently refuses before candidate I/O, so a long-lived // Windows server does not duplicate PATH into its inherited environment block. @@ -1249,6 +1400,9 @@ if (codexCliUpdateInspection && typeof process.versions.bun === "string") { } const { launchProof, launchContext, inheritedEnv } = createNodeLaunchContext(); +delete inheritedEnv.OCX_SYNC_MUTEX_HELD_BY; +// The parsed child capability was removed from process.env; only the Bun CLI handoff of this same child receives it. +if (childArgs?.ok) inheritedEnv.OCX_UPDATE_RESULT_CAPABILITY = childArgs.resultCapability; const desktopPlan = planDesktopCliHandoff({ selfPaths: [fileURLToPath(import.meta.url), process.execPath] }); if (desktopPlan.kind === "error") { if (desktopPlan.issue.startsWith("record-")) { @@ -1258,15 +1412,30 @@ if (desktopPlan.kind === "error") { } process.exit(1); } +let releaseSyncLease = () => {}; +let addSyncDelegate = () => {}; +if (process.argv[2] === "sync") { + const syncLease = acquireSyncGuard(configDir(), process.argv.slice(2)); + if (syncLease.kind === "refused") process.exit(syncLease.exit); + addSyncDelegate = pid => syncLease.addDelegate(pid); + inheritedEnv.OCX_SYNC_MUTEX_HELD_BY = String(process.pid); + let released = false; + releaseSyncLease = () => { + if (released) return; + try { syncLease.release(); released = true; } catch (error) { console.error(`opencodex: sync mutex release failed: ${error.message}`); } + }; + process.once("exit", releaseSyncLease); +} if (desktopPlan.kind === "handoff") { const result = await runDesktopCliHandoff(desktopPlan, { - argv: process.argv.slice(2), env: inheritedEnv, proof: launchProof, context: launchContext, + argv: process.argv.slice(2), env: inheritedEnv, proof: launchProof, context: launchContext, onSpawn: addSyncDelegate, }); if (result.kind === "error") { console.error(`opencodex: Desktop CLI handoff failed (${result.issue}). Repair the terminal command in OpenCodex Desktop, or run with OCX_NO_DESKTOP_HANDOFF=1.`); process.exit(127); } if (result.kind === "exit") { + releaseSyncLease(); if (result.signal) { relayOwnSignal(result.signal); } else { @@ -1278,7 +1447,7 @@ if (desktopPlan.kind === "handoff") { // Only confirmed target ENOENT reaches the ordinary package path below. } -if (process.argv[2] === "update" && installMethod === "mise") { +if (!orchestratedUpdate && process.argv[2] === "update" && installMethod === "mise") { if (installOwnership.owner) { console.error( `opencodex: this installation is externally managed by mise; update it with: mise upgrade ${installOwnership.owner.tool}`, @@ -1291,7 +1460,7 @@ if (process.argv[2] === "update" && installMethod === "mise") { process.exit(1); } -if (process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstall()) { +if (!orchestratedUpdate && process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstall()) { if (installMethod === "npm") await runNpmSelfUpdate(); if (installMethod === "pnpm") await runPnpmSelfUpdate(); } @@ -1299,7 +1468,7 @@ if (process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstal // #1849 boot probe: a prior update that lost power (or double-faulted) mid-swap leaves a // backup sibling and a broken live tree. Restore before anything tries to run from the // broken tree; reap stale backups once the live tree verifies healthy. -if (!codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall() && !isBunGlobalInstall()) { +if (process.argv[2] !== "sync" && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall() && !isBunGlobalInstall()) { try { const probe = bootRestoreProbe(resolve(here, "..")); if (probe.action === "restored") { @@ -1310,7 +1479,22 @@ if (!codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall } catch { /* the probe must never block launch */ } } -const bunRuntime = resolveBun({ allowInstall: !codexCliUpdateInspection }); +const passiveSync = process.argv[2] === "sync"; +const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync }); +if (!bunRuntime && passiveSync) fail("Bun is unavailable; install Bun before running sync."); +if (!bunRuntime && orchestratedArgs?.ok) { + const currentVersion = String(currentPackageVersion()), cliRoot = resolve(here, ".."); + if (orchestratedArgs.mode === "plan") { + const identity = { currentVersion, targetVersion: null, installer: installMethod, cliRoot, servingRoot: null, runtimeOwner: "unknown", runtime: null }; + console.log(JSON.stringify({ schema: "ocx.update.plan/1", currentVersion, targetVersion: null, installer: installMethod, + runtimeOwner: "unknown", servingPath: null, cliPath: cliRoot, canApply: false, reason: "plan-unavailable", restartRequired: false, + planToken: createUpdatePlanToken(identity), updateInFlight: true, mutationBoundMs: 900000 })); + process.exit(0); + } + console.log(JSON.stringify({ schema: "ocx.update.result/1", applied: false, fromVersion: currentVersion, toVersion: null, + installer: installMethod, restarted: false, healthy: false, rolledBack: false, error: "plan-unavailable" })); + process.exit(10); +} const bun = bunRuntime.path; // Run the Bun child asynchronously and FORWARD termination signals to it, then wait @@ -1438,6 +1622,15 @@ const child = probeSpawn(bun, [cliPath, `${NODE_LAUNCH_PROOF_PREFIX}${launchProo [BUN_RUNTIME_PATH_ENV]: bunRuntime.path, }, }); +let delegateError = false; +if (child.pid) { + try { addSyncDelegate(child.pid); } + catch (error) { + delegateError = true; + console.error(`opencodex: sync mutex delegate publication failed: ${error.message}`); + try { child.kill(); } catch (killError) { console.error(`opencodex: failed to stop sync child: ${killError.message}`); } + } +} // Windows has no real POSIX signals (no SIGHUP); forwarding is best-effort there. const FORWARDED = process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"]; @@ -1464,6 +1657,8 @@ child.on("error", err => { child.on("exit", (code, signal) => { clearHandlers(); + releaseSyncLease(); + if (delegateError) process.exit(1); // Mirror the child's terminating signal/exit code so this launcher's status matches. if (signal) { relayOwnSignal(signal); diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 8f416f48dc5..0cc2f6deea2 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -2645,7 +2645,7 @@ dependencies = [ [[package]] name = "opencodex-desktop" -version = "2.96.0" +version = "2.97.0" dependencies = [ "base64 0.22.1", "dbus", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 385e89c5464..a0ecc4f7a0a 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodex-desktop" -version = "2.96.0" +version = "2.97.0" description = "OpenCodex desktop shell" authors = ["OpenCodex contributors"] license = "MIT" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 38ac6967560..7a63a3e2b67 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCodex", - "version": "2.96.0", + "version": "2.97.0", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", diff --git a/devlog/_plan/261102_codex_affinity_persist/010_plan.md b/devlog/_plan/261102_codex_affinity_persist/010_plan.md new file mode 100644 index 00000000000..3eef8172862 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/010_plan.md @@ -0,0 +1,145 @@ +# 261102 Codex pool affinity persistence (Lane B) — 010 plan + +Status: P (plan) — awaiting Terra audit. + +## Problem + +Codex pool session pins live only in memory, so a proxy restart re-places every ongoing conversation. +Two process-local facts cause it, and both must change: + +1. `src/codex/routing/thread-affinity.ts` keeps `threadAccountMap` (conversation key -> scope -> binding) and + `conversationStateIssuerMap` (binding key -> account that minted carried encrypted state) in memory only. +2. The key those maps are indexed by is `codexConversationKeyFor()` in `src/codex/lineage.ts`: + `app:HMAC(CODEX_LINEAGE_KEY, family, thread)` where `CODEX_LINEAGE_KEY = randomBytes(32)` at module load. + After a restart the same conversation derives a different key, so a persisted map alone could never be + looked up again. (The lineage scope key `auth:HMAC(key, Authorization)` uses the same secret.) + +Under round-robin most conversations move after a restart: the prompt cache goes cold and carried encrypted +state minted by the old account can fail with `invalid_encrypted_content`. + +Reference implementation to mirror: `src/oauth/anthropic-session-affinity-store.ts` (#7813 / #7828) and its +structure section `structure/providers/anthropic-account-pool.md#durable-session-affinity`. + +## Design + +### A. Durable conversation-key secret — new `src/codex/affinity-key.ts` + +- `codexAffinityKey(): Buffer` returns a 32-byte secret cached per resolved `getConfigDir()` (re-resolved when the + home changes, as the Claude store's scope does). +- Path: `/codex-affinity-key`. Content: one line `v1:` (validated by regex). +- Hydration: `readBoundedRegularFileSync(path, 128)` (rejects symlinks/junctions/non-regular files and oversize). + Valid -> use. ENOENT -> `randomBytes(32)`, cache it, and persist asynchronously: + `trackBackgroundWork("codex-affinity-key-write", withConfigDirHardeningSettled(home, () => atomicWriteFileNoFollow(path, text, undefined, {}, { exclusive: true })))`. + If the exclusive publish loses a race (another process created it first), keep the in-memory key for this process + (its pins are lost at the next restart, same as today) — no overwrite. Invalid or unreadable -> identifier-free + `console.warn("[codex-affinity] key unavailable or invalid; affinity is process-local until it is replaced")`, generate + a fresh key and replace the file with a non-exclusive atomic write (a corrupt key must not disable persistence forever). +- The file is a secret: private mode via the atomic publisher (0600 on POSIX) and the config-dir Windows ACL barrier. + Never logged, never included in diagnostics. +- `src/codex/lineage.ts`: drop `CODEX_LINEAGE_KEY`; both HMACs call `codexAffinityKey()`. Update the LIFETIME doc block: + keys are now reproducible across restarts of one config home; lineage records themselves stay process-local. + Keep lineage a leaf: the new module imports only config/lib modules (no routing import, no cycle). +- `src/adapters/google-antigravity-wire.ts` comment that calls the key "process-random ... changes across a proxy restart": + reword only (the derivation there stays independent; it must survive loss of the key file too). No behavior change. + +### B. Durable pin + issuer snapshot — new `src/codex/routing/thread-affinity-store.ts` + +- File `/codex-affinity.json`, `{ version: 1, threads: [...], issuers: [...] }`. + - thread row: `{ keyDigest, scope, accountId, generation, createdAt, lastUsedAt }` + - issuer row: `{ keyDigest, accountId, lastUsedAt }` + - `keyDigest = sha256hex("opencodex/codex-affinity//v1\0" + key)`. Raw conversation keys, raw parent ids + (legacy keys) and binding keys never reach disk. Account ids are opaque pool ids (`isValidCodexAccountId` or `__main__`). + - Transient fields (`transientHoldSince`, `transientDetourAccountId`) and `lastReevalAt` are not persisted; restored + entries get `lastReevalAt = restore time`. +- Bounds: `MAX_FILE_BYTES = 1 MiB` on read; newest `CODEX_THREAD_AFFINITY_MAX_ENTRIES` (2048) rows per table on write and read; + rows idle longer than `CODEX_THREAD_AFFINITY_IDLE_TTL_MS` (24 h), future-dated rows, malformed rows are dropped. + Scope strings validated (`spark`/quota scopes, `legacy`, `model-detour::`, <= 512 bytes). +- Hydration is lazy per config home (first affinity read/write), synchronous and bounded, like the Claude store. + Restored rows are held in digest-keyed `restoredThreads` / `restoredIssuers` maps; they never enter + `threadAccountMap` until a request looks them up. +- Adoption: in `getThreadAffinityForScope(threadId, scope)` on a memory miss, and in `peekConversationStateIssuer`, + compute the digest, take the restored row, validate, and insert it into the in-memory map (removing it from the restored + map). Validation for thread rows = not expired AND `isThreadAffinityGenerationLive({accountId, generation})` (account record + exists, has a credential, not deleted, same credential generation; `__main__` must be generation 0). A failing row is + discarded and the request falls back to normal selection. Usability (paused, reauth, plan exclusion, quota, cooldown) is + NOT checked at restore: the existing resolve path already re-evaluates a bound account every request and releases it + with the usual reason. Issuer rows are restored after TTL validation only: an issuer for a deleted account still correctly + forces the account-change scrub. +- Writes: the snapshot is serialized from the live maps plus unadopted restored rows at flush time, so in-place mutations + elsewhere are captured. Structural changes (new bind, account change, delete, clear, per-account clear, hand-off, + prune/evict, issuer change) flush promptly; timestamp-only activity (bind of the same account, a binding read, an issuer + peek) schedules one coalesced flush after 1 s (unref'd timer). Reading a binding schedules the coalesced flush because + `src/codex/routing.ts` updates `lastUsedAt` in place after the read and that file is at its file-size cap. +- Publisher: `trackBackgroundWork("codex-affinity-write", withConfigDirHardeningSettled(home, () => atomicWriteFileNoFollow(path, json)))`, + revision counter re-flush exactly like `flushScope` in the Claude store, best-effort `registerOptionalShutdownHook("codex-affinity", ...)`, + identifier-free warnings (`[codex-affinity] snapshot persistence failed; using runtime affinity` / + `snapshot unavailable or invalid; using runtime affinity`). An observed config-home change retires the scope (memory + restored maps + pending timer), as in the Claude store. +- Exports: `flushCodexThreadAffinity()` (tests and shutdown), `resetCodexAffinityStoreMemoryForTests()`. + +### C. Minimal hooks in `src/codex/routing/thread-affinity.ts` + +- `getThreadAffinityForScope`: on miss, adopt from the store; on hit, schedule the coalesced touch flush. +- `bindThreadAffinityForScope`, `deleteThreadAffinityForScope`, `deleteThreadAffinitiesForAccount`, + `clearThreadAccountMapForAccount` (also purge restored rows for that account), `handOffThreadAffinityGeneration` (also + move restored rows fromGeneration -> toGeneration), prune/LRU paths, `rememberConversationStateIssuer`, + `peekConversationStateIssuer`, `clearConversationStateIssuerMap`, `clearThreadAccountMap` (also clears restored rows and + persists the empty snapshot, matching the Claude "explicit runtime selection clears bindings and persists the reset"). +- Update the doc comments that promise process-local lifetime (issuer map comment, `adoptLegacyAffinityForScope` comment). +- Keep edits to call sites; do not touch the affinity log label (Lane D) or `src/codex/routing/selection.ts` (Lane C). +- Core-path boundary: the store imports only `src/config/*` and `src/lib/*`; no `src/lab/` reachability. + +## Tests (new files; register each in `scripts/test-layout/layout.json` or its domain shard AND a `tests/fixtures/test-layout-expected*.json` shard) + +`tests/codex-integration/codex-affinity-restart.test.ts` (temp `OPENCODEX_HOME` per test, `removeTreeWithRetry` cleanup): + +1. Restart keeps the pin: build headers with `session-id`/`thread-id`, key = `codexPoolAffinityKey(headers)`, seed two pool + accounts, `bindThreadAffinity(key, B, now)`, `rememberConversationStateIssuer(key, B)`, flush, simulate restart + (reset in-memory affinity, store scope and key cache — NOT the files), recompute the key from the same headers: it is + identical, `getThreadAffinity(key)` returns B, `peekConversationStateIssuer(key)` returns B. Prefer one assertion through + the real resolver (`resolveCodexAccountForThread` or the existing public resolve used in `tests/codex-integration/codex-routing.test.ts`) + under round-robin, showing the restored binding wins over the strategy cursor. + MUST FAIL on old code (record output): the key differs after restart and the map is empty. +2. Dead pins fall back: account removed, credential generation bumped (re-login), and expired (>24 h) rows are dropped; + resolve returns a normal selection and the dropped row is gone from the next snapshot. +3. Privacy/bounds: the snapshot contains no raw session id, thread id or conversation key; key file is 0600 on POSIX; + oversized, malformed, future-dated and symlinked snapshots are ignored with an identifier-free warning (assert the + warning text contains no account id or key); more than 2048 rows keeps the newest. +4. `clearThreadAccountMap()` and `clearThreadAccountMapForAccount()` persist their removals (after restart the pin is gone). +5. Key file: reused across restart; a corrupt key file is replaced and a warning is emitted. + +Existing suites to rerun: `tests/codex-integration/codex-routing*.test.ts`, `codex-affinity-debug.test.ts`, +`codex-idle-window.test.ts`, `codex-account-selection-atomicity.test.ts`, `codex-auth-release.test.ts`, +`tests/responses/responses-account-change-scrub.test.ts`, `tests/responses/responses-4546-incident-regression.test.ts`, +lineage tests (`rg -l lineage tests`), `tests/lab/core-lab-boundary.test.ts`, `tests/test-layout.test.ts`, file-size ratchet test. + +## Docs + +- `structure/providers/openai-tiers.md`: lineage section (lines ~105-160) — key is a per-config-home durable secret; add a + "Durable Codex pool affinity" paragraph parallel to the Anthropic one (file names, row shape, bounds, validation, flush policy, + test names). Run `bun run structure:check`; add the new src files to the owning manifest entry if the check asks. +- `docs-site/src/content/docs/reference/cli/providers-accounts.md` (~line 848): replace "proxy restart or affinity eviction can + also leave a task unbound" with: bindings survive a proxy restart for 24 h idle; eviction, account removal or re-login leave a + task unbound. Apply the equivalent edit in every locale copy that carries the sentence (`rg -l` across docs-site locales) so no + locale contradicts English; follow `docs-site/AGENTS.md`. +- `docs-site/src/content/docs/reference/configuration/providers.md` `accountPoolStrategy` row (~line 128) says a task "can become unbound after proxy restart or affinity reset"; update it (and locale copies) the same way. + +Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Verification + +`bun test `, `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, +`bun scripts/test.ts --changed=dev --parallel=1`. Red-on-old proof: run test 1 against `origin/dev` sources (stash src changes) and record the failure. +`ci:full` label: yes — the change reaches on-disk files and docs the import graph cannot see. + +## Out of scope + +`src/codex/routing/selection.ts` (Lane C), `src/codex/auth-context.ts` and the affinity log label (Lane D), +`src/server/claude-*`, `src/server/caller-session-identity.ts` (Lane A). No change to selection policy. + +## Risks + +- Persisting the HMAC secret changes the documented "keys are unreproducible after restart" posture. The secret stays private + (same protection class as `admin-api-token`), and the snapshot holds only digests of keys derived from it. +- Two processes sharing one config home: exclusive create means the loser keeps a process-local key; acceptable and documented. +- Write amplification: at most one coalesced write per second while traffic flows, same as the Claude store. diff --git a/devlog/_plan/261102_codex_affinity_persist/020_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/020_plan_revision.md new file mode 100644 index 00000000000..cfb69bc1020 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/020_plan_revision.md @@ -0,0 +1,151 @@ +# 261102 Codex pool affinity persistence — 020 plan revision (answers audit round 1 + coordinator note) + +Supersedes the Design, Tests and Verification sections of 010_plan.md. Problem statement, docs list and out-of-scope +boundaries in 010 stay. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Security posture (coordinator note; security-sensitive per MAINTAINERS.md) + +The existing conversation-key secret `CODEX_LINEAGE_KEY` in `src/codex/lineage.ts` STAYS process-local and unchanged. +Every consumer of the derived key `app:HMAC(CODEX_LINEAGE_KEY, anchor, anchor)` therefore reveals exactly what it reveals today: + +| Consumer of the ephemeral key | Where | Changes? | +|---|---|---| +| `threadAccountMap` / `conversationStateIssuerMap` keys, pending release reasons | `src/codex/routing/thread-affinity.ts` (memory) | no | +| `authCtx.affinityKey` passed as `threadId` to routing | `src/codex/auth-context.ts`, `src/server/responses/core-codex-account.ts`, `passthrough-*.ts`, `src/providers/openai-sidecar.ts` (memory) | no | +| `_cursorClientThreadId` (Cursor adapter conversation id, advisor state) | `src/server/responses/request-prepare.ts:417,563`, `src/adapters/cursor/request-builder.ts:385`, `src/advisor/state.ts` | no | +| lineage scope `auth:HMAC(key, Authorization)` and records | `src/codex/lineage.ts` (memory) | no | +| debug capture tags | `src/codex/affinity-debug.ts` (own process-local key, ADR-0089) | no | +| request log / usage ledger lanes | `src/server/request-log-conversation.ts` — uses its own digest of raw headers, not the affinity key | no | + +The ONLY new durable artifact is the snapshot. Its row keys are derived from a SEPARATE secret used for nothing else: +`rowKey = HMAC-SHA256(storeSecret, "opencodex/codex-affinity/conversation/v1\0" + anchor)` (hex), where `anchor` is the +cohort anchor already used by `codexConversationKeyFor(anchor, anchor)` (the session id, or the parent thread id for +session-less requests). Issuer rows use domain `.../issuer/v1`. The store secret never leaves the store module and the +snapshot file; it is not logged, not exposed by diagnostics or management APIs. What becomes linkable across restarts: +only that "the same anchor was bound to account X", and only to someone who can read both the private snapshot and the +private secret file (owner-only). Nothing written to logs gains cross-restart linkability. + +## Design + +### A. Store secret — inside `src/codex/routing/thread-affinity-store.ts` + +- File `/codex-affinity-key`, content `v1:\n`, read with `readBoundedRegularFileSync(path, 128)` + (rejects symlinks, junctions, non-regular files, oversize). +- States per config-home scope: `durable` (read valid file, or our exclusive create succeeded and re-read matches), + `pending` (generated, publish in flight), `disabled` (publish failed, lost the exclusive race, file unreadable). + **The snapshot is written only in state `durable`** (blocker 2): a process with an unpublished or losing key never touches + `codex-affinity.json`. Exclusive-race loser: re-read the winner's key; if valid, adopt it before any row key is derived + (rows are derived lazily at flush time from retained anchors — see B — so adoption is safe) and become `durable`; + otherwise `disabled`. +- ENOENT -> generate, exclusive publish via `withConfigDirHardeningSettled(home, () => atomicWriteFileNoFollow(path, text, undefined, {}, { exclusive: true }))` + inside `trackBackgroundWork`. A snapshot with no key file is ignored (cannot be verified) and replaced on the first durable flush. +- Present-but-invalid regular file -> identifier-free warning, replace with a fresh key (non-exclusive atomic write), drop any + existing snapshot (its rows are unverifiable). Unreadable/symlink/non-regular -> warning, `disabled`, never replaced blindly. +- Ownership: the key file and snapshot are recorded as owned config files (use the default non-exclusive path's ownership + recording, or call `recordOwnedConfigPath` after an exclusive publish) so uninstall/reset removes them. Implementer verifies + how `src/lib/config-ownership.ts` is consumed and states it in the PR. + +### B. Durable rows without changing the ephemeral key + +- `src/codex/lineage.ts` gains a one-slot observer: `setCodexConversationAnchorObserver(fn | undefined)`; `codexConversationKeyFor(familyId, threadId)` + calls `fn?.(key, familyId, threadId)` after deriving. No new imports in lineage.ts (stays a leaf). The store registers the + observer when `thread-affinity.ts` loads it. +- The store keeps, per config-home scope, a bounded `anchorByKey: Map` (same TTL/size as the binding map; + memory only — raw anchors already live in lineage records in memory). Row keys are computed from the anchor only when a + snapshot is serialized or a restored row is looked up. Keys with no recorded anchor (legacy raw-parent keys, test keys bound + directly) are memory-only, exactly as today. +- **Durability contract (blocker 1, narrowed and documented):** a pin survives restart when the request's key is derivable from + its headers alone: every request carrying `session-id` (all Codex CLI/App turns, roots and subagents), and session-less + requests whose anchor is their immediate parent. A session-less chain of depth >= 2 resolves through an in-memory lineage + record that a restart forgets, so it re-places after restart as it does today. Docs say so. Test both sides. + +### C. Snapshot store (`codex-affinity.json`) + +- `{ version: 1, threads: [{ rowKey, scope, accountId, fence, createdAt, lastUsedAt }], issuers: [{ rowKey, accountId, fence?, lastUsedAt }] }`. +- Fence (blocker 5): `fence = sha256hex("opencodex/codex-affinity/identity/v1\0" + record.quotaHistoryIdentity)`. `quotaHistoryIdentity` is a random + UUID minted on every new login/replacement and preserved across same-account token refresh (`src/codex/account-store.ts:264,493,554`), + i.e. the Codex twin of the Claude `loginFence`. Records without a valid `quotaHistoryIdentity` stay memory-only (Claude legacy rule). +- `__main__` pins are not persisted (no durable identity fence for the native login). `__main__` issuer rows and pool issuer rows + whose fence no longer matches restore as a foreign sentinel issuer (`"\u0000foreign"`), which never equals a serving account id + and therefore forces the account-change scrub instead of letting stale carried state reach a new account. +- Restore of a thread row: TTL ok, not future-dated, scope valid, account record has credential, not deleted, fence matches. On adoption + the entry takes the record's CURRENT generation (fence proves identity continuity; this also covers an offline `ocx account refresh`), + `lastReevalAt = now`, no transient fields. Otherwise discard -> normal selection. Usability (paused, reauth, cooldown, plan/model + exclusion, transient) is left to the existing resolver (`resolveCodexAccountForThread`, `src/codex/routing.ts:498`, reuse checks ~959-1021). +- Bounds (blocker 6): read cap and write cap both `MAX_FILE_BYTES = 2 MiB`; per table newest-first up to 2048 rows; on write, if the + serialized document exceeds the cap, drop oldest rows (detour scopes first, then by `lastUsedAt`, ties by rowKey) until it fits — + deterministic. Duplicate rowKey+scope on read: keep newest. Scope validation mirrors the real component rules: `legacy`, a known + `CodexQuotaScope`, or `model-detour::` where model passes the existing 512-byte component limit (no extra cap on the whole scope). +- Lazy adoption + reconciliation (blocker 3): restored rows live in `restoredThreads: Map>` and + `restoredIssuers: Map`. EVERY mutation for an ephemeral key K with a known anchor first reconciles the restored rows of + rowKey(K): bind (restored row for that scope dropped, live wins), delete scope, delete-for-account, issuer remember, and the getters + (adopt). Account-wide operations (`clearThreadAccountMapForAccount`, `handOffThreadAffinityGeneration` — fence unchanged so no row edit + needed) and `clearThreadAccountMap`/`clearConversationStateIssuerMap` act on restored rows too, even when the live map misses. TTL pruning and + LRU eviction count live + restored rows against the 2048 bound, detour-first as `pruneLruThreadAffinities` does. Adoption increments + `threadAffinityEntryTotal` and runs the existing prune. `getThreadAffinityScopes(threadId)` adopts all restored scopes for that key first. +- Flush policy: structural changes publish promptly; timestamp-only activity (same-account rebind, binding read, issuer peek) schedules one + coalesced flush after 1 s (unref'd), which captures the in-place `lastUsedAt` writes in `src/codex/routing.ts:911,942,985,1021` + (that file is at its size cap). Revision re-flush, `trackBackgroundWork("codex-affinity-write", withConfigDirHardeningSettled(...))`, + best-effort `registerOptionalShutdownHook("codex-affinity", ...)`. Clear racing a pending flush: the flush serializes at callback time + from current state under the active-scope check, and a clear bumps the revision so a re-flush follows. +- Config-home scope (blocker 4): scope = resolved `getConfigDir()`. On an observed change the old scope is retired (restored rows, anchor map, + timers, key state) and the live runtime affinity maps are cleared (mirrors the Claude store, whose rows ARE its runtime map), so home B + never inherits or persists home A's pins. Every deferred callback re-checks `scope.active && getConfigDir() === scope.home` INSIDE the + ACL-settled callback before writing (Claude `flushSync` pattern). Lineage records stay process-global but carry only ephemeral keys, + which home B cannot persist without its own anchor observation — implementer confirms no cross-home leak in the A->B->A test. +- Passive reads (blocker 7): when `isPassiveRead()` is true the store neither creates/replaces the key, nor hydrates, adopts, schedules, + or flushes; affinity behaves exactly as today for that call. +- Warnings are identifier-free: `[codex-affinity] snapshot persistence failed; using runtime affinity`, + `[codex-affinity] snapshot unavailable or invalid; using runtime affinity`, `[codex-affinity] key unavailable; affinity stays process-local`. + +### D. Hooks in `src/codex/routing/thread-affinity.ts` + +Call-site hooks only: the getters, bind/delete/clear paths, LRU/TTL prune, issuer remember/peek/clear, `getThreadAffinityScopes`. +Comment updates for the issuer map and legacy adoption lifetime notes. No change to the affinity log label (Lane D), `selection.ts` (Lane C), +`auth-context.ts` (Lane D), or `src/codex/routing.ts` (at cap). + +## Tests + +`tests/codex-integration/codex-affinity-restart.test.ts` (register in `scripts/test-layout/layout.json` next to line 709 and in +`tests/fixtures/test-layout-expected.json` next to line 697; run `tests/test-layout.test.ts` and `tests/test-layout-tooling.test.ts`). + +1. **Restart, two fresh subprocesses (red-on-old)**: a helper script (`tests/helpers/codex-affinity-restart-worker.ts`, registered if the + layout requires) run with `bun` twice against one temp `OPENCODEX_HOME`: process 1 seeds two pool accounts (round-robin), resolves a + session-bearing request through `resolveCodexAccountForThread` with the key from `codexPoolAffinityKey(headers)`, records the issuer, + then awaits the store flush if the export exists (dynamic import with catch, like `tests/adapters/anthropic/anthropic-affinity-restart.test.ts`) + and exits; process 2 advances the round-robin cursor so a fresh pick would choose the other account, resolves the same headers, and + prints the account and whether the account-change scrub fires for a body carrying `previous_response_id` when served by the other account. + Expect: same account; issuer known. Old code: different account / no issuer. Record the old-code failure from an isolated export of + `origin/dev` (`git archive origin/dev | tar -x -C ` + the test file + `bun install --frozen-lockfile` or a node_modules link); + no stash, no worktree. +2. Fallbacks: account removed; account re-logged (new `quotaHistoryIdentity`); legacy record without identity; expired row; future row -> + normal selection, row gone from the next snapshot. Usability cases (paused, needs reauth, cooldown, model exclusion, transient hold) assert + the existing resolver behavior after restore, case by case, not a blanket "deleted". +3. `__main__`: pin not persisted; issuer restores as foreign sentinel and forces scrub. +4. Session-less depth-1 survives; depth-2 session-less chain re-places (documented limitation). +5. Reconciliation before first lookup: bind, delete, delete-for-account, issuer remember, clear and clear-for-account on a key whose row + was restored but not adopted; pending flush racing clear. +6. Key states: reused across restart; exclusive race loser adopts the winner or stays disabled and never writes the snapshot; publish + failure leaves no snapshot; corrupt regular key replaced and old snapshot dropped; symlinked/unreadable key disabled, not replaced. + Key file and snapshot are 0600 on POSIX. +7. Privacy and bounds: snapshot contains no raw session/thread id, no ephemeral key; warnings contain no account id; two full tables with + worst-case UTF-8 detour scopes stay under the cap and re-read successfully; oversized/malformed/symlinked snapshot ignored. +8. Config home A -> B -> A with pending writes: no cross-home rows, no write after retirement. +9. Passive read: no files created, no pending work. +Drain tracked background work before temp-home cleanup. + +Existing suites to rerun: `rg -l` of the affinity entry points (the round-1 audit counted 38 files) plus +`tests/lab/core-lab-boundary.test.ts`, the file-size ratchet test, `tests/ci-workflows/test-home-guard.test.ts`, lineage tests. + +## Docs + +As in 010, plus: `structure/providers/openai-tiers.md` lineage section states the conversation key stays process-local and adds +"Durable Codex pool affinity" (secret, row derivation, fence, main rule, contract narrowing, bounds, flush, passive, home scope, tests); +`structure/providers/openai-accounts.md` only where it claims pins are process-local (do not touch the diagnostic tags or the idle-window +reservation map). Locale copies found per locale (fr, ko, zh-cn, and any others), not by English text. Build the docs site per docs-site/AGENTS.md. + +## Verification + +Focused new + affected tests, `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, docs-site build, +`bun scripts/test.ts --changed=dev --parallel=1`, red-on-old recorded. Before the PR: a dedicated Terra security review (secret file +permissions/ACL, key scope, cross-restart linkability, snapshot contents, deletion on pool/config reset); its verdict goes in the PR description. diff --git a/devlog/_plan/261102_codex_affinity_persist/030_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/030_plan_revision.md new file mode 100644 index 00000000000..6be70fbd03d --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/030_plan_revision.md @@ -0,0 +1,98 @@ +# 261102 Codex pool affinity persistence — 030 plan revision (answers audit round 2) + +Amends 020_plan_revision.md; everything in 020 not changed here stands. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## R2-B1 — fences captured at the credential event + +- `ThreadAffinityEntry` gains an optional `identityFence?: string` (sha256hex of `"opencodex/codex-affinity/identity/v1\0" + quotaHistoryIdentity`). + `bindThreadAffinityForScope` already reads the account record once to take `generation`; it takes the fence from that SAME + record read, so the fence always describes the credential the binding was made under. `handOffThreadAffinityGeneration` + keeps the fence (an owned refresh preserves `quotaHistoryIdentity`, account-store.ts:493,554). An entry without a fence + (legacy record, `__main__`) is memory-only. Serialization writes the captured fence; it never reads the current record. +- Issuers: `rememberConversationStateIssuer(bindingKey, accountId, now?, credentialGeneration?)`. The fence is captured only when + the record's current generation equals the dispatched `credentialGeneration` (one record read, under the same call); otherwise + the issuer row is written without a fence. `rememberServingConversationStateIssuer` in `src/server/responses/account-change-state.ts` + passes `authCtx.generation` for pool contexts (`CodexAuthContext` pool kind carries `generation`, auth-context.ts:300). Callers that + pass no generation (routing.ts, compact) produce fence-less rows. A re-login while a response is in flight therefore cannot + attach the new identity to state issued by the old credential. +- Restore: thread row adopted only if record live AND current `quotaHistoryIdentity` fence equals the stored fence; then it takes + the record's current generation. Issuer row: fence equal -> issuer = accountId; fence missing or different -> UNKNOWN issuer + (R2-B2). `__main__` issuer rows are not persisted at all (behaves exactly as today after restart). +- Orca/external rotation (account-store.ts:1157) preserves `quotaHistoryIdentity` only after verifying `chatgptAccountId` and + `sourceSubject` are unchanged, i.e. the same upstream account; restoring across it is correct. Tested. +- Tests: re-login between bind and flush (row restored? no -> dropped); re-login between dispatch and issuer completion (issuer row + has no fence -> unknown); owned refresh/handoff before flush (restored); Orca rotation (restored); delete + re-add same id (dropped). + +## R2-B2 — unknown issuer is not proof of an account change for files + +- `thread-affinity.ts` exports `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER` (a value no account id can equal; account ids match + `^[A-Za-z0-9._-]{1,64}$` or `__main__`). `peekConversationStateIssuer` may return it only for a restored row. +- `applyAccountChangeConversationStateScrub`: unknown counts as changed (conservative continuation scrub; one cold turn). +- `accountChangeFileReferenceRefusal`: unknown issuer is ignored; refusal only when a KNOWN issuer differs or `priorAccountId` + proves an in-request move. So persistence adds no file refusal that did not exist before. +- Tests: pool re-login (fence mismatch) + file reference -> scrub of continuation state, no 400; known pool move + file -> 400 as today; + unchanged pool account -> neither. + +## R2-B3 — home switching and observer ordering + +- The anchor observer first resolves the active scope (`current()`: retire the old scope and clear live affinity maps if the home + changed) and only then records the anchor in the new scope. So the first request under home B keeps its own anchor. +- Anchor cache: per scope, LRU, refreshed on every derivation, bound 4096 (2x the binding bound), same 24 h TTL. Session-bearing + requests re-derive on every request, so their anchors are always present. A key that reaches routing without being observed in + the current scope (recorded session-less lineage reused after an anchor eviction or after a home change, legacy keys, directly + bound test keys) is memory-only: it is neither written nor matched. This is part of the documented narrowed contract. +- Tests: first B request persists under B; A -> B -> A with pending writes, both direct derivation and recorded lineage; no B row + ever appears in A's snapshot or vice versa; anchor eviction then recorded-lineage lookup -> memory-only. + +## R2-B4 — cross-process serialization + +All durable writes happen inside `withConfigDirHardeningSettled(home, () => withConfigMutationLockSync(() => ..., home))` +(`src/config/mutation-lock.ts:104`: OS-backed SQLite `BEGIN IMMEDIATE`, `busy_timeout=0`, released on process exit). Under the lock: + +1. Key: re-read the key file. Valid -> adopt it if it differs from ours (rows are derived lazily from anchors, so adoption is safe; + restored rows hydrated under a different key are discarded). Missing -> write ours. Invalid regular file -> replace with ours + and treat the existing snapshot as empty. Unreadable/symlink/non-regular -> `disabled`, no write. No `exclusive` publish is used, + so atomic-write records ownership as it does for other config files (verify; otherwise call `recordOwnedConfigPath` and treat a + `false` result as a one-time identifier-free warning, persistence continues). +2. Snapshot: read the on-disk snapshot (bounded) and MERGE: for each (rowKey, scope) keep the newest `lastUsedAt` of disk vs ours, + then apply our pending tombstones recorded since our last successful publish: per-row deletes, per-account deletes + (`{accountId, at}`: drop disk rows of that account with `lastUsedAt <= at`) and full clears (`{at}`: drop disk rows with + `lastUsedAt <= at`). Trim to the bounds. Write atomically. Clear tombstones only after the write succeeds. +3. Lock busy -> nothing written, state stays dirty, retried by the next coalesced flush (1 s, unref'd). Repeated failure warns once, + identifier-free. + +Two proxies on one config home therefore never lose each other's newer rows and never publish under a key the other replaced. +Tests: two processes creating the key concurrently end with one key and both see it; concurrent invalid-key recovery; two writers +with disjoint rows -> union; writer A deletes a row writer B still has older -> stays deleted; lock held by another process -> retry. + +## R2-B5 — reset and removal semantics + +| Entry point | Effect on disk | +|---|---| +| `clearThreadAccountMap()` — config, provider, model, combo, agent-settings, logs-usage, oauth-account and shared management routes, server index (`rg -n clearThreadAccountMap src`) | full-clear tombstone; next publish writes a snapshot without those rows (issuers cleared too, as today) | +| `clearConversationStateIssuerMap()` | issuer table cleared on disk | +| `clearThreadAccountMapForAccount(id)` — account removal, auto-pause, plan exclusion, quota refusal, account-preservation | per-account tombstone for pins only; issuer history is preserved, as today (thread-affinity.ts:223) | +| account deletion without a clear | row fails the fence on restore and is discarded | +| uninstall (`removeOwnedConfigState`) | both files are owned config paths and are removed | + +Clears bump the revision and fence pending writes (the publish serializes current state at callback time under the scope check). +Tests: restart after each row of the table. + +## R2-B7 (partial) — passive + +Under `isPassiveRead()`: no hydration, adoption, scope switch, anchor recording, scheduling or flushing. Tests with a populated +snapshot, an already scheduled write, passive getters and observer calls, and existing live maps. + +## Security table corrections (non-blocking 1) + +- Add rows: compact (`src/server/responses/compact.ts:1684` uses the ephemeral key as an in-memory issuer binding key only), + previous-response replay (keyed by response ids and its own scope, not the affinity key — implementer confirms with file:line), + advisor ledger (`src/advisor/state.ts:213` derives its own hash from `_cursorClientThreadId`, which stays ephemeral -> unchanged). +- Correct the linkability claim: anyone who can read two snapshots of the same home can link identical row keys and the plaintext + pool account ids across restarts without the secret; the secret is needed only to test a candidate session id against a row. + Both files are owner-only (0600 / config-dir ACL). The key file is itself a new durable artifact. + +## Security review + +Dedicated Terra security review before the PR; per MAINTAINERS.md security-sensitive changes also need explicit maintainer security +review — the PR says so and requests it. diff --git a/devlog/_plan/261102_codex_affinity_persist/040_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/040_plan_revision.md new file mode 100644 index 00000000000..0c24d47275b --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/040_plan_revision.md @@ -0,0 +1,94 @@ +# 261102 Codex pool affinity persistence — 040 plan revision (answers audit round 3) + +Replaces the STORAGE design of 010/020/030 (JSON snapshot, key file, merge, tombstones, config mutation lock). Everything the +round-3 audit marked RESOLVED stays as written in 020/030: identity fences captured at bind/issuance (030 R2-B1), unknown issuer +handling (030 R2-B2), observer/home ordering and the narrowed contract (030 R2-B3, 020 B), passive rule (030), security table (030), +regression-test approach (020 Tests 1). Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Why the storage changes + +Round 3 showed that a whole-file snapshot needs cross-process deletion evidence and a lock that config writes also use. A small +dedicated SQLite database gives both for free: every mutation is a row operation inside a transaction, a delete is a DELETE that +no other writer can undo by republishing its memory, and the database's own locking replaces the shared config lock. The Claude +store's properties are kept: config-home location, atomic commits, bounded rows, 24 h idle expiry, digested keys, identifier-free +warnings, private file mode and Windows ACL hardening. + +## Storage: `/codex-affinity.sqlite` (module `src/codex/routing/thread-affinity-store.ts`) + +- Opened lazily per config-home scope with `bun:sqlite`. Setup mirrors `configMutationDatabasePath` in `src/config/mutation-lock.ts:38`: + `assertNotRealHomeUnderTest`, dir 0700, `hardenSecretDir` on Windows (failure -> one identifier-free warning, persistence disabled for + the scope), file chmod 0600. `PRAGMA journal_mode=WAL; synchronous=NORMAL; busy_timeout=0`. Its own file: no interaction with + `config-mutation.sqlite`, so config and credential mutations are never blocked by this store (round-3 blocker 1). +- Ownership (round-3 blocker 3): before the first open, `recordOwnedConfigPath` for the db and its `-wal`, `-shm`, `-journal` sidecars; + every call's boolean is checked. If any returns false the store does NOT create the database (warn once, identifier-free; affinity + stays process-local for that scope). So any file this store creates is an owned path that uninstall (`removeOwnedConfigState`) removes. + Test: existing owned home -> paths recorded; manifest recording failure -> no database created. +- Schema v1 (`PRAGMA user_version = 1`; unknown version -> warn, disabled, file untouched): + - `meta(name TEXT PRIMARY KEY, value BLOB)` — row `secret`: 32 random bytes, created with `INSERT OR IGNORE` then read back, so + concurrent processes converge on one secret atomically. Replaces the key file; no corrupt-key recovery path exists. + - `threads(row_key TEXT, scope TEXT, account_id TEXT, fence TEXT, created_at INT, last_used_at INT, PRIMARY KEY(row_key, scope))` + - `issuers(row_key TEXT PRIMARY KEY, account_id TEXT, fence TEXT NULL, last_used_at INT)` + - `row_key` = HMAC-SHA256(secret, domain + anchor) hex as in 020; fence as in 030. +- Corrupt or unreadable database (open/pragma/query throws SQLITE_CORRUPT/NOTADB, symlink at the path, non-regular file): warn once, + persistence disabled for the scope, the file is left in place. + +## Writes: an ordered, coalesced in-process operation queue + +- Every mutation of the live maps enqueues an operation keyed so that the last operation per key wins: + - `bind(rowKey, scope, accountId, fence, createdAt, lastUsedAt)` -> `INSERT ... ON CONFLICT DO UPDATE` (a real placement decision). + - `touch(rowKey, scope, accountId, fence, lastUsedAt)` -> `UPDATE threads SET last_used_at = max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?`. + A touch can never create or revive a row: if another process deleted or rebound it, the touch is a no-op (round-3 blocker 2: + a stale in-memory pin in process B cannot undo A's clear). + - `deleteScope`, `deleteKey` (all scopes), `issuerSet` (upsert), `issuerTouch` (UPDATE-only, same rule), `issuerDelete`. + - `clearAccountPins(accountId)` -> `DELETE FROM threads WHERE account_id=?` (issuer history preserved, as today). + - `clearAll` -> `DELETE FROM threads; DELETE FROM issuers`; `clearIssuers` -> `DELETE FROM issuers`. + - A `clearAll` discards every queued operation before it; a `clearAccountPins` discards queued thread ops for that account. +- Flush: structural ops (bind, deletes, clears, issuerSet) schedule an immediate microtask-deferred flush; touches schedule a coalesced + flush after 1 s (unref'd timer). Read-time touches capture the in-place `lastUsedAt` writes in `src/codex/routing.ts` (at its size cap) + because the touch reads the entry's `lastUsedAt` at flush time. A flush runs the whole queue in ONE `BEGIN IMMEDIATE` transaction inside + `withConfigDirHardeningSettled(home, syncCallback)` with an in-callback `scope.active && getConfigDir() === scope.home` check, then prunes: + `DELETE` rows idle > 24 h or future-dated, and rows beyond the newest 2048 per table (ORDER BY last_used_at DESC, row_key, scope — + deterministic, detour scopes evicted first for threads, mirroring `pruneLruThreadAffinities`). +- Contention: SQLITE_BUSY -> nothing committed, queue kept, retry on the next coalesced flush; one identifier-free warning after repeated + failure. Queue bound: one entry per key (coalesced) plus per-account and full clears; if it exceeds 16384 entries (persistent failure), + drop queued touches first, then convert the remainder to `clearAll` + binds of current live rows — the failure direction loses pins + (today's behavior), never revives a deleted one. +- Same-row conflicts between processes resolve in commit order (SQLite serializes writers); equal timestamps need no tie rule. +- Best-effort shutdown flush via `registerOptionalShutdownHook("codex-affinity", ...)`; `trackBackgroundWork` around flushes; the db handle is + closed on scope retirement and in a test reset export. + +## Reads: lazy adoption straight from the database + +- No hydrated restored map. On a live-map miss for key K whose anchor is known in the current scope: + 1. If the queue holds a delete/clear covering rowKey(K) (or a pending `clearAll`), treat as absent. + 2. Otherwise `SELECT` the rows for rowKey(K) (WAL readers are not blocked by writers; a BUSY/error read is treated as absent). + 3. Validate each: TTL, not future-dated, scope rules (020), account record live with matching `quotaHistoryIdentity` fence (030). Valid -> + adopt into `threadAccountMap` with the record's current generation, count it in `threadAffinityEntryTotal`, run the existing LRU prune. + Invalid -> enqueue `deleteScope` for it. + 4. Remember per scope that rowKey(K) was consulted (bounded set, same TTL) so a second miss does not query again. +- Issuers: same on `peekConversationStateIssuer` miss; fence mismatch or null -> `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER` (030). +- Because writers go through the queue and reads check it first, a delete in this process can never be re-adopted from disk before it + is flushed, and a delete in another process is visible as soon as it commits. + +## Issuer fence capture (residual from round 3) + +`rememberServingConversationStateIssuer` passes `{ generation, chatgptAccountId }` from the pool auth context; the fence is captured only if the +record's current generation AND `credential.chatgptAccountId` both match (as `account-store.ts:382` does for dispatched credentials). + +## Tests (adds to/replaces 020+030 test list where storage-specific) + +- Two-process restart through `resolveCodexAccountForThread` (red-on-old from a `git archive origin/dev` export). +- Cross-process: A deletes/clears (row, account, issuer, full) and commits; B, holding the stale pin in memory, touches and flushes; a fresh + process restores nothing. B re-binds after A's clear (a real placement) -> row exists. Concurrent first open -> one secret. +- A process holding a write transaction on `codex-affinity.sqlite` does not block a real config mutation (`withConfigMutationLockSync`) or + a credential save. +- BUSY on flush -> retry succeeds later; queue overflow -> no deleted row revived. +- Ownership: paths recorded; recording failure -> no db created. Corrupt db / symlinked path / unknown user_version -> disabled, untouched. +- Bounds: >2048 rows per table keeps newest; idle and future rows pruned; worst-case UTF-8 detour scopes accepted. +- Everything else from 020/030 (fences, unknown issuer with files via responses and compact, priorAccountId retry, home A->B->A, passive, + privacy: no raw ids in db, warnings identifier-free, db 0600). + +## Docs + +structure/providers/openai-tiers.md "Durable Codex pool affinity" describes the SQLite store (file, schema, secret, fences, queue, touch +semantics, bounds, ownership, contract limits). Rest as in 010/030. diff --git a/devlog/_plan/261102_codex_affinity_persist/050_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/050_plan_revision.md new file mode 100644 index 00000000000..52e8b476845 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/050_plan_revision.md @@ -0,0 +1,79 @@ +# 261102 Codex pool affinity persistence — 050 plan revision (answers audit round 4: single writer) + +Amends 040 (SQLite store). Items marked RESOLVED in rounds 3-4 stay: dedicated database separate from the config mutation lock, +fences captured at bind/issuance including `chatgptAccountId` (030/040), unknown issuer (030), observer/home ordering and narrowed +contract (020/030), passive rule, security table, deterministic pruning, regression-test approach. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Step back (loop-engineering, repeated reviewer FAIL) + +Rounds 2-4 failed on the same root: several processes writing one store and reconciling stale memory. Instead of more ordering +machinery, the store gets exactly ONE writer per config home, enforced by the operating system, and only the proxy server writes. + +## Arming: only the running proxy persists + +- `armCodexAffinityPersistence()` (store module) sets a process flag; the store opens nothing and writes nothing until armed. + `startServer` arms it synchronously (no await; preserves the Lab-activation window guard in `tests/lab/core-lab-boundary.test.ts`), + via an existing non-capped startup helper in `src/server/index/*` if one fits, otherwise the single line of headroom in + `src/server/index.ts` (cap 893, now 892). CLI processes, management passive reads and every test that does not arm behave + exactly as today: no files, no handles. This also removes Windows open-handle teardown risk from existing tests. +- Tests that exercise the store arm explicitly and close it in teardown via `resetCodexAffinityStoreForTests()` (flush + close + disarm). + +## Single writer: SQLite exclusive locking mode + +- Open sequence (all inside `withConfigDirHardeningSettled(home, sync)`, scope check inside the callback): `assertNotRealHomeUnderTest`, + ownership (below), dir 0700 + `hardenSecretDir` on Windows, `new Database(path, {create:true})`, chmod 0600, then + `PRAGMA busy_timeout=0`, `PRAGMA locking_mode=EXCLUSIVE`, `PRAGMA journal_mode=WAL` (exclusive mode uses no `-shm`), `BEGIN IMMEDIATE` + (acquires and, in exclusive mode, KEEPS the write lock until close), read `user_version`: 0 + empty -> create schema v1 and secret; + 1 -> continue; anything else -> ROLLBACK, close, disable (file untouched). COMMIT. Any failure -> rollback, close the handle, classify. +- Classification: SQLITE_BUSY/LOCKED at open = another process owns the store -> state `standby`; corrupt/NOTADB/symlink/non-regular/ + unknown version/ACL failure -> `disabled` for the scope (one identifier-free warning, file untouched). +- `standby`: affinity is process-local (today's behavior). The open is retried on a later affinity access at most every 2 s + (no timer). This covers a restart whose old process is still exiting. While in standby, mutations are recorded in the pending + log (below) bounded at 4096 key groups; on overflow the oldest key group (all ops for that rowKey) is dropped — the database then + keeps its pre-gap state for that key, which is the state persistence intends to restore and is fence-checked on adoption. +- The lock is released on close and on process exit (OS file lock), so a crash never wedges the next start. +- Two-process tests: B opening while A holds the store gets standby and never writes; A closes -> B's retry acquires; A crash + (kill) -> next process acquires. + +## In-process write log (answers round-4 blockers 1-3) + +- Ordered structural log: bind, deleteScope, deleteKey, deleteAccountPins, clearAll, clearIssuers, issuerSet, issuerDelete appended in + call order. No per-key coalescing of structural ops; `clearAll` may drop entries before it (they are dominated), nothing else is dropped + except the standby overflow rule above. +- Touch set (rowKey+scope -> latest, issuer rowKey -> latest), separate from the log. At flush, in ONE transaction: replay the log in + order, then apply touches as `UPDATE ... SET last_used_at = max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?`. + Bind-then-touch: the bind inserts, the touch updates it. Delete-then-touch: the touch matches nothing. A touch never inserts. +- With a single writer, commit order equals this process's call order, so stale cross-process writes cannot exist; validation-driven + deletes are unconditional because nothing else can have replaced the row. +- Flush failure while open (disk full, I/O): rollback, keep log and touches, retry on the next flush. After 3 consecutive failures: + close and unlink the database (an owned path) so no stale pins can be restored, disable for the process, warn once. If the unlink + fails too, warn; the next start only adopts rows that pass the fence and are then re-checked by the resolver. + +## Reads + +On a live-map miss with a known anchor and the store open: if the log holds a delete/clear covering rowKey(K) -> absent; else +`SELECT` (we hold the only connection, so no BUSY). Valid -> adopt (030 validation, current generation, entry count + LRU). Invalid -> +append `deleteScope`. A per-scope "consulted" set prevents re-querying the same rowKey; read errors are not cached and do not disable +unless classified corrupt. In standby, misses do not read. + +## Ownership (round-4 blocker 4) + +- Add `codex-affinity.sqlite`, `codex-affinity.sqlite-wal`, `codex-affinity.sqlite-journal` (and `-shm` defensively) to + `INITIAL_OWNED_PATHS` in `src/lib/config-ownership.ts`, next to the `config-mutation.sqlite*` entries. Every home created from now + on owns the files from creation, with no manifest update and no race. +- Existing homes: `recordOwnedConfigPath` for each path before first create; a `false` result -> do not create the database (warn once). + The residual race — another process holding an older cached manifest rewriting it — is a property of `recordOwnedConfigPath` shared by + every config writer today (`atomicWriteFileNoFollow` default path, `config-mutation.sqlite`, the Anthropic affinity file); fixing that + API is outside this lane and is noted in the PR as pre-existing. Tests: new home lists the paths; existing owned home records them; + recording failure creates nothing; `removeOwnedConfigState` removes the db and sidecars. + +## Handle lifetime + +Closed on: scope retirement (home change), `resetCodexAffinityStoreForTests`, the shutdown hook (flush then close), the failure path. +Windows test: arm, use, reset, `removeTreeWithRetry` succeeds. + +## Guards to extend/run + +`tests/ci-workflows/test-home-guard.test.ts` (the new writer refuses before any filesystem mutation when pointed at the real home), +`tests/lab/core-lab-boundary.test.ts` (new imports do not reach Lab; startServer window scan), config-ownership tests (INITIAL list), +file-size ratchet, test-layout guards, plus the 020/030/040 test list adjusted: cross-process cases become single-writer cases above. diff --git a/devlog/_plan/261102_codex_affinity_persist/060_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/060_plan_revision.md new file mode 100644 index 00000000000..2febd334108 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/060_plan_revision.md @@ -0,0 +1,68 @@ +# 261102 Codex pool affinity persistence — 060 plan revision (answers audit round 5: reuse the existing single-writer lease) + +Amends 050. Items resolved in rounds 3-5 stay (dedicated database, fences captured at bind/issuance incl. chatgptAccountId, unknown +issuer, observer/home ordering and narrowed contract, passive rule, security table, ordered structural log + UPDATE-only touch set, +deterministic pruning, regression-test approach). 050's own lease (locking_mode=EXCLUSIVE), standby queue, overflow drop rule and +failure unlink are REMOVED. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## The product already has one serving writer per state directory + +`src/lib/spend-ledger-owner.ts` holds a process-lifetime SQLite write transaction on `spend-ledger-owner.sqlite` (acquireSpendLedgerOwner:144). +`startServer` acquires it first (`src/server/index.ts:210` via `acquireSpendLedgerServerLifecycle`); a second server on the same home fails with +`SPEND_LEDGER_OWNER_BUSY` and does not serve; a restart child waits up to 5 s for the parent's release (restartHandoffWaitMs). Leases are +reference-counted per process; release hooks (`onSpendLedgerOwnerReleased`) run BEFORE the owner transaction is rolled back and closed +(leaseFor:200-213), i.e. while the lock is still held. `mintSpendLedgerStorage(fileName)` issues a storage token bound to the current owner +generation and `assertStorageOwned(token)` refuses it after any release/reacquire (lines 255-326). The affinity store uses exactly this. + +## Activation and writes + +- The store is active for a config home only while `mintSpendLedgerStorage("codex-affinity.sqlite")` succeeds (this process owns the lease for + the current home). Otherwise affinity is process-local, exactly as today: CLI processes, passive reads, tests that never start a server. + No separate arming call; no change to `src/server/index.ts`. +- Every open and every flush first calls `assertStorageOwned(token)`; NOT_HELD or a generation change retires the scope (close the handle, + drop log/touches, memory-only) and writes nothing. A newer owner generation mints a new token and a new scope. +- One `onSpendLedgerOwnerReleased` hook (registered once): synchronously flush the pending log and touches, set `meta.clean = 1` in the same + transaction, close the handle, retire the scope. It runs while the lease is still held, so no next owner can open the database before the + final state is committed. If that flush fails, `clean` stays 0 (below). Mutations after release are memory-only (the server has stopped serving). +- Open (lazy, first affinity access while owned), synchronous like `prepareOwnerPath`: `assertNotRealHomeUnderTest` FIRST (before ownership + initialization), `recordOwnedConfigPath` for the db and its `-journal`/`-wal`/`-shm` sidecars (every boolean checked; any false -> do not create, + warn once), create with `openSync(path, "wx", 0o600)` tolerant of EEXIST, `assertPrivateFile`-equivalent (regular, not a symlink, nlink 1, + owned by uid on POSIX), `hardenSecretPath(path, { required: true })` on Windows. Then `new Database(path)`, `PRAGMA busy_timeout = 0` (the lease + guarantees no other writer; any BUSY is an anomaly -> disable), default rollback journal (no journal-mode change, so nothing is modified + before the version check), `BEGIN IMMEDIATE`, read `user_version` and `sqlite_master`: empty v0 -> create schema v1 + `meta.secret` + `meta.clean=0`; + v1 -> read `meta.clean`; if 0 (previous owner crashed or failed its final flush) DELETE all thread and issuer rows (fail closed: pins + fall back to normal selection, never revive a release that was not committed); then set `meta.clean = 0` for this ownership; any other + version/shape -> ROLLBACK, close, disable, file untouched. COMMIT. Any failure: rollback, close, classify, identifier-free warning. +- Flushes are synchronous SQLite transactions scheduled from a microtask (structural) or a 1 s unref'd timer (touches); no async ACL + barrier is needed because no file is created after open (the transient `-journal` inherits the hardened directory, as for the owner db). +- Flush failure: rollback, keep the log, retry next flush. If the log exceeds 16384 entries or 3 consecutive flushes fail, the scope is + POISONED: the log is dropped, nothing more is written, and `clean` is never set to 1 — the next owner discards every row. No unlink, no + handoff race: the file stays under the lease until this process releases or dies. + +## Why the round-5 blockers are closed + +1. Standby replay: there is no standby. Only the lease holder writes, and a new holder can open only after the previous holder's release + hook committed (or it died, in which case `clean = 0` discards everything). Decisions are never replayed across ownerships. +2. Close-then-unlink: removed. Invalidation is `clean = 0` + DELETE at the next open, serialized by the lease. +3. Dropped deletions: no drop rule. Overflow poisons the scope, which fails closed at the next start. +4. Ownership race for existing homes: REBUTTED as pre-existing and out of lane, with mitigation. New homes own the four paths from creation + via `INITIAL_OWNED_PATHS` (no manifest update, no race). Existing homes use `recordOwnedConfigPath` before creation — the identical + mechanism `spend-ledger-owner.sqlite` (prepareOwnerPath:93), `config-mutation.sqlite` (mutation-lock.ts:62) and every default + `atomicWriteFileNoFollow` write rely on today. The stale-cache rewrite is a defect of that shared API; fixing it would change every + writer and is outside this lane's scope. The PR states it as a residual: if another process's stale manifest rewrite drops the entry, + uninstall can leave `codex-affinity.sqlite` (row digests + opaque pool ids, no tokens) behind. A follow-up issue will be filed for the API. + +## Tests (storage-specific; replaces 050's cross-process list) + +- Two-process restart through `resolveCodexAccountForThread` with real `startServer`-equivalent lease acquisition (or `acquireSpendLedgerOwner` + directly) — red-on-old from a `git archive origin/dev` export. +- Not owned -> no file created, no handle; owned -> created 0600 with ownership recorded; INITIAL list contains the four names. +- Release hook: pending structural op made just before release is committed and `clean = 1`; next owner restores it. +- Crash: kill an owner subprocess with pending/committed rows -> next owner finds `clean = 0` and restores nothing. +- Poison: injected flush failures / log overflow -> next owner restores nothing. +- Release + reacquire in one process (generation change): old token refused, new scope, no writes from the old one. +- Second server on the same home is refused by the existing lease (document; existing test covers BUSY) and never opens the affinity db. +- Unknown version / non-v1 schema -> untouched bytes, disabled; symlink or non-regular path -> disabled. +- Windows: start, use, stop (release hook closes), `removeTreeWithRetry` succeeds. +- Everything else from 020/030/040 (fences, unknown issuer via responses/compact/retry, home switch, passive, bounds, privacy). +- Guards: test-home guard (real home refused before ownership init), core-lab boundary, config-ownership tests, file-size ratchet, test layout. diff --git a/devlog/_plan/261102_codex_affinity_persist/070_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/070_plan_revision.md new file mode 100644 index 00000000000..cb9316439c9 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/070_plan_revision.md @@ -0,0 +1,44 @@ +# 261102 Codex pool affinity persistence — 070 plan revision (answers audit round 6) + +Amends 060; everything else in 060 stands. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## R6 blocker — final flush runs while ownership is still logically held + +`leaseFor` (src/lib/spend-ledger-owner.ts:200-213) decrements references and nulls `activeOwner` before running `releaseHooks`, so a hook +cannot pass `assertStorageOwned`. Change (minimal, in spend-ledger-owner.ts): + +- New `onSpendLedgerOwnerReleasing(hook: () => void): void` registry. In `release()`, when this is the FINAL reference + (`owner.references === 1`), set a module flag `releasing = true`, run the releasing hooks (each in try/catch), clear the flag, then + decrement, null `activeOwner`, run the existing `releaseHooks`, ROLLBACK and close as today. During releasing hooks the owner, its + generation and the physical lock are unchanged, so `assertStorageOwned(token)` passes for the current-generation token only. +- While `releasing` is true, `acquireSpendLedgerOwner` and `mintSpendLedgerStorage` throw NOT_HELD (no reentrant acquisition or new tokens + from inside a hook). Ordinary flushes after release fail `assertStorageOwned` exactly as before; stale tokens from an earlier generation + are refused as before. +- Optional neutral alias: export `mintStateDirectoryStorage`/`assertStateDirectoryStorageOwned` as thin aliases of the spend-named functions, + with a doc comment that the lease is the state directory's single-writer primitive. (Implementer may skip if maintainers' naming rules + object; behavior is identical.) +- The affinity store registers ONE releasing hook: sync flush of log + touches, `meta.clean = 1` in the same transaction, close, retire scope. + Hook failure -> rollback, `clean` stays 0, close, retire (fail closed). The existing `onSpendLedgerOwnerReleased` hook is used only to make + sure the scope is retired if the releasing hook did not run (defensive). +- Tests: pending structural op committed and restored across a real final release (two leases in one process: first release does not flush/close, + final does); stale-token refusal after release + reacquire; hook failure leaves `clean = 0` and the next owner restores nothing; acquire/mint + inside a releasing hook is refused; existing tests/lib/spend-ledger-owner.test.ts and tests/server/spend-ledger-owner-startup.test.ts still pass. + +## R6 residuals, accepted and specified + +- Stop failure keeps ownership until process exit; abrupt exit has no release hook -> `clean = 0` path (pins discarded). Documented. +- The final transaction is synchronous and bounded (at most the pending log, itself bounded at 16384 entries + touches); filesystem stalls + can still delay shutdown. Documented in structure. +- After final release, late async work is memory-only: the scope is retired, its token is invalid, nothing reopens under it and `clean` is never + touched again by that scope. +- Multiple servers in one process share the lease; the store stays live until the last reference releases. +- Test isolation (060 wording corrected): tests that start a server AND exercise affinity will create `codex-affinity.sqlite` in their isolated + home; the handle closes on the final server stop. Implementer runs every suite that starts a server and uses pool affinity + (`rg -l startServer tests` intersected with affinity entry points), checks teardown order, and adds a Windows-safe close in any helper that + resets state without stopping the server. +- Passive calls stay passive under a held lease: no open, adoption, scheduling or flush. Lazy open happens before any durable deletion that + must invalidate an unadopted row (a delete for a key with a known anchor opens the store first when owned). +- Ownership race for existing homes: residual stated in the PR; a follow-up issue for `recordOwnedConfigPath` is filed before the PR opens + and linked from it. +- Unsupported version/shape tests assert the application wrote nothing (no schema/meta change, no row change); they do not claim byte-for-byte + identity where SQLite's own hot-journal recovery may touch the file. diff --git a/devlog/_plan/261102_codex_affinity_persist/080_implementation_spec.md b/devlog/_plan/261102_codex_affinity_persist/080_implementation_spec.md new file mode 100644 index 00000000000..44f5913513a --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/080_implementation_spec.md @@ -0,0 +1,187 @@ +# 261102 Codex pool affinity persistence — 080 consolidated implementation spec + +Single source of truth for implementation. Consolidates 010-070 and the round-7 residuals; where they differ, this file wins. +Issue: https://github.com/lidge-jun/opencodex/issues/8091. Follow-up (ownership manifest race): https://github.com/lidge-jun/opencodex/issues/8093. +Security-sensitive (MAINTAINERS.md): a dedicated Terra security review runs before the PR and its verdict goes in the PR description. + +## 1. Problem + +Codex pool pins (`threadAccountMap`) and conversation-state issuers (`conversationStateIssuerMap`) in `src/codex/routing/thread-affinity.ts` +are in memory only, and the key they use is `codexConversationKeyFor()` in `src/codex/lineage.ts`, an HMAC under a per-process random secret. +A restart re-places every conversation (round-robin moves most of them: cold prompt cache) and loses the issuer that triggers the +account-change scrub (carried encrypted state can fail with `invalid_encrypted_content`). + +## 2. Contract + +- A pin survives a graceful proxy restart for up to 24 h idle when the request's cohort anchor is derivable from its headers: every request + with `session-id` (Codex CLI/App roots and subagents) and session-less requests anchored on their immediate parent. Deeper session-less + chains, keys first derived under another config home, legacy raw-parent keys and keys whose anchor was evicted are memory-only. +- Pins whose account is gone, re-logged (new `quotaHistoryIdentity`), legacy (no identity) or expired are dropped: normal selection. + Usability (pause, reauth, cooldown, plan/model exclusion, transient hold) stays with the existing resolver (`resolveCodexAccountForThread`, src/codex/routing.ts:498). +- `__main__` pins and `__main__` issuers are not persisted. +- A crash, a failed final flush, or a poisoned store makes the next owner discard every row (fail closed). +- Only the process holding the state directory's single-writer lease (`src/lib/spend-ledger-owner.ts`, acquired by `startServer`) persists. + A server in another process on the same home is refused by that lease; servers in the same process share it (reference-counted). + +## 3. Security posture + +- `CODEX_LINEAGE_KEY` and every value derived from it stay process-local and unchanged: pin/issuer map keys, `authCtx.affinityKey`, + `_cursorClientThreadId` (request-prepare.ts:417,563; cursor request-builder.ts:385; advisor state.ts:213 derives its own hash from it), + compact's issuer binding key (compact.ts:1684), lineage scope keys, affinity-debug tags (own key, ADR-0089). Request-log lanes use their + own digest of raw headers. Previous-response replay is keyed by response ids (implementer cites file:line in the PR). None changes. +- New durable artifact: `/codex-affinity.sqlite` (0600, Windows ACL via `hardenSecretPath`). It holds a 32-byte store secret + (`meta.secret`), rows keyed by `HMAC-SHA256(secret, "opencodex/codex-affinity/conversation/v1\0" + anchor)` (issuers: `.../issuer/v1`), + opaque pool account ids, identity fences `sha256("opencodex/codex-affinity/identity/v1\0" + quotaHistoryIdentity)`, scopes and timestamps. + No raw session/thread ids, no ephemeral keys, no tokens, no emails. Anyone who can read two copies of the file can link identical row keys + and pool ids across restarts; the secret is needed only to test a guessed anchor. Never logged; warnings are identifier-free. + +## 4. Modules and changes + +### 4.1 `src/codex/lineage.ts` +- Add `setCodexConversationAnchorObserver(fn?: (key: string, anchor: string) => void)`; `codexConversationKeyFor` calls it after deriving + (`anchor` = the family/thread value; for the cohort form both are the anchor). No new imports. Update the LIFETIME doc block: keys stay + process-local; the affinity store persists only digests under its own secret. + +### 4.2 `src/lib/spend-ledger-owner.ts` +- `onSpendLedgerOwnerReleasing(hook)`: in `release()`, after the per-lease `released` idempotence guard and the existing owner/refcount checks, + when this is the final reference (`owner.references === 1`): set `releasing = true`; run each releasing hook in its own try/catch; + clear `releasing` in `finally`; then continue exactly as today (decrement, null `activeOwner`, `boundLedgerHome = null`, release hooks, + ROLLBACK/close, throw on rollback/close failure). +- While `releasing`, `acquireSpendLedgerOwner` and `mintSpendLedgerStorage` throw `SPEND_LEDGER_OWNER_NOT_HELD`. +- Optional neutral aliases (`mintStateDirectoryStorage`, `assertStateDirectoryStorageOwned`) with a doc comment; behavior identical. +- Tests: throwing releasing hook does not block release; repeated release is a no-op; first of two leases does not run hooks; acquire/mint inside + a hook refused; existing `tests/lib/spend-ledger-owner.test.ts`, `tests/server/spend-ledger-owner-startup.test.ts` pass. + +### 4.3 `src/lib/config-ownership.ts` +- Add `codex-affinity.sqlite`, `-journal`, `-wal`, `-shm` to `INITIAL_OWNED_PATHS` next to the `config-mutation.sqlite*` entries. + +### 4.4 New `src/codex/routing/thread-affinity-store.ts` +Imports only `src/config/*`, `src/lib/*`, `bun:sqlite`, node builtins and the account-store reader (no routing value import cycle, no Lab). + +Scope = (config home, owner generation, storage token). Created lazily on the first affinity access when `mintSpendLedgerStorage("codex-affinity.sqlite")` +succeeds and `isPassiveRead()` is false. A home change or generation change retires the scope (close handle, drop log/touches/anchors/consulted set) +and clears the live affinity maps (as the Claude store drops its rows on home change). The anchor observer resolves the active scope FIRST, +then records `anchorByKey` (LRU, 4096, 24 h TTL, refreshed per derivation). Passive calls do nothing (no open, observe, adopt, schedule, flush). + +Open (synchronous; any failing step -> rollback/close, identifier-free warning, scope disabled for its lifetime. Earlier steps may already have +created the empty file or set its mode/ACL; for an unsupported version or shape the app makes no schema, metadata or row change, though SQLite's +own hot-journal recovery may still alter bytes): +1. `assertNotRealHomeUnderTest(home)` before anything else. +2. `recordOwnedConfigPath` for the db and its three sidecars (`-journal`, `-wal`, `-shm`); any `false` -> do not create. +3. `openSync(path, "wx", 0o600)` tolerating EEXIST; regular file, not a symlink, nlink 1, uid owner on POSIX; chmod 0600; `hardenSecretPath(path, {required:true})`; re-check. +4. `assertStorageOwned(token)`; `new Database(path)`; `PRAGMA busy_timeout = 0`; default rollback journal (no journal-mode change). +5. `BEGIN IMMEDIATE`; read `user_version` and `sqlite_master`. Empty v0 -> create schema v1, `meta.secret` (32 random bytes), `meta.clean = 0`. + v1 with the exact expected tables -> if `meta.clean != 1`, DELETE all thread and issuer rows; set `meta.clean = 0`. Anything else -> ROLLBACK, close, disable. + COMMIT. BUSY at any point is an anomaly under the lease -> disable. + +Schema v1: `meta(name TEXT PRIMARY KEY, value BLOB)`; `threads(row_key TEXT, scope TEXT, account_id TEXT, fence TEXT, created_at INTEGER, last_used_at INTEGER, PRIMARY KEY(row_key, scope))`; +`issuers(row_key TEXT PRIMARY KEY, account_id TEXT, fence TEXT, last_used_at INTEGER)` (fence nullable). + +Writes: +- Ordered structural log in call order: bind(rowKey, scope, accountId, fence, createdAt, lastUsedAt) = upsert; deleteScope; deleteKey; + deleteAccountPins(accountId) (pins only; issuers kept, as today); issuerSet (upsert); issuerDelete; clearIssuers; clearAll. Only `clearAll` + may drop earlier entries. Ops are logged only for keys with a known anchor in the scope (account-wide and clear ops always). +- Touch set (rows touched since the last flush) applied after the log in the same transaction. The timestamp is read from the LIVE in-memory entry + AT FLUSH TIME, never captured when the touch is scheduled: the getter schedules the touch before `src/codex/routing.ts` mutates the returned entry + (routing.ts:903-911), so a captured value would persist the old time and could expire an active pin. A touched row whose live entry is gone is skipped. Statement: + `UPDATE ... SET last_used_at = max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?` (issuers: `account_id` and `fence IS ?`). Never inserts. +- Structural ops schedule a microtask flush; touches (same-account rebind, binding read, issuer peek) a 1 s unref'd timer. A binding read schedules a + touch so the in-place `lastUsedAt` writes in `src/codex/routing.ts:911,942,985,1021` are captured (that file is at its size cap and is not edited). +- Flush = `assertStorageOwned(token)`, one `BEGIN IMMEDIATE` transaction: log, touches, prune (idle > 24 h or future-dated; newest 2048 per table ordered by + `last_used_at DESC, row_key, scope`, model-detour scopes evicted first). Failure -> ROLLBACK, keep log, retry next flush. 3 consecutive failures or log + > 16384 entries -> POISONED: drop log/touches, never write again, `clean` stays 0. +- Releasing hook (registered once via `onSpendLedgerOwnerReleasing`): if the scope is open and not poisoned, one transaction = log + touches + prune + + `meta.clean = 1`. Transaction failure -> ROLLBACK (clean stays 0). Then close; a close error after a successful COMMIT leaves `clean = 1` committed + (state is consistent: everything was committed) and is reported as an identifier-free warning. Retire the scope. `onSpendLedgerOwnerReleased` retires + any scope still open (defensive). Late async work after release is memory-only and never reopens under the old token. + +Reads (adoption): +- On a live-map miss for key K with a known anchor in an open scope: a pending delete/clear in the log covering rowKey(K) -> absent. Otherwise SELECT. + Thread row valid when: not idle > 24 h, not future-dated, scope valid (`legacy`, a known `CodexQuotaScope`, or `model-detour::` whose model + passes the existing 512-byte component rule), account record has a credential, not deleted, current `quotaHistoryIdentity` fence equals the stored fence. + Valid -> insert into `threadAccountMap` with the record's CURRENT generation, `lastReevalAt = now`, no transient fields, increment + `threadAffinityEntryTotal`, run the existing LRU prune. Invalid -> log deleteScope. +- Issuer row: idle > 24 h or future-dated -> absent and log issuerDelete (time passes after the last flush prune, and the live issuer map also + expires on peek, thread-affinity.ts:238,274). Otherwise fence equal -> issuer = account id; fence null or different -> `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER`. +- A bounded per-scope consulted set avoids re-querying; read errors are not cached. +- `getThreadAffinityScopes(K)` adopts all restored scopes for K first. + +### 4.5 `src/codex/routing/thread-affinity.ts` (call-site hooks only; not the affinity log label) +- `ThreadAffinityEntry.identityFence?: string`, captured in `bindThreadAffinityForScope` from the same record read that supplies `generation`; + kept by `handOffThreadAffinityGeneration`. Entries without a fence (legacy record, `__main__`) are memory-only. +- `rememberConversationStateIssuer(bindingKey, accountId, now?, credential?: { generation, chatgptAccountId })`: fence captured only when the record's current + generation AND `credential.chatgptAccountId` match; else the row is fence-less (restores as unknown). `__main__` not persisted. +- Export `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER` (a string no account id can equal). +- Hooks in: scoped getters (adopt on miss; touch on hit), `getThreadAffinityScopes`, bind/delete/delete-for-account, `clearThreadAccountMapForAccount`, + TTL/LRU prune, `handOffThreadAffinityGeneration`, issuer remember/peek/clear, `clearThreadAccountMap` (clearAll). +- Update the lifetime comments (issuer map, legacy adoption). + +### 4.6 `src/server/responses/account-change-state.ts` +- `rememberServingConversationStateIssuer` passes `{ generation, chatgptAccountId }` for pool contexts. +- `applyAccountChangeConversationStateScrub`: unknown issuer counts as changed. +- `accountChangeFileReferenceRefusal`: unknown issuer ignored; refuse only for a known different issuer or a `priorAccountId` move. + +### 4.7 Comment-only +`src/adapters/google-antigravity-wire.ts` comment about the process-random key: keep the meaning (the key still changes across restarts), adjust wording only if needed. + +## 5. Reset and removal + +| Entry point | Durable effect | +|---|---| +| `clearThreadAccountMap()` (config/provider/model/combo/agent-settings/logs-usage/oauth-account/shared management routes, server index) | clearAll | +| `clearConversationStateIssuerMap()` | clearIssuers | +| `clearThreadAccountMapForAccount(id)` (removal, auto-pause, plan exclusion, quota refusal, preservation) | deleteAccountPins (issuers kept) | +| account deleted/re-logged without a clear | fence fails on adoption -> row deleted | +| uninstall | owned paths removed (new homes always; existing homes subject to #8093) | + +## 6. Tests + +New file `tests/codex-integration/codex-affinity-restart.test.ts` (+ helper worker under `tests/helpers/` if needed); register in +`scripts/test-layout/layout.json` (near line 709) and `tests/fixtures/test-layout-expected.json` (near line 697). Lease tests may live in +`tests/lib/spend-ledger-owner.test.ts` if under its size cap, else a sibling file (registered). Cases: + +1. Red-on-old: two fresh `bun` subprocesses on one temp home, each acquiring the lease, seeding two pool accounts with round-robin, resolving a + session-bearing request via `resolveCodexAccountForThread` with `codexPoolAffinityKey(headers)`, recording the issuer, releasing. Process 2 advances + the cursor so a fresh pick chooses the other account. Expect same account and known issuer (scrub not triggered for the same account; triggered for + a different one). Old code (isolated `git archive origin/dev` export with the test + helper copied, only the optional store import caught) fails on + the assertion; record output. +2. Fallbacks: removed, re-logged, legacy, expired, future -> normal selection, row deleted. Usability cases asserted against the resolver one by one. +3. `__main__`: pin and issuer not persisted. +4. Session-less depth-1 survives; depth-2 re-places; anchor eviction -> memory-only. +5. Reconciliation before first lookup: bind/delete/delete-for-account/issuer set/clear/clear-for-account on a key with a restored, unadopted row. +6. Fence races: re-login between bind and release; re-login between dispatch and issuer completion; owned refresh/handoff; Orca rotation; delete + re-add. +7. Unknown issuer with file references via responses and compact; `priorAccountId` retry still refuses; known different issuer still refuses. +8. Lease: not owned -> no file; release flush commits pending op and `clean = 1`; two leases -> only final release flushes; crash (kill subprocess) -> next owner + restores nothing; poison (injected failures, overflow) -> next owner restores nothing; transaction failure in the releasing hook -> clean 0; close failure + after commit -> rows restored; release + reacquire -> old token refused. +9. Database shape: unknown version/shape -> app makes no schema, metadata or row change (SQLite hot-journal recovery may still alter bytes) and disables; symlink/non-regular -> disabled; file 0600; INITIAL list has the four names; + existing owned home records them; recording failure -> no db. +10. Bounds and privacy: > 2048 rows per table keeps newest; worst-case UTF-8 detour scope accepted; no raw ids/ephemeral keys in the db; warnings identifier-free. + Touch timing: resolver reuse (which mutates `lastUsedAt` after the getter) then release and restart persists the NEW timestamp; an issuer row that + expired or is future-dated at read time is treated as absent and deleted. +11. Home A -> B -> A, first B request, recorded lineage; passive calls with a populated db and a held lease. +12. Windows: start, use, stop, `removeTreeWithRetry` succeeds. + +Existing suites to run: every test file using the affinity entry points or `startServer` + pool affinity (the round-1 audit counted 38), lineage tests, +`tests/responses/responses-account-change-scrub.test.ts`, `tests/responses/responses-4546-incident-regression.test.ts`, owner tests, config-ownership tests, +`tests/lab/core-lab-boundary.test.ts`, `tests/ci-workflows/test-home-guard.test.ts` (new writer refused before ownership init), file-size ratchet, +`tests/test-layout.test.ts`, `tests/test-layout-tooling.test.ts`. + +## 7. Docs + +- `structure/providers/openai-tiers.md`: lineage section (key stays process-local) + new "Durable Codex pool affinity" subsection (contract, file, schema, + secret, fences, lease, clean flag, write log, touches, bounds, ownership residual #8093, tests). +- `structure/providers/openai-accounts.md`: only claims that pins are process-local (not the diagnostic tags or idle-window reservations). +- `structure/` owner of `src/lib/spend-ledger-owner.ts` (find via structure/manifest.json): document releasing hooks. +- docs-site: `reference/cli/providers-accounts.md` (~848) and `reference/configuration/providers.md` (`accountPoolStrategy` row) restart wording, in English + and every locale copy (search per locale); build the docs site per docs-site/AGENTS.md. + +## 8. Verification + +Focused tests above, `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, docs-site build, `bun scripts/test.ts --changed=dev --parallel=1`, +red-on-old recorded. PR gets `ci:full` (subprocess tests, docs, on-disk contracts). + +## 9. Out of scope + +`src/codex/routing/selection.ts` (Lane C), `src/codex/auth-context.ts` and the affinity log label (Lane D), `src/server/claude-*` and +`src/server/caller-session-identity.ts` (Lane A), `src/codex/routing.ts` and `src/server/index.ts` (size caps), the ownership API fix (#8093). diff --git a/devlog/_plan/261102_codex_rr_headroom/010_plan.md b/devlog/_plan/261102_codex_rr_headroom/010_plan.md new file mode 100644 index 00000000000..3acba0ef824 --- /dev/null +++ b/devlog/_plan/261102_codex_rr_headroom/010_plan.md @@ -0,0 +1,195 @@ +# 010 — Codex round-robin places new conversations on accounts with headroom + +Lane C of the multi-account parallel lanes. Branch `goat/lane-c-codex-rr-threshold`, PR target `dev`. + +## Problem + +`accountPoolStrategy: "round-robin"` rotates unbound (new) Codex conversations by counter only. +`pickUnboundStrategyAccount` (src/codex/routing/selection.ts) hands `listEligibleCodexAccountIds` +straight to `pickRoundRobinAccount` / `peekRoundRobinAccount`. A new conversation can therefore land +on an account already at 95%. The conversation binds there (thread affinity), and when the account +reaches 100% the binding is released and the conversation moves to another account with a cold +prompt cache. + +## Finding that changes the brief + +The brief says the Claude pool's round-robin already skips accounts over `autoSwitchThreshold` for new +sessions. On current `dev` it does not: `src/oauth/anthropic-routing.ts` `pickUnboundStrategyAccount` +filters only `anthropicModelExhausted` (model family at 100%), and the docs say Claude round-robin is +not usage-driven (docs-site providers-accounts.md, structure/providers/anthropic-account-thresholds.md). +The "prefer under threshold, fall back when none" rule lives in Claude's `pickLowestUsage` +("Thresholds are preferences, never eligibility"). This lane models the Codex rule on that idea and +leaves Claude routing code alone (out of lane scope). The PR body states this. + +## Design (diff level) + +src/codex/routing/selection.ts only. + +1. New private helper next to `hasCodexQuotaHeadroom`: + + ```ts + function roundRobinPlacementCandidates(config, eligible, now, selectionOptions): readonly string[] { + const withHeadroom = eligible.filter(id => hasCodexQuotaHeadroom(config, id, selectionOptions, now)); + return withHeadroom.length > 0 ? withHeadroom : eligible; + } + ``` + +2. `pickUnboundStrategyAccount`, round-robin branch: compute `eligible` as today, then + `const candidates = roundRobinPlacementCandidates(...)` and pass `candidates` to BOTH + `peekRoundRobinAccount` (commit=false, preview) and `pickRoundRobinAccount` (commit=true). Everything + after the pick (shared-active commit, `bindThreadAffinity`, `notePoolRotationSuccess`) is unchanged. + +Why this predicate: `hasCodexQuotaHeadroom` is the score server-side threshold evaluation already uses +for fill-first, reset-first, the priority-tier filter, pin drain and the bound-thread cache-safe +replacement: `computeCodexUsageScore` (hottest known 5h/weekly/30d window, credits cap at 99) against +`getEffectiveCodexAutoSwitchThreshold` (per-account override, use-remaining = 0, else global, default 80). +"At or over" = `usage >= threshold` is not headroom. Threshold 0 = always headroom (switching disabled). +Unknown usage (unprimed) = headroom, same as fill-first and the tier filter. + +Scope/pool interactions: +- Quota scopes (shared / reserve): `eligible` is already scope-filtered (cooldowns per scope) and the ring + is keyed per scope (`codexPoolKeyForScope`). Usage score is the account-level quota for every scope, as + for every other Codex usage decision (quota strategy, fill-first, tier filter). No scope-specific usage + store exists. +- Model detours: `strategySelectionOptionsForModelDetour` narrows `modelEligibleAccountIds` before + eligibility; the headroom filter only narrows that further and falls back to it. +- Priority tiers: `selectPriorityTier` already keeps a tier while any member has headroom; members without + headroom are in that tier only because a sibling has some. The new filter drops them for RR placement. +- Sticky limit: `pickRoundRobinFromState` keeps `activeKey` while it is in the passed list; a sticky + account that crossed the threshold is released and rotation continues over the headroom set. With all + over, the full list returns and sticky behaves as today. + +Not changed (deliberate): +- Bound conversations: RR never re-evaluates a live binding for quota (`reevaluateAffinityQuota` returns + null for non-quota strategies); a binding releases only on exhaustion/cooldown/failure/pause etc. This + change does not touch that path, and a test pins it. +- `pickAlternateCodexAccount` / `peekAlternateCodexAccount` (failover and transient detours): the request is + leaving a failing account, not being placed. Left as-is; preview/resolve agreement there is untouched. +- `listEligibleCodexAccountIds` itself (shared by fill-first/reset-first and failover paths). +- Claude/Anthropic routing. + +Placement after a released binding (account exhausted/cooled) goes through `pickUnboundStrategyAccount` +too, so that re-placement also prefers headroom — which is the cold move we want to land well. + +## Tests (new file tests/codex-integration/codex-round-robin-headroom.test.ts) + +Registered in scripts/test-layout/layout.json and tests/fixtures/test-layout-expected.json. +Three accounts a/b/c, global threshold 80, RR, stickyLimit 1 unless stated. + +1. New placements skip an account at 95% while b/c are at 10%: 6 unbound picks never return a, split 3/3. +2. Exactly at threshold (80) is skipped (>=). +3. All over threshold (90/95/85): unbound picks rotate across all three (old behaviour). +4. Per-account override above usage (a override 99, usage 95) keeps a in rotation. +5. Global threshold 0 keeps a at 95% in rotation. +6. Unknown usage counts as headroom: a=95, b/c unprimed -> never a. +7. Bound conversation stays: thread bound to a at 10%, a rises to 95% -> 20 resolves stay on a. +8. Preview agrees with resolve: previewCodexAccountForRequest(null) equals next resolve and is never a. +9. Reserve scope ring also skips a and does not advance the shared ring. +10. Sticky limit 2 over headroom set: b,b,c,c. + +Regression proof: run the new file against unchanged selection.ts before implementing; record failing tests. + +## Docs + +docs-site (English + fr, ja, ko, ru, tr, zh-cn, zh-tw where the row exists): +- reference/configuration/providers.md `anthropicAccountPool.strategy` and `quotaWindow` rows: exact rule in + "Audit round 1" B3 below. (All 8 locales.) +- guides/claude-code.md quota sentence (en, fr, tr, zh-tw carry it): same correction. +- Codex `autoSwitchThreshold` row ("normal round-robin selection does not use it"), `accountPoolStrategy` row + (round-robin clause) and the Codex strategy table `round-robin` row ("ignores usage thresholds"; en, fr, tr, + zh-tw): new rule — new placements skip accounts at/over their effective threshold while any eligible + account is under it; all over -> plain rotation; bound conversations never move for the threshold. +- getting-started/how-it-works.mdx if it states RR ignores usage (it does not today; check only). + +structure/providers/openai-accounts.md (owner of src/codex routing): add the RR placement rule to the +per-account auto-switch thresholds paragraph (where effective threshold is consumed). + +## Verification + +Focused: new file + codex-pool-rotation, codex-account-threshold-routing, codex-routing, codex-idle-window, +codex-priority-failback, codex-use-remaining-quota, codex-preserve-signed-in, codex-pool-request-owned-main, +codex-auth-context (baseline 502 pass / 1 skip / 0 fail on 6f1d3e65c). +Gates: bun run typecheck, bun run structure:check, bun run privacy:scan, test-layout tests, +bun scripts/test.ts --changed=dev --parallel=1. docs-site build (required, see B4). + +## Risks + +- Existing tests asserting RR rotation onto an over-threshold account would change colour: none found in the + baseline run; any that appears is examined as contract vs incidental. +- Unknown-as-headroom differs from Claude's pickLowestUsage (which filters only when a KNOWN account is under + threshold). Chosen for consistency with Codex fill-first/tier filter; an unprimed account is a better + placement than a known 95% one. + + +## Audit round 1 (Terra, FAIL) — dispositions + +B1 lineage first placement (routing.ts pickLineageServingAccount) — REBUTTED. The lineage pick is not a +round-robin placement: it runs for every strategy, before any strategy pick, and it places a child that has +no binding on the account its PARENT (or a compatible sibling) is being served from right now. The parent is +itself pinned there and, under cache affinity, stays until exhaustion/cooldown/failure; the child following +it keeps the family on one warm prefix, and the whole family moves together at the same release. Applying the +round-robin headroom filter here would split a family onto a cold account to save headroom, which is exactly +the trade the cache-affinity design (#4546) refuses, and it would change quota/fill-first/reset-first behaviour +the brief does not ask for. `lineageServingAccountId` already refuses a serving account that is not selectable, +has an unrecovered quota refusal, or is failover-tripped, so an exhausted parent does not attract children. +Kept unchanged; the docs and PR state that a child of a live conversation follows its parent's account. +(routing.ts is also at 1623/1626 of its file-size cap.) + +B2 docs scope — ACCEPTED. Codex round-robin claims to update: +- en providers.md: autoSwitchThreshold row (126), accountPoolStrategy row (128), strategy table round-robin row (1047). +- fr: rows 58, 60, strategy table 258. tr: rows 58, 60, strategy table 284. zh-tw: rows 54, 56, table 199. +- ja: rows 56, 58, strategy prose 236. ko: rows 56, 58, strategy prose 240. ru: rows 57, 59, prose 268. + zh-cn: rows 56, 58, prose 264. +Claude quota claims to update (all 8 locales): `anthropicAccountPool.strategy` row, and the `quotaWindow` row +sentence that says `quota` ranks eligible candidates directly for new-session assignment; guides/claude-code.md +quota sentence (en, fr, tr, zh-tw). + +B3 Claude wording — ACCEPTED. Accurate rule (anthropic-routing.ts resolveAnthropicAccountForSession): +with a new session and no manual/affinity hit, `quota` keeps a healthy active account while its known usage in +`quotaWindow` is below that account's effective `autoSwitchThreshold` (default 80); unknown usage also keeps it. +It picks the lowest known usage in `quotaWindow` when the active account reaches the threshold, or cannot be used +(paused, reauth, cooling, model-family exhausted, or under `weekly` its 5-hour bar is exhausted). With threshold +`0` a healthy active account is kept and lowest usage is used only when it cannot be used. 429 recovery ranks +replacements by `quotaWindow` directly. + +B4 docs build — ACCEPTED. Required locally: `cd docs-site && bun install --frozen-lockfile && bun run build`; +report honestly if it cannot run. + +Non-blocking notes folded: +- Tests added: sticky batch where the sticky account crosses the threshold mid-batch; re-entry after usage drops; + all-over fallback after a narrowed ring; released-binding re-placement (bound account goes to 100% -> next + placement avoids an over-threshold sibling); failover (pickAlternateCodexAccount) unchanged (may pick an + over-threshold account) as a boundary; model roster (modelEligibleAccountIds) narrowing; priority tier; + terminal short window (short-only 100% = no headroom); credits documented, not separately tested. +- Score wording qualified: hottest KNOWN long window (weekly/30d) refined by an unexpired short window; a + short-only observation is unknown except a terminal (100%) short window; spendable credits cap at 99 only + when credits-after-limit is enabled. +- Regression proof without stash: write the new test file first, run it against unchanged selection.ts, record + the failing tests, then implement. +- structure/: openai-accounts.md (per-account thresholds paragraph) is the owner touched; other src/codex + mapped docs checked for RR-ignores-threshold claims (none found besides openai-tiers' pin note, unaffected). + +## Audit round 2 (Terra, FAIL on one blocker) — dispositions + +R2-B1 Claude rule — ACCEPTED. Replacement rule used by the docs (supersedes the B3 wording above where they differ): +With the pool enabled, a new session without a manual or affinity hit keeps a healthy active account while its +known usage in `quotaWindow` is below that account's effective `autoSwitchThreshold` (default 80); unknown usage +also keeps it. When the active account reaches its threshold or cannot be used (paused, reauth, cooling, +model-family exhausted, or under `weekly` its 5-hour bar is exhausted), `quota` picks a replacement: among +candidates (5-hour-exhausted and model-exhausted ones dropped while others remain) it prefers accounts below their +own effective threshold whenever any account with known usage is below it, then takes the lowest usage in +`quotaWindow`; when every account is at or over its threshold it takes the lowest usage among all. Threshold 0 +keeps a healthy active account. 429 recovery under `quota` uses the same replacement picker. (anthropic-routing.ts +pickLowestUsage ~785-830, resolveAnthropicAccountForSession ~1048-1083.) Docs keep this compact: "keeps the active +account until it reaches autoSwitchThreshold (or cannot serve); then moves to the least-used account, preferring +accounts still under their own threshold". + +R2-N1 lineage — rationale CORRECTED, decision unchanged. The lineage pick precedes strategy selection and gives a +child with no binding the account its parent (or compatible sibling) is serving from now, for the warm family prefix. +Once placed, the child's binding is independent (a later parent move does not drag it). Kept as-is because it is a +strategy-agnostic cache-family hint, not a round-robin placement; documented as an exception ("a child of a live +conversation starts on its parent's account"), with a regression test: parent bound to an over-threshold account, an +under-threshold alternative exists -> the child still starts on the parent's account (boundary pin). + +R2-N2 idle-window — idle-window steering (codexPool.startIdleWindows) precedes round-robin and already requires +hasCodexQuotaHeadroom; docs say "round-robin placements", not "all new placements". diff --git a/devlog/_plan/261102_ocx_update_orchestrated/010_plan.md b/devlog/_plan/261102_ocx_update_orchestrated/010_plan.md new file mode 100644 index 00000000000..5cefbb8c208 --- /dev/null +++ b/devlog/_plan/261102_ocx_update_orchestrated/010_plan.md @@ -0,0 +1,323 @@ +# 010 — Orchestrated ocx update (contract C1) — diff-level plan + +Lane L1, branch feat/ocx-update-orchestrated, base origin/dev affd8403a. Class C4 (public CLI +output contract + update/install mutation path). Consumer: GOAT L3 (adopted-member update). + +## Contract (agreed with L3, cc L2, 2026-11-02) + +- `ocx update --plan --json [--tag latest|preview | --version X.Y.Z]` read-only. stdout is one JSON + object, exit 0 even when the plan refuses (usage errors exit 64; --tag with --version is 64). + {schema:"ocx.update.plan/1", currentVersion, targetVersion|null, installer: + "npm"|"pnpm"|"bun"|"mise"|"desktop-app"|"source"|"unknown", runtimeOwner: + "service"|"desktop-app"|"unmanaged"|"none"|"unknown", servingPath|null, cliPath, canApply, + reason?, restartRequired}. +- reason codes (first match wins, in this order): desktop-app-owned, source-checkout, mise-managed, + installer-unknown, serving-install-unknown, cli-not-serving-install, runtime-ownership-refused, + target-unresolved, downgrade-refused, up-to-date. canApply=true only with no reason. +- `ocx update --yes --json [...]` recomputes the plan, then applies. stdout is one JSON object + {schema:"ocx.update.result/1", applied, fromVersion, toVersion|null, installer, restarted, healthy, + rolledBack, error?}; progress goes to stderr. exit 0 = applied or up-to-date (applied=false), + 10 = refused (plan reason, nothing touched), 11 = failed with the previous version verified in + place (rollback or refusal before mutation), 12 = failed with state not verified, 64 = usage. +- `ocx capabilities --json` gains top-level `contracts: string[]` on every output shape (full, + --route, --mutating-only, unmatched route). `ocx capabilities --contracts --json` prints only + {"schemaVersion":1,"contracts":[...]} (output is small enough for GOAT's 256 KiB / SSH budget); + --contracts with --route/--mutating-only exits 64. List lives in + src/cli/capability-contracts.ts CAPABILITY_CONTRACTS (L2 appends "sync.home-fanout/1"). +- desktop-app: the Tauri updater's check/install commands require the update page window + (desktop/src-tauri/src/lib.rs update_check/update_install → window::require_update_page) and the + tray menu; there is no external trigger, so desktop-app installs plan canApply=false + reason "desktop-app-owned" and the CLI never edits app-owned files. + +## Serving-install identity (core rule) + +Decide against the install that serves the live runtime of the current home: +1. Live runtime = runtime-port.json {pid,port} whose /healthz answers service "opencodex" with the + same pid (bounded timeout). No record / dead → runtimeOwner "none", subject is the CLI install. +2. Serving command = argv of that pid (POSIX: ps -ww -o command= / Linux /proc//cmdline; + Windows: Win32_Process CommandLine through the existing bounded reader, or null). Resolve its + install root: compiled exe → exe path; bun + /src/cli/index.ts → ; node /bin/ocx.mjs + → . Cross-check with serving-runtimes.json (src/config/serving-runtimes.ts) record whose + command key matches and whose version equals healthz version. Unresolvable → servingPath null + → reason serving-install-unknown (fail closed). +3. cliPath = realpath of this CLI's package root (or standalone exe). servingPath ≠ cliPath → + cli-not-serving-install (lidge: PATH npm 2.50.0 vs serving 2.83.0). Nothing is touched. +4. runtimeOwner: desktop supervision (inspectDesktopSupervision) or recorded desktop owner → + desktop-app; service installed and recorded owner is this CLI → service; else unmanaged; + read failures → unknown. planUpdateRuntimeHandling(...).mayReplacePackage=false or ownership + unknown → runtime-ownership-refused. +5. installer: detectInstallOwnership(); standalone → desktop-app when the exe lives in the desktop + bundle/home or desktop owns the runtime, else unknown. +6. target: --version validated as strict semver and confirmed published (registry view of that exact + version through the installer's trusted invocation) else latestVersion(tag). Unresolved → + target-unresolved. target < current → downgrade-refused; equal → up-to-date. +7. restartRequired = a live runtime served by this install exists (the update stops/restarts it). + +## Apply lanes (reuse, no new mutation code) + +- npm/pnpm (node_modules, non-bun-global): bin/ocx.mjs must keep the package's bundled Bun idle + during replacement (Windows file locks), so the Node launcher drives apply: spawn Bun child + `update --plan --json ` (capture), refuse/up-to-date → result; else spawn Node child of the + existing lane `node bin/ocx.mjs update --tag T | --version X` with stdout→stderr, then readback. + `--plan` (and apply for other installers) skips the launcher's mise/npm/pnpm intercepts and falls + through to the Bun CLI. +- bun global: Bun handler spawns the existing runUpdate lane as a child (selfLaunchArgv) with + stdout→stderr, then readback. +- Version pin: runUpdate and runPackageManagerSelfUpdate accept `--version X` (install + PKG@X instead of PKG@tag, integrity pre-flight for X, already-current check against X). +- Readback (shared .mjs, usable from Node and Bun): installed package.json version at the install + root; runtime probe (runtime-port + /healthz pid/version) with bounded probation when + restartRequired. applied = installed == target; restarted = new live pid ≠ prior pid; + healthy = restartRequired ? live && version == target : installed == target. Child failure with + installed == from (and prior runtime live again when it was live) → exit 11 rolledBack=true; anything + else → 12. + +## Files + +- new src/update/orchestrated-contract.mjs/.d.mts: schemas, exit codes, argv parser, result builder, + readback helpers (Node+Bun safe, no TS imports). +- new src/update/orchestrated.ts: planOrchestratedUpdate(request, deps) with injectable deps; + runOrchestratedUpdate(argv) for plan + bun-lane apply. +- src/update/serving-identity (inside orchestrated.ts or own file): process argv reader + root resolver. +- src/update/index.ts (runUpdate pin), bin/ocx.mjs (intercept order, pin, npm/pnpm apply driver, help). +- src/cli/dispatch.ts update branch; src/cli/registry.ts usage; src/cli/capability-contracts.ts; + src/cli/capabilities-command.ts (+ capability entry for update flags if the registry requires it). +- skills/ocx surface regenerated (bun run skill:surface); structure doc owning src/update + manifest; + docs-site reference/cli/lifecycle.md section (English). +- tests: tests/update/update-orchestrated-plan.test.ts (decision matrix incl. lidge mismatch, + desktop-app, source, mise, unknown, serving unknown, ownership refused, up-to-date, downgrade, pin), + tests/update/update-orchestrated-apply.test.ts (exit 0/10/11/12 classification, stdout = 1 JSON, + fake child runner + temp home), launcher routing test (plan never runs npm self-update; fake npm + on PATH in temp home), tests/cli capabilities contracts/--contracts; real subprocess + `bun src/cli/index.ts update --plan --json` in a temp OPENCODEX_HOME. Layout registrations in + scripts/test-layout + tests/fixtures/test-layout-expected*.json. + +## Out of scope +desktop/ Rust, sync fanout (L2), GOAT (L3), releases. No real home, service, desktop app restart. + +## Verification +bun run typecheck; focused new/changed tests; bun run test:changed; bun run structure:check; +bun run skill:surface:check; bun run privacy:scan; bun run lint:gui not needed (no gui/). +PR to dev, exact-head CI per job, fresh terra xhigh review PASS, squash merge --match-head-commit. + + +## Audit r1 folds (terra xhigh FAIL → revised) + +A1 Passive entry. bin/ocx.mjs recognizes orchestrated argv (`update` with --plan/--yes+--json, any + malformed variant of them, and `capabilities`) BEFORE the boot-restore probe (bin/ocx.mjs:1299) and + resolves Bun with allowInstall:false; src/cli/root.ts skips the Codex shim auto-repair (root.ts:156) + for the same argv. Missing Bun → plan JSON reason "plan-unavailable" (exit 0) / apply exit 10. + Tests: recoverable backup untouched, placeholder Bun not installed, eligible shim repair not run. +A2 Identity bound to mutation. The apply child gets internal flags + --orchestrated-expect + and --orchestrated-result . Both legacy lanes re-run the serving-identity check inside their + existing mutation lease immediately before stop and again before replacement (Bun lane: + withUpdateOwnershipLease in runUpdate; Node lane: acquireOwnershipMutationLease in + runPackageManagerSelfUpdate). Change before stop → write {phase:"refused-before-mutation"} and exit + → parent exit 10. Change after stop → existing recoverStoppedRuntime, outcome "failed" → 12. + Deterministic tests: takeover between plan and stop, PID reuse (same pid, different process start / + command), different serving root. +A3 Runtime presence is tri-state via existing liveness evidence (proxy-liveness / probeProxyLiveness): + absent = no valid record AND configured endpoint proven dead; live = record pid == /healthz pid on the + record's hostname:port; anything else (unreadable record, timeout, pid mismatch, pidless/legacy health, + live configured endpoint without matching record) = unknown → reason serving-install-unknown. +A4 Exact pin. The apply child always receives --version (never --tag) in npm, pnpm + and Bun lanes; each lane keeps its integrity pre-flight for that exact version. Tests: tag moves + between plan and apply → installs planned version; pin reaches npm/pnpm/bun argv. +A5 Outcome evidence comes from the installers, not readback alone. Lanes write the --orchestrated-result + file at existing decision points: npm transactionalNpmUpdate(tx.phase/rolledBack), pnpm + runPnpmGlobalUpdate({ok,path,activePath,rolledBack}), Bun lane install status. Absent/garbled file → + 12. rolledBack=true only from installer-verified rollback (+ runtime restored when it was live) → 11. + Pre-mutation refusal → 10 with rolledBack=false. Post-success runtime readback is bound to the same home + and the installer-reported active root (pnpm may switch activePath): healthz pid == record pid, + serving identity root == active root, version == target. exit 0 requires applied && healthy; + applied && !healthy → 12 error "runtime-unhealthy". +A6 Identity matching without guessing. Live process evidence: Linux /proc//cmdline split on NUL + (preserve boundaries); macOS executable via existing processIdentity (comm=) plus `ps -ww -o command=` + string; Windows Win32_Process ExecutablePath + CommandLine via the existing bounded reader. A census + record (serving-runtimes.json, relaunch prefix = record.command, live command = prefix + "start …") + matches only if realpath(executable) == realpath(command[0]) and the live args begin with the record's + remaining prefix (Linux: element-wise; macOS/Windows: the prefix rendered unquoted and quoted must be a + whole-token prefix of the string). Exactly one matching record with version == healthz version is + required; zero or several → serving-install-unknown. servingRoot derives from the matched record + (exe for standalone; of /src/cli/index.ts). Tests: spaces, symlinks, Windows quoting, + standalone, ambiguous duplicates. +A7 One stdout owner. Node launcher driver (npm/pnpm apply) and the Bun handler (plan, other apply) own + stdout from entry to exit: progress → stderr, every failure path (Bun missing, plan-child non-zero / + malformed / >64 KiB, spawn failure, signal, uncaught error) prints exactly one JSON document. Before + mutation → plan "plan-unavailable" (exit 0) or result exit 10; after the update child started → 12. + Tests run the real launcher subprocess against a temp npm-shaped package and fake npm/pnpm on PATH, + plus desktop standalone (installer desktop-app). version-skew notice already skips --json. +Also: update all structure owners touched (launcher: codex-cli-update.md, ops/desktop-supervision.md; +CLI and update owners per structure/INDEX.md); PR gets ci:full (subprocess/read-as-data coverage); +core–Lab boundary unaffected (lazy imports only). New additive reason code "plan-unavailable" sent to L3. + + +## Audit r2 folds (supersede the matching A-items above where they conflict) + +B1 (A1) Capability discovery reflects the CLI that handles update. `update` is already excluded from + Desktop handoff (src/lib/desktop-cli-handoff.mjs:9); add `capabilities` invoked with --contracts to the + same exclusion so a package launcher answers for itself and never hands off to an older bundled CLI. + The desktop terminal shim (~/.opencodex-desktop/bin/ocx) runs the bundled CLI directly, which then + answers for itself (and plans desktop-app). root.ts skips shim auto-repair for `capabilities`. + Tests: handoff record present + `capabilities --contracts --json` stays local; update stays local. +B2 (A2) Pre-mutation check sits at the first mutation choke point, BEFORE tray handoff + (src/update/index.ts:524 region, bin/ocx.mjs:759 region): re-verify home, cliRoot, servingRoot and + live runtime pid against --orchestrated-expect; on mismatch write outcome phase "refused" and exit + without touching tray/runtime/package. The second check is post-stop, before replacement: home and + cliRoot unchanged and runtime liveness proven dead (the existing replacementLiveness === "dead" + gate); the original pid is expected to be gone. +B3 (A3) A valid record whose pid is dead counts as unknown (serving-install-unknown) even if the endpoint + is dead. Conservative by design; documented with remedy "run ocx start or ocx stop to settle state". +B4 (A5/A7) Outcome by phase, with independent verification. The child writes --orchestrated-result + atomically: {phase:"preflight"} at entry (write failure → exit before mutation); {phase:"mutating"} + immediately before the first tray/runtime/package mutation (write failure → abort before it); + final {phase:"installed", activeRoot} or {phase:"failed", installerRolledBack:boolean}. + Parent precedence (also on catchable signals SIGINT/SIGTERM/SIGHUP; SIGKILL has no guarantee): + - plan refused → 10. + - outcome missing/unreadable → 12 (cannot prove no mutation). + - last phase preflight or refused, child non-zero → 10 (no mutation), error carries the cause. + - phase mutating/failed → independent verification of the install root the plan named (pnpm: the + owner-resolved active path): package.json version == fromVersion AND bounded `/bin/ocx.mjs + --version` (standalone: exe --version) == fromVersion AND, when a runtime was live before, a live + runtime bound to the same home/root (B5) → 11; rolledBack = installerRolledBack && verified; + otherwise 12. + - phase installed, child exit 0 → verify activeRoot version + launcher probe == target; runtime readback + (B5) when restartRequired → 0 applied=true healthy=true; any verification miss → 12 (applied reflects + the install verification, error "runtime-unhealthy" or "install-unverified"). +B5 (A6) Serving identity is self-reported, argument-preserving. The runtime writes + command: currentServingCommand() (absolute relaunch prefix, src/config/serving-runtimes.ts:50) into + runtime-port.json next to pid/port (validators ignore unknown fields, so old readers are unaffected). + Live runtime = record.pid == /healthz pid on the record endpoint; servingRoot derives from + record.command (standalone exe → exe; [bun, /src/cli/index.ts] → ). No ps/CommandLine + parsing is used to PROVE identity. Without record.command (older runtime): if the live process's + executable (processIdentity comm= on macOS, /proc exe on Linux, Win32 ExecutablePath) realpath differs + from this CLI's own runtime executable → cli-not-serving-install (refusal is the safe direction; a pid + race can only cause a false refusal); otherwise serving-install-unknown. Census matching is dropped. + lidge (2.83.0 runtime, no record.command, different bun) → cli-not-serving-install or + serving-install-unknown; both refuse without touching the npm install. +B6 (A7) Single stdout owner: orchestrated update/capabilities never take Desktop handoff (B1), so the + package launcher (npm/pnpm apply driver) or the Bun handler owns stdout from entry to exit. + + +## Audit r3 folds (supersede B4/B5 where they conflict) + +C1 Attested serving identity. Live runtime = the record listener proves possession of the record's + attestationSecret via the existing proveLiveProxyOwnedByHome / attestFencedIdentity path + (src/server/proxy-liveness.ts:204) — only "proven" counts; "refuted"/"indeterminate" → unknown. + The record is read before and after the proof and must be byte-identical (pid, port, hostname, secret, + command); servingRoot derives from that record's command. The same attested check is re-run under + the mutation lease before tray handoff. The Node lane cannot run the TS proof in-process, so it calls a + passive Bun probe subprocess (hidden `__update-orchestrated-identity`, same pattern as + `__update-home-probe`/service-home-probe-entry.ts, bin/ocx.mjs:150) that exits before any mutation. + Tests: stale record + reused pid (proof refuted), record replaced during the probe, no secret. +C2 No launcher execution for verification. Version/tree verification is passive file reads in-process + (readPackageManifestVersionAt / packageManifestPathIn, src/lib/package-tree-integrity.ts:87/129); no + `--version` subprocess, no Desktop handoff, no backup restore, no Bun install. +C3 Active-tree verification uses installer-specific evidence before exit 11 or 0: npm — required package + files present (package.json, bin/ocx.mjs, src/cli/index.ts, bundled bun dir) + no leftover transactional + backup sibling for that root (read-only check of the transactional-install naming); pnpm — read-only + owner re-resolution (resolvePnpmGlobalOwner / readPnpmGlobalPackage) confirms the active group path, + its manifest version and the launcher shim target; bun global — required files + manifest. Any miss → + 12. Test: damaged tree that keeps package.json version → 12. +C4 Signals: on SIGINT/SIGTERM/SIGHUP the parent forwards the signal to the child, waits for confirmed child + exit (bounded 60 s), then reads the final atomic outcome; child still running or outcome uncertain → 12. + Deterministic test: signal delivered at the preflight→mutating transition. +C5 Exit classification (final): + 0 — applied and verified (installed + tree + runtime when restartRequired), or plan reason "up-to-date". + 10 — a plan refusal: the parent's plan reason (any reason except up-to-date), or the child's + lease-time identity re-check refusing (phase "refused") — the plan recomputed at the boundary. + 11 — the update failed and the previous version is verified active (C3) with the runtime restored when it + was live; covers preflight failures (child exited before "mutating") and installer rollbacks. + rolledBack=true only when the installer reported a rollback AND C3 verification passed. + 12 — everything else: outcome missing/garbled, verification miss, unconfirmed child termination, + installed-but-runtime-unhealthy. + 64 — usage. + + +## Audit r4 residuals (NEAR-PASS) — folded as implementation requirements +D1 npm success retains a backup sibling by design (transactional-install.mjs:535): a retained backup is + not failure; verify the active tree itself. +D2 Tree verification reuses/matches the installer verifier (transactional-install.mjs:107: Bun executable + present and complete, dependencies, launcher, source) — tests: truncated/missing Bun, missing dependency, + missing source file → 12. +D3 pnpm rolledBack flag can mean "previous package simply remained active" (pnpm-global-install.mjs:544): + result.rolledBack=true only for an actual rollback action; unchanged-active is rolledBack=false (exit 11 + when verified). + + +## L3 additive requests (accepted 2026-11-02) +E1 plan JSON adds "planToken": base64url sha256 (43 chars, matches ^[A-Za-z0-9_-]{16,128}$) over a canonical + JSON of {currentVersion, targetVersion, installer, cliRoot, servingRoot, runtimeOwner, runtime:{pid, port, + hostname, command} | null} — never the attestation secret. Apply accepts --expect-plan ; it + recomputes its plan and, if the token differs, exits 10 before any mutation (error "plan-changed"). + The child's lease-time identity re-check compares against the same bound fields. +E2 plan JSON adds "updateInFlight": boolean. true when the update ownership/mutation lease is held by a live + process, or the home-scoped orchestrated marker (/update-orchestrated.json {pid, phase, startedAt}, + written by the apply child at preflight/mutating and cleared/finalized at the end) shows phase + preflight|mutating with a live pid; true when this cannot be determined (fail closed); false only on + positive evidence. Read-only probe (no lease acquisition that could block a real update). + + +## L3 additive request E3 (accepted 2026-11-02): deadline fencing +E3 apply accepts --not-after (positive safe integer; invalid → 64). At the B2 choke point (before the first + tray/runtime/package mutation) and immediately before writing the "mutating" marker, now > notAfter → exit 10 + error "deadline-passed", nothing touched. Contract constant ORCHESTRATED_MUTATION_BOUND_MS = 900000 (15 min); + plan JSON adds "mutationBoundMs": 900000. A child that started mutating arms a watchdog at notAfter + bound + (or start + bound without --not-after): on expiry it records outcome/marker phase "overrun" (→ parent 12) but + does NOT kill an in-progress package transaction (a mid-swap abort is the unsafe direction); while that child + lives, updateInFlight stays true, so updateInFlight=false remains the authoritative "no further mutation" fence. + + +## L3 requests E4/E5 (accepted 2026-11-02) +E4 Deadline↔visibility ordering (contract wording): the apply child (1) acquires the update ownership lease, + (2) publishes marker phase "mutating" with its pid, THEN (3) performs the final --not-after, --expect-plan and + attested identity checks; on failure it rewrites the marker to "refused", releases the lease and exits 10. + Thus at the last deadline check updateInFlight is already observably true, and lease + marker stay held + until no further mutation can occur (final outcome written before the lease is released). +E5 sync↔update exclusion (L1 implements; L2 rebases onto it): `ocx sync` (all variants incl. --local-only and the + Child-side --expect-link run) first runs the read-only update-in-flight probe (same as plan.updateInFlight); + in flight or undeterminable → no changes, stderr code "update-in-flight", exit 7. Placed at the sync command + entry before any local sync, expectation check or fan-out. + + +## L3 request E6 (accepted 2026-11-02): atomic sync↔update exclusion (supersedes E5's probe-only guard) +E6 One dedicated cross-process mutex shared by `ocx sync` and orchestrated apply: same primitive as the ownership + mutation lease (src/service/ownership-mutation-lease.mjs, dead-owner recovery, non-blocking try-acquire) but a + separate lease file in the home, recording holder kind (sync|update) and pid — kept separate from the ownership + lease so sync's own start/stop/restart paths cannot deadlock against it. + - `ocx sync` (every variant) try-acquires it before its first mutation and holds it to the end; held by an update + or undeterminable → no changes, stderr "update-in-flight", exit 7. + - Apply child step ① try-acquires it (then the ownership lease, then marker "mutating", then E4 checks); held by + sync → exit 10 error "sync-in-progress", nothing touched; held by another update → exit 10 "update-in-flight". + Held until the final outcome is written. + - updateInFlight = true iff an update holds the mutex or the update ownership lease, or the marker shows + preflight|mutating with a live pid, or undeterminable. Sync holding alone → false. + - Each machine has its own mutex; a Home fan-out's Child-side `ocx sync` takes the Child's mutex. + Tests: sync holds (paused) → apply 10 sync-in-progress untouched; apply holds → sync 7; dead holder recovered. + + +## Implementation resolutions (2026-11-02, after slice 3) +F1 The existing lanes release the ownership lease around service-manager restarts (#5760; src/update/index.ts:626, + bin/ocx.mjs:1043) — keep that. E4's "held until no further mutation" is carried by the dedicated sync/update mutex + (E6) and the marker, which the apply child holds from step ① until its final outcome is written, across the whole + lane including service restart/recovery. `ocx start` never takes that mutex, so no deadlock. +F2 The synchronous npm transaction blocks the child's event loop, so the overrun watchdog runs in the PARENT driver: + at notAfter+bound (or start+bound) with the child still alive, the parent emits result exit 12 error "overrun" and + exits without killing the child; the child's marker stays preflight|mutating with a live pid, so updateInFlight + stays true until the child finishes (supersedes E3's "child records overrun"). + +## Review r3 resolutions (2026-11-02) +G1 Admission refuses when plan.updateInFlight is true (exit 10 "update-in-flight"); the child, after acquiring the mutex, + re-reads the marker and proceeds only if it is positively free (finalized or absent); otherwise refused, marker untouched. +G2 Legacy `ocx update` (both lanes, interactive and package-only workers) also takes the sync/update mutex as "update" for + its full mutation lifetime and publishes the marker; held by sync → refuse before any mutation with a clear message. +G3 Fail-closed fence by time bound: publish the mutating marker with fenceUntil = startedAt + 900000 before launching an + installer. A dead worker, timeout, killed group, or unconfirmed exit retains the fence; live or uninspectable recorded + installers remain active independently. A normally exited installer with its POSIX process group confirmed gone or + Windows Job Object confirmed empty clears the fence on finalization. A POSIX descendant that escapes the group can + outlive a normally exiting installer and mutate after the fence clears; this residual is accepted. Windows uses the + Job Object supervisor. A timed-out escaped POSIX descendant can also outlive the 15-minute bound. + +## Review r8 resolution +The sync launcher atomically publishes the spawned child PID in its lease. Reclamation requires both holder and delegate to be dead; a new Bun child verifies its own PID before mutation. An older Desktop CLI cannot verify it, so launcher SIGKILL between spawn and delegate publication leaves a residual window in which that child can outlive the stale lease. diff --git a/devlog/_plan/261102_request_owned_affinity/000_plan.md b/devlog/_plan/261102_request_owned_affinity/000_plan.md new file mode 100644 index 00000000000..63eea7a8d92 --- /dev/null +++ b/devlog/_plan/261102_request_owned_affinity/000_plan.md @@ -0,0 +1,43 @@ +# 261102 — Request-owned bearer conversation affinity (#8080) + +**Reader summary.** When Codex CLI signs in with ChatGPT and talks to a Pool-mode proxy, its own +bearer makes `main` one more round-robin candidate (#5019), but the request had no affinity key, so +every turn re-ran the strategy and a conversation hopped between main and the stored accounts. The +request log labelled each of those picks `new_bind/healthy` although nothing was stored. This unit +makes every affinity label describe what selection actually stored, and adds the opt-in +`codexPool.requestOwnedAffinity` (default off) that keeps one account per conversation for a +request-owned bearer. Research: `010_research.md`. Contract: `structure/providers/codex-request-owned-affinity.md`. + +## Scope + +- In: `src/codex/request-owned-affinity.ts` (key, label check, issuer helpers), + `src/codex/request-owned-main-pin.ts` (byte-for-byte move), wiring in `src/codex/auth-context.ts`, + request previews (`src/server/responses/request-prepare.ts`), issuer and retry/compact fallbacks, + request log and usage normalization, config field, manual-selection issuer retention. +- Out: affinity persistence (#8091), round-robin eligibility (#8092), Claude identity lanes. + +## Decisions + +1. Labels are checked when selection returns: `new_bind`/`rebound` stay only if the key's entry names + the selected account; otherwise `unbound` (`request_owned`, `no_conversation`, or the original + reason) or `cleared`. `unbound` is not a spend move reason. +2. The opt-in key is an HMAC under a process-random secret over the exact Authorization value and the + conversation key. Account-id claims are not used as principal. +3. Final auth and both previews (first and recovery, per candidate model) share one derivation; fixed + selectors and Reserve get no key; request-owned traffic never records lineage. +4. A separate bearer-scoped conversation-state key (never passed to routing) carries issuer records + for request-owned Pool and caller-owned main contexts, with or without the opt-in. +5. Manual account selection keeps issuer records while clearing routing bindings. +6. A refusal on a caller-owned main binding releases that binding without touching shared main health. + +## Acceptance + +Regression tests in `tests/codex-integration/codex-request-owned-affinity.test.ts`, +`tests/codex-integration/reserve-auth-context.test.ts`, `tests/responses/compact-transient-alternate.test.ts`, +`tests/responses/responses-alternate-main-cancellation.test.ts` and +`tests/responses/responses-preview-main-read-fence.test.ts` fail on the pre-change code and pass after it. + +## Outcome + +PR #8096. Plan audited over five rounds; implementation reviewed by a dedicated security review +and an independent code review before publication. diff --git a/devlog/_plan/261102_request_owned_affinity/010_research.md b/devlog/_plan/261102_request_owned_affinity/010_research.md new file mode 100644 index 00000000000..c03e9bb25b1 --- /dev/null +++ b/devlog/_plan/261102_request_owned_affinity/010_research.md @@ -0,0 +1,20 @@ +# 010 — Research (#8080) + +Source: Terra research task, 2026-11-02, read-only, at 6f1d3e65c. + +- Ownership flag: `codexRouteCredentialOwnership` (src/server/responses/core-auth.ts) marks a forwardable + caller bearer request-scoped. +- `poolStateEligible` (src/codex/auth-context.ts) rejects request-scoped credentials, so `affinityKey` and + lineage are undefined and `resolveCodexAccountForThreadDetailed` receives a null key. +- Since #5019/#5024 an unpinned caller bearer makes main an ordinary round-robin candidate; a stored + account selection materializes that stored credential. Intentional and documented in + structure/providers/openai-tiers.md. +- Round-robin commits its pick with a null key but binds only when `commitAffinity && threadId` + (src/codex/routing/selection.ts). With main + one stored account and sticky limit 1 the ring + alternates; with two stored accounts it cycles main, A, B. +- Every unbound success returns `affinityAfterRelease(null, undefined)` = `new_bind/healthy`. +- Log path: `noteCodexSelectionAffinity` (pool/main-pool only) → request log → `persistedAffinityFields` + → usage.jsonl via `KNOWN_AFFINITY_MOVES/REASONS` (src/usage/log.ts). No exhaustive Record over the + unions; GUI does not render these values. +- Options weighed: opt-in process-local namespace (chosen); always serve main (contradicts #5019); + raise sticky limit (shared counter, not affinity); omit label only (honest but uninformative). diff --git a/devlog/_plan/261102_sync_home_fanout/010_plan.md b/devlog/_plan/261102_sync_home_fanout/010_plan.md new file mode 100644 index 00000000000..058699ee01f --- /dev/null +++ b/devlog/_plan/261102_sync_home_fanout/010_plan.md @@ -0,0 +1,303 @@ +# 10 — Home `ocx sync` fans out to linked Children (C2, `sync.home-fanout/1`) + +Class C4 (public CLI contract: new flags, a new JSON schema, a new exit code, a new capability +field). Single work-phase `wp1`. Sibling lanes: L1 `ocx update` orchestration (shares the capability +contracts list) and L3, the GOAT consumer. + +Revision 8 folds the round-7 audit: each candidate's `--version` runs once, in the background, +under a 10 s kill watchdog and a size bound, and that one run both selects and versions the +candidate; Windows reads through a new bounded C# helper; the capture file is removed before `exec`; +failed candidates fall through as today. It also reserves exit 7 for L1's sync/update mutex. +Revision 7 folded the round-6 audit: the POSIX version capture keeps the real exit status and is +size-limited with `ulimit -f` instead of a `head` pipeline. +Revision 6 folded the round-5 audit: the capability probe is removed (it could run shim repair +before the link check and buffered unbounded output on the Child). Children now identify themselves +by their own sync output, and success needs positive evidence in both forms. The wrapper's version +capture is bounded. +Revision 5 folded the round-4 audit (JSON support is probed from the selected executable, not +inferred from its version; best-effort store inspection on the thrown-Home path). +Revision 4 folded the round-3 audit (version marker and fail-closed modern output, exit 0 required +for success, thrown Home sync in human mode, strict SemVer bound, Windows execution tests). +Revision 3 folded the round-2 audit (single remote operation, machine-readable freshness, catalog +gate, bounded status deadline, termination-unconfirmed, store failure, restart wording). +Revision 2 folded the round-1 audit (terra xhigh, FAIL) and the origin's decision on its blocker: +`--restart-children` is removed (option A). Home fan-out never restarts a Child's Codex; restart +authority stays with GOAT, which knows real running turns, or with an operator running +`ocx sync --restart-codex` on the Child. + +## Problem + +To sync a Remote Link Home and its Children, GOAT or an operator has to SSH to every Child and run +`ocx sync --expect-link ` there. An operator who types `ocx sync` on the Home refreshes only +the Home, so Children keep a stale catalog until someone syncs them one by one. + +## Contract + +### When propagation runs + +- Only on the local branch of the `sync` runner (the machine is not a connected client) and only + without `--expect-link`/`--expect-hub-key`. A connected client never propagates. The pinned form is + the call a Home makes into a Child, so a chain cannot recurse. +- On by default; `--local-only` turns it off (accepted and a no-op on every other path). +- Only when the Home sync committed a current catalog: exit 0, `synced.status` is `applied` or + `catalog-only`, `synced.refreshOutcome === "committed"`, and `projectLocalSyncResult(synced).catalog.converged` + (catalog exists, not refused, no safety warning). An exit-0 run without that evidence (a refused or + thrown catalog refresh, `refreshOutcome` absent) skips every Child with `home-catalog-not-current` and + keeps the Home exit. The implementation must confirm with a test that an unchanged catalog reports + `committed`; if it does not, the gate uses the evidence the unchanged path does report, never weaker. A Child's + `/v1/catalog` fetch serializes the Home's persisted Codex catalog + (`src/server/index/serve-options.ts` `/v1/catalog` -> `src/server/catalog-download.ts`), so after a + failed or skipped Home sync a Child could only receive whatever the failed run left behind. Every + Child is then `skipped` with `home-sync-failed` or `home-sync-skipped`, and the Home exit code is + kept. A Home sync that throws is caught by the runner. JSON mode prints the document (`home.state + failed`, `home.exit` 1, every hub-initiated Child `skipped` `home-sync-failed` when the link store is + readable; an unreadable store instead yields `fanout.state` `failed`, reason `link-store-unreadable`, + and no children) and one sanitized + `Sync failed: ...` stderr line. Human mode prints + one stderr line, `Children were not synced because the Home sync failed.`, when a best-effort + store read (any error swallowed, so it can never replace the original error) finds a link, then + rethrows the original error unchanged so today's failure output and exit stay. +- Never requests a Codex app or app-server restart on a Child, and never restarts the Home proxy: + the command sent to a Child carries no restart flag. The Child's own pinned sync keeps its existing + behavior of restarting its OpenCodex client runtime after it applies changed Home settings + (`src/cli/link-apply-restart.ts`), which can interrupt a request relayed at that moment. Help and + docs state both and point to GOAT or `ocx sync --restart-codex` on the Child for a Codex restart. + +### Which links + +- Records come from `/link/links.json` (`readLinkStore`). `client-initiated` links are + `skipped` (`client-initiated-link`): the Home has no SSH path or pinned host key for them. +- Reachability comes from the Home runtime's `GET /api/link/status`, read once by + `readHomeLinkStatus` under one absolute 5 s deadline that covers live-runtime discovery, the + request headers and the body read (a `Promise.race` against a typed `LinkStatusTimeout` plus an + `AbortController` passed to fetch; discovery that ignores the deadline is abandoned, and the CLI + exits through `process.exit`). It uses the same discovery and admin headers as `runtimeRequest`. The route + admits the admin token on trusted loopback (`auth(ctx, "either")`). Outcomes, applied to every + hub-initiated Child: no live Home runtime -> `skipped` `home-runtime-not-running`; 401/403 -> + `failed` `home-link-status-unauthorized`; abort/timeout -> `failed` `home-link-status-timeout`; any + other error -> `failed` `home-link-status-unavailable`; a DTO that fails validation -> `failed` + `home-link-status-invalid`. Per link: absent from the DTO -> `skipped` `link-not-in-runtime`; state + not `connected` -> `skipped` `tunnel-` (state from the closed `LinkWireState` set). + +### Per Child + +Each Child runs in its own worker with one deadline (180 s from the moment the worker starts) +covering every ssh call. All commands use `buildExecArgv` with the link known_hosts +(`StrictHostKeyChecking=yes`) and `remoteOcxArgv(args, platform)`. + +1. Platform: `record.remotePlatform`, or when absent `requireRemotePlatformFramed` through the owned + runner with each call's timeout clamped to the remaining deadline. A successful Windows probe + identifies Windows when any trimmed stdout line is exactly `Windows_NT`. Otherwise a POSIX probe + prints `ocx-platform:`; exactly one framed line is required. Login-shell output is ignored; + exit 255 is a transport failure and ambiguous or failed probes -> `failed` `platform-probe-failed`. +2. One remote operation, `remotePinnedSyncArgv(linkId, platform)` (NEW in `src/link/ssh-argv.ts` for + POSIX and `src/link/remote-windows.ts` for Windows), sharing the candidate list and order with + `REMOTE_OCX_SCRIPT` / `windowsOcxArgv`. For each candidate in order it runs that executable's + `--version` exactly once, and that single run both decides selection and supplies the version: + - POSIX: `( ulimit -c 0; ulimit -f 1; exec "$c" --version ) >"$tmp" 2>/dev/null &`, a watchdog + `( sleep 10; kill -9 "$vp" ) &`, `wait "$vp"` for the real status, then the watchdog is killed and + reaped; the whole group's stderr goes to `/dev/null`. After exit, the capture file itself is + measured before parsing; a capture over 256 bytes is skipped even if the process exited 0. + Checked locally with `sh`: a writer that ignores SIGPIPE and SIGXFSZ and swallows its write + errors is killed at the watchdog (status 137, file at 512 bytes, its pid gone afterwards); a + version printing `opencodex 2.93.0` and exiting 17 returns 17; a normal one returns 0. + - Windows: a new `[OcxJob]::V(path)` in `OCX_JOB_SOURCE` starts the process with redirected + stdout and stderr, reads stdout in a loop into a 257-char buffer on a task, drains stderr on + another task discarding it, waits for the reading task and the exit together under one 10 s + deadline, kills and waits for the process on overflow or deadline, and returns the text only + when the process exited 0 with at most 256 characters. + - A candidate whose run exits nonzero, is killed by the watchdog or overflows is skipped and the + next candidate is tried, as today's `try_ocx` skips a failing one; it is never synced. No + qualifying candidate -> exit 127 as today. + - The first qualifying candidate is selected. Its output must parse as `opencodex ` or a + bare `` (the full `src/lib/strict-semver.ts` grammar: `MAJOR.MINOR.PATCH`, optional `-prerelease`, + optional `+build`; build metadata is accepted and ignored for precedence, as SemVer specifies, + and the marker carries the version string exactly as parsed); unparsable -> last stderr line `ocx-fanout:child-ocx-version-unknown`, exit 121. + A version that strict SemVer precedence orders below 2.93.0 (so `2.93.0-preview.*` is refused) + -> `ocx-fanout:child-ocx-lacks-expect-link`, exit 121. 2.93.0 is the first release with + `--expect-link` (959a07a5ea is in v2.93.0, not v2.92.0); checking first matters because an older + ocx ignores unknown flags and would run an unpinned sync. + - Otherwise it removes the capture file, clears the trap, writes exactly + `ocx-fanout:selected:` on stderr, then `ocx-fanout:stdout-begin` on stdout, and execs + ` sync --expect-link --json`. The trap removes the file on every refusal path. + - No `ocx` command other than `--version` runs on the Child before the pinned sync (platform + discovery may run its fixed OS probe first), so the pinned sync's "nothing changed on mismatch" + guarantee (shim repair deferred until after the identity check) is unchanged. + - Replacing the binary on disk between its version run and the exec is outside the threat model: + it needs write access to the Child's ocx install, which already controls the Child's OpenCodex. + The Windows script must stay within `POWERSHELL_ENCODED_MAX` (asserted by a test). +3. Classification, transport first (these apply whatever the output says): exit 255 -> `failed` `ssh-failed`; 127 -> `failed` + `child-ocx-not-found`; 126 (Windows containment) -> `failed` `child-ocx-not-contained`; 125 -> + `skipped` `child-platform-unsupported`; 121 with a known `ocx-fanout:` marker as the last stderr + line -> `skipped` with that code (121 without a marker -> `failed` `child-sync-failed`). Then the + sync result. Success needs exit 0 and positive evidence; a nonzero exit is never overridden by a + document. The Home requires exactly one stderr line matching `^ocx-fanout:selected:(.+)$` with a + strict SemVer version, and exactly one stdout line `ocx-fanout:stdout-begin`. Missing, duplicate, + or malformed framing -> `failed` `child-output-invalid` after the transport cases above. Login-shell + output before the markers is ignored; classification uses only stdout after the delimiter. For exit 0: + - that stdout, trimmed, starts with `{`: the Child claims the `--json` form (this release and later). + It must be exactly one valid `ocx.sync.fanout/1` document; `home.state "synced"` -> `synced`, + `home.state "stale"` -> `failed` `child-catalog-stale`; malformed JSON, an unknown schema, a + second document, an inconsistent document (any other state, or `home.exit` not 0) -> `failed` + `child-output-invalid`. + - otherwise the Child is a release from v2.93.0 up to the one before this change (it ignores + `--json`): stdout must contain the legacy success sentence `Remote Link Home catalog + synchronized.` -> `synced`, or the stale sentence `Home unavailable; retained and applied the + last-known-good remote catalog (stale).` -> `failed` `child-catalog-stale` (stale wins if both + appear); neither -> `failed` `child-output-invalid`. Both sentences are identical in v2.93.0, + v2.94.0, v2.95.0 and v2.96.0 (checked with `git show :src/cli/dispatch.ts`) and are exported + as constants that a test pins. + Exit 5 -> + `skipped` `child-link-mismatch:` when the final stderr line parses as + `{"phase":"child_link_mismatch","reason":R}` with R in the closed reason set, otherwise + `child-link-mismatch`; exit 7 -> `skipped` `child-updating` (reserved for L1's sync/update + mutex, `update-in-flight`; nothing changed on the Child); any other non-zero (including exit 1 after a fresh catalog when the apply + record or runtime restart failed) -> `failed` `child-sync-failed`. +4. Deadline -> `timed-out` `deadline-exceeded` with `exit: null`; when the process cannot be + confirmed gone after SIGKILL and its wait, the reason is `termination-unconfirmed` instead. Spawn failure -> `failed` + `ssh-spawn-failed`; output over the cap or undecodable -> `failed` `ssh-output`. A worker that + throws for any other reason -> `failed` `internal-error`. + +`reason` is always one of these fixed codes (null for `synced`). No ssh stderr or remote text +reaches the output. + +### Process ownership and isolation + +- A dedicated runner in `src/cli/sync-fanout-process.ts` spawns each ssh with `Bun.spawn` + (`stdin: "ignore"`, piped bounded stdout/stderr, `linkSshSpawnEnv()`). On deadline, output-limit or + decode failure it sends SIGTERM, waits up to 2 s for exit, then SIGKILL and waits up to 1 s more. + The worker returns only after that sequence, so the CLI's `process.exit` does not skip the + escalation. A `kill` that throws ESRCH counts as exited; any other signal error, or no exit within + the final wait, is reported as `termination-unconfirmed` and never claimed as gone. + Pipe readers are cancelled after exit plus a 250 ms grace, so a descendant holding an inherited + pipe cannot hold the worker. A grace-cancelled pipe is incomplete and fails as `ssh-output`. +- Concurrency cap 3. Workers catch every error. A Child's failure, hang or crash never stops another + active worker and never changes the Home result. A queued Child starts no later than + `ceil(position / 3)` waves of (180 s + 3 s kill grace); the whole run is bounded by + `ceil(n / 3) × 183 s` plus the 5 s status read. +- Propagation runs only in the CLI process. The Home server runs no propagation code. +- Killing the local ssh does not necessarily stop a remote `ocx sync` already running; it finishes + or fails on the Child by itself (documented). + +### Output and exit + +- `--json`: in JSON mode `console.log` is routed to stderr for the whole runner, and stdout carries + exactly one document on every path except usage errors: + `{schema:"ocx.sync.fanout/1", home:{state:"synced"|"stale"|"skipped"|"failed", exit}, fanout:{state:"ran"|"disabled"|"not-applicable"|"failed", reason}, children:[{linkId, alias, state, reason, exit}]}`. + `home.state` is `stale` when a connected sync applied the last-known-good catalog. `fanout` is + `disabled` under `--local-only`, `not-applicable` on connected, pinned and link-less runs, and + `failed` with `link-store-unreadable` when `links.json` cannot be read or parsed (Home ok -> exit 6). + `children` is empty on connected, pinned, `--local-only` and link-less runs. A pinned mismatch is + `home.state "failed"`, `exit 5`, with the existing stderr lines unchanged. +- Usage errors exit 2 with stderr only. New flags are validated in the root preflight + (`src/cli/root.ts`) before shim auto-restore and any other preflight side effect, alongside the + existing pinned-flag check. +- Exit 7 is reserved for L1's sync/update mutex (`update-in-flight`, nothing changed); the runner + keeps the Home's local sync as one step that ends before fan-out starts, so that mutex can cover + the Home's own mutation without being held for the fan-out. +- Exit: Home failure keeps its code (1, 5, 7, or `process.exitCode`); Home ok and every Child `synced` + or `skipped` -> 0; any Child `failed` or `timed-out`, or `fanout.state failed` -> **6** (partial). +- Human mode prints the existing Home lines, then one line per Child: + ` (): [ ()]`. An unreadable link store prints the fixed stderr line + `Children were not synced: the Remote Link store could not be read.` + +### Capabilities + +- `ocx capabilities --json` gains a top-level `contracts: string[]` (always present, unaffected by + `--route`/`--mutating-only`; schemaVersion stays 1) from `CAPABILITY_CONTRACTS` in + `src/cli/capability-contracts.ts`, containing `sync.home-fanout/1`. `ocx capabilities --contracts + --json` prints only `{"schemaVersion":1,"contracts":[...]}`; `--contracts` without `--json` prints + one contract per line; combined with `--route` or `--mutating-only` it exits 64. Agreed with L1 and + L3 (same file and constant name; the later merge adds one array entry). + +## Diff-level plan + +1. NEW `src/cli/capability-contracts.ts`: `export const CAPABILITY_CONTRACTS = ["sync.home-fanout/1"] as const;` + with no imports. +2. MODIFY `src/cli/capabilities-command.ts`: `--contracts` handling, 64 combinations, `contracts` on + every JSON document including the unmatched-route one, usage `[--contracts]`; capabilities-base + entry for `capabilities` gains the flag. +3. NEW `src/cli/sync-flags.ts`: `parseSyncFanoutFlags(args)` -> `{localOnly, json}` or a usage error + (repeated flag). Called from `root.ts` preflight and the runner. +4. NEW `src/cli/sync-command.ts`: the `sync` runner moved out of `dispatch.ts` with existing branches + unchanged, as `runSyncCommand(deps)`; JSON-mode stdout routing; Home result capture; fan-out call; + rendering; exit combination. `dispatch.ts` keeps a one-line delegate. Export + `STALE_REMOTE_CATALOG_MESSAGE` (link form) and use it in the existing print. +5. NEW `src/cli/sync-fanout.ts`: `runHomeFanout(deps)` with injected `readStore`, `readLinkStatus`, + `runChild`, `resolvePlatform`, `now`, `deadlineMs`, `concurrency`; `classifyVersionProbe`, + `classifySyncResult`, `parseOcxVersion`, `fanoutExitCode`, `renderFanoutJson`, `renderFanoutHuman`, + bounded pool, `SYNC_FANOUT_PARTIAL_EXIT = 6`. +6. NEW `src/cli/sync-fanout-process.ts`: the owned-process runner described above; it also + implements `SshRunner.run` (timeouts clamped to the remaining deadline) for `requireRemotePlatformFramed`. +6a. MODIFY `src/link/ssh-argv.ts` / `src/link/remote-windows.ts`: `remotePinnedSyncArgv` and its + Windows script, sharing the candidate lists with `REMOTE_OCX_SCRIPT` / `windowsOcxArgv`. +6b. NEW `src/cli/sync-link-status.ts`: `readHomeLinkStatus(deadlineMs)` with the typed errors. +7. MODIFY help, registry and capabilities-base `sync` entries (usage + `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]`, + flags, details, `json: "payload"`), including that fan-out never requests a Codex app or + app-server restart on a Child and that the Child's pinned sync may restart its own client runtime. +8. Docs: `docs-site/src/content/docs/reference/cli/lifecycle.md` (English), + `skills/ocx/references/05_remote_hub.md`, `04_failure_semantics.md` (exit 6), + `01_surface_lifecycle.md` if it lists sync flags, `structure/cli-management.md` and + `structure/remote-link.md`; regenerate `bun run skill:surface`; review `structure/manifest.json` + ownership for the new files. +9. Guards: extend the source scans in `tests/cli/cli-transport-honesty.test.ts` and + `tests/cli/cli-json-contract.test.ts` that read `dispatch.ts` to cover `sync-command.ts` too. +10. Tests, each new file registered in `scripts/test-layout/layout.json` and + `tests/fixtures/test-layout-expected.json`: + - `tests/cli/sync-fanout.test.ts`: classification tables (probe, sync, stale, mismatch reason + parsing incl. an unknown reason), version gate, client-initiated skip, each status-read error, + link-not-in-runtime, tunnel states, Home failed/skipped/thrown -> Children skipped, exit + combination, JSON shape, concurrency never above 3 with 7 Children, three hung Children delay a + fourth by at most one wave, a throwing worker is isolated. + - `tests/cli/sync-fanout-process.test.ts`: the owned runner against real child processes: a + process that ignores SIGTERM is SIGKILLed and gone before the call returns; a process that + exits 255; a descendant holding the stdout pipe is rejected as incomplete without holding the + call, and is reaped by the test; output over the cap. + - `tests/cli/sync-command-fanout.test.ts`: through the real CLI entry (`bun run src/cli/index.ts` + with a temp `OPENCODEX_HOME` and a fake `ssh` on PATH, no live runtime): `--local-only` makes no + ssh call; JSON mode prints exactly one document; usage errors exit 2 before preflight; a pinned + sync never fans out. + - `tests/clients/link-pinned-sync-argv.test.ts`: run the POSIX script with `sh` against fake + candidate directories (2.92.0 first -> exit 121 marker, never sync; 2.93.0 -> sync argv on the + same path with the `ocx-fanout:selected:2.93.0` marker and no other command run on that fake; + a fake whose `--version` writes endlessly while ignoring SIGPIPE, SIGXFSZ and its write errors is + killed by the watchdog, skipped, and its pid is gone; a broken first candidate followed by a + working one selects the second; a fake printing a valid version but exiting 17 is skipped, + never run; the capture file is gone after both a refusal and a successful exec; a zero-exit + version probe over 256 bytes is skipped; the stdout delimiter precedes the sync output; + `2.93.0-preview.1` -> refused; unparsable -> marker; a + candidate set that changes between two runs still pins the version check and the exec to one + path per run). Windows: extend the existing `windowsOcxArgv` execution tests + (`tests/clients/link-ssh-argv*.test.ts` and any PowerShell-executing test they use) to the new + script: selection order, fragmented output, delayed extra bytes past 256, a process that never + writes (deadline), version refusal, the exact argv handed to `Invoke-Native` (so + containment is kept), the marker line, and the size budget. + - Classification: stdout after the delimiter starting with `{` that is malformed, of an unknown schema, or two + documents fails `child-output-invalid`; empty stdout at exit 0 fails `child-output-invalid`; a + legacy Child printing the success sentence is `synced` and with the stale sentence is + `child-catalog-stale`; a document saying `synced` with exit 1 fails `child-sync-failed`; + a legacy 2.96.0 Child with and without the stale sentence; no marker -> `child-output-invalid`. + - Human-mode thrown Home sync: the one stderr line, then the original error and exit; with a + damaged `links.json` the original error still surfaces unchanged. + - `tests/cli/sync-link-status.test.ts`: stalled discovery, stalled headers, stalled body each end + at the deadline as `home-link-status-timeout`; 401/403; invalid DTO; no runtime. + - Home gate cases: refused refresh, thrown refresh, unchanged committed catalog, missing catalog. + - capabilities: `contracts` in every JSON output, `--contracts` output and the 64 combinations. + +## Verification + +`bun run typecheck`; the new test files plus the capabilities tests, `tests/ci-workflows/skill-ocx.test.ts`, +`tests/test-layout*.test.ts`, `tests/cli/cli-sync-expect-link.test.ts`, `tests/cli/cli-registry.test.ts`, +the extended guard tests, `tests/lab/core-lab-boundary.test.ts` and the file-size ratchet; +`bun run test:changed`; `bun run privacy:scan`; `bun run structure:check`; `bun run skill:surface:check`; +`bun run lint:gui` is not affected (no `gui/` change). No real service, desktop app, GOAT server or +Codex app is touched. + +## Risks + +- A powered-off Child whose tunnel state still reads `connected` costs up to the ssh ConnectTimeout + (10 s), reports `failed` and makes the run exit 6. +- A remote `ocx sync` can keep running after the Home kills its ssh on deadline. +- Stale detection depends on a sentence shared through one constant; a future Child that changes it + must keep the constant, and the classifier test pins it. diff --git a/devlog/_plan/261103_fix_8100_windows_batch/010_plan.md b/devlog/_plan/261103_fix_8100_windows_batch/010_plan.md new file mode 100644 index 00000000000..8a0bb5c5e1e --- /dev/null +++ b/devlog/_plan/261103_fix_8100_windows_batch/010_plan.md @@ -0,0 +1,70 @@ +# Fix the red dev batch: #8100 Windows containment exit and sync fan-out fixture (C3) + +Batch run https://github.com/lidge-jun/opencodex/actions/runs/41462914814 at `09b558580` failed two Windows shards. The tree before #8100 (`be51cb817`, run 41455278872) was green on every platform, and both failures trace to #8100 (`4948c04d9`). + +## Failure 1 — product regression: an uncontainable Windows ocx exits 1 instead of 126 + +`tests/clients/link-ssh-argv-discovery.test.ts` "a Windows ocx that cannot be contained in a kill-on-close job is refused before it runs" expects `WINDOWS_CONTAINMENT_EXIT` (126) and received 1 (windows 10/11). + +Cause. #8100 moved `windowsNativeArgv`, `windowsOcxArgv` and the new `windowsPinnedSyncArgv` onto `packedPowerShellArgv`. Its wrapper inflates the whole script with `[IO.MemoryStream]::new`, `[IO.Compression.DeflateStream]::new` and `[IO.StreamReader]::new`, then `Invoke-Expression`s it. That stage runs before the inflated script defines `Fail` (`exit 126`), outside any `try`, with the default `Continue` error preference. Constrained Language Mode (the AppLocker/WDAC case `structure/remote-link.md` names) blocks construction of those non-core types, so the inflate errors, `Invoke-Expression` receives `$null`, and `powershell.exe` ends with 1. Before #8100 only the helper source was deflated, and its inflation sat inside `try{Add-Type ...}catch{Fail}`, so the same session exited 126. + +Why it matters. 126 is the documented contract "the remote ocx could not be contained; nothing ran", and the Home classifies it as `child-ocx-not-contained` (`src/cli/sync-fanout.ts` `classifySyncResult`). An exit of 1 reads as an ordinary ocx failure (`child-sync-failed` for fan-out, a generic failure for link commands). Nothing runs uncontained, but the refusal is misreported. + +Change (`src/link/remote-windows.ts`, `packedPowerShellArgv` only): + +```text +$ocxPacked='' +$ErrorActionPreference='Stop';try{$b=...;$r=[IO.StreamReader]::new(...);$s=$r.ReadToEnd()}catch{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit 126};Invoke-Expression $s +``` + +- Only the inflate is inside the `try`. `Invoke-Expression` stays outside, so an error or exit code from the inflated script is never relabelled 126. CI already shows an inner `exit 23` propagating through `Invoke-Expression` ("Windows native execution preserves ... stdin bytes"). +- `$ErrorActionPreference='Stop'` makes every inflate failure terminating, so the `catch` sees it. The inflated `NATIVE_PROCESS` sets `Stop` on its first line already, so the inner script runs under the same preference as today. +- The message write is itself guarded because Constrained Language Mode also blocks `[Console]`, which matches the existing `Fail`. +- Encoded size, measured with realistic inputs: native 5,320 → 5,736, ocx 5,820 → 6,240, pinned sync 6,924 → 7,344 (measured on `09b558580` and on the fix), all under `POWERSHELL_ENCODED_MAX` (8,000). The existing `powershellArgv` throw still guards longer inputs. +- `unpackPowerShell`, `windowsScriptData` and `windowsScriptHelperSource` find `$ocxPacked='...'` by pattern and are unaffected. + +Regression tests (`tests/clients/link-ssh-argv-discovery.test.ts`, Windows-only, same file and seam as the failing case): run all three packed builders (`windowsNativeArgv` with the marker script, `windowsOcxArgv`, `windowsPinnedSyncArgv`) in a session that enters ConstrainedLanguage first, and expect 126 for each, with the native marker still absent. The two discovery builders run with `USERPROFILE`, `LOCALAPPDATA` and `ProgramFiles` pointed at an empty temp directory, and `PATH` set to `%SystemRoot%\System32` only. That directory holds no `ocx.exe`, and the session is launched by the absolute `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe`. No candidate exists, so a 126 can only be the refusal: a candidate cannot produce it, and an unguarded run would exit 1 or 127. The marker additionally proves "nothing ran" for the native builder. The failing case on `dev` is the before-fix evidence. + +The success paths through the guarded wrapper are already covered on Windows and must stay green on the final dispatch: "Windows native execution preserves spaces quotes Unicode empty arguments and stdin bytes" (an inner `exit 23` and stdin bytes through `Invoke-Expression`), "Windows discovery selects Desktop before the managed current junction before a legacy executable" (`windowsOcxArgv`), "closing the SSH channel terminates the remote ocx and its PowerShell host" (Job kill-on-close), and `tests/clients/link-pinned-sync-argv.test.ts` "Windows bounds version probes and runs the selected pinned command". A portable assertion that the wrapper refuses before `Invoke-Expression` cannot be made behaviorally off Windows, so none is added. The size budget stays covered portably: the POSIX cases in `link-pinned-sync-argv.test.ts` build the Windows pinned command, and the builder throws above `POWERSHELL_ENCODED_MAX`. The guard costs a fixed 416–420 encoded characters, so the variable argument headroom for `windowsOcxArgv` shrinks by that amount. Its production arguments are short CLI flags and ids; the key travels on stdin. + +Also correct the stale comment above `NATIVE_PROCESS` ("The helper travels deflated ... PowerShell inflates it and hands the text to Add-Type"). Since #8100 the whole script travels deflated, and the helper reaches `Add-Type` as a quoted literal. + +Docs. `structure/remote-link.md` still says the helper is "carried deflated ... and inflated only into `Add-Type`", which has been stale since #8100. Update it: the whole script travels deflated, and a failed inflation exits 126 before anything runs. + +## Failure 2 — the new test's fixture is wrong on Windows + +`tests/cli/sync-command-fanout.test.ts` "local-only JSON does not invoke ssh" (added by #8100) timed out at 15,000 ms on windows 2/11 with empty stdout. The same case takes about 300 ms on macOS. + +What the evidence establishes. The fixture is provably wrong on Windows (points 2 and 3). That the stall itself comes from the fixture, and not from product code, is a hypothesis supported by point 4: the log discards the child's stderr, so the blocking operation was not observed. The single Windows dispatch on the final head validates it. If the corrected case fails there, the outcome is unresolved, reported with the child stderr the new diagnostics capture, and nothing is weakened. + +1. With `--local-only`, `runHomeFanout` returns before reading the store, the status API or any SSH runner (`src/cli/sync-fanout.ts`). Everything that runs is the Home sync #8100 moved from `dispatch.ts` into `sync-command.ts` (the runner body is unchanged apart from routing `console.log` to stderr under `--json`), plus the new flag parse in `root.ts`, which is pure. +2. The child gets only `{HOME, OPENCODEX_HOME, CODEX_HOME, PATH: ":/usr/bin:/bin"}`. On Windows that has no `SystemRoot`, `USERPROFILE` or `PATHEXT`, a POSIX `:` delimiter, and an extensionless `#!/bin/sh` "ssh" Windows cannot execute. So even a passing run proves nothing about ssh on Windows (fan-out spawns `ssh` by PATH lookup with the inherited environment, `src/link/ssh-runner.ts`). +3. The Home sync reaches Codex write admission, whose ownership probe runs the machine's real `schtasks.exe`/`sc.exe`, resolved from System32 by `GetSystemDirectoryW`. A targeted query answer other than the English not-found text falls through to a full listing with a 20 s budget (`SERVICE_PROBE_LISTING_TIMEOUT_MS`, #2914). The repository's convention for any subprocess test reaching admission on Windows is `claimOwnedServiceHome` + `withOwnedServiceHomePreload` (`tests/helpers/owned-service-home.ts`: "PATH fixtures cannot isolate it"). This test skips it. +4. The same scenario written to that convention — `ocx sync` as a subprocess, Codex on, inherited env with temp `HOME`/`USERPROFILE`, owned-service-home preload (`tests/cli/cli-restore-back.test.ts`) — passed on Windows in this same batch in 688–721 ms (windows 9/11). + +The exact operation that blocked in the stripped environment is not observable from the log, because the test discards the child's stderr. No timeout is raised and no case is skipped. + +Changes (`tests/cli/sync-command-fanout.test.ts`): + +- Subprocess case: build the env the way `cli-restore-back.test.ts` does. Create a temp home directory, call `claimOwnedServiceHome(codexHome, opencodexHome, home)`, and use `{...process.env, HOME: home, USERPROFILE: home, OPENCODEX_HOME, CODEX_HOME, ...owned.env, PATH}`. PATH is `[sentinelDir, owned.env.PATH ?? process.env.PATH].join(delimiter)`, so the helper's Linux `systemctl` fixture survives. The argv goes through `withOwnedServiceHomePreload`. Codex integration stays on and the Codex home stays absent, so the Home path under test is unchanged. The child gets a spawn timeout below the 15,000 ms test budget. If stdout is not one document, the case fails with the child's exit code and stderr, so a future stall names its stage. +- Platform-neutral ssh sentinel. Add `tests/helpers/ssh-spawn-sentinel-preload.ts`, a test-only Bun preload enabled by `OCX_TEST_SSH_SENTINEL=`. It wraps exactly `Bun.spawn` and `Bun.spawnSync`, the APIs fan-out uses (`runFanoutProcess` calls `Bun.spawn` directly, and `fanoutSshRunner` delegates to it). An argv whose first element has basename `ssh` or `ssh.exe` (case-insensitive, either separator) appends one line ` ` to the marker and throws, so it never runs. Every other call passes through unchanged. It does not touch `node:child_process`, so it composes with the Windows service preload, which mocks that module, without either replacing the other. Its claim is scoped to those two APIs in the CLI process. No production module reads the flag. The subprocess case loads it as `withOwnedServiceHomePreload(["run", "--preload", sentinel, cli, ...])`, the exact combination the controls use. It asserts the marker is absent and the expected document (`schema`, `home.exit === code`, `fanout: disabled`, `children: []`) is present, so a thrown sentinel error cannot pass as a valid run. +- Positive control (same file, same preload combination and env shape). A child runs a script that calls `Bun.spawn(["ssh", "-V"])` and then `Bun.spawnSync(["C:\\fixture\\SSH.EXE", "-V"])`, each in its own try (the sentinel records each attempt), then `Bun.spawnSync([process.execPath, "--version"])` and prints that exit code. On Windows it also calls `child_process.spawnSync("schtasks.exe", ["/query", "/tn", "opencodex-proxy", "/xml"], { encoding: "buffer" })` and prints its stderr. The case asserts two marker lines, `Bun.spawn ssh` and `Bun.spawnSync ssh.exe`, a pass-through exit of 0, and on Windows the `[OCX_TEST_SERVICE_HOME]` stderr, which shows the service fixture is still active beside the sentinel. The `#!/bin/sh` PATH sentinel stays as a second, POSIX-only check. Helpers need no test-layout registration (`tests/test-layout.test.ts` treats `helpers/` as support files). +- New in-process case, `sync --local-only --json` with a committed Home catalog and a connected hub-initiated link, using the file's existing spies. It asserts that `readHomeLinkStatus`, `fanoutSshRunner` and `runFanoutProcess` are never called, and that the document reports `fanout: {state: "disabled", reason: null}` with no children. This is the platform-neutral proof that local-only never reaches ssh, including on Windows, where the PATH sentinel cannot run. +- The "human sync reports a damaged link store" case uses the same stripped POSIX env and reaches the same admission probe; it gets the same env correction, without changing what it asserts. + +Nothing in `src/` changes for failure 2. + +## Out of scope + +Workflows, timeouts, the Windows probe budgets, the slow pinned case (passes, 9.8 s on Windows), any refactor. + +## Verification + +- `bun test tests/clients/link-ssh-argv-discovery.test.ts tests/cli/sync-command-fanout.test.ts tests/clients/link-pinned-sync-argv.test.ts tests/cli/sync-fanout.test.ts tests/cli/sync-fanout-process.test.ts` (macOS: the Windows cases skip) +- `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, `bun scripts/test.ts --changed=dev --parallel=1` +- Full `bun run test`: the PR carries `ci:full`, so the four full Ubuntu shards run on the PR head, and the one dispatch runs every platform. Locally, the focused files plus `test:changed` are the floor. The PR's Verification section records the exact commands and anything left to CI, per AGENTS.md's resource exception, because several concurrent worktrees share this host. +- The one authorized `gh workflow run ci.yml --ref ` on the final head: windows 2/11 and 10/11 green, plus the new Windows CLM cases. +- Terra plan audit to PASS, a Terra security review of the containment change, and a Terra code review. + + + diff --git a/devlog/_plan/261103_windows_batch_shards/010_plan.md b/devlog/_plan/261103_windows_batch_shards/010_plan.md new file mode 100644 index 00000000000..db205b13790 --- /dev/null +++ b/devlog/_plan/261103_windows_batch_shards/010_plan.md @@ -0,0 +1,64 @@ +# Windows batch shards green after #8103/#8104 (dev @ 43e2e4e57) + +Run [41491122166](https://github.com/lidge-jun/opencodex/actions/runs/41491122166) (head 1800b4d7f = dev with #8103, #8104, #8106) left four Windows shards red. The previous full Windows run on dev, 41262132337, was green on all eleven shards, and its head is an ancestor of #8103's parent. Every failure below traces to #8103 (4d93716dd) or to a test fixture that depends on Windows runner timing. None is caused by #8106. + +## Findings + +| Shard | Failing file | Root cause | Side to fix | +|---|---|---|---| +| windows 10/11 | tests/update/update-orchestrated-identity.test.ts "identity requires a stable, attested runtime record" | The fixture uses POSIX paths (`/fixture/install/src/cli/index.ts`). On win32, `dirname` three times gives `/fixture/install`, and `join(root, "src", "cli", "index.ts")` rebuilds it with backslashes, so the equality check in src/update/orchestrated-identity.ts fails and the function correctly fails closed to `unknown`. Real records come from `currentServingCommand()` (src/config/serving-runtimes.ts), which uses `process.execPath` and `process.argv[1]` and joins relative parts with `node:path`, so they are native whenever Bun reports `process.argv[1]` natively; nothing forces that, which is why T1 also fixes the product. The real-listener case in the same file passed on Windows. Reproduced with `path.win32` in .tmp/research/win32-identity.ts. | Fixture is POSIX-only. The product also compares separators too strictly: `selfLaunchArgv` passes `process.argv[1]` through unchanged, and `currentServingCommand` keeps any absolute part as given, so a valid Windows path written with `/` would make a live install read as `unknown` (fail closed, but wrong). Fixed on both sides. | +| windows 7/11 | tests/update/update-bun-ownership-lease.test.ts (6 cases: home-unknown, home-unknown-fail, parent-package-only, parent-package-only-result, delegated-unknown-unknown, delegated-post-replacement) | #8103 routes the Windows Bun package replacement through `runWindowsInstallerSync` (src/update/npm-install.mjs). That spawns `process.execPath --input-type=module -e