import assert from "node:assert/strict"; import { lstatSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { test } from "node:test"; import { assertKind, delegateConfigRevision, resolveCheckpointAgent, saveCheckpointSettings, loadDelegateConfig, mergeDelegateConfig, parseDelegateConfig, parseCompletionHook, resolveAgent, saveDelegatePatch, type DelegateConfig, } from "../config.ts"; const shippedPath = join(dirname(fileURLToPath(import.meta.url)), "..", "config.json"); function shipped(): DelegateConfig { return parseDelegateConfig(JSON.parse(readFileSync(shippedPath, "utf8")), shippedPath); } test("kind validation", () => { assert.equal(assertKind("recon"), "recon"); assert.equal(assertKind("scout"), "scout"); assert.equal(assertKind("docs"), "docs"); for (const kind of ["", "../role", "__proto__", "a".repeat(65), 1]) assert.throws(() => assertKind(kind), /kind must/); }); test("shipped config parses four agents", () => { const config = shipped(); assert.deepEqual(Object.keys(config.agents), ["recon", "implement", "review", "oracle"]); assert.equal(config.maxTaskChars, 20000); assert.equal(config.maxConcurrent, 8); assert.equal(config.maxLocalConcurrent, 1); assert.equal(config.maxQueued, 16); assert.equal(config.checkIntervalMs, 60000); assert.equal(config.hardTimeoutMs, 0); assert.equal("responseTemplate" in config.agents.recon, false); assert.equal("saveToFile" in config.agents.recon, false); assert.equal("offline" in config.agents.recon, false); assert.equal("offline" in config.agents.implement, false); assert.ok(config.agents.implement.tools.includes("edit")); assert.equal(config.agents.implement.model, "openai-codex/gpt-6.1-sol"); assert.equal(config.agents.implement.thinking, "medium"); assert.equal(config.agents.review.model, "openai-codex/gpt-6.1-sol"); assert.equal(config.agents.review.thinking, "high"); assert.equal(config.agents.oracle.thinking, "high"); }); test("resolved model, tools and prompt come from role configuration", () => { const config = shipped(); const resolved = resolveAgent("implement", config); assert.equal(resolved.model, config.agents.implement.model); assert.deepEqual(resolved.agent.tools, config.agents.implement.tools); assert.equal(resolved.agent.prompt, config.agents.implement.prompt); assert.equal(resolved.agent.thinking, "medium"); assert.equal(resolveAgent("recon", config).model, config.agents.recon.model); assert.equal(resolveAgent("review", config).model, config.agents.review.model); }); test("disabled roles reject launches while other roles and explicit re-enabling work", () => { const base = shipped(); assert.equal(base.agents.implement.enabled, true); assert.deepEqual(base.agents.review.tools, ["read", "grep", "find", "ls", "bash"]); const disabled = mergeDelegateConfig(base, { agents: { implement: { enabled: false } } }, "overlay.json"); assert.throws(() => resolveAgent("implement", disabled), /implement is disabled/); assert.equal(resolveAgent("review", disabled).model, base.agents.review.model); const enabled = mergeDelegateConfig(disabled, { agents: { implement: { enabled: true } } }, "overlay.json"); assert.equal(resolveAgent("implement", enabled).agent.enabled, true); for (const enabled of [null, "false", 0]) { assert.throws(() => mergeDelegateConfig(base, { agents: { implement: { enabled } } }, "bad"), /enabled.*boolean/); } }); test("role configuration accepts local and hosted model IDs", () => { const config = mergeDelegateConfig(shipped(), { agents: { oracle: { model: "local-qwen38/qwen38-q4km" }, recon: { model: "openai-codex/gpt-5.6-luna" }, } }, "overlay.json"); assert.equal(resolveAgent("oracle", config).model, "local-qwen38/qwen38-q4km"); assert.equal(resolveAgent("recon", config).model, "openai-codex/gpt-5.6-luna"); }); test("user overlay overrides one model", () => { const config = shipped(); const merged = mergeDelegateConfig( config, { maxLocalConcurrent: 1, agents: { recon: { model: "ollama/qwen3" } } }, "overlay.json", ); assert.equal(merged.maxLocalConcurrent, 1); assert.equal(merged.maxQueued, config.maxQueued); assert.equal(merged.agents.recon.model, "ollama/qwen3"); assert.deepEqual(merged.agents.recon.tools, config.agents.recon.tools); assert.equal("offline" in merged.agents.recon, false); assert.equal(merged.agents.implement.model, config.agents.implement.model); const responseTemplate = " Summary:\n{{literal}}\n"; const output = mergeDelegateConfig(merged, { agents: { recon: { responseTemplate, saveToFile: true } } }, "output.json"); assert.equal(output.agents.recon.responseTemplate, responseTemplate); assert.equal(output.agents.recon.saveToFile, true); assert.deepEqual(mergeDelegateConfig(output, { agents: { recon: { model: "hosted/other" } } }, "model.json").agents.recon, { ...output.agents.recon, model: "hosted/other" }); const blank = mergeDelegateConfig(output, { agents: { recon: { responseTemplate: "" } } }, "blank.json"); assert.equal(blank.agents.recon.responseTemplate, ""); assert.equal(blank.agents.recon.saveToFile, true); const off = mergeDelegateConfig(output, { agents: { recon: { saveToFile: false } } }, "off.json"); assert.equal(off.agents.recon.saveToFile, false); assert.equal(off.agents.recon.responseTemplate, responseTemplate); const schema = { type: "object", properties: { summary: { type: "string" } }, required: ["summary"], additionalProperties: false }; const typed = mergeDelegateConfig(output, { agents: { recon: { responseSchema: schema, responseRepairAttempts: 0 } } }, "schema.json"); assert.deepEqual(typed.agents.recon.responseSchema, schema); schema.required.push("mutated"); assert.deepEqual((typed.agents.recon.responseSchema as any).required, ["summary"]); assert.deepEqual(mergeDelegateConfig(typed, {}, "inherited.json").agents.recon, typed.agents.recon); assert.equal(mergeDelegateConfig(typed, { agents: { recon: { responseSchema: null } } }, "disabled.json").agents.recon.responseSchema, null); assert.equal(mergeDelegateConfig(typed, { agents: { recon: { responseSchema: false } } }, "false.json").agents.recon.responseSchema, false); }); test("legacy context settings are accepted but ignored in defaults and overlays", () => { const base = shipped(); for (const context of [[], ["git-diff"], [{ source: "git-changed-files" }], "obsolete", null]) { const legacy = { ...base, agents: { ...base.agents, review: { ...base.agents.review, context } } }; assert.deepEqual(parseDelegateConfig(legacy, "legacy.json"), base); assert.deepEqual(mergeDelegateConfig(base, { agents: { review: { context } } }, "overlay.json"), base); } for (const offline of [true, false, "obsolete"]) { const legacy = { ...base, agents: { ...base.agents, recon: { ...base.agents.recon, offline } } }; assert.deepEqual(parseDelegateConfig(legacy, "legacy.json"), base); assert.deepEqual(mergeDelegateConfig(base, { agents: { recon: { offline } } }, "overlay.json"), base); } }); test("new overlay agents require a model and prompt", () => { assert.throws( () => mergeDelegateConfig(shipped(), { agents: { scout: { model: "x" } } }, "overlay.json"), /prompt/, ); assert.throws(() => resolveAgent("missing", shipped()), /unknown role/); assert.throws(() => resolveAgent("constructor", shipped()), /unknown role/); }); test("load uses shipped when user file missing", () => { const loaded = loadDelegateConfig({ shippedPath, userPath: join(tmpdir(), "pi-delegate-missing-user.json"), }); assert.deepEqual(loaded, shipped()); }); test("load merges user overlay file", () => { const dir = mkdtempSync(join(tmpdir(), "pi-delegate-config-")); const userPath = join(dir, "delegate.json"); writeFileSync(userPath, JSON.stringify({ agents: { implement: { model: "llama.cpp/qwen" } } })); const loaded = loadDelegateConfig({ shippedPath, userPath }); assert.equal(loaded.agents.implement.model, "llama.cpp/qwen"); assert.equal(loaded.agents.recon.model, shipped().agents.recon.model); }); test("model saves preserve overlays, reject stale/invalid config, and keep symlink targets", () => { const dir = mkdtempSync(join(tmpdir(), "pi-delegate-model-config-")); const userPath = join(dir, "delegate.json"); const paths = { shippedPath, userPath }; try { const current = shipped().agents.recon; const patch = { model: "hosted/first" }; saveDelegatePatch(paths, "recon", current, patch); assert.deepEqual(JSON.parse(readFileSync(userPath, "utf8")), { agents: { recon: patch } }); const overlay = { maxConcurrent: 3, note: "keep", agents: { recon: { ...patch, prompt: "Custom recon prompt\nPreserve this text.", responseTemplate: " Summary:\n{{literal}}\n", saveToFile: true, thinking: "medium", tools: ["read"], context: ["git-diff"], note: "keep role", offline: true }, review: { model: "other/review" }, docs: { model: "hosted/docs", prompt: "Write documentation.", context: [{ source: "git-changed-files" }] }, } }; writeFileSync(userPath, JSON.stringify(overlay)); const live = loadDelegateConfig(paths).agents.recon; const local = { model: "ollama/team/model" }; saveDelegatePatch(paths, "recon", live, local); assert.deepEqual(JSON.parse(readFileSync(userPath, "utf8")), { ...overlay, agents: { ...overlay.agents, recon: { ...overlay.agents.recon, ...local }, } }); const before = readFileSync(userPath, "utf8"); assert.throws(() => saveDelegatePatch(paths, "recon", live, { model: "hosted/stale" }), /changed on disk/); assert.equal(readFileSync(userPath, "utf8"), before); for (const bad of ["{broken", '{"agents":{"recon":false}}']) { writeFileSync(userPath, bad); assert.throws(() => saveDelegatePatch(paths, "recon", live, { model: "hosted/new" })); assert.equal(readFileSync(userPath, "utf8"), bad); } writeFileSync(userPath, before); if (process.platform !== "win32") { const link = join(dir, "linked.json"); symlinkSync(userPath, link); saveDelegatePatch({ shippedPath, userPath: link }, "recon", loadDelegateConfig(paths).agents.recon, { model: "hosted/symlink" }); assert.equal(lstatSync(link).isSymbolicLink(), true); assert.equal(loadDelegateConfig(paths).agents.recon.model, "hosted/symlink"); const defaults = join(dir, "defaults.json"), alias = join(dir, "defaults-link.json"); writeFileSync(defaults, readFileSync(shippedPath, "utf8")); symlinkSync(defaults, alias); assert.throws(() => saveDelegatePatch({ shippedPath: defaults, userPath: alias }, "recon", current, { model: "hosted/new" }), /shipped delegate defaults/); assert.equal(readFileSync(defaults, "utf8"), readFileSync(shippedPath, "utf8")); } } finally { rmSync(dir, { recursive: true, force: true }); } }); test("reasoning saves only thinking and refuses stale reasoning without writing", () => { const dir = mkdtempSync(join(tmpdir(), "pi-delegate-thinking-")); const paths = { shippedPath, userPath: join(dir, "delegate.json") }; try { const overlay = { note: "keep", agents: { recon: { model: "hosted/unchanged", thinking: "low", prompt: "Custom prompt", offline: false, tools: ["read"], context: ["git-diff"] } } }; writeFileSync(paths.userPath, JSON.stringify(overlay)); const current = loadDelegateConfig(paths).agents.recon; saveDelegatePatch(paths, "recon", current, { thinking: "xhigh" }); assert.equal(loadDelegateConfig(paths).agents.recon.thinking, "xhigh"); assert.deepEqual(JSON.parse(readFileSync(paths.userPath, "utf8")), { ...overlay, agents: { recon: { ...overlay.agents.recon, thinking: "xhigh" } }, }); assert.equal(current.thinking, "low"); const before = readFileSync(paths.userPath, "utf8"); assert.throws(() => saveDelegatePatch(paths, "recon", current, { thinking: "off" }), /changed on disk/); assert.equal(readFileSync(paths.userPath, "utf8"), before); const changedModel = JSON.stringify({ ...overlay, agents: { recon: { ...overlay.agents.recon, model: "hosted/changed" } } }); writeFileSync(paths.userPath, changedModel); assert.throws(() => saveDelegatePatch(paths, "recon", current, { thinking: "max" }), /changed on disk/); assert.equal(readFileSync(paths.userPath, "utf8"), changedModel); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("broken shipped invariants refused", () => { const config = shipped(); for (const prompt of [null, "", " \n\t", 42, [], {}]) { assert.throws(() => mergeDelegateConfig(config, { agents: { recon: { prompt } } }, "bad"), /prompt.*non-empty string/); } for (const extensions of [null, "true", 1, []]) { assert.throws(() => mergeDelegateConfig(config, { agents: { recon: { extensions } } }, "bad"), /extensions.*boolean/); } for (const [field, values, expected] of [ ["responseTemplate", [null, true, 42, [], {}], /responseTemplate.*string/], ["saveToFile", [null, "true", 1, [], {}], /saveToFile.*boolean/], ["responseSchema", ["{}", 1, [], { type: "strnig" }, { unknownKeyword: true }, { $async: true }, { $ref: "https://example.com/schema" }], /responseSchema/], ["responseRepairAttempts", [null, -1, 3, 1.5, "2"], /responseRepairAttempts/], ] as const) { for (const value of values) { assert.throws(() => mergeDelegateConfig(config, { agents: { recon: { [field]: value } } }, "bad"), expected); assert.throws(() => parseDelegateConfig({ ...config, agents: { ...config.agents, recon: { ...config.agents.recon, [field]: value } } }, "bad"), expected); } } const { prompt: _prompt, ...withoutPrompt } = config.agents.recon; assert.throws(() => parseDelegateConfig({ ...config, agents: { ...config.agents, recon: withoutPrompt } }, "bad"), /prompt.*non-empty string/); const valid = config as unknown as Record; assert.throws( () => parseDelegateConfig({ ...valid, maxTaskChars: 0 }, "x"), /maxTaskChars/, ); assert.throws( () => parseDelegateConfig({ ...valid, maxLocalConcurrent: 0 }, "x"), /maxLocalConcurrent/, ); assert.throws( () => parseDelegateConfig( { ...valid, agents: { ...(valid.agents as object), recon: { model: "", tools: ["read"], thinking: "off" } } }, "x", ), /model/, ); }); test("checkpoint defaults, field overlays and safe advisor resolution", () => { const base = shipped(); assert.deepEqual(base.checkpoints, { enabled: false, role: "goldfish", interval: 10 }); assert.throws(() => resolveCheckpointAgent(base), /unknown role goldfish/); const configured = mergeDelegateConfig(base, { checkpoints: { enabled: true, interval: 1000 } }, "checkpoints"); assert.deepEqual(configured.checkpoints, { enabled: true, role: "goldfish", interval: 1000 }); assert.deepEqual(mergeDelegateConfig(configured, { checkpoints: { interval: 1 } }, "partial").checkpoints, { enabled: true, role: "goldfish", interval: 1 }); for (const checkpoints of [null, [], false, 10, "on", { enabled: null }, { enabled: "true" }, { enabled: 1 }, { role: null }, { role: "../bad" }, { role: 1 }, { interval: null }, { interval: "10" }, { interval: 0 }, { interval: 1001 }, { interval: 1.5 }, { interval: true }]) { assert.throws(() => parseDelegateConfig({ ...base, checkpoints }, "bad"), /checkpoints/); assert.throws(() => mergeDelegateConfig(base, { checkpoints }, "bad"), /checkpoints/); } const safe = mergeDelegateConfig(configured, { agents: { goldfish: { model: "hosted/advisor", prompt: "Advise", tools: [], extensions: false } } }, "safe"); assert.deepEqual(resolveCheckpointAgent(safe), resolveAgent("goldfish", safe)); for (const patch of [{ enabled: false }, { tools: ["read"] }, { tools: ["*"] }, { extensions: true }]) { const unsafe = mergeDelegateConfig(safe, { agents: { goldfish: patch } }, "unsafe"); assert.equal(unsafe.checkpoints.enabled, true); // Loading fails open; launch validation is separate. assert.throws(() => resolveCheckpointAgent(unsafe), /disabled|tools: \[\]/); } }); test("checkpoint saves share revisions with roles and preserve unrelated overlay fields", () => { const dir = mkdtempSync(join(tmpdir(), "pi-delegate-checkpoints-")); const paths = { shippedPath, userPath: join(dir, "delegate.json") }; try { const overlay = { note: "keep", checkpoints: { interval: 20, note: "keep checkpoint metadata" }, agents: { recon: { offline: true, context: ["legacy"], note: "keep role" } } }; writeFileSync(paths.userPath, JSON.stringify(overlay)); const config = loadDelegateConfig(paths); let revision = delegateConfigRevision(paths); revision = saveCheckpointSettings(paths, config.checkpoints, { enabled: true }, revision); assert.equal(revision, delegateConfigRevision(paths)); assert.deepEqual(JSON.parse(readFileSync(paths.userPath, "utf8")), { ...overlay, checkpoints: { ...overlay.checkpoints, enabled: true }, }); revision = saveDelegatePatch(paths, "recon", config.agents.recon, { thinking: "low" }, revision); assert.equal(revision, delegateConfigRevision(paths)); const current = loadDelegateConfig(paths).checkpoints; assert.deepEqual(current, { enabled: true, role: "goldfish", interval: 20 }); revision = saveCheckpointSettings(paths, current, { enabled: false }, revision); const before = readFileSync(paths.userPath, "utf8"); assert.throws(() => saveCheckpointSettings(paths, current, { interval: 10 }), /changed on disk/); for (const patch of [{ interval: 0 }, { enabled: null }, { role: "bad role" }]) { assert.throws(() => saveCheckpointSettings(paths, loadDelegateConfig(paths).checkpoints, patch as any, revision), /checkpoints/); } assert.equal(readFileSync(paths.userPath, "utf8"), before); writeFileSync(paths.userPath, before + " "); // Even unrelated external edits conflict. assert.throws(() => saveCheckpointSettings(paths, loadDelegateConfig(paths).checkpoints, { interval: 10 }, revision), /changed on disk/); assert.equal(readFileSync(paths.userPath, "utf8"), before + " "); const saved = JSON.parse(before); assert.deepEqual(saved.agents, { recon: { ...overlay.agents.recon, thinking: "low" } }); assert.equal(saved.note, overlay.note); assert.equal(saved.checkpoints.note, overlay.checkpoints.note); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("completion hooks validate bounded argv without shell parsing or filesystem checks", () => { assert.equal(parseCompletionHook(null), null); const command = ["/nonexistent executable", "", " ", "$(touch nope); | >", "line\narg"]; assert.deepEqual(parseCompletionHook({ command }), { command, timeoutMs: 10000 }); for (const timeoutMs of [1, 300000]) assert.deepEqual(parseCompletionHook({ command, timeoutMs }), { command, timeoutMs }); const malformed = [undefined, false, 1, "shell command", [], {}, { command: [] }, { command: [""] }, { command: [" "] }, { command: ["relative/path"] }, { command: ["./hook"] }, { command: ["/bin/hook\0"] }, { command: ["/bin/hook", "bad\0arg"] }, { command: ["/bin/hook", 1] }, { command: ["/bin/hook", null] }, { command: new Array(1) }, { command, shell: true }, { command, extra: undefined }, ...[null, false, "10000", 0, -1, 300001, 1.5, NaN, Infinity].map(timeoutMs => ({ command, timeoutMs }))]; for (const value of malformed) assert.throws(() => parseCompletionHook(value), /completionHook/); const parsed = parseCompletionHook({ command })!; command.push("mutated"); assert.equal(parsed.command.length, 5); }); test("completion hooks inherit, disable, snapshot and save for every named role across model changes", () => { const dir = mkdtempSync(join(tmpdir(), "pi-delegate-hooks-")); const paths = { shippedPath, userPath: join(dir, "delegate.json") }; try { let config = shipped(); assert.equal(Object.hasOwn(config.agents.recon, "completionHook"), false); saveDelegatePatch(paths, "writer", undefined, { model: "hosted/writer", prompt: "Write.", tools: [] }); config = loadDelegateConfig(paths); for (const kind of Object.keys(config.agents)) { const hook = { command: ["/nonexistent hook", "", kind], timeoutMs: 300000 }; saveDelegatePatch(paths, kind, config.agents[kind], { completionHook: hook }); config = loadDelegateConfig(paths); assert.deepEqual(config.agents[kind].completionHook, hook); const snapshot = structuredClone(config.agents[kind]); config.agents[kind].completionHook!.command.push("mutation"); assert.deepEqual(snapshot.completionHook, hook); config = loadDelegateConfig(paths); const inherited = mergeDelegateConfig(config, { agents: { [kind]: { model: "hosted/changed", completionHook: undefined } } }, "inherit"); assert.deepEqual(inherited.agents[kind].completionHook, hook); saveDelegatePatch(paths, kind, config.agents[kind], { model: "hosted/changed" }); config = loadDelegateConfig(paths); assert.deepEqual(config.agents[kind].completionHook, hook); const before = readFileSync(paths.userPath, "utf8"); for (const completionHook of [{ command: ["relative"] }, { command: ["/hook"], timeoutMs: 300001 }, { command: ["/hook"], shell: true }]) { assert.throws(() => mergeDelegateConfig(config, { agents: { [kind]: { completionHook } } }, "bad"), /completionHook/); assert.throws(() => parseDelegateConfig({ ...config, agents: { ...config.agents, [kind]: { ...config.agents[kind], completionHook } } }, "bad"), /completionHook/); assert.throws(() => saveDelegatePatch(paths, kind, config.agents[kind], { completionHook } as any), /completionHook/); } assert.equal(readFileSync(paths.userPath, "utf8"), before); saveDelegatePatch(paths, kind, config.agents[kind], { completionHook: null }); config = loadDelegateConfig(paths); assert.equal(config.agents[kind].completionHook, null); assert.equal(mergeDelegateConfig(config, { agents: { [kind]: { thinking: "off" } } }, "disabled").agents[kind].completionHook, null); } } finally { rmSync(dir, { recursive: true, force: true }); } });