feat: 组合包配置集中到 my-pi/ 目录并改为整体重建

- 组合包拥有、可随时重建的配置、日志与缓存统一放在
  <agentDir>/my-pi/:permission-system/(policy.jsonc、hard-guards.jsonc、
  logs/)、rtk-optimizer/config.json、tool-search/(config.json、
  catalog-v1.json)与 system-prompt-cover.md。hashline.json、lsp.json
  由外部扩展读取固定路径,是唯一例外。
- 新增 config/bundle-manifest.json 与 scripts/rebuild-bundle-config.mjs:
  先校验全部来源与目标,在临时目录构建完整树,再整体删除旧 my-pi/
  (符号链接只删链接)并原子替换,不备份。install.sh / update.sh 每次
  运行都调用它;扩展自身不再播种或迁移配置。
- update.sh 删除 pi update 失败后的 git clean 恢复逻辑:Pi 1.3.0 会在
  下一次 pi update 时依据中断标记自行恢复。同时删除 Tool Search
  settings.json 快照迁移与封面部署脚本。
- Tool Search 改为读取 my-pi/tool-search/config.json(源为
  config/tool-search.json,须与 BUNDLE_TOOL_SEARCH_DEFAULTS 一致),
  不再读写 settings.json 的 toolSearch 段,移除 bundleDefaultsVersion。
- 默认权限策略开启 debugLog。
- 旧位置的残留文件不迁移、不清理;AGENTS.md / README 同步新约束。

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
云服务部-叶林立
2026-10-19 02:26:57 -07:00
co-authored by Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent 7e6a8faae1
commit 2682bd7fa7
40 changed files with 711 additions and 1339 deletions
-135
View File
@@ -1,135 +0,0 @@
#!/usr/bin/env node
/**
* Deploys the bundle-authoritative system prompt cover into the Pi agent directory.
*
* The cover is bundle-owned configuration: the repository copy under
* `config/system-prompt-cover.md` is authoritative, and this helper synchronizes it to
* `<agentDir>/SYSTEM_COVER.md`. There is no user-owned variant, so an existing file is
* replaced atomically without keeping a backup.
*/
import { readFileSync, realpathSync } from "node:fs";
import { mkdir, open, rename, rm } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
export const COVER_FILE_NAME = "SYSTEM_COVER.md";
const scriptPath = fileURLToPath(import.meta.url);
const bundleRoot = dirname(dirname(scriptPath));
export const BUNDLED_COVER_PATH = join(bundleRoot, "config", "system-prompt-cover.md");
/**
* Resolve the Pi agent directory, mirroring Pi's own `getAgentDir()`.
*
* Implemented locally so this helper stays runnable from `install.sh` / `update.sh`
* without loading the Pi runtime.
*
* @param {NodeJS.ProcessEnv} [env]
* @param {string} homedir
* @returns {string}
*/
export function resolveAgentDir(env = process.env, homedir) {
const configured = env.PI_CODING_AGENT_DIR;
if (configured) {
return configured.startsWith("~/") ? join(homedir, configured.slice(2)) : configured;
}
return join(homedir, ".pi", "agent");
}
/**
* Compare the bundle cover against the deployed copy and replace it when they differ.
*
* Returns `{ status }`:
* - `current` — deployed copy already matches the bundle.
* - `updated` — deployed copy was replaced.
* - `created` — no deployed copy existed.
*
* Read or write failures throw so callers can report a real failure instead of
* silently leaving a stale cover in place.
*
* @param {{ agentDir?: string, bundledCoverPath?: string }} options
* @returns {Promise<{ status: "current" | "updated" | "created", targetPath: string }>}
*/
export async function deploySystemPromptCover({ agentDir, bundledCoverPath = BUNDLED_COVER_PATH } = {}) {
if (!agentDir) {
throw new Error("agentDir is required");
}
let bundledCover;
try {
bundledCover = readFileSync(bundledCoverPath, "utf8");
} catch (error) {
throw new Error(
`cannot read bundled system prompt cover at ${bundledCoverPath}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
const targetPath = join(agentDir, COVER_FILE_NAME);
let existing;
let existed = false;
try {
existing = readFileSync(targetPath, "utf8");
existed = true;
} catch (error) {
if (error?.code !== "ENOENT") {
throw new Error(
`cannot read deployed system prompt cover at ${targetPath}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
if (existed && existing === bundledCover) {
return { status: "current", targetPath };
}
await mkdir(agentDir, { recursive: true });
const temporaryPath = join(
agentDir,
`.${COVER_FILE_NAME}.my-pi-${process.pid}-${Math.random().toString(16).slice(2)}.tmp`,
);
try {
const handle = await open(temporaryPath, "wx", 0o644);
try {
await handle.writeFile(bundledCover, "utf8");
await handle.sync();
} finally {
await handle.close();
}
await rename(temporaryPath, targetPath);
} catch (error) {
await rm(temporaryPath, { force: true }).catch(() => {});
throw error;
}
return { status: existed ? "updated" : "created", targetPath };
}
function isMainModule() {
if (!process.argv[1]) return false;
try {
return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]);
} catch {
return false;
}
}
async function main() {
const agentDir = process.argv[2] || resolveAgentDir(process.env, process.env.HOME);
const { status } = await deploySystemPromptCover({ agentDir });
process.stdout.write(`${status}\n`);
}
if (isMainModule()) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
-233
View File
@@ -1,233 +0,0 @@
#!/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;
});
}
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env node
/**
* Rebuilds the bundle-owned config directory inside the Pi agent directory.
*
* Every piece of bundle-owned, rebuildable state lives under
* `<agentDir>/my-pi/` (policy files, Tool Search config, the system prompt
* cover, permission logs). `config/bundle-manifest.json` is the authoritative
* source→target list: this helper builds the full tree in a sibling temp
* directory, deletes any existing `my-pi/` wholesale — no backup — and renames
* the fresh tree into place, so a rebuild can never half-apply.
*
* Nothing outside `my-pi/` is read or removed; leftovers at the old locations
* are ignored rather than migrated.
*/
import { realpathSync } from "node:fs";
import { chmod, copyFile, lstat, mkdir, readFile, rename, rm, unlink } from "node:fs/promises";
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
const scriptPath = fileURLToPath(import.meta.url);
const bundleRoot = dirname(dirname(scriptPath));
export const BUNDLE_ROOT = bundleRoot;
export const MANIFEST_PATH = join(bundleRoot, "config", "bundle-manifest.json");
/** Thrown for an unusable agentDir argument; maps to CLI exit code 2. */
export class RebuildUsageError extends Error {}
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/**
* Load and validate the manifest.
*
* Every source must be a readable repo-relative file and every target a
* relative path that stays inside the bundle directory — a `..` or absolute
* target would escape `my-pi/` during the rebuild, so it is rejected before
* anything is touched.
*
* @param {string} manifestPath
* @returns {Promise<{ directory: string, files: Array<{ source: string, target: string }> }>}
*/
export async function loadManifest(manifestPath) {
let manifest;
try {
manifest = JSON.parse(await readFile(manifestPath, "utf8"));
} catch (error) {
throw new Error(
`cannot read bundle manifest at ${manifestPath}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
if (!isObject(manifest) || manifest.directory !== "my-pi" || !Array.isArray(manifest.files)) {
throw new Error(`bundle manifest at ${manifestPath} is malformed`);
}
const files = manifest.files.map((entry, index) => {
if (!isObject(entry) || typeof entry.source !== "string" || typeof entry.target !== "string") {
throw new Error(`bundle manifest entry ${index} lacks source/target strings`);
}
const directoryBase = resolve(manifest.directory);
const resolved = resolve(directoryBase, entry.target);
if (
isAbsolute(entry.target) ||
resolved === directoryBase ||
!resolved.startsWith(directoryBase + sep)
) {
throw new Error(
`bundle manifest target ${entry.target} escapes the ${manifest.directory}/ directory`,
);
}
const sourcePath = join(bundleRoot, entry.source);
return { source: entry.source, sourcePath, target: entry.target };
});
// Fail before deleting anything: a missing source must not wipe the live tree.
for (const file of files) {
try {
await readFile(file.sourcePath);
} catch (error) {
throw new Error(
`cannot read manifest source ${file.source}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
return { directory: manifest.directory, files };
}
/**
* Rebuild `<agentDir>/my-pi` from the bundle manifest.
*
* The tree is staged in `<agentDir>/.my-pi.rebuild-<pid>-<rand>` (dirs 0700,
* files 0600), then the existing `my-pi` is removed — a symlink is unlinked,
* never followed — and the stage is renamed into place. Any failure removes
* the stage and throws.
*
* @param {string} agentDir - Absolute Pi agent directory.
* @param {{ manifestPath?: string }} [options]
* @returns {Promise<{ targetDir: string }>}
*/
export async function rebuildBundleConfig(agentDir, { manifestPath = MANIFEST_PATH } = {}) {
if (typeof agentDir !== "string" || agentDir.length === 0 || !isAbsolute(agentDir)) {
throw new RebuildUsageError("rebuild-bundle-config requires an absolute agentDir argument");
}
const manifest = await loadManifest(manifestPath);
const targetDir = join(agentDir, manifest.directory);
const stageDir = join(
agentDir,
`.${manifest.directory}.rebuild-${process.pid}-${Math.random().toString(16).slice(2)}`,
);
try {
await mkdir(agentDir, { recursive: true, mode: 0o700 });
await mkdir(stageDir, { mode: 0o700 });
for (const file of manifest.files) {
const destination = join(stageDir, file.target);
await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
// copyFile keeps the source mode on some platforms; pin owner-only.
await copyFile(file.sourcePath, destination);
await chmod(destination, 0o600);
}
// Never follow a symlink: unlink the link itself, never its target.
try {
const stats = await lstat(targetDir);
if (stats.isSymbolicLink()) {
await unlink(targetDir);
} else {
await rm(targetDir, { recursive: true, force: true });
}
} catch (error) {
if (error?.code !== "ENOENT") throw error;
}
await rename(stageDir, targetDir);
return { targetDir };
} catch (error) {
await rm(stageDir, { recursive: true, force: true }).catch(() => {});
throw error;
}
}
function isMainModule() {
if (!process.argv[1]) return false;
try {
return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]);
} catch {
return false;
}
}
async function main() {
const agentDir = process.argv[2] ?? "";
if (agentDir.length === 0 || !isAbsolute(agentDir)) {
console.error("usage: rebuild-bundle-config.mjs <absolute-agent-dir>");
process.exitCode = 2;
return;
}
const { targetDir } = await rebuildBundleConfig(agentDir);
process.stdout.write(`rebuilt:${targetDir}\n`);
}
if (isMainModule()) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = error instanceof RebuildUsageError ? 2 : 1;
});
}