Skip to content

Commit a523f0f

Browse files
lidge-junVoyagerroc-LabVoyagerroc-Code
committed
fix(cli): refuse an in-place restart through a different-version CLI
Carries lidge-jun#4529 by Voyagerroc-Lab, re-authored on current dev. An in-place restart respawns the live process from its own installation, so a restart accepted from a different-version CLI keeps the old build serving while reporting success (lidge-jun#4522). The restart client now reuses doctor's computeVersionSkew comparison (CLI package version vs the attested /healthz version) and refuses before POST with restart_version_skew; placeholder versions (unknown/0.0.0) stay incomparable and keep the restart path. Adds the CodeRabbit-asked regression: an "unknown" health-version case beside the carried "0.0.0" placeholder case, asserting the restart is accepted and both requests are made. structure/runtime.md records the restart-verb refusal on the src/cli/index.ts lifecycle row. Co-authored-by: Voyagerroc-Lab <[email protected]> Co-authored-by: Voyagerroc-Code <[email protected]>
1 parent a84e6e8 commit a523f0f

4 files changed

Lines changed: 129 additions & 1 deletion

File tree

‎src/cli/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,9 @@ function reportRestartFailure(result: Extract<ProxyRestartResult, { ok: false }>
732732
if (code === "restart_capability_unsupported") {
733733
console.error("❌ The running proxy predates process-bound restart support; no unsafe fallback was attempted.");
734734
console.error(" After confirming this home owns the proxy, run `ocx stop` and then `ocx start` once.");
735+
} else if (code === "restart_version_skew") {
736+
console.error("❌ The running proxy reports a different OpenCodex version than this CLI; restarting in place would respawn the old installation.");
737+
console.error(" Run `ocx stop` and then `ocx start` from this installation instead.");
735738
} else {
736739
console.error("❌ Proxy restart request could not be confirmed; no fallback stop/start was attempted.");
737740
}

‎src/cli/system-restart-client.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ import {
2222
type LiveProxy,
2323
} from "../server/proxy-liveness";
2424
import type { ProxyRestartRequestOutcome } from "./tray-proxy";
25+
import { packageVersion } from "./help";
26+
import { computeVersionSkew } from "./version-skew";
2527

2628
export const SYSTEM_RESTART_REQUEST_TIMEOUT_MS = 5_000;
2729
export const SYSTEM_RESTART_ATTESTATION_TIMEOUT_MS = 4_000;
@@ -32,12 +34,23 @@ export interface BoundSystemRestartDeps {
3234
findLive?: typeof findLiveProxy;
3335
createChallenge?: () => string;
3436
now?: () => number;
37+
/** Invoking CLI version for the skew guard; defaults to this bundle's package version. */
38+
cliVersion?: string;
3539
}
3640

3741
function rejected(code: string): ProxyRestartRequestOutcome {
3842
return { accepted: false, uncertain: false, error: new Error(code) };
3943
}
4044

45+
/** Own-bundle version for the skew comparison; an unreadable bundle is "cannot compare", not a crash. */
46+
function ownCliVersion(): string {
47+
try {
48+
return packageVersion();
49+
} catch {
50+
return "unknown";
51+
}
52+
}
53+
4154
function uncertain(code: string): ProxyRestartRequestOutcome {
4255
return { accepted: false, uncertain: true, error: new Error(code) };
4356
}
@@ -107,6 +120,18 @@ export async function requestBoundSystemRestart(
107120
return rejected("restart_capability_unsupported");
108121
}
109122

123+
// An in-place restart respawns the live process from its own installation
124+
// (selfLaunchArgv in server/management/system-restart.ts), so a restart accepted
125+
// from a different-version CLI would keep the OLD build serving while reporting
126+
// success (#4522). Both sides already publish exactly the data doctor's skew
127+
// diagnosis compares (packageVersion vs the /healthz version), so reuse that
128+
// comparison and refuse before POST. Placeholder versions (unknown/0.0.0) are
129+
// "cannot compare", not mismatch, and keep the existing behavior.
130+
const proxyVersion = typeof body.version === "string" ? body.version : undefined;
131+
if (computeVersionSkew(deps.cliVersion ?? ownCliVersion(), proxyVersion).skewed) {
132+
return rejected("restart_version_skew");
133+
}
134+
110135
let observed: LiveProxy | null;
111136
try {
112137
observed = await (deps.findLive ?? findLiveProxy)({ deadlineAt, nowFn: now });

‎structure/runtime.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Shared parsing and streaming follow the [request-copy](transports/byte-accountin
1515
| --- | --- |
1616
| `bin/ocx.mjs` | Published npm `bin` entry (Node shim). Resolves the bundled or explicit Bun binary before project dotenv can load, stamps its runtime provenance plus a proof-bound Anthropic parent-env snapshot, lazy-runs `bun/install.js` if only the placeholder stub is present, then execs `src/cli/index.ts` under Bun. Lets `npm install -g` work without a separately-installed Bun. The exact `system codex-cli-update` inspection namespace skips both boot repair and lazy Bun installation; missing runtime support fails closed instead of mutating state. |
1717
| `src/lib/bun-runtime.ts` | Bundled-Bun resolution: `isRealBunBinary()` (size gate vs the ~450-byte placeholder stub), `bundledBunPath()`, and `durableBunPath()` (path baked into service/shim artifacts). Durable selection accepts only the source/path pair already stamped for the running executable; it never re-reads a project-dotenv `OPENCODEX_BUN_PATH`. |
18-
| `src/cli/index.ts` | `ocx` / `opencodex` CLI. Lifecycle: init, start, stop, restart, status, sync, restore/eject, gui, service, update. Configuration: provider, account, models, combo/route, access, integrations, v2. Client launchers: Claude, OpenCode, MiniMax Code, and MiniMax CLI text. The MMX launcher owns a child-lifetime loopback path bridge from the client's hard-coded `/anthropic/v1/messages` path to the canonical `/v1/messages` data plane; the server does not expose an extra auth surface. Diagnostics: doctor, debug, observe, health. Windows adds tray. The full command surface is `src/cli/help.ts`; this table names the groups, not every verb. After help/version early exits, ordinary commands run the bounded best-effort Codex-shim auto-restore policy before dispatch. `system codex-cli-update` is the deliberate read-only exception and suppresses auto-restore for its whole namespace, including malformed invocations. Keeps the `#!/usr/bin/env bun` shebang for from-source dev (`bun run src/cli/index.ts`). |
18+
| `src/cli/index.ts` | `ocx` / `opencodex` CLI. Lifecycle: init, start, stop, restart, status, sync, restore/eject, gui, service, update. `restart` refuses an in-place restart requested by a CLI whose version differs from the attested `/healthz` version, because the replacement respawns from the live installation; placeholder versions (unknown/0.0.0) stay incomparable and keep the restart path. Configuration: provider, account, models, combo/route, access, integrations, v2. Client launchers: Claude, OpenCode, MiniMax Code, and MiniMax CLI text. The MMX launcher owns a child-lifetime loopback path bridge from the client's hard-coded `/anthropic/v1/messages` path to the canonical `/v1/messages` data plane; the server does not expose an extra auth surface. Diagnostics: doctor, debug, observe, health. Windows adds tray. The full command surface is `src/cli/help.ts`; this table names the groups, not every verb. After help/version early exits, ordinary commands run the bounded best-effort Codex-shim auto-restore policy before dispatch. `system codex-cli-update` is the deliberate read-only exception and suppresses auto-restore for its whole namespace, including malformed invocations. Keeps the `#!/usr/bin/env bun` shebang for from-source dev (`bun run src/cli/index.ts`). |
1919
| `src/server/index.ts` | Bun server entrypoint: `startServer`, `/v1/responses` HTTP + WebSocket routing (compact handled before generic Responses), exact `POST /v1/images/generations` and `POST /v1/images/edits` routing, `/v1/models`, the Anthropic-shaped `/v1/messages` and OpenAI-shaped `/v1/chat/completions` compatibility surfaces, the Live/Realtime surface, the hosted-search relay, artifact serving, `/healthz`, the `/api/*` auth gate, the `/v1/*` JSON 404 guard, GUI fallback, the opt-in loopback-only hub-management listener, and facade re-exports for split server modules. |
2020
| `src/server/images.ts` | Standalone Images data plane: default OpenAI or explicit custom-provider selection, Codex account affinity, bounded opaque request relay, single-attempt upstream fetch, pool health recording, and safe response/cancellation relay. |
2121
| `src/server/audio-transcriptions.ts` | Standalone multipart transcription; audio-specific key admission, bounded upload/response, stored OpenAI credential resolution and lease-bound cancellation. See [audio contracts](data-planes/inbound-compat.md#standalone-file-transcription). |

‎tests/cli/system-restart-client.test.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ function successfulDeps() {
5252
findLive: async () => target,
5353
createChallenge: () => challenge,
5454
now: () => 1_000,
55+
// Matches the /healthz fixture version below so the skew guard stays out of the way;
56+
// the dedicated skew tests override it explicitly.
57+
cliVersion: "test",
5558
},
5659
};
5760
}
@@ -144,6 +147,103 @@ describe("bound system restart client", () => {
144147
expect(setup.requests).toHaveLength(1);
145148
});
146149

150+
test("refuses a restart through a CLI whose version differs from the attested proxy", async () => {
151+
for (const [proxyVersion, cliVersion] of [
152+
["2.49.0", "2.53.0"],
153+
["2.53.0", "2.49.0"],
154+
["test", "2.53.0"],
155+
] as const) {
156+
const setup = successfulDeps();
157+
setup.deps.cliVersion = cliVersion;
158+
setup.deps.fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
159+
const url = String(input);
160+
setup.requests.push({ url, init });
161+
if (url.endsWith("/healthz")) {
162+
const response = successfulDepsResponse(setup.secret, setup.challenge);
163+
const body = await response.json() as Record<string, unknown>;
164+
body.version = proxyVersion;
165+
return new Response(JSON.stringify(body), {
166+
status: 200,
167+
headers: response.headers,
168+
});
169+
}
170+
throw new Error("POST must not be attempted");
171+
}) as typeof fetch;
172+
173+
const outcome = await requestBoundSystemRestart(target, 10_000, setup.deps);
174+
expect(outcome).toMatchObject({ accepted: false, uncertain: false });
175+
expect(outcome.accepted ? "" : (outcome.error as Error).message)
176+
.toBe("restart_version_skew");
177+
expect(setup.requests).toHaveLength(1);
178+
}
179+
});
180+
181+
test("allows a restart when the invoking CLI matches the attested proxy version", async () => {
182+
const setup = successfulDeps();
183+
setup.deps.cliVersion = "2.53.0";
184+
setup.deps.fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
185+
const url = String(input);
186+
setup.requests.push({ url, init });
187+
if (url.endsWith("/healthz")) {
188+
const response = successfulDepsResponse(setup.secret, setup.challenge);
189+
const body = await response.json() as Record<string, unknown>;
190+
body.version = "2.53.0";
191+
return new Response(JSON.stringify(body), {
192+
status: 200,
193+
headers: response.headers,
194+
});
195+
}
196+
return new Response(JSON.stringify({ success: true }), { status: 202 });
197+
}) as typeof fetch;
198+
199+
expect(await requestBoundSystemRestart(target, 10_000, setup.deps)).toEqual({ accepted: true });
200+
expect(setup.requests).toHaveLength(2);
201+
});
202+
203+
test("treats a placeholder proxy version as incomparable and keeps the restart path", async () => {
204+
const setup = successfulDeps();
205+
setup.deps.cliVersion = "2.53.0";
206+
setup.deps.fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
207+
const url = String(input);
208+
setup.requests.push({ url, init });
209+
if (url.endsWith("/healthz")) {
210+
const response = successfulDepsResponse(setup.secret, setup.challenge);
211+
const body = await response.json() as Record<string, unknown>;
212+
body.version = "0.0.0";
213+
return new Response(JSON.stringify(body), {
214+
status: 200,
215+
headers: response.headers,
216+
});
217+
}
218+
return new Response(JSON.stringify({ success: true }), { status: 202 });
219+
}) as typeof fetch;
220+
221+
expect(await requestBoundSystemRestart(target, 10_000, setup.deps)).toEqual({ accepted: true });
222+
expect(setup.requests).toHaveLength(2);
223+
});
224+
225+
test("treats an unknown proxy version as incomparable and keeps the restart path", async () => {
226+
const setup = successfulDeps();
227+
setup.deps.cliVersion = "2.53.0";
228+
setup.deps.fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
229+
const url = String(input);
230+
setup.requests.push({ url, init });
231+
if (url.endsWith("/healthz")) {
232+
const response = successfulDepsResponse(setup.secret, setup.challenge);
233+
const body = await response.json() as Record<string, unknown>;
234+
body.version = "unknown";
235+
return new Response(JSON.stringify(body), {
236+
status: 200,
237+
headers: response.headers,
238+
});
239+
}
240+
return new Response(JSON.stringify({ success: true }), { status: 202 });
241+
}) as typeof fetch;
242+
243+
expect(await requestBoundSystemRestart(target, 10_000, setup.deps)).toEqual({ accepted: true });
244+
expect(setup.requests).toHaveLength(2);
245+
});
246+
147247
test("refuses to POST when the live target changes after attestation", async () => {
148248
const setup = successfulDeps();
149249
setup.deps.findLive = async () => ({ ...target, pid: 4343 });

0 commit comments

Comments
 (0)