fix(setup): doctor FAILs when zcode would drop config.json and run no hook; live zcode fire test (D-NI-ZCODE-GATE-1)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mksgluandClaude Sonnet 5.5 committed 2026-10-30 01:52:27 +03:00
1 parent 807ae9a554
commit 5ef1f1894d
6 files changed
+352 -2

No files matched your search

+7 -1
View File
@@ -50,9 +50,15 @@ context-mode setup --remove --agents zcode
It puts each touched file back. To remove the package too, see [Uninstall](./README.md#uninstall).
## When ZCode runs no hook
ZCode 0.17.0 (built from zai-org/ZCode `3c5b2276`) reads `~/.zcode/cli/config.json` with one schema. If any key in the file is invalid (for example `ui.locale` set to a value other than `auto`, `en-US` or `zh-CN`, or `logging` set to a string), ZCode logs `config.file.invalid Config file failed to load` and uses no key of the file. The hooks and the MCP server do not load. Hooks in this user file need no workspace trust; only project `zcode.json` hooks do.
`context-mode doctor --agents zcode` FAILs `hook-registered` and names the invalid key. Fix or remove that key. Setup does not change keys it does not own.
## Known limits
- ZCode has no npm package, so no run showed ZCode load the server. The ZCode desktop app is not covered.
- ZCode has no npm package. The live test `tests/v2/e2e/zcode-fire.test.mjs` runs the real CLI built from source (set `ZCODE_CLI_BUNDLE` to `zcode.cjs`) against a local fake provider; it skips when no binary is found. The ZCode desktop app is not covered.
## Report a problem
+1
View File
@@ -101,3 +101,4 @@ Split: this file holds the deviation rows without a date (format: id, files, dec
| D-HF-OPENCODE-GATE-1 | `src/setup/engine.ts` (wantedPluginList, pluginListIssue, hasPluginIssue), `tests/v2/setup/opencode-plugin-gate.test.mjs` (new), `tests/v2/e2e/opencode-fire.test.mjs` (new), `docs/install/opencode.md` | OpenCode 1.19.5 loads every entry of the `plugin` list and skips an entry whose file is missing with no error. Two ways our hooks did not run or ran twice: (1) the native install `opencode plugin context-mode@next --global` writes `context-mode@next`; setup then added our absolute path as a second entry, so the plugin loaded twice (two `prompt` rows per message in context.db); (2) a stale path entry of ours (package moved or upgraded) never loads. Setup now writes no path entry when a `context-mode@<tag>` entry exists, drops our path entry in that case and drops a stale `.../context-mode/opencode/plugin.js` whose file is gone; user entries stay. Doctor FAILs hook-registered with a one-line fix (`context-mode setup`) for both. | Live: real opencode 1.19.5, fake OpenAI-compatible provider, `cat big.log` (200 KB): the model got 160 bytes (redirect) with the plugin, 51 KB-plus with a missing-file entry (control). Tests written first (3 red, output kept in the PR). |
| D-CC-HOOKS-RUN-1 | `src/setup/engine.ts` (`listState`, `statusOf`, `disabledBySettings`, `hookEnabledCheck`, enable step in `planRow`), `src/setup/registry.ts` (`HostCopy.enable`), `tests/v2/setup/claude-code-hooks-run.test.mjs` (new), `tests/v2/e2e/claude-code-fire.test.mjs` (new) | Live Claude Code 2.1.274 (`claude -p` against a fake Anthropic Messages endpoint through `ANTHROPIC_BASE_URL`, no login, temp HOME and `CLAUDE_CONFIG_DIR`, plugin installed with `claude plugin marketplace add` and `claude plugin install`): a Bash `cat big.log` of 200 KB reaches the model as one line plus a `ctx_search(` pointer (PostToolUse `updatedToolOutput`); the hooks fire. Two states keep our registered hooks from running: the plugin is installed but `Status: disabled` in `claude plugin list`, and `disableAllHooks: true` in `~/.claude/settings.json`, `settings.local.json` or the project `.claude/` (control run: the model then gets Claude Code's own 2 KB preview of the 195 KB file). Setup now runs the host's own `claude plugin enable context-mode@context-mode` for a disabled plugin; doctor adds `hook-enabled` and FAILs with a one-line fix for both states. Doctor never edits the user's own `disableAllHooks`. One `claude plugin list` call (about 1.8 s) serves the list check and the status. A settings file that is not JSON is left to the host's own error. |
| D-NI-KIRO-GATE-1 | src/setup/engine.ts (kiroDisabledIssue, hasPluginIssue, hookRegisteredCheck), tests/v2/setup/kiro-gate.test.mjs (new), tests/v2/e2e/kiro-fire.test.mjs (new), docs/install/kiro.md | Real kiro-cli 2.35.2 (V3, temp HOME, macOS standalone tarball https://prod.download.cli.kiro.dev/stable/2.35.2/, sha256 98d7a181...): the loader logs hooks.reload.loaded {read:6,registered:6} for our file, also when two entries carry "enabled": false; docs (kiro.dev/docs/cli/v3/hooks-migration, hooks[].enabled) say a false entry is skipped. Workspace trust flag, --trust-workspace and a workspace-only copy of the file changed nothing in the loaded count. A disabled own entry looked installed (doctor said only 'not set up'). No key: every engine stops at the model-list call (fake KIRO_API_KEY, api.q.service override ignored for GetProfile), so no hook fire was seen; ACP `_kiro.dev/commands/execute` has no handler. | Doctor FAILs hook-registered with a one-line fix naming the disabled own hook(s); setup rewrites only our entries back to enabled (user entries untouched). kiro-fire.test.mjs drives the real binary (skips when absent) and asserts read == registered == entries written. Red first: 1 of 4 failed (output kept). Fires: not live-proven. |
| D-NI-ZCODE-GATE-1 | src/setup/zcode-gate.ts (new), src/setup/engine.ts (verifyRow), tests/v2/setup/zcode-gate.test.mjs (new), tests/v2/e2e/zcode-fire.test.mjs (new), docs/install/zcode.md | zcode 0.17.0 (zai-org/ZCode 3c5b2276, built from source; live with a fake local OpenAI-compatible provider via ~/.zcode/v2/provider_config.json): user-scope hooks in ~/.zcode/cli/config.json run with no trust step and the model sees our redirect (178 bytes, not 208 KB). One key that zcode's zod schema rejects (ui.locale=12345, logging="loud") makes zcode log config.file.invalid and drop the whole file, hooks included, while the file still parses as JSON and doctor said PASS. Doctor now FAILs hook-registered with the key and a one-line fix; setup never edits a user's other keys. Tests: 12 red, 17 green. | Doctor behaviour change for zcode only; no setup write change. |
+4 -1
View File
@@ -2,6 +2,7 @@
// ADR-0019 section 3 steps: preflight, detect, plan, apply, verify, rollback per agent, summary. No UI here.
// Owner decisions D3 (hook overhead budget) and D4 (v1 forms replaced by the absolute form).
import { geminiSettingsGate } from "./gemini-gate.ts";
import { zcodeConfigGate } from "./zcode-gate.ts";
import { piSettingsGate } from "./pi-gate.ts";
import { vscodeSettingsGate } from "./vscode-gate.ts";
import { qwenHooksOff } from "./qwen-gate.ts";
@@ -811,7 +812,9 @@ async function verifyRow(row: CheckRow, ctx: SetupContext): Promise<Check[]> {
// D-NI-PI-GATE-1: a packages[] extensions filter keeps pi from loading the listed package's hooks.
if (row.id === "pi") return withHookGate(checks, piSettingsGate(env, ctx.home, ctx.pkgDir, process.cwd()));
// D-NI-VSCODE-GATE-1: chat.useHooks false, a hookFilesLocations that drops ~/.copilot/hooks, or a managed policy keeps VS Code from running the hook file.
return row.id === "vscode" ? withHookGate(checks, vscodeSettingsGate(env, ctx.home, process.cwd())) : checks;
if (row.id === "vscode") return withHookGate(checks, vscodeSettingsGate(env, ctx.home, process.cwd()));
// D-NI-ZCODE-GATE-1: one key zcode's schema rejects makes it drop the whole config.json, hooks included.
return row.id === "zcode" ? withHookGate(checks, zcodeConfigGate(ctx.home)) : checks;
}
// ---------- apply, backup, rollback ----------
+116
View File
@@ -0,0 +1,116 @@
// D-NI-ZCODE-GATE-1: zcode 0.17.0 (zai-org/ZCode 3c5b2276, built from source, live with a fake local provider) reads
// ~/.zcode/cli/config.json through one zod schema (apps/zcode-cli/packages/adapters/src/config/schema.ts). One invalid key
// makes it log "config.file.invalid Config file failed to load" and use no key of the file: our hooks never run, and the
// file still parses as JSON. User-scope hooks need no workspace trust (only project zcode.json hooks do, 09-hooks.md).
// This file mirrors the schema for the keys that can sink the file. Doctor reads it and never writes a user's key.
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { parseHostConfig } from "../core/ops/host-config.ts";
import { hostText } from "../core/ops/host-text.ts";
const OWN_AGENT = "zcode";
const EVENTS: readonly string[] = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PostToolUseFailure", "Stop"];
const HOOK_TYPES: readonly string[] = ["process", "command"];
type Bad = { key: string; why: string } | undefined;
type Obj = Record<string, unknown>;
const isObj = (v: unknown): v is Obj => typeof v === "object" && v !== null && !Array.isArray(v);
const isPositive = (v: unknown): boolean => typeof v === "number" && Number.isFinite(v) && v > 0;
const isText = (v: unknown): boolean => typeof v === "string" && v.length > 0;
const isTexts = (v: unknown): boolean => Array.isArray(v) && v.every((x) => typeof x === "string");
/** An optional key: absent is fine, present must pass `ok`. */
function field(o: Obj, at: string, name: string, ok: (v: unknown) => boolean, why: string): Bad {
const v = o[name];
return v === undefined || ok(v) ? undefined : { key: `${at}.${name}`, why };
}
function section(doc: Obj, name: string): { o?: Obj; bad?: Bad } {
const v = doc[name];
if (v === undefined) return {};
return isObj(v) ? { o: v } : { bad: { key: name, why: "must be an object" } };
}
const oneOf = (allowed: readonly unknown[]) => (v: unknown): boolean => allowed.includes(v);
const isBool = (v: unknown): boolean => typeof v === "boolean";
function firstBad(...checks: Bad[]): Bad { return checks.find((c) => c !== undefined); }
function simple(doc: Obj, name: string, rules: [string, (v: unknown) => boolean, string][]): Bad {
const s = section(doc, name);
if (s.bad) return s.bad;
if (!s.o) return undefined;
return firstBad(...rules.map(([k, ok, why]) => field(s.o as Obj, name, k, ok, why)));
}
function hookBad(h: unknown, at: string): Bad {
if (!isObj(h)) return { key: at, why: "must be an object" };
if (!HOOK_TYPES.includes(h.type as string)) return { key: `${at}.type`, why: "must be process or command" };
return firstBad(
isText(h.command) ? undefined : { key: `${at}.command`, why: "must be a non-empty string" },
field(h, at, "enabled", isBool, "must be a boolean"),
field(h, at, "timeoutMs", isPositive, "must be a positive number"),
field(h, at, "timeout", isPositive, "must be a positive number"),
field(h, at, "async", isBool, "must be a boolean"),
field(h, at, "args", isTexts, "must be an array of strings"),
field(h, at, "statusMessage", isText, "must be a non-empty string"),
);
}
const GROUP_KEYS: readonly string[] = ["matcher", "hooks"];
function groupBad(g: unknown, at: string): Bad {
if (!isObj(g)) return { key: at, why: "must be an object" };
const extra = Object.keys(g).find((k) => !GROUP_KEYS.includes(k));
if (extra !== undefined) return { key: at, why: `has the unknown key ${extra}` };
if (!Array.isArray(g.hooks) || g.hooks.length === 0) return { key: at, why: "needs a non-empty hooks array" };
const m = field(g, at, "matcher", isText, "must be a non-empty string");
if (m) return m;
for (let i = 0; i < g.hooks.length; i++) { const b = hookBad(g.hooks[i], `${at}.hooks[${i}]`); if (b) return b; }
return undefined;
}
const HOOK_ROOT_KEYS: readonly string[] = ["enabled", "timeoutMs", "maxOutputBytes", "events"];
function hooksBad(doc: Obj): Bad {
const s = section(doc, "hooks");
if (s.bad) return s.bad;
const h = s.o;
if (!h) return undefined;
const extra = Object.keys(h).find((k) => !HOOK_ROOT_KEYS.includes(k));
if (extra !== undefined) return { key: `hooks.${extra}`, why: "is not a hooks key" };
const root = firstBad(field(h, "hooks", "enabled", isBool, "must be a boolean"), field(h, "hooks", "timeoutMs", isPositive, "must be a positive number"), field(h, "hooks", "maxOutputBytes", isPositive, "must be a positive number"));
if (root || h.events === undefined) return root;
if (!isObj(h.events)) return { key: "hooks.events", why: "must be an object" };
for (const [ev, groups] of Object.entries(h.events)) {
if (!EVENTS.includes(ev)) return { key: `hooks.events.${ev}`, why: "is not a zcode hook event" };
if (!Array.isArray(groups)) return { key: `hooks.events.${ev}`, why: "must be an array of matcher groups" };
for (let i = 0; i < groups.length; i++) { const b = groupBad(groups[i], `hooks.events.${ev}[${i}]`); if (b) return b; }
}
return undefined;
}
/** The first key zcode's schema rejects in this config.json (undefined: the schema accepts the keys checked here). */
export function zcodeSchemaBad(doc: unknown): Bad {
if (!isObj(doc)) return { key: "(root)", why: "must be a JSON object" };
return firstBad(
simple(doc, "modelStream", [["idleTimeoutMs", isPositive, "must be a positive number"]]),
simple(doc, "permission", [["mode", oneOf(["plan", "build", "edit", "yolo", "guarded", "auto"]), "must be plan, build, edit, yolo, guarded or auto"], ["allowedTools", isTexts, "must be an array of strings"], ["disallowedTools", isTexts, "must be an array of strings"], ["autoApproveHighRisk", isBool, "must be a boolean"], ["allowMediumRiskInAuto", isBool, "must be a boolean"]]),
simple(doc, "features", ["compact", "rewind", "subagent", "memory", "skill", "mcp"].map((k): [string, (v: unknown) => boolean, string] => [k, isBool, "must be a boolean"])),
simple(doc, "memory", [["use", isBool, "must be a boolean"]]),
simple(doc, "logging", [["level", oneOf(["debug", "info", "warn", "error"]), "must be debug, info, warn or error"], ["format", oneOf(["text", "json"]), "must be text or json"]]),
simple(doc, "ui", [["locale", oneOf(["auto", "en-US", "zh-CN"]), "must be auto, en-US or zh-CN"], ["theme", oneOf(["auto", "dark", "light"]), "must be auto, dark or light"]]),
simple(doc, "toolConcurrency", [["maxConcurrency", isPositive, "must be a positive number"]]),
hooksBad(doc),
);
}
/** One line (what stops the hooks, and the fix), or undefined when zcode would load the file. */
export function zcodeConfigGate(home: string): string | undefined {
const file = path.join(home, ".zcode", "cli", "config.json");
if (!existsSync(file)) return undefined;
let doc: unknown;
try { doc = parseHostConfig(OWN_AGENT, file, hostText(readFileSync(file, "utf8")), "json"); }
catch { return undefined; } // an unreadable file is reported by the parse check
const bad = zcodeSchemaBad(doc);
if (!bad) return undefined;
return `${file}: ${bad.key} ${bad.why}, so zcode drops the whole config.json and runs no context-mode hook; fix or remove that key`;
}
+107
View File
@@ -0,0 +1,107 @@
// D-NI-ZCODE-GATE-1: the real zcode CLI (0.17.0, built from zai-org/ZCode; no npm package exists) against a local fake
// OpenAI-compatible provider (provider_config.json, api.type openai-chat-completions). The fake answers with one Bash call
// "cat big.log" (208 KB file), then a final text. context-mode is installed with its own `setup --agents zcode` into a temp
// HOME; the hook must block the call and the model must see the redirect, not the file. Then the gate doctor reports (one
// invalid key in config.json) is switched on and the model must see the file again.
// Skipped unless ZCODE_CLI_BUNDLE points at zcode.cjs (apps/zcode-cli/packages/cli/dist/zcode.cjs) or `zcode` is on PATH.
import { test } from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
const BUILD = resolve("build/build.mjs");
const BUNDLE = process.env.ZCODE_CLI_BUNDLE;
const onPath = spawnSync("zcode", ["--version"], { stdio: "ignore" }).status === 0;
const cmd = BUNDLE && existsSync(BUNDLE) ? [process.execPath, BUNDLE] : onPath ? ["zcode"] : undefined;
const RUN_MS = 100000;
function provider(command, bodies) {
return http.createServer((req, res) => {
let b = "";
req.on("data", (d) => { b += d; });
req.on("end", () => {
bodies.push(b);
let answered = false;
try { answered = (JSON.parse(b).messages ?? []).some((m) => m.role === "tool"); } catch { /* not JSON */ }
const chunk = (delta, fin) => `data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "fake", choices: [{ index: 0, delta, finish_reason: fin ?? null }] })}\n\n`;
res.writeHead(200, { "content-type": "text/event-stream" });
if (!answered) {
res.write(chunk({ role: "assistant", content: null, tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "Bash", arguments: JSON.stringify({ command }) } }] }));
res.write(chunk({}, "tool_calls"));
} else {
res.write(chunk({ role: "assistant", content: "done" }));
res.write(chunk({}, "stop"));
}
res.write(`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "fake", choices: [], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } })}\n\n`);
res.write("data: [DONE]\n\n");
res.end();
});
});
}
/** The tool message the model got for the Bash call ("" when zcode never sent one). */
async function fire(t, { command = "cat big.log", edit } = {}) {
const d = mkdtempSync(join(tmpdir(), "cm-zcfire-"));
t.after(() => rmSync(d, { recursive: true, force: true }));
const home = join(d, "home");
const work = join(d, "work");
const pkg = join(d, "pkg");
mkdirSync(home, { recursive: true });
mkdirSync(work);
writeFileSync(join(work, "big.log"), "line lorem ipsum dolor sit amet\n".repeat(6500));
const built = spawnSync(process.execPath, [BUILD, "--out", pkg], { encoding: "utf8" });
assert.equal(built.status, 0, built.stderr);
const bodies = [];
const srv = provider(command, bodies);
await new Promise((r) => srv.listen(0, "127.0.0.1", r));
t.after(() => srv.close());
const env = { PATH: process.env.PATH, HOME: home, USERPROFILE: home, ZCODE_DATA_BASE_DIR: home };
mkdirSync(join(home, ".zcode", "v2"), { recursive: true });
writeFileSync(join(home, ".zcode", "v2", "provider_config.json"), JSON.stringify({ schemaVersion: 1, config: {
providerConfigRules: { providerRules: [{ providerId: "fake", providerName: "Fake", config: { group: "standard-personal", access: { type: "api-key", apiKey: "fake" },
api: { type: "openai-chat-completions", baseUrl: `http://127.0.0.1:${srv.address().port}/v1` }, personalModelIds: ["fake-model"] } }] },
modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] },
defaultModelSelection: { providerId: "fake", modelId: "fake-model" } } }));
const setup = spawnSync(process.execPath, [join(pkg, "cli.mjs"), "setup", "--yes", "--agents", "zcode"], { env, encoding: "utf8", timeout: 120000 });
assert.equal(setup.status, 0, `${setup.stdout}${setup.stderr}`);
if (edit) {
const file = join(home, ".zcode", "cli", "config.json");
const doc = JSON.parse(readFileSync(file, "utf8"));
edit(doc);
writeFileSync(file, JSON.stringify(doc, null, 2));
}
await new Promise((resolveRun) => {
const c = spawn(cmd[0], [...cmd.slice(1), "--prompt", "show the log", "--cwd", work, "--mode", "yolo", "--json", "--no-color"], { cwd: work, env, stdio: "ignore" });
const k = setTimeout(() => c.kill(), RUN_MS);
c.on("close", () => { clearTimeout(k); resolveRun(); });
});
for (const body of bodies) {
let j;
try { j = JSON.parse(body); } catch { continue; }
for (const m of j.messages ?? []) if (m.role === "tool") return typeof m.content === "string" ? m.content : JSON.stringify(m.content);
}
return "";
}
const opts = { skip: !cmd && "no zcode binary: set ZCODE_CLI_BUNDLE to zcode.cjs or put zcode on PATH", timeout: 200000 };
test("D-NI-ZCODE-GATE-1: zcode Bash cat of a large log is replaced and the model sees the ctx_execute redirect", opts, async (t) => {
const out = await fire(t);
assert.match(out, /ctx_execute/, out.slice(0, 400));
assert.ok(out.length < 4000, `the model got ${out.length} bytes, not the 208 KB file`);
});
test("D-NI-ZCODE-GATE-1: zcode bounded head of a large log is not replaced", opts, async (t) => {
const out = await fire(t, { command: "head -n 3 big.log" });
assert.doesNotMatch(out, /ctx_execute/, out.slice(0, 400));
assert.ok(out.includes("lorem ipsum"), out.slice(0, 400));
});
test("D-NI-ZCODE-GATE-1: one invalid key (ui.locale) makes zcode drop the whole config.json, hooks included (the gate doctor reports)", opts, async (t) => {
const out = await fire(t, { edit: (doc) => { doc.ui = { locale: 12345 }; } });
assert.doesNotMatch(out, /context-mode: /, out.slice(0, 400));
assert.ok(out.length > 1000, `${out.length}`);
});
+117
View File
@@ -0,0 +1,117 @@
// D-NI-ZCODE-GATE-1: zcode 0.17.0 (zai-org/ZCode 3c5b2276, built from source, live with a fake local provider) loads
// ~/.zcode/cli/config.json through a zod schema; ONE invalid key anywhere in the file (ui.locale=12345, logging="loud")
// makes it log "config.file.invalid Config file failed to load" and use NO key of the file, so our hooks never run, while
// the file still parses as JSON. User-scope hooks need no workspace trust (only project zcode.json hooks do, 09-hooks.md).
// Doctor must FAIL with the key and a one-line fix; setup writes nothing to a user's other keys.
import { test } from "node:test";
import assert from "node:assert/strict";
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { TOOL_ORDER } from "../../../src/core/contracts/constants.ts";
import { generateManifests } from "../../../build/manifests.ts";
import { runDoctor, runSetup } from "../../../src/setup/index.ts";
const REPO = path.resolve(import.meta.dirname, "../../..");
function sandbox(t) {
const root = mkdtempSync(path.join(tmpdir(), "cm-zcode-gate-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const home = path.join(root, "home");
const pkgDir = path.join(root, "pkg");
mkdirSync(home, { recursive: true });
mkdirSync(pkgDir, { recursive: true });
writeFileSync(path.join(pkgDir, "server.mjs"), `
import { createInterface } from "node:readline";
const tools = ${JSON.stringify([...TOOL_ORDER])};
createInterface({ input: process.stdin }).on("line", (l) => {
const m = JSON.parse(l);
if (m.id === undefined) return;
const result = m.method === "initialize"
? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "context-mode", version: "2.0.0" } }
: { tools: tools.map((name) => ({ name, inputSchema: { type: "object" } })) };
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: m.id, result }) + "\\n");
});
`);
writeFileSync(path.join(pkgDir, "hook.mjs"), `let s = ""; process.stdin.on("data", (d) => { s += d; }); process.stdin.on("end", () => { const p = JSON.parse(s); if (!JSON.stringify(p).includes("context-mode-doctor-hook-runs")) return; const t = "deny: run ctx_execute; ctx_search( finds the rest"; process.stderr.write(t + "\\n"); process.stdout.write(JSON.stringify({ decision: "deny", reason: t })); });\n`);
writeFileSync(path.join(pkgDir, "package.json"), JSON.stringify({ name: "context-mode", version: "2.0.0" }));
generateManifests(pkgDir);
for (const rel of ["skills", path.join("pi", "skills"), path.join("claude-code", "skills")]) {
for (const k of ["ctx-doctor", "ctx-stats", "ctx-upgrade"]) cpSync(path.join(REPO, "skills", k), path.join(pkgDir, rel, k), { recursive: true });
}
return { home, pkgDir, env: { PATH: "/usr/bin:/bin", HOME: home, USERPROFILE: home, CM_HOOK_OVERHEAD_BUDGET_MS: "60000" } };
}
const file = (home) => path.join(home, ".zcode", "cli", "config.json");
const cfg = (home) => JSON.parse(readFileSync(file(home), "utf8"));
const put = (home, doc) => writeFileSync(file(home), JSON.stringify(doc, null, 2));
async function doctorAfterSetup(t, edit) {
const s = sandbox(t);
await runSetup({ home: s.home, pkgDir: s.pkgDir, env: s.env, agents: ["zcode"], runId: "z" });
if (edit) { const doc = cfg(s.home); edit(doc); put(s.home, doc); }
const d = await runDoctor({ home: s.home, pkgDir: s.pkgDir, env: s.env, agents: ["zcode"] });
return d.agents[0];
}
const reg = (a) => a.checks.find((c) => c.name === "hook-registered");
test("D-NI-ZCODE-GATE-1: a clean setup passes doctor", async (t) => {
const a = await doctorAfterSetup(t);
assert.equal(a.status, "PASS", JSON.stringify(a));
});
const BAD = [
["ui.locale not in auto|en-US|zh-CN", (d) => { d.ui = { locale: 12345 }; }, "ui.locale"],
["ui.theme not in auto|dark|light", (d) => { d.ui = { theme: "blue" }; }, "ui.theme"],
["logging is a string", (d) => { d.logging = "loud"; }, "logging"],
["logging.level not in debug|info|warn|error", (d) => { d.logging = { level: "trace" }; }, "logging.level"],
["permission.mode unknown", (d) => { d.permission = { mode: "wild" }; }, "permission.mode"],
["features.memory not a boolean", (d) => { d.features.memory = "yes"; }, "features.memory"],
["modelStream.idleTimeoutMs not positive", (d) => { d.modelStream = { idleTimeoutMs: -1 }; }, "modelStream.idleTimeoutMs"],
["hooks has an unknown key (strict)", (d) => { d.hooks.disabled = true; }, "hooks.disabled"],
["hooks.events has an unknown event (strict)", (d) => { d.hooks.events.OnSave = []; }, "hooks.events.OnSave"],
["a hook group has an unknown key (strict)", (d) => { d.hooks.events.SessionStart.push({ hooks: [{ type: "command", command: "echo user" }], when: "x" }); }, "hooks.events.SessionStart"],
["a hook group holds no hook", (d) => { d.hooks.events.UserPromptSubmit.push({ hooks: [] }); }, "hooks.events.UserPromptSubmit"],
["a hook has an unknown type", (d) => { d.hooks.events.SessionStart.push({ hooks: [{ type: "http", command: "x" }] }); }, "hooks.events.SessionStart"],
];
for (const [name, edit, key] of BAD) {
test(`D-NI-ZCODE-GATE-1: doctor FAILs when ${name} (zcode drops the whole config.json, hooks included)`, async (t) => {
const a = await doctorAfterSetup(t, edit);
assert.equal(a.status, "FAIL", JSON.stringify(a));
const c = reg(a);
assert.equal(c.ok, false, JSON.stringify(a.checks));
assert.ok(c.detail.includes(key), c.detail);
assert.ok(c.detail.includes("config.json"), c.detail);
});
}
test("D-NI-ZCODE-GATE-1: hooks.enabled=false FAILs doctor", async (t) => {
const a = await doctorAfterSetup(t, (d) => { d.hooks.enabled = false; });
assert.equal(a.status, "FAIL", JSON.stringify(a));
});
test("D-NI-ZCODE-GATE-1: our hook entry with enabled=false FAILs doctor", async (t) => {
const a = await doctorAfterSetup(t, (d) => { d.hooks.events.PreToolUse[0].hooks[0].enabled = false; });
assert.equal(a.status, "FAIL", JSON.stringify(a));
});
test("D-NI-ZCODE-GATE-1: valid user keys and unknown top-level keys (zcode passes them through) keep PASS", async (t) => {
const a = await doctorAfterSetup(t, (d) => {
d.ui = { locale: "zh-CN", theme: "dark" };
d.logging = { level: "debug", format: "json" };
d.permission = { mode: "yolo" };
d.someFutureKey = { anything: 1 };
d.hooks.timeoutMs = 20000;
});
assert.equal(a.status, "PASS", JSON.stringify(a));
});
test("D-NI-ZCODE-GATE-1: setup leaves the user's other keys byte for byte (it never repairs them)", async (t) => {
const s = sandbox(t);
mkdirSync(path.dirname(file(s.home)), { recursive: true });
put(s.home, { ui: { locale: 12345 } });
await runSetup({ home: s.home, pkgDir: s.pkgDir, env: s.env, agents: ["zcode"], runId: "z" });
assert.deepEqual(cfg(s.home).ui, { locale: 12345 });
});