teamsmith 0.0.0-stage → 0.1.2

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 (245) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +158 -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 +763 -0
  7. package/skills/teamsmith/SKILL.md +312 -0
  8. package/skills/teamsmith/extension/team-bg.ts +435 -0
  9. package/skills/teamsmith/extension/team-inbox-watch.ts +1412 -0
  10. package/skills/teamsmith/extension/team-notify.ts +663 -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 +222 -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/bg-ledger-harness.mjs +682 -0
  81. package/skills/teamsmith/tests/bg-ledger.sh +307 -0
  82. package/skills/teamsmith/tests/checkout-shape-probe.sh +800 -0
  83. package/skills/teamsmith/tests/config-cli.sh +1562 -0
  84. package/skills/teamsmith/tests/container-tmux.sh +493 -0
  85. package/skills/teamsmith/tests/coverage-inventory.sh +173 -0
  86. package/skills/teamsmith/tests/death-cause.sh +564 -0
  87. package/skills/teamsmith/tests/delivery-truth.sh +1231 -0
  88. package/skills/teamsmith/tests/fake-tui.py +450 -0
  89. package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +60 -0
  90. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +139 -0
  91. package/skills/teamsmith/tests/fixtures/delivery-truth-real/mock-server.py +29 -0
  92. package/skills/teamsmith/tests/fixtures/delivery-truth-real/observe.ts +20 -0
  93. package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +79 -0
  94. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +175 -0
  95. package/skills/teamsmith/tests/fixtures/p55/flip-p49.sh +229 -0
  96. package/skills/teamsmith/tests/fixtures/p71-incident/README.md +22 -0
  97. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.seen +8 -0
  98. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.wake +9 -0
  99. package/skills/teamsmith/tests/fixtures/p71-incident/pm-nudges.wake +3 -0
  100. package/skills/teamsmith/tests/fixtures/signal-lint-cases.txt +40 -0
  101. package/skills/teamsmith/tests/flip-glue.sh +162 -0
  102. package/skills/teamsmith/tests/flip-m12-26c.sh +129 -0
  103. package/skills/teamsmith/tests/flip-m12.sh +185 -0
  104. package/skills/teamsmith/tests/flip-m16.sh +166 -0
  105. package/skills/teamsmith/tests/flip-m17.sh +204 -0
  106. package/skills/teamsmith/tests/flip-m33.sh +284 -0
  107. package/skills/teamsmith/tests/flip-m34.sh +96 -0
  108. package/skills/teamsmith/tests/flip-m37.sh +185 -0
  109. package/skills/teamsmith/tests/flip-m4.3.sh +375 -0
  110. package/skills/teamsmith/tests/flip-m43.sh +128 -0
  111. package/skills/teamsmith/tests/flip-m44.sh +262 -0
  112. package/skills/teamsmith/tests/flip-m45.sh +244 -0
  113. package/skills/teamsmith/tests/flip-m46.sh +238 -0
  114. package/skills/teamsmith/tests/flip-m48.sh +304 -0
  115. package/skills/teamsmith/tests/flip-m6.2.sh +205 -0
  116. package/skills/teamsmith/tests/flip-m6.3.sh +283 -0
  117. package/skills/teamsmith/tests/flip-m6.4.sh +267 -0
  118. package/skills/teamsmith/tests/flip-m6.5.sh +113 -0
  119. package/skills/teamsmith/tests/flip-m7.1.sh +135 -0
  120. package/skills/teamsmith/tests/flip-m7.2.sh +321 -0
  121. package/skills/teamsmith/tests/flip-p144.sh +112 -0
  122. package/skills/teamsmith/tests/flip-p156.sh +133 -0
  123. package/skills/teamsmith/tests/flip-p158.sh +301 -0
  124. package/skills/teamsmith/tests/flip-p160.sh +182 -0
  125. package/skills/teamsmith/tests/flip-p171.sh +249 -0
  126. package/skills/teamsmith/tests/flip-p18.1.sh +95 -0
  127. package/skills/teamsmith/tests/flip-p20.sh +286 -0
  128. package/skills/teamsmith/tests/flip-p201.sh +249 -0
  129. package/skills/teamsmith/tests/flip-p210.sh +239 -0
  130. package/skills/teamsmith/tests/flip-p211.sh +152 -0
  131. package/skills/teamsmith/tests/flip-p217.sh +288 -0
  132. package/skills/teamsmith/tests/flip-p22.sh +123 -0
  133. package/skills/teamsmith/tests/flip-p23.sh +239 -0
  134. package/skills/teamsmith/tests/flip-p25.sh +165 -0
  135. package/skills/teamsmith/tests/flip-p71.sh +184 -0
  136. package/skills/teamsmith/tests/flip-p72.sh +202 -0
  137. package/skills/teamsmith/tests/frames/README.md +176 -0
  138. package/skills/teamsmith/tests/frames/p78-conversation-rule-below-box.txt +6 -0
  139. package/skills/teamsmith/tests/frames/p78-cursor-mid-draft.txt +6 -0
  140. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor-line.txt +6 -0
  141. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor.txt +6 -0
  142. package/skills/teamsmith/tests/frames/p78-draft-rule-blank-region.txt +6 -0
  143. package/skills/teamsmith/tests/frames/p78-draft-rule-only.txt +5 -0
  144. package/skills/teamsmith/tests/frames/p78-spinner-row-below-cursor.txt +6 -0
  145. package/skills/teamsmith/tests/frames/p78-wider-rule-below-cursor.txt +6 -0
  146. package/skills/teamsmith/tests/frames/p86-f1-mixed-width-disjoint-box.txt +8 -0
  147. package/skills/teamsmith/tests/frames/p86-f1-narrower-width-disjoint-box.txt +8 -0
  148. package/skills/teamsmith/tests/frames/p86-f1-spinner-top-disjoint-box.txt +8 -0
  149. package/skills/teamsmith/tests/frames/pi-0.85.1-update-banner.txt +30 -0
  150. package/skills/teamsmith/tests/frames/pi-0.87.0-draft-half-sentence.txt +30 -0
  151. package/skills/teamsmith/tests/frames/pi-0.87.0-empty-box.txt +30 -0
  152. package/skills/teamsmith/tests/frames/pi-0.87.0-one-line-draft.txt +30 -0
  153. package/skills/teamsmith/tests/frames/pi-0.87.0-project-trust-prompt.txt +30 -0
  154. package/skills/teamsmith/tests/frames/pi-0.99.2-empty-editor.txt +32 -0
  155. package/skills/teamsmith/tests/frames/pi-0.99.2-human-draft.txt +32 -0
  156. package/skills/teamsmith/tests/frames/pi-1.0.0-git-error-in-box.txt +32 -0
  157. package/skills/teamsmith/tests/gate-guard.sh +112 -0
  158. package/skills/teamsmith/tests/guard-matrix.sh +233 -0
  159. package/skills/teamsmith/tests/install-shape.sh +731 -0
  160. package/skills/teamsmith/tests/ledger-ban.sh +612 -0
  161. package/skills/teamsmith/tests/lib/box-judge.sh +68 -0
  162. package/skills/teamsmith/tests/lib/checkout-shape.sh +129 -0
  163. package/skills/teamsmith/tests/lib/loop-scan.awk +114 -0
  164. package/skills/teamsmith/tests/lib/pty-wait.sh +676 -0
  165. package/skills/teamsmith/tests/lib/section-guard.sh +855 -0
  166. package/skills/teamsmith/tests/lib/shell-lex.pl +261 -0
  167. package/skills/teamsmith/tests/lib/tmp-root.sh +528 -0
  168. package/skills/teamsmith/tests/lib/tmux-cap.sh +35 -0
  169. package/skills/teamsmith/tests/lib/tmux-iso-call-probe.sh +81 -0
  170. package/skills/teamsmith/tests/lib/tmux-iso-probe.sh +46 -0
  171. package/skills/teamsmith/tests/lib/tmux-iso.sh +381 -0
  172. package/skills/teamsmith/tests/load-experiment.sh +290 -0
  173. package/skills/teamsmith/tests/loop-inventory.tsv +84 -0
  174. package/skills/teamsmith/tests/panel-b2-slow-stub.sh +19 -0
  175. package/skills/teamsmith/tests/panel-b2.sh +1183 -0
  176. package/skills/teamsmith/tests/panel-b3-pty-mouse.py +240 -0
  177. package/skills/teamsmith/tests/panel-b3-pty-tmux-mouse.py +138 -0
  178. package/skills/teamsmith/tests/panel-b3-stub.sh +279 -0
  179. package/skills/teamsmith/tests/panel-b3.sh +1301 -0
  180. package/skills/teamsmith/tests/panel-choices.sh +572 -0
  181. package/skills/teamsmith/tests/panel-clipboard-model.ts +187 -0
  182. package/skills/teamsmith/tests/panel-compose-model.ts +290 -0
  183. package/skills/teamsmith/tests/panel-contrast.mjs +81 -0
  184. package/skills/teamsmith/tests/panel-cpu-premise.sh +173 -0
  185. package/skills/teamsmith/tests/panel-cpu.sh +391 -0
  186. package/skills/teamsmith/tests/panel-flip-m54.sh +207 -0
  187. package/skills/teamsmith/tests/panel-flip-p123.sh +278 -0
  188. package/skills/teamsmith/tests/panel-flip-p125.sh +318 -0
  189. package/skills/teamsmith/tests/panel-flip-p128.sh +259 -0
  190. package/skills/teamsmith/tests/panel-keyprobe-pty.py +99 -0
  191. package/skills/teamsmith/tests/panel-keyprobe-stub.sh +41 -0
  192. package/skills/teamsmith/tests/panel-keyprobe.sh +82 -0
  193. package/skills/teamsmith/tests/panel-keyprobe.tsx +116 -0
  194. package/skills/teamsmith/tests/panel-knobs.sh +83 -0
  195. package/skills/teamsmith/tests/panel-p21.sh +2181 -0
  196. package/skills/teamsmith/tests/panel-snapshots.sh +802 -0
  197. package/skills/teamsmith/tests/panel-strings.mjs +195 -0
  198. package/skills/teamsmith/tests/perf.sh +740 -0
  199. package/skills/teamsmith/tests/pm-box-real.sh +350 -0
  200. package/skills/teamsmith/tests/pulse-nudge-key.sh +563 -0
  201. package/skills/teamsmith/tests/routes.sh +1652 -0
  202. package/skills/teamsmith/tests/section-budgets.tsv +150 -0
  203. package/skills/teamsmith/tests/section-guard.sh +231 -0
  204. package/skills/teamsmith/tests/section-needs-audit.sh +94 -0
  205. package/skills/teamsmith/tests/section-paths.tsv +142 -0
  206. package/skills/teamsmith/tests/section-select.sh +655 -0
  207. package/skills/teamsmith/tests/signal-gate.sh +366 -0
  208. package/skills/teamsmith/tests/signal-lint-legacy.txt +14 -0
  209. package/skills/teamsmith/tests/signal-lint.pl +416 -0
  210. package/skills/teamsmith/tests/skill-load.mjs +65 -0
  211. package/skills/teamsmith/tests/smoke.sh +19711 -0
  212. package/skills/teamsmith/tests/snapshots/zh-dark-120-detail.txt +32 -0
  213. package/skills/teamsmith/tests/snapshots/zh-dark-120-p4.txt +32 -0
  214. package/skills/teamsmith/tests/snapshots/zh-dark-120.txt +32 -0
  215. package/skills/teamsmith/tests/snapshots/zh-dark-160-p4.txt +32 -0
  216. package/skills/teamsmith/tests/snapshots/zh-dark-160.txt +32 -0
  217. package/skills/teamsmith/tests/snapshots/zh-dark-59-detail.txt +32 -0
  218. package/skills/teamsmith/tests/snapshots/zh-dark-59-p4.txt +32 -0
  219. package/skills/teamsmith/tests/snapshots/zh-dark-59.txt +32 -0
  220. package/skills/teamsmith/tests/snapshots/zh-dark-99-p4.txt +32 -0
  221. package/skills/teamsmith/tests/snapshots/zh-dark-99.txt +32 -0
  222. package/skills/teamsmith/tests/snapshots/zh-light-120-detail.txt +32 -0
  223. package/skills/teamsmith/tests/snapshots/zh-light-120-p4.txt +32 -0
  224. package/skills/teamsmith/tests/snapshots/zh-light-120.txt +32 -0
  225. package/skills/teamsmith/tests/snapshots/zh-light-160-p4.txt +32 -0
  226. package/skills/teamsmith/tests/snapshots/zh-light-160.txt +32 -0
  227. package/skills/teamsmith/tests/snapshots/zh-light-59-detail.txt +32 -0
  228. package/skills/teamsmith/tests/snapshots/zh-light-59-p4.txt +32 -0
  229. package/skills/teamsmith/tests/snapshots/zh-light-59.txt +32 -0
  230. package/skills/teamsmith/tests/snapshots/zh-light-99-p4.txt +32 -0
  231. package/skills/teamsmith/tests/snapshots/zh-light-99.txt +32 -0
  232. package/skills/teamsmith/tests/spec-ledger-refs.tsv +78 -0
  233. package/skills/teamsmith/tests/spec-refs.sh +826 -0
  234. package/skills/teamsmith/tests/task-header-model.sh +267 -0
  235. package/skills/teamsmith/tests/team-bg-flip.sh +239 -0
  236. package/skills/teamsmith/tests/team-bg-harness.mjs +392 -0
  237. package/skills/teamsmith/tests/team-bg-stop.sh +434 -0
  238. package/skills/teamsmith/tests/team-inbox-watch-flip.sh +191 -0
  239. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +1559 -0
  240. package/skills/teamsmith/tests/tmp-hygiene.sh +1190 -0
  241. package/skills/teamsmith/tests/tmux-lint-legacy.txt +31 -0
  242. package/skills/teamsmith/tests/tmux-lint.pl +604 -0
  243. package/skills/teamsmith-init/SKILL.md +100 -0
  244. package/skills/teamsmith-init/references/bootstrap.md +74 -0
  245. package/skills/teamsmith-init/templates/bootstrap-prompt.md.tmpl +46 -0
@@ -0,0 +1,1559 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * teamsmith · team-inbox-watch 扩展的确定性夹具(M30)
4
+ *
5
+ * <node|bun> team-inbox-watch-harness.mjs <skill>/extension/team-inbox-watch.ts [--keep]
6
+ *
7
+ * 为什么用「假 Pi 宿主」而不是真模型:本夹具要证的是**扩展自己的契约**——注册文件(发送方据此判定
8
+ * 「目标是 pi 且有监视」)、spool 增量读取、合并成一条、只带指针不带 payload、会话级清理、账本格式。
9
+ * 这些完全由接口(on('session_start'/'session_shutdown') / sendMessage / 文件)决定,用真模型只会把判据
10
+ * 换成「模型有没有照着做」。真实的「唤醒一个空闲 pi 会话」由 E8 的 RPC 探针实证过(docs/team/reports/E8-verify/),
11
+ * 「pi 通道零 tmux 调用」由 smoke 12b/13d 的 tmux shim 实证。
12
+ *
13
+ * 隔离纪律(M7.2 的教训):继承来的团队身份/tmux 身份先清掉,TEAM_ROOT 显式指向临时仓库;每条断言都要求
14
+ * 产物落在临时仓库里;跑完再对比**真实仓库** state/ 的前后快照(反向守卫)。
15
+ *
16
+ * 每个用例打印一行 `TEAM-IW-CASE PASS|FAIL <name> [:: detail]`,任一 FAIL → 退出码 1。
17
+ */
18
+ import { execFileSync, spawnSync } from 'node:child_process'
19
+ import { createHash } from 'node:crypto'
20
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, watch, writeFileSync, appendFileSync } from 'node:fs'
21
+ import { tmpdir } from 'node:os'
22
+ import { join, resolve } from 'node:path'
23
+
24
+ const args = process.argv.slice(2)
25
+ const keep = args.includes('--keep') || process.env.TEAM_IW_KEEP === '1'
26
+ const ext = args.find(a => !a.startsWith('--'))
27
+ if (!ext) {
28
+ console.error('usage: team-inbox-watch-harness.mjs <path/to/team-inbox-watch.ts> [--keep]')
29
+ process.exit(2)
30
+ }
31
+ const EXT = resolve(ext)
32
+ const SKILL_DIR = resolve(EXT, '../..') // <skill>/extension/<file> → <skill>
33
+
34
+ // ── 身份隔离:绝不继承调用者的团队身份与 tmux 身份;但这四个**夹具控制**必须在清掉之前
35
+ // 快照、清完后只还原它们 —— 否则夹具自己的隔离会把「这次要强制失败」丢掉(有意制造的
36
+ // 故障被当成继承环境静默丢弃,这条正是 M53 要求说清楚的形状)。
37
+ const CONTROL_KEYS = ['TEAM_INBOX_WATCH_FORCE_FAIL', 'TEAM_IW_REQUIRE_WATCH', 'TEAM_IW_ONLY', 'TEAM_IW_KEEP',
38
+ 'TEAM_INBOX_WATCH_ABORT_AFTER', 'TEAM_SMOKE_FIXTURE',
39
+ 'TEAM_IW_CHILD_REPO', 'TEAM_IW_CHILD_TARGET', 'TEAM_IW_CHILD_KIND', 'TEAM_IW_CHILD_FROM', 'TEAM_IW_CHILD_INBOX', 'TEAM_IW_CHILD_PAYLOAD']
40
+ const CONTROLS = Object.fromEntries(CONTROL_KEYS.map(k => [k, process.env[k]]))
41
+ for (const key of Object.keys(process.env)) {
42
+ if (/^(TEAM_|SMOKE_)/.test(key) || key === 'TMUX' || key === 'TMUX_PANE') delete process.env[key]
43
+ }
44
+ for (const [k, v] of Object.entries(CONTROLS)) {
45
+ if (v === undefined) delete process.env[k]
46
+ else process.env[k] = v
47
+ }
48
+
49
+ // ── P81 · 崩溃子进程(夹具只在 TEAM_SMOKE_FIXTURE=1 下生效):父进程用 `--child` 启动同一个文件,
50
+ // 子进程跑一任真会话、追加一行 spool,然后由扩展的注入点(TEAM_INBOX_WATCH_ABORT_AFTER=read|intent)
51
+ // 在写前日志的那一步 SIGKILL 自己 —— 重启后的判定必须由日志(而不是内存)做出来。
52
+ if (args.includes('--child')) {
53
+ const repo = process.env.TEAM_IW_CHILD_REPO || ''
54
+ if (!repo) { console.error('harness --child: TEAM_IW_CHILD_REPO missing'); process.exit(2) }
55
+ process.env.TEAM_ROOT = repo
56
+ process.env.TEAM_INBOX_WATCH_TARGET = process.env.TEAM_IW_CHILD_TARGET || 'm30s:pm'
57
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '50'
58
+ process.env.TEAM_INBOX_WATCH_HEARTBEAT_MS = '200'
59
+ const cdir = join(repo, '.pi/team/state/inbox-watch')
60
+ const handlersC = {}
61
+ const factoryC = (await import(EXT)).default
62
+ factoryC({ on: (n, fn) => { (handlersC[n] ||= []).push(fn) }, registerTool() {}, registerCommand() {}, sendMessage: () => {} })
63
+ for (const fn of handlersC.session_start ?? []) await fn({ reason: 'startup' }, { cwd: repo })
64
+ const regC = readdirSync(cdir).find(f => f.endsWith('.reg'))
65
+ if (!regC) { console.error('harness --child: no .reg after session_start'); process.exit(2) }
66
+ appendFileSync(join(cdir, regC.replace(/\.reg$/, '.wake')),
67
+ `${Date.now()}\t${process.env.TEAM_IW_CHILD_KIND || 'say'}\t${process.env.TEAM_IW_CHILD_FROM || 'pm'}\t${process.env.TEAM_IW_CHILD_INBOX || 'pm'}\t${process.env.TEAM_IW_CHILD_PAYLOAD || 'child line'}\n`)
68
+ await new Promise(r => setTimeout(r, 4000))
69
+ console.error('harness --child: the abort knob never fired')
70
+ process.exit(3) // 走到这里 = 注入点没生效(父进程必须为此红)
71
+ }
72
+
73
+ // ── M53 前提:这个用户此刻能不能注册一个 watch(量它,不猜它)。只靠监视器唤醒的用例依赖它;
74
+ // TEAM_INBOX_WATCH_FORCE_FAIL 显式造出同一个不可用前提(不真去注册),并标 forced=1。
75
+ const FORCE_FAIL = (process.env.TEAM_INBOX_WATCH_FORCE_FAIL || '').trim()
76
+ let premise = { ok: true, errno: '', forced: false }
77
+ if (FORCE_FAIL) {
78
+ premise = { ok: false, errno: FORCE_FAIL, forced: true }
79
+ } else {
80
+ try {
81
+ const probeDir = mkdtempSync(join(tmpdir(), 'teamsmith-iw-prereq-'))
82
+ const probeWatcher = watch(probeDir, () => {})
83
+ probeWatcher.close()
84
+ rmSync(probeDir, { recursive: true, force: true })
85
+ } catch (error) {
86
+ premise = { ok: false, errno: String(error?.code ?? 'unknown'), forced: false }
87
+ }
88
+ }
89
+
90
+ // 前提行里的「额度观察」:与扩展同一条完整性规则(嵌套 PID 命名空间 / 读不到的 fdinfo → unknown)。
91
+ // 它只是前提行的上下文;判定权在前提本身(一次真注册),不在这个数。
92
+ function quotaObservation() {
93
+ let max = 'unknown'
94
+ try {
95
+ const t = readFileSync('/proc/sys/fs/inotify/max_user_watches', 'utf8').trim()
96
+ if (/^[0-9]+$/.test(t)) max = t
97
+ } catch { /* unknown */ }
98
+ let used = 'unknown'
99
+ try {
100
+ const ns = /^NSpid:\s*(.+)$/m.exec(readFileSync('/proc/self/status', 'utf8'))
101
+ if (ns && ns[1].trim().split(/\s+/).length === 1 && typeof process.getuid === 'function') {
102
+ const uid = process.getuid()
103
+ let total = 0
104
+ let complete = true
105
+ for (const entry of readdirSync('/proc')) {
106
+ if (!/^[0-9]+$/.test(entry)) continue
107
+ let owner
108
+ try { owner = statSync(`/proc/${entry}`).uid } catch { continue }
109
+ if (owner !== uid) continue
110
+ let fds
111
+ try { fds = readdirSync(`/proc/${entry}/fd`) } catch { complete = false; break }
112
+ for (const fd of fds) {
113
+ let link = ''
114
+ try { link = readlinkSync(`/proc/${entry}/fd/${fd}`) } catch { continue }
115
+ if (link !== 'anon_inode:inotify') continue
116
+ let info = ''
117
+ try { info = readFileSync(`/proc/${entry}/fdinfo/${fd}`, 'utf8') } catch { complete = false; break }
118
+ total += new Set([...info.matchAll(/^inotify wd:([0-9a-f]+)\s/gm)].map(m => m[1])).size
119
+ }
120
+ if (!complete) break
121
+ }
122
+ if (complete) used = String(total)
123
+ }
124
+ } catch { /* unknown */ }
125
+ return `${used}/${max}`
126
+ }
127
+
128
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms))
129
+ let failures = 0
130
+ let skipped = 0
131
+ const STRICT = /^(1|y|yes|true|on)$/i.test(String(process.env.TEAM_IW_REQUIRE_WATCH ?? ''))
132
+ const ONLY = new Set(String(process.env.TEAM_IW_ONLY ?? '').split(',').map(x => x.trim()).filter(Boolean))
133
+ const caseId = (name) => (name.match(/^[A-Za-z0-9][\w.-]*/) ?? [''])[0]
134
+ const only = (id) => ONLY.size === 0 || ONLY.has(id)
135
+ // 只靠监视器唤醒的用例(**逐字的名单**,不看启发式):前提不可用时既不算 PASS 也不算 FAIL。
136
+ // 前缀匹配;S24 的两条「成功注册」断言只依赖真 watcher,单独列出(同用例的强制失败部分照跑)。
137
+ const WATCH_DEPENDENT = [
138
+ 'S2 ', 'S3 ', 'S4 ', 'S5 ', 'S6 ', 'S9 ', 'S10 ', 'S11 ', 'S12 ', 'S13 ', 'S21',
139
+ 'S24 a healthy session writes no degraded record',
140
+ 'S24 a successful registration clears a stale degraded record',
141
+ ]
142
+ const isWatchDependent = (name) => WATCH_DEPENDENT.some(p => name.startsWith(p))
143
+ const check = (name, ok, detail = '') => {
144
+ if (!only(caseId(name))) return // TEAM_IW_ONLY:不选中的用例不打印、不计数(也不许悄悄算绿)
145
+ if (!premise.ok && isWatchDependent(name)) {
146
+ if (STRICT) {
147
+ console.log(`TEAM-IW-CASE FAIL ${name} :: watch premise unavailable (errno=${premise.errno}${premise.forced ? ', forced=1' : ''}) and TEAM_IW_REQUIRE_WATCH=1`)
148
+ failures++
149
+ } else {
150
+ console.log(`TEAM-IW-CASE SKIP ${name} :: watch unavailable (errno=${premise.errno}${premise.forced ? ', forced=1' : ''})`)
151
+ skipped++
152
+ }
153
+ return
154
+ }
155
+ console.log(`TEAM-IW-CASE ${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` :: ${detail}` : ''}`)
156
+ if (!ok) failures++
157
+ }
158
+ async function waitFor(fn, ms = 3000, step = 25) {
159
+ const t0 = Date.now()
160
+ for (;;) {
161
+ try { if (fn()) return true } catch { /* ignore */ }
162
+ if (Date.now() - t0 > ms) return false
163
+ await sleep(step)
164
+ }
165
+ }
166
+
167
+ console.log(premise.ok
168
+ ? `TEAM-IW-PREREQ watch=ok forced=0 strict=${STRICT ? 1 : 0}`
169
+ : `TEAM-IW-PREREQ watch=errno=${premise.errno} watches=${quotaObservation()} forced=${premise.forced ? 1 : 0} strict=${STRICT ? 1 : 0}`)
170
+
171
+ // ── 夹具仓库(有 .pi/team/config.sh 的 git 仓库;findRoot 走 git 主工作树那一支)────────
172
+ const TMP = mkdtempSync(join(tmpdir(), 'teamsmith-iw-'))
173
+ const ROOT = join(TMP, 'repo')
174
+ mkdirSync(join(ROOT, '.pi/team'), { recursive: true })
175
+ mkdirSync(join(ROOT, 'docs/team/inbox'), { recursive: true })
176
+ process.env.TEAM_ROOT = ROOT
177
+ process.env.TEAM_INBOX_WATCH_TARGET = 'm30s:pm' // headless 夹具:显式 target(不查 tmux)
178
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '3600000' // 先关掉轮询兜底:这一段只允许 fs.watch 叫醒
179
+ process.env.TEAM_INBOX_WATCH_HEARTBEAT_MS = '200'
180
+ process.env.TEAM_INBOX_WATCH_PREVIEW = '60'
181
+ if (!keep) process.on('exit', () => { try { rmSync(TMP, { recursive: true, force: true }) } catch {} })
182
+ try { execFileSync('git', ['init', '-q', '-b', 'main', ROOT], { stdio: 'ignore' }) } catch {}
183
+ writeFileSync(join(ROOT, ".pi/team/config.sh"),
184
+ 'TEAM_PROJECT="iw-harness"\nTEAM_SESSION="m30s"\nTEAM_PM_WINDOW="pm"\nTEAM_DOCS_DIR="docs/team"\n')
185
+ const STATE = join(ROOT, '.pi/team/state')
186
+ const WATCH_DIR = join(STATE, 'inbox-watch')
187
+ const LEDGER = join(STATE, 'inbox-watch.log')
188
+
189
+ // ── 反向守卫:真实仓库 state/ 前后快照 ────────────────────────────────────────
190
+ const REAL_REPO = resolve(EXT, '../../..') // <repo>/skills/teamsmith/extension/team-inbox-watch.ts
191
+ const snapshot = (dir) => {
192
+ if (!existsSync(dir)) return 'absent'
193
+ const walk = (d) => readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap(e =>
194
+ e.isDirectory() ? walk(join(d, e.name)) : [`${join(d, e.name)}:${statSync(join(d, e.name)).size}:${statSync(join(d, e.name)).mtimeMs}`])
195
+ return walk(dir).join('\n')
196
+ }
197
+ const REAL_STATE = join(REAL_REPO, '.pi/team/state')
198
+ const REAL_BEFORE = snapshot(REAL_STATE)
199
+
200
+ // ── 假 Pi 宿主 ────────────────────────────────────────────────────────────────
201
+ const sent = []
202
+ let hostFail = 0 // S25c:下一批 sendMessage 抛错(会话 API 拒绝的夹具形状)
203
+ const handlers = {}
204
+ const api = {
205
+ on: (name, fn) => { (handlers[name] ||= []).push(fn) },
206
+ registerTool: () => {},
207
+ registerCommand: () => {},
208
+ sendMessage: (msg, opts) => {
209
+ if (hostFail > 0) { hostFail--; throw new Error('S25c fake host refused the message') }
210
+ sent.push({ msg, opts, at: Date.now() })
211
+ },
212
+ }
213
+ const emit = async (name, ...rest) => { for (const fn of handlers[name] ?? []) await fn(...rest) }
214
+ const ctx = { cwd: ROOT }
215
+ const captureKey = () => { const r = regs()[0]; if (r) KEY = r.replace(/\.reg$/, ''); return KEY }
216
+ const sessionStart = async () => { await emit('session_start', { reason: 'startup' }, ctx); captureKey() }
217
+ const shutdown = () => emit('session_shutdown', { reason: 'quit' }, ctx)
218
+
219
+ const regs = () => (existsSync(WATCH_DIR) ? readdirSync(WATCH_DIR).filter(f => f.endsWith('.reg')) : [])
220
+ const wakes = () => (existsSync(WATCH_DIR) ? readdirSync(WATCH_DIR).filter(f => f.endsWith('.wake')) : [])
221
+ // spool 与注册同名(只差后缀):先看真的 .wake,再从未删的 .reg 推导,最后用记住的路径 ——
222
+ // shutdown 之后还要能往同一个 spool 写「历史行」(S5)。P81 组在 resetState 后会先按住 KEY 再建文件。
223
+ let lastSpool = ''
224
+ let KEY = ''
225
+ const spoolFile = () => {
226
+ const w = wakes()[0]
227
+ if (w) return (lastSpool = join(WATCH_DIR, w))
228
+ const r = regs()[0]
229
+ if (r) return (lastSpool = join(WATCH_DIR, r.replace(/\.reg$/, '.wake')))
230
+ if (KEY) return (lastSpool = join(WATCH_DIR, `${KEY}.wake`))
231
+ return lastSpool
232
+ }
233
+ const appendWake = (kind, from, inbox, payload) => appendWakeAt(Date.now(), kind, from, inbox, payload)
234
+ const appendWakeAt = (ts, kind, from, inbox, payload) => {
235
+ mkdirSync(WATCH_DIR, { recursive: true })
236
+ const f = spoolFile()
237
+ if (!f) throw new Error('no spool file: the extension never registered')
238
+ appendFileSync(f, `${ts}\t${kind}\t${from}\t${inbox}\t${payload}\n`)
239
+ }
240
+ // P28/B1:原样追加字节(生产者的 `LC_ALL=C cut -c1-700` 会写出非法 UTF-8 的预览)——
241
+ // 夹具里用 Buffer 直写,保证测的是「spool 里有非法字节」这个形状,而不是 String 的往返。
242
+ const appendWakeRaw = (buf) => {
243
+ mkdirSync(WATCH_DIR, { recursive: true })
244
+ const f = spoolFile()
245
+ if (!f) throw new Error('no spool file: the extension never registered')
246
+ appendFileSync(f, buf)
247
+ }
248
+ const ledger = () => (existsSync(LEDGER) ? readFileSync(LEDGER, 'utf8').trim().split('\n') : [])
249
+ const ledgerMatches = (re) => ledger().filter(l => re.test(l)).length
250
+ const lastText = (i = -1) => String(sent.at(i)?.msg?.content ?? '')
251
+
252
+ // ── P81 · 投递日志的**独立**解析(不复用实现里的解析器:夹具自己按规格解一遍)────────────────
253
+ const jesc = (s) => String(s).replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/ /g, '\\s')
254
+ const junesc = (s) => String(s).replace(/\\(.)/g, (_m, c) => (c === 'n' ? '\n' : c === 'r' ? '\r' : c === 't' ? '\t' : c === 's' ? ' ' : c))
255
+ const jrec = (line) => {
256
+ const m = /^(\S+) (start|read|intent|sent|failed|floor)(?: (.*))?$/.exec(line)
257
+ if (!m) return null
258
+ const fields = {}
259
+ for (const tok of (m[3] ?? '').split(' ')) {
260
+ if (!tok) continue
261
+ const i = tok.indexOf('=')
262
+ if (i <= 0) return null
263
+ fields[tok.slice(0, i)] = junesc(tok.slice(i + 1))
264
+ }
265
+ return { ts: m[1], kind: m[2], fields }
266
+ }
267
+ const journalPathOf = () => { const f = spoolFile(); return f ? f.replace(/\.wake$/, '.deliver') : '' }
268
+ const journalLines = () => { const f = journalPathOf(); return f && existsSync(f) && statSync(f).isFile() ? readFileSync(f, 'utf8').split('\n').filter(l => l.trim()) : [] }
269
+ const journalOf = (kind) => journalLines().map(jrec).filter(r => r && r.kind === kind)
270
+ const spoolLines = () => { const f = spoolFile(); return f && existsSync(f) ? readFileSync(f, 'utf8').split('\n').filter(l => l.trim()) : [] }
271
+ /** 与实现同口径的行身份:发送方的 `id=` 字段优先,否则整行 sha1(夹具自己算,不读实现) */
272
+ const identityOf = (line) => {
273
+ const id = (String(line).split('\t')[5] ?? '').trim()
274
+ if (id) return id
275
+ return `sha1:${createHash('sha1').update(String(line), 'utf8').digest('hex')}`
276
+ }
277
+ /** 清空夹具状态(只动临时仓库):新用例(P81 组)拿一个干净日志,避免前面用例的账本/日志串味 */
278
+ const resetStateSync = () => {
279
+ rmSync(WATCH_DIR, { recursive: true, force: true })
280
+ rmSync(LEDGER, { force: true })
281
+ lastSpool = ''
282
+ }
283
+ const resetState = async () => {
284
+ await shutdown()
285
+ resetStateSync()
286
+ }
287
+ /** 子进程崩溃运行器:父进程在**另一个进程**里跑一任会话,在注入点真死(SIGKILL) */
288
+ const runChild = (abortAfter, payload) => {
289
+ const env = {
290
+ ...process.env,
291
+ TEAM_SMOKE_FIXTURE: '1',
292
+ TEAM_IW_CHILD_REPO: ROOT,
293
+ TEAM_IW_CHILD_TARGET: 'm30s:pm',
294
+ TEAM_IW_CHILD_PAYLOAD: payload,
295
+ TEAM_INBOX_WATCH_ABORT_AFTER: abortAfter,
296
+ }
297
+ return spawnSync(process.execPath, [...process.execArgv, resolve(process.argv[1]), EXT, '--child'],
298
+ { cwd: ROOT, env, encoding: 'utf8', timeout: 20000 })
299
+ }
300
+
301
+ if (!existsSync(EXT)) {
302
+ check('import', false, `extension missing: ${EXT}`)
303
+ console.log('TEAM-IW-HARNESS FAIL (extension missing — this is the pre-M30 shape)')
304
+ process.exit(1)
305
+ }
306
+ let factory
307
+ try {
308
+ factory = (await import(EXT)).default
309
+ } catch (error) {
310
+ check('import', false, String(error?.stack ?? error))
311
+ console.log('TEAM-IW-HARNESS FAIL (import)')
312
+ process.exit(1)
313
+ }
314
+ factory(api)
315
+ check('factory registers session_start / session_shutdown hooks',
316
+ (handlers.session_start ?? []).length > 0 && (handlers.session_shutdown ?? []).length > 0)
317
+ check('factory starts no session resource (no state/ before session_start)', !existsSync(WATCH_DIR) && !existsSync(LEDGER))
318
+ check('nothing is delivered before session_start', sent.length === 0)
319
+
320
+ // ── S1:session_start 写出注册(发送方据此判定「目标是 pi 且有监视」)────────────
321
+ await sessionStart()
322
+ spoolFile() // 注册后把 spool 路径记下来:被 TEAM_IW_ONLY 过滤掉的用例(S2…)不再替后面钉路径
323
+ check('S1 session_start creates exactly one .reg', regs().length === 1, `regs=${regs().length}`)
324
+ const regText = regs().length ? readFileSync(join(WATCH_DIR, regs()[0]), 'utf8') : ''
325
+ for (const [field, want] of [['target', 'm30s:pm'], ['inbox', 'pm'], ['cwd', ROOT]]) {
326
+ check(`S1 registry carries ${field}=${want}`, new RegExp(`^${field}=${want}$`, 'm').test(regText), regText.replace(/\n/g, ' | '))
327
+ }
328
+ const pid = Number(/^pid=(\d+)$/m.exec(regText)?.[1] ?? 0)
329
+ check('S1 registry pid is this live process', pid === process.pid, `pid=${pid}`)
330
+ check('S1 registry has a fresh heartbeat', (() => {
331
+ const hb = Number(/^heartbeat=(\d+)$/m.exec(regText)?.[1] ?? 0)
332
+ return hb > 0 && Math.abs(Math.floor(Date.now() / 1000) - hb) <= 2
333
+ })())
334
+
335
+ // 心跳确实在刷新(文件被重写、mtime 前进;heartbeat 字段是秒级,400ms 内可能看不出变化)
336
+ {
337
+ const regPath = join(WATCH_DIR, regs()[0])
338
+ const m0 = statSync(regPath).mtimeMs
339
+ process.env.TEAM_INBOX_WATCH_HEARTBEAT_MS = '100'
340
+ await sleep(500)
341
+ const m1 = statSync(regPath).mtimeMs
342
+ check('S1 heartbeat keeps refreshing the registry file', m1 > m0, `mtimeMs ${m0} -> ${m1}`)
343
+ process.env.TEAM_INBOX_WATCH_HEARTBEAT_MS = '200'
344
+ }
345
+
346
+ // ── S2:spool 新行 → 唤醒(fs.watch;轮询被关掉,所以红 = 没在监视)──────────────
347
+ if (only('S2')) {
348
+ const before = sent.length
349
+ appendWake('say', 'pm', 'pm', 'please read the failing test')
350
+ const ok = await waitFor(() => sent.length > before + 0)
351
+ check('S2 a new spool line wakes the session (fs.watch, polling disabled)', ok && sent.length === before + 1,
352
+ `messages=${sent.length - before}`)
353
+ check('S2 wake is a custom team-inbox message with triggerTurn+followUp',
354
+ sent.at(-1)?.msg?.customType === 'team-inbox' && sent.at(-1)?.opts?.triggerTurn === true && sent.at(-1)?.opts?.deliverAs === 'followUp',
355
+ JSON.stringify({ customType: sent.at(-1)?.msg?.customType, ...(sent.at(-1)?.opts ?? {}) }))
356
+ const body = lastText()
357
+ check('S2 wake is a pointer to the inbox file, not the payload', body.includes('docs/team/inbox/pm.md'), body.split('\n')[0])
358
+ check('S2 wake carries a one-line preview and says it is a pointer', body.includes('please read the failing test') && /one-line pointer/i.test(body))
359
+ }
360
+
361
+ // ── S3:同一拍的多行合并成一条(不按行刷屏) ─────────────────────────────────
362
+ if (only('S3')) {
363
+ const before = sent.length
364
+ mkdirSync(WATCH_DIR, { recursive: true })
365
+ for (const n of [1, 2, 3]) appendWake('say', 'dev', 'pm', `burst line ${n}`)
366
+ await sleep(600)
367
+ check('S3 a burst of three lines produces exactly one wake', sent.length === before + 1, `messages=${sent.length - before}`)
368
+ const body = lastText()
369
+ check('S3 the merged wake names every line', [1, 2, 3].every(n => body.includes(`burst line ${n}`)), body.replace(/\n/g, ' | '))
370
+ }
371
+
372
+ // ── S4:预览截断 + 每条约 4 行上限(只带指针,不带 payload 全文) ───────────────
373
+ if (only('S4')) {
374
+ const before = sent.length
375
+ const long = 'X'.repeat(400)
376
+ appendWake('knock', 'dev', 'pm', `${long}TAIL-MARKER`)
377
+ await sleep(500)
378
+ const body = lastText()
379
+ check('S4 long payload is truncated in the wake (no payload dump)', !body.includes('TAIL-MARKER') && body.includes('…'),
380
+ `len=${body.length}`)
381
+ const before2 = sent.length
382
+ for (let i = 0; i < 8; i++) appendWake('say', 'dev', 'pm', `many ${i}`)
383
+ await sleep(600)
384
+ check('S4 eight lines in one burst still produce one wake', sent.length === before2 + 1, `messages=${sent.length - before2}`)
385
+ const body2 = lastText()
386
+ check('S4 the wake lists at most 5 lines and says how many more', body2.includes('and 3 more'), body2.replace(/\n/g, ' | '))
387
+ }
388
+
389
+ // ── S5:启动基线(历史行不叫醒任何人;启动后的行才唤醒) ─────────────────────────
390
+ if (only('S5')) {
391
+ await shutdown()
392
+ const before = sent.length
393
+ appendWake('say', 'pm', 'pm', 'historical line written while nobody watched')
394
+ await sleep(400)
395
+ check('S5 no wake while shut down (timers closed)', sent.length === before, `messages=${sent.length - before}`)
396
+ await sessionStart()
397
+ // 基线 = 启动那一刻 spool 的字节数:账本行把这件事写成可直接复核的事实(setabline 的定点破坏必红在这条)
398
+ const startedLine = ledger().filter(l => / started target=/.test(l)).at(-1) ?? ''
399
+ const spoolSize = statSync(spoolFile()).size
400
+ check('S5 startup baseline equals the current spool size', startedLine.includes(`baseline=${spoolSize}`) && spoolSize > 0,
401
+ `${startedLine.trim()} (size=${spoolSize})`)
402
+ await sleep(600)
403
+ check('S5 a line written before session_start is baseline, not a wake', sent.length === before,
404
+ `messages=${sent.length - before}`)
405
+ appendWake('say', 'pm', 'pm', 'line after startup')
406
+ const ok = await waitFor(() => sent.length > before)
407
+ check('S5 a line after startup still wakes (from the previous offset)', ok && sent.length === before + 1,
408
+ `messages=${sent.length - before}`)
409
+ check('S5 the wake only mentions the new line', lastText().includes('line after startup') && !lastText().includes('historical line'))
410
+ }
411
+
412
+ // ── S6:spool 上限(截头留尾)不把尾部重叫一遍 ───────────────────────────────
413
+ if (only('S6')) {
414
+ process.env.TEAM_INBOX_WATCH_MAX_BYTES = '2048'
415
+ const before = sent.length
416
+ const f = spoolFile()
417
+ // P28:裁剪是读者自己的记账动作 —— offset 对上新大小之后,账本不该出现任何恢复行。
418
+ // 快照必须在裁剪**之前**取(M30 翻转包的 trim-offset 定点破坏就钉在这一条上)。
419
+ const recovery0 = ledgerMatches(/spool shrink/) + ledgerMatches(/ rescan lines=/) + ledgerMatches(/offset clamp/)
420
+ // 一条超长行 + 紧跟一条正常行:裁剪后尾部应当留下后者(而不是被整段丢掉)
421
+ appendFileSync(f, `huge\tknock\tdev\tpm\t${'Y'.repeat(4096)}\n`)
422
+ appendFileSync(f, 'kept\tknock\tdev\tpm\tkeep-me-after-trim\n')
423
+ await sleep(700)
424
+ check('S6 oversized spool content is delivered once (both lines in one wake)',
425
+ sent.length === before + 1 && lastText().includes('keep-me-after-trim'), `messages=${sent.length - before}`)
426
+ const size = statSync(f).size
427
+ check('S6 spool is trimmed under the cap and keeps the tail line',
428
+ size <= 2048 && readFileSync(f, 'utf8').includes('keep-me-after-trim'), `bytes=${size}`)
429
+ appendWake('say', 'pm', 'pm', 'after trim')
430
+ await sleep(700)
431
+ check('S6 the trim is reconciled locally (no spool shrink / rescan / clamp afterwards)',
432
+ ledgerMatches(/spool shrink/) + ledgerMatches(/ rescan lines=/) + ledgerMatches(/offset clamp/) === recovery0,
433
+ `${ledger().slice(-3).join(' | ')}`)
434
+ check('S6 exactly one new wake after the trim (tail line is not replayed)', sent.length === before + 2,
435
+ `messages=${sent.length - before}`)
436
+ check('S6 the post-trim wake is the new line', lastText().includes('after trim'), lastText().replace(/\n/g, ' | '))
437
+ delete process.env.TEAM_INBOX_WATCH_MAX_BYTES
438
+ }
439
+
440
+ // ── S7:session_shutdown 清场(删注册 + 停表)——不然发送方会一直以为有活监视器 ──
441
+ {
442
+ await shutdown()
443
+ await sleep(300)
444
+ check('S7 shutdown removes the registry file', regs().length === 0, `regs=${regs().length}`)
445
+ const before = sent.length
446
+ appendWake('say', 'pm', 'pm', 'after shutdown')
447
+ await sleep(600)
448
+ check('S7 no wake after shutdown', sent.length === before, `messages=${sent.length - before}`)
449
+ }
450
+
451
+ // ── S8:没有 tmux 目标就不注册(绝不假装自己是某个窗口的收件箱) ─────────────────
452
+ {
453
+ delete process.env.TEAM_INBOX_WATCH_TARGET
454
+ await sessionStart()
455
+ check('S8 without a tmux target nothing is registered', regs().length === 0, `regs=${regs().length}`)
456
+ check('S8 the ledger says why it skipped', ledger().some(l => /skip setup: no tmux target/.test(l)),
457
+ ledger().at(-1) ?? '(no ledger)')
458
+ await shutdown()
459
+ }
460
+
461
+ // ── S9:账本(state/inbox-watch.log:started / wake / stopped,每行 ISO 前缀) ──
462
+ {
463
+ const lines = ledger()
464
+ const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z /
465
+ check('S9 every ledger line starts with an ISO timestamp', lines.length > 0 && lines.every(l => iso.test(l)), `${lines.length} lines`)
466
+ check('S9 ledger records startup with target+inbox', lines.some(l => / started target=m30s:pm inbox=pm /.test(l)))
467
+ check('S9 ledger records each wake with the merged count', lines.some(l => / wake n=3 /.test(l)) && lines.some(l => / wake n=1 /.test(l)),
468
+ lines.filter(l => l.includes('wake')).slice(0, 3).join(' | '))
469
+ // P81:wake 行点名 seq 与身份;启动基线的代价单独计数(doctrine 不变,只是不再静默)
470
+ check('S9 wake lines name their seq and the identities they carry',
471
+ lines.some(l => / wake n=\d+ total=\d+ inbox=\S+ kinds=\S+ seq=\d+ ids=\S+/.test(l)),
472
+ lines.filter(l => / wake n=/.test(l)).at(-1) ?? '(no wake line)')
473
+ check('S9 startup accounting is in the ledger (baseline swallowed n=)',
474
+ lines.some(l => /baseline swallowed n=\d+ /.test(l)), lines.filter(l => /baseline swallowed/.test(l)).at(-1) ?? '(none)')
475
+ check('S9 ledger records shutdown', lines.some(l => / stopped target=m30s:pm /.test(l)))
476
+ }
477
+
478
+ // ── S10:端到端(真扩展 + 真 CLI + 真文件):假 worker 的回合结束通知 → 监视唤醒 → 收件箱可读 ──
479
+ // 这是 brief 要求的那条实录的**零模型**形态:把假 Pi 宿主换掉,其余全是生产件(真扩展注册、
480
+ // `team notify pm` 真跑、真 durable 收件箱、真 spool)。真实的「唤醒一个空闲 pi 会话(含模型一轮)」
481
+ // 由 E8 的 RPC 探针实证(docs/team/reports/E8-verify/probes),这里不重复付模型成本。
482
+ process.env.TEAM_INBOX_WATCH_TARGET = 'm30s:pm'
483
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '3600000'
484
+ if (only('S10')) {
485
+ await sessionStart()
486
+ const before = sent.length
487
+ const summary = join(TMP, 'summary-dev-M30.md')
488
+ writeFileSync(summary, 'M30-E2E: fake worker turn end went through the watch channel')
489
+ const cli = join(SKILL_DIR, 'scripts/team')
490
+ let out = ''
491
+ let rc = 0
492
+ try {
493
+ out = execFileSync('bash', [cli, 'notify', 'pm', '--from-file', summary], {
494
+ cwd: ROOT, encoding: 'utf8', timeout: 20000,
495
+ env: { ...process.env, TEAM_ROOT: ROOT, TEAM_NOTIFY_TMUX: '1' },
496
+ })
497
+ } catch (error) {
498
+ rc = 1
499
+ out = `${String(error?.stdout ?? '')}${String(error?.stderr ?? '')}`
500
+ }
501
+ check('S10 real `team notify pm` exits 0', rc === 0, out.trim().split('\n').at(-1) ?? '')
502
+ check('S10 the CLI reports the pi watch channel (not a paste, not a tmux gate)',
503
+ /pi 监视通道/.test(out) && !/不在 tmux 会话里/.test(out), out.trim().split('\n').slice(-2).join(' | '))
504
+ const inboxFile = join(ROOT, 'docs/team/inbox/pm.md')
505
+ const hits = (existsSync(inboxFile) ? readFileSync(inboxFile, 'utf8') : '').split('\n').filter(l => l.includes('M30-E2E')).length
506
+ check('S10 the durable inbox line exists exactly once (no duplicate from the channel)', hits === 1, `lines=${hits}`)
507
+ const woke = await waitFor(() => sent.length > before, 5000)
508
+ check('S10 the running extension wakes the session (zero model calls)',
509
+ woke && sent.length === before + 1, `messages=${sent.length - before}`)
510
+ const body = lastText()
511
+ check('S10 the wake carries the summary and points at the inbox',
512
+ body.includes('M30-E2E') && body.includes('docs/team/inbox/pm.md'), body.replace(/\n/g, ' | '))
513
+ const activeEntries = existsSync(join(STATE, 'outbox'))
514
+ ? readdirSync(join(STATE, 'outbox')).filter(f => f.endsWith('.msg')).length : 0
515
+ check('S10 the outbox is empty after the watch delivery', activeEntries === 0, `entries=${activeEntries}`)
516
+ // P81/2.4:spool 行带发送方自己的记录 id,唤醒文本印的就是它,且能在 delivered.log 里一一定位
517
+ const spoolTail = (readFileSync(spoolFile(), 'utf8').trimEnd().split('\n').at(-1) ?? '').split('\t')
518
+ const entryId = (spoolTail[5] ?? '').trim()
519
+ check('S10 the spool line carries the sender record id (6th field)', !!entryId, `fields=${spoolTail.length} id=${entryId || '(none)'}`)
520
+ const deliveredLog = join(STATE, 'outbox/delivered.log')
521
+ const idHits = existsSync(deliveredLog)
522
+ ? readFileSync(deliveredLog, 'utf8').split('\n').filter(l => l.split('\t')[2] === entryId).length : 0
523
+ check('S10 the printed identity resolves to exactly one delivered.log record',
524
+ !!entryId && idHits === 1 && lastText().includes(entryId), `hits=${idHits} id=${entryId}`)
525
+ await shutdown()
526
+ }
527
+
528
+ // ── S11:外部截断+重写(M43 事故形状):已投递行不得重放,total 不灌水 ─────────────────
529
+ // 2026-09-19 事故(this-project 主树 inbox-watch.log:118-120):外部力量把 spool **原位截断又写回
530
+ // 同样内容**(两次,间隔 6 秒;inode btime 证明不是 rename 替换;仓内写路径只有 `>>` 追加)。
531
+ // 旧实现 `size < offset → offset = 0` 静默重置 → 下一拍从 0 全量重读 → 同一份 42 行被叫两遍、
532
+ // total 被灌水 84。修复后:shrink 必须记账本、已投递行靠去重记忆压掉、total 只随真新增涨。
533
+ const lastTotal = () => {
534
+ // 只看**本会话**(最后一个 started 之后)的 wake 行:`seen` 在 session_start 归零,
535
+ // 拿上一个会话的 total 跟本会话比会得出假结论。
536
+ const lines = ledger()
537
+ const started = lines.map((l, i) => (/ started target=/.test(l) ? i : -1)).filter(i => i >= 0).at(-1) ?? -1
538
+ const m = [...lines.slice(started + 1).join('\n').matchAll(/ wake n=\d+ total=(\d+) /g)]
539
+ return m.length ? Number(m.at(-1)[1]) : 0
540
+ }
541
+ let s11Lines = []
542
+ if (only('S11')) {
543
+ await sessionStart()
544
+ const f = spoolFile()
545
+ // 三条新行先正常投递(合并成一条唤醒),确保重放内容**全部已投递**
546
+ const b0 = sent.length
547
+ for (const n of [1, 2, 3]) appendWake('knock', 'dev', 'pm', `m43-replay-line-${n}`)
548
+ await waitFor(() => sent.length > b0)
549
+ await sleep(400)
550
+ // 事故里重写的是**同一批字节**:直接从 spool 尾取真实的三行作为重写内容
551
+ const content = readFileSync(f, 'utf8')
552
+ s11Lines = content.trimEnd().split('\n').slice(-3)
553
+ const before = sent.length
554
+ const totalBefore = lastTotal()
555
+ // 事故形状①:原位截断到 0(flush 在 merge window 后看到空文件 → shrink)
556
+ writeFileSync(f, '')
557
+ await sleep(500)
558
+ // 事故形状②:写回同一批已投递行(flush 看到从 0 长回 → 旧实现从 0 全量重读)
559
+ appendFileSync(f, `${s11Lines.join('\n')}\n`)
560
+ await sleep(700)
561
+ check('S11 external truncate+rewrite does not redeliver already-delivered lines',
562
+ sent.length === before, `messages=${sent.length - before}`)
563
+ const shrinkLines = ledger().filter(l => /spool shrink/.test(l))
564
+ const dedupLines = ledger().filter(l => /replay suppressed/.test(l))
565
+ check('S11 the ledger records the shrink and the replay suppression (auditable, not a silent reset)',
566
+ shrinkLines.length >= 1 && dedupLines.length >= 1,
567
+ `${shrinkLines.at(-1) ?? '(no shrink line)'} || ${dedupLines.at(-1) ?? '(no replay line)'}`)
568
+ check('S11 total is not inflated by the rewrite', lastTotal() === totalBefore, `${totalBefore} -> ${lastTotal()}`)
569
+ // 真新增仍然只叫一次、计数只 +1
570
+ appendWake('say', 'pm', 'pm', 'genuinely-new-after-rewrite')
571
+ const ok = await waitFor(() => sent.length > before)
572
+ check('S11 a genuinely new line after the rewrite still wakes exactly once',
573
+ ok && sent.length === before + 1 && lastText().includes('genuinely-new-after-rewrite'),
574
+ `messages=${sent.length - before}`)
575
+ check('S11 total grows by exactly one for the real new line', lastTotal() === totalBefore + 1,
576
+ `${totalBefore} -> ${lastTotal()}`)
577
+ }
578
+
579
+ // ── S12:截短后的重放有界 + 说明跳过(只投最近 N 条「真新」,计数与文本一致)────────────────
580
+ if (only('S12')) {
581
+ process.env.TEAM_INBOX_WATCH_REPLAY_MAX = '5'
582
+ const f = spoolFile()
583
+ // 垫大 spool(两条正常投递的填克行),保证后面的重写内容**一定比当前 offset 小**(真 shrink)
584
+ const bPad = sent.length
585
+ appendWake('say', 'dev', 'pm', `m43-pad-${'P'.repeat(240)}`)
586
+ appendWake('say', 'dev', 'pm', `m43-pad-${'Q'.repeat(240)}`)
587
+ await waitFor(() => sent.length > bPad)
588
+ await sleep(400)
589
+ const oldContent = readFileSync(f, 'utf8').trimEnd().split('\n')
590
+ const oneOld = [oldContent.reduce((a, b) => (Buffer.byteLength(a) <= Buffer.byteLength(b) ? a : b))] // 最短的一行(已投递)
591
+ const fresh = []
592
+ for (let i = 1; i <= 12; i++) fresh.push(`${Date.now()}\tsay\tdev\tpm\trescan-fresh-${i}`)
593
+ const rewritten = `${[...oneOld, ...fresh].join('\n')}\n`
594
+ const curSize = statSync(f).size
595
+ check('S12 fixture precondition: rewritten content is smaller than the current offset (a real shrink)',
596
+ Buffer.byteLength(rewritten, 'utf8') < curSize, `${Buffer.byteLength(rewritten, 'utf8')} < ${curSize}`)
597
+ const before = sent.length
598
+ const totalBefore = lastTotal()
599
+ // 单次 writeFileSync(O_TRUNC+写一盘):merge window 后唯一一拍 flush 直接看到终态 → shrink → rescan
600
+ writeFileSync(f, rewritten)
601
+ await sleep(800)
602
+ check('S12 rescan after a shrink delivers exactly one bounded wake',
603
+ sent.length === before + 1, `messages=${sent.length - before}`)
604
+ const body = lastText()
605
+ check('S12 the bounded wake carries the newest fresh lines, not the skipped older ones',
606
+ body.includes('rescan-fresh-12') && body.includes('rescan-fresh-8') && !body.includes('rescan-fresh-7'),
607
+ body.replace(/\n/g, ' | '))
608
+ check('S12 the wake text says it is a rescan and names the skipped counts',
609
+ /rescan/.test(body) && /skipped 1 already-delivered \+ 7 older/.test(body), body.split('\n').find(l => /rescan/.test(l)) ?? '(no rescan line)')
610
+ const rescanLine = ledger().filter(l => / rescan /.test(l)).at(-1) ?? ''
611
+ check('S12 ledger records the rescan counts (lines/dup/skipped/deliver)',
612
+ /rescan lines=13 dup=1 skipped=7 deliver=5 /.test(rescanLine), rescanLine.trim())
613
+ check('S12 total grows only by the delivered bound (5, not 14)',
614
+ lastTotal() === totalBefore + 5, `${totalBefore} -> ${lastTotal()}`)
615
+ delete process.env.TEAM_INBOX_WATCH_REPLAY_MAX
616
+ }
617
+
618
+ // ── S13:去重记忆跨会话重启(<key>.deliver 投递日志是唯一 durable 权威;P81 起 .seen 只是被一次性导入)
619
+ if (only('S13')) {
620
+ await shutdown()
621
+ await sessionStart() // 内存态清零 → 去重记忆只能从 <key>.deliver 重新加载
622
+ const deliverFiles = existsSync(WATCH_DIR) ? readdirSync(WATCH_DIR).filter(x => x.endsWith('.deliver')) : []
623
+ check('S13 the dedup memory is persisted (<key>.deliver is the journal)', deliverFiles.length === 1,
624
+ `deliver=${deliverFiles.length}`)
625
+ const f = spoolFile()
626
+ const before = sent.length
627
+ // 重写一批**上一会话投递过**的行(S11 那三行):若记忆只活在内存里,这里就会重放
628
+ writeFileSync(f, `${s11Lines.join('\n')}\n`)
629
+ await sleep(800)
630
+ check('S13 after a restart, rewriting already-delivered lines stays silent',
631
+ sent.length === before, `messages=${sent.length - before}`)
632
+ const rescanLine = ledger().filter(l => / rescan /.test(l)).at(-1) ?? ''
633
+ check('S13 ledger records the post-restart rescan with deliver=0',
634
+ /rescan lines=3 dup=3 skipped=0 deliver=0 /.test(rescanLine), rescanLine.trim())
635
+ await shutdown()
636
+ }
637
+
638
+ // ── M46:跳过留痕 / 注册清痕 / 继承的 TEAM_STATE_DIR 不许指向别的项目 ──────────────────
639
+ // 事故(2026-09-20):other_project 的 PM 加载的是旧扩展,按继承的 TEAM_* 解到 this-project,
640
+ // 用 this-project 的会话名算出期望 target 与真实会话不符 → 每 2 秒 skip setup 一次,痕迹全写进
641
+ // **别人的** state,而投递已经静默退回输入框粘贴路径(draft-raced-left + 两条消息滞留)。
642
+ // 这三条钉住修复后的契约:① 跳过的原因留在**本项目**;② 成功注册会把旧痕迹删掉;
643
+ // ③ 继承的 TEAM_STATE_DIR 指向别的项目时一律拒绝(M40 的 state 面)。
644
+ const skipFiles = () => (existsSync(WATCH_DIR) ? readdirSync(WATCH_DIR).filter(f => f.endsWith('.skip')) : [])
645
+ const cliPath = join(SKILL_DIR, 'scripts/team')
646
+ {
647
+ await shutdown()
648
+ const savedOverride = process.env.TEAM_INBOX_WATCH_TARGET
649
+ const savedState = process.env.TEAM_STATE_DIR
650
+
651
+ // ── S14:会话名不符(配置说 m30s,target 指向 other-project)→ 本项目 state 里的 skip 记录
652
+ // 注意:TEAM_INBOX_WATCH_TARGET 只改「从哪读 target」,不改「哪个会话是本项目的」——所以这条
653
+ // 显式覆盖同样会被拒(bun 会缓存启动时的 PATH,夹具不能靠 PATH 假 tmux 来造这个形状)。
654
+ process.env.TEAM_INBOX_WATCH_TARGET = 'other-project:pm'
655
+ await sessionStart()
656
+ const skips = skipFiles()
657
+ check('M46-S14 a session-name mismatch leaves exactly one .skip record', skips.length === 1, `skips=${skips.length}`)
658
+ const skipText = skips.length ? readFileSync(join(WATCH_DIR, skips[0]), 'utf8') : ''
659
+ for (const [field, want] of [['session', 'other-project'], ['window', 'pm'], ['expect', 'm30s'], ['reason', 'session-mismatch'], ['pid', String(process.pid)], ['cwd', ROOT]]) {
660
+ check(`M46-S14 the skip record carries ${field}=${want}`, new RegExp(`^${field}=${want}$`, 'm').test(skipText), skipText.replace(/\n/g, ' | '))
661
+ }
662
+ check('M46-S14 the skip record lives in the cwd-derived project state dir',
663
+ skips.length === 1 && existsSync(join(WATCH_DIR, skips[0])), `watch=${WATCH_DIR}`)
664
+ check('M46-S14 a foreign session is not registered', regs().length === 0, `regs=${regs().length}`)
665
+ check('M46-S14 the ledger still records the skip reason',
666
+ ledger().some(l => /skip setup: session other-project != m30s/.test(l)), ledger().at(-1) || '(no ledger)')
667
+ // 端到端:真 CLI 读这条痕迹 → status 报降级(不是只有日志里有)
668
+ {
669
+ let out = ''
670
+ try {
671
+ out = execFileSync('bash', ['-c', 'bash "$1" status 2>&1', 'bash', cliPath], {
672
+ cwd: ROOT, encoding: 'utf8', timeout: 20000,
673
+ env: { ...process.env, TEAM_ROOT: ROOT },
674
+ })
675
+ } catch (error) { out = `${String(error?.stdout ?? '')}${String(error?.stderr ?? '')}` }
676
+ check('M46-S14 the real CLI reports the delivery degradation in `team status`',
677
+ /投递通道降级/.test(out) && /会话名不符/.test(out),
678
+ out.trim().split('\n').filter(l => /降级/.test(l)).join(' | ') || out.trim().split('\n').at(-1) || '')
679
+ }
680
+ await shutdown()
681
+
682
+ // ── S15:成功注册会删掉同 target 的旧 .skip(痕迹不许一直骗人)
683
+ process.env.TEAM_INBOX_WATCH_TARGET = 'm30s:pm'
684
+ mkdirSync(WATCH_DIR, { recursive: true })
685
+ writeFileSync(join(WATCH_DIR, 'stale-skip.skip'),
686
+ `version=1\ntarget=m30s:pm\nkey=stale-skip\nreason=session-mismatch\ndetail=x\npid=${process.pid}\ncwd=${ROOT}\n`)
687
+ await sessionStart()
688
+ check('M46-S15 a successful registration clears the stale .skip for its target',
689
+ !existsSync(join(WATCH_DIR, 'stale-skip.skip')), `skips=${skipFiles().length}`)
690
+ check('M46-S15 the registration itself exists', regs().length === 1, `regs=${regs().length}`)
691
+ await shutdown()
692
+
693
+ // ── S16:继承的 TEAM_STATE_DIR 指向**另一个项目**的 state → 拒绝,写本项目
694
+ const OTHER = join(TMP, 'other-project')
695
+ mkdirSync(join(OTHER, '.pi/team'), { recursive: true })
696
+ writeFileSync(join(OTHER, '.pi/team/config.sh'), 'TEAM_PROJECT="other-project"\nTEAM_SESSION="m30s"\n')
697
+ process.env.TEAM_STATE_DIR = join(OTHER, '.pi/team/state')
698
+ await sessionStart()
699
+ check('M46-S16 an inherited TEAM_STATE_DIR pointing at another project is refused',
700
+ regs().length === 1 && !existsSync(join(OTHER, '.pi/team/state/inbox-watch')),
701
+ `regs=${regs().length} other=${existsSync(join(OTHER, '.pi/team/state/inbox-watch'))}`)
702
+ check('M46-S16 the refusal is recorded in the cwd-derived ledger',
703
+ ledger().some(l => /TEAM_IDENTITY_CONFLICT inherited TEAM_STATE_DIR=/.test(l)), ledger().at(-1) || '(no ledger)')
704
+ await sessionStart() // 幂等:第二次也不再往别处写
705
+ check('M46-S16 repeated setup still writes only to the derived project',
706
+ !existsSync(join(OTHER, '.pi/team/state/inbox-watch')), `other=${existsSync(join(OTHER, '.pi/team/state/inbox-watch'))}`)
707
+ await shutdown()
708
+
709
+ // ── S17:继承的 TEAM_CONFIG_FILE 指向**另一个项目** → 忽略(期望会话名必须来自本项目配置)
710
+ delete process.env.TEAM_STATE_DIR
711
+ const savedCfg = process.env.TEAM_CONFIG_FILE
712
+ writeFileSync(join(OTHER, '.pi/team/config.sh'), 'TEAM_PROJECT="other-project"\nTEAM_SESSION="other-project"\n')
713
+ process.env.TEAM_CONFIG_FILE = join(OTHER, '.pi/team/config.sh')
714
+ await sessionStart() // target m30s:pm = 本项目配置的会话;外来配置说是 other-project
715
+ check('M46-S17 an inherited TEAM_CONFIG_FILE pointing at another project is ignored',
716
+ regs().length === 1 && skipFiles().length === 0,
717
+ `regs=${regs().length} skips=${skipFiles().length}`)
718
+ check('M46-S17 the refusal is recorded in the cwd-derived ledger',
719
+ ledger().some(l => /TEAM_IDENTITY_CONFLICT inherited TEAM_CONFIG_FILE=/.test(l)), ledger().at(-1) || '(no ledger)')
720
+ if (savedCfg === undefined) delete process.env.TEAM_CONFIG_FILE; else process.env.TEAM_CONFIG_FILE = savedCfg
721
+ await shutdown()
722
+
723
+ // 还原环境:后面的用例(与反向守卫)走原来的状态
724
+ if (savedOverride === undefined) delete process.env.TEAM_INBOX_WATCH_TARGET; else process.env.TEAM_INBOX_WATCH_TARGET = savedOverride
725
+ if (savedState === undefined) delete process.env.TEAM_STATE_DIR; else process.env.TEAM_STATE_DIR = savedState
726
+ for (const f of skipFiles()) { try { rmSync(join(WATCH_DIR, f), { force: true }) } catch { /* ignore */ } }
727
+ }
728
+
729
+ // ── S18:字节裁切的 spool 行不再把 offset 推过文件末尾(P28/R1 · D2)────────────────────────
730
+ // 事故(2026-09-20 06:42):outbox.sh 的 `LC_ALL=C cut -c1-700` 把预览裁在多字节字符中间 →
731
+ // spool 行不是合法 UTF-8;旧 readNewLines 用 `Buffer.byteLength(解码结果)` 算 advance
732
+ // (每个 U+FFFD 量成 3 字节)→ `baseline=19635` 落在 19634 字节的文件上 → 每拍都像外部缩容。
733
+ {
734
+ await shutdown()
735
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '100' // 三拍空闲:这一段要看账本有没有动
736
+ mkdirSync(WATCH_DIR, { recursive: true })
737
+ const f = spoolFile()
738
+ const clipped = Buffer.from(`xy${'红'.repeat(300)}`, 'utf8').subarray(0, 700) // 700 字节落在“红”中间
739
+ appendWakeRaw(Buffer.concat([
740
+ Buffer.from(`${Date.now()}\tknock\tpm\tpm\t`, 'utf8'), clipped, Buffer.from('\n'),
741
+ ]))
742
+ const size = statSync(f).size
743
+ let valid = true
744
+ try { execFileSync('iconv', ['-f', 'UTF-8', '-t', 'UTF-8'], { input: clipped, stdio: ['pipe', 'ignore', 'ignore'] }) } catch { valid = false }
745
+ check('S18 precondition: the clipped preview is not valid UTF-8 (the incident trigger)', !valid && clipped.length === 700, `bytes=${clipped.length}`)
746
+ const shrinkBefore = ledgerMatches(/spool shrink/)
747
+ const before = sent.length
748
+ await sessionStart()
749
+ const started = ledger().filter(l => / started target=/.test(l)).at(-1) ?? ''
750
+ check('S18 the baseline is the spool byte size (no U+FFFD skew)', started.includes(`baseline=${size}`), `${started.trim()} (size=${size})`)
751
+ const regNow = regs()[0]
752
+ const regPath = regNow ? join(WATCH_DIR, regNow) : ''
753
+ const hb0 = regPath ? statSync(regPath).mtimeMs : 0
754
+ await sleep(400)
755
+ // 心跳前进 = 定时器真的在跑:空闲断言不是「压根没拍」(POLL_MS 低于 envNum 下限会被拒)
756
+ const hbMoved = regPath ? statSync(regPath).mtimeMs > hb0 : false
757
+ check('S18 idle ticks after a byte-clipped line add no spool shrink',
758
+ hbMoved && ledgerMatches(/spool shrink/) === shrinkBefore,
759
+ `timers-alive=${hbMoved} shrink lines ${shrinkBefore} -> ${ledgerMatches(/spool shrink/)}`)
760
+ check('S18 the byte-clipped line stays in the baseline (no wake for it)', sent.length === before, `messages=${sent.length - before}`)
761
+ appendWake('say', 'pm', 'pm', 'after-clipped-line')
762
+ const woke = await waitFor(() => sent.length > before)
763
+ check('S18 the next line after a byte-clipped line wakes exactly once', woke && sent.length === before + 1,
764
+ `messages=${sent.length - before}`)
765
+ check('S18 the wake preview is the appended line, byte-complete (no leading fragment)', lastText().includes('after-clipped-line'),
766
+ lastText().replace(/\n/g, ' | '))
767
+ check('S18 total grows by exactly one (the clipped baseline line never counts)', lastTotal() === 1, `total=${lastTotal()}`)
768
+ await shutdown()
769
+ }
770
+
771
+ // ── S19:回退要有证据,恢复要收敛(P28/R2 · D3+D4)────────────────────────────────────
772
+ // 判据:同一头部的小回退 = 我们自己的 offset 算错了(修复,不重扫、不唤醒);头部变了 = 真重写
773
+ // (一次有界重扫,下一拍收敛);同一 (size, head) 不重扫第二次。
774
+ {
775
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '100'
776
+ await sessionStart()
777
+ const f = spoolFile()
778
+
779
+ // (a) 末字节被删、头部不变 → 一次 offset clamp;clamp 落在行中,下一次读取的碎片被 resync 吸收
780
+ const sizeFull = statSync(f).size
781
+ const clampA = ledgerMatches(/offset clamp/)
782
+ const shrinkA = ledgerMatches(/spool shrink/)
783
+ const rescanA = ledgerMatches(/ rescan lines=/)
784
+ const wakesA = sent.length
785
+ writeFileSync(f, readFileSync(f).subarray(0, sizeFull - 1))
786
+ const clamped = await waitFor(() => ledgerMatches(/offset clamp/) > clampA, 2000)
787
+ check('S19a a one-byte regression with an unchanged head is repaired with one offset clamp',
788
+ clamped && ledgerMatches(/offset clamp/) === clampA + 1 && ledgerMatches(/spool shrink/) === shrinkA,
789
+ ledger().filter(l => /offset clamp|spool shrink/.test(l)).at(-1) ?? '(no clamp line)')
790
+ check('S19a the clamp is recorded with head=same (auditable repair)',
791
+ /offset clamp from=\d+ to=\d+ head=same/.test(ledger().filter(l => /offset clamp/.test(l)).at(-1) ?? ''),
792
+ ledger().filter(l => /offset clamp/.test(l)).at(-1) ?? '')
793
+ check('S19a the clamp neither rescans nor wakes',
794
+ ledgerMatches(/ rescan lines=/) === rescanA && sent.length === wakesA,
795
+ `rescans=${ledgerMatches(/ rescan lines=/)} messages=${sent.length - wakesA}`)
796
+ const resyncA = ledgerMatches(/offset resync/)
797
+ appendWake('say', 'pm', 'pm', 'fragment-joined-to-the-clamped-line')
798
+ const resynced = await waitFor(() => ledgerMatches(/offset resync/) > resyncA, 2000)
799
+ check('S19a the read that starts inside the clamped line resyncs instead of delivering a fragment',
800
+ resynced && ledgerMatches(/offset resync/) === resyncA + 1 && sent.length === wakesA,
801
+ ledger().filter(l => /offset resync/.test(l)).at(-1) ?? '(no resync line)')
802
+ check('S19a the resync records the skipped byte count (one line per action)',
803
+ /offset resync skipped=\d+ /.test(ledger().filter(l => /offset resync/.test(l)).at(-1) ?? ''),
804
+ ledger().filter(l => /offset resync/.test(l)).at(-1) ?? '')
805
+ appendWake('say', 'pm', 'pm', 'clean-line-after-resync')
806
+ const wokeA = await waitFor(() => sent.length > wakesA, 3000)
807
+ check('S19a a line appended after the resync wakes exactly once',
808
+ wokeA && sent.length === wakesA + 1 && lastText().includes('clean-line-after-resync'),
809
+ `messages=${sent.length - wakesA}`)
810
+ check('S19a the fragment itself never appears in a wake', !lastText().includes('fragment-joined-to-the-clamped-line'),
811
+ lastText().replace(/\n/g, ' | '))
812
+
813
+ // (b) 头部变了、文件变短 → 一次 spool shrink + 一次 rescan,下一拍什么都不加
814
+ const sizeB = statSync(f).size
815
+ const shrinkB = ledgerMatches(/spool shrink/)
816
+ const rescanB = ledgerMatches(/ rescan lines=/)
817
+ const wakesB = sent.length
818
+ const ts = Date.now()
819
+ const rewritten = Buffer.from([1, 2, 3].map(i => `${ts}\tsay\tdev\tpm\trewrite-fresh-${i}`).join('\n') + '\n')
820
+ const headNow = readFileSync(f).subarray(0, 16)
821
+ check('S19b precondition: the rewrite is shorter than the offset and its head differs',
822
+ rewritten.length < sizeB && !headNow.equals(rewritten.subarray(0, 16)), `${rewritten.length} < ${sizeB}`)
823
+ writeFileSync(f, rewritten)
824
+ const rescanned = await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanB, 2000)
825
+ check('S19b a rewrite with a changed head is rescanned exactly once',
826
+ rescanned && ledgerMatches(/spool shrink/) === shrinkB + 1 && ledgerMatches(/ rescan lines=/) === rescanB + 1,
827
+ ledger().filter(l => /rescan lines=/.test(l)).at(-1) ?? '(no rescan line)')
828
+ check('S19b the rescan delivers the rewritten content',
829
+ sent.length === wakesB + 1 && lastText().includes('rewrite-fresh-3'), `messages=${sent.length - wakesB}`)
830
+ await sleep(400)
831
+ check('S19b the next tick adds nothing (converged)',
832
+ ledgerMatches(/spool shrink/) === shrinkB + 1 && ledgerMatches(/ rescan lines=/) === rescanB + 1 && sent.length === wakesB + 1,
833
+ `shrink=${ledgerMatches(/spool shrink/)} rescan=${ledgerMatches(/ rescan lines=/)} messages=${sent.length - wakesB}`)
834
+
835
+ // (c) 同一 (size, head) 不再重扫第二次:先制造事件(clamp 到行中),再用一次 resync 推进
836
+ // offset(不投递任何行 → 事件记忆保留),然后把文件截回同一 (size, head)——回归 201 字节 > clamp 上限,
837
+ // 没有 repeat 守卫就会重扫第二次。
838
+ const sizeC = statSync(f).size
839
+ const clampC = ledgerMatches(/offset clamp/)
840
+ const shrinkC = ledgerMatches(/spool shrink/)
841
+ const rescanC = ledgerMatches(/ rescan lines=/)
842
+ const repeatsC = ledgerMatches(/shrink repeat/)
843
+ const wakesC = sent.length
844
+ writeFileSync(f, readFileSync(f).subarray(0, sizeC - 1))
845
+ const clampedC = await waitFor(() => ledgerMatches(/offset clamp/) > clampC, 2000)
846
+ check('S19c (setup) the clamp into the middle of a line is recorded once',
847
+ clampedC && ledgerMatches(/offset clamp/) === clampC + 1 && sent.length === wakesC,
848
+ ledger().filter(l => /offset clamp/.test(l)).at(-1) ?? '(no clamp line)')
849
+ const resyncC = ledgerMatches(/offset resync/)
850
+ appendWakeRaw(Buffer.from(`${'F'.repeat(200)}\n`)) // 200 字节碎片 + 换行:整段被跳过,不投递
851
+ const resyncedC = await waitFor(() => ledgerMatches(/offset resync/) > resyncC, 2000)
852
+ check('S19c (setup) the restored fragment is skipped as a resync (no line is delivered)',
853
+ resyncedC && ledgerMatches(/offset resync/) === resyncC + 1 && sent.length === wakesC,
854
+ ledger().filter(l => /offset resync/.test(l)).at(-1) ?? '(no resync line)')
855
+ writeFileSync(f, readFileSync(f).subarray(0, sizeC - 1)) // 截回同一 (size, head):回归 201 > 64
856
+ const repeated = await waitFor(() => ledgerMatches(/shrink repeat/) > repeatsC, 2000)
857
+ check('S19c the same (size, head) is recorded as a repeat and clamped, not rescanned twice',
858
+ repeated && ledgerMatches(/shrink repeat/) === repeatsC + 1 && ledgerMatches(/ rescan lines=/) === rescanC
859
+ && ledgerMatches(/spool shrink/) === shrinkC && sent.length === wakesC,
860
+ ledger().filter(l => /shrink repeat/.test(l)).at(-1) ?? '(no repeat line)')
861
+ check('S19c the repeat line names the state and the action',
862
+ /shrink repeat size=\d+ head=fnv[0-9a-f]+ action=clamp/.test(ledger().filter(l => /shrink repeat/.test(l)).at(-1) ?? ''),
863
+ ledger().filter(l => /shrink repeat/.test(l)).at(-1) ?? '')
864
+ await shutdown()
865
+ }
866
+
867
+ // ── S20:只有新鲜行唤醒;过期行只计数、不投递、不丢字节(P28/R3 · D5)────────────────────
868
+ // 判据是行自带的 `team_epoch_ms`(第一个字段):不看 mtime,也不看 .seen 的顺序。
869
+ {
870
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '100'
871
+ await sessionStart()
872
+ const f = spoolFile()
873
+ // (a) 一小时前的未投递行(不在 .seen)+ 它的 durable 收件箱行 → 重扫里 stale=1、deliver=0、不唤醒
874
+ const inboxFile = join(ROOT, 'docs/team/inbox/pm.md')
875
+ mkdirSync(join(ROOT, 'docs/team/inbox'), { recursive: true })
876
+ appendFileSync(inboxFile, '\n- [knock] S20 stale line body\n')
877
+ const staleLine = `${Date.now() - 3600_000}\tknock\tpm\tpm\tS20-stale-line`
878
+ const rescanA = ledgerMatches(/ rescan lines=/)
879
+ const totalA = lastTotal()
880
+ const wakesA = sent.length
881
+ writeFileSync(f, `${staleLine}\n`)
882
+ const rescanned = await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanA, 2000)
883
+ check('S20a an hour-old unseen line is rescan-counted, never woken about',
884
+ rescanned && /rescan lines=1 dup=0 skipped=0 deliver=0 stale=1 /.test(ledger().filter(l => /rescan lines=/.test(l)).at(-1) ?? ''),
885
+ ledger().filter(l => /rescan lines=/.test(l)).at(-1) ?? '(no rescan line)')
886
+ check('S20a a stale-only recovery moves neither the wake count nor total',
887
+ sent.length === wakesA && lastTotal() === totalA,
888
+ `messages=${sent.length - wakesA} total=${totalA}->${lastTotal()}`)
889
+ check('S20a the durable inbox copy is still there and the spool keeps the bytes',
890
+ readFileSync(inboxFile, 'utf8').includes('S20 stale line body') && readFileSync(f, 'utf8').includes('S20-stale-line'),
891
+ `spool=${statSync(f).size}B`)
892
+ // (b) 紧跟一条新行 → 只叫这一条一次,total +1
893
+ appendWake('say', 'pm', 'pm', 'S20-fresh-after-stale')
894
+ const wokeB = await waitFor(() => sent.length > wakesA, 3000)
895
+ check('S20b a fresh line after a stale one still wakes exactly once',
896
+ wokeB && sent.length === wakesA + 1 && lastText().includes('S20-fresh-after-stale') && !lastText().includes('S20-stale-line'),
897
+ `messages=${sent.length - wakesA}`)
898
+ check('S20b total grows by exactly one', lastTotal() === totalA + 1, `${totalA} -> ${lastTotal()}`)
899
+ // (c) 时间戳读不出来的行照样投(不静默吞),并计数 unparsable=1
900
+ const wakesC = sent.length
901
+ appendWakeRaw(Buffer.from('zzz\tsay\tpm\tpm\tS20-unparsable-line\n'))
902
+ const wokeC = await waitFor(() => sent.length > wakesC, 3000)
903
+ check('S20c a line whose timestamp is not a number is delivered (never swallowed)',
904
+ wokeC && sent.length === wakesC + 1 && lastText().includes('S20-unparsable-line'), `messages=${sent.length - wakesC}`)
905
+ check('S20c the ledger counts it as unparsable=1', ledgerMatches(/unparsable=1/) >= 1,
906
+ ledger().filter(l => /unparsable=1/.test(l)).at(-1) ?? '(no classify line)')
907
+ // (d) 普通路径(不是重扫)上的过期行同样不唤醒、但要计数
908
+ const wakesD = sent.length
909
+ appendWakeRaw(Buffer.from(`${Date.now() - 7200_000}\tsay\tpm\tpm\tS20-stale-normal-path\n`))
910
+ await sleep(500)
911
+ check('S20d a stale line on the ordinary path stays silent but is counted',
912
+ sent.length === wakesD && ledgerMatches(/classify stale=1/) >= 1,
913
+ ledger().filter(l => /classify /.test(l)).at(-1) ?? '(no classify line)')
914
+ await shutdown()
915
+ }
916
+
917
+ // ── S21:账本把新流量与恢复分开(P28/R4 · D6)──────────────────────────────────────────
918
+ // 操作员要能一眼看出「这次唤醒是新消息还是恢复」:`total=` 只随真投递增长,rescan 有自己的分解。
919
+ {
920
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '100'
921
+ await sessionStart()
922
+ const f = spoolFile()
923
+ // (a) 先投递三条真新行(从 spool 尾取回它们的真实字节),再把这批**已投递**行重写回 spool
924
+ // → deliver=0 + dup>0、total 不动、无唤醒
925
+ const bPick = sent.length
926
+ for (const n of [1, 2, 3]) appendWake('knock', 'dev', 'pm', `S21a-delivered-${n}`)
927
+ await waitFor(() => sent.length > bPick)
928
+ await sleep(300)
929
+ const picked = readFileSync(f, 'utf8').trimEnd().split('\n').slice(-3)
930
+ const rescanA = ledgerMatches(/ rescan lines=/)
931
+ const shrinkA = ledgerMatches(/spool shrink/)
932
+ const totalA = lastTotal()
933
+ const wakesA = sent.length
934
+ const sizeA = statSync(f).size
935
+ const rewriteA = Buffer.from(`${picked.join('\n')}\n`)
936
+ check('S21a precondition: a rewrite built from delivered lines, smaller, with a different head',
937
+ picked.length >= 2 && rewriteA.length < sizeA && !readFileSync(f).subarray(0, 16).equals(rewriteA.subarray(0, 16)),
938
+ `picked=${picked.length} ${rewriteA.length} < ${sizeA}`)
939
+ writeFileSync(f, rewriteA)
940
+ const rescannedA = await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanA, 2000)
941
+ check('S21a a dedup-only rescan reads deliver=0 with a non-zero dup and moves nothing',
942
+ rescannedA && new RegExp(`rescan lines=${picked.length} dup=${picked.length} skipped=0 deliver=0 `).test(ledger().filter(l => /rescan lines=/.test(l)).at(-1) ?? '')
943
+ && sent.length === wakesA && lastTotal() === totalA,
944
+ ledger().filter(l => /rescan lines=/.test(l)).at(-1) ?? '(no rescan line)')
945
+ // (b) 只含过期行的重写 → deliver=0 stale=<n>、total 不动、无唤醒
946
+ const rescanB = ledgerMatches(/ rescan lines=/)
947
+ const totalB = lastTotal()
948
+ const wakesB = sent.length
949
+ const staleA = `${Date.now() - 3600_000}\tknock\tpm\tpm\tS21-stale-a`
950
+ const staleB = `${Date.now() - 7200_000}\tknock\tpm\tpm\tS21-stale-b`
951
+ const rewriteB = Buffer.from(`${staleA}\n${staleB}\n`)
952
+ check('S21b precondition: a stale-only rewrite, smaller, with a different head',
953
+ rewriteB.length < statSync(f).size && !readFileSync(f).subarray(0, 16).equals(rewriteB.subarray(0, 16)),
954
+ `${rewriteB.length} < ${statSync(f).size}`)
955
+ writeFileSync(f, rewriteB)
956
+ const rescannedB = await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanB, 2000)
957
+ check('S21b a stale-only rescan reads deliver=0 with stale=<n> and moves nothing',
958
+ rescannedB && /rescan lines=2 dup=0 skipped=0 deliver=0 stale=2 /.test(ledger().filter(l => /rescan lines=/.test(l)).at(-1) ?? '')
959
+ && sent.length === wakesB && lastTotal() === totalB,
960
+ ledger().filter(l => /rescan lines=/.test(l)).at(-1) ?? '(no rescan line)')
961
+ // (c) 两条新鲜行合并成一条唤醒 → wake n=2、total +2
962
+ const totalC = lastTotal()
963
+ const wakesC = sent.length
964
+ appendWake('say', 'pm', 'pm', 'S21-fresh-a')
965
+ appendWake('say', 'pm', 'pm', 'S21-fresh-b')
966
+ const wokeC = await waitFor(() => sent.length > wakesC, 3000)
967
+ check('S21c a real delivery is one wake naming both lines',
968
+ wokeC && sent.length === wakesC + 1 && lastText().includes('S21-fresh-a') && lastText().includes('S21-fresh-b'),
969
+ `messages=${sent.length - wakesC}`)
970
+ check('S21c the wake line reads n=2 and total grows by exactly two',
971
+ ledgerMatches(/wake n=2 /) >= 1 && lastTotal() === totalC + 2,
972
+ `total=${totalC}->${lastTotal()} ${ledger().filter(l => / wake n=/.test(l)).at(-1) ?? ''}`)
973
+ await shutdown()
974
+ }
975
+
976
+ // ── S22–S24(M53):注册失败被记录、轮询兜底被证明、记录随生命周期收敛 ─────────────────
977
+ // 事故(2026-09-21):宿主 inotify 配额耗尽 → 扩展静默丢掉 errno 与配额,而 `.reg` 还在 →
978
+ // doctor 把「只剩轮询」的通道报成健康。三条契约:① 失败带 errno/额度/轮询间隔,落一条耐久记录;
979
+ // ② 轮询兜底仍投递一次且不改变消息形状;③ 记录只活到「成功注册」或「干净退出」。
980
+ const degradedFiles = () => (existsSync(WATCH_DIR) ? readdirSync(WATCH_DIR).filter(f => f.endsWith('.degraded')) : [])
981
+ {
982
+ await shutdown()
983
+ await sleep(150)
984
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '200'
985
+ process.env.TEAM_INBOX_WATCH_FORCE_FAIL = 'ENOSPC'
986
+ const beforeNotify = sent.length
987
+ await sessionStart()
988
+
989
+ // S22 —— 失败的两条痕迹都要自解释;`.reg` 必须留着(发送方的路由绝不因降级改道)
990
+ const failLine = ledger().filter(l => /watch unavailable/.test(l)).at(-1) ?? ''
991
+ check('S22 the failure line names errno, watches, poll_ms and fallback=polling',
992
+ /watch unavailable: errno=ENOSPC watches=([0-9]+|unknown)\/([0-9]+|unknown) poll_ms=200 fallback=polling forced=1$/.test(failLine),
993
+ failLine.trim() || '(no failure line)')
994
+ check('S22 the failure line marks the fixture-caused fault as forced=1', /\bforced=1$/.test(failLine), failLine.trim())
995
+ const deg = degradedFiles()
996
+ check('S22 a degraded record is written (exactly one)', deg.length === 1, `records=${deg.length}`)
997
+ const degText = deg.length ? readFileSync(join(WATCH_DIR, deg[0]), 'utf8') : ''
998
+ for (const [field, want] of [
999
+ ['version', '1'], ['target', 'm30s:pm'], ['reason', 'watch-unavailable'], ['errno', 'ENOSPC'],
1000
+ ['poll_ms', '200'], ['forced', '1'], ['pid', String(process.pid)], ['cwd', ROOT],
1001
+ ]) {
1002
+ check(`S22 the record carries ${field}=${want}`, new RegExp(`^${field}=${want}$`, 'm').test(degText), degText.replace(/\n/g, ' | '))
1003
+ }
1004
+ check('S22 the record carries watches=<used>/<max>',
1005
+ /^watches=([0-9]+|unknown)\/([0-9]+|unknown)$/m.test(degText), degText.replace(/\n/g, ' | '))
1006
+ check('S22 a degraded watcher does not lose the registration (.reg is still there)',
1007
+ regs().length === 1, `regs=${regs().length}`)
1008
+ // 真 CLI 的 route 助手仍从 .reg 解出 target → 走 pi 通道(降级不把发送方推回粘贴慢路径)
1009
+ const m53Summary = join(TMP, 'summary-dev-M53.md')
1010
+ writeFileSync(m53Summary, 'M53-S22: a degraded watcher keeps the spool route')
1011
+ let notifyOut = ''
1012
+ try {
1013
+ notifyOut = execFileSync('bash', [join(SKILL_DIR, 'scripts/team'), 'notify', 'pm', '--from-file', m53Summary], {
1014
+ cwd: ROOT, encoding: 'utf8', timeout: 20000,
1015
+ env: { ...process.env, TEAM_ROOT: ROOT, TEAM_NOTIFY_TMUX: '1' },
1016
+ })
1017
+ } catch (error) { notifyOut = `${String(error?.stdout ?? '')}${String(error?.stderr ?? '')}` }
1018
+ check('S22 the real route helper still resolves the target from .reg (pi channel, never the paste path)',
1019
+ /pi 监视通道/.test(notifyOut), notifyOut.trim().split('\n').at(-1) ?? '')
1020
+ await waitFor(() => sent.length > beforeNotify, 1500) // 先把通知那一拍投完,S23 才是干净的一行一次
1021
+
1022
+ // S23 —— 兜底是「被证明的保证」:强制失败 + 秒级轮询,一条新 spool 行在一个周期内唤醒一次
1023
+ const beforeWake = sent.length
1024
+ appendWake('say', 'pm', 'pm', `S23-POLL-FALLBACK-${'Z'.repeat(200)}S23-TAIL-MARKER`)
1025
+ const woke = await waitFor(() => sent.length > beforeWake, 600)
1026
+ await sleep(300)
1027
+ check('S23 a forced-failure session still wakes within one poll interval (200 ms)',
1028
+ woke && sent.length === beforeWake + 1, `messages=${sent.length - beforeWake}`)
1029
+ const fallbackWake = sent.at(-1)
1030
+ check('S23 the fallback wake keeps the live-watcher shape (customType/triggerTurn/followUp)',
1031
+ fallbackWake?.msg?.customType === 'team-inbox' && fallbackWake?.opts?.triggerTurn === true
1032
+ && fallbackWake?.opts?.deliverAs === 'followUp',
1033
+ JSON.stringify({ customType: fallbackWake?.msg?.customType, ...(fallbackWake?.opts ?? {}) }))
1034
+ const fallbackBody = lastText()
1035
+ check('S23 the fallback wake points at the inbox and truncates the payload',
1036
+ fallbackBody.includes('docs/team/inbox/pm.md') && fallbackBody.includes('S23-POLL-FALLBACK-')
1037
+ && !fallbackBody.includes('S23-TAIL-MARKER'), fallbackBody.replace(/\n/g, ' | '))
1038
+ check('S23 the ledger records the fallback delivery as one wake',
1039
+ /wake n=1 /.test(ledger().filter(l => / wake n=/.test(l)).at(-1) ?? ''), ledger().at(-1) ?? '')
1040
+
1041
+ // S24 —— 生命周期:干净退出删记录;真注册成功也删旧记录
1042
+ await shutdown()
1043
+ check('S24 a clean shutdown removes the degraded record', degradedFiles().length === 0, `records=${degradedFiles().length}`)
1044
+ delete process.env.TEAM_INBOX_WATCH_FORCE_FAIL
1045
+ mkdirSync(WATCH_DIR, { recursive: true })
1046
+ writeFileSync(join(WATCH_DIR, 'stale-m53.degraded'),
1047
+ `version=1\ntarget=m30s:pm\nkey=stale-m53\nreason=watch-unavailable\nerrno=ENOSPC\nwatches=1/2\n` +
1048
+ `poll_ms=5000\nforced=0\nsince=x\npid=${process.pid}\ncwd=${ROOT}\nheartbeat=${Math.floor(Date.now() / 1000)}\n`)
1049
+ await sessionStart()
1050
+ check('S24 a healthy session writes no degraded record', degradedFiles().length === 0, `records=${degradedFiles().length}`)
1051
+ check('S24 a successful registration clears a stale degraded record',
1052
+ !existsSync(join(WATCH_DIR, 'stale-m53.degraded')), `records=${degradedFiles().length}`)
1053
+ await shutdown()
1054
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '3600000'
1055
+ }
1056
+
1057
+ // ═══════════════════════════════════════════════════════════════════════════════
1058
+ // P81 · wake-delivery-idempotence:投递日志 / 至多一次 / fail-closed / 源行点名
1059
+ // 事故:一条 nudge 让 PM 在一个多小时里被「同一条」叫醒三次,而 durable 文件回答不了
1060
+ // 「到底投过没有」。契约:唤醒是 at-most-once(门铃),durable 收件箱行是 exactly-once(消息)。
1061
+ // 每个断言都指向**文件**(日志 / 账本),不读实现内部状态;本节用 100ms 轮询,不依赖 fs.watch。
1062
+ // ═══════════════════════════════════════════════════════════════════════════════
1063
+ process.env.TEAM_INBOX_WATCH_POLL_MS = '100'
1064
+
1065
+ // ── S25j:日志形状与写前顺序(start → read → intent → sent);过期行不写记录(1.1)────
1066
+ if (only('S25j')) {
1067
+ await resetState()
1068
+ await sessionStart()
1069
+ const f = spoolFile()
1070
+ appendWake('say', 'pm', 'pm', 'S25j-fresh-line')
1071
+ const woke = await waitFor(() => journalOf('sent').length > 0)
1072
+ const recs = journalLines().map(jrec).filter(Boolean)
1073
+ check('S25j the journal is start → read → intent → sent, one record per line',
1074
+ woke && recs.map(r => r.kind).join(',') === 'start,read,intent,sent', recs.map(r => r.kind).join(','))
1075
+ const read = recs.find(r => r.kind === 'read')
1076
+ const rawLine = spoolLines().find(l => l.includes('S25j-fresh-line')) ?? ''
1077
+ const size = statSync(f).size
1078
+ check('S25j the read record carries the line identity and the wake material',
1079
+ read && read.fields.id === identityOf(rawLine) && read.fields.kind === 'say' && read.fields.from === 'pm'
1080
+ && read.fields.durable === 'pm' && read.fields.preview === 'S25j-fresh-line' && Number(read.fields.src) > 0,
1081
+ read ? JSON.stringify(read.fields) : '(no read record)')
1082
+ check('S25j the read record carries the offset/size/head fingerprint',
1083
+ read && read.fields.off === String(size) && read.fields.size === String(size) && /^(fnv[0-9a-f]+|empty|absent)$/.test(read.fields.head),
1084
+ read ? `off=${read.fields.off} size=${read.fields.size} head=${read.fields.head}` : '(no read record)')
1085
+ check('S25j the batch is closed by intent then sent with the same seq',
1086
+ recs.some(r => r.kind === 'intent' && r.fields.seq === read?.fields.seq)
1087
+ && recs.some(r => r.kind === 'sent' && r.fields.seq === read?.fields.seq),
1088
+ recs.map(r => `${r.kind}${r.fields.seq ? `=${r.fields.seq}` : ''}`).join(' '))
1089
+ check('S25j every record is ISO-stamped', recs.every(r => /^\d{4}-\d{2}-\d{2}T/.test(r.ts)), recs[0]?.ts ?? '')
1090
+ check('S25j the wake ledger line names seq and the identities',
1091
+ / wake n=1 total=1 inbox=pm kinds=say seq=1 ids=\S+$/.test(ledger().filter(l => / wake n=/.test(l)).at(-1) ?? ''),
1092
+ ledger().filter(l => / wake n=/.test(l)).at(-1) ?? '(no wake line)')
1093
+ // 过期行:不写日志记录、不唤醒、只计数
1094
+ const before = sent.length
1095
+ const recordsBefore = journalLines().length
1096
+ const totalBefore = lastTotal()
1097
+ appendWakeRaw(Buffer.from(`${Date.now() - 3600_000}\tsay\tpm\tpm\tS25j-stale-line\n`))
1098
+ // 等分类行真的出现再断言「没写记录、没唤醒」:不然慢机器上可能是「还没读到」的假绿
1099
+ const classified = await waitFor(() => ledgerMatches(/classify stale=1 unparsable=0/) >= 1, 3000)
1100
+ check('S25j a stale line writes no journal record and wakes nobody',
1101
+ classified && sent.length === before && journalLines().length === recordsBefore,
1102
+ `messages=${sent.length - before} records=${journalLines().length - recordsBefore}`)
1103
+ check('S25j the stale line is counted apart from total',
1104
+ ledgerMatches(/classify stale=1 unparsable=0/) >= 1 && lastTotal() === totalBefore,
1105
+ ledger().filter(l => /classify /.test(l)).at(-1) ?? '(no classify line)')
1106
+ await shutdown()
1107
+ }
1108
+
1109
+ // ── S25g:启动核算 —— 没人看过的行只计数,基线契约不变(4.2)──────────────────────────
1110
+ if (only('S25g')) {
1111
+ await resetState()
1112
+ appendWake('say', 'pm', 'pm', 'S25g-nobody-watched')
1113
+ const before = sent.length
1114
+ await sessionStart()
1115
+ const started = ledger().filter(l => / started target=/.test(l)).at(-1) ?? ''
1116
+ check('S25g startup accounting names the swallowed lines and keeps the baseline contract',
1117
+ /baseline swallowed n=1 /.test(ledger().filter(l => /baseline swallowed/.test(l)).at(-1) ?? '')
1118
+ && started.includes(`baseline=${statSync(spoolFile()).size}`),
1119
+ `${ledger().filter(l => /baseline swallowed/.test(l)).at(-1) ?? '(none)'} || ${started.trim()}`)
1120
+ await sleep(500)
1121
+ check('S25g a line written while nobody watched wakes nobody', sent.length === before, `messages=${sent.length - before}`)
1122
+ appendWake('say', 'pm', 'pm', 'S25g-after-start')
1123
+ const woke = await waitFor(() => sent.length > before)
1124
+ check('S25g a line after startup still wakes exactly once',
1125
+ woke && sent.length === before + 1 && lastText().includes('S25g-after-start'), `messages=${sent.length - before}`)
1126
+ await shutdown()
1127
+ }
1128
+
1129
+ // ── S25r:恢复路径也受新鲜度约束 —— 已过期的恢复只计数、不唤醒(3.2 的 stale 半边)──
1130
+ if (only('S25r')) {
1131
+ await resetState()
1132
+ mkdirSync(WATCH_DIR, { recursive: true })
1133
+ const oldTs = Date.now() - 3600_000
1134
+ const line = `${oldTs}\tsay\tpm\tpm\tS25r-recovered-but-stale`
1135
+ writeFileSync(spoolFile(), `${line}\n`)
1136
+ const lineBytes = Buffer.byteLength(line, 'utf8') + 1
1137
+ writeFileSync(journalPathOf(),
1138
+ `${new Date().toISOString()} start baseline=0 size=0 head=absent\n` +
1139
+ `${new Date().toISOString()} read seq=1 off=${lineBytes} size=${lineBytes} head=empty id=${jesc(identityOf(line))} src=${oldTs} kind=say from=pm durable=pm preview=S25r-recovered-but-stale\n`)
1140
+ const before = sent.length
1141
+ await sessionStart()
1142
+ check('S25r a recovered line past the horizon is counted stale, not woken',
1143
+ sent.length === before && ledgerMatches(/recovery candidates=1 fresh=0 stale=1 unparsable=0/) === 1
1144
+ && ledgerMatches(/recovery n=/) === 0,
1145
+ `${ledger().filter(l => /recovery /.test(l)).at(-1) ?? '(none)'} || messages=${sent.length - before}`)
1146
+ await sleep(400)
1147
+ check('S25r the stale recovery stays silent and total does not move',
1148
+ sent.length === before && lastTotal() === 0, `messages=${sent.length - before} total=${lastTotal()}`)
1149
+ await shutdown()
1150
+ }
1151
+
1152
+ // ── S25z:注入旋钮是夹具专属;裸设无效、不杀会话、不留痕(3.1)────────────────────────
1153
+ if (only('S25z')) {
1154
+ await resetState()
1155
+ process.env.TEAM_INBOX_WATCH_ABORT_AFTER = 'read'
1156
+ await sessionStart()
1157
+ check('S25z the abort knob without TEAM_SMOKE_FIXTURE=1 is printed as ignored',
1158
+ ledger().some(l => /fixture knob ignored: TEAM_INBOX_WATCH_ABORT_AFTER=read/.test(l)),
1159
+ ledger().filter(l => /fixture knob/.test(l)).at(-1) ?? '(no ignored line)')
1160
+ const before = sent.length
1161
+ appendWake('say', 'pm', 'pm', 'S25z-live-process')
1162
+ const woke = await waitFor(() => sent.length > before)
1163
+ check('S25z an ignored knob does not kill the session (the line is still delivered)',
1164
+ woke && sent.length === before + 1, `messages=${sent.length - before}`)
1165
+ const recs = journalOf('sent')
1166
+ check('S25z the delivery went through the journal as usual', recs.length === 1, `sent records=${recs.length}`)
1167
+ delete process.env.TEAM_INBOX_WATCH_ABORT_AFTER
1168
+ await shutdown()
1169
+ }
1170
+
1171
+ // ── S25a:read 之后被杀 → 重启后**恰好一次**恢复(不是两次)(3.2)──────────────────
1172
+ if (only('S25a')) {
1173
+ await resetState()
1174
+ const payload = `S25a-read-then-die-${Date.now()}`
1175
+ const r = runChild('read', payload)
1176
+ check('S25a the child is a real separate process killed at the injection point',
1177
+ r.status === null && r.signal === 'SIGKILL',
1178
+ `status=${r.status} signal=${r.signal} stderr=${String(r.stderr ?? '').trim().split('\n').at(-1) ?? ''}`)
1179
+ const recs = journalLines().map(jrec).filter(Boolean)
1180
+ check('S25a the child left a read record and no intent/sent',
1181
+ recs.some(x => x.kind === 'read') && !recs.some(x => x.kind === 'intent' || x.kind === 'sent'),
1182
+ recs.map(x => x.kind).join(','))
1183
+ check('S25a the durable spool line survived the crash', spoolLines().some(l => l.includes(payload)), `lines=${spoolLines().length}`)
1184
+ const before = sent.length
1185
+ await sessionStart()
1186
+ const woke = await waitFor(() => sent.length > before, 3000)
1187
+ check('S25a exactly one recovery wake is sent for the crashed line',
1188
+ woke && sent.length === before + 1, `messages=${sent.length - before}`)
1189
+ const wakeLine = ledger().filter(l => / wake n=/.test(l)).at(-1) ?? ''
1190
+ check('S25a the ledger records it as recovery with its seq',
1191
+ / wake n=1 total=1 inbox=pm kinds=say seq=\d+ ids=\S+ recovery n=1$/.test(wakeLine), wakeLine.trim())
1192
+ check('S25a the recovery is recorded in the journal as sent (at most once from now on)',
1193
+ journalOf('sent').length === 1, `sent records=${journalOf('sent').length}`)
1194
+ // 同一批字节再重写一次 —— **跨一次重启**(重启本身也不得再恢复):证明至多一次是由日志
1195
+ // (不是内存)保证的
1196
+ await shutdown()
1197
+ const beforeR = sent.length
1198
+ await sessionStart()
1199
+ await sleep(400)
1200
+ check('S25a a restart after the recovery wakes nobody again (sent is terminal)',
1201
+ sent.length === beforeR, `messages=${sent.length - beforeR}`)
1202
+ const bytes = readFileSync(spoolFile())
1203
+ const rescan0 = ledgerMatches(/ rescan lines=/)
1204
+ const replay0 = ledgerMatches(/replay suppressed/)
1205
+ writeFileSync(spoolFile(), '')
1206
+ await waitFor(() => ledgerMatches(/ rescan lines=/) > rescan0, 3000)
1207
+ appendFileSync(spoolFile(), bytes)
1208
+ await waitFor(() => ledgerMatches(/replay suppressed/) > replay0, 3000)
1209
+ check('S25a a later rewrite of the same bytes produces no second wake',
1210
+ sent.length === beforeR && ledgerMatches(/replay suppressed/) > replay0,
1211
+ `messages=${sent.length - beforeR} replay=${ledgerMatches(/replay suppressed/)}`)
1212
+ await shutdown()
1213
+ }
1214
+
1215
+ // ── S25b:intent 之后被杀 → 重启后零重投 + inflight assumed(3.3)────────────────────
1216
+ if (only('S25b')) {
1217
+ await resetState()
1218
+ const inboxFile = join(ROOT, 'docs/team/inbox/pm.md')
1219
+ mkdirSync(join(ROOT, 'docs/team/inbox'), { recursive: true })
1220
+ appendFileSync(inboxFile, '\n- [say] S25b durable inbox line\n')
1221
+ const payload = `S25b-intent-then-die-${Date.now()}`
1222
+ const r = runChild('intent', payload)
1223
+ check('S25b the child is a real separate process killed at the intent injection point',
1224
+ r.status === null && r.signal === 'SIGKILL',
1225
+ `status=${r.status} signal=${r.signal} stderr=${String(r.stderr ?? '').trim().split('\n').at(-1) ?? ''}`)
1226
+ const recs = journalLines().map(jrec).filter(Boolean)
1227
+ check('S25b the child left a complete read+intent and no sent/failed',
1228
+ recs.filter(x => x.kind === 'read').length === 1 && recs.some(x => x.kind === 'intent')
1229
+ && !recs.some(x => x.kind === 'sent' || x.kind === 'failed'),
1230
+ recs.map(x => x.kind).join(','))
1231
+ // 证明权威是日志而不是 .seen:重启前删掉任何 .seen
1232
+ for (const n of readdirSync(WATCH_DIR).filter(x => x.endsWith('.seen'))) rmSync(join(WATCH_DIR, n), { force: true })
1233
+ const before = sent.length
1234
+ await sessionStart()
1235
+ await sleep(500)
1236
+ check('S25b the restart sends no wake at all', sent.length === before, `messages=${sent.length - before}`)
1237
+ check('S25b the ledger records exactly one inflight assumed n=1',
1238
+ ledger().filter(l => /inflight assumed n=1 /.test(l)).length === 1,
1239
+ ledger().filter(l => /inflight assumed/.test(l)).join(' | ') || '(none)')
1240
+ check('S25b the durable inbox line is still readable', readFileSync(inboxFile, 'utf8').includes('S25b durable inbox line'))
1241
+ check('S25b total did not move', lastTotal() === 0, `total=${lastTotal()}`)
1242
+ // 之后的重读同样沉默,total 也不动(先真的截断、让读者看见 shrink,再把字节写回)
1243
+ const bytes = readFileSync(spoolFile())
1244
+ const rescan0 = ledgerMatches(/ rescan lines=/)
1245
+ const replay0 = ledgerMatches(/replay suppressed/)
1246
+ writeFileSync(spoolFile(), '')
1247
+ await waitFor(() => ledgerMatches(/ rescan lines=/) > rescan0, 3000)
1248
+ appendFileSync(spoolFile(), bytes)
1249
+ await waitFor(() => ledgerMatches(/replay suppressed/) > replay0, 3000)
1250
+ check('S25b a later re-read of those bytes adds no wake and no total',
1251
+ sent.length === before && lastTotal() === 0 && ledgerMatches(/replay suppressed/) > replay0,
1252
+ `messages=${sent.length - before} total=${lastTotal()} replay=${ledgerMatches(/replay suppressed/)}`)
1253
+ await shutdown()
1254
+ }
1255
+
1256
+ // ── S25c:API 拒绝可重试(每拍至多一次);日志写不进去 = 一条都不发(1.2/1.3/1.4)──────
1257
+ if (only('S25c')) {
1258
+ // (a) 抛出两次 → 下一拍重试 → 只产生一次唤醒
1259
+ await resetState()
1260
+ await sessionStart()
1261
+ hostFail = 2
1262
+ const before = sent.length
1263
+ appendWake('say', 'pm', 'pm', 'S25c-host-raises')
1264
+ const failed = await waitFor(() => ledgerMatches(/wake failed/) >= 2, 4000)
1265
+ check('S25c a raising message API is recorded as wake failed once per attempt',
1266
+ failed && ledgerMatches(/wake failed/) === 2, `failed=${ledgerMatches(/wake failed/)}`)
1267
+ check('S25c a failed send moves neither the wake count nor total',
1268
+ sent.length === before && lastTotal() === 0, `messages=${sent.length - before} total=${lastTotal()}`)
1269
+ check('S25c the failed batch left no sent record', journalOf('sent').length === 0, `sent=${journalOf('sent').length}`)
1270
+ const retried = await waitFor(() => sent.length > before, 4000)
1271
+ check('S25c the retry is the only wake that line ever produces',
1272
+ retried && sent.length === before + 1 && lastText().includes('S25c-host-raises'), `messages=${sent.length - before}`)
1273
+ check('S25c the retry closed the batch with sent', journalOf('sent').length === 1, `sent=${journalOf('sent').length}`)
1274
+ check('S25c total grew by exactly one after the retry', lastTotal() === 1, `total=${lastTotal()}`)
1275
+ await shutdown()
1276
+
1277
+ // (b) 日志不可写(把 <key>.deliver 做成目录 → EISDIR)→ 零投递 + deliver blocked;恢复后恰好一次
1278
+ await resetState()
1279
+ await sessionStart()
1280
+ const df = journalPathOf()
1281
+ await shutdown()
1282
+ rmSync(df, { force: true })
1283
+ mkdirSync(df, { recursive: true })
1284
+ await sessionStart()
1285
+ check('S25c a session whose journal cannot be written records deliver blocked',
1286
+ ledgerMatches(/deliver blocked/) >= 1, ledger().filter(l => /deliver blocked/.test(l)).at(-1) ?? '(none)')
1287
+ const beforeB = sent.length
1288
+ appendWake('say', 'pm', 'pm', 'S25c-blocked-line')
1289
+ await sleep(600)
1290
+ check('S25c nothing is sent while the journal is unwritable',
1291
+ sent.length === beforeB && lastTotal() === 0, `messages=${sent.length - beforeB} total=${lastTotal()}`)
1292
+ rmSync(df, { recursive: true, force: true })
1293
+ const delivered = await waitFor(() => sent.length > beforeB, 4000)
1294
+ check('S25c the line is delivered exactly once when the journal becomes writable again',
1295
+ delivered && sent.length === beforeB + 1 && lastTotal() === 1, `messages=${sent.length - beforeB} total=${lastTotal()}`)
1296
+ check('S25c the line was never delivered while blocked (one wake, one sent record)',
1297
+ journalOf('sent').length === 1, `sent=${journalOf('sent').length}`)
1298
+ await shutdown()
1299
+
1300
+ // (c) 过期即止:失败的行越过新鲜度地平线后不再重试、不唤醒、只计数
1301
+ // (初始年龄 9s、地平线 10s —— 慢机器上第一拍也不会误判成过期;失败后把地平线降到 1s)
1302
+ await resetState()
1303
+ await sessionStart()
1304
+ process.env.TEAM_INBOX_WATCH_STALE_SEC = '10'
1305
+ hostFail = 1
1306
+ appendWakeRaw(Buffer.from(`${Date.now() - 9000}\tsay\tpm\tpm\tS25c-stale-retry\n`))
1307
+ const sawFail = await waitFor(() => ledgerMatches(/wake failed/) >= 1, 3000)
1308
+ process.env.TEAM_INBOX_WATCH_STALE_SEC = '1' // 让下一拍时这一行已过期
1309
+ const beforeC = sent.length
1310
+ await waitFor(() => ledgerMatches(/retry stale=1/) >= 1, 3000)
1311
+ check('S25c a failed wake is not retried past the freshness horizon',
1312
+ sawFail && sent.length === beforeC && lastTotal() === 0, `messages=${sent.length - beforeC} total=${lastTotal()}`)
1313
+ check('S25c the skipped retry is counted as stale',
1314
+ ledgerMatches(/retry stale=1/) >= 1, ledger().filter(l => /retry /.test(l)).at(-1) ?? '(no retry line)')
1315
+ delete process.env.TEAM_INBOX_WATCH_STALE_SEC
1316
+ await shutdown()
1317
+ }
1318
+
1319
+ // ── S25d:逐字相同的两条 payload 靠身份与源时间区分;重写不再唤醒(2.3)──────────────
1320
+ if (only('S25d')) {
1321
+ await resetState()
1322
+ await sessionStart()
1323
+ const f = spoolFile()
1324
+ const before = sent.length
1325
+ const t1 = Date.now() - 2000
1326
+ const t2 = t1 + 1
1327
+ const text = '[pulse] 待办:未读通知 7 · 待复验 4'
1328
+ appendWakeAt(t1, 'nudge', 'pulse', '-', text)
1329
+ appendWakeAt(t2, 'nudge', 'pulse', '-', text)
1330
+ const woke = await waitFor(() => sent.length > before, 3000)
1331
+ const body = lastText()
1332
+ const rows = body.split('\n').filter(l => l.startsWith('- [nudge]'))
1333
+ check('S25d two byte-identical payloads are one wake listing two rows', woke && rows.length === 2, `messages=${sent.length - before} rows=${rows.length}`)
1334
+ check('S25d the two rows differ by source time and identity',
1335
+ rows.length === 2 && rows[0] !== rows[1] && new Set(rows).size === 2,
1336
+ rows.join(' | '))
1337
+ check('S25d the wake names each line\'s absolute source time and its identity',
1338
+ body.includes(new Date(t1).toISOString()) && body.includes(new Date(t2).toISOString())
1339
+ && body.includes(identityOf(`${t1}\tnudge\tpulse\t-\t${text}`)) && body.includes(identityOf(`${t2}\tnudge\tpulse\t-\t${text}`)),
1340
+ rows.join(' | '))
1341
+ check('S25d total counts both lines (two real deliveries)', lastTotal() === 2, `total=${lastTotal()}`)
1342
+ // 重写其中一条 → 零唤醒 + replay suppressed reason=rescan
1343
+ const first = readFileSync(f, 'utf8').split('\n').find(l => l.startsWith(String(t1))) ?? ''
1344
+ const beforeR = sent.length
1345
+ const rescanA = ledgerMatches(/ rescan lines=/)
1346
+ writeFileSync(f, `${first}\n`)
1347
+ await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanA, 3000)
1348
+ check('S25d a rewrite of one of them produces no wake', sent.length === beforeR, `messages=${sent.length - beforeR}`)
1349
+ check('S25d the rewrite is named replay suppressed reason=rescan',
1350
+ ledgerMatches(/replay suppressed n=1 reason=rescan/) >= 1,
1351
+ ledger().filter(l => /replay suppressed/.test(l)).at(-1) ?? '(none)')
1352
+ check('S25d the rescan reads deliver=0',
1353
+ /rescan lines=1 dup=1 skipped=0 deliver=0 /.test(ledger().filter(l => / rescan lines=/.test(l)).at(-1) ?? ''),
1354
+ ledger().filter(l => / rescan lines=/.test(l)).at(-1) ?? '(none)')
1355
+ check('S25d total is unchanged by the rewrite', lastTotal() === 2, `total=${lastTotal()}`)
1356
+ await shutdown()
1357
+ }
1358
+
1359
+ // ── S25e:.seen 一次性导入 / 撕裂尾 / 压缩边界与 floor(3.3/3.4/4.1/4.3)────────────
1360
+ if (only('S25e')) {
1361
+ // (a) 升级:老 .seen 只被导入一次,之后删掉它不改变任何决定
1362
+ await resetState()
1363
+ const key = KEY
1364
+ const oldLine = `${Date.now() - 7200_000}\tsay\tpm\tpm\tS25e-seen-line`
1365
+ mkdirSync(WATCH_DIR, { recursive: true })
1366
+ writeFileSync(join(WATCH_DIR, `${key}.seen`), `${oldLine}\n`)
1367
+ await sessionStart()
1368
+ check('S25e the first start imports <key>.seen once and records it',
1369
+ ledgerMatches(/seen import n=1 /) === 1
1370
+ && journalLines().some(l => / sent .*imported=1/.test(l) && l.includes(identityOf(oldLine))),
1371
+ ledger().filter(l => /seen import/.test(l)).at(-1) ?? '(no import line)')
1372
+ const beforeA = sent.length
1373
+ appendWakeRaw(Buffer.from(`${oldLine}\n`))
1374
+ await sleep(600)
1375
+ check('S25e an imported (already-delivered) line wakes nobody',
1376
+ sent.length === beforeA && lastTotal() === 0 && ledgerMatches(/replay suppressed/) >= 1,
1377
+ `messages=${sent.length - beforeA} total=${lastTotal()}`)
1378
+ // 删掉 .seen:同一份字节再重写一次,仍然沉默(日志是唯一记忆;先截断让读者看见 shrink)
1379
+ rmSync(join(WATCH_DIR, `${key}.seen`), { force: true })
1380
+ const bytes = readFileSync(spoolFile())
1381
+ const rescanB = ledgerMatches(/ rescan lines=/)
1382
+ const replayB = ledgerMatches(/replay suppressed/)
1383
+ writeFileSync(spoolFile(), '')
1384
+ await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanB, 3000)
1385
+ appendFileSync(spoolFile(), bytes)
1386
+ await waitFor(() => ledgerMatches(/replay suppressed/) > replayB, 3000)
1387
+ check('S25e deleting .seen changes no delivery decision',
1388
+ sent.length === beforeA && lastTotal() === 0, `messages=${sent.length - beforeA} total=${lastTotal()}`)
1389
+ await shutdown()
1390
+
1391
+ // (b) 撕裂尾:read 完整、intent 被截断 → 结果未知,永不重投
1392
+ await resetState()
1393
+ mkdirSync(WATCH_DIR, { recursive: true })
1394
+ const tornLine = `${Date.now()}\tsay\tpm\tpm\tS25e-torn-line`
1395
+ writeFileSync(spoolFile(), `${tornLine}\n`)
1396
+ const tornId = identityOf(tornLine)
1397
+ writeFileSync(journalPathOf(),
1398
+ `${new Date().toISOString()} start baseline=0 size=0 head=absent\n` +
1399
+ `${new Date().toISOString()} read seq=1 off=1 size=1 head=empty id=${jesc(tornId)} src=${tornLine.split('\t')[0]} kind=say from=pm durable=pm preview=S25e-torn-line\n` +
1400
+ `${new Date().toISOString()} intent seq=`)
1401
+ await sessionStart()
1402
+ check('S25e a torn trailing record is named in the ledger',
1403
+ ledgerMatches(/torn tail/) >= 1, ledger().filter(l => /torn tail/.test(l)).at(-1) ?? '(none)')
1404
+ check('S25e a torn tail is treated as inflight assumed',
1405
+ ledgerMatches(/inflight assumed n=1 /) === 1, ledger().filter(l => /inflight assumed/.test(l)).join(' | ') || '(none)')
1406
+ const beforeB = sent.length
1407
+ await sleep(500)
1408
+ check('S25e a line whose outcome is unknown is never woken', sent.length === beforeB, `messages=${sent.length - beforeB}`)
1409
+ const rescanC = ledgerMatches(/ rescan lines=/)
1410
+ writeFileSync(spoolFile(), '')
1411
+ await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanC, 3000)
1412
+ appendFileSync(spoolFile(), `${tornLine}\n`)
1413
+ await waitFor(() => ledgerMatches(/replay suppressed/) >= 1, 3000)
1414
+ check('S25e a later rewrite of a torn-read line stays silent',
1415
+ sent.length === beforeB && lastTotal() === 0, `messages=${sent.length - beforeB} total=${lastTotal()}`)
1416
+ await shutdown()
1417
+
1418
+ // (c) 压缩:越界即压到界内、写 floor=;保留的身份仍被压制,被淘汰的身份 unprovable
1419
+ await resetState()
1420
+ process.env.TEAM_INBOX_WATCH_JOURNAL_MAX = '24'
1421
+ await sessionStart()
1422
+ for (let i = 0; i < 12; i++) {
1423
+ appendWakeAt(Date.now() - (12 - i) * 60_000, 'say', 'pm', 'pm', `S25e-compact-${i}`)
1424
+ await waitFor(() => journalOf('sent').length > i, 4000)
1425
+ }
1426
+ check('S25e compaction keeps the journal under the bound', journalLines().length <= 24, `records=${journalLines().length}`)
1427
+ check('S25e compaction records its eviction floor',
1428
+ ledgerMatches(/journal compacted /) >= 1 && / floor=\S+ floor_ts=\d+ /.test(ledger().filter(l => /journal compacted/.test(l)).at(-1) ?? ''),
1429
+ ledger().filter(l => /journal compacted/.test(l)).at(-1) ?? '(none)')
1430
+ const all = spoolLines()
1431
+ const oldest = all[0] ?? ''
1432
+ const newest = all[all.length - 1] ?? ''
1433
+ const keptIds = journalOf('read').map(r => r.fields.id)
1434
+ check('S25e the retained identities are still in the journal and the evicted one is not',
1435
+ keptIds.includes(identityOf(newest)) && !keptIds.includes(identityOf(oldest)),
1436
+ `kept=${keptIds.length} oldestEvicted=${!keptIds.includes(identityOf(oldest))}`)
1437
+ await shutdown()
1438
+ // 重启后(内存清零)重写两条:保留的 → replay suppressed;被淘汰的 → unprovable,永不唤醒
1439
+ await sessionStart()
1440
+ const beforeC = sent.length
1441
+ const totalC = lastTotal()
1442
+ const rescan0 = ledgerMatches(/ rescan lines=/)
1443
+ writeFileSync(spoolFile(), `${oldest}\n${newest}\n`)
1444
+ await waitFor(() => ledgerMatches(/ rescan lines=/) > rescan0, 3000)
1445
+ await waitFor(() => ledgerMatches(/unprovable n=1 /) >= 1, 3000)
1446
+ check('S25e a retained identity is suppressed on a rewrite',
1447
+ ledgerMatches(/replay suppressed n=1 reason=rescan/) >= 1,
1448
+ ledger().filter(l => /replay suppressed/.test(l)).at(-1) ?? '(none)')
1449
+ check('S25e an identity below the eviction floor is unprovable, never woken',
1450
+ ledgerMatches(/unprovable n=1 /) >= 1, ledger().filter(l => /unprovable/.test(l)).at(-1) ?? '(none)')
1451
+ check('S25e compaction cannot resurrect a delivery',
1452
+ sent.length === beforeC && lastTotal() === totalC,
1453
+ `messages=${sent.length - beforeC} total=${totalC}->${lastTotal()}`)
1454
+ check('S25e the rescan reads deliver=0 with dup=1 and the unprovable counted separately',
1455
+ /rescan lines=2 dup=1 skipped=0 deliver=0 /.test(ledger().filter(l => / rescan lines=/.test(l)).at(-1) ?? ''),
1456
+ ledger().filter(l => / rescan lines=/.test(l)).at(-1) ?? '(none)')
1457
+ delete process.env.TEAM_INBOX_WATCH_JOURNAL_MAX
1458
+ await shutdown()
1459
+ }
1460
+
1461
+ // ── S25f:事故重放(原始字节 + 从 .seen/交付事实播种的日志)→ 零唤醒、deliver=0(5.1)──
1462
+ if (only('S25f')) {
1463
+ await resetState()
1464
+ const fx = join(SKILL_DIR, 'tests/fixtures/p71-incident')
1465
+ const dev2 = readFileSync(join(fx, 'dev2.wake'))
1466
+ const seenLines = readFileSync(join(fx, 'dev2.seen'), 'utf8').split('\n').filter(l => l.trim())
1467
+ const pmNudges = readFileSync(join(fx, 'pm-nudges.wake'))
1468
+ mkdirSync(WATCH_DIR, { recursive: true })
1469
+ writeFileSync(spoolFile(), Buffer.concat([dev2, pmNudges]))
1470
+ // 从事故的 sent 事实播种:dev2 的 8 条 .seen + PM 的三条 nudge;最老的 dev2 行(投过但没记进 .seen)不播种
1471
+ const seeded = [...seenLines.map(identityOf), ...pmNudges.toString('utf8').split('\n').filter(l => l.trim()).map(identityOf)]
1472
+ const seedRecs = [`${new Date().toISOString()} start baseline=0 size=0 head=absent`]
1473
+ seeded.forEach((id, i) => seedRecs.push(`${new Date().toISOString()} sent seq=-${i + 1} id=${jesc(id)} imported=1`))
1474
+ writeFileSync(journalPathOf(), `${seedRecs.join('\n')}\n`)
1475
+ const before = sent.length
1476
+ await sessionStart() // 基线吞掉整份 spool(没有人活着看过它)
1477
+ await sleep(500)
1478
+ check('S25f the incident spool produces zero wakes at startup', sent.length === before, `messages=${sent.length - before}`)
1479
+ // ① 记录下来的那一拍(事故 17:46:49):原位截断 → 读者看到 shrink,rescan 读 0 行(`deliver=0`)
1480
+ const bytes = readFileSync(spoolFile())
1481
+ writeFileSync(spoolFile(), '')
1482
+ await waitFor(() => ledgerMatches(/ rescan lines=/) >= 1, 3000)
1483
+ check('S25f the recorded truncation reads deliver=0 (the incident shape)',
1484
+ sent.length === before && /rescan lines=0 dup=0 skipped=0 deliver=0 /.test(ledger().filter(l => / rescan lines=/.test(l)).at(-1) ?? ''),
1485
+ ledger().filter(l => / rescan lines=/.test(l)).at(-1) ?? '(none)')
1486
+ // ② 同一批字节写回(普通路径):已投递的身份一律 replay suppressed,没记进 .seen 的那一行过期只计数
1487
+ appendFileSync(spoolFile(), bytes)
1488
+ await waitFor(() => ledgerMatches(/replay suppressed n=11 reason=normal/) >= 1, 3000)
1489
+ check('S25f every seeded identity is replay-suppressed, none is woken',
1490
+ sent.length === before && ledgerMatches(/replay suppressed n=11 reason=normal/) >= 1,
1491
+ ledger().filter(l => /replay suppressed/.test(l)).at(-1) ?? '(none)')
1492
+ check('S25f the one delivered-but-unrecorded line is counted stale and never woken',
1493
+ ledgerMatches(/classify stale=1 unparsable=0/) >= 1, ledger().filter(l => /classify /.test(l)).at(-1) ?? '(none)')
1494
+ // ③ 截断与写回落在同一拍:有界重扫也要逐条分类、零唤醒(reason=rescan)
1495
+ const classifyBefore = ledgerMatches(/classify stale=/)
1496
+ appendFileSync(spoolFile(), `${Date.now() - 3600_000}\tknock\tpm\t-\tS25f-padding-${'P'.repeat(200)}\n`)
1497
+ await waitFor(() => ledgerMatches(/classify stale=/) > classifyBefore, 3000)
1498
+ const rescanBefore = ledgerMatches(/ rescan lines=/)
1499
+ writeFileSync(spoolFile(), bytes)
1500
+ await waitFor(() => ledgerMatches(/ rescan lines=/) > rescanBefore, 3000)
1501
+ await waitFor(() => ledgerMatches(/replay suppressed n=11 reason=rescan/) >= 1, 3000)
1502
+ const rescanLine = ledger().filter(l => / rescan lines=/.test(l)).at(-1) ?? ''
1503
+ check('S25f a one-shot truncate+rewrite is rescanned, classified and silent',
1504
+ ledgerMatches(/ rescan lines=/) > rescanBefore && sent.length === before
1505
+ && /rescan lines=12 dup=11 skipped=0 deliver=0 stale=1 /.test(rescanLine)
1506
+ && ledgerMatches(/replay suppressed n=11 reason=rescan/) >= 1,
1507
+ `${rescanLine.trim()} || messages=${sent.length - before}`)
1508
+ check('S25f total is untouched by the incident replay', lastTotal() === 0, `total=${lastTotal()}`)
1509
+ await shutdown()
1510
+ }
1511
+
1512
+ // ── S26:唤醒文本契约(源行点名 / 单调序号 / 日志路径 / 形状不变)(2.2)──────────────
1513
+ if (only('S26')) {
1514
+ await resetState()
1515
+ await sessionStart()
1516
+ const f = spoolFile()
1517
+ const t1 = Date.now()
1518
+ const b0 = sent.length
1519
+ appendWakeAt(t1, 'say', 'pm', 'pm', 'S26-first')
1520
+ await waitFor(() => sent.length >= b0 + 1)
1521
+ const seq1 = Number(/#(\d+)/.exec(lastText())?.[1] ?? 0)
1522
+ const t2 = t1 + 1
1523
+ appendWakeAt(t2, 'say', 'pm', 'pm', 'S26-second')
1524
+ await waitFor(() => sent.length >= b0 + 2)
1525
+ const body = lastText()
1526
+ const seq2 = Number(/#(\d+)/.exec(body)?.[1] ?? 0)
1527
+ check('S26 the wake carries a monotonic sequence and an absolute send time',
1528
+ seq2 === seq1 + 1 && /#\d+ · \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/.test(body), `seqs=${seq1}->${seq2}`)
1529
+ const line2 = `${t2}\tsay\tpm\tpm\tS26-second`
1530
+ check('S26 every listed line names its own absolute source time and identity',
1531
+ body.includes(new Date(t2).toISOString()) && body.includes(identityOf(line2)),
1532
+ body.split('\n').filter(l => l.startsWith('- ')).join(' | '))
1533
+ check('S26 the wake names the delivery journal the identities were recorded in',
1534
+ body.includes(journalPathOf()) && existsSync(journalPathOf()),
1535
+ (body.split('\n').find(l => l.includes('Delivery journal')) ?? '(none)').slice(0, 200))
1536
+ check('S26 the wake shape is unchanged (customType/triggerTurn/followUp)',
1537
+ sent.at(-1)?.msg?.customType === 'team-inbox' && sent.at(-1)?.opts?.triggerTurn === true
1538
+ && sent.at(-1)?.opts?.deliverAs === 'followUp',
1539
+ JSON.stringify({ customType: sent.at(-1)?.msg?.customType, ...(sent.at(-1)?.opts ?? {}) }))
1540
+ check('S26 no payload dump: the wake stays a bounded one-line pointer per line',
1541
+ body.split('\n').filter(l => l.startsWith('- ')).every(l => l.length <= 220), `len=${body.length}`)
1542
+ check('S26 every wake line in the ledger names seq and ids',
1543
+ ledger().filter(l => / wake n=/.test(l)).every(l => / seq=\d+ ids=\S+/.test(l)),
1544
+ ledger().filter(l => / wake n=/.test(l)).join(' | '))
1545
+ await shutdown()
1546
+ }
1547
+
1548
+ // ── 反向守卫:真实仓库 state/ 未被触碰 ───────────────────────────────────────
1549
+ {
1550
+ const after = snapshot(REAL_STATE)
1551
+ check('reverse guard: the real repo state/ is untouched', after === REAL_BEFORE,
1552
+ after === REAL_BEFORE ? '' : 'real state/ changed during the harness')
1553
+ }
1554
+
1555
+ console.log(failures === 0
1556
+ ? `TEAM-IW-HARNESS OK (skipped=${skipped})`
1557
+ : `TEAM-IW-HARNESS FAIL (${failures})`)
1558
+ console.log(`fixture: ${keep || process.env.TEAM_IW_KEEP === '1' ? TMP : '(removed)'}`)
1559
+ process.exit(failures === 0 ? 0 : 1)