pi-patch-keeper 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.ts +578 -128
  2. package/package.json +3 -2
package/index.ts CHANGED
@@ -1,161 +1,611 @@
1
- /**
2
- * pi-patch-keeper — extension load-order guard for the pi coding agent.
1
+ /**
2
+ * patch-keeper —— 补丁自愈与状态检测(pi 扩展,外置 · 模块化 · 抗上游升级)
3
3
  *
4
- * Force-type extensions (those returning { systemPrompt } / forceSystemPrompt)
5
- * replace the whole system prompt, silently dropping every section written by
6
- * handlers that run after them. This extension keeps known force-type packages
7
- * at the tail of settings.json "packages" and reports packages that still follow
8
- * one of them.
4
+ * ## 为什么存在
5
+ * 本机对「别人的东西」的全部改动登记在快照 `05-脚本补丁/PATCH-REGISTRY.md`(唯一权威清单):
6
+ * PiDeck app.asar ×3(只检测)、npm 包 ×2(pi-lens / pi-memory,自愈)、PiDeck builtin ×5(双份自愈)、
7
+ * npm 包注入通道 ×2(pi-memory / tactician 改 section)。
8
+ * 上游一升级就覆盖,得重跑桌面上的补丁脚本 —— 容易忘。这个扩展把它变成自愈:
9
+ * 每次 pi 启动时检查一遍,能修的直接修,不能修的(PiDeck 正开着,asar 被锁)明确报出来。
9
10
  *
10
- * Release edition: no machine-specific patch healing (source patches, PiDeck
11
- * asar, memory fixes) is included.
11
+ * ## 为什么能修 pi-lens
12
+ * pi 的资源加载有优先级(dist/core/package-manager.js resourcePrecedenceRank):
13
+ * 0/1 project · 2/3 user(本扩展)· 4 package(pi-lens)· 5 builtin
14
+ * 本扩展是「user 扩展」= rank 2,pi-lens 是「package 扩展」= rank 4,**先加载**。
15
+ * 所以在 factory 里同步改 dist/index.js,pi-lens 随后 import 到的就是打过补丁的内容 —— 当轮生效。
16
+ *
17
+ * ## 边界(刻意的)
18
+ * - PiDeck asar:**只检测不修**。PiDeck 正开着,文件被锁;且插件无权碰 Electron 主进程。
19
+ * 检测到未打补丁 → 提示跑 `run-all.cmd` / `launch-pideck.cmd`(桌面 PI脚本补丁/ 不在时用快照副本 05-脚本补丁/)。
20
+ * - 任何失败都只 notify,不抛错、不影响会话(纪律:不合法就跳过 + 记日志,绝不崩溃)。
12
21
  */
13
- import { existsSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
22
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
23
+ import { existsSync, readFileSync, writeFileSync, copyFileSync, readdirSync } from "node:fs";
24
+ import { createHash } from "node:crypto";
14
25
  import * as os from "node:os";
15
26
  import * as path from "node:path";
16
27
 
28
+ // 路径从 home / %LOCALAPPDATA% 推导(不写死用户名:换机 / 换用户名 / 复刻包到别的机器仍可用)
17
29
  const HOME = os.homedir();
30
+ const LOCALAPPDATA = process.env.LOCALAPPDATA ?? path.join(HOME, "AppData", "Local");
31
+ const PI_LENS = path.join(HOME, ".pi", "agent", "npm", "node_modules", "pi-lens", "dist", "index.js");
32
+ const PI_MEMORY = path.join(HOME, ".pi", "agent", "npm", "node_modules", "pi-memory", "index.ts");
33
+ const ASAR = path.join(LOCALAPPDATA, "Programs", "PiDeck", "resources", "app.asar");
34
+ // 唯一处置入口:快照 05-脚本补丁/(桌面旧目录 PI脚本补丁/ 已不存在,2026-10-15 核实)
35
+ const SNAPSHOT_PATCH_DIR = path.join(HOME, "Desktop", "pi-env-snapshot", "05-脚本补丁");
36
+ // 环境指纹文件(settings 关键字段,用于漂移检测)
37
+ const FINGERPRINT = path.join(HOME, ".pi", "patch-keeper.json");
18
38
  const SETTINGS = path.join(HOME, ".pi", "agent", "settings.json");
19
- const CONFIG = path.join(HOME, ".pi", "patch-keeper.json");
20
- const NPM_DIR = path.join(HOME, ".pi", "agent", "npm", "node_modules");
21
- const DEFAULT_TAIL = ["npm:pi-rtk-optimizer", "npm:pi-cache-optimizer"];
39
+ // 手册(注入对齐检测:本轮注入文本的版本行 vs 磁盘版)
40
+ const MANUAL = path.join(HOME, ".pi", "agent", "APPEND_SYSTEM.md");
41
+
42
+ // PiDeck 内置扩展补丁(本机修改;升级会覆盖,缺失时提示从快照恢复)
43
+ const PIDECK_BUILTIN = path.join(HOME, "AppData", "Roaming", "PiDeck", "builtin-extensions");
44
+ const PIDECK_INSTALL = path.join(process.env.LOCALAPPDATA ?? path.join(HOME, "AppData", "Local"), "Programs", "PiDeck", "resources", "extensions");
45
+ // needle = 本机修复特征串(不是 section 名):命中即视为已打;升级覆盖后从快照恢复。
46
+ const BUILTIN_PATCHES: Array<{ file: string; install: string; needle: string; name: string }> = [
47
+ { file: path.join(PIDECK_BUILTIN, "pi-deck-security-gate.ts"), install: path.join(PIDECK_INSTALL, "pi-deck-security-gate.ts"), needle: "越界操作先说明理由", name: "security-gate" },
48
+ { file: path.join(PIDECK_BUILTIN, "pi-deck-plan-mode.ts"), install: path.join(PIDECK_INSTALL, "pi-deck-plan-mode.ts"), needle: "keepThirdParty", name: "plan-mode" },
49
+ { file: path.join(PIDECK_BUILTIN, "pi-deck-goal-mode.ts"), install: path.join(PIDECK_INSTALL, "pi-deck-goal-mode.ts"), needle: "roundLine", name: "goal-mode" },
50
+ { file: path.join(PIDECK_BUILTIN, "pi-deck-trash-guard.ts"), install: path.join(PIDECK_INSTALL, "pi-deck-trash-guard.ts"), needle: "deleteFlagStyle", name: "trash-guard" },
51
+ { file: path.join(PIDECK_BUILTIN, "pi-deck-session-title.ts"), install: path.join(PIDECK_INSTALL, "pi-deck-session-title.ts"), needle: "TITLE_SOURCE_MARKER_HEAD", name: "session-title" },
52
+ ];
53
+ const SNAPSHOT_BUILTIN = path.join(HOME, "Desktop", "pi-env-snapshot", "03-PiDeck", "builtin-extensions");
54
+ const MANUAL_STATE = path.join(HOME, ".pi", "patch-keeper-manual.json");
55
+ /**
56
+ * 从手册文本里取版本号(标题「自主工作手册」后 200 字符内的第一个 vNN.NN)。
57
+ * 取不到返回 null(注入文本若不含标题即静默跳过,绝不猜)。
58
+ */
59
+ function manualVer(text: string): string | null {
60
+ const i = text.indexOf("自主工作手册");
61
+ if (i < 0) return null;
62
+ const m = text.slice(i, i + 200).match(/v(\d+\.\d+)/);
63
+ return m ? m[1] : null;
64
+ }
65
+
66
+ // ── pi-lens word index 补丁:两处替换(与 patches/pi-lens-wordindex-patch.js 同源)
67
+ const A1_FROM = " warmWordIndexes.set(key4, entry);\n }\n entry.leases++;";
68
+ const A1_MARK = "if (entry && !entry.index) {";
69
+ const A1_TO = " warmWordIndexes.set(key4, entry);\n }\n if (entry && !entry.index) {\n const late = deserializeWordIndex(loadProjectSnapshot(key4)?.wordIndex) ?? void 0;\n if (late?.forward) entry.index = late;\n }\n entry.leases++;";
70
+ const A2_FROM = "if (!snapshot.wordIndex && existing.wordIndex && existing.seq === snapshot.seq && (snapshot.incomplete || !existing.incomplete)) {";
71
+ const A2_MARK = "existing.wordIndex && (snapshot.incomplete";
72
+ const A2_TO = "if (!snapshot.wordIndex && existing.wordIndex && (snapshot.incomplete || !existing.incomplete)) {";
73
+
74
+
75
+ // ── pi-memory exit summary 空行规范化补丁(幂等;与 pi-memory/index.ts 内已打状态一致)
76
+ const ME_MARK = "normalizeExitSummaryMarkdown";
77
+ const ME_FROM_FN = "function formatExitSummaryEntry(";
78
+ const ME_FROM_RET = 'header, "", summary.trim()].join("\\n");';
79
+ const ME_TO_RET = 'header, "", normalizeExitSummaryMarkdown(summary.trim())].join("\\n");';
80
+ const ME_FN = ['/**', ' * 规范 exit summary 的块级空行(MD022 / MD032:标题 / 列表前后须空行);代码围栏内不动。', ' */', 'function normalizeExitSummaryMarkdown(text: string): string {', '\tconst lines = text.split(/\\r?\\n/);', '\tconst out: string[] = [];', '\tconst isFence = (l: string) => /^\\s*(\\x60{3,}|~{3,})/.test(l);', '\tconst isHeading = (l: string) => /^#{1,6}\\s/.test(l);', '\tconst isList = (l: string) => /^\\s*(?:[-*+]|\\d+\\.)\\s/.test(l);', '\tlet inFence = false;', '\tfor (const line of lines) {', '\t\tconst fenceLine = isFence(line);', '\t\tif (fenceLine) inFence = !inFence;', '\t\tconst prev = out.length ? out[out.length - 1] : "";', '\t\tif (!fenceLine && !inFence && prev !== "") {', '\t\t\tconst startsBlock = (isHeading(line) || isList(line)) && !(isList(line) && isList(prev));', '\t\t\tconst afterBlock = isHeading(prev) || (isList(prev) && !isList(line));', '\t\t\tif (startsBlock || afterBlock) out.push("");', '\t\t}', '\t\tout.push(line);', '\t}', '\treturn out.join("\\n");', '}'].join("\n");
81
+ const MEM_SECTION_MARK = 'sections["pi_memory"]';
82
+ const MEM_SECTION_ANCHOR = [
83
+ "\t\treturn {",
84
+ "\t\t\tsystemPrompt: event.systemPrompt + headerLines.join(\"\\n\"),",
85
+ "\t\t};",
86
+ ].join("\n");
87
+ const MEM_SECTION_BLOCK = [
88
+ "\t\t// R7:有 sections 的宿主优先写 section —— 返回 systemPrompt 是 force 覆盖,",
89
+ "\t\t// 会丢弃其后(builtin 组)goal / plan / security 的 section 写入",
90
+ "\t\t// (2026-10-17 实证:goal 的 Objective 与 Rules 从 system 消失,只剩 Round 消息)。",
91
+ "\t\tconst sections = (event as { systemPromptOptions?: { sections?: Record<string, string> } }).systemPromptOptions?.sections;",
92
+ "\t\tif (sections) {",
93
+ "\t\t\tsections[\"pi_memory\"] = headerLines.join(\"\\n\").replace(/^\\n+/, \"\");",
94
+ "\t\t\treturn;",
95
+ "\t\t}",
96
+ "\t\treturn {",
97
+ "\t\t\tsystemPrompt: event.systemPrompt + headerLines.join(\"\\n\"),",
98
+ "\t\t};",
99
+ ].join("\n");
100
+ const TACT = path.join(HOME, ".pi", "agent", "npm", "node_modules", "@khanhicetea", "pi-tactician", "src", "index.ts");
101
+ const TACT_MARK = 'sections["tactician"]';
102
+ const TACT_ANCHOR = [
103
+ "\t\tif (event.systemPrompt.includes(GUIDANCE_MARKER)) return;",
104
+ "\t\treturn { systemPrompt: `${event.systemPrompt}\\n\\n${TACTICIAN_GUIDANCE}` };",
105
+ ].join("\n");
106
+ const TACT_BLOCK = [
107
+ "\t\t// R7b:有 sections 的宿主写 section(不 force)——force 会让其后 builtin 组",
108
+ "\t\t// (goal / plan / security)的 section 写入被整组丢弃(2026-10-17 实证)。",
109
+ "\t\tconst sections = (event as { systemPromptOptions?: { sections?: Record<string, string> } }).systemPromptOptions?.sections;",
110
+ "\t\tif (sections) {",
111
+ "\t\t\tsections[\"tactician\"] = TACTICIAN_GUIDANCE;",
112
+ "\t\t\treturn;",
113
+ "\t\t}",
114
+ "\t\tif (event.systemPrompt.includes(GUIDANCE_MARKER)) return;",
115
+ "\t\treturn { systemPrompt: `${event.systemPrompt}\\n\\n${TACTICIAN_GUIDANCE}` };",
116
+ ].join("\n");
117
+
118
+ /** pi-memory 状态:done / none。 */
119
+ function piMemoryState(src: string): "done" | "none" {
120
+ return src.includes(ME_MARK) ? "done" : "none";
121
+ }
122
+
123
+ /** 打/补 pi-memory exit summary 规范化(幂等)。 */
124
+ function healPiMemory(): Result {
125
+ if (!existsSync(PI_MEMORY)) return { ok: false, detail: "pi-memory/index.ts 不存在(未安装?)" };
126
+ const src = safeRead(PI_MEMORY);
127
+ if (src === null) return { ok: false, detail: "读取失败" };
128
+ if (piMemoryState(src) === "done") return { ok: true, detail: "已是最新(无需动作)" };
129
+ if (!src.includes(ME_FROM_FN) || !src.includes(ME_FROM_RET)) return { ok: false, detail: "锚点未找到(版本变化?)—— 需人工确认" };
130
+ let next = src.replace(ME_FROM_RET, ME_TO_RET);
131
+ next = next.replace(ME_FROM_FN, ME_FN + "\n\n" + ME_FROM_FN);
132
+ if (!next.includes(ME_MARK) || next === src) return { ok: false, detail: "打补丁失败(结果校验不通过)" };
133
+ try {
134
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
135
+ const bak = `${PI_MEMORY}.bak-exitsummary-${stamp}`;
136
+ if (!existsSync(bak)) copyFileSync(PI_MEMORY, bak);
137
+ writeFileSync(PI_MEMORY, next, "utf8");
138
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
139
+ return { ok: true, detail: "已自动修补(exit summary 空行规范化)—— 本轮即生效" };
140
+ }
141
+ /** R7:memory 段改 section(防 force 吞掉其后 builtin 组的 section)。 */
142
+ function healMemorySection(): Result {
143
+ if (!existsSync(PI_MEMORY)) return { ok: false, detail: "pi-memory/index.ts 不存在(未安装?)" };
144
+ const src = safeRead(PI_MEMORY);
145
+ if (src === null) return { ok: false, detail: "读取失败" };
146
+ if (src.includes(MEM_SECTION_MARK)) return { ok: true, detail: "已是最新(无需动作)" };
147
+ if (!src.includes(MEM_SECTION_ANCHOR)) return { ok: false, detail: "锚点未找到(版本变化?)—— 需人工确认" };
148
+ const next = src.replace(MEM_SECTION_ANCHOR, MEM_SECTION_BLOCK);
149
+ if (!next.includes(MEM_SECTION_MARK) || next === src) return { ok: false, detail: "打补丁失败(结果校验不通过)" };
150
+ try {
151
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
152
+ const bak = `${PI_MEMORY}.bak-memsec-${stamp}`;
153
+ if (!existsSync(bak)) copyFileSync(PI_MEMORY, bak);
154
+ writeFileSync(PI_MEMORY, next, "utf8");
155
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
156
+ return { ok: true, detail: "已自动修补(memory 段改 section)—— 重启后生效" };
157
+ }
158
+ /** R7b:tactician 改 section(防 force 吞掉其后 builtin 组的 section)。 */
159
+ function healTactician(): Result {
160
+ if (!existsSync(TACT)) return { ok: false, detail: "pi-tactician/src/index.ts 不存在(未安装?)" };
161
+ const src = safeRead(TACT);
162
+ if (src === null) return { ok: false, detail: "读取失败" };
163
+ if (src.includes(TACT_MARK)) return { ok: true, detail: "已是最新(无需动作)" };
164
+ if (!src.includes(TACT_ANCHOR)) return { ok: false, detail: "锚点未找到(版本变化?)—— 需人工确认" };
165
+ const next = src.replace(TACT_ANCHOR, TACT_BLOCK);
166
+ if (!next.includes(TACT_MARK) || next === src) return { ok: false, detail: "打补丁失败(结果校验不通过)" };
167
+ try {
168
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
169
+ const bak = `${TACT}.bak-tactician-${stamp}`;
170
+ if (!existsSync(bak)) copyFileSync(TACT, bak);
171
+ writeFileSync(TACT, next, "utf8");
172
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
173
+ return { ok: true, detail: "已自动修补(tactician 改 section)—— 重启后生效" };
174
+ }
175
+ // ── PiDeck asar 补丁:只读检测(needle 出现次数)
176
+ const ASAR_CHECKS: Array<{ name: string; needle: string; expected: number }> = [
177
+ { name: "history-race", needle: "runtime.tab.runtimeGeneration !== runtimeGeneration", expected: 8 },
178
+ { name: "katex", needle: "singleDollarTextMath: !0", expected: 0 },
179
+ { name: "noise", needle: "appLogger.warn(\"app\", \"Main window renderer console error\"", expected: 0 },
180
+ ];
181
+
182
+ type Result = { ok: boolean; detail: string };
22
183
 
184
+ /** 读文件;失败返回 null(永不抛)。 */
23
185
  function safeRead(p: string): string | null {
24
- try { return readFileSync(p, "utf8"); } catch { return null; }
186
+ try { return readFileSync(p, "utf8"); } catch { return null; }
25
187
  }
26
188
 
27
- function readJson(p: string): Record<string, unknown> | null {
28
- const t = safeRead(p);
29
- if (t === null) return null;
30
- try { return JSON.parse(t) as Record<string, unknown>; } catch { return null; }
189
+ /** 统计 needle 在原串里的出现次数。 */
190
+ function count(hay: string, needle: string): number {
191
+ let n = 0, i = 0;
192
+ while ((i = hay.indexOf(needle, i)) >= 0) { n += 1; i += needle.length; }
193
+ return n;
31
194
  }
32
195
 
33
- function forceTail(): string[] {
34
- const c = readJson(CONFIG);
35
- const t = c?.forceTail;
36
- const list = Array.isArray(t) ? t.filter((x): x is string => typeof x === "string") : DEFAULT_TAIL;
37
- return list.length ? list : DEFAULT_TAIL;
196
+ /** pi-lens 状态:both / partial / none / missing。 */
197
+ function piLensState(src: string): { state: "both" | "partial" | "none"; a1: boolean; a2: boolean } {
198
+ const a1 = src.includes(A1_MARK);
199
+ const a2 = !src.includes(A2_FROM) && src.includes(A2_MARK);
200
+ let state: "both" | "partial" | "none" = "none";
201
+ if (a1 && a2) state = "both";
202
+ else if (a1 || a2) state = "partial";
203
+ return { state, a1, a2 };
38
204
  }
39
205
 
40
- function packagesOf(): string[] | null {
41
- const s = readJson(SETTINGS);
42
- const p = s?.packages;
43
- return Array.isArray(p) ? p.filter((x): x is string => typeof x === "string") : null;
206
+ /** 只在未打或半打时修补 pi-lens(幂等)。 */
207
+ function healPiLens(): Result {
208
+ if (!existsSync(PI_LENS)) return { ok: false, detail: "pi-lens dist 不存在(未安装?)" };
209
+ const src = safeRead(PI_LENS);
210
+ if (src === null) return { ok: false, detail: "读取失败" };
211
+ const { state, a1, a2 } = piLensState(src);
212
+ if (state === "both") return { ok: true, detail: "已是最新(无需动作)" };
213
+ let next = src;
214
+ // 半打状态先还原,再整体重打(避免只打一半造成新的不一致)
215
+ if (a2 && !a1) next = next.replace(A2_TO, A2_FROM); // 半打:先把 B 还原,再由下面两步整体重打
216
+ if (!next.includes(A1_MARK)) next = next.replace(A1_FROM, A1_TO);
217
+ if (next.includes(A2_FROM)) next = next.replace(A2_FROM, A2_TO);
218
+ const after = piLensState(next);
219
+ if (after.state !== "both") return { ok: false, detail: `打补丁失败(结果 ${after.state},锚点可能已随版本变化)` };
220
+ try {
221
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
222
+ const bak = `${PI_LENS}.bak-wordindex-${stamp}`;
223
+ if (!existsSync(bak)) copyFileSync(PI_LENS, bak);
224
+ writeFileSync(PI_LENS, next, "utf8");
225
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
226
+ return { ok: true, detail: `已自动修补(原状态 ${state})—— 本轮即生效` };
227
+ }
228
+
229
+
230
+ /** 记忆文件格式规范化(压连续空行 + 单尾换行;围栏内不动)。 */
231
+ function normMd(txt: string): string {
232
+ const lines = txt.split(/\r?\n/);
233
+ const out: string[] = [];
234
+ let inFence = false;
235
+ for (const line of lines) {
236
+ const isF = /^\s*(?:`{3,}|~{3,})/.test(line);
237
+ if (isF) inFence = !inFence;
238
+ if (!inFence && line.trim() === "" && out.length > 0 && out[out.length - 1].trim() === "") continue;
239
+ out.push(line);
240
+ }
241
+ while (out.length > 0 && out[out.length - 1].trim() === "") out.pop();
242
+ return out.join("\n") + "\n";
44
243
  }
45
244
 
46
- /** Problems in the current load order (empty = OK). */
245
+ /** 第 3 处自愈:memory_write 每次写入都会引入 MD012/MD047(同日复发 3 次后机制化)——启动即规范。 */
246
+ function healMemoryFormat(): Result {
247
+ try {
248
+ const dir = path.join(HOME, ".pi", "agent", "memory");
249
+ if (!existsSync(dir)) return { ok: true, detail: "memory 目录不存在(跳过)" };
250
+ let fixed = 0;
251
+ const walk = (d: string): void => {
252
+ for (const e of readdirSync(d, { withFileTypes: true })) {
253
+ const p = path.join(d, e.name);
254
+ if (e.isDirectory()) { if (e.name !== ".git") walk(p); continue; }
255
+ if (!e.name.endsWith(".md")) continue;
256
+ const txt = safeRead(p);
257
+ if (txt === null) continue;
258
+ const norm = normMd(txt);
259
+ if (norm !== txt) { try { writeFileSync(p, norm, "utf8"); fixed += 1; } catch { /* 静默 */ } }
260
+ }
261
+ };
262
+ walk(dir);
263
+ return { ok: true, detail: fixed > 0 ? `已规范化 ${fixed} 个记忆文件(空行 / 尾换行)` : "记忆格式无需动作" };
264
+ } catch (e) { return { ok: false, detail: (e as Error).message }; }
265
+ }
266
+ /** PiDeck asar:只读检测,返回未打补丁的项名。 */
267
+ let asarOk = false;
268
+ /** 未打补丁时的处置提示(纯函数,便于单测)。 */
269
+ function patchTip(lines: string[]): string {
270
+ if (!lines.some((l) => l.includes("未打") || l.includes("半打"))) return "";
271
+ const dir = existsSync(SNAPSHOT_PATCH_DIR) ? SNAPSHOT_PATCH_DIR : "pi-env-snapshot/05-脚本补丁/(也未找到)";
272
+ return ` → PiDeck 补丁需退出 PiDeck 后重跑补丁脚本(快照副本:${dir};或用其中的 launch-pideck.cmd 启动 PiDeck 时自动重打)`;
273
+ }
274
+
275
+
276
+ function checkAsar(): { ran: boolean; missing: string[]; detail: string } {
277
+ if (asarOk) return { ran: true, missing: [], detail: "三个补丁都在" };
278
+ if (!existsSync(ASAR)) return { ran: false, missing: [], detail: "app.asar 不存在" };
279
+ let buf: Buffer;
280
+ try { buf = readFileSync(ASAR); } catch (e) { return { ran: false, missing: [], detail: `读取失败:${(e as NodeJS.ErrnoException).code ?? (e as Error).message}` }; }
281
+ const txt = buf.toString("utf8");
282
+ const missing: string[] = [];
283
+ for (const c of ASAR_CHECKS) {
284
+ const n = count(txt, c.needle);
285
+ if (n !== c.expected) missing.push(`${c.name}(=${n}, 期望 ${c.expected})`);
286
+ }
287
+ if (!missing.length) asarOk = true; // 只在通过时缓存:缺失时每次都实测,便于打完补丁后立刻复检
288
+ return { ran: true, missing, detail: missing.length ? `未打补丁:${missing.join(" ")}` : "三个补丁都在" };
289
+ }
290
+
291
+ /** 汇总报告(给命令与启动提示共用)。 */
292
+ // ── 环境指纹:settings 关键字段漂移 → 提示「手册 / 验证结论可能过期」
293
+ function fingerprint(): Record<string, string[]> | null {
294
+ const txt = safeRead(SETTINGS);
295
+ if (txt === null) return null;
296
+ try {
297
+ const s = JSON.parse(txt) as Record<string, unknown>;
298
+ return {
299
+ packages: (s.packages as string[]) ?? [],
300
+ defaultTools: (s.defaultTools as string[]) ?? [],
301
+ enabledModels: (s.enabledModels as string[]) ?? [],
302
+ extensions: (s.extensions as string[]) ?? [],
303
+ codemode: [(s.codemode as { mode?: string })?.mode ?? "?"],
304
+ };
305
+ } catch { return null; }
306
+ }
307
+ /** 与上次指纹对比;变化摘要数组(无变化为空)。对比后写回新指纹。 */
308
+ function fingerprintDrift(): string[] {
309
+ const cur = fingerprint();
310
+ if (cur === null) return [];
311
+ let prev: Record<string, string[]> | null = null;
312
+ const prevRaw = safeRead(FINGERPRINT);
313
+ if (prevRaw) { try { prev = JSON.parse(prevRaw) as Record<string, string[]>; } catch { prev = null; } }
314
+ try { writeFileSync(FINGERPRINT, JSON.stringify(cur, null, 1), "utf8"); } catch { /* 静默 */ }
315
+ if (prev === null) return [];
316
+ const out: string[] = [];
317
+ for (const k of ["packages", "defaultTools", "enabledModels", "extensions", "codemode"] as const) {
318
+ const a = prev[k] ?? [];
319
+ const b = cur[k];
320
+ const added = b.filter((x) => !a.includes(x)).length;
321
+ const removed = a.filter((x) => !b.includes(x)).length;
322
+ if (added || removed) out.push(`${k} ${a.length}→${b.length}${added ? ` +${added}` : ""}${removed ? ` -${removed}` : ""}`);
323
+ }
324
+ return out;
325
+ }
326
+
327
+ /** codemode 单点一致性:禁 builtin:codemode ⟺ packages 含 pi-codemode-guard(启动检查 / /patch-keeper 共用)。 */
328
+ export function consistencyCheck(exts: string[], pkgs: string[]): string[] {
329
+ const disabled = (exts ?? []).includes("-builtin:codemode");
330
+ const guard = (pkgs ?? []).includes("npm:pi-codemode-guard");
331
+ if (disabled && !guard) return ["codemode 单点断裂:已禁 builtin:codemode 但 packages 无 pi-codemode-guard —— codemode 工具将不可用"];
332
+ if (!disabled && guard) return ["codemode 单点异常:pi-codemode-guard 在但未禁 builtin:codemode —— 双实现风险"];
333
+ return [];
334
+ }
335
+
336
+
337
+ function restoreBuiltinPatches(): string | null {
338
+ const out: string[] = [];
339
+ for (const bp of BUILTIN_PATCHES) {
340
+ for (const target of [bp.install, bp.file]) {
341
+ if (!existsSync(target)) continue; // 未装 PiDeck / 路径不同:跳过,不算缺失
342
+ const cur = safeRead(target);
343
+ if (cur !== null && cur.includes(bp.needle)) continue;
344
+ const snap = path.join(SNAPSHOT_BUILTIN, path.basename(target));
345
+ if (!existsSync(snap)) { out.push(`${bp.name}: 缺补丁且快照无副本`); continue; }
346
+ try {
347
+ if (cur !== null) copyFileSync(target, `${target}.bak-restore-${Date.now()}`);
348
+ copyFileSync(snap, target);
349
+ out.push(`${bp.name}(${target === bp.install ? "安装目录" : "用户层"}): 已从快照恢复`);
350
+ } catch (e) { out.push(`${bp.name}: 恢复失败(${(e as Error).message})`); }
351
+ }
352
+ }
353
+ return out.length ? out.join(";") : null;
354
+ }
355
+
356
+ /** 手册内容漂移:版本号未变但正文变了(只比版本号会漏)。 */
357
+ function manualDrift(): string | null {
358
+ const disk = safeRead(MANUAL);
359
+ if (disk === null) return null;
360
+ const ver = manualVer(disk) ?? "";
361
+ const sig = createHash("sha256").update(disk).digest("hex").slice(0, 12);
362
+ let prev: { ver?: string; sig?: string } | null = null;
363
+ const raw = safeRead(MANUAL_STATE);
364
+ if (raw) { try { prev = JSON.parse(raw); } catch { prev = null; } }
365
+ try { writeFileSync(MANUAL_STATE, JSON.stringify({ ver, sig })); } catch { /* ignore */ }
366
+ if (prev && prev.ver === ver && prev.sig !== sig) return `手册内容已变但版本号未升(${ver})—— bump-manual 或撤销未登记改动`;
367
+ return null;
368
+ }
369
+ // 已知盲区:caveman-think-zh 是 user 扩展(不在 packages 数组),它在检测到原版英文段时
370
+ // 也会 force;FORCE_TAIL 覆盖不到,触发时本扩展看不到。
371
+ /** force/条件 force 型必须排在 packages 末尾(其后 section 写入会被静默丢弃)。触发概率升序:rtk → cache-optimizer。 */
372
+ const FORCE_TAIL = ["npm:pi-rtk-optimizer", "npm:pi-cache-optimizer"];
47
373
  export function forceOrderIssues(packages: string[]): string[] {
48
- const out: string[] = [];
49
- const tail = forceTail();
50
- const present = tail.filter((n) => packages.includes(n));
51
- if (!present.length) return out;
52
- const minForce = Math.min(...present.map((n) => packages.indexOf(n)));
53
- const later = packages.slice(minForce + 1).filter((n) => !tail.includes(n));
54
- if (later.length) out.push(
55
- "force-type package is followed by " + later.length + " package(s) (" + later.slice(0, 2).join(" / ") +
56
- ") — their sections are dropped; move " + tail.join(" / ") + " to the end");
57
- if (tail.every((n) => packages.includes(n)) && packages.indexOf(tail[0]) > packages.indexOf(tail[1]))
58
- out.push("force order should be " + tail.join(" -> ") + " (the most likely trigger goes last)");
59
- return out;
60
- }
61
-
62
- /** Reordered packages, or null when already correct. */
374
+ const out: string[] = [];
375
+ const idx = (n: string) => packages.indexOf(n);
376
+ const present = FORCE_TAIL.filter((n) => idx(n) >= 0);
377
+ if (!present.length) return out;
378
+ const minForce = Math.min(...present.map(idx));
379
+ const later = packages.slice(minForce + 1).filter((n) => !FORCE_TAIL.includes(n));
380
+ if (later.length) out.push(`force 型之后仍有 ${later.length} 个包(${later.slice(0, 2).join(" / ")})—— 它们的 section 写入会被丢弃;把 ${FORCE_TAIL.join(" / ")} 移到末尾`);
381
+ if (idx(FORCE_TAIL[0]) >= 0 && idx(FORCE_TAIL[1]) >= 0 && idx(FORCE_TAIL[0]) > idx(FORCE_TAIL[1])) out.push("force 顺序应为 rtk → cache-optimizer(最可能触发者最后)");
382
+ return out;
383
+ }
384
+ /** 把 FORCE_TAIL 成员移到末尾(其余相对顺序不变);已正确时返回 null。 */
63
385
  export function normalizeForceOrder(packages: string[]): string[] | null {
64
- const tail = forceTail();
65
- const present = tail.filter((n) => packages.includes(n));
66
- if (!present.length) return null;
67
- const next = [...packages.filter((n) => !tail.includes(n)), ...present];
68
- return next.join("\n") === packages.join("\n") ? null : next;
386
+ const present = FORCE_TAIL.filter((n) => packages.includes(n));
387
+ if (!present.length) return null;
388
+ const rest = packages.filter((n) => !FORCE_TAIL.includes(n));
389
+ const next = [...rest, ...present];
390
+ return next.join("\n") === packages.join("\n") ? null : next;
69
391
  }
70
392
 
71
- /** Repair settings.json order; backs up first. Returns a message or null. */
393
+ /** 自动修复 settings.json 的 force 顺序;无变化返回 null。先备份再写。 */
72
394
  function fixForceOrder(): string | null {
73
- const s = readJson(SETTINGS);
74
- if (!s) return null;
75
- const packages = Array.isArray(s.packages) ? (s.packages as string[]) : [];
76
- const next = normalizeForceOrder(packages);
77
- if (!next) return null;
78
- try {
79
- copyFileSync(SETTINGS, SETTINGS + ".bak-force-order-" + Date.now());
80
- s.packages = next;
81
- writeFileSync(SETTINGS, JSON.stringify(s, null, 2), "utf8");
82
- } catch (e) { return "force order repair failed: " + (e as Error).message; }
83
- return "force order repaired: " + forceTail().filter((n) => next.includes(n)).join(" / ") + " moved to the end";
395
+ const txt = safeRead(SETTINGS);
396
+ if (txt === null) return null;
397
+ let s: Record<string, unknown>;
398
+ try { s = JSON.parse(txt) as Record<string, unknown>; } catch { return "force 顺序自动修复失败:settings.json 解析失败"; }
399
+ const packages = (s.packages as string[] | undefined) ?? [];
400
+ const next = normalizeForceOrder(packages);
401
+ if (!next) return null;
402
+ try {
403
+ copyFileSync(SETTINGS, `${SETTINGS}.bak-force-order-${Date.now()}`);
404
+ s.packages = next;
405
+ writeFileSync(SETTINGS, JSON.stringify(s, null, 2), "utf8");
406
+ } catch (e) { return `force 顺序自动修复失败:${(e as Error).message}`; }
407
+ return `force 顺序已自动修复:${FORCE_TAIL.filter((n) => next.includes(n)).join(" / ")} 移到 packages 末尾`;
84
408
  }
85
-
409
+ /** 静态扫描:packages 中疑似 force 型扩展(入口源码含 return { systemPrompt } / forceSystemPrompt)。 */
86
410
  const FORCE_RE = /return\s*\{\s*systemPrompt|forceSystemPrompt/;
87
411
  const SECTION_RE = /sections\s*(\[|\.)/;
88
412
 
89
- /** Classify static force candidates: sections-first means a legacy-host fallback. */
90
- function classify(packages: string[]): { force: string[]; fallback: string[] } {
91
- const force: string[] = [];
92
- const fallback: string[] = [];
93
- const tail = forceTail();
94
- for (const name of packages) {
95
- if (!name.startsWith("npm:") || tail.includes(name)) continue;
96
- const dir = path.join(NPM_DIR, name.slice(4));
97
- if (!existsSync(dir)) continue;
98
- let entries: string[] = [];
99
- const pj = readJson(path.join(dir, "package.json")) as { pi?: { extensions?: unknown } } | null;
100
- const ex = pj?.pi?.extensions;
101
- entries = Array.isArray(ex) ? ex.filter((x): x is string => typeof x === "string") : [];
102
- for (const rel of entries.slice(0, 3)) {
103
- const src = safeRead(path.join(dir, rel));
104
- if (src === null) continue;
105
- const i = src.indexOf("before_agent_start");
106
- if (i < 0) continue;
107
- const body = src.slice(i, i + 4000);
108
- const fi = body.search(FORCE_RE);
109
- if (fi < 0) continue;
110
- const si = body.search(SECTION_RE);
111
- if (si >= 0 && si < fi) fallback.push(name); else force.push(name);
112
- break;
113
- }
114
- }
115
- return { force, fallback };
413
+ /** 分类:先写 section、只有旧宿主才 force 的算兼容兜底,不算疑似无条件 force。 */
414
+ function classifyPackages(packages: string[]): { force: string[]; fallback: string[] } {
415
+ const force: string[] = [];
416
+ const fallback: string[] = [];
417
+ for (const name of packages) {
418
+ if (!name.startsWith("npm:") || FORCE_TAIL.includes(name)) continue;
419
+ const dir = path.join(HOME, ".pi", "agent", "npm", "node_modules", name.slice(4));
420
+ if (!existsSync(dir)) continue;
421
+ let entries: string[] = [];
422
+ try {
423
+ const pj = JSON.parse(safeRead(path.join(dir, "package.json")) ?? "{}") as { pi?: { extensions?: unknown } };
424
+ const ex = pj.pi?.extensions;
425
+ entries = Array.isArray(ex) ? ex.filter((x): x is string => typeof x === "string") : [];
426
+ } catch { continue; }
427
+ for (const rel of entries.slice(0, 3)) {
428
+ const src = safeRead(path.join(dir, rel));
429
+ if (src === null) continue;
430
+ const i = src.indexOf("before_agent_start");
431
+ if (i < 0) continue;
432
+ const body = src.slice(i, i + 4000);
433
+ const fi = body.search(FORCE_RE);
434
+ if (fi < 0) continue;
435
+ const si = body.search(SECTION_RE);
436
+ if (si >= 0 && si < fi) fallback.push(name); else force.push(name);
437
+ break;
438
+ }
439
+ }
440
+ return { force, fallback };
441
+ }
442
+
443
+ /** 疑似无条件 force(会静默吞掉其后 section)。 */
444
+ export function scanForcePackages(packages: string[]): string[] {
445
+ return classifyPackages(packages).force;
446
+ }
447
+
448
+ /** 兼容兜底(section 优先,旧宿主才 force)。 */
449
+ export function scanForceFallbacks(packages: string[]): string[] {
450
+ return classifyPackages(packages).fallback;
116
451
  }
117
452
 
118
453
  function report(): string[] {
119
- const lines: string[] = [];
120
- const pk = packagesOf();
121
- if (!pk) { lines.push("settings: cannot read " + SETTINGS); return lines; }
122
- const issues = forceOrderIssues(pk);
123
- lines.push("force order: " + (issues.length ? issues[0] : "OK"));
124
- const tail = forceTail();
125
- lines.push("force packages: " + tail.filter((n) => pk.includes(n)).join(" / ") + (tail.some((n) => !pk.includes(n)) ? " (partial)" : ""));
126
- const { force, fallback } = classify(pk);
127
- lines.push("static scan: " + (force.length ? "force-like " + force.join(" / ") : "none"));
128
- lines.push("fallbacks: " + (fallback.length ? fallback.join(" / ") : "none"));
129
- return lines;
454
+ const lines: string[] = [];
455
+ const lensSrc = safeRead(PI_LENS);
456
+ if (lensSrc === null) lines.push("pi-lens : 读不到 dist/index.js");
457
+ else {
458
+ const st = piLensState(lensSrc);
459
+ let label = `半打(A=${st.a1} B=${st.a2})`;
460
+ if (st.state === "both") label = "已打(A+B)";
461
+ else if (st.state === "none") label = "未打";
462
+ lines.push(`pi-lens : ${label}`);
463
+ }
464
+ const memSrc = safeRead(PI_MEMORY);
465
+ if (memSrc === null) lines.push("pi-memory: 读不到 index.ts");
466
+ else lines.push(`pi-memory: ${memSrc.includes(ME_MARK) ? "已打(exit summary 空行规范化)" : "未打"} · ${memSrc.includes(MEM_SECTION_MARK) ? "已打(section 优先)" : "未打(section 优先)"}`);
467
+ const tactSrc = safeRead(TACT);
468
+ lines.push(`tactician: ${tactSrc === null ? "读不到" : tactSrc.includes(TACT_MARK) ? "已打(section 优先)" : "未打(section 优先)"}`);
469
+ const asar = checkAsar();
470
+ lines.push(`PiDeck : ${asar.detail}`);
471
+ for (const bp of BUILTIN_PATCHES) {
472
+ const st = (p: string): string => { const src = safeRead(p); return src === null ? "无" : src.includes(bp.needle) ? "已打" : "未打"; };
473
+ lines.push(`builtin : ${bp.name} 生效版=${st(bp.install)} 用户层=${st(bp.file)}`);
474
+ }
475
+ const fp = fingerprint();
476
+ const cm = fp ? consistencyCheck(fp.extensions, fp.packages) : [];
477
+ let cmLabel = "读不到 settings";
478
+ if (fp) cmLabel = cm.length ? cm[0] : "单点一致";
479
+ lines.push(`codemode : ${cmLabel}`);
480
+ const fo = fp ? forceOrderIssues(fp.packages) : [];
481
+ lines.push(`force序 : ${fp ? (fo.length ? fo[0] : "OK") : "读不到 settings"}`);
482
+ const fe = fp ? scanForcePackages(fp.packages) : [];
483
+ lines.push(`forceExt: ${fp ? (fe.length ? "疑似 " + fe.join(" / ") : "无(静态扫描)") : "读不到 settings"}`);
484
+ const fb = fp ? scanForceFallbacks(fp.packages) : [];
485
+ lines.push(`force兜底: ${fp ? (fb.length ? fb.join(" / ") : "无") : "读不到 settings"}`);
486
+ return lines;
130
487
  }
131
488
 
132
489
  export default function (pi: ExtensionAPI) {
133
- pi.registerCommand("patch-keeper", {
134
- description: "Show / repair extension load order (force-type packages must load last)",
135
- handler: async (args: string, ctx: ExtensionContext) => {
136
- const arg = (args || "").trim().toLowerCase();
137
- if (arg === "fix") {
138
- const r = fixForceOrder();
139
- ctx.ui.notify(r ?? "patch-keeper: load order already correct", "info");
140
- return;
141
- }
142
- ctx.ui.notify("patch-keeper\n" + report().join("\n"), "info");
143
- },
144
- });
145
-
146
- pi.on("session_start", async (_event, ctx: ExtensionContext) => {
147
- try {
148
- const pk = packagesOf();
149
- if (!pk) return;
150
- const msgs: string[] = [];
151
- for (const x of forceOrderIssues(pk)) msgs.push("patch-keeper: " + x);
152
- const fixed = fixForceOrder();
153
- if (fixed) msgs.push("patch-keeper: " + fixed);
154
- const { force } = classify(pk);
155
- const tail = forceTail();
156
- const mid = force.filter((n) => pk.indexOf(n) < pk.length - 1 && !tail.includes(n));
157
- if (mid.length) msgs.push("patch-keeper: force-like package not last: " + mid.join(" / ") + " — move it to the end of packages");
158
- for (const m of msgs) ctx.ui.notify(m, "warning");
159
- } catch { /* detection must never break the session */ }
160
- });
161
- }
490
+ // 启动自愈:factory 是同步上下文,此时 pi-lens(rank 4)尚未加载。
491
+ let healNote: string | null = null;
492
+ try {
493
+ const r = healPiLens();
494
+ if (!r.ok) healNote = `patch-keeper: pi-lens 自愈失败 —— ${r.detail}`;
495
+ } catch (e) { healNote = `patch-keeper: pi-lens 自愈异常 —— ${(e as Error).message}`; }
496
+ try {
497
+ const r = healPiMemory();
498
+ if (!r.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory 自愈失败 —— ${r.detail}`;
499
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory 自愈异常 —— ${(e as Error).message}`; }
500
+ try {
501
+ const r = healMemorySection();
502
+ if (!r.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory section 自愈失败 —— ${r.detail}`;
503
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory section 自愈异常 —— ${(e as Error).message}`; }
504
+ try {
505
+ const rt = healTactician();
506
+ if (!rt.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: tactician section 自愈失败 —— ${rt.detail}`;
507
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: tactician section 自愈异常 —— ${(e as Error).message}`; }
508
+ try {
509
+ const r = healMemoryFormat();
510
+ if (!r.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: 记忆格式自愈失败 —— ${r.detail}`;
511
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: 记忆格式自愈异常 —— ${(e as Error).message}`; }
512
+
513
+ pi.registerCommand("patch-keeper", {
514
+ description: "查看 / 自愈本机源码补丁状态(PiDeck asar ×3、pi-lens ×1、pi-memory ×1)",
515
+ handler: async (args: string, ctx: ExtensionContext) => {
516
+ const arg = (args || "").trim().toLowerCase();
517
+ if (arg === "fix") {
518
+ const r = healPiLens();
519
+ ctx.ui.notify(`pi-lens: ${r.detail}`, r.ok ? "info" : "error");
520
+
521
+ const r2 = healPiMemory();
522
+ ctx.ui.notify(`pi-memory: ${r2.detail}`, r2.ok ? "info" : "error");
523
+ const r3 = healMemorySection();
524
+ ctx.ui.notify(`pi-memory section: ${r3.detail}`, r3.ok ? "info" : "error");
525
+ const r4 = healTactician();
526
+ ctx.ui.notify(`tactician section: ${r4.detail}`, r4.ok ? "info" : "error");
527
+ const rForce = fixForceOrder();
528
+ if (rForce) ctx.ui.notify(`patch-keeper: ${rForce}`, "info");
529
+ const rb = restoreBuiltinPatches();
530
+ if (rb) ctx.ui.notify(`patch-keeper: ${rb}`, "warning");
531
+ return;
532
+ }
533
+ const lines = report();
534
+ const tip = patchTip(lines);
535
+ ctx.ui.notify(`补丁状态\n${lines.join("\n")}${tip}`, "info");
536
+ },
537
+ });
538
+
539
+ // 启动提示:只在「PiDeck 补丁缺失」时出声(pi-lens 已自动修好,不打扰)
540
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
541
+ try {
542
+ const asar = checkAsar();
543
+ const msgs: string[] = [];
544
+ const drift = fingerprintDrift();
545
+ const forceFix = fixForceOrder();
546
+ const fp = fingerprint();
547
+ const cm = fp ? consistencyCheck(fp.extensions, fp.packages) : [];
548
+ for (const x of cm) msgs.push("patch-keeper: " + x);
549
+ if (forceFix) msgs.push("patch-keeper: " + forceFix);
550
+ else if (fp) for (const x of forceOrderIssues(fp.packages)) msgs.push("patch-keeper: " + x);
551
+ if (fp) {
552
+ const fe = scanForcePackages(fp.packages);
553
+ const mid = fe.filter((n) => fp.packages.indexOf(n) < fp.packages.length - 1);
554
+ if (mid.length) msgs.push("patch-keeper: 疑似 force 型扩展不在末尾(其后的 section 可能被静默丢弃):" + mid.join(" / ") + " —— 核源码后移到 packages 末尾");
555
+ }
556
+ if (drift.length) msgs.push(`patch-keeper: 环境指纹已变(${drift.join(";")})—— 手册 / 上轮验证结论可能过期,按 08-台账核对纪律逐项重验`);
557
+ if (asar.ran && asar.missing.length) {
558
+ msgs.push(`patch-keeper: PiDeck 补丁缺失 —— ${asar.detail}`);
559
+ msgs.push(`关闭 PiDeck 后重跑补丁脚本(快照 ${SNAPSHOT_PATCH_DIR};或用其中的 launch-pideck.cmd 启动 PiDeck 时自动重打)`);
560
+ }
561
+ for (const bp of BUILTIN_PATCHES) {
562
+ const missing = [bp.install, bp.file].filter((p: string) => { const src = safeRead(p); return src !== null && !src.includes(bp.needle); });
563
+ if (missing.length) {
564
+ const where = missing.length === 2 ? "两处" : missing[0] === bp.install ? "安装目录(生效版)" : "用户层";
565
+ msgs.push(`patch-keeper: PiDeck 内置扩展补丁缺失(${bp.name},${where})—— 升级覆盖?从快照 03-PiDeck/builtin-extensions 恢复`);
566
+ }
567
+ }
568
+ {
569
+ const memSrc2 = safeRead(PI_MEMORY);
570
+ if (memSrc2 !== null && !memSrc2.includes(MEM_SECTION_MARK)) msgs.push("patch-keeper: pi-memory 未打 section 优先补丁 —— goal / plan / security 的 section 会被 force 吞掉,建议 /patch-keeper fix");
571
+ }
572
+ {
573
+ const tactSrc2 = safeRead(TACT);
574
+ if (tactSrc2 !== null && !tactSrc2.includes(TACT_MARK)) msgs.push("patch-keeper: tactician 未打 section 优先补丁 —— 会 force 吞掉其后的 section(goal / plan / security),建议 /patch-keeper fix");
575
+ }
576
+ const md = manualDrift();
577
+ if (md) msgs.push(`patch-keeper: ${md}`);
578
+ if (healNote) msgs.push(healNote);
579
+ for (const m of msgs) ctx.ui.notify(m, "warning");
580
+ } catch { /* 静默:检测不该影响会话 */ }
581
+ });
582
+
583
+ // 注入对齐(手册 §2 纪律区):注入的是宿主上次读取的文本,可能与磁盘版不同步。每轮比对一次,不一致时提示一次。
584
+ // 纪律:**绝不返回 systemPrompt** —— 返回即 forceSystemPrompt 覆盖式替换,会静默丢弃其后所有 section 的修改。
585
+ let lastPair = "";
586
+ pi.on("before_agent_start", async (event, ctx: ExtensionContext) => {
587
+ try {
588
+ const injected = String((event as { systemPrompt?: string } | undefined)?.systemPrompt ?? "");
589
+ const vi = manualVer(injected);
590
+ const disk = safeRead(MANUAL);
591
+ const vd = disk === null ? null : manualVer(disk);
592
+ if (!vi || !vd) return undefined;
593
+ const pair = vi + "|" + vd;
594
+ if (vi === vd || pair === lastPair) return undefined;
595
+ lastPair = pair;
596
+ ctx.ui.notify(`注入对齐:注入 v${vi} ≠ 磁盘 v${vd}(观察者 = 磁盘版)→ 判据:注入版不可作判断依据;动作:读回全文执行,重启后自愈`, "warning");
597
+ // 回灌四律②:用户已收到通知;模型也需要知道,否则「以磁盘版执行」停在用户侧。
598
+ try {
599
+ (pi as unknown as { sendMessage?: (m: unknown, o?: unknown) => void }).sendMessage?.(
600
+ {
601
+ customType: "patch-keeper",
602
+ content: `注入对齐:注入 v${vi} ≠ 磁盘 v${vd}(观察者 = 磁盘版)→ 注入版不可作判断依据;动作:读回 APPEND_SYSTEM.md 全文后执行,重启后自愈。`,
603
+ display: false,
604
+ },
605
+ { deliverAs: "nextTurn" },
606
+ );
607
+ } catch { /* 静默:回灌失败不影响会话 */ }
608
+ } catch { /* 静默:检测不该影响会话 */ }
609
+ return undefined;
610
+ });
611
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-patch-keeper",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "Guards extension load order so later sections are not silently dropped.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -22,5 +22,6 @@
22
22
  ],
23
23
  "peerDependencies": {
24
24
  "@earendil-works/pi-coding-agent": "*"
25
- }
25
+ },
26
+ "author": "15066212pp"
26
27
  }