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,663 @@
1
+ /**
2
+ * teamsmith · notify 扩展
3
+ *
4
+ * 作用:worker agent 每结束一个回合(`agent_settled`,Pi 不会再自动继续的那个点),
5
+ * 自动把一条简报写进 PM 的收件箱,并(可选)在 PM 的 tmux 窗口里敲一行把它唤醒。
6
+ *
7
+ * 为什么必须显式 `-e` 加载:linked worktree 里 Pi 不会自动发现项目本地的
8
+ * `.pi/extensions/`(CEP 已验证过),所以 `team dispatch` 用 `-e <skill>/extension/team-notify.ts`
9
+ * 显式传入。
10
+ *
11
+ * 守卫(全部失败都静默,通知绝不能影响 agent 会话):
12
+ * - cwd 必须位于 <项目根>/<worktrees>/ 之下(主工作树/PM 会话不触发)
13
+ * - 窗口名不能等于 PM 窗口名(避免 PM 自触发循环)
14
+ * - tmux session 必须是配置里的那个
15
+ * - 同样的简报在 TEAM_NOTIFY_DEDUP_SEC 秒内只发一次(Pi 可能连续 settle)
16
+ *
17
+ * 配置来自 <项目根>/.pi/team/config.sh,仅解析需要的少量扁平 KEY=VALUE,
18
+ * 不 source(不在 agent 的 Node 进程里执行项目代码)。
19
+ */
20
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
21
+ import { execFileSync } from 'node:child_process'
22
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
23
+ import { dirname, join, resolve } from 'node:path'
24
+ import { fileURLToPath } from 'node:url'
25
+
26
+ type Cfg = {
27
+ session: string
28
+ pmWindow: string
29
+ worktreesDir: string
30
+ docsDir: string
31
+ notifyTmux: boolean
32
+ dedupSec: number
33
+ maxChars: number
34
+ log: string
35
+ roster: string[]
36
+ }
37
+
38
+ const DEFAULTS: Cfg = {
39
+ session: 'team',
40
+ pmWindow: 'pm',
41
+ worktreesDir: '.worktrees',
42
+ docsDir: 'docs/team',
43
+ notifyTmux: true,
44
+ dedupSec: 20,
45
+ maxChars: 150,
46
+ log: '/tmp/teamsmith-notify.log',
47
+ roster: [],
48
+ }
49
+
50
+ /** P160 F2 · 修订标识的宽度:HEAD 的**前 12 个十六进制字符**,工具自己截(不用受 core.abbrev
51
+ * 和对象数影响的 `--short`)—— 与 CLI 的 `cut -c1-12` 是同一契约,同一 HEAD 在两个发送方逐字节相同。
52
+ * 接收方不需要 checkout:reviews/<ID>.md 里记的 HEAD 与 tip 互为前缀(同一个 revision)就算已判过
53
+ * (`team review` 今天写 9 位,12 位的 wire 形状让这个判定不受 Git 设置影响)。 */
54
+ const TIP_WIDTH = 12
55
+
56
+ /** 本扩展所在 skill 的目录(<skill>/extension/team-notify.ts) */
57
+ function skillDir(): string {
58
+ try {
59
+ return resolve(dirname(fileURLToPath(import.meta.url)), '..')
60
+ } catch {
61
+ return ''
62
+ }
63
+ }
64
+
65
+ /** 从 <skill>/scripts/lib/common.sh 读 TEAM_VERSION */
66
+ function skillVersion(): string {
67
+ try {
68
+ const f = join(skillDir(), 'scripts/lib/common.sh')
69
+ return /^TEAM_VERSION="([^"]+)"/m.exec(readFileSync(f, 'utf8'))?.[1] ?? ''
70
+ } catch {
71
+ return ''
72
+ }
73
+ }
74
+
75
+ function run(cmd: string, args: string[], cwd?: string): string {
76
+ try {
77
+ return execFileSync(cmd, args, { cwd, encoding: 'utf8', timeout: 5000 }).trim()
78
+ } catch {
79
+ return ''
80
+ }
81
+ }
82
+
83
+ function expand(value: string): string {
84
+ return value
85
+ .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name: string) => process.env[name] ?? '')
86
+ .replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (_, name: string) => process.env[name] ?? '')
87
+ }
88
+
89
+ function unquote(raw: string): string {
90
+ const v = raw.trim()
91
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) return v.slice(1, -1)
92
+ return v
93
+ }
94
+
95
+ /** 去掉行尾注释:「值 + 空白 + #...」。配置约定:值里不要写 # */
96
+ function stripComment(raw: string): string {
97
+ const m = /^(.*?)\s+#.*$/.exec(raw)
98
+ return m ? m[1] : raw
99
+ }
100
+
101
+ /** 定位团队根目录(期望是主工作树)。
102
+ * M40:与 team CLI / inbox-watch 同一条原则 —— **cwd 推导优先**,TEAM_ROOT 只在①与推导结果一致、
103
+ * 或②完全推导不出来且它指向一个真项目时被信任。为什么不许 env 优先(M40 实测):agent 工作树里也有
104
+ * config.sh 的副本,而收件箱/重载标记必须落在主工作树的账本里 —— env 指到工作树时,旧实现会把 cwd
105
+ * 判成「不在 worktrees 之下」(前缀是 <wt>/.worktrees/),于是**整个回合通知都不发**(收件箱 0 行)。
106
+ * 推导顺序:git 主工作树(账本所在地)→ 向上找 config.sh;两路都推不出来才退回 TEAM_ROOT。 */
107
+ function findRoot(cwd: string): string {
108
+ const envRoot = process.env.TEAM_ROOT ? resolve(process.env.TEAM_ROOT) : ''
109
+ let derived = ''
110
+ const common = run('git', ['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'])
111
+ if (common) {
112
+ const main = dirname(common)
113
+ if (existsSync(join(main, '.pi/team/config.sh'))) derived = main
114
+ }
115
+ if (!derived) {
116
+ let dir = resolve(cwd)
117
+ for (;;) {
118
+ if (existsSync(join(dir, '.pi/team/config.sh'))) { derived = dir; break }
119
+ const parent = dirname(dir)
120
+ if (parent === dir) break
121
+ dir = parent
122
+ }
123
+ }
124
+ if (envRoot && envRoot !== derived) {
125
+ if (derived) {
126
+ log(`TEAM_IDENTITY_CONFLICT inherited TEAM_ROOT=${envRoot} ≠ cwd-derived=${derived}: using cwd`, readCfg(derived))
127
+ return derived
128
+ }
129
+ if (existsSync(join(envRoot, '.pi/team/config.sh'))) return envRoot
130
+ return ''
131
+ }
132
+ return derived || envRoot
133
+ }
134
+
135
+ /** 后台车道自己写记录的 state 目录(team-bg 的 findRoot + stateDir 两条规则的复刻)——挂起判定
136
+ * **只**读这里。为什么不拿 notify 自己的 root 顶替(design 决策 4):本仓 worker worktree 不带 config,
137
+ * 两侧今天巧合都落主工作树;而 worktree 自带 config 的形状(S11 夹具)下车道落 worktree 侧,
138
+ * notify 的 git-common-dir 就会读错目录。规则:显式 TEAM_STATE_DIR 优先;否则「cwd 的 worktree 带
139
+ * config → 它自己;TEAM_ROOT(带 config);最近的带 config 的祖先;git 主工作树(最后的兜底)」。
140
+ * 任何一步推不出来 → 空串(调用方 fail-closed:不挂起)。 */
141
+ function laneStateDir(cwd: string): string {
142
+ const envDir = process.env.TEAM_STATE_DIR
143
+ if (envDir) return resolve(envDir)
144
+ let root = ''
145
+ const top = run('git', ['-C', cwd, 'rev-parse', '--path-format=absolute', '--show-toplevel'])
146
+ if (top && existsSync(join(top, '.pi/team/config.sh'))) root = resolve(top)
147
+ const envRoot = process.env.TEAM_ROOT ? resolve(process.env.TEAM_ROOT) : ''
148
+ if (!root && envRoot && existsSync(join(envRoot, '.pi/team/config.sh'))) root = envRoot
149
+ if (!root) {
150
+ let dir = resolve(cwd)
151
+ for (;;) {
152
+ if (existsSync(join(dir, '.pi/team/config.sh'))) { root = dir; break }
153
+ const parent = dirname(dir)
154
+ if (parent === dir) break
155
+ dir = parent
156
+ }
157
+ }
158
+ if (!root) {
159
+ const common = run('git', ['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'])
160
+ if (common) {
161
+ const main = dirname(common)
162
+ if (existsSync(join(main, '.pi/team/config.sh'))) root = main
163
+ }
164
+ }
165
+ return root ? join(root, '.pi/team/state') : ''
166
+ }
167
+
168
+ /** notify 自己的落点(它的项目根 + .pi/team/state)。**不许**拿它当车道的目录;只用来在两侧分歧时
169
+ * 记一行日志点名(否则这种错位会静默地读到错目录)。 */
170
+ function notifyStateDir(root: string): string {
171
+ return root ? join(root, '.pi/team/state') : ''
172
+ }
173
+
174
+ /** /proc/<pid>/stat 的启动时间指纹(第 22 字段)。comm 字段带空格/括号 → 按**最后一个** `)` 切开再数。
175
+ * 进程不在 / 读不到 → 空串(调用方据此判「不算在跑」)。 */
176
+ function procStartTime(pid: number): string {
177
+ try {
178
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
179
+ const rest = stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\s+/)
180
+ return rest[19] ?? ''
181
+ } catch {
182
+ return ''
183
+ }
184
+ }
185
+
186
+ /** 真实路径(软链与尾斜杠都归一):只接受绝对路径 —— 相对路径在记录里没有对象可解析,属畸形;
187
+ * 解析失败(路径已不存在 / 无权限)返回空串。调用方拿空串一律 fail-closed(不判挂起,绝不猜)。 */
188
+ function realPathOf(p: string): string {
189
+ if (!p || p[0] !== '/') return ''
190
+ try {
191
+ return realpathSync(p)
192
+ } catch {
193
+ return ''
194
+ }
195
+ }
196
+
197
+ /** P236 · 本会话的归属路径集合(真实路径):会话自己的 cwd 与它所在的工作树。任一路径解析失败就不
198
+ * 放进去 —— 集合为空 = 一条作业都不认(fail-closed 的极端形状,好过认错别人的作业)。 */
199
+ function ownedSessionPaths(cwd: string, worktree: string): Set<string> {
200
+ const owned = new Set<string>()
201
+ for (const p of [cwd, worktree]) {
202
+ const real = realPathOf(resolve(p))
203
+ if (real) owned.add(real)
204
+ }
205
+ return owned
206
+ }
207
+
208
+ /** P236 · 归属判据:作业记录里的 `cwd`(作业启动时的工作目录,也就是拥有它的那个席位的工作树)
209
+ * 解析到本会话自己的工作树/cwd(真实路径相等)才算「我的作业」。缺 `cwd`、相对路径、解析失败、
210
+ * 或指向别人的工作树 → 都不算(fail-closed)。 */
211
+ function isOwnedCwd(jobCwd: string, owned: Set<string>): boolean {
212
+ const real = realPathOf(jobCwd)
213
+ return real !== '' && owned.has(real)
214
+ }
215
+
216
+ /** 在跑作业集合:读车道目录下的 `bg/*.job`,逐条做 (pid, start-time) 活体验证(与 `team bg list`
217
+ * 同一条身份规则),再按 `cwd` 只留**本会话自己的**作业(P236 归属范围 —— 同一车道目录里的记录
218
+ * 可能属于别的席位,把别人的长作业算成自己挂起会污染 `awaiting=`)。任何一条失败都**跳过**
219
+ * (目录/记录读不了、软链-FIFO 记录、pid 非正整数、start 缺失、/proc 读不到、指纹不符、cwd 缺失
220
+ * 或不属于本会话)—— fail-closed:判定的不确定方向永远是「不挂起」,绝不假造挂起(design 决策 4)。 */
221
+ function runningLaneJobs(laneDir: string, owned: Set<string>): string[] {
222
+ if (!laneDir || owned.size === 0) return []
223
+ let names: string[]
224
+ try {
225
+ names = readdirSync(join(laneDir, 'bg'))
226
+ } catch {
227
+ return [] // 车道还没起过作业(目录不存在)/ 读不了:没有在跑作业
228
+ }
229
+ const ids: string[] = []
230
+ for (const name of names.sort()) {
231
+ if (!name.endsWith('.job')) continue
232
+ const id = name.slice(0, -'.job'.length)
233
+ if (!/^[A-Za-z0-9._-]+$/.test(id)) continue // 平坦 id(读侧边界与 team bg 同规则)
234
+ try {
235
+ const file = join(laneDir, 'bg', name)
236
+ if (!lstatSync(file).isFile()) continue // 软链 / FIFO / 目录:记录畸形
237
+ const fields: Record<string, string> = {}
238
+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
239
+ const i = line.indexOf('=')
240
+ if (i > 0) fields[line.slice(0, i).trim()] = line.slice(i + 1).trim()
241
+ }
242
+ const pid = Number(fields.pid ?? '')
243
+ const start = fields.start ?? ''
244
+ if (!Number.isInteger(pid) || pid <= 0 || !start) continue
245
+ if (procStartTime(pid) !== start) continue // 死进程 / pid 复用 / /proc 读不到:都不算在跑
246
+ if (!isOwnedCwd(fields.cwd ?? '', owned)) continue // P236:别人的作业不算自己挂起
247
+ ids.push(id)
248
+ } catch {
249
+ continue // 读不了:不算在跑
250
+ }
251
+ }
252
+ return ids
253
+ }
254
+
255
+ function readCfg(root: string): Cfg {
256
+ const file = process.env.TEAM_CONFIG_FILE || join(root, '.pi/team/config.sh')
257
+ const cfg: Cfg = { ...DEFAULTS }
258
+ let text = ''
259
+ try {
260
+ text = readFileSync(file, 'utf8')
261
+ } catch {
262
+ return cfg
263
+ }
264
+ const values: Record<string, string> = {}
265
+ for (const line of text.split(/\r?\n/)) {
266
+ const m = /^\s*(TEAM_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line)
267
+ if (!m) continue
268
+ const raw = m[2]
269
+ values[m[1]] = expand(unquote(stripComment(raw)))
270
+ }
271
+ const pick = (key: string): string | undefined => values[key]?.trim() || undefined
272
+ cfg.session = pick('TEAM_SESSION') ?? cfg.session
273
+ cfg.pmWindow = pick('TEAM_PM_WINDOW') ?? cfg.pmWindow
274
+ cfg.worktreesDir = pick('TEAM_WORKTREES_DIR') ?? cfg.worktreesDir
275
+ cfg.docsDir = pick('TEAM_DOCS_DIR') ?? cfg.docsDir
276
+ if (pick('TEAM_NOTIFY_TMUX')) cfg.notifyTmux = values.TEAM_NOTIFY_TMUX !== '0' && values.TEAM_NOTIFY_TMUX !== 'false'
277
+ const dedup = Number(pick('TEAM_NOTIFY_DEDUP_SEC') ?? NaN)
278
+ if (Number.isFinite(dedup) && dedup >= 0) cfg.dedupSec = dedup
279
+ const max = Number(pick('TEAM_INBOX_MAX_CHARS') ?? NaN)
280
+ if (Number.isFinite(max) && max > 0) cfg.maxChars = max
281
+ cfg.log = pick('TEAM_NOTIFY_LOG') ?? cfg.log
282
+ cfg.roster = (pick('TEAM_AGENTS') ?? '').split(/[\s,]+/).filter(Boolean)
283
+ return cfg
284
+ }
285
+
286
+ /** 发送者解析(与 CLI 的 team_sender_from_dir 同规则,见 openspec/changes/notify-sender-identity/design.md §2):
287
+ * cwd 在 <root>/<worktrees>/ 之下(上面那个守卫已经证明)→ 路径的一级目录名就是席位;名册里真有这个名字时
288
+ * 取名册里的拼写,不匹配时目录名自己就是发送者(review-<ID> 这类非席位目录也算名字)。推不出来 → 空串。 */
289
+ function senderFromDir(cwd: string, wtPrefix: string, roster: string[]): string {
290
+ const rel = `${cwd}`.slice(wtPrefix.length)
291
+ const first = rel.split('/')[0] ?? ''
292
+ if (!first) return ''
293
+ return roster.find(name => name === first) ?? first
294
+ }
295
+
296
+ function tail(line: string, max: number): string {
297
+ const flat = line.replace(/\s+/g, ' ').trim()
298
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat
299
+ }
300
+
301
+ /** P160 F3 · 任务标识的证据:<ID> 必须在 state/<sender>.env 的 task=、看板行或任务书里真的存在
302
+ * (与 CLI 的 team_notify_task_proven 同一组判据)。席位名(agent/<席位>)不是任务;没有证据就不盖。 */
303
+ function hasTaskEvidence(root: string, cfg: Cfg, agent: string, id: string): boolean {
304
+ const stateDir = process.env.TEAM_STATE_DIR || join(root, '.pi/team/state')
305
+ try {
306
+ const st = readFileSync(join(stateDir, `${agent}.env`), 'utf8')
307
+ if (st.split(/\r?\n/).some(l => l.trim() === `task=${id}`)) return true
308
+ } catch { /* 没有这个席位的状态记录 */ }
309
+ const tasksDir = join(root, cfg.docsDir, 'tasks')
310
+ try {
311
+ if (existsSync(join(tasksDir, `${id}.md`))) return true
312
+ if (readdirSync(tasksDir).some(f => f.startsWith(`${id}-`) && f.endsWith('.md'))) return true
313
+ } catch { /* 没有任务书目录 */ }
314
+ try {
315
+ for (const line of readFileSync(join(root, cfg.docsDir, 'BOARD.md'), 'utf8').split(/\r?\n/)) {
316
+ if (!line.trimStart().startsWith('|')) continue
317
+ const cells = line.split('|')
318
+ if ((cells[1] ?? '').trim() === id) return true
319
+ }
320
+ } catch { /* 没有看板 */ }
321
+ return false
322
+ }
323
+
324
+ /** 一条 assistant 消息里的文本(字符串或 content parts) */
325
+ function messageText(content: unknown): string {
326
+ if (typeof content === 'string') return content
327
+ if (Array.isArray(content)) {
328
+ return content
329
+ .map(part => (part && typeof part === 'object' && 'text' in part ? String((part as { text?: unknown }).text ?? '') : ''))
330
+ .join(' ')
331
+ }
332
+ return ''
333
+ }
334
+
335
+ /** 回合是否真的完成了:模型给了最终答复(stop/length)才算。
336
+ * toolUse = 还在调工具(mid-turn);aborted/error = 被中断。M4.3 E:只有前者能当「最后消息」。 */
337
+ function isCompletedTurn(stopReason: string): boolean {
338
+ return stopReason === 'stop' || stopReason === 'length'
339
+ }
340
+
341
+ function log(line: string, cfg: Cfg): void {
342
+ try {
343
+ appendFileSync(cfg.log, `${new Date().toISOString()} ${line}\n`)
344
+ } catch {
345
+ /* ignore */
346
+ }
347
+ }
348
+
349
+ /** 内容指纹(FNV-1a 32 位):去重键必须能区分「前缀相同、后半不同」的简报(M6.3 F17) */
350
+ function fingerprint(text: string): string {
351
+ let h = 0x811c9dc5
352
+ for (let i = 0; i < text.length; i++) {
353
+ h ^= text.charCodeAt(i)
354
+ h = Math.imul(h, 0x01000193) >>> 0
355
+ }
356
+ return h.toString(16).padStart(8, '0')
357
+ }
358
+
359
+ /** 同一条简报在 dedupSec 秒内只发一次 */
360
+ function isDuplicate(key: string, sec: number, stateDir: string): boolean {
361
+ if (sec <= 0) return false
362
+ const file = join(stateDir, 'notify-dedup')
363
+ const now = Date.now()
364
+ const rows: Array<[string, number]> = []
365
+ try {
366
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
367
+ const idx = line.indexOf(' ')
368
+ if (idx <= 0) continue
369
+ const t = Number(line.slice(0, idx))
370
+ if (Number.isFinite(t) && now - t < sec * 1000) rows.push([line.slice(idx + 1), t])
371
+ }
372
+ } catch {
373
+ /* first run */
374
+ }
375
+ if (rows.some(([k]) => k === key)) return true
376
+ rows.push([key, now])
377
+ try {
378
+ writeFileSync(file, rows.map(([k, t]) => `${t} ${k}`).join('\n') + '\n')
379
+ } catch {
380
+ /* ignore */
381
+ }
382
+ return false
383
+ }
384
+
385
+ export default function (pi: ExtensionAPI) {
386
+ let count = 0
387
+
388
+ // M4.3 E:内部生命周期事件(压缩 / 会话重启 / reload)会以**同一个回合里的 settle** 形式冒出来,
389
+ // 而那不是「agent 交回合了、在等 PM」(现场:PM 收到一条读起来像「agent 停了但还有未提交文件」的
390
+ // 通知,其实 agent 正 mid-turn)。这里记「本回合内发生过什么」,settle 时据此判断真伪。
391
+ // 回合边界用 before_agent_start(一次用户提交只发一次;继续/重试/压缩不走它)。
392
+ let lifecycleDuringTurn = ''
393
+ const noteLifecycle = (what: string): void => {
394
+ lifecycleDuringTurn = what
395
+ }
396
+ pi.on('before_agent_start', async () => {
397
+ lifecycleDuringTurn = ''
398
+ })
399
+ pi.on('session_start', async (event: any) => {
400
+ // startup 是正常开局;reload/new/resume/fork 都是「会话被换掉了」的内部事件
401
+ const reason = String(event?.reason ?? '')
402
+ if (reason && reason !== 'startup') noteLifecycle(`session_start(${reason})`)
403
+ })
404
+ pi.on('session_before_compact', async () => noteLifecycle('compaction'))
405
+ pi.on('session_compact', async (event: any) => noteLifecycle(`compaction(${String(event?.reason ?? '?')})`))
406
+ pi.on('session_compact_failed', async () => noteLifecycle('compaction-failed'))
407
+ pi.on('session_shutdown', async (event: any) => noteLifecycle(`session_shutdown(${String(event?.reason ?? '?')})`))
408
+
409
+ pi.on('agent_settled', async (_event, ctx) => {
410
+ const cwd = ctx.cwd ?? process.cwd()
411
+ const root = findRoot(cwd)
412
+ if (!root) return
413
+ const cfg = readCfg(root)
414
+
415
+ const wtPrefix = `${resolve(root, cfg.worktreesDir)}/`
416
+ if (!`${resolve(cwd)}`.startsWith(wtPrefix)) {
417
+ log(`skip settle (not in worktrees): cwd=${cwd} root=${root} prefix=${wtPrefix}`, cfg)
418
+ return
419
+ }
420
+
421
+ const pane = process.env.TMUX_PANE
422
+ const window = pane ? run('tmux', ['display-message', '-p', '-t', pane, '#{window_name}']) : ''
423
+ const session = pane ? run('tmux', ['display-message', '-p', '-t', pane, '#{session_name}']) : ''
424
+ if (window && window === cfg.pmWindow) {
425
+ log(`skip settle (pm window): window=${window}`, cfg)
426
+ return
427
+ }
428
+ if (window && session && session !== cfg.session) {
429
+ log(`skip settle (session ${session} != ${cfg.session})`, cfg)
430
+ return
431
+ }
432
+
433
+ // P82(notify-sender-identity):发送者 = **运行时目录**(M40 身份),不是窗口名。
434
+ // cwd 在这个守卫里已经证明位于 <root>/<worktrees>/ 之下 → 取那段路径的一级目录名(名册里的席位优先);
435
+ // 窗口名是可改的 UI 状态、headless 时不存在,只用来发现并记录分歧(设计 §2 的裁决)。
436
+ const agent = senderFromDir(resolve(cwd), wtPrefix, cfg.roster)
437
+ if (!agent) {
438
+ log(`skip settle (worktrees prefix matches but names no sender): cwd=${cwd}`, cfg)
439
+ return
440
+ }
441
+ if (window && window !== agent) log(`window ${window} ignored: the runtime directory names ${agent}`, cfg)
442
+ const branch = run('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'])
443
+ const task = /^(?:task|agent)\/([^/]+)/.exec(branch)?.[1] ?? ''
444
+ const id = task.split('-')[0] || 'unknown'
445
+ // R2/P160:通知要指认它讲的是哪个修订 —— task 从分支推,tip 从 HEAD 推;非任务分支(主工作树/
446
+ // 临时工作树/普通席位分支 agent/<席位>)没有 task 语义就不盖(宁可没有,不许编造),
447
+ // 而且 task/<ID>-… 的 <ID> 必须有任务证据(state/<agent>.env 的 task=、看板行或任务书)。
448
+ const isTaskBranch = /^task\//.test(branch)
449
+ const proven = isTaskBranch && id !== 'unknown' && hasTaskEvidence(root, cfg, agent, id)
450
+ const tip = proven ? run('git', ['-C', cwd, 'rev-parse', 'HEAD']).slice(0, TIP_WIDTH) : ''
451
+ const revStamp = tip ? ` · task=${id} tip=${tip}` : ''
452
+ const dirty = run('git', ['-C', cwd, 'status', '--porcelain']).split('\n').filter(Boolean).length
453
+ const upstream = run('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'])
454
+ const unpushed = upstream
455
+ ? run('git', ['-C', cwd, 'rev-list', '--count', '@{upstream}..HEAD']) || '?'
456
+ : run('git', ['-C', cwd, 'rev-list', '--count', 'HEAD', '--not', '--remotes']) || '?'
457
+
458
+ // 最后一条 assistant 消息才是「本轮的最后消息」;只有**完成了的回合**才允许当摘要(M4.3 E)。
459
+ // 旧实现在回合未完成时从末尾往前找第一条有文本的消息 —— 于是一轮长工具调用里的开头那句
460
+ // ("I'll start by reading the required files in order.")被当成结论报给 PM,读起来像「agent 停了」。
461
+ let last = ''
462
+ let completed = false
463
+ try {
464
+ const entries = ctx.sessionManager.getEntries() as Array<{ message?: { role?: string; stopReason?: string; content?: unknown } }>
465
+ for (let i = entries.length - 1; i >= 0; i--) {
466
+ const message = entries[i]?.message
467
+ if (message?.role !== 'assistant') continue
468
+ completed = isCompletedTurn(String(message.stopReason ?? ''))
469
+ if (completed) last = tail(messageText(message.content), cfg.maxChars)
470
+ break
471
+ }
472
+ } catch {
473
+ /* 通知绝不能打断会话 */
474
+ }
475
+
476
+ // 挂起判定(design 决策 4 + P236 归属范围):在跑集合从**车道自己写记录的目录**读(laneStateDir),
477
+ // 逐条 (pid, start-time) 验活、再按 cwd 只留**本会话自己的**作业;判定失败一律退回非挂起形状
478
+ // (fail-closed)——既不假造挂起,也不拿 notify 自己的 root 顶替车道目录(两侧分歧时它只负责把
479
+ // 这件事记进日志)。
480
+ // P236(缺陷现场):同一车道目录里的记录可能属于**别的席位** —— 只看「项目里有活作业」会把别人的
481
+ // 长作业算成自己挂起。归属判据 = 作业的 cwd 与本会话自己的工作树/cwd 解析到同一个真实路径。
482
+ const laneDir = laneStateDir(cwd)
483
+ const ownDir = notifyStateDir(root)
484
+ if (laneDir && ownDir && laneDir !== ownDir) {
485
+ log(`suspend check reads the lane's directory ${laneDir} (notify's own root would be ${ownDir})`, cfg)
486
+ }
487
+ const owned = ownedSessionPaths(cwd, join(wtPrefix, agent))
488
+ const running = runningLaneJobs(laneDir, owned)
489
+ const awaiting = running.length > 0 ? `awaiting=${running.join(',')}` : ''
490
+ const suspended = completed && running.length > 0
491
+
492
+ const summary = [
493
+ `agent:${agent}`,
494
+ id,
495
+ `branch=${branch || '-'}`,
496
+ `uncommitted=${dirty}`,
497
+ ...(awaiting ? [awaiting] : []),
498
+ `unpushed=${unpushed}${upstream ? '' : '(no-upstream)'}`,
499
+ ].join(' · ')
500
+ // 未完成的回合 + 本轮内有过生命周期事件 = 内部重启/压缩的产物,不是交付:不发简报、不敲门。
501
+ // 未完成但**没有**生命周期事件(Esc / 错误)仍然告诉 PM,只是绝不带摘要(不编造「最后消息」)。
502
+ if (!completed && lifecycleDuringTurn) {
503
+ log(`skip settle (${lifecycleDuringTurn} 期间的 settle,回合未完成 → 不是交付) ${summary}`, cfg)
504
+ lifecycleDuringTurn = ''
505
+ return
506
+ }
507
+ lifecycleDuringTurn = ''
508
+
509
+ // 未提交 = 没交付干净:让 PM 一眼看出来(CEP 实测:这种状态和"干净交付"在通知里长得一样)。
510
+ // 挂起不是交付主张:省略 ⚠ 前缀(事实留在 uncommitted=<n> 字段里),否则告警框只会误导。
511
+ const dirtyFlag = dirty > 0 && !suspended ? `⚠ 未提交 ${dirty} 个文件 · ` : ''
512
+
513
+ count++
514
+ const tag = completed ? (suspended ? '[auto·suspended]' : '[auto]') : '[auto·interrupted]'
515
+ // 去重键:整条末消息的「长度+指纹」+ 修订标识(新 tip = 新修订,不该被去重吞掉)。
516
+ // 老键(last[0:60])会把三条开头相同、后半不同的简报当成同一条吞掉(M6.3 F17)。
517
+ const key = `${agent}|${tag}|${summary}|${revStamp}|${last.length}:${fingerprint(last)}`
518
+
519
+ const stateDir = join(root, '.pi/team/state')
520
+ try {
521
+ mkdirSync(stateDir, { recursive: true })
522
+ } catch {
523
+ /* ignore */
524
+ }
525
+ if (isDuplicate(key, cfg.dedupSec, stateDir)) {
526
+ log(`dedup settle #${count} ${summary}`, cfg)
527
+ return
528
+ }
529
+
530
+ const line = `${new Date().toISOString()} ${dirtyFlag}${tag} ${summary}${revStamp}${completed && last ? ` :: ${last}` : ''}`
531
+ try {
532
+ const dir = join(root, cfg.docsDir, 'inbox')
533
+ mkdirSync(dir, { recursive: true })
534
+ appendFileSync(join(dir, `${agent}.md`), `- ${line}\n`)
535
+ log(`inbox ${tag} ${summary}`, cfg)
536
+ } catch (error) {
537
+ log(`inbox write failed: ${String(error)}`, cfg)
538
+ }
539
+
540
+ if (!cfg.notifyTmux || !window) return
541
+ const target = `${cfg.session}:${cfg.pmWindow}`
542
+ try {
543
+ // 安全:只有当 PM 窗口里真的在跑 pi 时才敲键盘。
544
+ // 否则(PM 已退出、窗口停在 shell)send-keys 会被 shell 当命令执行。
545
+ const paneCmd = run('tmux', ['display-message', '-p', '-t', target, '#{pane_current_command}'])
546
+ if (!paneCmd || /^(bash|sh|zsh|fish|dash|ash|ksh|nu)$/.test(paneCmd)) {
547
+ log(`skip tmux notify (pm not running: pane=${paneCmd || 'missing'}) inbox only`, cfg)
548
+ return
549
+ }
550
+ } catch {
551
+ /* PM 窗口不在:只留收件箱 */
552
+ return
553
+ }
554
+ // 敲门不再自己 send-keys:交给 teamsmith 的投递守卫 + 延后队列(delivery-guard)。
555
+ // 为什么:扩展原来直接 `send-keys -l` + Enter,人正在 PM 输入框里写草稿时会把草稿粘走
556
+ // (D20 的原始事故)。入队时带上扩展自己的去重键(key),两层抑制不会打架。
557
+ // 失败只记日志:绝不回退到打字(那会悄悄重建同一个 bug)。
558
+ const notice = `${dirtyFlag}${tag} ${summary}${revStamp}${completed && last ? `\n> ${last}` : ''}`
559
+ const cli = join(skillDir(), 'scripts/team')
560
+ const tmp = join(stateDir, `knock-${process.pid}-${Date.now()}.txt`)
561
+ try {
562
+ writeFileSync(tmp, notice)
563
+ const out = execFileSync(
564
+ 'bash',
565
+ [cli, '--root', root, 'outbox', 'enqueue', '--kind', 'knock', '--target', target,
566
+ '--from', agent, '--dedup', key, '--from-file', tmp],
567
+ { encoding: 'utf8', timeout: 5000 },
568
+ )
569
+ log(`knock queued (${String(out).trim() || 'entry written'})`, cfg)
570
+ } catch (error) {
571
+ log(`knock enqueue failed — inbox line kept, NOT falling back to typing: ${String(error)}`, cfg)
572
+ } finally {
573
+ try { rmSync(tmp, { force: true }) } catch { /* ignore */ }
574
+ }
575
+ try {
576
+ // 一次有界排水:PM 输入框空则立刻投递;有草稿则留在队列(下一次 tick / flush 再送)
577
+ execFileSync('bash', [cli, '--root', root, 'outbox', 'flush', '--quiet'], { timeout: 5000 })
578
+ } catch { /* PM 窗口不在或队列不可写:条目已经落盘,下一次 drain 再送 */ }
579
+ })
580
+
581
+ // ---------------------------------------------------------------------------
582
+ // skill 热重载:/teamsmith-reload(/reload 的别名,语义更直白)
583
+ //
584
+ // 为什么需要:skill 更新后,`scripts/**` 立刻生效,但 SKILL.md 的清单/描述
585
+ // 只在下一次资源加载时才刷新。Pi 的 /reload 会重新发现 skills 并重建 system prompt,
586
+ // 所以 PM 发现版本落后时跑这个命令即可,不必重启会话。
587
+ // 工具 reload_skills 让模型也能自助触发:Pi 的工具跑在 ExtensionContext 里,
588
+ // 不能直接调 ctx.reload(),得把命令作为 follow-up 消息排队(官方推荐做法)。
589
+ const reloadHandler = {
590
+ description: '重新加载 skills/扩展(等同于 /reload)——skill 更新后用它生效',
591
+ handler: async (ctx: any) => {
592
+ try {
593
+ log('teamsmith-reload: reloading resources', readCfg(findRoot(ctx?.cwd ?? process.cwd()) ?? process.cwd()))
594
+ } catch { /* ignore */ }
595
+ if (typeof ctx?.reload === 'function') {
596
+ await ctx.reload()
597
+ return
598
+ }
599
+ if (typeof ctx?.showMessage === 'function') ctx.showMessage('当前环境不支持热重载:请手动输入 /reload')
600
+ },
601
+ }
602
+ if (typeof (pi as any).registerCommand === 'function') pi.registerCommand('teamsmith-reload', reloadHandler)
603
+ // 兼容别名:旧名(v1.13.0 前叫 pi-team)
604
+ if (typeof (pi as any).registerCommand === 'function') {
605
+ try { pi.registerCommand('pi-team-reload', reloadHandler) } catch { /* ignore */ }
606
+ }
607
+
608
+ // ---------------------------------------------------------------------------
609
+ // /reload 之后:历史里已经读过的 SKILL.md 是旧文本(Pi 不会改写历史消息),
610
+ // 所以这里主动提醒 agent 重新 read 一遍 skill —— 否则"重载"只刷新了清单/描述,
611
+ // 正文仍是旧的。顺带清掉 team reload 留下的请求标记。
612
+ pi.on('session_start', async (event: any, ctx: any) => {
613
+ try {
614
+ if (event?.reason !== 'reload') return
615
+ const cwd = ctx?.cwd ?? process.cwd()
616
+ const root = findRoot(cwd)
617
+ if (!root) return
618
+ const v = skillVersion()
619
+ const dir = skillDir()
620
+ // 重载已完成 → 清掉请求标记
621
+ try {
622
+ const marker = join(root, '.pi/team/state/reload-requested')
623
+ if (existsSync(marker)) rmSync(marker, { force: true })
624
+ } catch {
625
+ /* ignore */
626
+ }
627
+ const text =
628
+ `[teamsmith] skill 已重载${v ? `(v${v})` : ''}:**历史里读过的 SKILL.md 是旧版**,` +
629
+ `当前会话不会自动更新那段文本。请现在重新 read ${dir}/SKILL.md` +
630
+ `(需要时再读 references/ 或 templates/),然后跑 \`team version --check\` 记录新版本。`
631
+ ;(pi as any).sendMessage(
632
+ { customType: 'teamsmith-reloaded', content: text, display: true },
633
+ { deliverAs: 'followUp', triggerTurn: true },
634
+ )
635
+ } catch {
636
+ /* 重载提示绝不能影响会话 */
637
+ }
638
+ })
639
+
640
+ if (typeof (pi as any).registerTool === 'function') pi.registerTool({
641
+ name: 'reload_skills',
642
+ description:
643
+ '重新加载 skill/扩展定义(等同于 /reload)。当 team version --check 提示 skill 已更新时调用它。',
644
+ parameters: { type: 'object', properties: {}, additionalProperties: false } as any,
645
+ async execute(_toolCallId: string, _params: any, _signal: any, _onUpdate: any, ctx: any) {
646
+ const prompt = '/teamsmith-reload'
647
+ if (typeof ctx?.queueFollowUp === 'function') {
648
+ await ctx.queueFollowUp(prompt)
649
+ } else if (typeof ctx?.pi?.queueFollowUp === 'function') {
650
+ await ctx.pi.queueFollowUp(prompt)
651
+ } else if (typeof ctx?.sendMessage === 'function') {
652
+ await ctx.sendMessage(prompt)
653
+ } else {
654
+ return {
655
+ content: [
656
+ { type: 'text', text: `请手动运行 ${prompt}(当前上下文不支持排队 follow-up 消息)` },
657
+ ],
658
+ }
659
+ }
660
+ return { content: [{ type: 'text', text: `已排队 ${prompt}:本回合结束后会自动重新加载 skill。` }] }
661
+ },
662
+ } as any)
663
+ }