Files
my-pi/tests/tool-search-settings-migration.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

242 lines
10 KiB
TypeScript

import assert from "node:assert/strict";
import { chmod, copyFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import {
CURRENT_TOOL_SEARCH_DEFAULTS,
LEGACY_TOOL_SEARCH_DEFAULTS,
PREVIOUS_TOOL_SEARCH_DEFAULTS,
migrateToolSearchSettings,
} from "../scripts/migrate-tool-search-settings.mjs";
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
async function fixture(t: test.TestContext): Promise<{ root: string; settingsPath: string }> {
const root = await mkdtemp(join(tmpdir(), "my-pi-tool-search-migration-"));
t.after(() => rm(root, { recursive: true, force: true }));
return { root, settingsPath: join(root, "settings.json") };
}
test("migrates only the complete legacy default snapshot with a private backup", async (t) => {
const { root, settingsPath } = await fixture(t);
const original = {
theme: "dark",
toolSearch: LEGACY_TOOL_SEARCH_DEFAULTS,
unrelated: { keep: true },
};
await writeFile(settingsPath, `${JSON.stringify(original, null, 2)}\n`, "utf8");
await chmod(settingsPath, 0o644);
const result = await migrateToolSearchSettings(settingsPath, { now: new Date("2026-08-28T12:34:56.789Z") });
assert.equal(result.status, "migrated");
assert.equal(result.backupPath, `${settingsPath}.bak.2026-08-28T12-34-56-789Z`);
assert.deepEqual(JSON.parse(await readFile(settingsPath, "utf8")), {
...original,
toolSearch: CURRENT_TOOL_SEARCH_DEFAULTS,
});
assert.deepEqual(JSON.parse(await readFile(result.backupPath!, "utf8")), original);
assert.equal((await stat(settingsPath)).mode & 0o777, 0o600);
assert.equal((await stat(result.backupPath!)).mode & 0o777, 0o600);
assert.deepEqual((await readdir(root)).sort(), [
"settings.json",
"settings.json.bak.2026-08-28T12-34-56-789Z",
]);
});
test("does not remove a pre-existing backup when the timestamp collides", async (t) => {
const { settingsPath } = await fixture(t);
const now = new Date("2026-08-28T12:34:56.789Z");
const backupPath = `${settingsPath}.bak.2026-08-28T12-34-56-789Z`;
const original = JSON.stringify({ toolSearch: LEGACY_TOOL_SEARCH_DEFAULTS });
await writeFile(settingsPath, original, "utf8");
await writeFile(backupPath, "existing backup\n", "utf8");
await assert.rejects(migrateToolSearchSettings(settingsPath, { now }), { code: "EEXIST" });
assert.equal(await readFile(backupPath, "utf8"), "existing backup\n");
assert.equal(await readFile(settingsPath, "utf8"), original);
});
test("preserves custom Tool Search settings even when they retain the old capacities", async (t) => {
const { root, settingsPath } = await fixture(t);
const custom = {
toolSearch: {
...LEGACY_TOOL_SEARCH_DEFAULTS,
alwaysEnabled: [...LEGACY_TOOL_SEARCH_DEFAULTS.alwaysEnabled, "custom_tool"],
},
};
const original = `${JSON.stringify(custom, null, 2)}\n`;
await writeFile(settingsPath, original, "utf8");
assert.deepEqual(await migrateToolSearchSettings(settingsPath), { status: "custom" });
assert.equal(await readFile(settingsPath, "utf8"), original);
assert.deepEqual(await readdir(root), ["settings.json"]);
});
test("recognizes current defaults and skips files without a Tool Search section", async (t) => {
const current = await fixture(t);
await writeFile(current.settingsPath, JSON.stringify({ toolSearch: CURRENT_TOOL_SEARCH_DEFAULTS }), "utf8");
assert.deepEqual(await migrateToolSearchSettings(current.settingsPath), { status: "current" });
const unversioned = await fixture(t);
const { bundleDefaultsVersion: _version, ...runtimeDefaults } = CURRENT_TOOL_SEARCH_DEFAULTS;
await writeFile(unversioned.settingsPath, JSON.stringify({ toolSearch: runtimeDefaults }), "utf8");
assert.deepEqual(await migrateToolSearchSettings(unversioned.settingsPath), { status: "current" });
const absent = await fixture(t);
await writeFile(absent.settingsPath, JSON.stringify({ theme: "dark" }), "utf8");
assert.deepEqual(await migrateToolSearchSettings(absent.settingsPath), { status: "missing-section" });
});
test("migrates the previous versioned default snapshot and pins the Hermes memory tools", async (t) => {
const { settingsPath } = await fixture(t);
await writeFile(settingsPath, JSON.stringify({ toolSearch: PREVIOUS_TOOL_SEARCH_DEFAULTS }), "utf8");
const result = await migrateToolSearchSettings(settingsPath);
assert.equal(result.status, "migrated");
const migrated = JSON.parse(await readFile(settingsPath, "utf8")).toolSearch;
assert.deepEqual(migrated, CURRENT_TOOL_SEARCH_DEFAULTS);
assert.equal(migrated.bundleDefaultsVersion, 3);
for (const name of ["memory_search", "session_search", "memory_add", "memory_replace", "memory_remove", "skill_manage"]) {
assert.ok(migrated.alwaysEnabled.includes(name), `${name} must be pinned after migration`);
}
});
test("preserves custom settings that keep the previous capacities but pin extra tools", async (t) => {
const { root, settingsPath } = await fixture(t);
const custom = {
toolSearch: {
...PREVIOUS_TOOL_SEARCH_DEFAULTS,
alwaysEnabled: [...PREVIOUS_TOOL_SEARCH_DEFAULTS.alwaysEnabled, "custom_tool"],
},
};
const original = `${JSON.stringify(custom, null, 2)}\n`;
await writeFile(settingsPath, original, "utf8");
assert.deepEqual(await migrateToolSearchSettings(settingsPath), { status: "custom" });
assert.equal(await readFile(settingsPath, "utf8"), original);
assert.deepEqual(await readdir(root), ["settings.json"]);
});
test("fails safely for invalid JSON and reports a missing settings file", async (t) => {
const invalid = await fixture(t);
await writeFile(invalid.settingsPath, "{ invalid\n", "utf8");
await assert.rejects(migrateToolSearchSettings(invalid.settingsPath), /invalid JSON/);
assert.equal(await readFile(invalid.settingsPath, "utf8"), "{ invalid\n");
const missing = await fixture(t);
assert.deepEqual(await migrateToolSearchSettings(missing.settingsPath), { status: "missing" });
});
test("aborts when settings change before the atomic replacement", async (t) => {
const { root, settingsPath } = await fixture(t);
await writeFile(settingsPath, JSON.stringify({ toolSearch: LEGACY_TOOL_SEARCH_DEFAULTS }), "utf8");
const competing = `${JSON.stringify({ toolSearch: { ...LEGACY_TOOL_SEARCH_DEFAULTS, maxActiveGroups: 4 } })}\n`;
await assert.rejects(
migrateToolSearchSettings(settingsPath, {
beforeCommit: () => writeFile(settingsPath, competing, "utf8"),
}),
/changed during migration/,
);
assert.equal(await readFile(settingsPath, "utf8"), competing);
const files = await readdir(root);
assert.equal(files.filter((name) => name.includes(".bak.")).length, 1);
assert.equal(files.some((name) => name.endsWith(".tmp")), false);
});
async function updateFixture(t: test.TestContext, piExitStatus = 0) {
const root = await mkdtemp(join(tmpdir(), "my-pi-tool-search-update-"));
t.after(() => rm(root, { recursive: true, force: true }));
const home = join(root, "home");
const bin = join(root, "bin");
const agentDir = join(home, ".pi", "agent");
const settingsPath = join(agentDir, "settings.json");
const log = join(root, "pi.log");
const updatedBundle = join(root, "updated-bundle");
await mkdir(bin, { recursive: true });
await mkdir(agentDir, { recursive: true });
await mkdir(join(updatedBundle, "config"), { recursive: true });
await mkdir(join(updatedBundle, "scripts"), { recursive: true });
await copyFile(join(repositoryRoot, "config", "p10k.zsh"), join(updatedBundle, "config", "p10k.zsh"));
await copyFile(
join(repositoryRoot, "config", "pi-hashline-edit.json"),
join(updatedBundle, "config", "pi-hashline-edit.json"),
);
await copyFile(
join(repositoryRoot, "scripts", "migrate-tool-search-settings.mjs"),
join(updatedBundle, "scripts", "migrate-tool-search-settings.mjs"),
);
await copyFile(
join(repositoryRoot, "config", "pi-permission-policy.jsonc"),
join(updatedBundle, "config", "pi-permission-policy.jsonc"),
);
await writeFile(
join(bin, "pi"),
`#!/bin/sh\nprintf 'pi %s\\n' "$*" >> "$MOCK_PI_LOG"\nexit ${piExitStatus}\n`,
"utf8",
);
await chmod(join(bin, "pi"), 0o755);
await writeFile(settingsPath, JSON.stringify({ toolSearch: LEGACY_TOOL_SEARCH_DEFAULTS }), "utf8");
return {
settingsPath,
log,
env: {
...process.env,
HOME: home,
XDG_CONFIG_HOME: join(home, ".config"),
PI_CODING_AGENT_DIR: agentDir,
PI_PACKAGE_SOURCE: updatedBundle,
MOCK_PI_LOG: log,
PATH: `${bin}:${dirname(process.execPath)}:/usr/bin:/bin`,
ZSH: "",
ZSH_CUSTOM: "",
ZDOTDIR: home,
},
};
}
test("update.sh migrates the exact legacy snapshot after a successful package update", async (t) => {
const fixture = await updateFixture(t);
const result = spawnSync("sh", [join(repositoryRoot, "update.sh")], {
cwd: repositoryRoot,
env: fixture.env,
encoding: "utf8",
timeout: 30_000,
});
assert.equal(result.status, 0, result.stderr || result.stdout);
assert.match(await readFile(fixture.log, "utf8"), /pi update .*updated-bundle/);
assert.match(result.stdout, /旧版默认配置已迁移/);
assert.deepEqual(JSON.parse(await readFile(fixture.settingsPath, "utf8")).toolSearch, CURRENT_TOOL_SEARCH_DEFAULTS);
assert.equal((await stat(fixture.settingsPath)).mode & 0o777, 0o600);
});
test("update.sh does not migrate settings when pi update fails", async (t) => {
const fixture = await updateFixture(t, 1);
const before = await readFile(fixture.settingsPath, "utf8");
const result = spawnSync("sh", [join(repositoryRoot, "update.sh")], {
cwd: repositoryRoot,
env: fixture.env,
encoding: "utf8",
timeout: 30_000,
});
assert.equal(result.status, 1);
assert.equal(await readFile(fixture.settingsPath, "utf8"), before);
assert.doesNotMatch(result.stdout, /旧版默认配置已迁移/);
});
test("update.sh preserves settings when the updated bundle helper cannot be located", async (t) => {
const fixture = await updateFixture(t);
const before = await readFile(fixture.settingsPath, "utf8");
const result = spawnSync("sh", [join(repositoryRoot, "update.sh")], {
cwd: repositoryRoot,
env: { ...fixture.env, PI_PACKAGE_SOURCE: "unsupported:my-pi" },
encoding: "utf8",
timeout: 30_000,
});
assert.equal(result.status, 1);
assert.equal(await readFile(fixture.settingsPath, "utf8"), before);
assert.match(result.stderr, /无法定位升级后组合包中的 Tool Search/);
});