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

234 lines
7.1 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 VERSION_3_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 VERSION_3_TOOL_SEARCH_DEFAULTS = {
...VERSION_3_TOOL_SEARCH_RUNTIME_DEFAULTS,
bundleDefaultsVersion: 3,
};
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",
"context_tree_query",
],
showToolSearchFooterStatus: false,
maxActiveGroups: 5,
maxToolsPerGroup: 8,
maxDynamicTools: 28,
groupOverrides: {},
};
export const CURRENT_TOOL_SEARCH_DEFAULTS = {
...CURRENT_TOOL_SEARCH_RUNTIME_DEFAULTS,
bundleDefaultsVersion: 4,
};
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)
|| exactJsonValue(settings.toolSearch, VERSION_3_TOOL_SEARCH_DEFAULTS)
|| exactJsonValue(settings.toolSearch, VERSION_3_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;
});
}