pi-patch-keeper 1.0.12 → 1.1.1

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 (4) hide show
  1. package/README.en.md +24 -38
  2. package/README.md +46 -40
  3. package/index.ts +568 -168
  4. package/package.json +5 -4
package/README.en.md CHANGED
@@ -1,57 +1,43 @@
1
- # pi-patch-keeper — extension load-order guard (pi extension)
1
+ # pi-patch-keeper — patch self-healing and status checks (pi extension)
2
2
 
3
- Prevents "force-typed" extensions from silently swallowing every section written after them.
3
+ Turns "patches to other people's packages must be re-applied after every upgrade" into startup self-healing with an explicit report.
4
4
 
5
- ## Why it exists
5
+ ## What it heals
6
6
 
7
- `before_agent_start` runs extensions in order. An extension that returns `{ systemPrompt }` (or sets `forceSystemPrompt`) performs a **full replacement**, so every later extension's `sections` write is discarded — with no error. The symptom looks like "this extension is installed but has no effect".
8
-
9
- ## What it does
10
-
11
- - On startup, checks the order of `packages` in `~/.pi/agent/settings.json`: known force-typed extensions must sit at the end.
12
- - Statically scans installed npm extension entry files and separates:
13
- - **unconditional force** (`return { systemPrompt }` / `forceSystemPrompt`) → must be last;
14
- - **sections-first with legacy fallback** → report only, no move suggested.
15
- - Records a fingerprint of key settings fields and warns when it changes (earlier conclusions may be stale).
16
- - `codemode` single-point check: disabling `builtin:codemode` requires a replacement, and vice versa.
17
- - Silent when everything is fine.
18
-
19
- ## Commands
20
-
21
- | Command | Effect |
7
+ | Target | Action |
22
8
  | --- | --- |
23
- | `/patch-keeper` | Show order, suspected force packages, fallback packages, codemode status |
24
- | `/patch-keeper fix` | Move known force-typed packages to the end (backup written first) |
9
+ | pi-lens wordindex patch (symbol_search stuck on "building") | fixes in place at startup; stops when upstream ships the fix (warm_cache_adopted) |
10
+ | pi-memory exit summary / section precedence | fixes in place, backup first |
11
+ | pi-tactician section precedence | fixes in place, backup first |
12
+ | PiDeck builtin extensions (5, dual copies) | restores from the snapshot copy when a release overwrites them |
13
+ | PiDeck app.asar (3 patches) | detect only (file locked while PiDeck runs) |
14
+ | force-typed extension order | auto-moves known force-typed packages to the end, backup first |
15
+ | manual version vs injected version | warns once per mismatch pair |
25
16
 
26
17
  ## Install
27
18
 
28
- ```bash
29
- pi install npm:pi-patch-keeper
30
- pi install ./pi-patch-keeper
31
- ```
19
+ pi install npm:pi-patch-keeper
20
+ pi install ./pi-patch-keeper
32
21
 
33
- ## Defaults
22
+ Reload or restart the session after installing.
34
23
 
35
- | Key | Default |
36
- | --- | --- |
37
- | `forceTail` | `npm:pi-rtk-optimizer`, `npm:pi-cache-optimizer` |
38
- | Auto-fix | on (order only, backup first) |
39
- | Notify | only on problems |
40
- | Scope | `npm:` packages |
24
+ ## Commands
41
25
 
42
- Optional config: `~/.pi/patch-keeper.json`
26
+ | Command | Effect |
27
+ | --- | --- |
28
+ | /patch-keeper | status of every patch face |
29
+ | /patch-keeper fix | heal what can be healed now |
43
30
 
44
31
  ## Discipline
45
32
 
46
- - Never `return { systemPrompt }` — otherwise it becomes the problem it guards against.
47
- - Writes only two places: `packages` order in `settings.json` (backup first) and the fingerprint in `~/.pi/patch-keeper.json`; failures are reported, never thrown.
48
- - Any error is reported as a hint, never thrown; silent when clean.
33
+ - Never returns systemPrompt; only notifies.
34
+ - Any failure is reported as a hint, never thrown.
35
+ - All paths derive from the home directory, so it survives machine, username and drive changes.
49
36
 
50
37
  ## Limits
51
38
 
52
- - Detects static forms only; dynamic `systemPrompt` construction is not detected.
53
- - Local-path packages are skipped.
54
- - Unknown force-typed extensions must be added to `forceTail` manually.
39
+ - asar patches cannot be applied while PiDeck is running; the extension only reports them.
40
+ - Upstream patches are detected by marker strings; a substantially rewritten upstream file is reported as unknown instead of being patched.
55
41
 
56
42
  ## License
57
43
 
package/README.md CHANGED
@@ -1,57 +1,63 @@
1
- # pi-patch-keeper — 扩展加载顺序守护(pi 扩展)
1
+ # pi-patch-keeper —— 补丁自愈与状态检测(pi 扩展)
2
2
 
3
- 防止「force 型扩展」静默吞掉其后的 system 注入。
3
+ ## 安装
4
4
 
5
- ## 为什么需要
5
+ npm 发布版:`pi install npm:pi-patch-keeper`
6
6
 
7
- pi 的 system prompt 由各扩展写入的 section 拼装。若某扩展在 `before_agent_start` 里
8
- `return { systemPrompt }`(或设置 `forceSystemPrompt`),宿主会用返回值**整段替换**,
9
- 其后所有扩展的 section 写入被静默丢弃——没有报错,表现为「配了却不起效」。
7
+ 本地目录:`pi install <path/to/patch-keeper>`
10
8
 
11
- ## 功能
9
+ 安装后 `/reload` 或重启会话生效(扩展源码改动需重启)。
12
10
 
13
- - **启动检查** `settings.json` 的 `packages` 顺序:已知 force 型必须整体位于末尾。
14
- - **静态扫描**已装 npm 扩展的入口源码,区分两类:
15
- - 「无条件 force」——从不写 section,只 return systemPrompt(会吞掉其后一切)
16
- - 「兼容兜底」——先写 section,只在旧宿主才 force(安全)
17
- - **自动修复**:把已知 force 型移到末尾(写前备份 `settings.json.bak-force-order-*`)。
18
- - **指纹提示**:记录 `packages / defaultTools / enabledModels / extensions / codemode` 指纹,
19
- 变化时提示「环境已变,旧结论可能过期」。
20
- - **codemode 单点检查**:禁用 `builtin:codemode` 必须有替代实现,反之亦然。
11
+ **是什么**:把「对别人的东西」的改动(**12 个面**:PiDeck builtin ×5 双份 · npm 包 ×4 · app.asar ×3)从「升级后手工重跑」变成**启动自愈 + 明确报告**——外置、模块化、抗上游升级。全量清单由本机补丁登记表维护(PATCH-REGISTRY,随快照包分发)。
21
12
 
22
- ## 命令
13
+ ## 来源与借鉴
23
14
 
24
- | 命令 | 作用 |
25
- | --- | --- |
26
- | `/patch-keeper` | 查看顺序 / 疑似 force / 兼容兜底 / codemode 单点 |
27
- | `/patch-keeper fix` | 修 force 顺序(写前备份) |
15
+ 原创,无上游实现。设计灵感来自本机长期维护 PiDeck / pi 补丁的实践:补丁会被升级覆盖,故需要启动时自检与自愈。
28
16
 
29
- ## 配置
17
+ ## 机制(源码级)
30
18
 
31
- `~/.pi/patch-keeper.json`(可选):
19
+ 1. **session_start 自检**(每次 pi 启动):
20
+ - **pi-lens wordindex 补丁:能修的直接修**——本扩展是 user 扩展(加载 rank 2),先于 pi-lens 的 package rank 4;factory 内同步改 `dist/index.js`,pi-lens 随后 import 到的即打过补丁的内容(**当轮生效**);半打状态先还原再重打(幂等)。**上游发版后停手**:dist 出现 `warm_cache_adopted`(#4583 / PR #4586)即视为 A 已修复——跳过 A、只补 B(B 上游未修),`/patch-keeper` 显示「上游已修复 #4583」。
21
+ - **pi-memory exit summary 空行规范化:能修的直接修**——改 npm pi-memory 的 `index.ts`(render 侧规范块级空行;幂等;写前留 `.bak-exitsummary-<stamp>` 备份)。
22
+ - **PiDeck asar 三补丁:只检测不修**——PiDeck 运行中文件被锁、插件无权碰 Electron 主进程;检测到未打补丁时提示跑 `launch-pideck.cmd`(启动前自动重打)或快照 `05-脚本补丁/` 下脚本。
23
+ 2. **before_agent_start 注入对齐检测**:比对「本轮注入的手册版本」vs「磁盘版」——不一致提示**一次**(同 pair 去重);方向不限(注入滞后 / 磁盘回滚都可能)。
24
+ 3. **环境漂移指纹**:`~/.pi/patch-keeper.json` 记录 settings 关键字段(packages / defaultTools 等)——支撑漂移检测。
25
+ 4. **force 顺序守卫(自动修复)**:packages 中条件 force 型(pi-rtk-optimizer / pi-cache-optimizer)须在末尾——启动与 /patch-keeper fix 时自动移到末尾(先备份 settings.json.bak-force-order-*),修复幂等;其后 section 写入不会被静默丢弃。
26
+ 5. **force 型扩展扫描(疑似)**:扫描 packages 入口源码中的 return { systemPrompt } / forceSystemPrompt,报告疑似无条件 force 的包(会覆盖 system、使其后 section 静默丢失);位于中间者启动时提示。先写 section、只有旧宿主才 force 的归为「兼容兜底」,不计入疑似。
32
27
 
33
- ```json
34
- { "forceTail": ["npm:pi-rtk-optimizer", "npm:pi-cache-optimizer"] }
35
- ```
28
+ ## 自我回灌(条件触发型)
36
29
 
37
- `forceTail` 覆盖默认的「已知 force 型」列表;数组顺序即期望顺序(最可能触发者最后)。
38
- 指纹状态写入同文件的 `fingerprint` 字段。
30
+ 与 caveman / ptc-meter / think-anchor 的「每轮回灌」不同:**常态零注入**,只在异常时出声一次——
39
31
 
40
- ## 纪律
32
+ - 每轮 before_agent_start 比对「本轮实际注入的手册版本」vs「磁盘版本」;
33
+ - 不一致(注入滞后 / 磁盘回滚均可能)→ 一次 notify 提示「以磁盘为准、先读回全文」(同 pair 去重,不重复打扰);
34
+ - notify 用户 + 回灌模型(nextTurn,四律②:用户侧收到后模型也须知道,否则「以磁盘为准」停在用户侧);检测失败静默。
41
35
 
42
- - **绝不** `return { systemPrompt }` —— 否则自己就是它要防的问题。
43
- - 写操作两处:修 `settings.json` 的 `packages`(写前备份)与更新 `~/.pi/patch-keeper.json` 的指纹;失败都只提示。
44
- - 任何异常只提示、不抛错;无问题不打扰。
36
+ ## 纪律(回灌四律实践)
45
37
 
46
- ## 安装
38
+ - **绝不返回 systemPrompt**——只 notify;任何失败静默(检测不该影响会话,绝不抛错)。
39
+ - 路径全部从 home / `%LOCALAPPDATA%` 推导——换机、换用户名、复刻包到别机均可用。
40
+
41
+ ## 配置与命令
42
+
43
+ | 项 | 值 |
44
+ | --- | --- |
45
+ | 指纹文件 | `~/.pi/patch-keeper.json`(随 settings 变化同步) |
46
+ | 命令 | `/patch-keeper`(状态)· `/patch-keeper fix`(能修的立即修) |
47
+
48
+ ## 生效与回滚
49
+
50
+ - 生效:装上即用(每次会话启动自检);代码改动 `/reload` 或重启。
51
+ - 回滚:删本目录;已打补丁保持原样(回退用 `05-脚本补丁/` 下脚本各自的 rollback)。
52
+
53
+ ## 测试
54
+
55
+ 源码仓库内的隔离自测覆盖:force 顺序三例、命令注册、版本不一致告警一次的 pair 去重、一致静默、空 event 不抛、session_start 失败静默、自建扩展被覆盖后从快照恢复、上游已修标记(A 停打 / 仅补 B)。
56
+
57
+ ## 环境依赖与降级
47
58
 
48
- ```bash
49
- pi install npm:pi-patch-keeper
50
- pi install ./pi-patch-keeper
51
- ```
59
+ 补丁目标(npm 包与 PiDeck builtin)不存在时对应项跳过并只报状态,不报错;本机快照目录(备份与恢复来源)缺失时,恢复类动作跳过,自愈仍然工作。适配任意用户名与安装路径。
52
60
 
53
- ## 限制
61
+ ## License
54
62
 
55
- - 静态扫描从各入口的 `before_agent_start` 命中处起看 4000 字符(只看前 3 个入口文件),动态构造的 force 检测不到。
56
- - user 扩展(不在 `packages` 数组里)不在扫描范围。
57
- - 只处理顺序问题;不修改任何第三方扩展的源码。
63
+ MIT.
package/index.ts CHANGED
@@ -1,113 +1,445 @@
1
1
  /**
2
- * patch-keeper —— 扩展加载顺序守护(pi 扩展)
2
+ * patch-keeper —— 补丁自愈与状态检测(pi 扩展,外置 · 模块化 · 抗上游升级)
3
3
  *
4
- * 问题:pi 的 system prompt 由各扩展的 section 写入拼装。若某扩展在
5
- * `before_agent_start` 里 `return { systemPrompt }`(或设置 forceSystemPrompt),
6
- * 它会**静默丢弃其后所有扩展的 section 写入**——没有任何报错,表现为
7
- * 「某个扩展配了却没效果」。
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 被锁)明确报出来。
8
10
  *
9
- * 本扩展做三件事(全部只读,唯一的写是带备份修 settings):
10
- * 1. 检查 `settings.json` 的 packages 顺序:已知 force 型必须排在末尾。
11
- * 2. 静态扫描已装 npm 扩展入口源码,区分「无条件 force」与「section 优先 + 旧宿主兜底」。
12
- * 3. 记录 settings 关键字段指纹;变化时提示「环境已变,旧结论可能过期」。
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 到的就是打过补丁的内容 —— 当轮生效。
13
16
  *
14
- * 纪律:绝不 return systemPrompt(否则自己就是问题);任何失败只提示、不抛错。
17
+ * ## 边界(刻意的)
18
+ * - PiDeck asar:**只检测不修**。PiDeck 正开着,文件被锁;且插件无权碰 Electron 主进程。
19
+ * 检测到未打补丁 → 提示跑 `run-all.cmd` / `launch-pideck.cmd`(桌面 PI脚本补丁/ 不在时用快照副本 05-脚本补丁/)。
20
+ * - 任何失败都只 notify,不抛错、不影响会话(纪律:不合法就跳过 + 记日志,绝不崩溃)。
15
21
  */
16
22
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
17
- import { existsSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
23
+ import { existsSync, readFileSync, writeFileSync, copyFileSync, readdirSync, renameSync } from "node:fs";
24
+ import { createHash } from "node:crypto";
18
25
  import * as os from "node:os";
19
26
  import * as path from "node:path";
20
27
 
28
+ // 路径从 home / %LOCALAPPDATA% 推导(不写死用户名:换机 / 换用户名 / 复刻包到别的机器仍可用)
21
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
+ // 自建扩展保护:发布精简版覆盖自愈版时(2026-10-18 实证)从快照恢复
37
+ const SELF_EXT = path.join(HOME, ".pi", "agent", "extensions", "patch-keeper", "index.ts");
38
+ const SELF_SNAP = path.join(HOME, "Desktop", "pi-env-snapshot", "01-pi核心配置", "extensions", "patch-keeper", "index.ts");
39
+ const SELF_MARK = "SNAPSHOT_PATCH_DIR"; // 自愈版特征:发布精简版没有这行
40
+ // 环境指纹文件(settings 关键字段,用于漂移检测)
41
+ const FINGERPRINT = path.join(HOME, ".pi", "patch-keeper.json");
22
42
  const SETTINGS = path.join(HOME, ".pi", "agent", "settings.json");
23
- // 配置与指纹同文件(与 README 一致;保留用户已有键)
24
- const STATE = path.join(HOME, ".pi", "patch-keeper.json");
25
- const NPM_ROOT = path.join(HOME, ".pi", "agent", "npm", "node_modules");
43
+ // 手册(注入对齐检测:本轮注入文本的版本行 vs 磁盘版)
44
+ const MANUAL = path.join(HOME, ".pi", "agent", "APPEND_SYSTEM.md");
26
45
 
27
- /** 已知无条件 force 型包。触发概率升序:越靠后越应排在 packages 末尾。 */
28
- const DEFAULT_FORCE_TAIL = ["npm:pi-rtk-optimizer", "npm:pi-cache-optimizer"];
46
+ // PiDeck 内置扩展补丁(本机修改;升级会覆盖,缺失时提示从快照恢复)
47
+ const PIDECK_BUILTIN = path.join(HOME, "AppData", "Roaming", "PiDeck", "builtin-extensions");
48
+ const PIDECK_INSTALL = path.join(process.env.LOCALAPPDATA ?? path.join(HOME, "AppData", "Local"), "Programs", "PiDeck", "resources", "extensions");
49
+ // needle = 本机修复特征串(不是 section 名):命中即视为已打;升级覆盖后从快照恢复。
50
+ const BUILTIN_PATCHES: Array<{ file: string; install: string; needle: string; name: string }> = [
51
+ { file: path.join(PIDECK_BUILTIN, "pi-deck-security-gate.ts"), install: path.join(PIDECK_INSTALL, "pi-deck-security-gate.ts"), needle: "越界操作先说明理由", name: "security-gate" },
52
+ { 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" },
53
+ { 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" },
54
+ { 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" },
55
+ { 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" },
56
+ ];
57
+ const SNAPSHOT_BUILTIN = path.join(HOME, "Desktop", "pi-env-snapshot", "03-PiDeck", "builtin-extensions");
58
+ const MANUAL_STATE = path.join(HOME, ".pi", "patch-keeper-manual.json");
59
+ /**
60
+ * 从手册文本里取版本号(标题「自主工作手册」后 200 字符内的第一个 vNN.NN)。
61
+ * 取不到返回 null(注入文本若不含标题即静默跳过,绝不猜)。
62
+ */
63
+ function manualVer(text: string): string | null {
64
+ const i = text.indexOf("自主工作手册");
65
+ if (i < 0) return null;
66
+ const m = text.slice(i, i + 200).match(/v(\d+\.\d+)/);
67
+ return m ? m[1] : null;
68
+ }
29
69
 
30
- /** 静态扫描:入口源码里出现这两个形态即判为 force。 */
31
- const FORCE_RE = /return\s*\{\s*systemPrompt|forceSystemPrompt/;
32
- const SECTION_RE = /sections\s*(\[|\.)/;
70
+ // ── pi-lens word index 补丁:两处替换(与 patches/pi-lens-wordindex-patch.js 同源)
71
+ const A1_FROM = " warmWordIndexes.set(key4, entry);\n }\n entry.leases++;";
72
+ const A1_MARK = "if (entry && !entry.index) {";
73
+ 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++;";
74
+ const A2_FROM = "if (!snapshot.wordIndex && existing.wordIndex && existing.seq === snapshot.seq && (snapshot.incomplete || !existing.incomplete)) {";
75
+ const A2_MARK = "existing.wordIndex && (snapshot.incomplete";
76
+ const A2_TO = "if (!snapshot.wordIndex && existing.wordIndex && (snapshot.incomplete || !existing.incomplete)) {";
77
+ // 上游修复标记(#4583 / PR #4586):build 完成即推送 warm cache;出现即停打 A 补丁(与 patches/pi-lens-wordindex-patch.js 同源)
78
+ const UPSTREAM_MARK = "warm_cache_adopted";
79
+
80
+
81
+ // ── pi-memory exit summary 空行规范化补丁(幂等;与 pi-memory/index.ts 内已打状态一致)
82
+ const ME_MARK = "normalizeExitSummaryMarkdown";
83
+ const ME_FROM_FN = "function formatExitSummaryEntry(";
84
+ const ME_FROM_RET = 'header, "", summary.trim()].join("\\n");';
85
+ const ME_TO_RET = 'header, "", normalizeExitSummaryMarkdown(summary.trim())].join("\\n");';
86
+ 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");
87
+ const MEM_SECTION_MARK = 'sections["pi_memory"]';
88
+ const MEM_SECTION_ANCHOR = [
89
+ "\t\treturn {",
90
+ "\t\t\tsystemPrompt: event.systemPrompt + headerLines.join(\"\\n\"),",
91
+ "\t\t};",
92
+ ].join("\n");
93
+ const MEM_SECTION_BLOCK = [
94
+ "\t\t// R7:有 sections 的宿主优先写 section —— 返回 systemPrompt 是 force 覆盖,",
95
+ "\t\t// 会丢弃其后(builtin 组)goal / plan / security 的 section 写入",
96
+ "\t\t// (2026-10-17 实证:goal 的 Objective 与 Rules 从 system 消失,只剩 Round 消息)。",
97
+ "\t\tconst sections = (event as { systemPromptOptions?: { sections?: Record<string, string> } }).systemPromptOptions?.sections;",
98
+ "\t\tif (sections) {",
99
+ "\t\t\tsections[\"pi_memory\"] = headerLines.join(\"\\n\").replace(/^\\n+/, \"\");",
100
+ "\t\t\treturn;",
101
+ "\t\t}",
102
+ "\t\treturn {",
103
+ "\t\t\tsystemPrompt: event.systemPrompt + headerLines.join(\"\\n\"),",
104
+ "\t\t};",
105
+ ].join("\n");
106
+ const TACT = path.join(HOME, ".pi", "agent", "npm", "node_modules", "@khanhicetea", "pi-tactician", "src", "index.ts");
107
+ const TACT_MARK = 'sections["tactician"]';
108
+ const TACT_ANCHOR = [
109
+ "\t\tif (event.systemPrompt.includes(GUIDANCE_MARKER)) return;",
110
+ "\t\treturn { systemPrompt: `${event.systemPrompt}\\n\\n${TACTICIAN_GUIDANCE}` };",
111
+ ].join("\n");
112
+ const TACT_BLOCK = [
113
+ "\t\t// R7b:有 sections 的宿主写 section(不 force)——force 会让其后 builtin 组",
114
+ "\t\t// (goal / plan / security)的 section 写入被整组丢弃(2026-10-17 实证)。",
115
+ "\t\tconst sections = (event as { systemPromptOptions?: { sections?: Record<string, string> } }).systemPromptOptions?.sections;",
116
+ "\t\tif (sections) {",
117
+ "\t\t\tsections[\"tactician\"] = TACTICIAN_GUIDANCE;",
118
+ "\t\t\treturn;",
119
+ "\t\t}",
120
+ "\t\tif (event.systemPrompt.includes(GUIDANCE_MARKER)) return;",
121
+ "\t\treturn { systemPrompt: `${event.systemPrompt}\\n\\n${TACTICIAN_GUIDANCE}` };",
122
+ ].join("\n");
123
+
124
+ /** pi-memory 状态:done / none。 */
125
+ function piMemoryState(src: string): "done" | "none" {
126
+ return src.includes(ME_MARK) ? "done" : "none";
127
+ }
128
+
129
+ /** 打/补 pi-memory exit summary 规范化(幂等)。 */
130
+ function healPiMemory(): Result {
131
+ if (!existsSync(PI_MEMORY)) return { ok: false, detail: "pi-memory/index.ts 不存在(未安装?)" };
132
+ const src = safeRead(PI_MEMORY);
133
+ if (src === null) return { ok: false, detail: "读取失败" };
134
+ if (piMemoryState(src) === "done") return { ok: true, detail: "已是最新(无需动作)" };
135
+ if (!src.includes(ME_FROM_FN) || !src.includes(ME_FROM_RET)) return { ok: false, detail: "锚点未找到(版本变化?)—— 需人工确认" };
136
+ let next = src.replace(ME_FROM_RET, ME_TO_RET);
137
+ next = next.replace(ME_FROM_FN, ME_FN + "\n\n" + ME_FROM_FN);
138
+ if (!next.includes(ME_MARK) || next === src) return { ok: false, detail: "打补丁失败(结果校验不通过)" };
139
+ try {
140
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
141
+ const bak = `${PI_MEMORY}.bak-exitsummary-${stamp}`;
142
+ if (!existsSync(bak)) copyFileSync(PI_MEMORY, bak);
143
+ writeAtomic(PI_MEMORY, next);
144
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
145
+ return { ok: true, detail: "已自动修补(exit summary 空行规范化)—— 本轮即生效" };
146
+ }
147
+ /** R7:memory 段改 section(防 force 吞掉其后 builtin 组的 section)。 */
148
+ function healMemorySection(): Result {
149
+ if (!existsSync(PI_MEMORY)) return { ok: false, detail: "pi-memory/index.ts 不存在(未安装?)" };
150
+ const src = safeRead(PI_MEMORY);
151
+ if (src === null) return { ok: false, detail: "读取失败" };
152
+ if (src.includes(MEM_SECTION_MARK)) return { ok: true, detail: "已是最新(无需动作)" };
153
+ if (!src.includes(MEM_SECTION_ANCHOR)) return { ok: false, detail: "锚点未找到(版本变化?)—— 需人工确认" };
154
+ const next = src.replace(MEM_SECTION_ANCHOR, MEM_SECTION_BLOCK);
155
+ if (!next.includes(MEM_SECTION_MARK) || next === src) return { ok: false, detail: "打补丁失败(结果校验不通过)" };
156
+ try {
157
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
158
+ const bak = `${PI_MEMORY}.bak-memsec-${stamp}`;
159
+ if (!existsSync(bak)) copyFileSync(PI_MEMORY, bak);
160
+ writeAtomic(PI_MEMORY, next);
161
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
162
+ return { ok: true, detail: "已自动修补(memory 段改 section)—— 重启后生效" };
163
+ }
164
+ /** R7b:tactician 改 section(防 force 吞掉其后 builtin 组的 section)。 */
165
+ function healTactician(): Result {
166
+ if (!existsSync(TACT)) return { ok: false, detail: "pi-tactician/src/index.ts 不存在(未安装?)" };
167
+ const src = safeRead(TACT);
168
+ if (src === null) return { ok: false, detail: "读取失败" };
169
+ if (src.includes(TACT_MARK)) return { ok: true, detail: "已是最新(无需动作)" };
170
+ if (!src.includes(TACT_ANCHOR)) return { ok: false, detail: "锚点未找到(版本变化?)—— 需人工确认" };
171
+ const next = src.replace(TACT_ANCHOR, TACT_BLOCK);
172
+ if (!next.includes(TACT_MARK) || next === src) return { ok: false, detail: "打补丁失败(结果校验不通过)" };
173
+ try {
174
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
175
+ const bak = `${TACT}.bak-tactician-${stamp}`;
176
+ if (!existsSync(bak)) copyFileSync(TACT, bak);
177
+ writeAtomic(TACT, next);
178
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
179
+ return { ok: true, detail: "已自动修补(tactician 改 section)—— 重启后生效" };
180
+ }
181
+ // ── PiDeck asar 补丁:只读检测(needle 出现次数)
182
+ const ASAR_CHECKS: Array<{ name: string; needle: string; expected: number }> = [
183
+ { name: "history-race", needle: "runtime.tab.runtimeGeneration !== runtimeGeneration", expected: 8 },
184
+ { name: "katex", needle: "singleDollarTextMath: !0", expected: 0 },
185
+ { name: "noise", needle: "appLogger.warn(\"app\", \"Main window renderer console error\"", expected: 0 },
186
+ ];
33
187
 
34
- export type Result = { ok: boolean; detail: string };
188
+ type Result = { ok: boolean; detail: string };
35
189
 
190
+ /** 读文件;失败返回 null(永不抛)。 */
36
191
  function safeRead(p: string): string | null {
192
+ try { return readFileSync(p, "utf8"); } catch { return null; }
193
+ }
194
+
195
+ /** 原子写:临时文件 + rename(崩溃/被杀不留半写文件)。 */
196
+ function writeAtomic(file: string, data: string | Buffer): void {
197
+ const tmp = file + ".tmp-" + process.pid;
198
+ writeFileSync(tmp, data);
199
+ renameSync(tmp, file);
200
+ }
201
+
202
+ /** 统计 needle 在原串里的出现次数。 */
203
+ function count(hay: string, needle: string): number {
204
+ let n = 0, i = 0;
205
+ while ((i = hay.indexOf(needle, i)) >= 0) { n += 1; i += needle.length; }
206
+ return n;
207
+ }
208
+
209
+ /** pi-lens 状态:both / partial / none / missing。 */
210
+ export function piLensState(src: string): { state: "upstream" | "both" | "partial" | "none"; a1: boolean; a2: boolean } {
211
+ const upstream = src.includes(UPSTREAM_MARK); // 上游已修 #4583:A 无需本机补丁
212
+ const a1 = src.includes(A1_MARK);
213
+ const a2 = !src.includes(A2_FROM) && src.includes(A2_MARK);
214
+ let state: "upstream" | "both" | "partial" | "none" = "none";
215
+ if (upstream) state = "upstream";
216
+ else if (a1 && a2) state = "both";
217
+ else if (a1 || a2) state = "partial";
218
+ return { state, a1, a2 };
219
+ }
220
+
221
+ /** 只在未打或半打时修补 pi-lens(幂等)。 */
222
+ function healPiLens(): Result {
223
+ if (!existsSync(PI_LENS)) return { ok: false, detail: "pi-lens dist 不存在(未安装?)" };
224
+ const src = safeRead(PI_LENS);
225
+ if (src === null) return { ok: false, detail: "读取失败" };
226
+ const { state, a1, a2 } = piLensState(src);
227
+ if (state === "both") return { ok: true, detail: "已是最新(无需动作)" };
228
+ if (state === "upstream" && a2) return { ok: true, detail: "上游已修复 #4583(B 已打,无需动作)" };
229
+ let next = src;
230
+ // 半打状态先还原,再整体重打(避免只打一半造成新的不一致)
231
+ if (a2 && !a1) next = next.replace(A2_TO, A2_FROM); // 半打:先把 B 还原,再由下面两步整体重打
232
+ if (state !== "upstream" && !next.includes(A1_MARK)) next = next.replace(A1_FROM, A1_TO);
233
+ if (next.includes(A2_FROM)) next = next.replace(A2_FROM, A2_TO);
234
+ const after = piLensState(next);
235
+ if (after.state !== "both" && after.state !== "upstream") return { ok: false, detail: `打补丁失败(结果 ${after.state},锚点可能已随版本变化)` };
236
+ try {
237
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
238
+ const bak = `${PI_LENS}.bak-wordindex-${stamp}`;
239
+ if (!existsSync(bak)) copyFileSync(PI_LENS, bak);
240
+ writeAtomic(PI_LENS, next);
241
+ } catch (e) { return { ok: false, detail: `写入失败:${(e as Error).message}` }; }
242
+ return { ok: true, detail: state === "upstream" ? `上游已修复 #4583 —— 跳过 A,仅补 B${a1 ? "(A 残留,建议 npm 重装清除)" : ""}` : `已自动修补(原状态 ${state})—— 本轮即生效` };
243
+ }
244
+
245
+
246
+ /** 记忆文件格式规范化(压连续空行 + 单尾换行;围栏内不动)。 */
247
+ function normMd(txt: string): string {
248
+ const lines = txt.split(/\r?\n/);
249
+ const out: string[] = [];
250
+ let inFence = false;
251
+ for (const line of lines) {
252
+ const isF = /^\s*(?:`{3,}|~{3,})/.test(line);
253
+ if (isF) inFence = !inFence;
254
+ if (!inFence && line.trim() === "" && out.length > 0 && out[out.length - 1].trim() === "") continue;
255
+ out.push(line);
256
+ }
257
+ while (out.length > 0 && out[out.length - 1].trim() === "") out.pop();
258
+ return out.join("\n") + "\n";
259
+ }
260
+
261
+ /** 第 3 处自愈:memory_write 每次写入都会引入 MD012/MD047(同日复发 3 次后机制化)——启动即规范。 */
262
+ function healMemoryFormat(): Result {
37
263
  try {
38
- return readFileSync(p, "utf8");
39
- } catch {
40
- return null;
264
+ const dir = path.join(HOME, ".pi", "agent", "memory");
265
+ if (!existsSync(dir)) return { ok: true, detail: "memory 目录不存在(跳过)" };
266
+ let fixed = 0;
267
+ const walk = (d: string): void => {
268
+ for (const e of readdirSync(d, { withFileTypes: true })) {
269
+ const p = path.join(d, e.name);
270
+ if (e.isDirectory()) { if (e.name !== ".git") walk(p); continue; }
271
+ if (!e.name.endsWith(".md")) continue;
272
+ const txt = safeRead(p);
273
+ if (txt === null) continue;
274
+ const norm = normMd(txt);
275
+ if (norm !== txt) { try { writeAtomic(p, norm); fixed += 1; } catch { /* 静默 */ } }
276
+ }
277
+ };
278
+ walk(dir);
279
+ return { ok: true, detail: fixed > 0 ? `已规范化 ${fixed} 个记忆文件(空行 / 尾换行)` : "记忆格式无需动作" };
280
+ } catch (e) { return { ok: false, detail: (e as Error).message }; }
281
+ }
282
+ /** PiDeck asar:只读检测,返回未打补丁的项名。 */
283
+ let asarOk = false;
284
+ /** 未打补丁时的处置提示(纯函数,便于单测)。 */
285
+ function patchTip(lines: string[]): string {
286
+ if (!lines.some((l) => l.includes("未打") || l.includes("半打"))) return "";
287
+ const dir = existsSync(SNAPSHOT_PATCH_DIR) ? SNAPSHOT_PATCH_DIR : "pi-env-snapshot/05-脚本补丁/(也未找到)";
288
+ return ` → PiDeck 补丁需退出 PiDeck 后重跑补丁脚本(快照副本:${dir};或用其中的 launch-pideck.cmd 启动 PiDeck 时自动重打)`;
289
+ }
290
+
291
+
292
+ function checkAsar(): { ran: boolean; missing: string[]; detail: string } {
293
+ if (asarOk) return { ran: true, missing: [], detail: "三个补丁都在" };
294
+ if (!existsSync(ASAR)) return { ran: false, missing: [], detail: "app.asar 不存在" };
295
+ let buf: Buffer;
296
+ try { buf = readFileSync(ASAR); } catch (e) { return { ran: false, missing: [], detail: `读取失败:${(e as NodeJS.ErrnoException).code ?? (e as Error).message}` }; }
297
+ const txt = buf.toString("utf8");
298
+ const missing: string[] = [];
299
+ for (const c of ASAR_CHECKS) {
300
+ const n = count(txt, c.needle);
301
+ if (n !== c.expected) missing.push(`${c.name}(=${n}, 期望 ${c.expected})`);
41
302
  }
303
+ if (!missing.length) asarOk = true; // 只在通过时缓存:缺失时每次都实测,便于打完补丁后立刻复检
304
+ return { ran: true, missing, detail: missing.length ? `未打补丁:${missing.join(" ")}` : "三个补丁都在" };
42
305
  }
43
306
 
44
- function readSettings(): Record<string, unknown> | null {
307
+ /** 汇总报告(给命令与启动提示共用)。 */
308
+ // ── 环境指纹:settings 关键字段漂移 → 提示「手册 / 验证结论可能过期」
309
+ function fingerprint(): Record<string, string[]> | null {
45
310
  const txt = safeRead(SETTINGS);
46
311
  if (txt === null) return null;
47
312
  try {
48
- return JSON.parse(txt) as Record<string, unknown>;
49
- } catch {
50
- return null;
313
+ const s = JSON.parse(txt) as Record<string, unknown>;
314
+ return {
315
+ packages: (s.packages as string[]) ?? [],
316
+ defaultTools: (s.defaultTools as string[]) ?? [],
317
+ enabledModels: (s.enabledModels as string[]) ?? [],
318
+ extensions: (s.extensions as string[]) ?? [],
319
+ codemode: [(s.codemode as { mode?: string })?.mode ?? "?"],
320
+ };
321
+ } catch { return null; }
322
+ }
323
+ /** 与上次指纹对比;变化摘要数组(无变化为空)。对比后写回新指纹。 */
324
+ function fingerprintDrift(): string[] {
325
+ const cur = fingerprint();
326
+ if (cur === null) return [];
327
+ let prev: Record<string, string[]> | null = null;
328
+ const prevRaw = safeRead(FINGERPRINT);
329
+ if (prevRaw) { try { prev = JSON.parse(prevRaw) as Record<string, string[]>; } catch { prev = null; } }
330
+ try { writeAtomic(FINGERPRINT, JSON.stringify(cur, null, 1)); } catch { /* 静默 */ }
331
+ if (prev === null) return [];
332
+ const out: string[] = [];
333
+ for (const k of ["packages", "defaultTools", "enabledModels", "extensions", "codemode"] as const) {
334
+ const a = prev[k] ?? [];
335
+ const b = cur[k];
336
+ const added = b.filter((x) => !a.includes(x)).length;
337
+ const removed = a.filter((x) => !b.includes(x)).length;
338
+ if (added || removed) out.push(`${k} ${a.length}→${b.length}${added ? ` +${added}` : ""}${removed ? ` -${removed}` : ""}`);
51
339
  }
340
+ return out;
52
341
  }
53
342
 
54
- /** 用户可在 ~/.pi/patch-keeper.json 用 forceTail 覆盖已知 force 型列表。 */
55
- function forceTail(): string[] {
56
- const txt = safeRead(STATE);
57
- if (!txt) return DEFAULT_FORCE_TAIL;
58
- try {
59
- const cfg = JSON.parse(txt) as { forceTail?: unknown };
60
- return Array.isArray(cfg.forceTail) && cfg.forceTail.every((x) => typeof x === "string")
61
- ? (cfg.forceTail as string[])
62
- : DEFAULT_FORCE_TAIL;
63
- } catch {
64
- return DEFAULT_FORCE_TAIL;
343
+ /** codemode 单点一致性:禁 builtin:codemode ⟺ packages 含 pi-codemode-guard(启动检查 / /patch-keeper 共用)。 */
344
+ export function consistencyCheck(exts: string[], pkgs: string[]): string[] {
345
+ const disabled = (exts ?? []).includes("-builtin:codemode");
346
+ const guard = (pkgs ?? []).includes("npm:pi-codemode-guard");
347
+ if (disabled && !guard) return ["codemode 单点断裂:已禁 builtin:codemode 但 packages 无 pi-codemode-guard —— codemode 工具将不可用"];
348
+ if (!disabled && guard) return ["codemode 单点异常:pi-codemode-guard 在但未禁 builtin:codemode —— 双实现风险"];
349
+ return [];
350
+ }
351
+
352
+
353
+ function restoreBuiltinPatches(): string | null {
354
+ const out: string[] = [];
355
+ for (const bp of BUILTIN_PATCHES) {
356
+ for (const target of [bp.install, bp.file]) {
357
+ if (!existsSync(target)) continue; // 未装 PiDeck / 路径不同:跳过,不算缺失
358
+ const cur = safeRead(target);
359
+ if (cur !== null && cur.includes(bp.needle)) continue;
360
+ const snap = path.join(SNAPSHOT_BUILTIN, path.basename(target));
361
+ if (!existsSync(snap)) { out.push(`${bp.name}: 缺补丁且快照无副本`); continue; }
362
+ try {
363
+ if (cur !== null) copyFileSync(target, `${target}.bak-restore-${Date.now()}`);
364
+ copyFileSync(snap, target);
365
+ out.push(`${bp.name}(${target === bp.install ? "安装目录" : "用户层"}): 已从快照恢复`);
366
+ } catch (e) { out.push(`${bp.name}: 恢复失败(${(e as Error).message})`); }
367
+ }
65
368
  }
369
+ return out.length ? out.join(";") : null;
66
370
  }
67
371
 
68
- /** force 型必须整体位于末尾,且相对顺序按 tail 数组。 */
69
- export function forceOrderIssues(packages: string[], tail: string[] = DEFAULT_FORCE_TAIL): string[] {
372
+ /** 手册内容漂移:版本号未变但正文变了(只比版本号会漏)。 */
373
+ function manualDrift(): string | null {
374
+ const disk = safeRead(MANUAL);
375
+ if (disk === null) return null;
376
+ const ver = manualVer(disk) ?? "";
377
+ const sig = createHash("sha256").update(disk).digest("hex").slice(0, 12);
378
+ let prev: { ver?: string; sig?: string } | null = null;
379
+ const raw = safeRead(MANUAL_STATE);
380
+ if (raw) { try { prev = JSON.parse(raw); } catch { prev = null; } }
381
+ try { writeAtomic(MANUAL_STATE, JSON.stringify({ ver, sig })); } catch { /* ignore */ }
382
+ if (prev && prev.ver === ver && prev.sig !== sig) return `手册内容已变但版本号未升(${ver})—— bump-manual 或撤销未登记改动`;
383
+ return null;
384
+ }
385
+ // 已知盲区:caveman-think-zh 是 user 扩展(不在 packages 数组),它在检测到原版英文段时
386
+ // 也会 force;FORCE_TAIL 覆盖不到,触发时本扩展看不到。
387
+ /** force/条件 force 型必须排在 packages 末尾(其后 section 写入会被静默丢弃)。触发概率升序:rtk → cache-optimizer。 */
388
+ const FORCE_TAIL = ["npm:pi-rtk-optimizer", "npm:pi-cache-optimizer"];
389
+ export function forceOrderIssues(packages: string[]): string[] {
70
390
  const out: string[] = [];
71
391
  const idx = (n: string) => packages.indexOf(n);
72
- const present = tail.filter((n) => idx(n) >= 0);
392
+ const present = FORCE_TAIL.filter((n) => idx(n) >= 0);
73
393
  if (!present.length) return out;
74
394
  const minForce = Math.min(...present.map(idx));
75
- const later = packages.slice(minForce + 1).filter((n) => !tail.includes(n));
76
- if (later.length) {
77
- out.push(
78
- `force 型之后仍有 ${later.length} 个包(${later.slice(0, 2).join(" / ")})—— 它们的 section 写入会被静默丢弃;把 ${tail.join(" / ")} 移到 packages 末尾`,
79
- );
80
- }
81
- const ordered = present.every((n, i) => i === 0 || idx(present[i - 1]) < idx(n));
82
- if (!ordered) out.push(`force 型相对顺序应与 ${tail.join(" → ")} 一致(最可能触发者最后)`);
395
+ const later = packages.slice(minForce + 1).filter((n) => !FORCE_TAIL.includes(n));
396
+ if (later.length) out.push(`force 型之后仍有 ${later.length} 个包(${later.slice(0, 2).join(" / ")})—— 它们的 section 写入会被丢弃;把 ${FORCE_TAIL.join(" / ")} 移到末尾`);
397
+ 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(最可能触发者最后)");
83
398
  return out;
84
399
  }
85
-
86
- /** 把 force 型移到末尾(其余相对顺序不变);已正确返回 null。 */
87
- export function normalizeForceOrder(packages: string[], tail: string[] = DEFAULT_FORCE_TAIL): string[] | null {
88
- const present = tail.filter((n) => packages.includes(n));
400
+ /** 把 FORCE_TAIL 成员移到末尾(其余相对顺序不变);已正确时返回 null。 */
401
+ export function normalizeForceOrder(packages: string[]): string[] | null {
402
+ const present = FORCE_TAIL.filter((n) => packages.includes(n));
89
403
  if (!present.length) return null;
90
- const rest = packages.filter((n) => !tail.includes(n));
404
+ const rest = packages.filter((n) => !FORCE_TAIL.includes(n));
91
405
  const next = [...rest, ...present];
92
406
  return next.join("\n") === packages.join("\n") ? null : next;
93
407
  }
94
408
 
95
- /** 读扩展入口源码并分类:无条件 force / section 优先(旧宿主兜底)/ 无。 */
96
- export function classifyForcePackages(packages: string[], tail: string[]): { force: string[]; fallback: string[] } {
409
+ /** 自动修复 settings.json 的 force 顺序;无变化返回 null。先备份再写。 */
410
+ function fixForceOrder(): string | null {
411
+ const txt = safeRead(SETTINGS);
412
+ if (txt === null) return null;
413
+ let s: Record<string, unknown>;
414
+ try { s = JSON.parse(txt) as Record<string, unknown>; } catch { return "force 顺序自动修复失败:settings.json 解析失败"; }
415
+ const packages = (s.packages as string[] | undefined) ?? [];
416
+ const next = normalizeForceOrder(packages);
417
+ if (!next) return null;
418
+ try {
419
+ copyFileSync(SETTINGS, `${SETTINGS}.bak-force-order-${Date.now()}`);
420
+ s.packages = next;
421
+ writeAtomic(SETTINGS, JSON.stringify(s, null, 2));
422
+ } catch (e) { return `force 顺序自动修复失败:${(e as Error).message}`; }
423
+ return `force 顺序已自动修复:${FORCE_TAIL.filter((n) => next.includes(n)).join(" / ")} 移到 packages 末尾`;
424
+ }
425
+ /** 静态扫描:packages 中疑似 force 型扩展(入口源码含 return { systemPrompt } / forceSystemPrompt)。 */
426
+ const FORCE_RE = /return\s*\{\s*systemPrompt|forceSystemPrompt/;
427
+ const SECTION_RE = /sections\s*(\[|\.)/;
428
+
429
+ /** 分类:先写 section、只有旧宿主才 force 的算兼容兜底,不算疑似无条件 force。 */
430
+ function classifyPackages(packages: string[]): { force: string[]; fallback: string[] } {
97
431
  const force: string[] = [];
98
432
  const fallback: string[] = [];
99
433
  for (const name of packages) {
100
- if (!name.startsWith("npm:") || tail.includes(name)) continue;
101
- const dir = path.join(NPM_ROOT, name.slice(4));
434
+ if (!name.startsWith("npm:") || FORCE_TAIL.includes(name)) continue;
435
+ const dir = path.join(HOME, ".pi", "agent", "npm", "node_modules", name.slice(4));
102
436
  if (!existsSync(dir)) continue;
103
437
  let entries: string[] = [];
104
438
  try {
105
439
  const pj = JSON.parse(safeRead(path.join(dir, "package.json")) ?? "{}") as { pi?: { extensions?: unknown } };
106
440
  const ex = pj.pi?.extensions;
107
441
  entries = Array.isArray(ex) ? ex.filter((x): x is string => typeof x === "string") : [];
108
- } catch {
109
- continue;
110
- }
442
+ } catch { continue; }
111
443
  for (const rel of entries.slice(0, 3)) {
112
444
  const src = safeRead(path.join(dir, rel));
113
445
  if (src === null) continue;
@@ -117,136 +449,204 @@ export function classifyForcePackages(packages: string[], tail: string[]): { for
117
449
  const fi = body.search(FORCE_RE);
118
450
  if (fi < 0) continue;
119
451
  const si = body.search(SECTION_RE);
120
- if (si >= 0 && si < fi) fallback.push(name);
121
- else force.push(name);
452
+ if (si >= 0 && si < fi) fallback.push(name); else force.push(name);
122
453
  break;
123
454
  }
124
455
  }
125
456
  return { force, fallback };
126
457
  }
127
458
 
128
- /** 疑似无条件 force(会吞掉其后 section)。 */
129
- export function scanForcePackages(packages: string[], tail: string[] = DEFAULT_FORCE_TAIL): string[] {
130
- return classifyForcePackages(packages, tail).force;
131
- }
132
-
133
- /** 兼容兜底型(section 优先,仅旧宿主 force)。 */
134
- export function scanForceFallbacks(packages: string[], tail: string[] = DEFAULT_FORCE_TAIL): string[] {
135
- return classifyForcePackages(packages, tail).fallback;
459
+ /** 疑似无条件 force(会静默吞掉其后 section)。 */
460
+ export function scanForcePackages(packages: string[]): string[] {
461
+ return classifyPackages(packages).force;
136
462
  }
137
463
 
138
- /** codemode 单点检查:禁用 builtin:codemode 时必须有替代实现,反之亦然。 */
139
- export function consistencyCheck(extensions: string[], packages: string[]): string[] {
140
- const disabled = extensions.includes("-builtin:codemode");
141
- const guard = packages.includes("npm:pi-codemode-guard");
142
- if (disabled && !guard) return ["codemode 单点断裂:已禁 builtin:codemode 但 packages 无替代实现 —— codemode 工具将不可用"];
143
- if (!disabled && guard) return ["codemode 单点异常:替代实现已在,但 builtin:codemode 未禁用 —— 双实现风险"];
144
- return [];
145
- }
146
-
147
- /** settings 关键字段指纹(顺序敏感)。 */
148
- function fingerprint(s: Record<string, unknown>): Record<string, string[]> {
149
- return {
150
- packages: (s.packages as string[]) ?? [],
151
- defaultTools: (s.defaultTools as string[]) ?? [],
152
- enabledModels: (s.enabledModels as string[]) ?? [],
153
- extensions: (s.extensions as string[]) ?? [],
154
- codemode: [(s.codemode as { mode?: string })?.mode ?? "?"],
155
- };
464
+ /** 兼容兜底(section 优先,旧宿主才 force)。 */
465
+ export function scanForceFallbacks(packages: string[]): string[] {
466
+ return classifyPackages(packages).fallback;
156
467
  }
157
468
 
158
- /** 与上次指纹对比并写回;返回变化摘要(无变化为空)。 */
159
- function fingerprintDrift(cur: Record<string, string[]>): string[] {
160
- let prev: Record<string, string[]> | null = null;
161
- const raw = safeRead(STATE);
162
- if (raw) {
163
- try {
164
- const j = JSON.parse(raw) as { fingerprint?: Record<string, string[]> };
165
- prev = j.fingerprint ?? null;
166
- } catch {
167
- prev = null;
168
- }
169
- }
469
+ /** 自建扩展保护:本地 patch-keeper 被发布精简版覆盖时,从快照恢复(幂等)。 */
470
+ function healSelfExtension(): Result {
471
+ if (!existsSync(SELF_EXT)) return { ok: false, detail: "本地 patch-keeper 不存在" };
472
+ const src = safeRead(SELF_EXT);
473
+ if (src === null) return { ok: false, detail: "读取失败" };
474
+ if (src.includes(SELF_MARK)) return { ok: true, detail: "自愈版完好(无需动作)" };
475
+ if (!existsSync(SELF_SNAP)) return { ok: false, detail: "疑似被发布精简版覆盖,快照缺失 —— 需人工恢复" };
476
+ const snap = safeRead(SELF_SNAP);
477
+ if (snap === null || !snap.includes(SELF_MARK)) return { ok: false, detail: "快照不含自愈版 —— 需人工确认" };
170
478
  try {
171
- const cfg = raw ? (JSON.parse(raw) as Record<string, unknown>) : {};
172
- writeFileSync(STATE, JSON.stringify({ ...cfg, fingerprint: cur }, null, 1), "utf8");
173
- } catch {
174
- /* 静默 */
175
- }
176
- if (prev === null) return [];
177
- const out: string[] = [];
178
- for (const k of ["packages", "defaultTools", "enabledModels", "extensions", "codemode"] as const) {
179
- const a = prev[k] ?? [];
180
- const b = cur[k];
181
- if (a.join("\n") !== b.join("\n")) out.push(k);
182
- }
183
- return out;
479
+ const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, "");
480
+ const bak = `${SELF_EXT}.bak-overwrite-${stamp}`;
481
+ if (!existsSync(bak)) copyFileSync(SELF_EXT, bak);
482
+ writeAtomic(SELF_EXT, snap);
483
+ } catch (e) { return { ok: false, detail: `恢复失败:${(e as Error).message}` }; }
484
+ return { ok: true, detail: "疑似被发布精简版覆盖 —— 已从快照恢复(重启后生效)" };
184
485
  }
185
-
186
- /** 修 settings 的 force 顺序(写前备份);无变化返回 null。 */
187
- function fixForceOrder(): string | null {
188
- const s = readSettings();
189
- if (!s) return null;
190
- const tail = forceTail();
191
- const packages = (s.packages as string[] | undefined) ?? [];
192
- const next = normalizeForceOrder(packages, tail);
193
- if (!next) return null;
194
- try {
195
- copyFileSync(SETTINGS, `${SETTINGS}.bak-force-order-${Date.now()}`);
196
- s.packages = next;
197
- writeFileSync(SETTINGS, JSON.stringify(s, null, 2), "utf8");
198
- } catch (e) {
199
- return `force 顺序自动修复失败:${(e as Error).message}`;
200
- }
201
- return `force 顺序已自动修复:${tail.filter((n) => next.includes(n)).join(" / ")} 移到 packages 末尾`;
202
- }
203
-
204
- /** 状态报告(命令与启动提示共用)。 */
205
486
  function report(): string[] {
206
- const s = readSettings();
207
- if (!s) return ["读不到 settings.json"];
208
- const tail = forceTail();
209
- const packages = (s.packages as string[]) ?? [];
210
487
  const lines: string[] = [];
211
- const fo = forceOrderIssues(packages, tail);
212
- lines.push(`force顺序 : ${fo.length ? fo[0] : "OK"}`);
213
- const { force: fe, fallback: fb } = classifyForcePackages(packages, tail);
214
- lines.push(`疑似force: ${fe.length ? fe.join(" / ") : "无(静态扫描)"}`);
215
- lines.push(`兼容兜底 : ${fb.length ? fb.join(" / ") : "无"}`);
216
- const cm = consistencyCheck((s.extensions as string[]) ?? [], packages);
217
- lines.push(`codemode : ${cm.length ? cm[0] : "单点一致"}`);
488
+ const lensSrc = safeRead(PI_LENS);
489
+ if (lensSrc === null) lines.push("pi-lens : 读不到 dist/index.js");
490
+ else {
491
+ const st = piLensState(lensSrc);
492
+ let label = `半打(A=${st.a1} B=${st.a2})`;
493
+ if (st.state === "upstream") label = `上游已修复 #4583(B=${st.a2 ? "已打" : "未打"};A 无需补丁)`;
494
+ else if (st.state === "both") label = "已打(A+B)";
495
+ else if (st.state === "none") label = "未打";
496
+ lines.push(`pi-lens : ${label}`);
497
+ }
498
+ const memSrc = safeRead(PI_MEMORY);
499
+ if (memSrc === null) lines.push("pi-memory: 读不到 index.ts");
500
+ else lines.push(`pi-memory: ${memSrc.includes(ME_MARK) ? "已打(exit summary 空行规范化)" : "未打"} · ${memSrc.includes(MEM_SECTION_MARK) ? "已打(section 优先)" : "未打(section 优先)"}`);
501
+ const tactSrc = safeRead(TACT);
502
+ lines.push(`tactician: ${tactSrc === null ? "读不到" : tactSrc.includes(TACT_MARK) ? "已打(section 优先)" : "未打(section 优先)"}`);
503
+ lines.push(`自建扩展: ${safeRead(SELF_EXT)?.includes(SELF_MARK) ? "自愈版" : "疑似被覆盖(跑 /patch-keeper fix)"}`);
504
+ const asar = checkAsar();
505
+ lines.push(`PiDeck : ${asar.detail}`);
506
+ for (const bp of BUILTIN_PATCHES) {
507
+ const st = (p: string): string => { const src = safeRead(p); return src === null ? "无" : src.includes(bp.needle) ? "已打" : "未打"; };
508
+ lines.push(`builtin : ${bp.name} 生效版=${st(bp.install)} 用户层=${st(bp.file)}`);
509
+ }
510
+ const fp = fingerprint();
511
+ const cm = fp ? consistencyCheck(fp.extensions, fp.packages) : [];
512
+ let cmLabel = "读不到 settings";
513
+ if (fp) cmLabel = cm.length ? cm[0] : "单点一致";
514
+ lines.push(`codemode : ${cmLabel}`);
515
+ const fo = fp ? forceOrderIssues(fp.packages) : [];
516
+ lines.push(`force序 : ${fp ? (fo.length ? fo[0] : "OK") : "读不到 settings"}`);
517
+ const fe = fp ? scanForcePackages(fp.packages) : [];
518
+ lines.push(`forceExt: ${fp ? (fe.length ? "疑似 " + fe.join(" / ") : "无(静态扫描)") : "读不到 settings"}`);
519
+ const fb = fp ? scanForceFallbacks(fp.packages) : [];
520
+ lines.push(`force兜底: ${fp ? (fb.length ? fb.join(" / ") : "无") : "读不到 settings"}`);
218
521
  return lines;
219
522
  }
220
523
 
221
- export default function patchKeeper(pi: ExtensionAPI): void {
222
- pi.on("session_start", async (_event, ctx: ExtensionContext) => {
223
- try {
224
- const s = readSettings();
225
- if (!s) return;
226
- const msgs: string[] = [];
227
- const fixed = fixForceOrder();
228
- if (fixed) msgs.push(fixed);
229
- else for (const x of forceOrderIssues((s.packages as string[]) ?? [], forceTail())) msgs.push(x);
230
- const drift = fingerprintDrift(fingerprint(s));
231
- if (drift.length) msgs.push(`环境指纹已变(${drift.join(" / ")})—— 此前关于工具/模型的结论可能过期`);
232
- const cm = consistencyCheck((s.extensions as string[]) ?? [], (s.packages as string[]) ?? []);
233
- for (const x of cm) msgs.push(x);
234
- for (const m of msgs) ctx.ui.notify("patch-keeper: " + m, "warning");
235
- } catch {
236
- /* 静默:检测不该影响会话 */
237
- }
238
- });
524
+ export default function (pi: ExtensionAPI) {
525
+ // 启动自愈:factory 是同步上下文,此时 pi-lens(rank 4)尚未加载。
526
+ let healNote: string | null = null;
527
+ try {
528
+ const r = healPiLens();
529
+ if (!r.ok) healNote = `patch-keeper: pi-lens 自愈失败 —— ${r.detail}`;
530
+ } catch (e) { healNote = `patch-keeper: pi-lens 自愈异常 —— ${(e as Error).message}`; }
531
+ try {
532
+ const r = healPiMemory();
533
+ if (!r.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory 自愈失败 —— ${r.detail}`;
534
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory 自愈异常 —— ${(e as Error).message}`; }
535
+ try {
536
+ const r = healMemorySection();
537
+ if (!r.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory section 自愈失败 —— ${r.detail}`;
538
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: pi-memory section 自愈异常 —— ${(e as Error).message}`; }
539
+ try {
540
+ const rt = healTactician();
541
+ if (!rt.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: tactician section 自愈失败 —— ${rt.detail}`;
542
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: tactician section 自愈异常 —— ${(e as Error).message}`; }
543
+ try {
544
+ const r = healSelfExtension();
545
+ if (!r.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: 自建扩展保护失败 —— ${r.detail}`;
546
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: 自建扩展保护异常 —— ${(e as Error).message}`; }
547
+ try {
548
+ const r = healMemoryFormat();
549
+ if (!r.ok) healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: 记忆格式自愈失败 —— ${r.detail}`;
550
+ } catch (e) { healNote = (healNote ? healNote + "\n" : "") + `patch-keeper: 记忆格式自愈异常 —— ${(e as Error).message}`; }
239
551
 
240
552
  pi.registerCommand("patch-keeper", {
241
- description: "查看 / 修复扩展加载顺序(force 型必须在 packages 末尾)",
553
+ description: "查看 / 自愈本机源码补丁状态(PiDeck asar ×3、pi-lens ×1、pi-memory ×1)",
242
554
  handler: async (args: string, ctx: ExtensionContext) => {
243
555
  const arg = (args || "").trim().toLowerCase();
244
556
  if (arg === "fix") {
245
- const r = fixForceOrder();
246
- ctx.ui.notify(r ? `patch-keeper: ${r}` : "patch-keeper: force 顺序已正确,无需修复", "info");
557
+ const r = healPiLens();
558
+ ctx.ui.notify(`pi-lens: ${r.detail}`, r.ok ? "info" : "error");
559
+
560
+ const r2 = healPiMemory();
561
+ ctx.ui.notify(`pi-memory: ${r2.detail}`, r2.ok ? "info" : "error");
562
+ const r3 = healMemorySection();
563
+ ctx.ui.notify(`pi-memory section: ${r3.detail}`, r3.ok ? "info" : "error");
564
+ const r4 = healTactician();
565
+ ctx.ui.notify(`tactician section: ${r4.detail}`, r4.ok ? "info" : "error");
566
+ const r5 = healSelfExtension();
567
+ ctx.ui.notify(`自建扩展: ${r5.detail}`, r5.ok ? "info" : "error");
568
+ const rForce = fixForceOrder();
569
+ if (rForce) ctx.ui.notify(`patch-keeper: ${rForce}`, "info");
570
+ const rb = restoreBuiltinPatches();
571
+ if (rb) ctx.ui.notify(`patch-keeper: ${rb}`, "warning");
247
572
  return;
248
573
  }
249
- ctx.ui.notify(`扩展加载顺序\n${report().join("\n")}`, "info");
574
+ const lines = report();
575
+ const tip = patchTip(lines);
576
+ ctx.ui.notify(`补丁状态\n${lines.join("\n")}${tip}`, "info");
250
577
  },
251
578
  });
252
- }
579
+
580
+ // 启动提示:只在「PiDeck 补丁缺失」时出声(pi-lens 已自动修好,不打扰)
581
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
582
+ try {
583
+ const asar = checkAsar();
584
+ const msgs: string[] = [];
585
+ const drift = fingerprintDrift();
586
+ const forceFix = fixForceOrder();
587
+ const fp = fingerprint();
588
+ const cm = fp ? consistencyCheck(fp.extensions, fp.packages) : [];
589
+ for (const x of cm) msgs.push("patch-keeper: " + x);
590
+ if (forceFix) msgs.push("patch-keeper: " + forceFix);
591
+ else if (fp) for (const x of forceOrderIssues(fp.packages)) msgs.push("patch-keeper: " + x);
592
+ if (fp) {
593
+ const fe = scanForcePackages(fp.packages);
594
+ const mid = fe.filter((n) => fp.packages.indexOf(n) < fp.packages.length - 1);
595
+ if (mid.length) msgs.push("patch-keeper: 疑似 force 型扩展不在末尾(其后的 section 可能被静默丢弃):" + mid.join(" / ") + " —— 核源码后移到 packages 末尾");
596
+ }
597
+ if (drift.length) msgs.push(`patch-keeper: 环境指纹已变(${drift.join(";")})—— 手册 / 上轮验证结论可能过期,按 08-台账核对纪律逐项重验`);
598
+ if (asar.ran && asar.missing.length) {
599
+ msgs.push(`patch-keeper: PiDeck 补丁缺失 —— ${asar.detail}`);
600
+ msgs.push(`关闭 PiDeck 后重跑补丁脚本(快照 ${SNAPSHOT_PATCH_DIR};或用其中的 launch-pideck.cmd 启动 PiDeck 时自动重打)`);
601
+ }
602
+ for (const bp of BUILTIN_PATCHES) {
603
+ const missing = [bp.install, bp.file].filter((p: string) => { const src = safeRead(p); return src !== null && !src.includes(bp.needle); });
604
+ if (missing.length) {
605
+ const where = missing.length === 2 ? "两处" : missing[0] === bp.install ? "安装目录(生效版)" : "用户层";
606
+ msgs.push(`patch-keeper: PiDeck 内置扩展补丁缺失(${bp.name},${where})—— 升级覆盖?从快照 03-PiDeck/builtin-extensions 恢复`);
607
+ }
608
+ }
609
+ {
610
+ const memSrc2 = safeRead(PI_MEMORY);
611
+ if (memSrc2 !== null && !memSrc2.includes(MEM_SECTION_MARK)) msgs.push("patch-keeper: pi-memory 未打 section 优先补丁 —— goal / plan / security 的 section 会被 force 吞掉,建议 /patch-keeper fix");
612
+ }
613
+ {
614
+ const tactSrc2 = safeRead(TACT);
615
+ if (tactSrc2 !== null && !tactSrc2.includes(TACT_MARK)) msgs.push("patch-keeper: tactician 未打 section 优先补丁 —— 会 force 吞掉其后的 section(goal / plan / security),建议 /patch-keeper fix");
616
+ }
617
+ const md = manualDrift();
618
+ if (md) msgs.push(`patch-keeper: ${md}`);
619
+ if (healNote) msgs.push(healNote);
620
+ for (const m of msgs) ctx.ui.notify(m, "warning");
621
+ } catch { /* 静默:检测不该影响会话 */ }
622
+ });
623
+
624
+ // 注入对齐(手册 §2 纪律区):注入的是宿主上次读取的文本,可能与磁盘版不同步。每轮比对一次,不一致时提示一次。
625
+ // 纪律:**绝不返回 systemPrompt** —— 返回即 forceSystemPrompt 覆盖式替换,会静默丢弃其后所有 section 的修改。
626
+ let lastPair = "";
627
+ pi.on("before_agent_start", async (event, ctx: ExtensionContext) => {
628
+ try {
629
+ const injected = String((event as { systemPrompt?: string } | undefined)?.systemPrompt ?? "");
630
+ const vi = manualVer(injected);
631
+ const disk = safeRead(MANUAL);
632
+ const vd = disk === null ? null : manualVer(disk);
633
+ if (!vi || !vd) return undefined;
634
+ const pair = vi + "|" + vd;
635
+ if (vi === vd || pair === lastPair) return undefined;
636
+ lastPair = pair;
637
+ ctx.ui.notify(`注入对齐:注入 v${vi} ≠ 磁盘 v${vd}(观察者 = 磁盘版)→ 判据:注入版不可作判断依据;动作:读回全文执行,重启后自愈`, "warning");
638
+ // 回灌四律②:用户已收到通知;模型也需要知道,否则「以磁盘版执行」停在用户侧。
639
+ try {
640
+ (pi as unknown as { sendMessage?: (m: unknown, o?: unknown) => void }).sendMessage?.(
641
+ {
642
+ customType: "patch-keeper",
643
+ content: `注入对齐:注入 v${vi} ≠ 磁盘 v${vd}(观察者 = 磁盘版)→ 注入版不可作判断依据;动作:读回 APPEND_SYSTEM.md 全文后执行,重启后自愈。`,
644
+ display: false,
645
+ },
646
+ { deliverAs: "nextTurn" },
647
+ );
648
+ } catch { /* 静默:回灌失败不影响会话 */ }
649
+ } catch { /* 静默:检测不该影响会话 */ }
650
+ return undefined;
651
+ });
652
+ }
package/package.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "pi-patch-keeper",
3
- "version": "1.0.12",
4
- "description": "Detect and fix pi extension load-order hazards: force-typed extensions silently swallow later system-prompt sections.",
3
+ "version": "1.1.1",
4
+ "description": "Startup self-healing for pi/pi-lens/pi-memory/PiDeck patches, plus force-typed extension order guard and status report.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "keywords": [
8
- "load-order",
8
+ "patch",
9
+ "self-healing",
9
10
  "pi",
10
11
  "pi-coding-agent",
11
12
  "pi-extension",
12
13
  "pi-package",
13
- "system-prompt"
14
+ "pideck"
14
15
  ],
15
16
  "pi": {
16
17
  "extensions": [