mirror of
https://bitbucket.org/siakitem/my-pi.git
synced 2026-10-26 10:45:22 +00:00
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:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
7e6a8faae1
commit
2682bd7fa7
@@ -0,0 +1,220 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { lstat, mkdir, mkdtemp, readdir, readFile, rm, stat, symlink, 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 {
|
||||
getGlobalConfigPath,
|
||||
getGlobalLogsDir,
|
||||
getHardGuardConfigPath,
|
||||
} from "../pi-permission-system/src/config-paths.ts";
|
||||
import {
|
||||
BUNDLE_TOOL_SEARCH_DEFAULTS,
|
||||
getToolSearchCatalogPath,
|
||||
getToolSearchConfigPath,
|
||||
} from "../pi-tool-search/extensions/config.ts";
|
||||
import { resolveCoverPath } from "../extensions/system-prompt-cover-config.ts";
|
||||
import { rebuildBundleConfig } from "../scripts/rebuild-bundle-config.mjs";
|
||||
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const rebuildScript = join(repositoryRoot, "scripts", "rebuild-bundle-config.mjs");
|
||||
const manifestPath = join(repositoryRoot, "config", "bundle-manifest.json");
|
||||
|
||||
interface ManifestFile {
|
||||
source: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {
|
||||
version: number;
|
||||
directory: string;
|
||||
files: ManifestFile[];
|
||||
};
|
||||
|
||||
async function makeTempDir() {
|
||||
return mkdtemp(join(tmpdir(), "my-pi-rebuild-"));
|
||||
}
|
||||
|
||||
function modeOf(path: string): Promise<number> {
|
||||
return stat(path).then((info) => info.mode & 0o777);
|
||||
}
|
||||
|
||||
async function readSnapshot(path: string): Promise<string> {
|
||||
return readFile(path, "utf8");
|
||||
}
|
||||
|
||||
test("rebuild replaces the my-pi tree with byte-identical manifest targets and leaves outside files alone", async () => {
|
||||
const dir = await makeTempDir();
|
||||
try {
|
||||
// Pre-existing junk inside the managed directory must disappear entirely.
|
||||
await mkdir(join(dir, "my-pi", "permission-system"), { recursive: true });
|
||||
await writeFile(join(dir, "my-pi", "permission-system", "policy.jsonc"), "STALE POLICY", "utf8");
|
||||
await writeFile(join(dir, "my-pi", "leftover.txt"), "JUNK", "utf8");
|
||||
await mkdir(join(dir, "my-pi", "stray", "deep"), { recursive: true });
|
||||
|
||||
// Files outside my-pi/ must survive byte-identical — the script owns only my-pi/.
|
||||
const outside = [
|
||||
join(dir, "settings.json"),
|
||||
join(dir, "sessions", "abc", "session.jsonl"),
|
||||
join(dir, "extensions", "pi-permission-system", "policy.jsonc"),
|
||||
];
|
||||
for (const path of outside) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, `outside ${path}\n`, "utf8");
|
||||
}
|
||||
const before = new Map(await Promise.all(outside.map(async (p) => [p, await readSnapshot(p)])));
|
||||
|
||||
await rebuildBundleConfig(dir);
|
||||
|
||||
const myPi = join(dir, "my-pi");
|
||||
const expectedFiles = new Set(manifest.files.map((file) => file.target));
|
||||
const actualFiles: string[] = [];
|
||||
const walk = async (root: string, rel: string) => {
|
||||
for (const entry of await readdir(root, { withFileTypes: true })) {
|
||||
const next = rel ? `${rel}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) await walk(join(root, entry.name), next);
|
||||
else actualFiles.push(next);
|
||||
}
|
||||
};
|
||||
await walk(myPi, "");
|
||||
assert.deepEqual(actualFiles.sort(), [...expectedFiles].sort(), "my-pi must contain exactly the manifest targets");
|
||||
|
||||
for (const file of manifest.files) {
|
||||
const target = join(myPi, file.target);
|
||||
assert.equal(await readFile(target, "utf8"), await readFile(join(repositoryRoot, file.source), "utf8"));
|
||||
assert.equal(await modeOf(target), 0o600, `${file.target} must be owner-only`);
|
||||
assert.equal(await modeOf(dirname(target)), 0o700, `${dirname(file.target)} must be owner-only`);
|
||||
}
|
||||
|
||||
for (const [path, content] of before) {
|
||||
assert.equal(await readSnapshot(path), content, `outside file ${path} must be untouched`);
|
||||
}
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects an empty or relative agentDir without deleting anything", async () => {
|
||||
const dir = await makeTempDir();
|
||||
try {
|
||||
const sentinel = join(dir, "keep.txt");
|
||||
await writeFile(sentinel, "keep", "utf8");
|
||||
|
||||
await assert.rejects(rebuildBundleConfig(""), /absolute/);
|
||||
await assert.rejects(rebuildBundleConfig("relative/dir"), /absolute/);
|
||||
assert.equal(await readFile(sentinel, "utf8"), "keep");
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("CLI rejects a relative agentDir and reports the failure", async () => {
|
||||
const dir = await makeTempDir();
|
||||
try {
|
||||
await mkdir(join(dir, "my-pi"), { recursive: true });
|
||||
await writeFile(join(dir, "my-pi", "sentinel.txt"), "still here", "utf8");
|
||||
|
||||
const failure = spawnSync(process.execPath, [rebuildScript, "relative/dir"], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
assert.equal(failure.status, 2);
|
||||
assert.match(failure.stderr ?? "", /absolute/);
|
||||
assert.equal(await readFile(join(dir, "my-pi", "sentinel.txt"), "utf8"), "still here");
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("CLI prints rebuilt:<path> on success", async () => {
|
||||
const dir = await makeTempDir();
|
||||
try {
|
||||
const result = spawnSync(process.execPath, [rebuildScript, dir], { encoding: "utf8" });
|
||||
assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
|
||||
assert.equal(result.stdout.trim(), `rebuilt:${join(dir, "my-pi")}`);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a manifest target escaping the directory is rejected without deleting my-pi", async () => {
|
||||
const dir = await makeTempDir();
|
||||
try {
|
||||
await mkdir(join(dir, "my-pi"), { recursive: true });
|
||||
await writeFile(join(dir, "my-pi", "sentinel.txt"), "still here", "utf8");
|
||||
|
||||
const badManifestPath = join(dir, "bad-manifest.json");
|
||||
await writeFile(
|
||||
badManifestPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
directory: "my-pi",
|
||||
files: [{ source: "config/tool-search.json", target: "../escape.txt" }],
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
await assert.rejects(
|
||||
rebuildBundleConfig(dir, { manifestPath: badManifestPath }),
|
||||
/escapes/,
|
||||
);
|
||||
assert.equal(await readFile(join(dir, "my-pi", "sentinel.txt"), "utf8"), "still here");
|
||||
await assert.rejects(readFile(join(dir, "escape.txt"), "utf8"), /ENOENT/);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a symlinked my-pi is replaced, never followed", async () => {
|
||||
const dir = await makeTempDir();
|
||||
const elsewhere = await makeTempDir();
|
||||
try {
|
||||
const targetContent = join(elsewhere, "precious.txt");
|
||||
await writeFile(targetContent, "do not touch", "utf8");
|
||||
await symlink(elsewhere, join(dir, "my-pi"), "dir");
|
||||
|
||||
await rebuildBundleConfig(dir);
|
||||
|
||||
// The link itself must be replaced by a real directory…
|
||||
const rebuilt = await stat(join(dir, "my-pi"));
|
||||
assert.ok(rebuilt.isDirectory());
|
||||
assert.ok(!(await lstat(join(dir, "my-pi"))).isSymbolicLink(), "my-pi must be a real directory now");
|
||||
|
||||
// …and the link target's contents must survive untouched.
|
||||
assert.equal(await readFile(targetContent, "utf8"), "do not touch");
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await rm(elsewhere, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("manifest targets match the paths the extensions actually read", () => {
|
||||
const targets = new Map(manifest.files.map((file) => [file.target, file.source]));
|
||||
const agentDir = "/agent";
|
||||
const base = `${agentDir}/${manifest.directory}`;
|
||||
|
||||
const expectTarget = (source: string, resolved: string, suffix: string) => {
|
||||
assert.ok(resolved.startsWith(`${base}/`), `${resolved} must live under ${base}`);
|
||||
assert.equal(
|
||||
targets.get(resolved.slice(base.length + 1)),
|
||||
source,
|
||||
`${resolved} must be a manifest target backed by ${source}`,
|
||||
);
|
||||
assert.ok(resolved.endsWith(suffix), `${resolved} must end with ${suffix}`);
|
||||
};
|
||||
|
||||
expectTarget("config/pi-permission-policy.jsonc", getGlobalConfigPath(agentDir), "my-pi/permission-system/policy.jsonc");
|
||||
expectTarget("config/pi-permission-hard-guards.jsonc", getHardGuardConfigPath(agentDir), "my-pi/permission-system/hard-guards.jsonc");
|
||||
expectTarget("config/tool-search.json", getToolSearchConfigPath(agentDir), "my-pi/tool-search/config.json");
|
||||
expectTarget("config/system-prompt-cover.md", resolveCoverPath(agentDir), "my-pi/system-prompt-cover.md");
|
||||
|
||||
// Runtime state that is created rather than deployed must still live under my-pi/.
|
||||
assert.ok(getGlobalLogsDir(agentDir).endsWith("my-pi/permission-system/logs"));
|
||||
assert.ok(getToolSearchCatalogPath(agentDir).endsWith("my-pi/tool-search/catalog-v1.json"));
|
||||
});
|
||||
|
||||
test("deployed tool-search config is exactly BUNDLE_TOOL_SEARCH_DEFAULTS", async () => {
|
||||
const deployed = JSON.parse(await readFile(join(repositoryRoot, "config", "tool-search.json"), "utf8"));
|
||||
assert.deepEqual(deployed, BUNDLE_TOOL_SEARCH_DEFAULTS);
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -201,34 +201,4 @@ test("all package extensions load together without global registration conflicts
|
||||
|
||||
assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
|
||||
assert.doesNotMatch(`${result.stdout}\n${result.stderr}`, /Failed to load extension|conflicts with/u);
|
||||
const deployedPermissionPolicy = await readFile(
|
||||
join(home, ".pi-agent", "extensions", "pi-permission-system", "policy.jsonc"),
|
||||
"utf8",
|
||||
);
|
||||
const deployedHardGuards = await readFile(
|
||||
join(home, ".pi-agent", "extensions", "pi-permission-system", "hard-guards.jsonc"),
|
||||
"utf8",
|
||||
);
|
||||
assert.equal(deployedPermissionPolicy, permissionPolicySource, "the seeded policy must match the bundle source");
|
||||
assert.equal(deployedHardGuards, hardGuardSource, "the seeded hard guards must match the bundle source");
|
||||
|
||||
const deployedConfigDir = join(home, ".pi-agent", "extensions", "pi-permission-system");
|
||||
const deployedPolicyPath = join(deployedConfigDir, "policy.jsonc");
|
||||
const deployedHardGuardPath = join(deployedConfigDir, "hard-guards.jsonc");
|
||||
const customPolicy = `{ "permission": { "*": "deny" } }\n`;
|
||||
const customHardGuards = `{ "version": 1, "permission": { "*": "allow" } }\n`;
|
||||
await writeFile(deployedPolicyPath, customPolicy, "utf8");
|
||||
await writeFile(deployedHardGuardPath, customHardGuards, "utf8");
|
||||
const preserveResult = runBundle();
|
||||
assert.equal(preserveResult.status, 0, `${preserveResult.stdout}\n${preserveResult.stderr}`);
|
||||
assert.equal(await readFile(deployedPolicyPath, "utf8"), customPolicy, "reload must preserve user policy edits");
|
||||
assert.equal(await readFile(deployedHardGuardPath, "utf8"), customHardGuards, "reload must preserve user hard guards");
|
||||
|
||||
await rm(deployedPolicyPath);
|
||||
const legacyPolicy = `{ "authorizerChain": ["auto-review"], "permission": { "*": "ask" } }\n`;
|
||||
await writeFile(join(deployedConfigDir, "config.json"), legacyPolicy, "utf8");
|
||||
const migrationResult = runBundle();
|
||||
assert.equal(migrationResult.status, 0, `${migrationResult.stdout}\n${migrationResult.stderr}`);
|
||||
assert.equal(await readFile(deployedPolicyPath, "utf8"), legacyPolicy, "legacy config.json must seed policy.jsonc once");
|
||||
assert.equal(await readFile(deployedHardGuardPath, "utf8"), customHardGuards, "legacy migration must not replace hard guards");
|
||||
});
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
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,
|
||||
@@ -149,8 +143,10 @@ test("readCoverFile returns undefined when the file is absent or blank", async (
|
||||
const dir = await makeTempDir();
|
||||
try {
|
||||
const coverPath = resolveCoverPath(dir);
|
||||
assert.equal(coverPath, join(dir, "my-pi", "system-prompt-cover.md"));
|
||||
assert.equal(readCoverFile(coverPath), undefined);
|
||||
|
||||
await mkdir(dirname(coverPath), { recursive: true });
|
||||
await writeFile(coverPath, " \n\n", "utf8");
|
||||
assert.equal(readCoverFile(coverPath), undefined);
|
||||
|
||||
@@ -160,58 +156,3 @@ test("readCoverFile returns undefined when the file is absent or blank", async (
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
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, 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`);
|
||||
}
|
||||
});
|
||||
|
||||
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"),
|
||||
);
|
||||
// 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"),
|
||||
);
|
||||
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/);
|
||||
});
|
||||
@@ -1,171 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { chmod, copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import test from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const repositoryRoot = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
|
||||
async function fixture(
|
||||
t: test.TestContext,
|
||||
options: { createMarker?: boolean; origin?: string; secondPiStatus?: number } = {},
|
||||
) {
|
||||
const root = await mkdtemp(join(tmpdir(), "my-pi-update-clean-recovery-"));
|
||||
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 target = join(agentDir, "git", "bitbucket.org", "siakitem", "my-pi");
|
||||
const marker = join(agentDir, "git", "bitbucket.org", "siakitem", ".my-pi.pi-update-incomplete");
|
||||
const piLog = join(root, "pi.log");
|
||||
const piCount = join(root, "pi.count");
|
||||
const gitLog = join(root, "git.log");
|
||||
const cleanCount = join(root, "clean.count");
|
||||
|
||||
await mkdir(join(target, ".git"), { recursive: true });
|
||||
await mkdir(join(target, "config"), { recursive: true });
|
||||
await copyFile(join(repositoryRoot, "config", "p10k.zsh"), join(target, "config", "p10k.zsh"));
|
||||
await copyFile(
|
||||
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(
|
||||
join(bin, "pi"),
|
||||
`#!/bin/sh
|
||||
count=0
|
||||
[ ! -f "$MOCK_PI_COUNT" ] || count=$(cat "$MOCK_PI_COUNT")
|
||||
count=$((count + 1))
|
||||
printf '%s\n' "$count" > "$MOCK_PI_COUNT"
|
||||
printf 'pi %s\n' "$*" >> "$MOCK_PI_LOG"
|
||||
if [ "$count" -eq 1 ]; then
|
||||
if [ "$MOCK_CREATE_MARKER" = 1 ]; then
|
||||
: > "$MOCK_MARKER"
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
if [ "$MOCK_SECOND_PI_STATUS" -eq 0 ]; then
|
||||
rm -f "$MOCK_MARKER"
|
||||
fi
|
||||
exit "$MOCK_SECOND_PI_STATUS"
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
await chmod(join(bin, "pi"), 0o755);
|
||||
|
||||
await writeFile(
|
||||
join(bin, "git"),
|
||||
`#!/bin/sh
|
||||
printf 'git %s\n' "$*" >> "$MOCK_GIT_LOG"
|
||||
case "$*" in
|
||||
*" rev-parse --show-toplevel")
|
||||
printf '%s\n' "$MOCK_GIT_TARGET"
|
||||
;;
|
||||
*" remote get-url origin")
|
||||
printf '%s\n' "$MOCK_GIT_ORIGIN"
|
||||
;;
|
||||
*" clean -fdx")
|
||||
count=0
|
||||
[ ! -f "$MOCK_CLEAN_COUNT" ] || count=$(cat "$MOCK_CLEAN_COUNT")
|
||||
count=$((count + 1))
|
||||
printf '%s\n' "$count" > "$MOCK_CLEAN_COUNT"
|
||||
if [ "$count" -eq 1 ]; then
|
||||
printf '%s\n' 'warning: failed to remove node_modules/: Directory not empty' >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
await chmod(join(bin, "git"), 0o755);
|
||||
|
||||
await writeFile(join(bin, "uname"), "#!/bin/sh\nprintf '%s\\n' Linux\n", "utf8");
|
||||
await chmod(join(bin, "uname"), 0o755);
|
||||
|
||||
const env = {
|
||||
...process.env,
|
||||
HOME: home,
|
||||
XDG_CONFIG_HOME: join(home, ".config"),
|
||||
PI_CODING_AGENT_DIR: agentDir,
|
||||
MOCK_CREATE_MARKER: options.createMarker === false ? "0" : "1",
|
||||
MOCK_MARKER: marker,
|
||||
MOCK_PI_COUNT: piCount,
|
||||
MOCK_PI_LOG: piLog,
|
||||
MOCK_SECOND_PI_STATUS: String(options.secondPiStatus ?? 0),
|
||||
MOCK_GIT_LOG: gitLog,
|
||||
MOCK_CLEAN_COUNT: cleanCount,
|
||||
MOCK_GIT_TARGET: target,
|
||||
MOCK_GIT_ORIGIN: options.origin ?? "git@bitbucket.org:siakitem/my-pi.git",
|
||||
PATH: `${bin}:${dirname(process.execPath)}:/usr/bin:/bin`,
|
||||
ZSH: "",
|
||||
ZSH_CUSTOM: "",
|
||||
ZDOTDIR: home,
|
||||
};
|
||||
delete env.PI_PACKAGE_SOURCE;
|
||||
|
||||
return { cleanCount, env, gitLog, marker, piCount, piLog };
|
||||
}
|
||||
|
||||
test("update.sh retries an identity-checked interrupted Git cleanup before retrying pi update", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const result = spawnSync("sh", [join(repositoryRoot, "update.sh")], {
|
||||
cwd: repositoryRoot,
|
||||
env: f.env,
|
||||
encoding: "utf8",
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
assert.equal(result.status, 0, result.stderr || result.stdout);
|
||||
assert.equal((await readFile(f.piCount, "utf8")).trim(), "2");
|
||||
assert.equal((await readFile(f.cleanCount, "utf8")).trim(), "2");
|
||||
assert.match(result.stdout, /检测到默认组合包的 Pi Git 升级中断/);
|
||||
assert.match(result.stdout, /第 2 次尝试后完成/);
|
||||
await assert.rejects(readFile(f.marker, "utf8"), { code: "ENOENT" });
|
||||
});
|
||||
|
||||
test("update.sh keeps the original fail-fast behavior when no update marker exists", async (t) => {
|
||||
const f = await fixture(t, { createMarker: false });
|
||||
const result = spawnSync("sh", [join(repositoryRoot, "update.sh")], {
|
||||
cwd: repositoryRoot,
|
||||
env: f.env,
|
||||
encoding: "utf8",
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
assert.equal(result.status, 1);
|
||||
assert.equal((await readFile(f.piCount, "utf8")).trim(), "1");
|
||||
await assert.rejects(readFile(f.gitLog, "utf8"), { code: "ENOENT" });
|
||||
assert.match(result.stderr, /pi update 执行失败/);
|
||||
});
|
||||
|
||||
test("update.sh refuses cleanup when the cached checkout origin does not match", async (t) => {
|
||||
const f = await fixture(t, { origin: "git@example.invalid:other/package.git" });
|
||||
const result = spawnSync("sh", [join(repositoryRoot, "update.sh")], {
|
||||
cwd: repositoryRoot,
|
||||
env: f.env,
|
||||
encoding: "utf8",
|
||||
timeout: 30_000,
|
||||
});
|
||||
|
||||
assert.equal(result.status, 1);
|
||||
assert.equal((await readFile(f.piCount, "utf8")).trim(), "1");
|
||||
const gitLog = await readFile(f.gitLog, "utf8");
|
||||
assert.doesNotMatch(gitLog, /clean -fdx/);
|
||||
assert.match(result.stderr, /checkout 身份校验失败/);
|
||||
});
|
||||
Reference in New Issue
Block a user