Files
my-pi/tests/tool-search-settings-migration.test.ts
T
云服务部-叶林立 dec48dab6d feat: 新增系统提示词封面,并修正工具结果投影与常驻工具
系统提示词封面(新增能力):

- extensions/system-prompt-cover.ts:读取 ~/.pi/agent/SYSTEM_COVER.md,
  在 before_agent_start 返回 { systemPrompt },用文本拼接替换 Pi 默认
  系统提示词的开头,同时保留 tools / rules / docs / skills /
  project_context / cwd 全部分区及其原始顺序。
- 必须走 forceSystemPrompt 投影路径。customPrompt 选项会连带抑制
  tools / rules / docs 三个分区,而回填只能追加到末尾,无法恢复原顺序;
  且 forceSystemPrompt 优先级更高,二者同时存在时 customPrompt 会被
  静默忽略,因此 handler 不得写 customPrompt。
- 分割边界要求独占一行的裸标签:<project_instructions path="..."> 嵌套在
  <project_context> 内,只有裸标签才是分区边界。
- 注册在 tool-routing 之前,否则提示词已被压平,改 systemPromptOptions
  不再影响本轮请求。
- scripts/deploy-system-prompt-cover.mjs:同目录临时文件 + rename 原子
  覆盖,不保留备份;install.sh 从脚本目录、update.sh 从升级后组合包
  定位 helper,禁止回退到可能陈旧的脚本目录。
- 封面缺失、不可读或空白时静默 no-op,Pi 行为保持不变;封面每轮重新
  读取,修改后在下一轮生效,不影响已结束的历史对话。

pi-compaction 投影修正:

- 仅在「摘要 + Source 行」严格短于原文时才替换工具结果。此前命中即
  无条件替换,小结果反而被包壳放大;未替换的结果完整保留原始 content
  parts(含非文本部分)。
- deterministic.maxStubTokens 由 256 提升到 1024。

pi-tool-search 常驻工具:

- alwaysEnabled 增加 context_tree_query:恢复被投影的工具证据不应依赖
  一次 tool_search 激活,常驻同时保持请求前缀稳定。
- BUNDLE_TOOL_SEARCH_DEFAULTS_VERSION 由 3 提升到 4;
  scripts/migrate-tool-search-settings.mjs 新增 version-3 快照常量,
  使其与 version-2 一样可被完整精确匹配并迁移。
- 权限策略为 context_tree_query 显式 allow:它只读扩展自己的 segment
  索引、不触碰工作区,常驻后不应每轮触发 AutoReview 往返。该种子仅在
  全新安装时部署,已存在的用户 policy.jsonc 不会被覆盖。

文档与测试同步:

- AGENTS.md:新增 system-prompt-cover 开发约定,修正加载顺序、
  bundleDefaultsVersion、可迁移旧快照集合与常驻工具范围的描述。
- pi-tool-search 的 README / CHANGELOG 同步 version 4 与新增常驻工具。
- tests/system-prompt-cover.test.ts:覆盖顺序保持、尾部逐字节不变、
  嵌套 project_instructions 不误判、部署幂等与覆盖、缺源时非零退出。
- 修正 pi-tool-search/test/config.test.ts 与
  tests/tool-search-settings-migration.test.ts 中写死的 version 3 与
  工具列表断言。
- update-git-clean-recovery / tool-search-settings-migration 的 mock
  组合包补拷 scripts/,与真实发布包结构一致,避免 helper 定位失败。

测试:根 61/61、pi-compaction 36/36 + tsc、pi-tool-search 16/16 + tsc、
pi-permission-system 2577/2577;sh -n 与 git diff --check 通过。
2026-10-15 18:02:03 -07:00

252 lines
11 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, 4);
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"),
);
// A released bundle also ships the system prompt cover and its deploy helper; update.sh
// resolves both from the upgraded bundle directory.
await copyFile(
join(repositoryRoot, "config", "system-prompt-cover.md"),
join(updatedBundle, "config", "system-prompt-cover.md"),
);
await copyFile(
join(repositoryRoot, "scripts", "deploy-system-prompt-cover.mjs"),
join(updatedBundle, "scripts", "deploy-system-prompt-cover.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/);
});