teamsmith 0.3.3 → 0.4.0

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 (82) hide show
  1. package/README.md +8 -8
  2. package/package.json +2 -6
  3. package/skills/teamsmith/CHANGELOG.md +77 -0
  4. package/skills/teamsmith/SKILL.md +83 -163
  5. package/skills/teamsmith/extension/team-inbox-watch.ts +30 -1
  6. package/skills/teamsmith/extension/team-notify.ts +162 -21
  7. package/skills/teamsmith/extension/team-reply.ts +105 -0
  8. package/skills/teamsmith/references/agent-adapters.md +4 -2
  9. package/skills/teamsmith/references/config.md +21 -12
  10. package/skills/teamsmith/references/migration.md +47 -3
  11. package/skills/teamsmith/references/protocol.md +85 -31
  12. package/skills/teamsmith/references/reminders.md +131 -0
  13. package/skills/teamsmith/references/troubleshooting.md +26 -8
  14. package/skills/teamsmith/references/workflows.md +18 -16
  15. package/skills/teamsmith/scripts/lib/cmd-agents.sh +290 -68
  16. package/skills/teamsmith/scripts/lib/cmd-config.sh +1 -1
  17. package/skills/teamsmith/scripts/lib/cmd-project.sh +193 -21
  18. package/skills/teamsmith/scripts/lib/cmd-remind.sh +103 -0
  19. package/skills/teamsmith/scripts/lib/cmd-status.sh +177 -21
  20. package/skills/teamsmith/scripts/lib/cmd-update.sh +7 -4
  21. package/skills/teamsmith/scripts/lib/cmd-watch.sh +11 -1
  22. package/skills/teamsmith/scripts/lib/common.sh +50 -6
  23. package/skills/teamsmith/scripts/lib/outbox.sh +103 -21
  24. package/skills/teamsmith/scripts/panel/panel.js +1 -1
  25. package/skills/teamsmith/scripts/panel/src/strings/en.ts +1 -1
  26. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +1 -1
  27. package/skills/teamsmith/scripts/remind-store.mjs +529 -0
  28. package/skills/teamsmith/scripts/replies.mjs +9 -3
  29. package/skills/teamsmith/scripts/reply-capture.mjs +596 -0
  30. package/skills/teamsmith/scripts/state-authority.mjs +500 -0
  31. package/skills/teamsmith/scripts/strings/commands.tsv +2 -1
  32. package/skills/teamsmith/scripts/strings/help.en.tsv +16 -2
  33. package/skills/teamsmith/scripts/strings/help.zh.tsv +16 -2
  34. package/skills/teamsmith/scripts/team +2 -0
  35. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +68 -123
  36. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +48 -55
  37. package/skills/teamsmith/templates/config.sh.tmpl +2 -1
  38. package/skills/teamsmith/templates/pm-prompt.md.tmpl +126 -119
  39. package/skills/teamsmith/tests/bg-ledger-harness.mjs +17 -6
  40. package/skills/teamsmith/tests/bg-ledger.sh +16 -5
  41. package/skills/teamsmith/tests/checkout-shape-probe.sh +6 -5
  42. package/skills/teamsmith/tests/delivery-truth.sh +82 -47
  43. package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +71 -23
  44. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
  45. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-dirty-ab.py +143 -0
  46. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +26 -9
  47. package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +92 -20
  48. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +47 -3
  49. package/skills/teamsmith/tests/fixtures/reply-capture-provider.ts +76 -0
  50. package/skills/teamsmith/tests/flip-p410-order2.sh +205 -0
  51. package/skills/teamsmith/tests/frames/README.md +3 -1
  52. package/skills/teamsmith/tests/gate-guard.sh +20 -4
  53. package/skills/teamsmith/tests/help-surface.sh +61 -3
  54. package/skills/teamsmith/tests/install-shape.sh +400 -38
  55. package/skills/teamsmith/tests/key-replies-pty.sh +197 -21
  56. package/skills/teamsmith/tests/key-replies.sh +187 -68
  57. package/skills/teamsmith/tests/ledger-claim.sh +8 -6
  58. package/skills/teamsmith/tests/lib/box-judge.sh +2 -1
  59. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +104 -0
  60. package/skills/teamsmith/tests/lib/pm-window.sh +127 -0
  61. package/skills/teamsmith/tests/lib/reply-fixture.sh +7 -19
  62. package/skills/teamsmith/tests/lib/reply-guard.sh +188 -0
  63. package/skills/teamsmith/tests/lib/section-calls.pl +171 -0
  64. package/skills/teamsmith/tests/loop-inventory.tsv +7 -5
  65. package/skills/teamsmith/tests/meta-suite.sh +215 -0
  66. package/skills/teamsmith/tests/panel-b3-pty-mouse.py +154 -17
  67. package/skills/teamsmith/tests/panel-b3.sh +33 -4
  68. package/skills/teamsmith/tests/panel-choices.sh +11 -7
  69. package/skills/teamsmith/tests/remind-cli.sh +574 -0
  70. package/skills/teamsmith/tests/reply-capture-real.mjs +360 -0
  71. package/skills/teamsmith/tests/reply-capture-real.sh +5 -0
  72. package/skills/teamsmith/tests/reply-capture.mjs +622 -0
  73. package/skills/teamsmith/tests/section-paths.tsv +41 -10
  74. package/skills/teamsmith/tests/section-select.sh +180 -26
  75. package/skills/teamsmith/tests/smoke.sh +1829 -249
  76. package/skills/teamsmith/tests/state-authority-node.mjs +42 -0
  77. package/skills/teamsmith/tests/state-authority.sh +629 -0
  78. package/skills/teamsmith/tests/task-model-routing.sh +10 -1
  79. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +33 -0
  80. package/skills/teamsmith/tests/team-notify-knock-marker.mjs +91 -0
  81. package/skills/teamsmith/tests/workflow-entry.sh +123 -3
  82. package/skills/teamsmith-init/SKILL.md +1 -1
@@ -74,7 +74,7 @@ function skillVersion(): string {
74
74
 
75
75
  function run(cmd: string, args: string[], cwd?: string): string {
76
76
  try {
77
- return execFileSync(cmd, args, { cwd, encoding: 'utf8', timeout: 5000 }).trim()
77
+ return execFileSync(cmd, args, { cwd, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
78
78
  } catch {
79
79
  return ''
80
80
  }
@@ -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
  }
@@ -0,0 +1,105 @@
1
+ /** PM-only, explicit live-message capture. No tools, provider hooks, history import, or automatic selection. */
2
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent'
3
+ import { createHash, randomUUID } from 'node:crypto'
4
+ import { readFileSync, realpathSync } from 'node:fs'
5
+ import { dirname, join } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { isDeepStrictEqual } from 'node:util'
8
+
9
+ // Captured during module evaluation, never reread later as a claim about loaded code.
10
+ const entry = realpathSync(fileURLToPath(import.meta.url))
11
+ const entryBytes = readFileSync(entry)
12
+ const hash = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex')
13
+ const slot = Symbol.for('teamsmith.reply-capture.owners.v1')
14
+ const owners: Map<string, object> = (globalThis as any)[slot] ??= new Map()
15
+ const moduleURL = (bytes: string) => `data:text/javascript;base64,${Buffer.from(bytes).toString('base64')}`
16
+
17
+ export default async function (pi: ExtensionAPI) {
18
+ const skill = dirname(dirname(entry))
19
+ // Snapshot and evaluate both dependencies on every factory/reload, bypassing native/Jiti dependency caches.
20
+ // This is the same reviewed local code, not generated behaviour or a general module loader.
21
+ const parserBytes = readFileSync(join(skill, 'scripts/reply-capture.mjs'), 'utf8')
22
+ const repliesBytes = readFileSync(join(skill, 'scripts/replies.mjs'), 'utf8')
23
+ const dependency = moduleURL(repliesBytes)
24
+ const parserURL = moduleURL(parserBytes.replace("'./replies.mjs'", JSON.stringify(dependency)))
25
+ const capture = await import(parserURL)
26
+ const fingerprint = capture.captureFingerprint({
27
+ 'extension/team-reply.ts': hash(entryBytes),
28
+ 'scripts/reply-capture.mjs': hash(parserBytes),
29
+ 'scripts/replies.mjs': hash(repliesBytes),
30
+ })
31
+ let engine: any, registration: any, key = '', active = false
32
+ const context = (ctx: ExtensionContext) => ({ cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId(), sessionFile: ctx.sessionManager.getSessionFile() })
33
+ const current = () => active && owners.get(key) === registration
34
+ const view = (ctx: ExtensionContext) => ({
35
+ identity: registration,
36
+ leaf: ctx.sessionManager.getLeafId(),
37
+ branch: ctx.sessionManager.getBranch(),
38
+ entry: (id: string) => ctx.sessionManager.getEntry(id),
39
+ })
40
+ const diagnostic = (d: { reason: string; entryId: string; path: string }) => {
41
+ // Never title/body/model text. Diagnostics are separate from the ordinary answer, including print/JSON modes.
42
+ process.stderr.write(`[team-reply] ${d.reason}; source=${d.entryId || 'unbound'}; evidence=${d.path}\n`)
43
+ }
44
+ const runtime = (status: string, reason?: string) => {
45
+ if (!current()) return
46
+ capture.updateRuntime(registration, (previous: any) => {
47
+ if (status !== 'ready' && previous?.generation !== registration.generation) return undefined
48
+ return { ...registration, status, reason, extension: entry, fingerprint, at: new Date().toISOString() }
49
+ })
50
+ }
51
+ pi.on('session_start', (_event, ctx) => {
52
+ active = false
53
+ engine = undefined
54
+ let identity: any
55
+ try { identity = capture.resolvePMIdentity(context(ctx)) }
56
+ catch (e: any) {
57
+ process.stderr.write(`[team-reply] disabled: ${e.message}\n`)
58
+ return // Unproven worker/ordinary/custom/foreign contexts do not mutate messages or register ready.
59
+ }
60
+ key = capture.sessionKey(identity)
61
+ if (owners.has(key)) return // A second loaded path must not sanitize, stage, or register a second owner.
62
+ registration = { ...identity, generation: randomUUID() }
63
+ owners.set(key, registration)
64
+ active = true
65
+ const claimed = registration
66
+ const owns = () => current() && registration === claimed
67
+ const expected = identity
68
+ const verify = () => {
69
+ try {
70
+ const valid = isDeepStrictEqual(expected, capture.resolvePMIdentity(context(ctx)))
71
+ if (!valid) runtime('degraded', 'identity/config changed')
72
+ return valid
73
+ } catch (e: any) {
74
+ try { runtime('degraded', e.message) } catch { /* A failed registry write cannot change identity refusal. */ }
75
+ return false
76
+ }
77
+ }
78
+ engine = new capture.ReplyCapture({ identity, current: owns, verify, owner: { pid: identity.pid, starttime: identity.starttime, generation: registration.generation }, diagnostic,
79
+ writer: (record: any) => capture.runReplyWriter({ team: join(skill, 'scripts/team'), identity, env: { ...process.env } }, record) })
80
+ try { runtime('ready') }
81
+ catch (e: any) { diagnostic({ reason: `runtime:${e.code ?? e.name}`, entryId: '', path: join(identity.state, 'reply-capture/runtime.json') }) }
82
+ engine.recover(view(ctx))
83
+ })
84
+ pi.on('before_agent_start', (_event, ctx) => { if (current()) engine.before(view(ctx)) })
85
+ pi.on('message_start', (event, ctx) => { if (current()) engine.start(event.message, view(ctx)) })
86
+ pi.on('message_end', (event, ctx) => {
87
+ if (!current()) return
88
+ return { message: engine.end(event.message, view(ctx)) }
89
+ })
90
+ pi.on('turn_end', (event, ctx) => { if (current()) engine.turn(event, view(ctx)) })
91
+ pi.on('agent_settled', (event, ctx) => { if (current()) engine.settled(event, view(ctx)) })
92
+ for (const event of ['session_before_switch', 'session_before_fork', 'session_tree'] as const) {
93
+ pi.on(event, () => { if (current()) engine.reset() })
94
+ }
95
+ pi.on('session_shutdown', async () => {
96
+ if (!current()) return
97
+ engine.reset()
98
+ await engine.drain()
99
+ try { runtime('degraded', 'session shutdown') }
100
+ catch (e: any) { diagnostic({ reason: `shutdown-runtime:${e.code ?? e.name}`, entryId: '', path: join(registration.state, 'reply-capture/runtime.json') }) }
101
+ // A delayed old shutdown must not clear a replacement generation.
102
+ if (owners.get(key) === registration) owners.delete(key)
103
+ active = false
104
+ })
105
+ }
@@ -321,7 +321,7 @@ ways, and **the channel is chosen by the target, not by the sender**:
321
321
  | Target | Channel |
322
322
  |---|---|
323
323
  | a Pi session that loaded `extension/team-inbox-watch.ts` (both built-in launch paths pass it with `-e`; a custom Pi-shaped template can add `-e {skill_dir}/extension/team-inbox-watch.ts`) | **inbox watch**: a durable inbox line plus one pointer line in `state/inbox-watch/<key>.wake`; the session's own extension calls `pi.sendMessage({customType:'team-inbox'}, {triggerTurn:true, deliverAs:'followUp'})`. **The input box is never read and never typed into.** |
324
- | everything else — a custom adapter, a Pi session without the extension, a dead or foreign registration — and the explicit escape hatch (`--now`) | **paste path**: the delivery guard reads the box, defers while it holds a draft, types, verifies the submission in the conversation above the box, and retracts or leaves residue honestly (`references/troubleshooting.md` §3) |
324
+ | everything else — a custom adapter, a Pi session without the extension, a dead or foreign registration — and any default `team say` that finds no usable watcher (it attempts the direct send at once, audited in `state/outbox/forced.log`), plus the human's explicit override (`team draft send --now` / `team outbox flush --now`) | **paste path**: the delivery guard reads the box, defers while it holds a draft, types, verifies the submission in the conversation above the box, and retracts or leaves residue honestly (`references/troubleshooting.md` §3) |
325
325
 
326
326
  Readiness is proven by the session itself: the extension writes `state/inbox-watch/<key>.reg`
327
327
  (`target=<session>:<window>`, `inbox=<name>`, `pid`, `cwd`, `started`, `heartbeat`), and a sender routes to the
@@ -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` |
@@ -190,17 +190,26 @@ project's seat, still without a live pane, and the same process start time the p
190
190
 
191
191
  ### Deferred delivery (`delivery-guard`)
192
192
 
193
- Automatic senders never type into an input box that already holds a draft: the message is queued in
194
- `state/outbox/` (one immutable file per message) and delivered when the box is free. A message deferred behind a
195
- **trusted** non-empty box is reported as `queued` (exit 0). Two outcomes are instead `held` with a machine reason
196
- and a non-zero exit: `geometry-untrusted` (the supported Pi layout cannot be established — no key is sent and no
197
- draft is asserted) and `queue-stalled` (three consecutive eligible drains read a trusted empty box but made no
198
- progress; observations are recorded per entry in `state/outbox/diagnostics/`). Both keep the immutable entry and
199
- its durable inbox copy; `team outbox list` names the reason and the recovery command, and the obstacles are also
200
- counted on the `team status` / `team digest` outbox line and in the panel. The escape hatches are explicit:
201
- `team say <agent> "…" --now` and `team outbox flush --now` type immediately **even into a non-empty box** and append
202
- one audit line to `state/outbox/forced.log`; `team outbox drop <n|all>` discards entries; `team draft pm`
203
- (`state/draft-pm.md`) is the human entry point. See `references/troubleshooting.md` §3 for the detector's known edges.
193
+ Protected automated senders — a `team notify` knock, the watchdog wake line, the notify extension's knock, the
194
+ meeting knock, ordinary `team draft send` and ordinary queued pane delivery — never type into an input box that
195
+ already holds a draft: the message is queued in `state/outbox/` (one immutable file per message) and delivered when
196
+ the box is free. A message deferred behind a **trusted** non-empty box is reported as `queued` (exit 0). Two
197
+ outcomes are instead `held` with a machine reason and a non-zero exit: `geometry-untrusted` (the supported Pi
198
+ layout cannot be established — no key is sent and no draft is asserted) and `queue-stalled` (three consecutive
199
+ eligible drains read a trusted empty box but made no progress; observations are recorded per entry in
200
+ `state/outbox/diagnostics/`). Both keep the immutable entry and its durable inbox copy; `team outbox list` names
201
+ the reason and the recovery command, and the obstacles are also counted on the `team status` / `team digest` outbox
202
+ line and in the panel.
203
+
204
+ `team say` is the exception the user chose. It prefers a valid live inbox watcher (durable inbox line plus wake
205
+ spool, zero tmux keys, the draft untouched). With no usable watcher it attempts the old direct send immediately,
206
+ even into a draft, after its recipient/`--any`, window, dead-pane and empty-shell checks, and appends one line to
207
+ `state/outbox/forced.log`. That is an **attempt**: it never claims confirmed model receipt and does not promise an
208
+ automatic queueing of a failed transport. The public `say --now` flag is retired (an unknown flag, exit 2).
209
+ The remaining explicit human overrides are `team draft send --now` and `team outbox flush --now`, which type even
210
+ into a non-empty box and record the skip in `state/outbox/forced.log`; `team outbox drop <n|all>` discards
211
+ entries; `team draft pm` (`state/draft-pm.md`) is the human entry point. See `references/troubleshooting.md` §3 for
212
+ the detector's known edges.
204
213
 
205
214
  ### Branch model (D1)
206
215
 
@@ -18,7 +18,7 @@ session) and for anyone deciding whether upgrading is safe.
18
18
  | `TEAM_*` environment variables | override the config file (env beats config) and are read that way in every version |
19
19
  | the `docs/team/**` layout | `tasks/ reports/ reviews/ threads/ inbox/` plus `BOARD.md ROADMAP.md OWNERSHIP.md DECISIONS.md PROTOCOL.md` |
20
20
  | `docs/team/BOARD.md` columns | `ID · task · agent · branch · deps · status`, with the status vocabulary `todo/wip/review/done/blocked/dropped` |
21
- | the `AGENTS.md` protocol section | injected between markers and **refreshed in place** by `team init`, never appended twice; only the marker text changed once (§2) |
21
+ | the `AGENTS.md` protocol section | injected between markers and **refreshed in place** by an explicit `team init` (never by `bootstrap`/`team up`), never appended twice; only the marker text changed once (§2). Outside the pair every byte is preserved — §1b |
22
22
  | `.pi/team/state/` | flat `key=value` files (agent records, `pm-loaded.env`, logs); version-agnostic and never migrated |
23
23
  | version bookkeeping | `team mark-loaded` + `team version --check` compare a version string and a content hash; deleting `state/pm-loaded.env` only makes the tool say "unknown", nothing breaks |
24
24
 
@@ -26,6 +26,47 @@ The **text** of `SKILL.md`, `references/**` and the templates is the part that g
26
26
  Commands always re-read `scripts/**` from disk, but text already read into a running session does not change under
27
27
  you — that is what `/reload` is for (§6), and §7 covers going back.
28
28
 
29
+ ## 1b. The AGENTS managed block: what an explicit refresh does, and what it does not
30
+
31
+ `team init` (without `--force`) is the only refresh path for the generated AGENTS block. `team bootstrap` on an
32
+ existing valid config installs the project-local skills and stops there — it does **not** run init's AGENTS writer —
33
+ and `team up` never touches AGENTS. `--force` re-renders config and ledger as well, so it is not the refresh switch.
34
+
35
+ **The boundary.** A delimiter is an exact standalone `<!-- teamsmith:begin -->` / `<!-- teamsmith:end -->` line
36
+ outside a fenced code block. Exactly one such pair is replaced between its two delimiter lines; a file with no such
37
+ line gains one block; any other shape is refused with the file left byte-identical and the reason named — two or more
38
+ pairs, a begin without its end (or the reverse), current and legacy delimiter lines mixed, or no pair in a file that
39
+ ends inside an unclosed fence. A marker quoted in prose, indented, sharing a line with text or sitting inside a closed
40
+ fenced example is ordinary content: never a pair, never an error.
41
+
42
+ **What survives.** Both delimiter lines and every byte outside them — preceding and following sections, ordinary
43
+ headings, project rules, those examples, line order, line endings (LF, CRLF, mixed) and a final line without a
44
+ newline. The inserted body uses the begin line's own terminator; nothing is normalized and no trailing newline is
45
+ added. **What does not survive**: everything *inside* the pair is managed text and is replaced, including any project
46
+ customization there. Project rules belong outside the markers — the managed block is not a customization surface.
47
+
48
+ **Before a refresh.** The PM inventories the rules currently inside the block and preserves them outside under the
49
+ project's own authorization, previews the exact command in a private copy with the project's actual inputs, and diffs
50
+ the result. init classifies nothing and moves no text for you.
51
+
52
+ **Render parameters.** Without the matching flag, a valid existing contract's present session, roster, docs path, PM
53
+ window and gates are used; the ordinary defaults (main-root basename session, `dev verify` roster, `docs/team`, `pm`
54
+ PM window, detected gates) apply only to a fresh project or an absent key, and an explicitly supplied flag still wins.
55
+ The AGENTS render currently passes the protected branch `main` — a non-main protected branch is a known limitation,
56
+ not something this recipe overrides.
57
+
58
+ **Write target.** Run it from the main checkout: a linked worktree resolves to the main root, so the main-root AGENTS
59
+ is the one refreshed and no private worktree AGENTS is created.
60
+
61
+ **The rest of init's writes are not skipped.** init also writes or skips config (and chmods it), creates the docs
62
+ skeleton, renders missing ledger files, overwrites the inbox/reviews `.gitignore` files, updates the root `.gitignore`,
63
+ and — unless `--no-skills` — installs the project-local skills and the `/team` extension. `--no-skills` skips
64
+ installation only, not the AGENTS refresh. The sequence is **not transactional**: a late install conflict can return
65
+ non-zero after AGENTS, docs and ignore writes already happened. Without `--force`, an existing valid config and
66
+ existing ledger documents keep their bytes; `--force` may replace config and ledger. A retired-model configuration is
67
+ refused before any write, with or without `--force`. An existing generated `PROTOCOL.md` is skipped by a non-force
68
+ init and keeps its old text.
69
+
29
70
  ## 2. The rename: `pi-team` → `teamsmith` (v1.13.0)
30
71
 
31
72
  The name change touched three things and only one of them needs a command from you.
@@ -34,7 +75,7 @@ The name change touched three things and only one of them needs a command from y
34
75
  |---|---|---|
35
76
  | `skills/pi-team` (repository path **and** installed skill directory) | `skills/teamsmith` | **change the path** (since the release that carries M22): the compatibility symlink was **removed**, so an absolute path or a `settings.json` entry that still says `skills/pi-team` must be updated to `skills/teamsmith` (or to the installed `~/.agents/skills/teamsmith`). The installed copy is unaffected — it is a link to *this repository*, not to the old name. See §2b below |
36
77
  | the Pi command `/pi-team-reload` | `/teamsmith-reload` | **nothing**: the old spelling stays registered as an alias |
37
- | the `AGENTS.md` marker `<!-- pi-team:begin -->` … `<!-- pi-team:end -->` | `<!-- teamsmith:begin -->` … `<!-- teamsmith:end -->` | run `team init` (or `team bootstrap`) once: the marker is rewritten **in place** and idempotently, with no duplicate section. `team doctor` prints a pointer to this file while the old marker is still there |
78
+ | the `AGENTS.md` marker `<!-- pi-team:begin -->` … `<!-- pi-team:end -->` | `<!-- teamsmith:begin -->` … `<!-- teamsmith:end -->` | run an explicit `team init` once: the legacy pair is converted **in place** and idempotently, with no duplicate section (§1b). An existing valid config's `team bootstrap` does not run this writer, and `team up` never does. `team doctor` prints a pointer to this file while the old marker is still there |
38
79
  | the repository name `pi-team` | `teamsmith` | only if your own notes or scripts hard-code it; the skill's contracts (command, config, `TEAM_*`, `docs/team/**`) were never renamed |
39
80
  | prose in your own docs, briefs or scripts | — | by hand: the skill cannot rewrite your files (the former name is also what a "stale session" error message used to say) |
40
81
 
@@ -73,7 +114,7 @@ period was ended early by the user's call. What this means for an existing proje
73
114
  | your `settings.json` `skills` array, or a config/`TEAM_*` value with an **absolute** path | replace the removed alias `skills/pi-team` with `skills/teamsmith` (a project that uses the CLI through `PATH` or a `~/.agents/skills/teamsmith` link needs nothing) |
74
115
  | your own notes, briefs or scripts | by hand — the skill cannot rewrite your files |
75
116
  | the installed directory `~/.agents/skills/pi-team` | re-run `./install.sh` (it installs the canonical directories only); `./install.sh --uninstall` also removes a legacy `pi-team` entry left by an older install |
76
- | an `AGENTS.md` marker `<!-- pi-team:begin -->` | **still automatic**: the next `team init`/`team bootstrap` rewrites the marker in place (§2) |
117
+ | an `AGENTS.md` marker `<!-- pi-team:begin -->` | **still automatic, by an explicit `team init`**: it converts the legacy pair in place (§1b); `team bootstrap` on an existing valid config does not, and `team up` never does |
77
118
  | the Pi command `/pi-team-reload` | **still works**: it stays registered as an alias of `/teamsmith-reload` — a *command name*, not a path |
78
119
 
79
120
  A *copy* install (`./install.sh --copy`) made while the symlink existed simply carries a copy of the old alias;
@@ -290,6 +331,9 @@ and inference are **not** migration routes (§5b). Confirm the new shape before
290
331
  team config list # exit code 0, and no `migration_required` line at the end
291
332
  ```
292
333
 
334
+ The AGENTS managed block is not part of this migration: `team up` and `bootstrap` do not refresh it. An explicit
335
+ `team init` does, under the boundary and preservation rules in §1b.
336
+
293
337
  ### Step 3 — the PM launch identity (`state/pm-launch.env`)
294
338
 
295
339
  `.pi/team/state/pm-launch.env` is a flat record of the identity the PM was last started with: the project and