Files
my-pi/pi-permission-system/test/config-loader.test.ts
T
云服务部-叶林立andDevin <158243242+devin-ai-integration[bot]@users.noreply.github.com> 7e6a8faae1 feat(pi-permission-system): AutoReview 改为跟随主模型的对话式工具调用审查
AutoReview:

- 审查器回到 Codex Guardian 风格的对话式审查,默认跟随会话当前主模型
  (每次审查实时读取 ctx.model);provider/model 必须同时设置才固定审查
  模型,只设其一视为配置错误并转人工。
- 结论只通过 approve / reject 两个工具给出,参数仅 reason;不强制
  toolChoice,正文文本(即使是合法 JSON)一律忽略。
- approve 自动放行;reject 转人工并在弹窗显示理由(标注模型生成)。
  超时、Provider 错误、截断、未调用工具、多次调用、参数无效等异常同样
  转人工,并附固定的系统说明;用户按 Esc 中止时直接拒绝。
- 模型调用改为 modelRegistry.streamSimple(...).result():Pi 1.3.0 面向
  扩展的 ModelRegistry 没有 completeSimple,原写法在真实环境中每次都会
  转人工。
- 对话记录保留可信度标注;工具结果在有更短的 pi-compaction 摘要时替换
  为摘要;token 估算改为非 ASCII 字符按 1 token 计;预算可配置。
- 同一条用户消息内完全相同的请求只缓存 approve 结论。
- 默认 reasoning low、总超时 30 秒、最多 2 次尝试、maxOutputTokens 4000。

删除:

- 未发布过的 TypeSafe Jev 分类器实现、DenialCircuitBreaker。
- 整个 annotator 机制(model-explanation、注册表、registerAnnotator、
  provider-timeout);annotators 配置键保留为已弃用并忽略,避免旧配置
  被拒绝。

测试:

- 新增 reviewer / transcript / 弹窗说明 / 默认配置测试;清理重复、恒真
  或只测实现细节的旧测试。
- 使用 deepseek-v4.1-flash 实测 5 个场景各 5 次,25 次结论全部符合预期。

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-19 01:54:17 -07:00

878 lines
28 KiB
TypeScript

import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
detectDeprecatedPreviewCaps,
loadAndMergeConfigs,
loadUnifiedConfig,
mergeUnifiedConfigs,
stripJsonComments,
} from "#src/config-loader";
describe("stripJsonComments", () => {
it("returns empty string for empty input", () => {
expect(stripJsonComments("")).toBe("");
});
it("passes through plain JSON unchanged", () => {
const input = '{"key": true}';
expect(stripJsonComments(input)).toBe(input);
});
it("drops a line comment body and preserves the trailing newline", () => {
// The space before // is emitted; the comment body is dropped; \n is kept.
expect(stripJsonComments('{ // comment\n"k": 1}')).toBe('{ \n"k": 1}');
});
it("drops a line comment that runs to EOF with no trailing newline", () => {
expect(stripJsonComments('{"k": 1} // trailing')).toBe('{"k": 1} ');
});
it("drops a block comment and nothing else", () => {
expect(stripJsonComments('{ /* block */ "k": 1}')).toBe('{ "k": 1}');
});
it("drops an unterminated block comment to EOF", () => {
expect(stripJsonComments("{ /* no close")).toBe("{ ");
});
it("preserves // inside a double-quoted string", () => {
expect(stripJsonComments('{"url": "http://example.com"}')).toBe(
'{"url": "http://example.com"}',
);
});
it("preserves block-comment markers inside a double-quoted string", () => {
expect(stripJsonComments('{"v": "a /* b */ c"}')).toBe(
'{"v": "a /* b */ c"}',
);
});
it("preserves // inside a single-quoted string", () => {
expect(stripJsonComments("{'url': 'http://x.com'}")).toBe(
"{'url': 'http://x.com'}",
);
});
it("preserves block-comment markers inside a single-quoted string", () => {
expect(stripJsonComments("{'v': 'a /* b */ c'}")).toBe(
"{'v': 'a /* b */ c'}",
);
});
it("honors a backslash-escaped quote so it does not close the string", () => {
// The string value is: a\"b (backslash-escaped double quote)
expect(stripJsonComments('{"k": "a\\"b"}')).toBe('{"k": "a\\"b"}');
});
it("emits an unterminated string to EOF verbatim", () => {
expect(stripJsonComments('{"k": "unterminated')).toBe(
'{"k": "unterminated',
);
});
it("preserves a lone slash that is not part of // or /*", () => {
expect(stripJsonComments('{"v": 1/2}')).toBe('{"v": 1/2}');
});
it("handles a combined JSONC document that round-trips to valid JSON", () => {
const jsonc = [
"{",
' "debugLog": true, // runtime knob',
' "permission": { /* the policy */ "*": "ask" }',
"}",
].join("\n");
const stripped = stripJsonComments(jsonc);
// Must parse without throwing
const parsed = JSON.parse(stripped) as Record<string, unknown>;
expect(parsed.debugLog).toBe(true);
expect(parsed.permission).toEqual({ "*": "ask" });
});
});
describe("loadUnifiedConfig", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "config-loader-test-"));
});
afterEach(() => {
rmSync(tempDir, { recursive: true, force: true });
});
it("parses a valid JSON file with runtime knobs and flat permission", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
debugLog: true,
permissionReviewLog: false,
yoloMode: true,
permission: {
"*": "ask",
read: "allow",
bash: { "git status": "allow" },
},
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.issues).toEqual([]);
expect(result.config.debugLog).toBe(true);
expect(result.config.permissionReviewLog).toBe(false);
expect(result.config.yoloMode).toBe(true);
expect(result.config.permission).toEqual({
"*": "ask",
read: "allow",
bash: { "git status": "allow" },
});
});
it("rejects the removed analysis key so a stale config cannot silently widen", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({ analysis: { threshold: 500 }, permission: { "*": "ask" } }),
);
const result = loadUnifiedConfig(configPath);
expect(result.issues.some((issue) => issue.includes("analysis"))).toBe(true);
// Fail-closed: the whole scope config is dropped, so `ask` is the effective
// default again rather than any rule the stale file meant to contribute.
expect(result.config).toEqual({});
});
it("merges the autoReview object field-by-field", () => {
const merged = mergeUnifiedConfigs(
{ autoReview: { enabled: true, provider: "vendor", model: "m" } },
{ autoReview: { reasoning: "low" } },
);
expect(merged.autoReview).toEqual({
enabled: true,
provider: "vendor",
model: "m",
reasoning: "low",
});
});
it("strips JSONC comments before parsing", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
`{
// This is a comment
"debugLog": true,
/* block comment */
"permission": { "*": "ask" }
}`,
);
const result = loadUnifiedConfig(configPath);
expect(result.issues).toEqual([]);
expect(result.config.debugLog).toBe(true);
expect(result.config.permission).toEqual({ "*": "ask" });
});
it("rejects unknown keys with a clear issue and empty config", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
debugLog: false,
unknownField: "ignored",
anotherRandom: 42,
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.issues.join("\n")).toContain("unknownField");
expect(result.issues.join("\n")).toContain("anotherRandom");
// Fail-closed: the whole scope is rejected, dropping the valid field too.
expect(result.config).toEqual({});
});
it("returns empty config and no issues when the file does not exist", () => {
const configPath = join(tempDir, "nonexistent.json");
const result = loadUnifiedConfig(configPath);
expect(result.issues).toEqual([]);
expect(result.config.debugLog).toBeUndefined();
expect(result.config.permission).toBeUndefined();
});
it("returns empty config and an issue when the file contains invalid JSON", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, "not valid json {{{");
const result = loadUnifiedConfig(configPath);
expect(result.issues).toHaveLength(1);
expect(result.issues[0]).toContain(configPath);
});
it("rejects non-boolean runtime knobs with a clear issue", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
debugLog: "yes",
permissionReviewLog: 1,
yoloMode: null,
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.config).toEqual({});
expect(result.issues.join("\n")).toContain("debugLog");
});
it("fails closed: an invalid field contributes no permission rules", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
permission: { "*": "allow", read: "allow" },
toolInputPreviewMaxLength: -5,
}),
);
const result = loadUnifiedConfig(configPath);
// Even though permission carried `allow` rules, the invalid knob rejects
// the whole scope so no `allow` leaks through — downstream falls to `ask`.
expect(result.config).toEqual({});
expect(result.config.permission).toBeUndefined();
expect(result.issues.length).toBeGreaterThan(0);
});
it("rejects an invalid PermissionState inside a permission map", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
permission: {
read: "allow",
write: "invalid",
bash: { "git *": "ask", "rm -rf": 42 },
},
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.config).toEqual({});
expect(result.issues.length).toBeGreaterThan(0);
});
it("accepts permission as object with mixed string and object values", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
permission: {
"*": "ask",
read: "allow",
bash: { "*": "ask", "git *": "allow" },
},
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.issues).toEqual([]);
expect(result.config.permission).toEqual({
"*": "ask",
read: "allow",
bash: { "*": "ask", "git *": "allow" },
});
});
it("preserves a deny-with-reason object inside a pattern map", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
permission: {
bash: {
"git *": "allow",
"npm *": { action: "deny", reason: "Use pnpm instead" },
},
},
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.config.permission).toEqual({
bash: {
"git *": "allow",
"npm *": { action: "deny", reason: "Use pnpm instead" },
},
});
});
it("rejects a deny object with a non-string reason", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
permission: {
bash: {
"git *": "allow",
"npm *": { action: "deny", reason: 42 },
},
},
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.config).toEqual({});
expect(result.issues.length).toBeGreaterThan(0);
});
it("returns no permission when the permission field is absent", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, JSON.stringify({ debugLog: false }));
const result = loadUnifiedConfig(configPath);
expect(result.config.permission).toBeUndefined();
});
it("rejects a non-object permission field", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, JSON.stringify({ permission: "allow" }));
const result = loadUnifiedConfig(configPath);
expect(result.config).toEqual({});
expect(result.issues.length).toBeGreaterThan(0);
});
it("parses the positive-integer scalar knobs", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({
forwardingTimeoutMs: 120_000,
toolInputPreviewMaxLength: 1000,
toolTextSummaryMaxLength: 120,
}),
);
const result = loadUnifiedConfig(configPath);
expect(result.config.forwardingTimeoutMs).toBe(120_000);
expect(result.config.toolInputPreviewMaxLength).toBe(1000);
expect(result.config.toolTextSummaryMaxLength).toBe(120);
});
it("rejects a non-positive forwardingTimeoutMs", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, JSON.stringify({ forwardingTimeoutMs: 0 }));
const result = loadUnifiedConfig(configPath);
expect(result.issues.length).toBeGreaterThan(0);
});
it("omits the scalar knobs when absent", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, JSON.stringify({ debugLog: false }));
const result = loadUnifiedConfig(configPath);
expect(result.config).not.toHaveProperty("toolInputPreviewMaxLength");
expect(result.config).not.toHaveProperty("toolTextSummaryMaxLength");
expect(result.config).not.toHaveProperty("forwardingTimeoutMs");
});
it.each([
["zero", 0],
["negative", -1],
["float", 1.5],
["string", "200"],
["boolean", true],
] as const)("rejects invalid toolInputPreviewMaxLength: %s", (_label, value) => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({ toolInputPreviewMaxLength: value }),
);
const result = loadUnifiedConfig(configPath);
expect(result.config).toEqual({});
expect(result.issues.length).toBeGreaterThan(0);
});
it.each([
["zero", 0],
["negative", -1],
["float", 1.5],
["string", "80"],
["boolean", false],
] as const)("rejects invalid toolTextSummaryMaxLength: %s", (_label, value) => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({ toolTextSummaryMaxLength: value }),
);
const result = loadUnifiedConfig(configPath);
expect(result.config).toEqual({});
expect(result.issues.length).toBeGreaterThan(0);
});
it.each([
["string", "not-an-array"],
["number", 42],
["mixed-type array", ["a", 1]],
["object", { a: "b" }],
] as const)("rejects invalid piInfrastructureReadPaths: %s", (_label, value) => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({ piInfrastructureReadPaths: value }),
);
const result = loadUnifiedConfig(configPath);
expect(result.config).toEqual({});
expect(result.issues.length).toBeGreaterThan(0);
});
});
describe("mergeUnifiedConfigs", () => {
it("deep-merges permission objects so the later config overrides per key", () => {
const merged = mergeUnifiedConfigs(
{
permission: {
"*": "ask",
read: "allow",
bash: { "git status": "allow" },
},
},
{
permission: {
"*": "allow",
bash: { "rm -rf *": "deny" },
},
},
);
expect(merged.permission).toEqual({
"*": "allow",
read: "allow",
bash: { "git status": "allow", "rm -rf *": "deny" },
});
});
it("string permission value in override replaces base string for same key", () => {
const merged = mergeUnifiedConfigs(
{ permission: { read: "ask" } },
{ permission: { read: "allow" } },
);
expect(merged.permission).toEqual({ read: "allow" });
});
it("object replaces string when override uses object for same surface", () => {
const merged = mergeUnifiedConfigs(
{ permission: { bash: "ask" } },
{ permission: { bash: { "*": "allow", "rm -rf *": "deny" } } },
);
expect(merged.permission).toEqual({
bash: { "*": "allow", "rm -rf *": "deny" },
});
});
it("string replaces object when override uses string for same surface", () => {
const merged = mergeUnifiedConfigs(
{ permission: { bash: { "git *": "allow" } } },
{ permission: { bash: "deny" } },
);
expect(merged.permission).toEqual({ bash: "deny" });
});
it("replaces scalar runtime knobs with later values", () => {
const merged = mergeUnifiedConfigs(
{
debugLog: true,
permissionReviewLog: true,
yoloMode: false,
doublePressToConfirm: true,
},
{ debugLog: false, yoloMode: true, doublePressToConfirm: false },
);
expect(merged.debugLog).toBe(false);
expect(merged.permissionReviewLog).toBe(true);
expect(merged.yoloMode).toBe(true);
expect(merged.doublePressToConfirm).toBe(false);
});
it("replaces prompt-budget scalars with later values", () => {
const merged = mergeUnifiedConfigs(
{ promptMaxRows: 24, promptFieldMaxWidth: 400 },
{ promptMaxRows: 10 },
);
expect(merged.promptMaxRows).toBe(10);
expect(merged.promptFieldMaxWidth).toBe(400);
});
it("replaces the review-log field width with a later value and keeps the base's otherwise", () => {
expect(
mergeUnifiedConfigs(
{ reviewLogFieldMaxWidth: 1000 },
{ reviewLogFieldMaxWidth: 200 },
).reviewLogFieldMaxWidth,
).toBe(200);
expect(
mergeUnifiedConfigs({ reviewLogFieldMaxWidth: 200 }, {})
.reviewLogFieldMaxWidth,
).toBe(200);
});
it("returns base unchanged when override is empty", () => {
const base = {
debugLog: true,
permission: { read: "allow" as const },
};
const merged = mergeUnifiedConfigs(base, {});
expect(merged.debugLog).toBe(true);
expect(merged.permission).toEqual({ read: "allow" });
});
it("returns override unchanged when base is empty", () => {
const override = {
yoloMode: true,
permission: { bash: { "rm -rf *": "deny" as const } },
};
const merged = mergeUnifiedConfigs({}, override);
expect(merged.yoloMode).toBe(true);
expect(merged.permission).toEqual({ bash: { "rm -rf *": "deny" } });
});
it("does not set undefined keys in the merged result", () => {
const merged = mergeUnifiedConfigs({ debugLog: true }, { yoloMode: false });
expect(merged.debugLog).toBe(true);
expect(merged.yoloMode).toBe(false);
expect(merged).not.toHaveProperty("permissionReviewLog");
expect(merged).not.toHaveProperty("permission");
});
it("override toolInputPreviewMaxLength replaces base value", () => {
const merged = mergeUnifiedConfigs(
{ toolInputPreviewMaxLength: 200 },
{ toolInputPreviewMaxLength: 1000 },
);
expect(merged.toolInputPreviewMaxLength).toBe(1000);
});
it("base toolInputPreviewMaxLength survives when override omits it", () => {
const merged = mergeUnifiedConfigs(
{ toolInputPreviewMaxLength: 500 },
{ debugLog: true },
);
expect(merged.toolInputPreviewMaxLength).toBe(500);
});
it("toolInputPreviewMaxLength is absent when both base and override omit it", () => {
const merged = mergeUnifiedConfigs({ debugLog: true }, { yoloMode: false });
expect(merged).not.toHaveProperty("toolInputPreviewMaxLength");
});
it("override toolTextSummaryMaxLength replaces base value", () => {
const merged = mergeUnifiedConfigs(
{ toolTextSummaryMaxLength: 80 },
{ toolTextSummaryMaxLength: 200 },
);
expect(merged.toolTextSummaryMaxLength).toBe(200);
});
it("base toolTextSummaryMaxLength survives when override omits it", () => {
const merged = mergeUnifiedConfigs(
{ toolTextSummaryMaxLength: 120 },
{ debugLog: false },
);
expect(merged.toolTextSummaryMaxLength).toBe(120);
});
it("toolTextSummaryMaxLength is absent when both base and override omit it", () => {
const merged = mergeUnifiedConfigs({}, { permissionReviewLog: true });
expect(merged).not.toHaveProperty("toolTextSummaryMaxLength");
});
it("override authorizerChain replaces base array", () => {
const merged = mergeUnifiedConfigs(
{ authorizerChain: ["base-judge"] },
{ authorizerChain: ["override-judge"] },
);
expect(merged.authorizerChain).toEqual(["override-judge"]);
});
it("base authorizerChain survives when override omits it", () => {
const merged = mergeUnifiedConfigs(
{ authorizerChain: ["kept-judge"] },
{ debugLog: true },
);
expect(merged.authorizerChain).toEqual(["kept-judge"]);
});
it("base shellTools survives when override omits it", () => {
const merged = mergeUnifiedConfigs(
{ shellTools: { exec_command: { commandArgument: "cmd" } } },
{},
);
expect(merged.shellTools).toEqual({
exec_command: { commandArgument: "cmd" },
});
});
it("override shellTools survives when base omits it", () => {
const merged = mergeUnifiedConfigs(
{},
{ shellTools: { exec_command: { commandArgument: "cmd" } } },
);
expect(merged.shellTools).toEqual({
exec_command: { commandArgument: "cmd" },
});
});
it("merges shellTools by tool name: override adds without dropping base", () => {
const merged = mergeUnifiedConfigs(
{ shellTools: { exec_command: { commandArgument: "cmd" } } },
{ shellTools: { run_shell: { commandArgument: "script" } } },
);
expect(merged.shellTools).toEqual({
exec_command: { commandArgument: "cmd" },
run_shell: { commandArgument: "script" },
});
});
it("field-merges a colliding shell alias and preserves its decision floor", () => {
const merged = mergeUnifiedConfigs(
{
shellTools: {
exec_command: {
commandArgument: "cmd",
workdirArgument: "workdir",
decisionFloor: "ask",
},
},
},
{ shellTools: { exec_command: { commandArgument: "command" } } },
);
expect(merged.shellTools).toEqual({
exec_command: {
commandArgument: "command",
workdirArgument: "workdir",
decisionFloor: "ask",
},
});
});
it("shellTools is absent when both base and override omit it", () => {
const merged = mergeUnifiedConfigs({ debugLog: true }, { yoloMode: false });
expect(merged).not.toHaveProperty("shellTools");
});
});
describe("loadAndMergeConfigs", () => {
let tempDir: string;
let agentDir: string;
let cwd: string;
let extensionRoot: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "config-merge-test-"));
agentDir = join(tempDir, "agent");
cwd = join(tempDir, "project");
extensionRoot = join(tempDir, "ext");
});
afterEach(() => {
rmSync(tempDir, { recursive: true, force: true });
});
function writeGlobal(content: Record<string, unknown>): void {
const dir = join(agentDir, "extensions", "pi-permission-system");
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "policy.jsonc"), JSON.stringify(content));
}
function writeProject(content: Record<string, unknown>): void {
const dir = join(cwd, ".pi", "extensions", "pi-permission-system");
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "policy.jsonc"), JSON.stringify(content));
}
function writeLegacyGlobalPolicy(content: Record<string, unknown>): void {
mkdirSync(agentDir, { recursive: true });
writeFileSync(
join(agentDir, "pi-permissions.jsonc"),
JSON.stringify(content),
);
}
function writeLegacyProjectPolicy(content: Record<string, unknown>): void {
const dir = join(cwd, ".pi", "agent");
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "pi-permissions.jsonc"), JSON.stringify(content));
}
function writeLegacyExtensionConfig(content: Record<string, unknown>): void {
mkdirSync(extensionRoot, { recursive: true });
writeFileSync(join(extensionRoot, "config.json"), JSON.stringify(content));
}
it("detects legacy global policy and emits migration issue", () => {
writeLegacyGlobalPolicy({
defaultPolicy: { tools: "allow" },
tools: { read: "allow" },
});
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.issues).toHaveLength(1);
expect(result.issues[0]).toContain("pi-permissions.jsonc");
expect(result.issues[0]).toContain("extensions/pi-permission-system");
// Legacy file has no flat-format permission key — no rules extracted
expect(result.merged.permission).toBeUndefined();
});
it("detects legacy extension runtime config and emits migration issue", () => {
writeLegacyExtensionConfig({
debugLog: true,
yoloMode: true,
});
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.issues).toHaveLength(1);
expect(result.issues[0]).toContain(extensionRoot);
expect(result.merged.debugLog).toBe(true);
expect(result.merged.yoloMode).toBe(true);
});
it("does not emit legacy extension config issue when its path equals the runtime legacy path", () => {
const newGlobalDir = join(agentDir, "extensions", "pi-permission-system");
mkdirSync(newGlobalDir, { recursive: true });
writeFileSync(
join(newGlobalDir, "config.json"),
JSON.stringify({ debugLog: true }),
);
const result = loadAndMergeConfigs(agentDir, cwd, newGlobalDir);
expect(result.issues.filter((i) => i.includes("legacy"))).toHaveLength(0);
});
it("emits no issues when no legacy files exist and no new files exist", () => {
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.issues).toEqual([]);
});
it("new-layout config takes precedence over legacy config at same scope", () => {
writeGlobal({
permission: { "*": "deny" },
});
writeLegacyGlobalPolicy({
permission: { "*": "allow" },
});
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
// New layout wins (legacy loaded first, new layout loaded second → new wins)
expect(result.merged.permission).toEqual({ "*": "deny" });
// But legacy still emits a migration warning
expect(result.issues.some((i) => i.includes("pi-permissions.jsonc"))).toBe(
true,
);
});
it("warns when the merged config leaves bash inheriting a permissive top-level '*'", () => {
writeGlobal({
permission: { "*": "allow", read: "allow" },
});
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.issues.some((i) => i.includes("bash"))).toBe(true);
});
it("does not warn about bash fallback when bash is explicitly gated", () => {
writeGlobal({
permission: { "*": "allow", bash: { "*": "ask" } },
});
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.issues).toEqual([]);
});
it("ignores new and legacy project policy files", () => {
writeGlobal({ permission: { "*": "ask", bash: "deny" } });
writeProject({ permission: { bash: "allow" } });
writeLegacyProjectPolicy({ permission: { "*": "allow" } });
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.merged.permission).toEqual({ "*": "ask", bash: "deny" });
expect(result.issues).toEqual([]);
});
describe("deprecated tool-preview caps", () => {
it("notices a config that sets either cap", () => {
writeGlobal({
permission: { "*": "ask" },
toolInputPreviewMaxLength: 400,
});
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.issues).toHaveLength(1);
expect(result.issues[0]).toContain("toolInputPreviewMaxLength");
});
it("keeps accepting the config rather than rejecting it fail-closed", () => {
writeGlobal({
permission: { "*": "ask", bash: "deny" },
toolTextSummaryMaxLength: 120,
});
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.merged.permission).toEqual({ "*": "ask", bash: "deny" });
});
it("stays silent when neither cap is set", () => {
writeGlobal({ permission: { "*": "ask", bash: "deny" } });
const result = loadAndMergeConfigs(agentDir, cwd, extensionRoot);
expect(result.issues).toEqual([]);
});
});
});
// ── detectDeprecatedPreviewCaps ────────────────────────────────────────────
describe("detectDeprecatedPreviewCaps", () => {
it("names the input-preview cap when it alone is set", () => {
const notice = detectDeprecatedPreviewCaps({
toolInputPreviewMaxLength: 400,
});
expect(notice).toContain("toolInputPreviewMaxLength");
expect(notice).not.toContain("toolTextSummaryMaxLength");
});
it("names the text-summary cap when it alone is set", () => {
const notice = detectDeprecatedPreviewCaps({
toolTextSummaryMaxLength: 120,
});
expect(notice).toContain("toolTextSummaryMaxLength");
expect(notice).not.toContain("toolInputPreviewMaxLength");
});
it("names both caps when both are set", () => {
const notice = detectDeprecatedPreviewCaps({
toolInputPreviewMaxLength: 400,
toolTextSummaryMaxLength: 120,
});
expect(notice).toContain("toolInputPreviewMaxLength");
expect(notice).toContain("toolTextSummaryMaxLength");
});
it("returns undefined when neither cap is set", () => {
expect(detectDeprecatedPreviewCaps({})).toBeUndefined();
});
});