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 通过。
This commit is contained in:
云服务部-叶林立
2026-10-15 18:02:03 -07:00
parent cdd91b3f8b
commit dec48dab6d
24 changed files with 675 additions and 20 deletions
+11
View File
@@ -138,6 +138,17 @@ test("all package extensions load together without global registration conflicts
packageJson.pi.extensions.includes("./pi-hermes-memory/src/index.ts"),
"the bundle must load the locally maintained Hermes memory extension",
);
// The cover must rewrite the prompt before tool-routing flattens it into a forced prompt;
// once flattened, later handlers cannot restore the section structure.
assert.ok(
packageJson.pi.extensions.includes("./extensions/system-prompt-cover.ts"),
"the bundle must load the system prompt cover extension",
);
assert.ok(
packageJson.pi.extensions.indexOf("./extensions/system-prompt-cover.ts") <
packageJson.pi.extensions.indexOf("./extensions/tool-routing.ts"),
"the system prompt cover must run before tool-routing forces the prompt",
);
assert.equal(packageJson.dependencies["pi-hermes-memory"], "file:./pi-hermes-memory");
assert.ok(
packageJson.files.includes("pi-hermes-memory"),
+217
View File
@@ -0,0 +1,217 @@
import assert from "node:assert/strict";
import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { execFileSync } 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 {
COVER_FILE_NAME,
deploySystemPromptCover,
resolveAgentDir,
} from "../scripts/deploy-system-prompt-cover.mjs";
import {
readCoverFile,
resolveCoverPath,
spliceCover,
} from "../extensions/system-prompt-cover-config.ts";
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bundledCoverPath = join(repositoryRoot, "config", "system-prompt-cover.md");
const DEFAULT_PREAMBLE =
"You are an expert coding assistant operating inside pi, a coding agent harness. " +
"You help users by reading files, executing commands, editing code, and writing new files.";
/** A rendered prompt shaped like Pi's: preamble, then tag-wrapped top-level sections. */
function renderedPrompt(preamble = DEFAULT_PREAMBLE) {
return [
preamble,
"<tools>",
"- read: reads files",
"</tools>",
"<rules>",
"- Be concise",
"</rules>",
"<skills>",
"<available_skills>",
" <skill>",
" <name>s</name>",
" </skill>",
"</available_skills>",
"</skills>",
"<project_context>",
'<project_instructions path="/work/AGENTS.md">',
"Nested content with a </project_context>-looking line is not a tag.",
"</project_instructions>",
"</project_context>",
"<cwd>",
"/work",
"</cwd>",
].join("\n");
}
function tagsOf(text: string): string[] {
return [...text.matchAll(/^<([a-z][a-z0-9_-]*)>$/gm)].map((match) => match[1]);
}
async function makeTempDir() {
return mkdtemp(join(tmpdir(), "my-pi-cover-"));
}
test("bundled cover holds Pi's default preamble text", async () => {
const content = await readFile(bundledCoverPath, "utf8");
assert.equal(content.replace(/\s+$/, ""), DEFAULT_PREAMBLE);
});
test("spliceCover replaces only the preamble and preserves the remaining bytes", () => {
const rendered = renderedPrompt();
const spliced = spliceCover(rendered, "MY CUSTOM COVER");
assert.ok(spliced.startsWith("MY CUSTOM COVER\n"));
// Everything after the preamble's terminating newline is untouched.
const originalTail = rendered.slice(rendered.indexOf("\n<tools>"));
assert.ok(spliced.endsWith(originalTail));
// Section order — including nested tags — is identical to the unmodified prompt.
assert.deepEqual(tagsOf(spliced), tagsOf(rendered));
assert.deepEqual(tagsOf(spliced), [
"tools",
"rules",
"skills",
"available_skills",
"project_context",
"cwd",
]);
});
test("spliceCover keeps section order rather than appending recovered sections", () => {
const rendered = renderedPrompt("ORIGINAL COVER");
const spliced = spliceCover(rendered, "NEW COVER");
const order = tagsOf(spliced).join(",");
assert.equal(order, "tools,rules,skills,available_skills,project_context,cwd");
assert.ok(
order.indexOf("tools") < order.indexOf("cwd"),
"tools must still precede cwd; a re-appended section list would invert this",
);
assert.ok(
order.indexOf("project_context") < order.indexOf("cwd"),
"project_context must keep its original position",
);
});
test("spliceCover tolerates a trailing newline from the editor and a blank cover", () => {
const rendered = renderedPrompt();
assert.equal(spliceCover(rendered, "COVER\n\n"), spliceCover(rendered, "COVER"));
// A whitespace-only cover leaves an empty preamble but still keeps every section.
const blank = spliceCover(rendered, " \n");
assert.equal(blank, rendered.slice(rendered.indexOf("\n<tools>")));
assert.deepEqual(tagsOf(blank), tagsOf(rendered));
});
test("spliceCover degenerates to the cover when the prompt has no sections", () => {
assert.equal(spliceCover("just a preamble", "NEW"), "NEW");
assert.equal(spliceCover("", "NEW"), "NEW");
});
test("spliceCover keeps an attribute-bearing nested tag inside its parent section", () => {
// Pi nests <project_instructions path="..."> inside the bare <project_context> tag, so the
// boundary must be the first *bare* tag line and the nested markup must survive verbatim.
const rendered = [
"ORIGINAL COVER",
"<tools>",
"- read: reads files",
"</tools>",
"<project_context>",
'<project_instructions path="/work/AGENTS.md">',
"nested instructions",
"</project_instructions>",
"</project_context>",
"<cwd>",
"/work",
"</cwd>",
].join("\n");
const spliced = spliceCover(rendered, "NEW");
assert.equal(tagsOf(spliced).join(","), "tools,project_context,cwd");
assert.ok(spliced.startsWith("NEW\n<tools>"));
assert.ok(
spliced.includes('<project_instructions path="/work/AGENTS.md">\nnested instructions\n</project_instructions>'),
"nested project instructions must be preserved byte-for-byte",
);
});
test("readCoverFile returns undefined when the file is absent or blank", async () => {
const dir = await makeTempDir();
try {
const coverPath = resolveCoverPath(dir);
assert.equal(readCoverFile(coverPath), undefined);
await writeFile(coverPath, " \n\n", "utf8");
assert.equal(readCoverFile(coverPath), undefined);
await writeFile(coverPath, " REAL COVER \n", "utf8");
assert.equal(readCoverFile(coverPath), " REAL COVER");
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("resolveAgentDir honours PI_CODING_AGENT_DIR and defaults to ~/.pi/agent", () => {
assert.equal(resolveAgentDir({}, "/home/u"), "/home/u/.pi/agent");
assert.equal(resolveAgentDir({ PI_CODING_AGENT_DIR: "/custom/agent" }, "/home/u"), "/custom/agent");
assert.equal(resolveAgentDir({ PI_CODING_AGENT_DIR: "~/other" }, "/home/u"), "/home/u/other");
});
test("deploySystemPromptCover creates, is idempotent, and overwrites without a backup", async () => {
const dir = await makeTempDir();
try {
const target = join(dir, COVER_FILE_NAME);
assert.equal((await deploySystemPromptCover({ agentDir: dir })).status, "created");
assert.equal(await readFile(target, "utf8"), await readFile(bundledCoverPath, "utf8"));
assert.equal((await deploySystemPromptCover({ agentDir: dir })).status, "current");
await writeFile(target, "USER EDITED COVER\n", "utf8");
assert.equal((await deploySystemPromptCover({ agentDir: dir })).status, "updated");
assert.equal(await readFile(target, "utf8"), await readFile(bundledCoverPath, "utf8"));
// No backup and no temporary file may survive an overwrite.
assert.deepEqual(await readdir(dir), [COVER_FILE_NAME]);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("deploySystemPromptCover fails loudly when the bundled cover is unreadable", async () => {
const dir = await makeTempDir();
try {
await assert.rejects(
deploySystemPromptCover({ agentDir: dir, bundledCoverPath: join(dir, "missing.md") }),
/cannot read bundled system prompt cover/,
);
// The failure must not leave a partial file behind.
assert.deepEqual(await readdir(dir), []);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("deploy-system-prompt-cover.mjs prints a status line and exits zero", async () => {
const dir = await makeTempDir();
try {
const helper = join(repositoryRoot, "scripts", "deploy-system-prompt-cover.mjs");
const first = execFileSync(process.execPath, [helper, dir], { encoding: "utf8" }).trim();
const second = execFileSync(process.execPath, [helper, dir], { encoding: "utf8" }).trim();
assert.equal(first, "created");
assert.equal(second, "current");
} finally {
await rm(dir, { recursive: true, force: true });
}
});
+11 -1
View File
@@ -98,7 +98,7 @@ test("migrates the previous versioned default snapshot and pins the Hermes memor
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);
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`);
}
@@ -168,6 +168,16 @@ async function updateFixture(t: test.TestContext, piExitStatus = 0) {
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"),
+11
View File
@@ -32,6 +32,17 @@ async function fixture(
join(repositoryRoot, "config", "pi-hashline-edit.json"),
join(target, "config", "pi-hashline-edit.json"),
);
// A real released bundle also ships `scripts/`; the update flow locates its helpers
// there rather than falling back to a possibly stale script directory.
await mkdir(join(target, "scripts"), { recursive: true });
await copyFile(
join(repositoryRoot, "config", "system-prompt-cover.md"),
join(target, "config", "system-prompt-cover.md"),
);
await copyFile(
join(repositoryRoot, "scripts", "deploy-system-prompt-cover.mjs"),
join(target, "scripts", "deploy-system-prompt-cover.mjs"),
);
await mkdir(bin, { recursive: true });
await writeFile(