Files
my-pi/pi-permission-system/test/config-loader.test.ts
T
云服务部-叶林立 cdd91b3f8b feat: 移除 Codex Fast mode 与 AutoReview 后台分析,模型改为配置驱动
移除 pi-extension-codex-fast-mode:
- 删除整个扩展目录;同步清理根 package.json 的 files / pi.extensions /
  dependencies 条目、package-lock.json、tests/extension-load.test.ts 断言
  与文档章节。
- pi-minimal-footer 的 Fast on 渲染是该扩展的唯一消费者。扩展移除后 accent
  分支不再有生产者,collectFooterStatusItems 简化为直接返回非空状态字符串,
  去掉 FooterStatusItem 与 accent 标志,避免留下死代码。

移除 500 次裁决后的后台分析体系:
- 删除 analysis-agent.ts(192 行)与 ledger.ts(296 行),以及对应的
  auto-review-runtime / auto-review-ledger 测试。
- runtime.ts 由 177 行收敛到 85 行:安装选项缩为 { service, config };删除
  handleAgentSettled 与 agent_settled 注册;保留 session_start / turn_start
  (denial circuit breaker 属安全语义)/ session_shutdown。
- 删除 analysis 配置键:config、extension-config、config-schema、生成的
  permissions.schema.json 与种子配置。
- 删除 reviewer 的 onDecision 回调(唯一消费者是 ledger)。
- 删除迁移机制 scripts/migrate-permission-policy.mjs、其测试与 update.sh 中
  46 行 migrate_permission_policy 接线。种子部署保持“目标缺失才写入”,已存在
  的 policy.jsonc 永不被覆盖。

AutoReview 模型改为纯配置驱动:
- 删除 DEFAULT_PROVIDER / DEFAULT_MODEL 常量与 findCodexTemplate 合成逻辑;
  model.ts 由 65 行收敛到 48 行。
- provider / model 任一缺失时返回新增失败类别 model-unconfigured 并 defer 到
  人工审批;provider 未注册或模型未发布同样 defer。
- reasoning 不再有默认常量,完全由配置决定。
- session_start 在 auto-review 已列入 authorizerChain 且 provider/model 未配齐
  时 ui.notify 提示一次,避免不使用 AutoReview 的用户被打扰。
- 种子 autoReview 只保留 enabled,provider/model/reasoning 由用户按本机实际
  可用的模型填写。

破坏性变更:analysis 键已从 strictObject schema 删除,任何仍带该键的
policy.jsonc 会使整份配置被拒(fail-closed 到全 ask)。这是刻意的变更,已由
config-loader 测试固定,防止将来无声放宽。

测试:
- 新增 auto-review-model.test.ts(7 例),覆盖此前完全缺失的模型解析:真实
  命中、未配置、provider 未知、模型未发布,以及不再合成替代模型。
- 重写 auto-review-runtime.test.ts(6 例):authorizer 注册、未配置时提示
  一次、已配置 / disabled / 无 UI / 不在 chain 时静默。
- config-loader.test.ts 新增 2 例:带 analysis 的旧配置被拒且 fail-closed、
  autoReview 逐字段合并。
- composition-root.test.ts 的 EXPECTED_HANDLERS 移除 agent_settled。

文档:AGENTS.md、README.md、pi-permission-system 的 README / CHANGELOG /
configuration.md / architecture.md / auto-review UPSTREAM.md。

验证:pi-permission-system 的 typecheck、2577 个测试与 build 全部通过;根 50
个测试通过;schema 重新生成无漂移;新种子通过 schema 校验;5 个脚本 sh -n
通过;git diff --check 无空白问题。未安装 shellcheck;未执行真实 pi install /
update(属外部写操作)。
2026-10-14 08:15:13 -07:00

897 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 forwardingTimeoutMs when a valid positive integer is present", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, JSON.stringify({ forwardingTimeoutMs: 120_000 }));
const result = loadUnifiedConfig(configPath);
expect(result.config.forwardingTimeoutMs).toBe(120_000);
});
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("parses toolInputPreviewMaxLength when a valid positive integer is present", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({ toolInputPreviewMaxLength: 1000 }),
);
const result = loadUnifiedConfig(configPath);
expect(result.config.toolInputPreviewMaxLength).toBe(1000);
});
it("parses toolTextSummaryMaxLength when a valid positive integer is present", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(
configPath,
JSON.stringify({ toolTextSummaryMaxLength: 120 }),
);
const result = loadUnifiedConfig(configPath);
expect(result.config.toolTextSummaryMaxLength).toBe(120);
});
it("omits toolInputPreviewMaxLength when absent", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, JSON.stringify({ debugLog: false }));
const result = loadUnifiedConfig(configPath);
expect(result.config).not.toHaveProperty("toolInputPreviewMaxLength");
});
it("omits toolTextSummaryMaxLength when absent", () => {
const configPath = join(tempDir, "config.json");
writeFileSync(configPath, JSON.stringify({ debugLog: false }));
const result = loadUnifiedConfig(configPath);
expect(result.config).not.toHaveProperty("toolTextSummaryMaxLength");
});
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", () => {
expect(
mergeUnifiedConfigs(
{ reviewLogFieldMaxWidth: 1000 },
{ reviewLogFieldMaxWidth: 200 },
).reviewLogFieldMaxWidth,
).toBe(200);
});
it("carries the review-log field width from the base when unoverridden", () => {
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();
});
});