Files
my-pi/tests/tool-search-settings-migration.test.ts
T
云服务部-叶林立 73f3117a7e feat(pi-hermes-memory): 接入持久记忆扩展并移除 Hippo
用仓库内 pi-hermes-memory 替换 hippo-memory-pi,清理 Hippo 在组合包中的
全部注入点。

移除 Hippo:
- 删除 hippo-memory-pi/ 与 config/hippo-memory-version。
- extensions/plugin-init.ts 只保留 CodeGraph 初始化目标与预检。
- install.sh / update.sh / uninstall.sh 移除 Hippo CLI 的安装、升级、卸载
  与版本校验逻辑;uninstall.sh 同时删除仅服务于该提示的死代码 ask_yes_no。
- 删除 tests/hippo-extension.test.ts 与 tests/hippo-scripts.test.ts。
- tests/extension-load.test.ts 反转“不得加载 Hermes”的断言为必须加载,
  并断言其排在 pi-compaction 之前。

接入 pi-hermes-memory:
- package.json 增加 file:./pi-hermes-memory 依赖、files 条目与加载入口;
  加载顺序位于 pi-compaction 之前,否则 flushOnCompact 会被 pi-compaction
  的 { cancel: true } 静默跳过。
- 六个记忆工具在 Tool Search 中常驻:memory_search 与 session_search 连同
  context_tree_query 归入 memory-recall,memory_add / memory_replace /
  memory_remove / skill_manage 归入 memory-management。常驻是必需的——注入
  的 memory policy 会在普通工作中指示模型调用它们,schema 不可见会让模型
  静默放弃而不是去 tool_search,同时常驻也保持请求前缀缓存稳定。
- bundleDefaultsVersion 由 2 升到 3;migrate-tool-search-settings.mjs 新增
  上一版快照到当前版本的迁移路径,仍只迁移完整匹配的默认快照并保留自定义
  配置。
- config/pi-permission-policy.jsonc 为六个工具设置 allow:它们只写扩展自己的
  agent 目录数据、不触碰工作区,且 memory_search 每轮都可能被调用,落入
  默认 ask 会产生每轮 AutoReview 往返。

依赖:
- pi-hermes-memory 的 devDependencies 由上游 ^0.80.2 等范围改为与根包一致的
  精确版本。上游范围与根包 0.84.2 不兼容,会让 npm 在本目录嵌套安装第二套
  Pi runtime(实测 229 MB),违反“不得在组合包内再安装一套 Pi runtime”的
  纪律。
- 根 allowScripts 保持只有 better-sqlite3@12.11.1。hermes 的
  better-sqlite3@13 运行时 dlopen 的是包内 N-API 预编译二进制
  prebuilds/<platform>.node,npm 因 binding.gyp 推断出的 node-gyp rebuild
  无需执行;实测删除 build/ 目录后仍正常工作。

文档:AGENTS.md 与 README.md 改写记忆章节,新增 pi-hermes-memory 开发约定,
替换文末的 Hippo 项目记忆块。

验证:根 12 个测试文件、pi-tool-search 的 typecheck/test/build、
pi-permission-system 的 typecheck/2569 测试、pi-hermes-memory 自带的 59 个
测试文件全部通过;隔离 Pi 环境联合加载无错误并生成 bundleDefaultsVersion 3;
npm install 幂等;迁移 helper 对 v2 快照迁移、对自定义配置保留。
2026-10-14 00:56:41 -07:00

246 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, 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 copyFile(
join(repositoryRoot, "scripts", "migrate-permission-policy.mjs"),
join(updatedBundle, "scripts", "migrate-permission-policy.mjs"),
);
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/);
});