Files
my-pi/scripts/migrate-tool-search-settings.mjs
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

205 lines
6.3 KiB
JavaScript
Executable File

#!/usr/bin/env node
import { constants, realpathSync } from "node:fs";
import { chmod, open, rename, rm } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
export const LEGACY_TOOL_SEARCH_DEFAULTS = {
alwaysEnabled: ["codegraph_explore", "lsp_diagnostics"],
showToolSearchFooterStatus: false,
maxActiveGroups: 3,
maxToolsPerGroup: 8,
maxDynamicTools: 20,
groupOverrides: {},
};
const PREVIOUS_TOOL_SEARCH_RUNTIME_DEFAULTS = {
alwaysEnabled: [
"codegraph_explore",
"lsp_diagnostics",
"ctx_execute",
"ctx_execute_file",
"ctx_batch_execute",
],
showToolSearchFooterStatus: false,
maxActiveGroups: 5,
maxToolsPerGroup: 8,
maxDynamicTools: 28,
groupOverrides: {},
};
export const PREVIOUS_TOOL_SEARCH_DEFAULTS = {
...PREVIOUS_TOOL_SEARCH_RUNTIME_DEFAULTS,
bundleDefaultsVersion: 2,
};
export const CURRENT_TOOL_SEARCH_RUNTIME_DEFAULTS = {
alwaysEnabled: [
"codegraph_explore",
"lsp_diagnostics",
"ctx_execute",
"ctx_execute_file",
"ctx_batch_execute",
"memory_search",
"session_search",
"memory_add",
"memory_replace",
"memory_remove",
"skill_manage",
],
showToolSearchFooterStatus: false,
maxActiveGroups: 5,
maxToolsPerGroup: 8,
maxDynamicTools: 28,
groupOverrides: {},
};
export const CURRENT_TOOL_SEARCH_DEFAULTS = {
...CURRENT_TOOL_SEARCH_RUNTIME_DEFAULTS,
bundleDefaultsVersion: 3,
};
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function exactJsonValue(left, right) {
if (Array.isArray(left) || Array.isArray(right)) {
return Array.isArray(left)
&& Array.isArray(right)
&& left.length === right.length
&& left.every((value, index) => exactJsonValue(value, right[index]));
}
if (isObject(left) || isObject(right)) {
if (!isObject(left) || !isObject(right)) return false;
const leftKeys = Object.keys(left).sort();
const rightKeys = Object.keys(right).sort();
return exactJsonValue(leftKeys, rightKeys)
&& leftKeys.every((key) => exactJsonValue(left[key], right[key]));
}
return Object.is(left, right);
}
function backupTimestamp(now) {
return now.toISOString().replace(/[:.]/g, "-");
}
async function readFileSnapshot(path) {
let handle;
try {
handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
const metadata = await handle.stat();
if (!metadata.isFile()) throw new Error(`settings path is not a regular file: ${path}`);
return { metadata, content: await handle.readFile("utf8") };
} finally {
if (handle) await handle.close().catch(() => {});
}
}
export async function migrateToolSearchSettings(settingsPath, options = {}) {
const now = options.now ?? new Date();
let initial;
try {
initial = await readFileSnapshot(settingsPath);
} catch (error) {
if (error?.code === "ENOENT") return { status: "missing" };
throw error;
}
const { metadata, content: original } = initial;
let settings;
try {
settings = JSON.parse(original);
} catch (error) {
throw new Error(`settings.json is invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
}
if (!isObject(settings)) throw new Error("settings.json root must be a JSON object");
if (!("toolSearch" in settings)) return { status: "missing-section" };
if (!isObject(settings.toolSearch)) return { status: "custom" };
if (
exactJsonValue(settings.toolSearch, CURRENT_TOOL_SEARCH_DEFAULTS)
|| exactJsonValue(settings.toolSearch, CURRENT_TOOL_SEARCH_RUNTIME_DEFAULTS)
) return { status: "current" };
const matchesPreviousSnapshot = exactJsonValue(settings.toolSearch, PREVIOUS_TOOL_SEARCH_DEFAULTS)
|| exactJsonValue(settings.toolSearch, PREVIOUS_TOOL_SEARCH_RUNTIME_DEFAULTS);
if (!exactJsonValue(settings.toolSearch, LEGACY_TOOL_SEARCH_DEFAULTS) && !matchesPreviousSnapshot) {
return { status: "custom" };
}
const updated = `${JSON.stringify({ ...settings, toolSearch: CURRENT_TOOL_SEARCH_DEFAULTS }, null, 2)}\n`;
const directory = dirname(settingsPath);
const backupPath = `${settingsPath}.bak.${backupTimestamp(now)}`;
const temporaryPath = join(
directory,
`.${basename(settingsPath)}.my-pi-${process.pid}-${Math.random().toString(16).slice(2)}.tmp`,
);
let backup;
let backupCreated = false;
try {
backup = await open(backupPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
backupCreated = true;
await backup.writeFile(original, "utf8");
await backup.sync();
await backup.close();
backup = undefined;
} catch (error) {
if (backup) await backup.close().catch(() => {});
if (backupCreated) await rm(backupPath, { force: true }).catch(() => {});
throw error;
}
let temporary;
try {
temporary = await open(temporaryPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
await temporary.writeFile(updated, "utf8");
await temporary.sync();
await temporary.close();
temporary = undefined;
if (options.beforeCommit) await options.beforeCommit();
const latest = await readFileSnapshot(settingsPath);
if (
latest.metadata.dev !== metadata.dev
|| latest.metadata.ino !== metadata.ino
|| latest.content !== original
) throw new Error("settings.json changed during migration; original file was preserved");
await rename(temporaryPath, settingsPath);
await chmod(settingsPath, 0o600);
} catch (error) {
if (temporary) await temporary.close().catch(() => {});
await rm(temporaryPath, { force: true }).catch(() => {});
throw error;
}
return { status: "migrated", backupPath };
}
async function main() {
const settingsPath = process.argv[2];
if (!settingsPath) {
console.error("usage: migrate-tool-search-settings.mjs <settings.json>");
process.exitCode = 2;
return;
}
const result = await migrateToolSearchSettings(settingsPath);
if (result.status === "migrated") console.log(`migrated:${result.backupPath}`);
else console.log(result.status);
}
function isMainModule() {
if (!process.argv[1]) return false;
try {
return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]);
} catch {
return false;
}
}
if (isMainModule()) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}