teamsmith 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +4 -4
  2. package/package.json +2 -6
  3. package/skills/teamsmith/CHANGELOG.md +47 -0
  4. package/skills/teamsmith/SKILL.md +1 -1
  5. package/skills/teamsmith/extension/team-inbox-watch.ts +30 -1
  6. package/skills/teamsmith/extension/team-notify.ts +161 -20
  7. package/skills/teamsmith/references/agent-adapters.md +3 -1
  8. package/skills/teamsmith/references/config.md +1 -1
  9. package/skills/teamsmith/references/protocol.md +21 -0
  10. package/skills/teamsmith/references/troubleshooting.md +7 -3
  11. package/skills/teamsmith/scripts/lib/cmd-agents.sh +213 -19
  12. package/skills/teamsmith/scripts/lib/cmd-config.sh +1 -1
  13. package/skills/teamsmith/scripts/lib/cmd-status.sh +177 -21
  14. package/skills/teamsmith/scripts/lib/cmd-watch.sh +11 -1
  15. package/skills/teamsmith/scripts/lib/common.sh +7 -3
  16. package/skills/teamsmith/scripts/lib/outbox.sh +31 -3
  17. package/skills/teamsmith/scripts/panel/panel.js +1 -1
  18. package/skills/teamsmith/scripts/panel/src/strings/en.ts +1 -1
  19. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +1 -1
  20. package/skills/teamsmith/scripts/team +1 -0
  21. package/skills/teamsmith/templates/config.sh.tmpl +2 -1
  22. package/skills/teamsmith/tests/bg-ledger-harness.mjs +17 -6
  23. package/skills/teamsmith/tests/bg-ledger.sh +16 -5
  24. package/skills/teamsmith/tests/help-surface.sh +1 -1
  25. package/skills/teamsmith/tests/install-shape.sh +88 -38
  26. package/skills/teamsmith/tests/panel-choices.sh +11 -7
  27. package/skills/teamsmith/tests/section-paths.tsv +2 -2
  28. package/skills/teamsmith/tests/smoke.sh +594 -11
  29. package/skills/teamsmith/tests/task-model-routing.sh +10 -1
  30. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +33 -0
  31. package/skills/teamsmith/tests/team-notify-knock-marker.mjs +91 -0
  32. package/skills/teamsmith-init/SKILL.md +1 -1
package/README.md CHANGED
@@ -57,14 +57,14 @@ than replaced (`--force` replaces only an entry recognised as this skill).
57
57
  ### As a Pi package (no global CLI)
58
58
 
59
59
  ```bash
60
- pi install git:git@github.com:Track07-cda/teamsmith@v0.3.3 # user level: every project
61
- pi install -l git:git@github.com:Track07-cda/teamsmith@v0.3.3 # project level: recorded in .pi/settings.json
60
+ pi install git:git@github.com:Track07-cda/teamsmith@v0.3.4 # user level: every project
61
+ pi install -l git:git@github.com:Track07-cda/teamsmith@v0.3.4 # project level: recorded in .pi/settings.json
62
62
  ```
63
63
 
64
64
  - **Pin a released tag**: `@v<version>`, the version `team version` prints. Latest tag:
65
65
  `git tag --sort=-v:refname | head -1`.
66
- - The `git@github.com:` form (or `ssh://git@github.com/Track07-cda/teamsmith@v0.3.3`) uses your SSH key and works
67
- whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.3.3` takes the HTTPS
66
+ - The `git@github.com:` form (or `ssh://git@github.com/Track07-cda/teamsmith@v0.3.4`) uses your SSH key and works
67
+ whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.3.4` takes the HTTPS
68
68
  route, so it works anonymously on the public repository and asks for credentials if your access is private.
69
69
  - The clone lands in `~/.pi/agent/git/<host>/<path>` (user level) or `.pi/git/<host>/<path>` (project level); the
70
70
  skill directory — the `<skill>` used in every command below — is `<clone>/skills/teamsmith`.
package/package.json CHANGED
@@ -1,14 +1,10 @@
1
1
  {
2
2
  "name": "teamsmith",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "Turn one agent session into a project owner: self-contained task briefs dispatched to worker agents in their own git worktrees, independent verification on a separate checkout, and an auditable ledger (BOARD / reviews / threads / DECISIONS). Runs on Pi today.",
5
5
  "license": "MIT",
6
6
  "bin": {
7
- "team": "./bin/team.mjs",
8
- "pkill": "./skills/teamsmith/scripts/shim/pkill",
9
- "killall": "./skills/teamsmith/scripts/shim/killall",
10
- "pgrep": "./skills/teamsmith/scripts/shim/pgrep",
11
- "pidof": "./skills/teamsmith/scripts/shim/pidof"
7
+ "team": "./bin/team.mjs"
12
8
  },
13
9
  "repository": {
14
10
  "type": "git",
@@ -5,6 +5,53 @@
5
5
  > `SKILL.md`/`references/**`/`templates/**`/`extension/**` 在 Pi 里输入 `/reload`(或 `/pi-team-reload`)即生效;
6
6
  > 判断自己是不是旧的:`team mark-loaded`(开局记一次)→ `team version --check`。
7
7
 
8
+ ## v0.3.4(2026-10-26)
9
+
10
+ 补丁版:**没有破坏性配置迁移、没有新依赖**。这一版主要修通知可靠性,以及三处会让使用者误判状态的缺陷。
11
+
12
+ ### 安装面:npm 不再遮蔽系统命令
13
+
14
+ - **`package.json` 的 `bin` 只剩 `team`**:0.3.2 曾把 `pkill` / `killall` / `pgrep` / `pidof` 也列进 `bin`,
15
+ 想让 npm 安装的人也有信号闸门;代价是 `npm i -g` 在用户的全局 `prefix/bin` 里建了这四个链接 ——
16
+ **Teamsmith 之外的普通终端**敲 `pgrep -f …` 或 `pkill …` 也会落进闸门并以 64 退出。
17
+ 现在这四条全局链接撤掉:安装后 `prefix/bin` 里只有 `team`,普通 shell 解析到系统的同名可执行文件。
18
+ - **闸门本身没变,也没有变弱**:四个 shim 文件仍随包发布(`files` 仍含 `skills/`),PM / worker 窗口的启动命令
19
+ 照旧由 `team_tmux_shim_exports` 把 `scripts/shim` 放到 `PATH` 最前,所以**窗口里**这四个名字仍然是闸门。
20
+ 安装面夹具(`tests/install-shape.sh`)现在正向钉住「`prefix/bin` 只有 `team`、普通 shell 不遮蔽、包内 shim 仍在、
21
+ 窗口前缀解析回包内 shim」,并用一个翻转(把四个名字加回 `bin`)证明这条判据会红。
22
+ - **升级**:`npm i -g teamsmith@<新版>` 会把旧版留下的四条链接删掉(npm 11 实测:装完 `prefix/bin` 只剩 `team`);
23
+ 用 Git 检出或 `install.sh` 的人本来就没有这些链接,无需动作。
24
+
25
+ ### 通知与交付
26
+
27
+ - **通知不再依赖一次敲门是否成功**:每次回合结算同时给 PM 的收件箱写一条指针行,包含任务、状态、
28
+ `knock=` 结果和 `see=` 明细位置;发送者自己的记录保持原样,同一条通知只计一次待办。即使 PM 窗口当时
29
+ 不在或暂时不能接收键入,通知仍留在 PM 会读的地方。
30
+ - **没有叫醒 PM 的原因可以追查**:新增项目内的 `state/notify-knock.log`,记录挂起、去重、窗口不可用、
31
+ 指针写失败等结果;`team digest` 会显示「未敲门 N 条(按原因分类)」以及最近一次指针失败。
32
+ 这些行只展示事实,不会因此把 PM 反复叫醒。
33
+ - **完成消息保存全文**:收件箱和 `state/notify.log` 不再只保留前 150 字。只有预览会截断,并标明
34
+ `truncated=preview:<显示>/<原文>B full=<位置>`;硬上限 64 KiB 只用于防畸形输出,超限时具名且不伪造全文位置。
35
+ - **待 PM 回答的问题可以计数**:完成消息末尾 400 字内出现闭集的「请裁决 / 待你确认 / 需要你回答」等标记时,
36
+ 记录 `asks=<n>`,由 `team digest` 汇总,避免问题藏在交付消息末尾而被忽略。
37
+ - `TEAM_INBOX_MAX_CHARS` 现在表示**预览长度**,不再截断持久记录;配置 schema、模板、说明和中英文面板标签已同步。
38
+
39
+ ### 状态与诊断修复
40
+
41
+ - **PM 窗口创建失败不再假报成功**:`team up` 在 tmux 创建窗口失败时返回非零、保留 tmux 诊断并点名失败目标,
42
+ 不再打印「✓ 创建 PM 窗口」后继续按窗口存在处理。成功路径不变。
43
+ - **容器中的进程身份读取不再污染正常输出**:`/proc/<pid>/environ` 读不到时按「身份未知」处理,
44
+ 不再把 shell 的 `Permission denied` 写进 digest 等输出,避免缓存开关等逐字节比较被无关报错打乱。
45
+
46
+ ### 门禁与测试
47
+
48
+ - 等待耐心的「缓存一次就不再重算」错误有定点反例;默认锁与私有锁的伴生锁断言都按真实输入推导,
49
+ 默认锁名在普通运行中确实被检查。
50
+ - 选段声明补齐新通知断言读取的文件;`bg-ledger` 改按新契约统计通知流量,并把 `merge` / `detail` 纳入对应选段。
51
+ - 测试用技能树从源目录派生;翻转夹具不再沿软链把补丁写回真实工作树。
52
+
53
+ **升级后注意**:CLI 下次调用即读取新代码;已经运行的 PM / 席位需要 `/reload` 或重开会话,才会加载新的通知扩展。
54
+
8
55
  ## v0.3.3(2026-10-22)
9
56
 
10
57
  小版本:**新增一个技能**,已有项目跑一次 `team init`(或 `team bootstrap`)就会把它装进 `.pi/skills/`。
@@ -3,7 +3,7 @@ name: teamsmith
3
3
  description: teamsmith gives one agent real ownership of a project — it plans, writes self-contained task briefs, dispatches worker agents into their own tmux windows and git worktrees, verifies their work on an independent checkout, merges, and keeps an auditable ledger (BOARD/reviews/threads/DECISIONS). A pulse window (the periodic patrol) wakes the owner only when there is pending work, and the owner can deliberately stand down. Works with Pi; the launch/notify seam is an internal seam (frozen) reserved for a possible future non-Pi adapter, with no compatibility promise. Use when the user wants an agent to own a project end to end, dispatch tasks to worker agents, run agents in parallel in tmux with git worktree isolation, act as a PM/orchestrator over other agents, review an agent's work independently, run the patrol (`pulse`) as a tmux window, wake the PM only when there is pending work, or resume and coordinate a multi-agent project. To start a new project, use the teamsmith-init skill.
4
4
  license: MIT
5
5
  metadata:
6
- version: "0.3.3"
6
+ version: "0.3.4"
7
7
  ---
8
8
 
9
9
  # teamsmith · one agent that actually owns the project
@@ -294,6 +294,22 @@ function oneLine(raw: string, max: number): string {
294
294
  return flat.length > max ? `${flat.slice(0, Math.max(1, max - 1))}…` : flat
295
295
  }
296
296
 
297
+ /** notice-fulltext-and-asks:唤醒文本里那一行预览**自己**说出「剪了、剪了多少、原文在哪」(design §4)。
298
+ * 为什么不能继承 spool 层那个标记:160 字的剪断常常正好把上一层的标记剪掉(它排在最前一个预览的末尾),
299
+ * 于是两层的读者都看不到「被剪了」—— 谁剪谁写。
300
+ * `<shown>`/`<total>` 都是 UTF-8 字节数:`<total>` 是**它拿到的那份 spool 预览**的字节数(不是收件箱里
301
+ * 全文的字节数 —— 那一层已经剪过了);`<shown>` 是留下来的那段前缀(省略号是记号,不是正文)。
302
+ * `locator` = 仍然存着全文的那份收件箱文件;没有可指的文件时为空串(只报剪了多少,不编造路径)。
303
+ * 没剪 → 一个字节都不加(设计 §7 的逐字节不变性)。 */
304
+ function markedPreview(raw: string, max: number, locator: string): string {
305
+ const flat = raw.replace(/\s+/g, ' ').trim()
306
+ const total = Buffer.byteLength(flat, 'utf8')
307
+ if (flat.length <= max) return flat
308
+ const kept = flat.slice(0, Math.max(1, max - 1))
309
+ const shown = Buffer.byteLength(kept, 'utf8')
310
+ return `${kept}… truncated=preview:${shown}/${total}B${locator ? ` full=${locator}` : ''}`
311
+ }
312
+
297
313
  function appendLedger(root: string, line: string): void {
298
314
  try {
299
315
  mkdirSync(stateDir(root), { recursive: true })
@@ -694,6 +710,7 @@ type SpoolLine = {
694
710
  from: string
695
711
  durable: string
696
712
  preview: string
713
+ marker: string // 第 7 字段:发送方那一层自己的截断标记(没有 = 未剪 / 旧行)
697
714
  }
698
715
 
699
716
  function parseSpoolLine(raw: string): SpoolLine {
@@ -707,6 +724,7 @@ function parseSpoolLine(raw: string): SpoolLine {
707
724
  from: (f[2] ?? '').trim() || '-',
708
725
  durable: (f[3] ?? '').trim() || '-',
709
726
  preview: f[4] ?? '',
727
+ marker: f[6] ?? '',
710
728
  }
711
729
  }
712
730
 
@@ -744,6 +762,9 @@ function journalMaterial(rec: { fields: Map<string, string> }, identity: string)
744
762
  from: rec.fields.get('from') ?? '-',
745
763
  durable: rec.fields.get('durable') ?? '-',
746
764
  preview: rec.fields.get('preview') ?? '',
765
+ // 投递日志的 read 记录不存第 7 字段(它已经被空格分隔的 key=value 格式吃掉了):崩溃恢复重投时
766
+ // 标记由**这一层自己**重算(见 markedPreview),它只需要 durable 就能给出定位。
767
+ marker: '',
747
768
  }
748
769
  }
749
770
 
@@ -1016,11 +1037,19 @@ export default function (pi: ExtensionAPI) {
1016
1037
  * 指针 + 截断预览,绝不带 payload 全文;身份是有界的(发送方的 id 或整行 sha1 摘要)。 */
1017
1038
  const wakeText = (seq: number, lines: SpoolLine[], meta: WakeMeta): string => {
1018
1039
  const sendTs = new Date().toISOString()
1040
+ /** 标记的 `full=` 指哪份文件:`durable` 字段点名的那个收件箱行(条目头部就是真相);没有 durable
1041
+ * (knock/nudge)时退回**发送方那一层**写在标记字段/预览里的 `full=`(knock 载荷自带它);
1042
+ * 两者都没 → 空串:只报剪了多少,不编造一个不存在的文件。 */
1043
+ const locatorOf = (l: SpoolLine): string => {
1044
+ if (l.durable && l.durable !== '-') return `${docsDir(root)}/inbox/${l.durable}.md`
1045
+ const m = /full=([^ ]+)/.exec(l.marker || '') ?? /full=([^ ]+)/.exec(l.preview || '')
1046
+ return m ? m[1] : ''
1047
+ }
1019
1048
  const rows = lines.map(l => {
1020
1049
  const from = l.from && l.from !== '-' ? ` from ${l.from}` : ''
1021
1050
  const where = l.durable && l.durable !== '-' ? ` → ${l.durable}.md` : ''
1022
1051
  const src = l.src > 0 ? new Date(l.src).toISOString() : '(no timestamp)'
1023
- const preview = oneLine(l.preview || '(empty)', previewLimit())
1052
+ const preview = markedPreview(l.preview || '(empty)', previewLimit(), locatorOf(l))
1024
1053
  return `- [${l.kind}]${from}${where} :: ${preview} (src ${src} · id ${l.identity})`
1025
1054
  })
1026
1055
  const shown = rows.slice(0, MAX_LISTED)
@@ -293,9 +293,76 @@ function senderFromDir(cwd: string, wtPrefix: string, roster: string[]): string
293
293
  return roster.find(name => name === first) ?? first
294
294
  }
295
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
296
+ /** 空白折叠成一行(收件箱是按行读的文件,这一条是既有契约)。**不是截断**:只把换行/制表折成空格,
297
+ * 一个字符都不丢 —— 记录路径(收件箱行、`state/notify.log` 明细)存的就是它的结果。 */
298
+ function flatten(raw: string): string {
299
+ return raw.replace(/\s+/g, ' ').trim()
300
+ }
301
+
302
+ /** 记录的硬上限(常量,**不是**配置键):它是给畸形输出(例如整段日志被当成末消息)的最后一道闸,
303
+ * 不是一个调参口 —— 用户明确要求「不要设置限制」,给一个能关掉的旋钮等于把这道闸变成偏好。
304
+ * 64 KiB 是本仓实测末消息最大值(7280 B)的九倍,正常消息碰不到它。 */
305
+ const RECORD_HARD_LIMIT = 65536
306
+
307
+ /** `asks` 的判据窗口:扁平化后末消息的**最后 400 个字符**(约 2–4 句中文)。窗口之外的标记不算 ——
308
+ * 否则正文中间的「请确认」会把一条纯汇报数成待裁决。 */
309
+ const ASK_WINDOW = 400
310
+
311
+ /** `asks` 的**闭集**(与 `openspec/specs/notify-and-inbox` 的规格正文逐字同源:中文 22 条 + 英文 7 条)。
312
+ * 加标记要改规格,不许在这里临时加一句 —— 它是「这是不是在问我」的判据,不是关键词搜索。 */
313
+ const ASK_MARKERS = [
314
+ '请裁决', '待你裁决', '等你裁决', '请你裁决', '请裁定', '请定夺', '请示下',
315
+ '请你确认', '需要你确认', '待你确认', '等你确认', '请确认一下', '请确认',
316
+ '请你决定', '需要你决定', '需要你定', '待你拍板', '等你拍板', '请你拍板',
317
+ '是否需要我', '要我继续', '要不要我',
318
+ 'please confirm', 'please decide', 'awaiting your decision', 'your call', 'need your approval',
319
+ 'needs your call', 'do you want me to',
320
+ ]
321
+
322
+ /** ASCII 大小写折叠(规格判据:`Please Confirm` 算一个标记)。只折 ASCII —— 中文没有大小写。 */
323
+ function foldAscii(text: string): string {
324
+ return text.replace(/[A-Z]/g, c => c.toLowerCase())
325
+ }
326
+
327
+ /** 最长优先(同一位置先试最长的标记,`请你确认` 不会再被计成一次 `请确认`)、从左到右、不重叠。 */
328
+ const ASK_MARKERS_FOLDED = ASK_MARKERS.map(foldAscii).sort((a, b) => b.length - a.length)
329
+
330
+ function countAsks(flat: string): number {
331
+ if (!flat) return 0
332
+ const window = flat.length > ASK_WINDOW ? flat.slice(-ASK_WINDOW) : flat
333
+ const hay = foldAscii(window)
334
+ let i = 0
335
+ let n = 0
336
+ while (i < hay.length) {
337
+ const hit = ASK_MARKERS_FOLDED.find(m => hay.startsWith(m, i))
338
+ if (hit) {
339
+ n++
340
+ i += hit.length
341
+ } else {
342
+ i++
343
+ }
344
+ }
345
+ return n
346
+ }
347
+
348
+ function byteLen(text: string): number {
349
+ return Buffer.byteLength(text, 'utf8')
350
+ }
351
+
352
+ /** 按 UTF-8 字节取前缀,且**退到字符边界**(逐码点累加;等价于 spool 侧 `head -c` + `iconv -c` 的
353
+ * 「丢字节、不引入 U+FFFD」惯用法)。返回留下来的文本与实际字节数,以及原文的字节数。 */
354
+ function clipBytes(text: string, maxBytes: number): { kept: string; keptBytes: number; totalBytes: number } {
355
+ const totalBytes = byteLen(text)
356
+ if (totalBytes <= maxBytes) return { kept: text, keptBytes: totalBytes, totalBytes }
357
+ let kept = ''
358
+ let keptBytes = 0
359
+ for (const ch of text) {
360
+ const b = byteLen(ch)
361
+ if (keptBytes + b > maxBytes) break
362
+ kept += ch
363
+ keptBytes += b
364
+ }
365
+ return { kept, keptBytes, totalBytes }
299
366
  }
300
367
 
301
368
  /** P160 F3 · 任务标识的证据:<ID> 必须在 state/<sender>.env 的 task=、看板行或任务书里真的存在
@@ -458,15 +525,32 @@ export default function (pi: ExtensionAPI) {
458
525
  // 最后一条 assistant 消息才是「本轮的最后消息」;只有**完成了的回合**才允许当摘要(M4.3 E)。
459
526
  // 旧实现在回合未完成时从末尾往前找第一条有文本的消息 —— 于是一轮长工具调用里的开头那句
460
527
  // ("I'll start by reading the required files in order.")被当成结论报给 PM,读起来像「agent 停了」。
528
+ //
529
+ // notice-fulltext-and-asks:这里算出的是**记录用的全文**(只做空白折叠,不套任何显示预算),
530
+ // 外加两个字段区标记:`asks=<n>`(末尾 400 字的闭集标记)与 `truncated=hard-limit:…`(病态输入)。
531
+ // 预览(敲门 / spool / wake)在各自的层里剪、各自自带标记 —— 记录路径不再剪任何东西。
461
532
  let last = ''
462
533
  let completed = false
534
+ let asksField = ''
535
+ let hardField = ''
463
536
  try {
464
537
  const entries = ctx.sessionManager.getEntries() as Array<{ message?: { role?: string; stopReason?: string; content?: unknown } }>
465
538
  for (let i = entries.length - 1; i >= 0; i--) {
466
539
  const message = entries[i]?.message
467
540
  if (message?.role !== 'assistant') continue
468
541
  completed = isCompletedTurn(String(message.stopReason ?? ''))
469
- if (completed) last = tail(messageText(message.content), cfg.maxChars)
542
+ if (completed) {
543
+ const full = flatten(messageText(message.content))
544
+ // asks 在硬上限**之前**判:计数是「这个席位说了什么」的属性,副本才是「留了多少」——
545
+ // 被闸剪掉尾巴的消息仍然要告诉 PM「它问了你一件事,但那段文字没留下来」。
546
+ const asks = countAsks(full)
547
+ if (asks > 0) asksField = ` · asks=${asks}`
548
+ const cut = clipBytes(full, RECORD_HARD_LIMIT)
549
+ last = cut.kept
550
+ // 硬上限的标记**不带** `full=`:这段原文从没落过盘,标一个不存在的定位等于说谎。
551
+ // 「没有 full=」就是读者区分「原文没了」与「原文在别处」的唯一记号。
552
+ if (cut.totalBytes > cut.keptBytes) hardField = ` · truncated=hard-limit:${cut.keptBytes}/${cut.totalBytes}B`
553
+ }
470
554
  break
471
555
  }
472
556
  } catch {
@@ -497,11 +581,36 @@ export default function (pi: ExtensionAPI) {
497
581
  ...(awaiting ? [awaiting] : []),
498
582
  `unpushed=${unpushed}${upstream ? '' : '(no-upstream)'}`,
499
583
  ].join(' · ')
584
+ // turn-notice-in-pm-inbox(A1):settle 的**旁路**记账入口。记录行照旧走 `__inbox-write`;指针行由
585
+ // `__notify-settle` 从同一行派生、写进 pm.md(不写明细)。指针是旁路:它的失败只进扩展日志,不回退
586
+ // 打字、不抑制已经入队的敲门、不改变退出。每个退出点给出**闭集**里的一类(design §6):suspended /
587
+ // merged / dedup / turn-unfinished / write-failed / notify-off / no-pane / pm-not-running /
588
+ // pm-window-missing / enqueue-failed;成功交给投递守卫后是 enqueued(≠ 已送达)。
589
+ const cli = join(skillDir(), 'scripts/team')
590
+ let lineFile = ''
591
+ let writeOut = ''
592
+ let identity = '-'
593
+ const settleSkipped = (outcome: string, withRecord: boolean): void => {
594
+ const args = [cli, '--root', root, '__notify-settle', '--agent', agent, '--outcome', outcome, '--task', proven ? id : '-', '--identity', identity]
595
+ if (withRecord && lineFile) args.push('--record-from-file', lineFile)
596
+ try {
597
+ const out = execFileSync('bash', args, { encoding: 'utf8', timeout: 5000 })
598
+ log(`settle ${outcome} ${String(out).trim()}`, cfg)
599
+ } catch (error) {
600
+ log(`settle ${outcome} failed (the pointer is a side channel, the knock is untouched): ${String(error)}`, cfg)
601
+ } finally {
602
+ if (lineFile) {
603
+ try { rmSync(lineFile, { force: true }) } catch { /* ignore */ }
604
+ lineFile = ''
605
+ }
606
+ }
607
+ }
500
608
  // 未完成的回合 + 本轮内有过生命周期事件 = 内部重启/压缩的产物,不是交付:不发简报、不敲门。
501
609
  // 未完成但**没有**生命周期事件(Esc / 错误)仍然告诉 PM,只是绝不带摘要(不编造「最后消息」)。
502
610
  if (!completed && lifecycleDuringTurn) {
503
611
  log(`skip settle (${lifecycleDuringTurn} 期间的 settle,回合未完成 → 不是交付) ${summary}`, cfg)
504
612
  lifecycleDuringTurn = ''
613
+ settleSkipped('skipped:turn-unfinished', false)
505
614
  return
506
615
  }
507
616
  lifecycleDuringTurn = ''
@@ -524,17 +633,17 @@ export default function (pi: ExtensionAPI) {
524
633
  }
525
634
  if (isDuplicate(key, cfg.dedupSec, stateDir)) {
526
635
  log(`dedup settle #${count} ${summary}`, cfg)
636
+ settleSkipped('skipped:dedup', false)
527
637
  return
528
638
  }
529
639
 
530
- const line = `${new Date().toISOString()} ${dirtyFlag}${tag} ${summary}${revStamp}${completed && last ? ` :: ${last}` : ''}`
640
+ const line = `${new Date().toISOString()} ${dirtyFlag}${tag} ${summary}${revStamp}${asksField}${hardField}${completed && last ? ` :: ${last}` : ''}`
531
641
  // turn-notice-merge(写入侧合并 + 明细):判定「扩展末尾的同类 run 还是新起一行」在 CLI 的收件箱
532
642
  // 写入口里(每收件人一把锁 + 先明细后合并),扩展只消费写入结果 —— 只有写下**新行**才入队 knock。
533
- const cli = join(skillDir(), 'scripts/team')
534
- const lineFile = join(stateDir, `notify-line-${process.pid}-${Date.now()}.txt`)
535
- let writeOut = ''
643
+ const linePath = join(stateDir, `notify-line-${process.pid}-${Date.now()}.txt`)
536
644
  try {
537
- writeFileSync(lineFile, line)
645
+ writeFileSync(linePath, line)
646
+ lineFile = linePath
538
647
  writeOut = execFileSync(
539
648
  'bash',
540
649
  [cli, '--root', root, '__inbox-write', '--agent', agent, '--from-file', lineFile],
@@ -544,14 +653,21 @@ export default function (pi: ExtensionAPI) {
544
653
  } catch (error) {
545
654
  writeOut = ''
546
655
  log(`inbox write failed: ${String(error)}`, cfg)
547
- } finally {
548
- try { rmSync(lineFile, { force: true }) } catch { /* ignore */ }
549
656
  }
550
657
  const writeState = /^state=([a-z]+)/m.exec(writeOut)?.[1] ?? ''
658
+ // 行身份 = 敲门自己的去重身份,也是结果账(A2)的 identity= 字段:席位是 mergeKey 的第一个分量;
659
+ // 两条文本逐字相同但不同的行不会互吞,同一 run 的重复 settle 也绝不会二次敲门(此时它连条目都不入队)。
660
+ // `new` 与 `extended` 都算「这一行写了」—— extended 是把事件并进已有那一行;只有写盘失败才没有行身份。
661
+ if (writeState === 'new' || writeState === 'extended') {
662
+ const firstEvent = /^first=(\S+)/m.exec(writeOut)?.[1] ?? ''
663
+ const mergeKey = /^key=(\S*)/m.exec(writeOut)?.[1] ?? ''
664
+ identity = `line|${mergeKey}|${firstEvent}`
665
+ }
551
666
  if (writeState !== 'new') {
552
667
  // 扩展既有 run(state=extended)的 settle 不入队、不敲字:计数抖动看得见但不叫醒。
553
668
  // 写盘失败(异常 / state=failed)也不叫醒 —— 与手工路径的「写失败不得授权唤醒」同一条规则。
554
669
  log(`no knock (inbox write state=${writeState || 'failed'})`, cfg)
670
+ settleSkipped(writeState === 'extended' ? 'skipped:merged' : 'skipped:write-failed', writeState === 'extended')
555
671
  return
556
672
  }
557
673
 
@@ -561,15 +677,20 @@ export default function (pi: ExtensionAPI) {
561
677
  // 「任务未完成 + 窗口不在」那一档,不由这条通知兜。
562
678
  if (suspended) {
563
679
  log('no knock (suspended records only)', cfg)
680
+ settleSkipped('skipped:suspended', true)
564
681
  return
565
682
  }
566
- const firstEvent = /^first=(\S+)/m.exec(writeOut)?.[1] ?? ''
567
- const mergeKey = /^key=(\S*)/m.exec(writeOut)?.[1] ?? ''
568
- // knock 的去重身份 = **行身份**(席位 + 合并键 + 首事件时间):两条文本逐字相同但不同的行不会互吞,
569
- // 同一 run 的重复 settle 也绝不会二次敲门(此时它连条目都不入队)。席位是 mergeKey 的第一个分量。
570
- const lineIdentity = `line|${mergeKey}|${firstEvent}`
571
683
 
572
- if (!cfg.notifyTmux || !window) return
684
+ if (!cfg.notifyTmux) {
685
+ log('no knock (tmux notify disabled) inbox only', cfg)
686
+ settleSkipped('skipped:notify-off', true)
687
+ return
688
+ }
689
+ if (!window) {
690
+ log('no knock (no tmux pane) inbox only', cfg)
691
+ settleSkipped('skipped:no-pane', true)
692
+ return
693
+ }
573
694
  const target = `${cfg.session}:${cfg.pmWindow}`
574
695
  try {
575
696
  // 安全:只有当 PM 窗口里真的在跑 pi 时才敲键盘。
@@ -577,29 +698,49 @@ export default function (pi: ExtensionAPI) {
577
698
  const paneCmd = run('tmux', ['display-message', '-p', '-t', target, '#{pane_current_command}'])
578
699
  if (!paneCmd || /^(bash|sh|zsh|fish|dash|ash|ksh|nu)$/.test(paneCmd)) {
579
700
  log(`skip tmux notify (pm not running: pane=${paneCmd || 'missing'}) inbox only`, cfg)
701
+ settleSkipped('skipped:pm-not-running', true)
580
702
  return
581
703
  }
582
704
  } catch {
583
705
  /* PM 窗口不在:只留收件箱 */
706
+ settleSkipped('skipped:pm-window-missing', true)
584
707
  return
585
708
  }
586
709
  // 敲门不再自己 send-keys:交给 teamsmith 的投递守卫 + 延后队列(delivery-guard)。
587
710
  // 为什么:扩展原来直接 `send-keys -l` + Enter,人正在 PM 输入框里写草稿时会把草稿粘走
588
- // (D20 的原始事故)。入队时带上 knock 自己的**行身份**(lineIdentity),两层抑制不会打架。
711
+ // (D20 的原始事故)。入队时带上 knock 自己的**行身份**(identity,与结果账的 identity= 同一个值),两层抑制不会打架。
589
712
  // 失败只记日志:绝不回退到打字(那会悄悄重建同一个 bug)。
590
- const notice = `${dirtyFlag}${tag} ${summary}${revStamp}${completed && last ? `\n> ${last}` : ''}`
713
+ // 打字的那一份是**预览**(有界);它被剪时自己说出剪了多少、原文在哪(设计 §4)。
714
+ // `<shown>`/`<total>` 都是 UTF-8 字节数(`wc -c` 读到的同一对数字);`full=` 指向记录行 ——
715
+ // 行号由**持锁的写入侧**(`__inbox-write` 的 `lineno=`)给出,扩展不用自己算的数。
716
+ // 行号缺失(写盘侧没给)时省略 `:<n>`,但那一位只在写盘失败时才会缺,而写盘失败本来就不敲门。
717
+ // `<shown>` 数的是**留下来的那段前缀**(省略号是「这里省略了」的记号,不是正文)—— 这样它与 spool
718
+ // 层的读数同口径,且永远有 shown ≤ total(把 U+2026 的三个字节算进去的话,纯 ASCII 消息会出现 shown > total)。
719
+ const clipped = completed && last.length > cfg.maxChars
720
+ const kept = clipped ? last.slice(0, cfg.maxChars - 1) : last
721
+ const previewText = clipped ? `${kept}…` : last
722
+ let previewMark = ''
723
+ if (clipped) {
724
+ const inboxFile = `${cfg.docsDir}/inbox/${agent}.md`
725
+ const written = Number(/^lineno=(\d+)/m.exec(writeOut)?.[1] ?? '')
726
+ const locator = Number.isInteger(written) && written > 0 ? `${inboxFile}:${written}` : inboxFile
727
+ previewMark = ` · truncated=preview:${byteLen(kept)}/${byteLen(last)}B full=${locator}`
728
+ }
729
+ const notice = `${dirtyFlag}${tag} ${summary}${revStamp}${asksField}${completed && last ? `${previewMark}\n> ${previewText}` : ''}`
591
730
  const tmp = join(stateDir, `knock-${process.pid}-${Date.now()}.txt`)
592
731
  try {
593
732
  writeFileSync(tmp, notice)
594
733
  const out = execFileSync(
595
734
  'bash',
596
735
  [cli, '--root', root, 'outbox', 'enqueue', '--kind', 'knock', '--target', target,
597
- '--from', agent, '--dedup', lineIdentity, '--from-file', tmp],
736
+ '--from', agent, '--dedup', identity, '--from-file', tmp],
598
737
  { encoding: 'utf8', timeout: 5000 },
599
738
  )
600
739
  log(`knock queued (${String(out).trim() || 'entry written'})`, cfg)
740
+ settleSkipped('enqueued', true)
601
741
  } catch (error) {
602
742
  log(`knock enqueue failed — inbox line kept, NOT falling back to typing: ${String(error)}`, cfg)
743
+ settleSkipped('skipped:enqueue-failed', true)
603
744
  } finally {
604
745
  try { rmSync(tmp, { force: true }) } catch { /* ignore */ }
605
746
  }
@@ -335,7 +335,9 @@ paste path.
335
335
  What the session receives is a **pointer**: `[teamsmith] inbox wake: N new team message(s)`, one line per
336
336
  message (`[kind] from <who> → <inbox>.md :: <truncated preview>`) and where to read the full text. Bursts merge
337
337
  into one message, previews are truncated (`TEAM_INBOX_WATCH_PREVIEW`, default 160 chars), and the spool itself
338
- is bounded (`TEAM_INBOX_WATCH_MAX_BYTES`, default 128 KiB: head dropped, tail kept). A session restart
338
+ is bounded (`TEAM_INBOX_WATCH_MAX_BYTES`, default 128 KiB: head dropped, tail kept). A preview that was cut says
339
+ so on its own line — `… truncated=preview:<shown>/<total>B full=<inbox file>[:<line>]` — so a reader can always
340
+ tell a truncated preview from a short message and go read the whole thing (the inbox file keeps the full text). A session restart
339
341
  re-baselines the spool, so lines written before it started never wake anybody — the pulse's pending check is
340
342
  the fallback and its semantics are unchanged.
341
343
 
@@ -158,7 +158,7 @@ empty panel reported as success.
158
158
  | `TEAM_AGENT_MEM_MB` | `6144` | empirical footprint of one agent, used by `team ps` for its "how many more fit" estimate |
159
159
  | `TEAM_NOTIFY_TMUX` | `1` | `0` = write the inbox only, never type into the PM window |
160
160
  | `TEAM_NOTIFY_DEDUP_SEC` | `20` | deduplication window (seconds); `0` = no deduplication |
161
- | `TEAM_INBOX_MAX_CHARS` | `150` | truncation length of the agent's last message inside a briefing |
161
+ | `TEAM_INBOX_MAX_CHARS` | `150` | **preview only**: how many characters of the agent's last message a knock quotes. The record line in `docs/team/inbox/<seat>.md` and the `state/notify.log` detail keep the **whole** message; a cut preview says so in-line (`truncated=preview:<shown>/<total>B full=<file>[:<line>]`) |
162
162
  | `TEAM_NOTIFY_LOG` | `/tmp/<project>-teamsmith-notify.log` | extension debug log (look here when notifications misbehave) |
163
163
  | `TEAM_NOTIFY_DETAIL_MAX` | `2048` | events a turn-end notification's detail file (`state/notify.log`) may hold before it is rotated to `state/notify.log.1` (one generation kept; a rotation is named in the extension log) |
164
164
  | `TEAM_DEFER_TTL` | `300` | delivery guard: seconds a queued message may wait before it is moved to `state/outbox/held/` (holding never types anything; the payload is already in the recipient's inbox). A backstop, not the first symptom: an untrusted geometry holds immediately and three trusted-empty drains with no progress hold as `queue-stalled` |
@@ -78,6 +78,27 @@ Guards and limitations:
78
78
  records in `state/notify.log`, bounded by `TEAM_NOTIFY_DETAIL_MAX` and rotated once). A different key, a manual
79
79
  notice in between, or a record write that failed starts a new line; a byte-identical briefing inside
80
80
  `TEAM_NOTIFY_DEDUP_SEC` is still suppressed outright.
81
+ - **A notice also lands where the PM reads it** (change `turn-notice-in-pm-inbox`): when the resolved sender is not
82
+ the PM, the same settle writes a second, **independent** line — a pointer — into `docs/team/inbox/pm.md`:
83
+ `<ISO> [<tag>] agent:<seat> · <ID> · knock=enqueued|skipped:<class> · see=docs/team/inbox/<seat>.md`, plus
84
+ `task=<ID> tip=<hex>` when the record carries the revision stamp and `awaiting=<ids>` for a suspension. It is
85
+ derived by the writing side from the record line (same merge key, same merger, no second "what is the same run"
86
+ implementation) and it does **not** append to the detail file, so a run's `×N` still equals its record count. It
87
+ carries no last-message summary, no `branch=`/`uncommitted=`/`unpushed=` and no `⚠ 未提交` prefix: it says where to
88
+ look, and the PM's line count is the PM's pending count. `knock=` is a **run-scoped** field like `×N` and
89
+ `first=`: extending a run keeps the value its first event wrote, because only that event could have woken the PM.
90
+ `enqueued` means "handed to the delivery guard", never "delivered" (`state/outbox/delivered.log` says that). A
91
+ failed pointer write is logged by the extension and changes nothing else: it does not delay, suppress or duplicate
92
+ the knock, and the record line is already on disk. The record line itself stays byte-identical — the pointer is a
93
+ second, independent write, not a rewrite.
94
+ - **One notice is counted once**: an auto-class line whose `agent:` names the inbox file's own seat is that seat's
95
+ record, not its unread traffic (`team_inbox_new` and `team_inbox_since` share the one predicate), so one delivery
96
+ adds exactly one to the PM's pending count — the pointer line — and a seat no longer sees its own `[auto]` lines as
97
+ new mail. Historical `[auto]` lines are not counted after the upgrade and are **not** backfilled with pointers: a
98
+ pointer records where a notice landed and what the knock did, and neither is observable for a notice written before
99
+ the pointer existed. `team inbox <seat> --all` still shows them. `--detail` reconciles a merged line's `×N`
100
+ against the records of **that line's own key** (its first component is the sender), so a `×N` pointer line in
101
+ `pm.md` is not reported as a gap.
81
102
  - **A notice names the revision it describes** (R2/P139; width and branch proof fixed by P160): the durable inbox
82
103
  line and the knock payload carry `task=<ID> tip=<12-hex>` — the **first twelve hex characters of the branch tip,
83
104
  truncated by the sender itself** (`git rev-parse HEAD | cut -c1-12`; the extension's `TIP_WIDTH`), never a Git
@@ -299,9 +299,13 @@ Honest edges (documented, not hidden):
299
299
  captures a pane, advances a drain observation or retries a delivery.
300
300
 
301
301
  If a notification really did get glued (e.g. the whitespace-only case), the mitigations from before still apply:
302
- answer with a short sentence right after reading it, lower the volume with `TEAM_INBOX_MAX_CHARS`, or set
303
- `TEAM_NOTIFY_TMUX=0` and read `team digest` yourself — or run that session on a built-in Pi launch path, where
304
- the box is not part of the delivery channel at all.
302
+ answer with a short sentence right after reading it, set `TEAM_NOTIFY_TMUX=0` and read `team digest` yourself — or
303
+ run that session on a built-in Pi launch path, where the box is not part of the delivery channel at all.
304
+
305
+ `TEAM_INBOX_MAX_CHARS` is **not** one of them: it only shortens the preview a knock quotes. The record line in
306
+ `docs/team/inbox/<seat>.md` and the detail in `state/notify.log` keep the whole message, so lowering it removes no
307
+ text from the inbox and no text from the disk — read what is already there and `team inbox <seat> --ack` it away,
308
+ and the volume that matters (events per day) is bounded by `TEAM_NOTIFY_DETAIL_MAX`, not by this key.
305
309
 
306
310
  ## 4. `team dispatch` refuses to dispatch
307
311