teamsmith 0.0.0-stage → 0.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 (243) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -2
  3. package/bin/team.mjs +59 -0
  4. package/install.sh +94 -0
  5. package/package.json +37 -4
  6. package/skills/teamsmith/CHANGELOG.md +747 -0
  7. package/skills/teamsmith/SKILL.md +312 -0
  8. package/skills/teamsmith/extension/team-bg.ts +399 -0
  9. package/skills/teamsmith/extension/team-inbox-watch.ts +1412 -0
  10. package/skills/teamsmith/extension/team-notify.ts +524 -0
  11. package/skills/teamsmith/references/agent-adapters.md +643 -0
  12. package/skills/teamsmith/references/config.md +477 -0
  13. package/skills/teamsmith/references/meeting.md +124 -0
  14. package/skills/teamsmith/references/memory.md +133 -0
  15. package/skills/teamsmith/references/migration.md +227 -0
  16. package/skills/teamsmith/references/openspec.md +208 -0
  17. package/skills/teamsmith/references/philosophy.md +95 -0
  18. package/skills/teamsmith/references/protocol.md +712 -0
  19. package/skills/teamsmith/references/troubleshooting.md +1384 -0
  20. package/skills/teamsmith/references/workflows.md +448 -0
  21. package/skills/teamsmith/scripts/lib/cmd-agents.sh +1709 -0
  22. package/skills/teamsmith/scripts/lib/cmd-bg.sh +284 -0
  23. package/skills/teamsmith/scripts/lib/cmd-bootstrap.sh +311 -0
  24. package/skills/teamsmith/scripts/lib/cmd-config.sh +1156 -0
  25. package/skills/teamsmith/scripts/lib/cmd-death.sh +562 -0
  26. package/skills/teamsmith/scripts/lib/cmd-docs.sh +149 -0
  27. package/skills/teamsmith/scripts/lib/cmd-draft.sh +124 -0
  28. package/skills/teamsmith/scripts/lib/cmd-init.sh +212 -0
  29. package/skills/teamsmith/scripts/lib/cmd-meeting.sh +904 -0
  30. package/skills/teamsmith/scripts/lib/cmd-outbox.sh +196 -0
  31. package/skills/teamsmith/scripts/lib/cmd-project.sh +642 -0
  32. package/skills/teamsmith/scripts/lib/cmd-review.sh +1393 -0
  33. package/skills/teamsmith/scripts/lib/cmd-status.sh +1399 -0
  34. package/skills/teamsmith/scripts/lib/cmd-update.sh +191 -0
  35. package/skills/teamsmith/scripts/lib/cmd-watch.sh +1681 -0
  36. package/skills/teamsmith/scripts/lib/common.sh +4964 -0
  37. package/skills/teamsmith/scripts/lib/draft-entry.sh +51 -0
  38. package/skills/teamsmith/scripts/lib/outbox.sh +2042 -0
  39. package/skills/teamsmith/scripts/lib/tmux-argv.sh +165 -0
  40. package/skills/teamsmith/scripts/monitor.mjs +616 -0
  41. package/skills/teamsmith/scripts/panel/README.md +192 -0
  42. package/skills/teamsmith/scripts/panel/build.sh +47 -0
  43. package/skills/teamsmith/scripts/panel/bun.lock +109 -0
  44. package/skills/teamsmith/scripts/panel/draft-send.sh +68 -0
  45. package/skills/teamsmith/scripts/panel/package.json +24 -0
  46. package/skills/teamsmith/scripts/panel/panel.js +388 -0
  47. package/skills/teamsmith/scripts/panel/src/App.tsx +2150 -0
  48. package/skills/teamsmith/scripts/panel/src/clipboard.ts +154 -0
  49. package/skills/teamsmith/scripts/panel/src/compose.ts +691 -0
  50. package/skills/teamsmith/scripts/panel/src/data.ts +555 -0
  51. package/skills/teamsmith/scripts/panel/src/format.ts +50 -0
  52. package/skills/teamsmith/scripts/panel/src/layout.ts +2562 -0
  53. package/skills/teamsmith/scripts/panel/src/main.tsx +894 -0
  54. package/skills/teamsmith/scripts/panel/src/markdown.ts +340 -0
  55. package/skills/teamsmith/scripts/panel/src/sanitize.ts +42 -0
  56. package/skills/teamsmith/scripts/panel/src/settings.ts +154 -0
  57. package/skills/teamsmith/scripts/panel/src/strings/en.ts +416 -0
  58. package/skills/teamsmith/scripts/panel/src/strings/index.ts +65 -0
  59. package/skills/teamsmith/scripts/panel/src/strings/types.ts +9 -0
  60. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +414 -0
  61. package/skills/teamsmith/scripts/panel/src/theme.ts +116 -0
  62. package/skills/teamsmith/scripts/panel/src/types.ts +652 -0
  63. package/skills/teamsmith/scripts/panel/src/width.ts +105 -0
  64. package/skills/teamsmith/scripts/panel/tsconfig.json +16 -0
  65. package/skills/teamsmith/scripts/shim/signal-gate +156 -0
  66. package/skills/teamsmith/scripts/shim/tmux +403 -0
  67. package/skills/teamsmith/scripts/team +143 -0
  68. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +147 -0
  69. package/skills/teamsmith/templates/BOARD.md.tmpl +18 -0
  70. package/skills/teamsmith/templates/DECISIONS.md.tmpl +22 -0
  71. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +25 -0
  72. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +84 -0
  73. package/skills/teamsmith/templates/ROADMAP.md.tmpl +29 -0
  74. package/skills/teamsmith/templates/config.sh.tmpl +106 -0
  75. package/skills/teamsmith/templates/memory-seed.md.tmpl +46 -0
  76. package/skills/teamsmith/templates/pm-prompt.md.tmpl +110 -0
  77. package/skills/teamsmith/templates/report.md.tmpl +36 -0
  78. package/skills/teamsmith/templates/task.md.tmpl +65 -0
  79. package/skills/teamsmith/templates/threads-README.md +17 -0
  80. package/skills/teamsmith/tests/checkout-shape-probe.sh +571 -0
  81. package/skills/teamsmith/tests/config-cli.sh +1562 -0
  82. package/skills/teamsmith/tests/container-tmux.sh +493 -0
  83. package/skills/teamsmith/tests/coverage-inventory.sh +173 -0
  84. package/skills/teamsmith/tests/death-cause.sh +564 -0
  85. package/skills/teamsmith/tests/delivery-truth.sh +1231 -0
  86. package/skills/teamsmith/tests/fake-tui.py +450 -0
  87. package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +60 -0
  88. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +139 -0
  89. package/skills/teamsmith/tests/fixtures/delivery-truth-real/mock-server.py +29 -0
  90. package/skills/teamsmith/tests/fixtures/delivery-truth-real/observe.ts +20 -0
  91. package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +79 -0
  92. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +175 -0
  93. package/skills/teamsmith/tests/fixtures/p55/flip-p49.sh +229 -0
  94. package/skills/teamsmith/tests/fixtures/p71-incident/README.md +22 -0
  95. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.seen +8 -0
  96. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.wake +9 -0
  97. package/skills/teamsmith/tests/fixtures/p71-incident/pm-nudges.wake +3 -0
  98. package/skills/teamsmith/tests/fixtures/signal-lint-cases.txt +40 -0
  99. package/skills/teamsmith/tests/flip-glue.sh +162 -0
  100. package/skills/teamsmith/tests/flip-m12-26c.sh +129 -0
  101. package/skills/teamsmith/tests/flip-m12.sh +185 -0
  102. package/skills/teamsmith/tests/flip-m16.sh +166 -0
  103. package/skills/teamsmith/tests/flip-m17.sh +204 -0
  104. package/skills/teamsmith/tests/flip-m33.sh +284 -0
  105. package/skills/teamsmith/tests/flip-m34.sh +96 -0
  106. package/skills/teamsmith/tests/flip-m37.sh +185 -0
  107. package/skills/teamsmith/tests/flip-m4.3.sh +375 -0
  108. package/skills/teamsmith/tests/flip-m43.sh +128 -0
  109. package/skills/teamsmith/tests/flip-m44.sh +262 -0
  110. package/skills/teamsmith/tests/flip-m45.sh +244 -0
  111. package/skills/teamsmith/tests/flip-m46.sh +238 -0
  112. package/skills/teamsmith/tests/flip-m48.sh +304 -0
  113. package/skills/teamsmith/tests/flip-m6.2.sh +205 -0
  114. package/skills/teamsmith/tests/flip-m6.3.sh +283 -0
  115. package/skills/teamsmith/tests/flip-m6.4.sh +267 -0
  116. package/skills/teamsmith/tests/flip-m6.5.sh +113 -0
  117. package/skills/teamsmith/tests/flip-m7.1.sh +135 -0
  118. package/skills/teamsmith/tests/flip-m7.2.sh +321 -0
  119. package/skills/teamsmith/tests/flip-p144.sh +112 -0
  120. package/skills/teamsmith/tests/flip-p156.sh +133 -0
  121. package/skills/teamsmith/tests/flip-p158.sh +301 -0
  122. package/skills/teamsmith/tests/flip-p160.sh +182 -0
  123. package/skills/teamsmith/tests/flip-p171.sh +249 -0
  124. package/skills/teamsmith/tests/flip-p18.1.sh +95 -0
  125. package/skills/teamsmith/tests/flip-p20.sh +286 -0
  126. package/skills/teamsmith/tests/flip-p201.sh +249 -0
  127. package/skills/teamsmith/tests/flip-p210.sh +239 -0
  128. package/skills/teamsmith/tests/flip-p211.sh +152 -0
  129. package/skills/teamsmith/tests/flip-p217.sh +288 -0
  130. package/skills/teamsmith/tests/flip-p22.sh +123 -0
  131. package/skills/teamsmith/tests/flip-p23.sh +239 -0
  132. package/skills/teamsmith/tests/flip-p25.sh +165 -0
  133. package/skills/teamsmith/tests/flip-p71.sh +184 -0
  134. package/skills/teamsmith/tests/flip-p72.sh +202 -0
  135. package/skills/teamsmith/tests/frames/README.md +176 -0
  136. package/skills/teamsmith/tests/frames/p78-conversation-rule-below-box.txt +6 -0
  137. package/skills/teamsmith/tests/frames/p78-cursor-mid-draft.txt +6 -0
  138. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor-line.txt +6 -0
  139. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor.txt +6 -0
  140. package/skills/teamsmith/tests/frames/p78-draft-rule-blank-region.txt +6 -0
  141. package/skills/teamsmith/tests/frames/p78-draft-rule-only.txt +5 -0
  142. package/skills/teamsmith/tests/frames/p78-spinner-row-below-cursor.txt +6 -0
  143. package/skills/teamsmith/tests/frames/p78-wider-rule-below-cursor.txt +6 -0
  144. package/skills/teamsmith/tests/frames/p86-f1-mixed-width-disjoint-box.txt +8 -0
  145. package/skills/teamsmith/tests/frames/p86-f1-narrower-width-disjoint-box.txt +8 -0
  146. package/skills/teamsmith/tests/frames/p86-f1-spinner-top-disjoint-box.txt +8 -0
  147. package/skills/teamsmith/tests/frames/pi-0.85.1-update-banner.txt +30 -0
  148. package/skills/teamsmith/tests/frames/pi-0.87.0-draft-half-sentence.txt +30 -0
  149. package/skills/teamsmith/tests/frames/pi-0.87.0-empty-box.txt +30 -0
  150. package/skills/teamsmith/tests/frames/pi-0.87.0-one-line-draft.txt +30 -0
  151. package/skills/teamsmith/tests/frames/pi-0.87.0-project-trust-prompt.txt +30 -0
  152. package/skills/teamsmith/tests/frames/pi-0.99.2-empty-editor.txt +32 -0
  153. package/skills/teamsmith/tests/frames/pi-0.99.2-human-draft.txt +32 -0
  154. package/skills/teamsmith/tests/frames/pi-1.0.0-git-error-in-box.txt +32 -0
  155. package/skills/teamsmith/tests/gate-guard.sh +112 -0
  156. package/skills/teamsmith/tests/guard-matrix.sh +233 -0
  157. package/skills/teamsmith/tests/install-shape.sh +731 -0
  158. package/skills/teamsmith/tests/ledger-ban.sh +612 -0
  159. package/skills/teamsmith/tests/lib/box-judge.sh +68 -0
  160. package/skills/teamsmith/tests/lib/checkout-shape.sh +77 -0
  161. package/skills/teamsmith/tests/lib/loop-scan.awk +114 -0
  162. package/skills/teamsmith/tests/lib/pty-wait.sh +676 -0
  163. package/skills/teamsmith/tests/lib/section-guard.sh +855 -0
  164. package/skills/teamsmith/tests/lib/shell-lex.pl +261 -0
  165. package/skills/teamsmith/tests/lib/tmp-root.sh +528 -0
  166. package/skills/teamsmith/tests/lib/tmux-cap.sh +35 -0
  167. package/skills/teamsmith/tests/lib/tmux-iso-call-probe.sh +81 -0
  168. package/skills/teamsmith/tests/lib/tmux-iso-probe.sh +46 -0
  169. package/skills/teamsmith/tests/lib/tmux-iso.sh +381 -0
  170. package/skills/teamsmith/tests/load-experiment.sh +290 -0
  171. package/skills/teamsmith/tests/loop-inventory.tsv +84 -0
  172. package/skills/teamsmith/tests/panel-b2-slow-stub.sh +19 -0
  173. package/skills/teamsmith/tests/panel-b2.sh +1183 -0
  174. package/skills/teamsmith/tests/panel-b3-pty-mouse.py +240 -0
  175. package/skills/teamsmith/tests/panel-b3-pty-tmux-mouse.py +138 -0
  176. package/skills/teamsmith/tests/panel-b3-stub.sh +279 -0
  177. package/skills/teamsmith/tests/panel-b3.sh +1301 -0
  178. package/skills/teamsmith/tests/panel-choices.sh +572 -0
  179. package/skills/teamsmith/tests/panel-clipboard-model.ts +187 -0
  180. package/skills/teamsmith/tests/panel-compose-model.ts +290 -0
  181. package/skills/teamsmith/tests/panel-contrast.mjs +81 -0
  182. package/skills/teamsmith/tests/panel-cpu-premise.sh +173 -0
  183. package/skills/teamsmith/tests/panel-cpu.sh +391 -0
  184. package/skills/teamsmith/tests/panel-flip-m54.sh +207 -0
  185. package/skills/teamsmith/tests/panel-flip-p123.sh +278 -0
  186. package/skills/teamsmith/tests/panel-flip-p125.sh +318 -0
  187. package/skills/teamsmith/tests/panel-flip-p128.sh +259 -0
  188. package/skills/teamsmith/tests/panel-keyprobe-pty.py +99 -0
  189. package/skills/teamsmith/tests/panel-keyprobe-stub.sh +41 -0
  190. package/skills/teamsmith/tests/panel-keyprobe.sh +82 -0
  191. package/skills/teamsmith/tests/panel-keyprobe.tsx +116 -0
  192. package/skills/teamsmith/tests/panel-knobs.sh +83 -0
  193. package/skills/teamsmith/tests/panel-p21.sh +2181 -0
  194. package/skills/teamsmith/tests/panel-snapshots.sh +802 -0
  195. package/skills/teamsmith/tests/panel-strings.mjs +195 -0
  196. package/skills/teamsmith/tests/perf.sh +740 -0
  197. package/skills/teamsmith/tests/pm-box-real.sh +350 -0
  198. package/skills/teamsmith/tests/pulse-nudge-key.sh +563 -0
  199. package/skills/teamsmith/tests/routes.sh +1652 -0
  200. package/skills/teamsmith/tests/section-budgets.tsv +150 -0
  201. package/skills/teamsmith/tests/section-guard.sh +231 -0
  202. package/skills/teamsmith/tests/section-needs-audit.sh +94 -0
  203. package/skills/teamsmith/tests/section-paths.tsv +142 -0
  204. package/skills/teamsmith/tests/section-select.sh +648 -0
  205. package/skills/teamsmith/tests/signal-gate.sh +366 -0
  206. package/skills/teamsmith/tests/signal-lint-legacy.txt +14 -0
  207. package/skills/teamsmith/tests/signal-lint.pl +416 -0
  208. package/skills/teamsmith/tests/skill-load.mjs +65 -0
  209. package/skills/teamsmith/tests/smoke.sh +19599 -0
  210. package/skills/teamsmith/tests/snapshots/zh-dark-120-detail.txt +32 -0
  211. package/skills/teamsmith/tests/snapshots/zh-dark-120-p4.txt +32 -0
  212. package/skills/teamsmith/tests/snapshots/zh-dark-120.txt +32 -0
  213. package/skills/teamsmith/tests/snapshots/zh-dark-160-p4.txt +32 -0
  214. package/skills/teamsmith/tests/snapshots/zh-dark-160.txt +32 -0
  215. package/skills/teamsmith/tests/snapshots/zh-dark-59-detail.txt +32 -0
  216. package/skills/teamsmith/tests/snapshots/zh-dark-59-p4.txt +32 -0
  217. package/skills/teamsmith/tests/snapshots/zh-dark-59.txt +32 -0
  218. package/skills/teamsmith/tests/snapshots/zh-dark-99-p4.txt +32 -0
  219. package/skills/teamsmith/tests/snapshots/zh-dark-99.txt +32 -0
  220. package/skills/teamsmith/tests/snapshots/zh-light-120-detail.txt +32 -0
  221. package/skills/teamsmith/tests/snapshots/zh-light-120-p4.txt +32 -0
  222. package/skills/teamsmith/tests/snapshots/zh-light-120.txt +32 -0
  223. package/skills/teamsmith/tests/snapshots/zh-light-160-p4.txt +32 -0
  224. package/skills/teamsmith/tests/snapshots/zh-light-160.txt +32 -0
  225. package/skills/teamsmith/tests/snapshots/zh-light-59-detail.txt +32 -0
  226. package/skills/teamsmith/tests/snapshots/zh-light-59-p4.txt +32 -0
  227. package/skills/teamsmith/tests/snapshots/zh-light-59.txt +32 -0
  228. package/skills/teamsmith/tests/snapshots/zh-light-99-p4.txt +32 -0
  229. package/skills/teamsmith/tests/snapshots/zh-light-99.txt +32 -0
  230. package/skills/teamsmith/tests/spec-ledger-refs.tsv +78 -0
  231. package/skills/teamsmith/tests/spec-refs.sh +826 -0
  232. package/skills/teamsmith/tests/task-header-model.sh +267 -0
  233. package/skills/teamsmith/tests/team-bg-flip.sh +239 -0
  234. package/skills/teamsmith/tests/team-bg-harness.mjs +392 -0
  235. package/skills/teamsmith/tests/team-bg-stop.sh +434 -0
  236. package/skills/teamsmith/tests/team-inbox-watch-flip.sh +191 -0
  237. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +1559 -0
  238. package/skills/teamsmith/tests/tmp-hygiene.sh +1190 -0
  239. package/skills/teamsmith/tests/tmux-lint-legacy.txt +31 -0
  240. package/skills/teamsmith/tests/tmux-lint.pl +604 -0
  241. package/skills/teamsmith-init/SKILL.md +100 -0
  242. package/skills/teamsmith-init/references/bootstrap.md +74 -0
  243. package/skills/teamsmith-init/templates/bootstrap-prompt.md.tmpl +46 -0
@@ -0,0 +1,1412 @@
1
+ /**
2
+ * teamsmith · inbox-watch 扩展 — 投递换道:收件箱监视唤醒取代输入框粘贴(M30)
3
+ *
4
+ * 为什么换道:自动化消息以前只有一条投递路径 —— `tmux send-keys -l` + `Enter` 直接打进 pi 的
5
+ * 输入框。五次 draft-race 事故(D20 / M17 / M24 / …)证明「人的草稿 vs 我们刚贴进去的 payload」
6
+ * 在真实 TUI 上判不准:一个错误的 ENTER 就把人写了一半的话送出去。用户拍板:不再修框检测。
7
+ *
8
+ * pi 通道现在的形状(完全不碰输入框):
9
+ * 1. 发送方(outbox.sh)把消息写进 **durable 收件箱** `docs/team/inbox/<name>.md`(唯一真相);
10
+ * 2. 再往本项目 `state/inbox-watch/<key>.wake` 追加**一行指针**(kind / from / inbox / 截断预览);
11
+ * 3. 本扩展 `fs.watch` 那个目录,读到新行就
12
+ * `pi.sendMessage({customType:'team-inbox'}, …, {triggerTurn:true, deliverAs:'followUp'})`
13
+ * —— 消息进会话队列(agent 空闲时立刻触发一轮),输入框一个键都不碰。
14
+ *
15
+ * 就绪注册(发送方据此判定「目标是 pi 且有监视」):`state/inbox-watch/<key>.reg` 里写
16
+ * target / inbox / pid / cwd / started / heartbeat;心跳每 HEARTBEAT_MS 刷新。`team_inbox_watch_route`
17
+ * 只认「pid 活着 + cwd 在本项目内」的注册(心跳是 cwd 读不出来时的兜底判据,也是排障时间线)。
18
+ *
19
+ * 投递纪律(照 E8 §5 与 team-bg 的实测教训):
20
+ * - 一个新行 = 一次唤醒;同一拍到的多行**合并成一条**(merge window),不按行刷屏;
21
+ * - 唤醒消息只带**一行指针 + 截断预览**,不带 payload 全文(全文在收件箱;防注入习惯不变);
22
+ * - session 启动时以 spool 当前大小为基线:**历史行不叫醒任何人**(backlog 是 pulse 的活),
23
+ * 启动**之后**写入的行才唤醒 —— 关掉这个窗口的原语就是 M30 验收里那条「启动前的行不唤醒」;
24
+ * - spool 有上限(TEAM_INBOX_WATCH_MAX_BYTES,默认 128KB):超了截头留尾(尾部信号不丢);
25
+ * - **spool 变小(size < offset)= 外部截断/重写**(M43:仓内写路径只有 `>>` 追加,变小一定是
26
+ * 外部力量)。旧行为是静默 `offset = 0`、下一拍把整个 spool 从 0 重读 —— 2026-09-19 就是这条
27
+ * 把同一份 42 行叫了两遍、`total` 灌水 84。现在的语义(投递保真三条):
28
+ * 1. **shrink 必记账本**(`spool shrink …` 一行),不再是静默重置;
29
+ * 2. **去重**:整行元组进过去重记忆 —— P81 起这份记忆是 `state/inbox-watch/<key>.deliver`
30
+ * **投递日志**(append-only,`read` → `intent` → `sent`/`failed`),进程内存绝不是权威;
31
+ * `<key>.seen` 只被一次性导入(此后删掉/清空它不改变任何投递决定),已投递的行一律不再投;
32
+ * 3. **有界重放**:shrink 后的 rescan 对「真新」行只投最近 TEAM_INBOX_WATCH_REPLAY_MAX 条
33
+ * (默认 20),更早的跳过并在唤醒文本与账本里说明;全去重压掉时**不唤醒**(没什么好说的),
34
+ * 账本记 `rescan … deliver=0`。
35
+ * `seen`(账本 `total=`)只随**真实投递**增长 —— 重放/去重跳过都不计数。
36
+ *
37
+ * 生命周期(Pi 文档的硬约束):factory 里不起任何后台资源;watch / 定时器 / 注册文件都在
38
+ * session_start 里建、session_shutdown 里清(并删掉自己的注册文件 —— 不然发送方会一直以为
39
+ * 「有个活着的监视器」而不再走粘贴路径)。任何失败都只写自己的账本(state/inbox-watch.log),
40
+ * 绝不抛进会话。
41
+ *
42
+ * 降级可见(M46):跳过 setup 不再只写日志 —— 本项目 state/inbox-watch/<key>.skip 记下「哪个 target、
43
+ * 为什么跳过」(reason=session-mismatch / …),doctor / status / digest / 面板据此报「本项目 PM 没有
44
+ * inbox-watch 注册 → 通知走输入框慢路径」;成功注册会删掉同 target 的旧记录。state 目录一律锚定
45
+ * cwd 推导出的项目根:继承来的 TEAM_STATE_DIR / TEAM_CONFIG_FILE 若指向**另一个 teamsmith 项目**,
46
+ * 一律拒绝并记账本(绝不把别人家的 state / 会话名当自己的,M40 原则的文件面)。
47
+ *
48
+ * 降级通道(M53):`fs.watch` 注册失败(典型:宿主 inotify 配额耗尽 ENOSPC)不再是一行无语境的日志 ——
49
+ * 账本写唯一形状 `watch unavailable: errno=… watches=<used|unknown>/<max> poll_ms=… fallback=polling
50
+ * [forced=1]`,并落一条耐久记录 `<key>.degraded`(pid + cwd 可判活,成功注册或干净退出删掉)。
51
+ * `.reg` 在失败时保留:路由(发送方)只认 `.reg`,降级绝不把消息推回输入框粘贴路径;轮询计时器
52
+ * 无条件安装 —— 兜底是契约,不是失败路径的补丁(夹具 S22/S23 证明它)。`watches` 只报可证明完整的
53
+ * 同 UID 视图(容器里 /proc 是嵌套 PID 命名空间 → `unknown`,绝不把局部计数当总量)。
54
+ *
55
+ * P81 · 投递日志(`<key>.deliver`,唯一 durable 去重权威;事故:一条 nudge 被叫醒两次,而文件无法回答
56
+ * 「到底投过没有」):
57
+ * - 顺序是契约:`read`(点名行身份 + 唤醒材料 + 偏移/大小/头指纹)→ `intent`(一批)→ **发送** →
58
+ * `sent`/`failed`;`intent` 没写成**绝不许发** —— 写不进去就 `deliver blocked`,行保持未读等下一拍;
59
+ * - 重启后按日志判三态(绝不靠内存):`read` 无 `intent` → **恰好一次**恢复(`recovery`);
60
+ * `intent` 无 `sent`/`failed`(含半截尾记录)→ `inflight assumed`,**永不重投**;`sent` → 永不;
61
+ * `failed` → 每拍至多重试一次、且不得越过新鲜度地平线;
62
+ * - 日志有界(`TEAM_INBOX_WATCH_JOURNAL_MAX`,默认 1024):越界压缩并写 `floor=`;比地板更早的身份
63
+ * 日志已不能证明「没投过」→ `unprovable`,永不唤醒(fail-safe,不是 fail-open);
64
+ * - 唤醒文本点名源行:`#<seq>` + 绝对发送时间 + 每行的源时间与身份(发送方写进 spool 第 6 字段的
65
+ * `id=<outbox 条目名>`,老行用整行 sha1 摘要)—— 收件方只凭 durable 文件就能分辨「两条」与「一条两次」。
66
+ *
67
+ * 作用域:只认本项目(git 主工作树)的 state 目录 —— 注册与 spool 是**发送方与会话之间的接口**
68
+ * (发送方是 CLI,它的 TEAM_STATE_DIR 在主工作树),所以它们必须待在共享根,不能跟着会话的 worktree 走。
69
+ * 会话本地的产物(作业日志/账户)不归这里管(那是 team-bg 的活,它跟会话自己的工作树走)。只服务
70
+ * dispatch/PM 启动链 `-e` 注入的团队会话 —— 用户自己的 pi 会话没有它。
71
+ */
72
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
73
+ import { execFileSync } from 'node:child_process'
74
+ import { createHash } from 'node:crypto'
75
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
76
+ import { basename, dirname, join, resolve } from 'node:path'
77
+
78
+ const DEFAULT_PREVIEW = 160 // 预览截断(字符):唤醒消息只带一行指针,不带全文
79
+ const DEFAULT_MAX_BYTES = 128 * 1024 // spool 上限
80
+ const DEFAULT_POLL_MS = 5000 // fs.watch 的兜底轮询(错过 inotify 事件时仍能醒来)
81
+ const DEFAULT_HEARTBEAT_MS = 5000 // 注册心跳
82
+ const DEFAULT_REPLAY_MAX = 20 // shrink 后 rescan 的「真新」行投递上限(更早的跳过并说明)
83
+ const DEFAULT_SEEN_MAX = 512 // 老 <key>.seen 的一次性导入上限(P81 起日志是唯一记忆)
84
+ const DEFAULT_JOURNAL_MAX = 1024 // P81:投递日志的记录上限(越过 → 压缩 + `floor=`)
85
+ const HEAD_BYTES = 256 // 头部指纹前缀(P28/B2:回退时比较「开头有没有被改写」)
86
+ const DEFAULT_CLAMP_BYTES = 64 // 头部不变、回退 ≤ 此字节数 = 我们自己的 offset 错了(修复,不是重写)
87
+ const DEFAULT_STALE_SEC = 900 // 行年龄超过此秒数 = 过期:只计数、不唤醒(P28/B3/R3)
88
+ const MERGE_MS = 150 // 同一拍到的多行合并成一条唤醒
89
+ const MAX_LISTED = 5 // 一条唤醒消息里最多列几条
90
+
91
+ function envNum(name: string, fallback: number, min: number): number {
92
+ const n = Number(process.env[name] ?? NaN)
93
+ return Number.isFinite(n) && n >= min ? n : fallback
94
+ }
95
+
96
+ function previewLimit(): number { return envNum('TEAM_INBOX_WATCH_PREVIEW', DEFAULT_PREVIEW, 16) }
97
+ function maxBytes(): number { return envNum('TEAM_INBOX_WATCH_MAX_BYTES', DEFAULT_MAX_BYTES, 1024) }
98
+ function pollMs(): number { return envNum('TEAM_INBOX_WATCH_POLL_MS', DEFAULT_POLL_MS, 100) }
99
+ function heartbeatMs(): number { return envNum('TEAM_INBOX_WATCH_HEARTBEAT_MS', DEFAULT_HEARTBEAT_MS, 100) }
100
+ function replayMax(): number { return envNum('TEAM_INBOX_WATCH_REPLAY_MAX', DEFAULT_REPLAY_MAX, 1) }
101
+ function seenMax(): number { return envNum('TEAM_INBOX_WATCH_SEEN_MAX', DEFAULT_SEEN_MAX, 32) }
102
+ function journalMax(): number { return envNum('TEAM_INBOX_WATCH_JOURNAL_MAX', DEFAULT_JOURNAL_MAX, 16) }
103
+ function clampBytes(): number { return Math.min(1024 * 1024, envNum('TEAM_INBOX_WATCH_CLAMP_BYTES', DEFAULT_CLAMP_BYTES, 1)) }
104
+ function staleSec(): number { return envNum('TEAM_INBOX_WATCH_STALE_SEC', DEFAULT_STALE_SEC, 1) }
105
+
106
+ /**
107
+ * 定位团队根(主工作树):M40 —— **cwd 推导为准**(与 team CLI 同一条原则)。
108
+ * TEAM_ROOT 只在①与推导结果一致,或②完全推导不出来且它指向一个真项目时被信任;
109
+ * 不一致时按 cwd 走,并往 state/inbox-watch.log 记一行 —— 绝不静默服务别的项目
110
+ * (事故②:cwd=other_project 的进程却渲染/读写 this-project)。
111
+ * 推导顺序:git 主工作树(账本所在地;worktree 里的 `.pi/team/config.sh` 是副本)→ 向上找 config.sh。
112
+ */
113
+ function findRoot(cwd: string): string {
114
+ const envRoot = process.env.TEAM_ROOT ? resolve(process.env.TEAM_ROOT) : ''
115
+ let derived = ''
116
+ try {
117
+ const out = execFileSync('git', ['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'],
118
+ { encoding: 'utf8', timeout: 5000 })
119
+ const main = dirname(out.trim())
120
+ if (existsSync(join(main, '.pi/team/config.sh'))) derived = main
121
+ } catch {
122
+ /* 不是 git 仓库 / 没有 git */
123
+ }
124
+ if (!derived) {
125
+ let dir = resolve(cwd)
126
+ for (;;) {
127
+ if (existsSync(join(dir, '.pi/team/config.sh'))) { derived = dir; break }
128
+ const parent = dirname(dir)
129
+ if (parent === dir) break
130
+ dir = parent
131
+ }
132
+ }
133
+ if (envRoot && envRoot !== derived) {
134
+ if (derived) {
135
+ appendLedger(derived, `TEAM_IDENTITY_CONFLICT inherited TEAM_ROOT=${envRoot} ≠ cwd-derived=${derived};按 cwd 走`)
136
+ return derived
137
+ }
138
+ if (existsSync(join(envRoot, '.pi/team/config.sh'))) {
139
+ appendLedger(envRoot, `TEAM_IDENTITY_CONFLICT cwd(${cwd})推导不出项目,回退到 TEAM_ROOT=${envRoot}`)
140
+ return envRoot
141
+ }
142
+ return ''
143
+ }
144
+ return derived || envRoot
145
+ }
146
+
147
+ /** M46:这个 state 目录属于**另一个 teamsmith 项目**吗(<other>/.pi/team/config.sh 是别的根)?
148
+ * 是 → 返回那个项目根(调用方拒绝该路径)。不是(本项目内 / 项目外的普通目录)= null。
149
+ * 为什么只拒「别的项目」而不是「项目外的一切」:TEAM_STATE_DIR 是显式旋钮(夹具把它指到
150
+ * /tmp/xxx 搬家队列 —— 规格 scenario「TEAM_STATE_DIR moves the queue」);但**继承来的**旋钮
151
+ * 若落在别的项目的 state 上,就是把别人家当自己家(M40 事故②的形状:cwd=other_project 的进程
152
+ * 读写 this-project 的 state)——那条绝不许静默通过。 */
153
+ function foreignProjectRoot(dir: string, root: string): string | null {
154
+ const norm = (p: string): string => { try { return realpathSync(p) } catch { return resolve(p) } }
155
+ const r = norm(dir)
156
+ const rr = norm(root)
157
+ if (r === rr || r.startsWith(rr.endsWith('/') ? rr : `${rr}/`)) return null // 本项目内(含根本身)
158
+ let d = r
159
+ for (;;) {
160
+ if (existsSync(join(d, '.pi/team/config.sh'))) return norm(d) === rr ? null : d
161
+ const parent = dirname(d)
162
+ if (parent === d) return null
163
+ d = parent
164
+ }
165
+ }
166
+
167
+ /** 本项目的 state 目录:锚定 cwd 推导出的根。继承的 TEAM_STATE_DIR 指向别的项目的 state 时
168
+ * 一律改用 <root>/.pi/team/state(并记账本,见 noteStateDirConflict);其它显式值照用。 */
169
+ function stateDir(root: string): string {
170
+ const envDir = (process.env.TEAM_STATE_DIR || '').trim()
171
+ if (envDir) {
172
+ const abs = resolve(envDir)
173
+ if (!foreignProjectRoot(abs, root)) return abs
174
+ }
175
+ return join(root, '.pi/team/state')
176
+ }
177
+
178
+ /** 被拒绝的继承指针(TEAM_STATE_DIR / TEAM_CONFIG_FILE)要留痕(写进**本项目**的账本;绝不静默)。 */
179
+ function noteIdentityFileConflicts(root: string): void {
180
+ const stateEnv = (process.env.TEAM_STATE_DIR || '').trim()
181
+ if (stateEnv) {
182
+ const abs = resolve(stateEnv)
183
+ const foreign = foreignProjectRoot(abs, root)
184
+ if (foreign) {
185
+ appendLedger(root,
186
+ `TEAM_IDENTITY_CONFLICT inherited TEAM_STATE_DIR=${abs}(属于别的项目 ${foreign})≠ cwd-derived=${root};按 cwd 走`)
187
+ }
188
+ }
189
+ const cfgEnv = (process.env.TEAM_CONFIG_FILE || '').trim()
190
+ if (cfgEnv) {
191
+ const abs = resolve(cfgEnv)
192
+ const foreign = foreignProjectRoot(abs, root)
193
+ if (foreign && abs !== join(root, '.pi/team/config.sh')) {
194
+ appendLedger(root,
195
+ `TEAM_IDENTITY_CONFLICT inherited TEAM_CONFIG_FILE=${abs}(属于别的项目 ${foreign})≠ cwd-derived=${root};按 cwd 走`)
196
+ }
197
+ }
198
+ }
199
+
200
+ function watchDir(root: string): string {
201
+ return join(stateDir(root), 'inbox-watch')
202
+ }
203
+
204
+ /** 项目配置文件的定位(M46):TEAM_CONFIG_FILE 只在**不指向别的项目**时被信任 ——
205
+ * 与 state 目录同一条规则(继承的文件指针也不许把别的项目的会话名/文档目录当成本项目的)。 */
206
+ function configFile(root: string): string {
207
+ const def = join(root, '.pi/team/config.sh')
208
+ const envFile = (process.env.TEAM_CONFIG_FILE || '').trim()
209
+ if (envFile) {
210
+ const abs = resolve(envFile)
211
+ if (abs === def || !foreignProjectRoot(abs, root)) return abs
212
+ }
213
+ return def
214
+ }
215
+
216
+ /** 从 <root>/.pi/team/config.sh 读 TEAM_DOCS_DIR(只解析需要的扁平 KEY=VALUE,不 source)。 */
217
+ function docsDir(root: string): string {
218
+ try {
219
+ const file = configFile(root)
220
+ const text = readFileSync(file, 'utf8')
221
+ const m = /^\s*TEAM_DOCS_DIR\s*=\s*(.*?)\s*$/m.exec(text)
222
+ if (!m) return 'docs/team'
223
+ const raw = m[1].replace(/\s+#.*$/, '').trim()
224
+ const v = (raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'")) ? raw.slice(1, -1) : raw
225
+ return v.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g, (_s, name: string) => process.env[name] ?? '') || 'docs/team'
226
+ } catch {
227
+ return 'docs/team'
228
+ }
229
+ }
230
+
231
+ function cfgSession(root: string): string {
232
+ try {
233
+ const file = configFile(root)
234
+ const m = /^\s*TEAM_SESSION\s*=\s*(.*?)\s*$/m.exec(readFileSync(file, 'utf8'))
235
+ if (!m) return 'team'
236
+ const raw = m[1].replace(/\s+#.*$/, '').trim()
237
+ return ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'")) ? raw.slice(1, -1) : raw) || 'team'
238
+ } catch {
239
+ return 'team'
240
+ }
241
+ }
242
+
243
+ function pmWindow(root: string): string {
244
+ try {
245
+ const file = configFile(root)
246
+ const m = /^\s*TEAM_PM_WINDOW\s*=\s*(.*?)\s*$/m.exec(readFileSync(file, 'utf8'))
247
+ if (!m) return 'pm'
248
+ const raw = m[1].replace(/\s+#.*$/, '').trim()
249
+ return ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'")) ? raw.slice(1, -1) : raw) || 'pm'
250
+ } catch {
251
+ return 'pm'
252
+ }
253
+ }
254
+
255
+ /** target(`<session>:<window>`)→ spool/注册文件名用的 key:可读前缀 + 32 位短哈希(两个不同 target 不撞名)。
256
+ * 发送侧只从**注册文件名**读 key(`team_inbox_watch_route` 返回的第 1 段),所以两边不需要共享哈希实现。 */
257
+ function targetKey(target: string): string {
258
+ const slug = target.replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 40) || 'target'
259
+ let h = 0
260
+ for (let i = 0; i < target.length; i++) h = (Math.imul(h, 31) + target.charCodeAt(i)) >>> 0
261
+ return `${slug}-${h.toString(16).padStart(8, '0')}`
262
+ }
263
+
264
+ /** 本会话在 tmux 里的 `session:window`(env 覆盖优先:headless 与夹具用它)。
265
+ * 注意(M46):覆盖只改「从哪里读 target」,**不改**「哪个会话才是这个项目的」——
266
+ * session_start 的会话检查对覆盖值同样生效(外来会话不许接管本项目的投递)。 */
267
+ function resolveTarget(): { target: string; session: string; window: string } | null {
268
+ const override = (process.env.TEAM_INBOX_WATCH_TARGET || '').trim()
269
+ if (override) {
270
+ const idx = override.indexOf(':')
271
+ if (idx > 0) return { target: override, session: override.slice(0, idx), window: override.slice(idx + 1) }
272
+ return null
273
+ }
274
+ const pane = process.env.TMUX_PANE
275
+ if (!pane) return null
276
+ try {
277
+ const out = execFileSync('tmux', ['display-message', '-p', '-t', pane, '#{session_name}:#{window_name}'],
278
+ { encoding: 'utf8', timeout: 5000 }).trim()
279
+ const idx = out.indexOf(':')
280
+ if (idx <= 0) return null
281
+ return { target: out, session: out.slice(0, idx), window: out.slice(idx + 1) }
282
+ } catch {
283
+ return null
284
+ }
285
+ }
286
+
287
+ /** 收件人 = PM 窗口 → `pm`,其它窗口 → 窗口名(与 `team say`/`team notify` 的收件箱名一致)。 */
288
+ function inboxName(window: string, root: string): string {
289
+ return window === pmWindow(root) ? 'pm' : window
290
+ }
291
+
292
+ function oneLine(raw: string, max: number): string {
293
+ const flat = raw.replace(/\s+/g, ' ').trim()
294
+ return flat.length > max ? `${flat.slice(0, Math.max(1, max - 1))}…` : flat
295
+ }
296
+
297
+ function appendLedger(root: string, line: string): void {
298
+ try {
299
+ mkdirSync(stateDir(root), { recursive: true })
300
+ appendFileSync(join(stateDir(root), 'inbox-watch.log'), `${new Date().toISOString()} ${line}\n`)
301
+ } catch {
302
+ /* 账本绝不能影响会话 */
303
+ }
304
+ }
305
+
306
+ /** M46 · 降级痕迹:跳过/失败不再只活在日志里 —— 在**本项目** state/inbox-watch/ 里写
307
+ * `<key>.skip`(与 .reg 同一种 KEY=VALUE 格式,发送侧与 doctor/status/panel 都读它)。
308
+ * 为什么需要它:「本项目 PM 没有注册」有两种原因(会话名不符 vs 扩展没加载),只有扩展自己
309
+ * 知道前者;没有这份记录,检查方只能给一句笼统的「未注册」。字段:target/session/window/expect/
310
+ * reason/detail/pid/cwd/ts/heartbeat。成功注册时同 target 的旧记录会被删掉(不再骗人)。 */
311
+ function writeSkipRecord(root: string, target: string, info: {
312
+ session?: string; window?: string; expect?: string; inbox?: string; reason: string; detail: string
313
+ }): void {
314
+ const dir = watchDir(root)
315
+ const key = targetKey(target)
316
+ try { mkdirSync(dir, { recursive: true }) } catch { return }
317
+ const body = [
318
+ 'version=1',
319
+ `target=${target}`,
320
+ `key=${key}`,
321
+ `session=${info.session ?? '-'}`,
322
+ `window=${info.window ?? '-'}`,
323
+ `expect=${info.expect ?? '-'}`,
324
+ `inbox=${info.inbox ?? '-'}`,
325
+ `reason=${info.reason}`,
326
+ `detail=${info.detail}`,
327
+ `pid=${process.pid}`,
328
+ `cwd=${root}`,
329
+ `ts=${new Date().toISOString()}`,
330
+ `heartbeat=${Math.floor(Date.now() / 1000)}`,
331
+ '',
332
+ ].join('\n')
333
+ try {
334
+ const tmp = join(dir, `${key}.skip.tmp-${process.pid}`)
335
+ writeFileSync(tmp, body)
336
+ renameSync(tmp, join(dir, `${key}.skip`))
337
+ } catch {
338
+ /* 痕迹写不进去也不能影响会话;账本那一行仍然有 */
339
+ }
340
+ }
341
+
342
+ /** 成功注册 = 这个 window 在本项目不再降级:删掉自己或上一次进程留下的 .skip。
343
+ * 匹配两条:① target 逐字相同;② 同一个 window 的 session-mismatch 记录 —— 我们刚刚
344
+ * 用**匹配配置的会话**注册成功,那条「会话名不符」对同一个 window 已经不成立了(与 CLI 侧
345
+ * 读记录时的 window 匹配规则成对;否则修好会话后旧痕迹会永远刷降级告警)。 */
346
+ function clearSkipRecords(root: string, target: string): void {
347
+ const dir = watchDir(root)
348
+ const wantWin = target.includes(':') ? target.slice(target.indexOf(':') + 1) : target
349
+ try {
350
+ for (const name of readdirSync(dir)) {
351
+ if (!name.endsWith('.skip')) continue
352
+ const file = join(dir, name)
353
+ try {
354
+ const ft = readField(file, 'target')
355
+ if (ft === target) { rmSync(file, { force: true }); continue }
356
+ if (readField(file, 'window') === wantWin && readField(file, 'reason') === 'session-mismatch') {
357
+ rmSync(file, { force: true })
358
+ }
359
+ } catch { /* ignore */ }
360
+ }
361
+ } catch {
362
+ /* ignore */
363
+ }
364
+ }
365
+
366
+ /** M53 · inotify 额度上限(/proc/sys/fs/inotify/max_user_watches)。读不到 → 'unknown'。 */
367
+ function inotifyMaxWatches(): string {
368
+ try {
369
+ const text = readFileSync('/proc/sys/fs/inotify/max_user_watches', 'utf8').trim()
370
+ return /^[0-9]+$/.test(text) ? text : 'unknown'
371
+ } catch {
372
+ return 'unknown'
373
+ }
374
+ }
375
+
376
+ /** M53 · 当前用户的 inotify watch 占用 —— 只认「可证明完整」的同 UID 视图,否则 'unknown'。
377
+ * 完整性有一个硬前提:我们不在嵌套的 PID 命名空间里(/proc/self/status 的 NSpid 只有一个值)。
378
+ * 容器里 /proc 只看得见自己的 PID 命名空间,计数会小得离谱(本机实测 16/65536,而宿主已 65312),
379
+ * 把局部计数当总量就是假绿;另:同 UID 进程的 fd/fdinfo 有一个读不到 → unknown,绝不报部分量。 */
380
+ function inotifyUsedWatches(): string {
381
+ try {
382
+ const status = readFileSync('/proc/self/status', 'utf8')
383
+ const ns = /^NSpid:\s*(.+)$/m.exec(status)
384
+ if (!ns || ns[1].trim().split(/\s+/).length > 1) return 'unknown'
385
+ } catch {
386
+ return 'unknown'
387
+ }
388
+ const uid = typeof process.getuid === 'function' ? process.getuid() : -1
389
+ if (uid < 0) return 'unknown'
390
+ let total = 0
391
+ try {
392
+ for (const entry of readdirSync('/proc')) {
393
+ if (!/^[0-9]+$/.test(entry)) continue
394
+ const pdir = `/proc/${entry}`
395
+ let owner: number
396
+ try { owner = statSync(pdir).uid } catch { continue } // 进程刚退出:不是我们的证据缺口
397
+ if (owner !== uid) continue
398
+ let fds: string[]
399
+ try { fds = readdirSync(`${pdir}/fd`) } catch (error) {
400
+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') continue
401
+ return 'unknown' // 同 UID 却读不到 = 视图不完整(不是「占用很小」)
402
+ }
403
+ for (const fd of fds) {
404
+ let link = ''
405
+ try { link = readlinkSync(`${pdir}/fd/${fd}`) } catch (error) {
406
+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') continue
407
+ return 'unknown'
408
+ }
409
+ if (link !== 'anon_inode:inotify') continue
410
+ let info = ''
411
+ try { info = readFileSync(`${pdir}/fdinfo/${fd}`, 'utf8') } catch (error) {
412
+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') continue
413
+ return 'unknown'
414
+ }
415
+ const wds = new Set<string>() // 一个 inotify 实例里同一个 wd 只算一个 watch
416
+ for (const line of info.split('\n')) {
417
+ const m = /^inotify wd:([0-9a-f]+)\s/.exec(line)
418
+ if (m) wds.add(m[1])
419
+ }
420
+ total += wds.size
421
+ }
422
+ }
423
+ } catch {
424
+ return 'unknown'
425
+ }
426
+ return String(total)
427
+ }
428
+
429
+ /** `<used>/<max>` 形状(用于账本行与降级记录;used 可能是 unknown)。 */
430
+ function watchUsageField(): string { return `${inotifyUsedWatches()}/${inotifyMaxWatches()}` }
431
+
432
+ /** 失败原因 → errno 文本(优先 error.code;取不到时从 message 里挑一个 E… 记号)。 */
433
+ function watchErrnoOf(error: unknown): string {
434
+ const code = (error as NodeJS.ErrnoException)?.code
435
+ if (typeof code === 'string' && /^E[A-Z0-9]+$/.test(code)) return code
436
+ const m = /\b(E[A-Z][A-Z0-9]+)\b/.exec(String((error as Error)?.message ?? error))
437
+ return m ? m[1] : 'unknown'
438
+ }
439
+
440
+ /** 夹具旋钮(config.md 登记为 fixture-only):<errno> ⇒ 不尝试注册,走同一条失败路径并标 `forced=1`。 */
441
+ function forcedWatchErrno(): string {
442
+ return (process.env.TEAM_INBOX_WATCH_FORCE_FAIL || '').trim()
443
+ }
444
+
445
+ /** M53 · 降级记录 `state/inbox-watch/<key>.degraded`(与 .reg/.skip 同一种 KEY=VALUE 家族)。
446
+ * 为什么不是 .skip:`.skip` 的含义是「没有注册」(发送方会退回粘贴路径),而这里是「注册在、
447
+ * watcher 不在」——路由(`team_inbox_watch_route`)只认 .reg,绝不能被这条记录改道。
448
+ * 读者只认「pid 活着 + cwd 在本项目内」(与 .reg/.skip 同一条证据规则);成功注册或干净退出删掉它。 */
449
+ function writeDegradedRecord(root: string, target: string, info: {
450
+ errno: string; watches: string; pollMs: number; forced: boolean
451
+ }): void {
452
+ // 变量名故意不叫 dir:flip-m46 包用 `}): void {\n const dir = watchDir(root)` 当 writeSkipRecord 的注射锚点,
453
+ // 这里重名会让那个锚点变成 2 处(既有翻转包会 exit 2)——不动的包不该被新代码抵掉。
454
+ const wdir = watchDir(root)
455
+ const key = targetKey(target)
456
+ try { mkdirSync(wdir, { recursive: true }) } catch { return }
457
+ const body = [
458
+ 'version=1',
459
+ `target=${target}`,
460
+ `key=${key}`,
461
+ 'reason=watch-unavailable',
462
+ `errno=${info.errno}`,
463
+ `watches=${info.watches}`,
464
+ `poll_ms=${info.pollMs}`,
465
+ `forced=${info.forced ? 1 : 0}`,
466
+ `since=${new Date().toISOString()}`,
467
+ `pid=${process.pid}`,
468
+ `cwd=${root}`,
469
+ `heartbeat=${Math.floor(Date.now() / 1000)}`,
470
+ '',
471
+ ].join('\n')
472
+ try {
473
+ const tmp = join(wdir, `${key}.degraded.tmp-${process.pid}`)
474
+ writeFileSync(tmp, body)
475
+ renameSync(tmp, join(wdir, `${key}.degraded`))
476
+ } catch {
477
+ /* 痕迹写不进去也不能影响会话;账本那一行仍然有 */
478
+ }
479
+ }
480
+
481
+ /** 成功注册(或本次会话结束)后,同 target 的旧降级记录不再成立 → 删掉(不再骗 doctor/status/面板)。 */
482
+ function clearDegradedRecords(root: string, target: string): void {
483
+ const dir = watchDir(root)
484
+ try {
485
+ for (const name of readdirSync(dir)) {
486
+ if (!name.endsWith('.degraded')) continue
487
+ const file = join(dir, name)
488
+ try { if (readField(file, 'target') === target) rmSync(file, { force: true }) } catch { /* ignore */ }
489
+ }
490
+ } catch {
491
+ /* ignore */
492
+ }
493
+ }
494
+
495
+ /** M53 · 失败路径的唯一出口:账本一行(唯一形状 `watch unavailable: errno=… watches=… poll_ms=…
496
+ * fallback=polling [forced=1]`)+ 一条耐久降级记录。轮询计时器**不在这里** —— 它在 session_start
497
+ * 里无条件安装(兜底是契约,不是失败路径的补丁;兜底的证明见夹具 S23)。 */
498
+ function recordWatchFailure(root: string, target: string, err: string, forced: boolean): void {
499
+ const usage = watchUsageField()
500
+ const ms = pollMs()
501
+ appendLedger(root,
502
+ `watch unavailable: errno=${err} watches=${usage} poll_ms=${ms} fallback=polling${forced ? ' forced=1' : ''}`)
503
+ writeDegradedRecord(root, target, { errno: err, watches: usage, pollMs: ms, forced })
504
+ }
505
+
506
+ /** 读一份 KEY=VALUE 文件里的单个字段(.reg/.skip 共用;没有 → 空串)。 */
507
+ function readField(file: string, name: string): string {
508
+ try {
509
+ const m = new RegExp(`^${name}=(.*)$`, 'm').exec(readFileSync(file, 'utf8'))
510
+ return m ? m[1].trim() : ''
511
+ } catch {
512
+ return ''
513
+ }
514
+ }
515
+
516
+ /** spool 的当前大小(读不到 = -1)。 */
517
+ function fileSize(file: string): number {
518
+ try { return statSync(file).size } catch { return -1 }
519
+ }
520
+
521
+ /** spool 的头部前缀(前 min(HEAD_BYTES, size) 字节):回退时用它判断「开头有没有被改写」(B2/D3)。
522
+ * 只读前缀;读不到 → null(调用方按「没有证据」处理,不会误判成「没变」)。 */
523
+ function readHead(file: string, size: number): Buffer | null {
524
+ if (size < 0) return null
525
+ const n = Math.min(HEAD_BYTES, size)
526
+ if (n === 0) return Buffer.alloc(0)
527
+ try {
528
+ const fd = openSync(file, 'r')
529
+ try {
530
+ const buf = Buffer.alloc(n)
531
+ const got = readSync(fd, buf, 0, n, 0)
532
+ return Buffer.from(buf.subarray(0, got))
533
+ } finally {
534
+ closeSync(fd)
535
+ }
536
+ } catch {
537
+ return null
538
+ }
539
+ }
540
+
541
+ /** 头部指纹(账本里的可读短记号;只用于记账本与 repeat 比较,不参与「变没变」的判断)。 */
542
+ function headStamp(head: Buffer | null): string {
543
+ if (head === null) return 'absent'
544
+ if (head.length === 0) return 'empty'
545
+ let h = 2166136261
546
+ for (let i = 0; i < head.length; i++) { h ^= head[i]; h = Math.imul(h, 16777619) >>> 0 }
547
+ return `fnv${h.toString(16).padStart(8, '0')}`
548
+ }
549
+
550
+ type Freshness = 'fresh' | 'stale' | 'unparsable'
551
+
552
+ /** 行年龄(B3/R3):spool 行的第一个字段是发送者落盘时的 `team_epoch_ms`(毫秒)。
553
+ * 判据只用行自带的这个字段 —— 不看文件 mtime(外部重写会动它,且它回答不了「这一行什么时候写的」),
554
+ * 也不看日志的顺序(那只回答「投过没有」)。读不出来的时间戳算 fresh-for-delivery 并单独计数。 */
555
+ function freshnessOf(src: number): Freshness {
556
+ if (!Number.isFinite(src) || src <= 0) return 'unparsable' // 不可解析 ≠ 过期:投递 + 计数,绝不静默吞
557
+ return Date.now() - src > staleSec() * 1000 ? 'stale' : 'fresh'
558
+ }
559
+
560
+ type ReadResult = {
561
+ lines: string[]
562
+ offset: number
563
+ shrank: boolean
564
+ size: number // 本次读到的文件大小(-1 = 文件不见了)
565
+ resync: number // 起点落在行中时跳过的碎片字节数(含换行;0 = 没有碎片)
566
+ }
567
+
568
+ /** 读完 spool 自 <offset> 起的新行(只消费完整行)。
569
+ * size < offset 或文件消失(且此前跟踪过内容)= **外部截断/重写/替换**(仓内写路径只有追加)——
570
+ * 此时返回 shrank=true 且一行都不读:怎么有界地重扫是 flush() 的决策(M43),这里绝不静默重置。
571
+ * P28/B1:offset 只按**实际读到的字节**推进 —— 在原始 buffer 上找 `\n`、认 readSync 的返回值、
572
+ * 逐行解码。绝不经过「先解码成字符串、再用 Buffer.byteLength 量长度」的往返:非法字节会变成
573
+ * U+FFFD(1 字节量成 3 字节),offset 于是越过文件末尾,下一拍看起来像外部缩容(2026-09-20 事故)。
574
+ * 起点落在行中(只有 clamp/trim 会把 offset 落在行中)→ 到下一个换行为止都是碎片,跳过并记账本。 */
575
+ function readNewLines(file: string, offset: number): ReadResult {
576
+ let size = -1
577
+ try { size = statSync(file).size } catch {
578
+ return { lines: [], offset: 0, shrank: offset > 0, size: -1, resync: 0 } // 文件没了 = 缩到 0
579
+ }
580
+ if (size < offset) return { lines: [], offset: 0, shrank: true, size, resync: 0 }
581
+ if (size === offset) return { lines: [], offset, shrank: false, size, resync: 0 }
582
+ try {
583
+ const fd = openSync(file, 'r')
584
+ try {
585
+ // 起点是不是落在行中:offset 前一个字节不是 `\n`(offset=0 = 文件头,永远算行首)
586
+ let midLine = false
587
+ if (offset > 0) {
588
+ const prev = Buffer.alloc(1)
589
+ midLine = readSync(fd, prev, 0, 1, offset - 1) === 1 && prev[0] !== 0x0a
590
+ }
591
+ const buf = Buffer.alloc(size - offset)
592
+ const bytesRead = readSync(fd, buf, 0, buf.length, offset) // B1:返回值算数(短读的 NUL 填充不许当内容)
593
+ const win = buf.subarray(0, bytesRead)
594
+ const end = win.lastIndexOf(0x0a) // 原始字节上的最后一个换行 = 最后一个完整行
595
+ if (end < 0) return { lines: [], offset, shrank: false, size, resync: 0 }
596
+ // 行中起步 = 碎片(被 clamp 截住的旧行的尾巴):跳到它自己的换行为止,绝不投递(B1.2)
597
+ const start = midLine ? win.indexOf(0x0a) + 1 : 0
598
+ const resync = start
599
+ const advance = end + 1 // P28/B1:字节真值(flip-p25.sh 的 mutant A/B 把这一行换成解码→再编码的长度)
600
+ const lines: string[] = []
601
+ let from = start
602
+ for (let i = start; i <= end; i++) {
603
+ if (i !== end && win[i] !== 0x0a) continue
604
+ const line = win.subarray(from, i).toString('utf8').replace(/\r$/, '') // 只解码行文本
605
+ if (line.trim()) lines.push(line)
606
+ from = i + 1
607
+ }
608
+ return { lines, offset: offset + advance, shrank: false, size, resync }
609
+ } finally {
610
+ closeSync(fd)
611
+ }
612
+ } catch {
613
+ return { lines: [], offset, shrank: false, size, resync: 0 }
614
+ }
615
+ }
616
+
617
+ /** spool 的当前大小 = 本次会话的**投递基线**:启动之前写入的行不叫醒任何人(backlog 是 pulse 的活)。
618
+ * (单抽成函数是为了让「基线」这件事有一个可定点破坏的单点。) */
619
+ function baselineOffset(file: string): number {
620
+ return readNewLines(file, 0).offset
621
+ }
622
+
623
+ /** spool 超上限 → 截头留尾(尾部信号不丢)。返回裁剪后的新大小(没裁 → -1):
624
+ * 调用方必须把 offset 对上新大小,否则下一拍会看到「size < offset」走 shrink/rescan ——
625
+ * 有去重兑底不会再叫一遍,但白扫一遍 + 账本多两行噪音,没必要。 */
626
+ function trimSpool(file: string): number {
627
+ const cap = maxBytes()
628
+ try {
629
+ if (statSync(file).size <= cap) return -1
630
+ const keep = Math.max(1024, Math.floor(cap / 2))
631
+ const fd = openSync(file, 'r')
632
+ let text = ''
633
+ try {
634
+ const size = statSync(file).size
635
+ const start = Math.max(0, size - keep)
636
+ const buf = Buffer.alloc(size - start)
637
+ readSync(fd, buf, 0, buf.length, start)
638
+ text = buf.toString('utf8')
639
+ } finally {
640
+ closeSync(fd)
641
+ }
642
+ const firstNl = text.indexOf('\n')
643
+ writeFileSync(file, firstNl >= 0 ? text.slice(firstNl + 1) : '')
644
+ return statSync(file).size
645
+ } catch {
646
+ return -1
647
+ }
648
+ }
649
+
650
+ /* ── P81 · 投递日志(`state/inbox-watch/<key>.deliver`,唯一 durable 去重权威) ─────────────────
651
+ * 形状:一行一条记录,ISO 时间戳开头,其余字段 `key=value` 空格分隔;值里的空白一律转义
652
+ * (jesc/junesc)——身份可能是整行的摘要,绝不许把分隔符带进值里。记录种类:
653
+ * start baseline=<n> size=<n> head=<stamp>
654
+ * read seq=<n> off=<n> size=<n> head=<stamp> id=<身份> src=<ms> kind=<k> from=<f> durable=<d> preview=<p>
655
+ * intent seq=<n>
656
+ * sent seq=<n> (导入老 .seen 时也写 sent seq=<负> id=<身份> imported=1)
657
+ * failed seq=<n> reason=<why>
658
+ * floor id=<保留的最老身份> ts=<地板源时间> evicted=<n> kept=<n>
659
+ * 判定是逐记录的:`read` 点名的身份进入「读数」态,`intent`/`sent`/`failed` 按文件顺序落到同一批的
660
+ * 身份上 —— 最后一条说了算(`sent` → 已投递;`intent` → 结果未知;`failed` → 可重试一次;`read` → 可恢复一次)。 */
661
+
662
+ /** 日志值编码:空白 → 反斜杠转义(解析逐字可逆)。 */
663
+ function jesc(s: string): string {
664
+ return s.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/ /g, '\\s')
665
+ }
666
+
667
+ function junesc(s: string): string {
668
+ let out = ''
669
+ for (let i = 0; i < s.length; i++) {
670
+ const c = s[i]
671
+ if (c !== '\\') { out += c; continue }
672
+ const n = s[++i]
673
+ out += n === 'n' ? '\n' : n === 'r' ? '\r' : n === 't' ? '\t' : n === 's' ? ' ' : n === '\\' ? '\\' : (n ?? '')
674
+ }
675
+ return out
676
+ }
677
+
678
+ /** 行的身份:发送方写在第 6 字段的 `id=`(outbox 条目名,与 state/outbox/delivered.log 对得上)优先;
679
+ * 没有该字段的旧行/外来行 = 整行的 SHA-1 摘要(有界的**身份**,不是 payload 全文)。日志与唤醒文本
680
+ * 印同一个串 —— 收件方据此自证「这是哪一条」,两条逐字相同的 payload 靠源时间 + 身份区分。 */
681
+ function lineIdentity(line: string): string {
682
+ const id = (line.split('\t')[5] ?? '').trim()
683
+ if (id) return id
684
+ return `sha1:${createHash('sha1').update(line, 'utf8').digest('hex')}`
685
+ }
686
+
687
+ type SpoolLine = {
688
+ raw: string
689
+ identity: string
690
+ src: number // 行首的 team_epoch_ms;0 = 不可解析(照投 + 计数,绝不静默吞)
691
+ kind: string
692
+ from: string
693
+ durable: string
694
+ preview: string
695
+ }
696
+
697
+ function parseSpoolLine(raw: string): SpoolLine {
698
+ const f = raw.split('\t')
699
+ const first = (f[0] ?? '').trim()
700
+ return {
701
+ raw,
702
+ identity: lineIdentity(raw),
703
+ src: /^\d+$/.test(first) ? Number(first) : 0,
704
+ kind: (f[1] ?? '').trim() || 'msg',
705
+ from: (f[2] ?? '').trim() || '-',
706
+ durable: (f[3] ?? '').trim() || '-',
707
+ preview: f[4] ?? '',
708
+ }
709
+ }
710
+
711
+ type JournalEntryState = 'read' | 'intent' | 'sent' | 'failed'
712
+ type JournalEntry = { state: JournalEntryState; material: SpoolLine | null; failure: string }
713
+ type Journal = {
714
+ entries: Map<string, JournalEntry>
715
+ batch: Map<number, string[]>
716
+ maxSeq: number
717
+ floorTs: number | null
718
+ floorId: string
719
+ torn: boolean
720
+ records: number
721
+ }
722
+
723
+ function parseJournalLine(line: string): { kind: string; fields: Map<string, string> } | null {
724
+ const m = /^(\S+) (start|read|intent|sent|failed|floor)(?: (.*))?$/.exec(line)
725
+ if (!m) return null
726
+ const fields = new Map<string, string>()
727
+ for (const tok of (m[3] ?? '').split(' ')) {
728
+ if (!tok) continue
729
+ const eq = tok.indexOf('=')
730
+ if (eq <= 0) return null
731
+ fields.set(tok.slice(0, eq), junesc(tok.slice(eq + 1)))
732
+ }
733
+ return { kind: m[2], fields }
734
+ }
735
+
736
+ function journalMaterial(rec: { fields: Map<string, string> }, identity: string): SpoolLine {
737
+ const src = Number(rec.fields.get('src') ?? '')
738
+ return {
739
+ raw: '', identity,
740
+ src: Number.isFinite(src) && src > 0 ? src : 0,
741
+ kind: rec.fields.get('kind') ?? 'msg',
742
+ from: rec.fields.get('from') ?? '-',
743
+ durable: rec.fields.get('durable') ?? '-',
744
+ preview: rec.fields.get('preview') ?? '',
745
+ }
746
+ }
747
+
748
+ /** 读投递日志(唯一的 durable 去重权威)。尾部没有收尾换行 / 解析不出来的记录 = **撕裂**
749
+ * (崩溃正落在写日志中间):保守地当成「结果未知」—— 有 read 没 intent 的行绝不因此被当成
750
+ * 「还没发过」而重投(宁可漏一次敲门,也不许无据重投)。 */
751
+ function loadJournal(file: string): Journal {
752
+ const j: Journal = { entries: new Map(), batch: new Map(), maxSeq: 0, floorTs: null, floorId: '', torn: false, records: 0 }
753
+ let text = ''
754
+ try { text = readFileSync(file, 'utf8') } catch { return j }
755
+ if (!text) return j
756
+ const lines = text.split('\n')
757
+ if (text.endsWith('\n')) lines.pop()
758
+ else { j.torn = true; lines.pop() } // 没有收尾换行的尾记录 = 半截
759
+ for (const line of lines) {
760
+ if (!line.trim()) continue
761
+ j.records++
762
+ const rec = parseJournalLine(line)
763
+ if (!rec) { j.torn = true; continue }
764
+ const seq = Number(rec.fields.get('seq') ?? '')
765
+ if (rec.kind === 'start') continue
766
+ if (rec.kind === 'floor') {
767
+ const ts = Number(rec.fields.get('ts') ?? '')
768
+ if (Number.isFinite(ts) && ts > 0) j.floorTs = ts
769
+ j.floorId = rec.fields.get('id') ?? j.floorId
770
+ continue
771
+ }
772
+ if (Number.isFinite(seq)) j.maxSeq = Math.max(j.maxSeq, seq)
773
+ if (rec.kind === 'read') {
774
+ const identity = rec.fields.get('id') ?? ''
775
+ if (!identity) continue
776
+ j.entries.set(identity, { state: 'read', material: journalMaterial(rec, identity), failure: '' })
777
+ if (Number.isFinite(seq)) {
778
+ const ids = j.batch.get(seq) ?? []
779
+ ids.push(identity)
780
+ j.batch.set(seq, ids)
781
+ }
782
+ continue
783
+ }
784
+ // sent 带显式 id(老 .seen 的导入):直接就是「已投递」,不依赖任何批次
785
+ const explicit = rec.fields.get('id') ?? ''
786
+ if (explicit && (rec.kind === 'sent' || rec.kind === 'failed')) {
787
+ j.entries.set(explicit, {
788
+ state: rec.kind === 'sent' ? 'sent' : 'failed',
789
+ material: j.entries.get(explicit)?.material ?? null,
790
+ failure: rec.fields.get('reason') ?? '',
791
+ })
792
+ continue
793
+ }
794
+ // intent / sent / failed 是批级的:落到这一批 read 记录点名的每个身份上
795
+ for (const identity of (Number.isFinite(seq) ? (j.batch.get(seq) ?? []) : [])) {
796
+ const entry = j.entries.get(identity)
797
+ if (!entry) continue
798
+ if (rec.kind === 'intent') { if (entry.state === 'read') entry.state = 'intent'; continue }
799
+ if (rec.kind === 'sent') { entry.state = 'sent'; entry.failure = ''; continue }
800
+ entry.state = 'failed'
801
+ entry.failure = rec.fields.get('reason') ?? ''
802
+ }
803
+ }
804
+ return j
805
+ }
806
+
807
+ export default function (pi: ExtensionAPI) {
808
+ let root = ''
809
+ let key = ''
810
+ let keyTarget = ''
811
+ let startedAt = ''
812
+ let inbox = ''
813
+ let spool = ''
814
+ let reg = ''
815
+ let seenPath = ''
816
+ let journalPath = ''
817
+ let offset = 0
818
+ let seen = 0
819
+ let delivered = new Set<string>() // P81:已投递的身份(来自日志 sent/intent 导入/本次会话成功发送)
820
+ let journalEntries = new Map<string, JournalEntry>() // 启动时从日志载入的身份态(只读快照)
821
+ let retryQueue = new Map<string, SpoolLine>() // failed:会话 API 拒过、每拍至多重试一次
822
+ let recoveryQueue = new Map<string, SpoolLine>() // read 无 intent:恰好允许一次恢复
823
+ let floorTs: number | null = null // 日志淘汰下限(更早的身份 → unprovable)
824
+ let floorId = ''
825
+ let journalRecords = 0
826
+ let seqCounter = 1 // 唤醒序号(跨重启单调;来自日志 max seq)
827
+ let abortAt = '' // 夹具注入点(只在 TEAM_SMOKE_FIXTURE=1 下生效)
828
+ let watcher: any = null
829
+ let fileWatcher: any = null // spool 的**文件级** watcher(Bun 的目录 watcher 会丢逐文件事件)
830
+ let pollTimer: ReturnType<typeof setInterval> | null = null
831
+ let beatTimer: ReturnType<typeof setInterval> | null = null
832
+ let mergeTimer: ReturnType<typeof setTimeout> | null = null
833
+
834
+ const stopAll = (): void => {
835
+ try { watcher?.close?.() } catch { /* ignore */ }
836
+ watcher = null
837
+ try { fileWatcher?.close?.() } catch { /* ignore */ }
838
+ fileWatcher = null
839
+ if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
840
+ if (beatTimer) { clearInterval(beatTimer); beatTimer = null }
841
+ if (mergeTimer) { clearTimeout(mergeTimer); mergeTimer = null }
842
+ }
843
+
844
+ let headBytes: Buffer | null = null // 上次建立 offset 时的头部前缀(B2 的回退证据)
845
+ let lastShrink: { size: number; head: string } | null = null // 上一个 shrink 事件的 (size, head)(B2 的收敛记忆)
846
+
847
+ /** 现在的头部算不算「没变」:与记录的头部相同,或者是它的前缀(文件在头部范围内变短了,
848
+ * 但留下的字节一个没动)。头部读不出来(文件没了)→ 不算「没变」(没有证据就不是修复)。 */
849
+ const headUnchanged = (cur: Buffer | null): boolean => {
850
+ if (headBytes === null || cur === null) return false
851
+ if (cur.length === headBytes.length) return cur.equals(headBytes)
852
+ return cur.length < headBytes.length && cur.equals(headBytes.subarray(0, cur.length))
853
+ }
854
+
855
+ /** offset 越过文件末尾(size < offset):按证据决定「修复」还是「重写」(B2 / 设计 D3+D4)。
856
+ * 同一头部 + 小回退(≤ TEAM_INBOX_WATCH_CLAMP_BYTES)= 我们自己的 offset 算错了 → 一次 `offset clamp`;
857
+ * 头部变了 / 回退太大 = 真重写 → 有界重扫;同一 (size, head) 已处理过 = `shrink repeat` + clamp,
858
+ * 绝不重扫第二次(这是协议级的收敛,与 B1 的算术正确性互相独立)。
859
+ * clamp 目标只能是 size(当前末尾):走回上一个换行会退回基线之前的内容、重投 S5 故意压住的行;
860
+ * 落在行中由 B1.2 的碎片跳过规则吸掉。 */
861
+ const handleShrink = (): void => {
862
+ const size = fileSize(spool)
863
+ if (size >= 0 && size >= offset) return // 竞态:已经长回来了 → 下一拍正常读,不在这里决策
864
+ const cur = size >= 0 ? readHead(spool, size) : null
865
+ const stamp = headStamp(cur)
866
+ const repeat = lastShrink !== null && lastShrink.size === size && lastShrink.head === stamp
867
+ const regress = size >= 0 ? offset - size : Number.POSITIVE_INFINITY
868
+ if (size >= 0 && headUnchanged(cur) && (repeat || regress <= clampBytes())) {
869
+ if (repeat) {
870
+ appendLedger(root, `shrink repeat size=${size} head=${stamp} action=clamp inbox=${inbox}`)
871
+ } else {
872
+ appendLedger(root, `offset clamp from=${offset} to=${size} head=same inbox=${inbox}`)
873
+ }
874
+ offset = size
875
+ headBytes = cur
876
+ lastShrink = { size, head: stamp }
877
+ return
878
+ }
879
+ appendLedger(root, `spool shrink: size fell below offset=${offset} inbox=${inbox} → bounded rescan from 0(外部截断/重写;仓内只有追加写)`)
880
+ lastShrink = { size, head: stamp }
881
+ if (rescan() === 'blocked') lastShrink = null // 日志写不进去:不收敛到 clamp,下一拍重试同一份重写
882
+ }
883
+
884
+ /** 追加一条日志记录。失败 = false:调用方**绝不因此发送任何东西**(fail-closed),
885
+ * 账本记 `deliver blocked`,行保持未读等下一拍(丢一次敲门允许,丢日志不允许)。 */
886
+ const journalAppend = (record: string): boolean => {
887
+ try {
888
+ mkdirSync(dirname(journalPath), { recursive: true })
889
+ appendFileSync(journalPath, `${new Date().toISOString()} ${record}\n`)
890
+ journalRecords++
891
+ return true
892
+ } catch {
893
+ return false
894
+ }
895
+ }
896
+
897
+ /** P81 · 一次性导入老代码的 `<key>.seen`(仅当投递日志还不存在时)。导入的身份作为
898
+ * 「已投递」追加进日志(synthetic seq + 显式 id);此后不再读它 —— 删掉/清空 `.seen` 不改变
899
+ * 任何投递决定(日志是唯一记忆)。 */
900
+ const importSeen = (): number => {
901
+ let lines: string[] = []
902
+ try { lines = readFileSync(seenPath, 'utf8').split('\n').filter(l => l.trim()) } catch { return 0 }
903
+ let n = 0
904
+ for (const raw of lines.slice(-seenMax())) {
905
+ if (!journalAppend(`sent seq=-${n + 1} id=${jesc(lineIdentity(raw))} imported=1`)) break
906
+ n++
907
+ }
908
+ return n
909
+ }
910
+
911
+ /** P81 · 压缩:日志越过上限 → 只留最近的记录(**绝不从一组 read/intent/sent 中间切起**,
912
+ * 不然已投递的身份会连同它的 read 一起丢掉),写一条 `floor` 记淘汰下限;地板 = 保留下来的
913
+ * read 里最小的源时间戳 —— 比它更早的身份日志已不能证明「没投过」(`unprovable`,永不唤醒)。
914
+ * tmp + rename:崩溃只留下旧文件,绝不留半截。 */
915
+ const compactJournal = (): boolean => {
916
+ let lines: string[] = []
917
+ try {
918
+ const text = readFileSync(journalPath, 'utf8')
919
+ if (!text.endsWith('\n')) return false // 撕裂尾先不碰(下一次完整追加后再压)
920
+ lines = text.split('\n').filter(l => l.trim())
921
+ } catch { return false }
922
+ const max = journalMax()
923
+ if (lines.length <= max) return false
924
+ // 组的边界:一批 read…intent…sent/failed 不能从中间切开(不然已投递的身份会连同它的 read 一起丢掉)。
925
+ // 从尾往前按**整组**累计,直到再加一组就超过上限 —— floor 行也算一条记录,所以留一个位置。
926
+ const starts: number[] = []
927
+ for (let i = 0; i < lines.length; i++) {
928
+ const kind = parseJournalLine(lines[i])?.kind
929
+ if (i === 0 || kind === 'read' || kind === 'start' || kind === 'floor') starts.push(i)
930
+ }
931
+ let cut = lines.length
932
+ for (let i = starts.length - 1; i >= 0; i--) {
933
+ if (lines.length - starts[i] + 1 > max) break // +1 = 将要写下的 floor 行
934
+ cut = starts[i]
935
+ }
936
+ const dropped = lines.slice(0, cut)
937
+ const kept = lines.slice(cut)
938
+ let evicted = 0
939
+ for (const line of dropped) if (parseJournalLine(line)?.kind === 'read') evicted++
940
+ let floor: number | null = null
941
+ let floorIdentity = ''
942
+ for (const line of kept) {
943
+ const rec = parseJournalLine(line)
944
+ if (rec?.kind !== 'read') continue
945
+ const src = Number(rec.fields.get('src') ?? '')
946
+ if (Number.isFinite(src) && src > 0 && (floor === null || src < floor)) { floor = src; floorIdentity = rec.fields.get('id') ?? '' }
947
+ }
948
+ if (floor === null) { floor = floorTs ?? Date.now(); floorIdentity = floorId }
949
+ const floorLine = `${new Date().toISOString()} floor id=${jesc(floorIdentity || '-')} ts=${floor} evicted=${evicted} kept=${kept.length}`
950
+ try {
951
+ const tmp = `${journalPath}.tmp-${process.pid}`
952
+ writeFileSync(tmp, `${[floorLine, ...kept].join('\n')}\n`)
953
+ renameSync(tmp, journalPath)
954
+ } catch { return false }
955
+ floorTs = floor
956
+ floorId = floorIdentity
957
+ journalRecords = kept.length + 1
958
+ appendLedger(root,
959
+ `journal compacted records=${lines.length} kept=${kept.length} floor=${floorIdentity || '-'} floor_ts=${floor} evicted=${evicted} inbox=${inbox}`)
960
+ return true
961
+ }
962
+
963
+ const maybeCompact = (): void => {
964
+ if (journalRecords <= journalMax()) return
965
+ if (!compactJournal()) return
966
+ // 地板与记录数重新对齐(内存里的 delivered/retry/recovery 保留 —— 被淘汰的身份在本次会话里
967
+ // 仍然有证据,绝不因为压缩反而放行)
968
+ const reloaded = loadJournal(journalPath)
969
+ floorTs = reloaded.floorTs ?? floorTs
970
+ floorId = reloaded.floorId || floorId
971
+ journalRecords = reloaded.records
972
+ }
973
+
974
+ /** 夹具注入点(只在 `TEAM_SMOKE_FIXTURE=1` 下生效,否则启动时记一行 ignored):
975
+ * `TEAM_INBOX_WATCH_ABORT_AFTER=read|intent` 让**当前进程**在写前记录的那一步真死(SIGKILL)——
976
+ * 崩溃必须发生在另一个进程里,日志才有机会证明自己是权威。 */
977
+ const fixtureAbort = (): void => {
978
+ try { process.kill(process.pid, 'SIGKILL') } catch { /* ignore */ }
979
+ }
980
+
981
+ const writeReg = (note: string): void => {
982
+ if (!reg) return
983
+ const body = [
984
+ 'version=1',
985
+ `target=${keyTarget}`,
986
+ `inbox=${inbox}`,
987
+ `pid=${process.pid}`,
988
+ `cwd=${root}`,
989
+ `started=${startedAt}`,
990
+ `heartbeat=${Math.floor(Date.now() / 1000)}`,
991
+ `note=${note}`,
992
+ '',
993
+ ].join('\n')
994
+ try {
995
+ const tmp = `${reg}.tmp-${process.pid}`
996
+ writeFileSync(tmp, body)
997
+ renameSync(tmp, reg)
998
+ } catch {
999
+ /* 注册写不进去 → 发送方走粘贴路径;这不是会话该关心的事 */
1000
+ }
1001
+ }
1002
+
1003
+ type WakeMeta = {
1004
+ dup?: number
1005
+ skipped?: number
1006
+ recovery?: boolean
1007
+ retry?: boolean
1008
+ off?: number
1009
+ size?: number
1010
+ head?: string
1011
+ }
1012
+
1013
+ /** P81 · 唤醒文本:`#<seq>` + 绝对发送时间 + 每行的源时间/身份 + 投递日志路径。
1014
+ * 指针 + 截断预览,绝不带 payload 全文;身份是有界的(发送方的 id 或整行 sha1 摘要)。 */
1015
+ const wakeText = (seq: number, lines: SpoolLine[], meta: WakeMeta): string => {
1016
+ const sendTs = new Date().toISOString()
1017
+ const rows = lines.map(l => {
1018
+ const from = l.from && l.from !== '-' ? ` from ${l.from}` : ''
1019
+ const where = l.durable && l.durable !== '-' ? ` → ${l.durable}.md` : ''
1020
+ const src = l.src > 0 ? new Date(l.src).toISOString() : '(no timestamp)'
1021
+ const preview = oneLine(l.preview || '(empty)', previewLimit())
1022
+ return `- [${l.kind}]${from}${where} :: ${preview} (src ${src} · id ${l.identity})`
1023
+ })
1024
+ const shown = rows.slice(0, MAX_LISTED)
1025
+ const more = rows.length - shown.length
1026
+ const hasInbox = lines.some(l => !!l.durable && l.durable !== '-')
1027
+ const hasLogOnly = lines.some(l => !l.durable || l.durable === '-')
1028
+ const firstInbox = lines.map(l => l.durable).find(d => !!d && d !== '-') || inbox
1029
+ const inboxPath = `${docsDir(root)}/inbox/${firstInbox}.md`
1030
+ const rescanNote = meta.dup !== undefined
1031
+ ? `(spool rescan after external shrink: delivered the last ${lines.length} unseen line(s); ` +
1032
+ `skipped ${meta.dup} already-delivered + ${meta.skipped ?? 0} older. Full history stays in the spool file.)\n`
1033
+ : ''
1034
+ const recoveryNote = meta.recovery
1035
+ ? `(recovered from the delivery journal: a previous session read these lines and stopped before sending them.)\n`
1036
+ : ''
1037
+ const retryNote = meta.retry ? `(retry of a wake whose delivery failed earlier; at most one retry per tick.)\n` : ''
1038
+ return (
1039
+ `[teamsmith] inbox wake #${seq} · ${sendTs}\n` +
1040
+ `${shown.join('\n')}${more > 0 ? `\n- … and ${more} more` : ''}\n` +
1041
+ rescanNote + recoveryNote + retryNote +
1042
+ `Delivery journal: ${journalPath} — the ids above are recorded there (cross-check the sender's state/outbox/delivered.log).\n` +
1043
+ (hasInbox && hasLogOnly
1044
+ ? `Full text: the ${inboxPath} file named on each line; the others (knock/nudge) are pointers to the sender's own log (\`team inbox\` / \`team digest\` / state/nudges.log).\n`
1045
+ : hasLogOnly
1046
+ ? `These wakes point at the sender's own log (\`team inbox\` / \`team digest\`); they carry no inbox line.\n`
1047
+ : `Full text: read ${inboxPath} — this wake-up carries a one-line pointer, not the payload.\n`)
1048
+ )
1049
+ }
1050
+
1051
+ const shortError = (error: unknown): string => oneLine(String((error as Error)?.message ?? error ?? 'unknown'), 160)
1052
+
1053
+ /** P81 · 唯一的发送出口:写前记录(read → intent)→ 发送 → sent/failed。
1054
+ * `intent` 没写成**绝不发送**(fail-closed);API 拒了记 `failed`,下一拍重试。 */
1055
+ const sendWake = (lines: SpoolLine[], meta: WakeMeta = {}): 'ok' | 'failed' | 'blocked' => {
1056
+ if (!lines.length) return 'ok'
1057
+ const seq = seqCounter++
1058
+ const off = meta.off ?? offset
1059
+ const size = meta.size ?? fileSize(spool)
1060
+ const head = meta.head ?? headStamp(readHead(spool, size))
1061
+ const readRecord = (l: SpoolLine): string =>
1062
+ `read seq=${seq} off=${off} size=${size} head=${head} id=${jesc(l.identity)} src=${l.src || ''} ` +
1063
+ `kind=${jesc(l.kind)} from=${jesc(l.from)} durable=${jesc(l.durable)} preview=${jesc(oneLine(l.preview || '(empty)', previewLimit()))}`
1064
+ const blocked = (): 'blocked' => {
1065
+ appendLedger(root, `deliver blocked seq=${seq} inbox=${inbox}(投递日志写不进去 → 按失败关闭:一条都不发,行保持未读)`)
1066
+ return 'blocked'
1067
+ }
1068
+ for (const l of lines) if (!journalAppend(readRecord(l))) return blocked()
1069
+ maybeCompact()
1070
+ if (abortAt === 'read') fixtureAbort()
1071
+ if (!journalAppend(`intent seq=${seq}`)) return blocked()
1072
+ maybeCompact()
1073
+ if (abortAt === 'intent') fixtureAbort()
1074
+ try {
1075
+ pi.sendMessage({ customType: 'team-inbox', content: wakeText(seq, lines, meta), display: true },
1076
+ { triggerTurn: true, deliverAs: 'followUp' })
1077
+ } catch (error) {
1078
+ journalAppend(`failed seq=${seq} reason=${jesc(shortError(error))}`)
1079
+ appendLedger(root,
1080
+ `wake failed seq=${seq} reason=${oneLine(shortError(error), 120)} inbox=${inbox}(会话 API 拒绝:这一行没投出,下一拍重试至多一次)`)
1081
+ for (const l of lines) retryQueue.set(l.identity, l)
1082
+ return 'failed'
1083
+ }
1084
+ if (!journalAppend(`sent seq=${seq}`)) {
1085
+ appendLedger(root, `sent record blocked seq=${seq} inbox=${inbox}(会话已接受但日志没记上 sent → 下一次启动按 inflight 处理,绝不重投)`)
1086
+ }
1087
+ maybeCompact()
1088
+ seen += lines.length
1089
+ for (const l of lines) {
1090
+ delivered.add(l.identity)
1091
+ retryQueue.delete(l.identity)
1092
+ recoveryQueue.delete(l.identity)
1093
+ }
1094
+ appendLedger(root,
1095
+ `wake n=${lines.length} total=${seen} inbox=${inbox} kinds=${lines.map(l => l.kind).join(',')} seq=${seq} ids=${lines.map(l => l.identity).join('|')}` +
1096
+ (meta.recovery ? ` recovery n=${lines.length}` : '') +
1097
+ (meta.retry ? ' retry=1' : '') +
1098
+ (meta.dup !== undefined ? ` rescan[dup=${meta.dup} skipped=${meta.skipped ?? 0}]` : ''))
1099
+ return 'ok'
1100
+ }
1101
+
1102
+ type Classification = { fresh: SpoolLine[]; replay: number; stale: number; unparsable: number; unprovable: number }
1103
+
1104
+ /** 逐行判定(普通读/重扫共用一个口径):日志里有记录 → 绝不重投;日志没有但早于淘汰下限 → unprovable;
1105
+ * 过期 → 只计数;时间戳不可解析 → 照投并计数;其余才是真的新行。 */
1106
+ const classify = (lines: SpoolLine[]): Classification => {
1107
+ const out: Classification = { fresh: [], replay: 0, stale: 0, unparsable: 0, unprovable: 0 }
1108
+ for (const l of lines) {
1109
+ if (delivered.has(l.identity) || retryQueue.has(l.identity) || recoveryQueue.has(l.identity) || journalEntries.has(l.identity)) {
1110
+ out.replay++
1111
+ continue
1112
+ }
1113
+ if (l.src > 0 && floorTs !== null && l.src < floorTs) { out.unprovable++; continue }
1114
+ const f = freshnessOf(l.src)
1115
+ if (f === 'stale') { out.stale++; continue }
1116
+ if (f === 'unparsable') out.unparsable++
1117
+ out.fresh.push(l)
1118
+ }
1119
+ return out
1120
+ }
1121
+
1122
+ /** 普通路径:追加读到的新行。与日志重叠的行跳过并记账本;过期行只计数不唤醒(B3/R3),
1123
+ * 它们可读的副本是发送方在 spool 行之前写的 durable 收件箱行。 */
1124
+ const deliverNormal = (lines: string[], meta: { off: number; size: number; head: string }): 'ok' | 'blocked' => {
1125
+ const cls = classify(lines.map(parseSpoolLine))
1126
+ if (cls.replay > 0) {
1127
+ appendLedger(root, `replay suppressed n=${cls.replay} reason=normal inbox=${inbox}(外部重写带回了日志里已有记录的行)`)
1128
+ }
1129
+ if (cls.unprovable > 0) {
1130
+ appendLedger(root, `unprovable n=${cls.unprovable} inbox=${inbox}(身份早于日志淘汰下限:日志已不能证明它没投过 → 永不唤醒)`)
1131
+ }
1132
+ if (cls.stale > 0 || cls.unparsable > 0) {
1133
+ appendLedger(root, `classify stale=${cls.stale} unparsable=${cls.unparsable} inbox=${inbox}(过期行不唤醒;时间戳不可解析的行照投)`)
1134
+ }
1135
+ if (!cls.fresh.length) return 'ok'
1136
+ return sendWake(cls.fresh, { off: meta.off, size: meta.size, head: meta.head })
1137
+ }
1138
+
1139
+ /** shrink 后的有界重扫(M43):从 0 读,但①日志里已有一律不重复投 ②真新行只投最近 replayMax 条,
1140
+ * 更早的跳过 ③过期行只计数不投(B3/R3)—— 三种数量都进账本;全部被压掉时不唤醒(没什么好说的),
1141
+ * total 不动。`lines=/dup=/skipped=/deliver=` 保持原样在前(M43 的断言逐字不改),新计数接在后面。 */
1142
+ const rescan = (): 'ok' | 'blocked' => {
1143
+ const res = readNewLines(spool, 0)
1144
+ offset = res.offset
1145
+ headBytes = readHead(spool, res.size) // 重扫后 offset 重新建立:头部证据跟着刷新
1146
+ const cls = classify(res.lines.map(parseSpoolLine))
1147
+ const cap = replayMax()
1148
+ const skipped = Math.max(0, cls.fresh.length - cap)
1149
+ const fresh = skipped > 0 ? cls.fresh.slice(-cap) : cls.fresh
1150
+ appendLedger(root,
1151
+ `rescan lines=${res.lines.length} dup=${cls.replay} skipped=${skipped} deliver=${fresh.length} stale=${cls.stale} unparsable=${cls.unparsable} total=${seen} inbox=${inbox}`)
1152
+ if (cls.replay > 0) appendLedger(root, `replay suppressed n=${cls.replay} reason=rescan inbox=${inbox}`)
1153
+ if (cls.unprovable > 0) {
1154
+ appendLedger(root, `unprovable n=${cls.unprovable} inbox=${inbox}(身份早于日志淘汰下限:日志已不能证明它没投过 → 永不唤醒)`)
1155
+ }
1156
+ if (!fresh.length) return 'ok'
1157
+ return sendWake(fresh, { dup: cls.replay, skipped, off: res.offset, size: res.size, head: headStamp(readHead(spool, res.size)) })
1158
+ }
1159
+
1160
+ /** `failed` 的重试:每拍至多一次、不得越过新鲜度地平线(过期即丢弃并计数,绝不唤醒)。 */
1161
+ const runRetryTick = (): void => {
1162
+ if (!retryQueue.size) return
1163
+ let stale = 0
1164
+ const fresh: SpoolLine[] = []
1165
+ for (const [identity, material] of [...retryQueue]) {
1166
+ if (delivered.has(identity)) { retryQueue.delete(identity); continue }
1167
+ if (freshnessOf(material.src) === 'stale') { stale++; retryQueue.delete(identity); continue }
1168
+ fresh.push(material)
1169
+ }
1170
+ if (stale > 0) appendLedger(root, `retry stale=${stale} fresh=${fresh.length} inbox=${inbox}(重试不越过新鲜度地平线)`)
1171
+ if (fresh.length) sendWake(fresh, { retry: true })
1172
+ }
1173
+
1174
+ /** `read` 无 `intent`(上一次的发送根本没开始):恰好一次恢复。新鲜度优先 ——
1175
+ * 已过期的只计数(`stale=`,不是 `recovery=`),绝不唤醒。 */
1176
+ const runRecoveryTick = (): void => {
1177
+ if (!recoveryQueue.size) return
1178
+ let stale = 0
1179
+ let unparsable = 0
1180
+ const fresh: SpoolLine[] = []
1181
+ for (const [identity, material] of [...recoveryQueue]) {
1182
+ if (delivered.has(identity)) { recoveryQueue.delete(identity); continue }
1183
+ const f = freshnessOf(material.src)
1184
+ if (f === 'stale') { stale++; recoveryQueue.delete(identity); delivered.add(identity); continue }
1185
+ if (f === 'unparsable') unparsable++
1186
+ fresh.push(material)
1187
+ }
1188
+ appendLedger(root,
1189
+ `recovery candidates=${stale + fresh.length} fresh=${fresh.length} stale=${stale} unparsable=${unparsable} inbox=${inbox}`)
1190
+ if (!fresh.length) return
1191
+ const state = sendWake(fresh, { recovery: true })
1192
+ if (state !== 'blocked') for (const l of fresh) recoveryQueue.delete(l.identity)
1193
+ }
1194
+
1195
+ /** 启动基线的代价核算(P81/D4):启动那一刻 spool 里已经完整、但没有任何日志记录的行,
1196
+ * 仍然按 doctrine 被基线吞掉(不唤醒)—— 但不再静默:只计数,不改 `started … baseline=` 契约。 */
1197
+ const baselineSwallowed = (): void => {
1198
+ let n = 0
1199
+ try {
1200
+ const res = readNewLines(spool, 0)
1201
+ for (const raw of res.lines) {
1202
+ const identity = lineIdentity(raw)
1203
+ if (delivered.has(identity) || journalEntries.has(identity)) continue
1204
+ n++
1205
+ }
1206
+ } catch { /* 读不到就当 0:核算绝不把会话搞崩 */ }
1207
+ appendLedger(root, `baseline swallowed n=${n} inbox=${inbox}(启动时完整行里没有任何日志记录的行;基线仍是 spool 末尾)`)
1208
+ }
1209
+
1210
+ /** 读 spool 的新行并合并成一条唤醒(同一拍收到的多行只叫一次)。
1211
+ * 日志写不进去时 `deliverNormal` 返回 blocked:offset 不动,行保持未读(下一拍重读)。 */
1212
+ const flush = (): void => {
1213
+ if (!spool) return
1214
+ try { runRetryTick() } catch { /* ignore */ }
1215
+ try { runRecoveryTick() } catch { /* ignore */ }
1216
+ const res = readNewLines(spool, offset)
1217
+ if (res.shrank) {
1218
+ // M43:spool 变小/消失了 —— 仓内写路径只有 `>>` 追加,变小一定是外部力量(截断/重写/替换)。
1219
+ // 旧行为在这里静默 offset=0,下一拍把整个 spool 从 0 重读(2026-09-19 的 42 行双投事故)。
1220
+ // P28/B2:先看证据(头部 + 回退幅度 + 上次的事件),小回退是修复,其余才是有界重扫。
1221
+ handleShrink()
1222
+ return
1223
+ }
1224
+ if (res.lines.length > 0) {
1225
+ const state = deliverNormal(res.lines, { off: res.offset, size: res.size, head: headStamp(readHead(spool, res.size)) })
1226
+ if (state === 'blocked') return // fail-closed:行保持未读,offset 不动
1227
+ }
1228
+ const advanced = res.offset > offset
1229
+ offset = res.offset
1230
+ if (res.resync > 0) {
1231
+ // B1.2:读取起点落在行中 —— 碎片被跳过(它的旧行早就投递过),只记账本,不唤醒
1232
+ appendLedger(root, `offset resync skipped=${res.resync} inbox=${inbox}`)
1233
+ }
1234
+ if (advanced) headBytes = readHead(spool, res.size) // offset 建立时记下头部证据
1235
+ if (res.lines.length > 0) lastShrink = null // 正常推进(读到完整行)= 上一个 shrink 事件结束
1236
+ const trimmed = trimSpool(spool)
1237
+ if (trimmed >= 0) {
1238
+ offset = trimmed // 裁剪后 size 变小:offset 对上新大小,避免把尾部重叫一次
1239
+ headBytes = readHead(spool, trimmed)
1240
+ lastShrink = null
1241
+ }
1242
+ }
1243
+
1244
+ const scheduleFlush = (): void => {
1245
+ if (mergeTimer) return
1246
+ mergeTimer = setTimeout(() => {
1247
+ mergeTimer = null
1248
+ try { flush() } catch { /* ignore */ } finally { armFileWatcher() }
1249
+ }, MERGE_MS)
1250
+ }
1251
+
1252
+ /** Bun 实测(harness S2/S3):目录 watcher 在 spool 被**创建**之后会静默丢掉它的逐文件事件
1253
+ * (之后对 spool 的追加一个都不报),而同一个进程里对 spool 的文件级 watch 照常工作。
1254
+ * spool 只被 `>>` 追加(inode 不变),所以文件级 watcher 一旦 arm 上就长期有效;
1255
+ * 目录 watcher 继续负责「文件还不存在」那一刻的创建事件,轮询是兜底。 */
1256
+ const armFileWatcher = (): void => {
1257
+ try { fileWatcher?.close?.() } catch { /* ignore */ }
1258
+ fileWatcher = null
1259
+ if (!spool || !existsSync(spool)) return
1260
+ try { fileWatcher = watch(spool, () => { scheduleFlush() }) } catch { /* 目录 watcher 与轮询兜底仍在 */ }
1261
+ }
1262
+
1263
+ /** 本地管家的清场:注册文件里 pid 已死的条目删掉(不让陈旧注册把发送方骗走)。 */
1264
+ const reapDeadRegs = (dir: string, self: string): void => {
1265
+ try {
1266
+ for (const name of readdirSync(dir)) {
1267
+ if (!name.endsWith('.reg')) continue
1268
+ const file = join(dir, name)
1269
+ if (file === self) continue
1270
+ const m = /^pid=(\d+)$/m.exec(readFileSync(file, 'utf8'))
1271
+ if (!m) continue
1272
+ try { process.kill(Number(m[1]), 0) } catch { rmSync(file, { force: true }) }
1273
+ }
1274
+ } catch {
1275
+ /* ignore */
1276
+ }
1277
+ }
1278
+
1279
+ pi.on('session_start', async (_event: any, ctx: any) => {
1280
+ stopAll()
1281
+ root = findRoot(String(ctx?.cwd ?? process.cwd()))
1282
+ if (!root) return
1283
+ noteIdentityFileConflicts(root)
1284
+ const found = resolveTarget()
1285
+ if (!found) {
1286
+ appendLedger(root, 'skip setup: no tmux target (set TEAM_INBOX_WATCH_TARGET to override)')
1287
+ return
1288
+ }
1289
+ if (found.session !== cfgSession(root)) {
1290
+ // 不是本团队的 session:绝不接管(跨项目的窗口不归这里管)。M46:跳过也留本项目可见的痕迹。
1291
+ // 注意 TEAM_INBOX_WATCH_TARGET 只是「从哪里读 target」的旋钮(headless/夹具),**不改**
1292
+ // 「哪个会话才是本项目的」——显式覆盖进来的外来会话同样拒绝(隐式与显式两个入口同一扇门)。
1293
+ const expect = cfgSession(root)
1294
+ const detail = `session ${found.session} != ${expect}`
1295
+ appendLedger(root, `skip setup: ${detail}`)
1296
+ writeSkipRecord(root, found.target, {
1297
+ session: found.session, window: found.window, expect, inbox: inboxName(found.window, root),
1298
+ reason: 'session-mismatch', detail,
1299
+ })
1300
+ return
1301
+ }
1302
+ const dir = watchDir(root)
1303
+ try { mkdirSync(dir, { recursive: true }) } catch { /* ignore */ }
1304
+ keyTarget = found.target
1305
+ key = targetKey(found.target)
1306
+ inbox = inboxName(found.window, root)
1307
+ spool = join(dir, `${key}.wake`)
1308
+ reg = join(dir, `${key}.reg`)
1309
+ journalPath = join(dir, `${key}.deliver`)
1310
+ seenPath = join(dir, `${key}.seen`)
1311
+ startedAt = new Date().toISOString()
1312
+ // 基线:启动之前写入的行不叫醒任何人(backlog 是 pulse 的活)—— P81 不改变这条 doctrine,
1313
+ // 只把它的代价数出来(baseline swallowed)
1314
+ offset = baselineOffset(spool)
1315
+ headBytes = readHead(spool, fileSize(spool))
1316
+ lastShrink = null
1317
+ seen = 0
1318
+ delivered = new Set()
1319
+ journalEntries = new Map()
1320
+ retryQueue = new Map()
1321
+ recoveryQueue = new Map()
1322
+ floorTs = null
1323
+ floorId = ''
1324
+ journalRecords = 0
1325
+ seqCounter = 1
1326
+ // P81:投递日志是唯一 durable 去重权威。首次启动把老代码的 `.seen` 一次性导入 ——
1327
+ // 此后删掉/清空它不再影响任何投递决定。
1328
+ if (!existsSync(journalPath)) {
1329
+ const imported = importSeen()
1330
+ if (imported > 0) appendLedger(root, `seen import n=${imported} inbox=${inbox}(一次性:此后投递日志是唯一去重记忆)`)
1331
+ }
1332
+ const loaded = loadJournal(journalPath)
1333
+ journalEntries = loaded.entries
1334
+ floorTs = loaded.floorTs
1335
+ floorId = loaded.floorId
1336
+ journalRecords = loaded.records
1337
+ seqCounter = Math.max(1, loaded.maxSeq + 1)
1338
+ // 重启后的三态判定(只从日志,绝不从内存):sent → 永不;intent 无结论 → inflight assumed(含撕裂尾);
1339
+ // read 无 intent → 恰好一次 recovery;failed → 每拍至多重试一次
1340
+ let assumed = 0
1341
+ for (const [identity, entry] of loaded.entries) {
1342
+ if (entry.state === 'sent' || entry.state === 'intent') {
1343
+ delivered.add(identity)
1344
+ if (entry.state === 'intent') assumed++
1345
+ } else if (entry.state === 'read') {
1346
+ if (entry.material) recoveryQueue.set(identity, entry.material)
1347
+ } else if (entry.state === 'failed') {
1348
+ if (entry.material) retryQueue.set(identity, entry.material)
1349
+ }
1350
+ }
1351
+ if (loaded.torn) {
1352
+ appendLedger(root, `torn tail inbox=${inbox}(日志尾部有半截记录:结果未知,绝不重投)`)
1353
+ for (const identity of [...recoveryQueue.keys()]) {
1354
+ recoveryQueue.delete(identity)
1355
+ delivered.add(identity)
1356
+ assumed++
1357
+ }
1358
+ }
1359
+ if (assumed > 0) appendLedger(root, `inflight assumed n=${assumed} inbox=${inbox}(intent 无 sent/failed:结果未知,永不重投)`)
1360
+ // 夹具注入点:裸设(没有 TEAM_SMOKE_FIXTURE=1)无效,并留一行「被忽略」的痕迹
1361
+ const abortEnv = (process.env.TEAM_INBOX_WATCH_ABORT_AFTER || '').trim()
1362
+ abortAt = ''
1363
+ if (abortEnv) {
1364
+ if (process.env.TEAM_SMOKE_FIXTURE === '1' && (abortEnv === 'read' || abortEnv === 'intent')) abortAt = abortEnv
1365
+ else appendLedger(root, `fixture knob ignored: TEAM_INBOX_WATCH_ABORT_AFTER=${abortEnv}(需要 TEAM_SMOKE_FIXTURE=1)`)
1366
+ }
1367
+ reapDeadRegs(dir, reg)
1368
+ clearSkipRecords(root, keyTarget) // M46:注册成功 = 这个 target 不再降级,旧痕迹不骗人
1369
+ clearDegradedRecords(root, keyTarget) // M53:上一次失败留下的记录同样不再成立
1370
+ writeReg('ready')
1371
+ appendLedger(root, `started target=${keyTarget} inbox=${inbox} spool=${spool} baseline=${offset}`)
1372
+ // P81 · 启动记录(审计:这一任读者从哪里起步)+ 越界就压缩(写下 floor)
1373
+ if (!journalAppend(`start baseline=${offset} size=${fileSize(spool)} head=${headStamp(headBytes)}`)) {
1374
+ appendLedger(root, `deliver blocked inbox=${inbox}(启动时投递日志写不进去 → 本次会话一条都不发)`)
1375
+ }
1376
+ maybeCompact()
1377
+ baselineSwallowed()
1378
+ runRecoveryTick()
1379
+ // M53 · 失败不再静默:errno + 额度观察 + 轮询间隔进账本,并写一条耐久降级记录(读的人看 pid+cwd)。
1380
+ // 夹具旋钮强制失败时同样走这条路径(evidence 里带 forced=1,免得测试事故被当成真事故)。
1381
+ const forced = forcedWatchErrno()
1382
+ if (forced) {
1383
+ recordWatchFailure(root, keyTarget, forced, true)
1384
+ } else {
1385
+ try {
1386
+ watcher = watch(dir, (_type: string, filename: string | null) => {
1387
+ if (filename && basename(String(filename)) !== `${key}.wake`) return
1388
+ scheduleFlush()
1389
+ })
1390
+ } catch (error) {
1391
+ recordWatchFailure(root, keyTarget, watchErrnoOf(error), false)
1392
+ }
1393
+ }
1394
+ armFileWatcher() // spool 可能早已存在(上一任会话留下的):文件级 watcher 现在就 arm 上
1395
+ pollTimer = setInterval(() => { try { flush() } catch { /* ignore */ } }, pollMs())
1396
+ beatTimer = setInterval(() => { try { writeReg('ready') } catch { /* ignore */ } }, heartbeatMs())
1397
+ })
1398
+
1399
+ pi.on('session_shutdown', async () => {
1400
+ stopAll()
1401
+ if (reg) {
1402
+ try { rmSync(reg, { force: true }) } catch { /* ignore */ }
1403
+ appendLedger(root, `stopped target=${keyTarget} inbox=${inbox}`)
1404
+ }
1405
+ // M53:干净退出 = 这条降级不再成立(下一次会话会重新注册,或重新记录一次失败)
1406
+ if (keyTarget) clearDegradedRecords(root, keyTarget)
1407
+ root = ''; key = ''; inbox = ''; spool = ''; reg = ''; offset = 0
1408
+ headBytes = null; lastShrink = null
1409
+ journalPath = ''; journalEntries = new Map(); retryQueue = new Map(); recoveryQueue = new Map()
1410
+ delivered = new Set(); floorTs = null; floorId = ''; journalRecords = 0; abortAt = ''
1411
+ })
1412
+ }