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
11 changes: 9 additions & 2 deletions src/zcode/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,16 +592,23 @@ export async function handoffZcodeRoutingOnExit(opts: ExitHandoffOptions): Promi
const env = opts.env ?? process.env;
const log = opts.log ?? defaultLog;
const dataDir = opts.dataDir ?? resolveZcodeDataDir(env);
const current = detectCurrentZcodeOrigin(dataDir, env);
if (!current || current !== opts.ownOrigin) return "not-ours";
const stillOurs = () => detectCurrentZcodeOrigin(dataDir, env) === opts.ownOrigin;
if (!stillOurs()) return "not-ours";
const replacement = await (opts.findReplacement ?? defaultFindReplacement)();
// Replacement discovery awaits; another process may have taken the shared
// route meanwhile, and its route must not be overwritten or removed.
if (!stillOurs()) {
log("exit handoff: the store changed owner during replacement discovery — leaving it untouched");
return "not-ours";
}
if (replacement) {
const routed = await routeZcodeConfig({ origin: replacement.origin, env, dataDir: opts.dataDir, log, policy: zcodePolicyFromEnv(env) });
if (routed) {
await activateZcodePluginMode(routed, { env, dataDir: opts.dataDir, log });
log(`exit handoff: store → ${replacement.origin}`);
return "handed-off";
}
if (!stillOurs()) return "not-ours";

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: Cover both outcomes of the post-reroute ownership guard

Both new cases return at the earlier post-discovery check, and the existing handoff tests either successfully route or bypass this replacement block. Removing this guard would therefore leave the handoff tests passing even though a refused re-route could then strip another owner's route; an unconditional return here would also pass while leaving our exiting origin in place. AGENTS.md and the Gate Test Discipline require positive and negative assertions for every new gate.

Add replacement-present cases that force routeZcodeConfig to return undefined: changed ownership must produce not-ours with unchanged store bytes, while retained ownership must produce reverted-direct and remove the wrappers. A pre-wrapped signing-blocked personal store with BILI_ZCODE_ROUTE=plans can force refusal; the existing injected log callback can change the stored origin when that refusal is logged, without adding a production test seam.

}
unrouteZcode({ env, dataDir: opts.dataDir, log });
log("exit handoff: store reverted to direct upstream");
Expand Down
67 changes: 67 additions & 0 deletions tests/zcode-native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,73 @@ test("handoffZcodeRoutingOnExit reverts to direct when no replacement lives (#16
}
});

for (const replacementFound of [false, true]) {
test(`handoffZcodeRoutingOnExit leaves a route another owner took during replacement discovery (replacement=${replacementFound})`, async () => {
const dir = dataDir();
const newOwner = "http://127.0.0.1:38787";
try {
await routeZcodeConfig({ origin: "http://127.0.0.1:18787", dataDir: dir, env: {}, log: NO_LOG });
let taken = "";
assert.equal(
await handoffZcodeRoutingOnExit({
ownOrigin: "http://127.0.0.1:18787",
dataDir: dir,
env: {},
log: NO_LOG,
findReplacement: async () => {
await routeZcodeConfig({ origin: newOwner, dataDir: dir, env: {}, log: NO_LOG });
taken = readFileSync(storeFile(dir), "utf8");
return replacementFound ? { origin: "http://127.0.0.1:28787" } : undefined;
},
}),
"not-ours",
);
assert.equal(detectCurrentZcodeOrigin(dir, {}), newOwner);
assert.equal(readFileSync(storeFile(dir), "utf8"), taken);
} finally {
rmrf(dir);
}
});
}

for (const takenDuringReroute of [false, true]) {
test(`handoffZcodeRoutingOnExit after a refused re-route reverts only a route it still owns (taken=${takenDuringReroute})`, async () => {
const dir = mkdtempSync(path.join(tmpdir(), "zcode-native-refused-"));
mkdirSync(path.join(dir, "v2"), { recursive: true });
const file = zcodeStoreCandidates(dir, "new", {})[0];
writeFileSync(
file,
JSON.stringify({ schemaVersion: 1, config: { providerConfigRules: { providerRules: [{ providerId: "account:deepseek", config: { api: { baseUrl: "https://api.deepseek.com/v1" } } }] } } }) + "\n",
);
try {
assert.ok(await routeZcodeConfig({ origin: "http://127.0.0.1:18787", dataDir: dir, env: {}, log: NO_LOG }));
let taken: string | undefined;
const outcome = await handoffZcodeRoutingOnExit({
ownOrigin: "http://127.0.0.1:18787",
dataDir: dir,
// route:"plans" on the signing-era store makes the re-route refuse (#1621).
env: { BILI_ZCODE_ROUTE: "plans" },
log: (msg) => {
if (!takenDuringReroute || taken !== undefined || !/client[- ]signing/.test(msg)) return;
taken = readFileSync(file, "utf8").split("127.0.0.1:18787").join("127.0.0.1:38787");
writeFileSync(file, taken);
},
findReplacement: async () => ({ origin: "http://127.0.0.1:28787" }),
});
if (takenDuringReroute) {
assert.equal(outcome, "not-ours");
assert.equal(detectCurrentZcodeOrigin(dir, {}), "http://127.0.0.1:38787");
assert.equal(readFileSync(file, "utf8"), taken);
} else {
assert.equal(outcome, "reverted-direct");
assert.doesNotMatch(readFileSync(file, "utf8"), /\/bili\//);
}
} finally {
rmrf(dir);
}
});
}

// #1892: the zero-wrapped path must explain itself instead of leaving the
// client a bare "Connection closed". An empty personal store is NOT "no
// provider" — this build sources active providers from the built-in/account
Expand Down
Loading