Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions src/zcode/mcp-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ export interface MutableZcodeWatchdogState extends ZcodeWatchdogState {
origin: string;
failures: number;
stopped?: boolean;
/** Origin a replacement tick has started routing the store to but has not
* adopted as `origin` yet; the exit handoff owns that route too (#14). */
routing?: string;
}

function buildEnsureOpts(): Parameters<typeof ensureProxyRunning>[0] {
Expand Down Expand Up @@ -94,17 +97,21 @@ export async function zcodeWatchdogTick(state: MutableZcodeWatchdogState, extern
} else {
const ensure = deps.ensure ?? defaultEnsure;
const { origin } = await ensure(buildEnsureOpts());
if (origin !== state.origin) {
if (origin === state.origin) {
log(`proxy ${origin} recovered without a re-route`);
} else if (state.stopped) {
log(`proxy respawned at ${origin} during shutdown — routing left to the exit handoff`);
} else {
state.routing = origin;
process.env.BILI_MCP_PROXY = origin;
const route = deps.route ?? routeZcodeConfig;
const routed = await route({ origin, log, policy: state.policy });
if (!routed) throw new Error("proxy respawned but the zcode config rewrite failed");
const activate = deps.activate ?? activateZcodePluginMode;
await activate(routed, { log });
state.origin = origin;
state.routing = undefined;
log(`proxy respawned at ${origin} — config re-routed`);
} else {
log(`proxy ${origin} recovered without a re-route`);
}
state.failures = 0;
}
Expand All @@ -129,16 +136,24 @@ export function startWatchdog(
return async () => { state.stopped = true; clearInterval(timer); await pending; };
}

export function installExitHandoff(state: { origin: string }, log: (msg: string) => void, deps: {
export function installExitHandoff(state: { origin: string; routing?: string; stopped?: boolean }, log: (msg: string) => void, deps: {
events?: { once(event: string, listener: () => void): unknown };
handoff?: () => Promise<unknown>;
handoff?: (ownOrigin: string) => Promise<unknown>;
exit?: (code: number) => void;
timeoutMs?: number;
} = {}): () => Promise<void> {
let pending: Promise<void> | undefined;
const finish = () => pending ??= (async () => {
state.stopped = true;
try {
await (deps.handoff ? deps.handoff() : handoffZcodeRoutingOnExit({ ownOrigin: state.origin, log }));
const tried = new Set<string>();
for (;;) {
const ownOrigin = [state.origin, state.routing].find((o): o is string => o !== undefined && !tried.has(o));
if (ownOrigin === undefined) break;
tried.add(ownOrigin);
const outcome = await (deps.handoff ? deps.handoff(ownOrigin) : handoffZcodeRoutingOnExit({ ownOrigin, log }));
if (outcome !== "not-ours") break;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(ai: openai/gpt-6-astra)

WARNING: Add the required negative assertion for the fallback gate

There is no test with both state.origin and a distinct state.routing populated where the first handoff succeeds and the fallback must not run. The new activation case exercises only not-ours followed by fallback; the ensure case and existing single-handoff tests have no pending routing origin. Consequently, removing this success short-circuit would still satisfy their assertions even though it permits a second handoff after a successful transfer. AGENTS.md:53 and the development contract's gate-test discipline require both directions. Add a case with both origins present, return handed-off or reverted-direct for the first origin, and assert that the handoff receives only that origin.

}
} catch (err) {
log(`exit handoff failed: ${err instanceof Error ? err.message : String(err)}`);
} finally {
Expand Down
78 changes: 77 additions & 1 deletion tests/zcode-mcp-eof.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { EventEmitter } from "node:events";
import * as entry from "../src/zcode/mcp-entry.ts";
import { defaultZcodeRoutePolicy } from "../src/zcode/json-edit.ts";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { defaultZcodeRoutePolicy, detectCurrentZcodeOrigin, zcodeStoreCandidates } from "../src/zcode/json-edit.ts";
import { handoffZcodeRoutingOnExit, routeZcodeConfig } from "../src/zcode/native.ts";
import { rmrf } from "./tmp-rm.ts";

function deferred() {
let resolve!: () => void;
Expand Down Expand Up @@ -106,6 +111,77 @@ for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]] as const) {
});
}

const OLD = "http://127.0.0.1:18787";
const NEW = "http://127.0.0.1:28787";

function routedStore(): string {
const dir = mkdtempSync(path.join(tmpdir(), "zcode-eof-"));
mkdirSync(path.join(dir, "v2"), { recursive: true });
writeFileSync(
zcodeStoreCandidates(dir, "legacy", {})[0],
JSON.stringify({ provider: { "builtin:bigmodel-coding-plan": { options: { baseURL: "https://open.bigmodel.cn/api/anthropic" } } } }) + "\n",
);
return dir;
}

for (const blockedAt of ["activate", "ensure"] as const) {
test(`signal during a watchdog replacement hands off the route the replacement wrote (blocked in ${blockedAt})`, { timeout: 5000 }, async () => {
const dir = routedStore();
const blocked = deferred();
const entered = deferred();
const exited = deferred();
const emitter = new EventEmitter();
const exits: number[] = [];
let routes = 0;
const state = { origin: OLD, failures: 2, policy: defaultZcodeRoutePolicy() };
await routeZcodeConfig({ origin: OLD, dataDir: dir, env: {}, log: () => {} });
const stop = entry.startWatchdog(state, false, () => {}, {
intervalMs: 1,
probe: async () => false,
ensure: async () => {
if (blockedAt === "ensure") { entered.resolve(); await blocked.promise; }
return { origin: NEW };
},
route: async (opts) => { routes++; return routeZcodeConfig({ ...opts, dataDir: dir, env: {}, log: () => {} }); },
activate: async () => {
if (blockedAt === "activate") { entered.resolve(); await blocked.promise; }
},
repair: async () => {},
});
entry.installExitHandoff(state, () => {}, {
events: emitter,
handoff: (ownOrigin) => handoffZcodeRoutingOnExit({ ownOrigin, dataDir: dir, env: {}, log: () => {}, findReplacement: async () => undefined }),
exit: (code) => { exits.push(code); exited.resolve(); },
});
const hold = setTimeout(() => {}, 5000);
try {
await entered.promise;
assert.equal(detectCurrentZcodeOrigin(dir, {}), blockedAt === "activate" ? NEW : OLD);
emitter.emit("SIGTERM");
await exited.promise;
assert.deepEqual(exits, [143]);
assert.equal(detectCurrentZcodeOrigin(dir, {}), undefined);
blocked.resolve();
await stop();
assert.equal(detectCurrentZcodeOrigin(dir, {}), undefined);
assert.equal(routes, blockedAt === "activate" ? 1 : 0);
} finally { clearTimeout(hold); blocked.resolve(); await stop(); rmrf(dir); }
});
}

for (const first of ["reverted-direct", "not-ours"] as const) {
test(`exit handoff tries the in-flight routing origin only when the adopted origin is not the owner (first=${first})`, async () => {
const asked: string[] = [];
const handoff = entry.installExitHandoff({ origin: OLD, routing: NEW }, () => {}, {
events: new EventEmitter(),
handoff: async (ownOrigin) => { asked.push(ownOrigin); return ownOrigin === OLD ? first : "reverted-direct"; },
exit: () => { assert.fail("EOF must not force exit"); },
});
await handoff();
assert.deepEqual(asked, first === "not-ours" ? [OLD, NEW] : [OLD]);
});
}

test("signal deadline forces the original code while overlapping handoff runs once", async () => {
const work = deferred();
const emitter = new EventEmitter();
Expand Down
Loading