teamsmith 0.4.5 → 0.4.7

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 (81) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +37 -1
  4. package/skills/teamsmith/SKILL.md +32 -23
  5. package/skills/teamsmith/extension/team-bg.ts +12 -11
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +149 -5
  7. package/skills/teamsmith/extension/team-notify.ts +20 -13
  8. package/skills/teamsmith/extension/team-remind.ts +189 -0
  9. package/skills/teamsmith/extension/team-reply.ts +4 -7
  10. package/skills/teamsmith/references/migration.md +101 -0
  11. package/skills/teamsmith/references/openspec.md +43 -27
  12. package/skills/teamsmith/references/protocol.md +28 -18
  13. package/skills/teamsmith/references/reminders.md +133 -98
  14. package/skills/teamsmith/references/troubleshooting.md +12 -7
  15. package/skills/teamsmith/references/workflows.md +85 -34
  16. package/skills/teamsmith/scripts/lib/cmd-agents.sh +28 -5
  17. package/skills/teamsmith/scripts/lib/cmd-project.sh +100 -15
  18. package/skills/teamsmith/scripts/lib/cmd-remind.sh +135 -10
  19. package/skills/teamsmith/scripts/lib/cmd-review.sh +42 -4
  20. package/skills/teamsmith/scripts/lib/cmd-update.sh +90 -88
  21. package/skills/teamsmith/scripts/lib/cmd-watch.sh +322 -159
  22. package/skills/teamsmith/scripts/lib/common.sh +156 -26
  23. package/skills/teamsmith/scripts/panel/panel.js +182 -182
  24. package/skills/teamsmith/scripts/panel/src/data.ts +113 -6
  25. package/skills/teamsmith/scripts/panel/src/layout.ts +26 -4
  26. package/skills/teamsmith/scripts/panel/src/main.tsx +103 -14
  27. package/skills/teamsmith/scripts/remind-capability.mjs +261 -0
  28. package/skills/teamsmith/scripts/remind-store.mjs +404 -17
  29. package/skills/teamsmith/scripts/remind-tick.mjs +105 -0
  30. package/skills/teamsmith/scripts/reminder-delivery.mjs +76 -0
  31. package/skills/teamsmith/scripts/reply-capture.mjs +8 -9
  32. package/skills/teamsmith/scripts/state-authority.mjs +334 -20
  33. package/skills/teamsmith/scripts/strings/commands.tsv +3 -3
  34. package/skills/teamsmith/scripts/strings/help.en.tsv +12 -12
  35. package/skills/teamsmith/scripts/strings/help.zh.tsv +12 -12
  36. package/skills/teamsmith/scripts/team +4 -3
  37. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +13 -11
  38. package/skills/teamsmith/templates/DECISIONS.md.tmpl +2 -2
  39. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +3 -3
  40. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +19 -14
  41. package/skills/teamsmith/templates/memory-seed.md.tmpl +2 -2
  42. package/skills/teamsmith/templates/pm-prompt.md.tmpl +36 -18
  43. package/skills/teamsmith/templates/report.md.tmpl +33 -0
  44. package/skills/teamsmith/tests/bg-ledger-harness.mjs +217 -33
  45. package/skills/teamsmith/tests/bg-ledger.sh +24 -10
  46. package/skills/teamsmith/tests/checkout-shape-probe.sh +7 -6
  47. package/skills/teamsmith/tests/death-cause.sh +5 -0
  48. package/skills/teamsmith/tests/fixtures/remind-adversarial-delay.ts +27 -0
  49. package/skills/teamsmith/tests/fixtures/remind-tool-provider.ts +65 -0
  50. package/skills/teamsmith/tests/help-surface.sh +14 -151
  51. package/skills/teamsmith/tests/isolation-ledger.sh +89 -0
  52. package/skills/teamsmith/tests/key-replies-ui.sh +53 -0
  53. package/skills/teamsmith/tests/key-replies.sh +307 -106
  54. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +17 -1
  55. package/skills/teamsmith/tests/lib/routes-pages.sh +243 -0
  56. package/skills/teamsmith/tests/live-capture-probe.sh +12 -2
  57. package/skills/teamsmith/tests/loop-inventory.tsv +1 -0
  58. package/skills/teamsmith/tests/panel-b3-stub.sh +9 -2
  59. package/skills/teamsmith/tests/pulse-nudge-key.sh +5 -0
  60. package/skills/teamsmith/tests/remind-adversarial-faults.mjs +163 -0
  61. package/skills/teamsmith/tests/remind-adversarial-faults.sh +26 -0
  62. package/skills/teamsmith/tests/remind-adversarial-real.sh +27 -0
  63. package/skills/teamsmith/tests/remind-cli.sh +108 -3
  64. package/skills/teamsmith/tests/remind-delivery-node.mjs +189 -0
  65. package/skills/teamsmith/tests/remind-delivery.sh +699 -0
  66. package/skills/teamsmith/tests/remind-lifecycle.sh +197 -0
  67. package/skills/teamsmith/tests/remind-pulse.sh +199 -0
  68. package/skills/teamsmith/tests/remind-recovery-real.sh +5 -0
  69. package/skills/teamsmith/tests/remind-recovery-unit.sh +118 -0
  70. package/skills/teamsmith/tests/remind-tool-node.mjs +159 -0
  71. package/skills/teamsmith/tests/remind-tool-real.mjs +754 -0
  72. package/skills/teamsmith/tests/remind-tool-real.sh +5 -0
  73. package/skills/teamsmith/tests/reply-capture-real.mjs +93 -2
  74. package/skills/teamsmith/tests/routes.sh +213 -293
  75. package/skills/teamsmith/tests/section-paths.tsv +14 -12
  76. package/skills/teamsmith/tests/smoke.sh +876 -130
  77. package/skills/teamsmith/tests/state-authority.sh +392 -28
  78. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +58 -8
  79. package/skills/teamsmith/tests/tmux-identity-leak.sh +12 -16
  80. package/skills/teamsmith-init/SKILL.md +5 -5
  81. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
@@ -621,6 +621,16 @@ export async function loadPanelData(opts: DataOptions): Promise<DataResult> {
621
621
  return res
622
622
  }
623
623
 
624
+ /** Signal the child's own process group, so a timed-out/stopped patrol cannot orphan its sleep or helper. */
625
+ export function signalPulseChild(child: ReturnType<typeof spawn>, signal: NodeJS.Signals): void {
626
+ try {
627
+ if (child.pid) process.kill(-child.pid, signal)
628
+ else child.kill(signal)
629
+ } catch {
630
+ try { child.kill(signal) } catch { /* already gone */ }
631
+ }
632
+ }
633
+
624
634
  /**
625
635
  * One patrol tick: `team watch --once`, output appended to the tick log and the log trimmed at
626
636
  * 200 lines — the same tick (and the same trim) the bash loop performed, now owned by the run
@@ -632,6 +642,7 @@ export function runTick(
632
642
  root: string,
633
643
  tickLog: string,
634
644
  timeoutMs = 180000,
645
+ children?: Set<ReturnType<typeof spawn>>,
635
646
  ): Promise<{ ok: boolean; output: string }> {
636
647
  return new Promise((resolve) => {
637
648
  let child: ReturnType<typeof spawn>
@@ -640,7 +651,9 @@ export function runTick(
640
651
  cwd: root,
641
652
  env: cleanIdentityEnv(),
642
653
  stdio: ['ignore', 'pipe', 'pipe'],
654
+ detached: true,
643
655
  })
656
+ children?.add(child)
644
657
  } catch (e) {
645
658
  resolve({ ok: false, output: (e as Error).message })
646
659
  return
@@ -651,6 +664,7 @@ export function runTick(
651
664
  if (settled) return
652
665
  settled = true
653
666
  clearTimeout(timer)
667
+ children?.delete(child)
654
668
  try {
655
669
  appendFileSync(tickLog, out)
656
670
  const lines = readFileSync(tickLog, 'utf8').split('\n')
@@ -662,12 +676,8 @@ export function runTick(
662
676
  resolve({ ok, output: out })
663
677
  }
664
678
  const timer = setTimeout(() => {
665
- try {
666
- child.kill('SIGKILL')
667
- } catch {
668
- /* already gone */
669
- }
670
- done(false)
679
+ signalPulseChild(child, 'SIGKILL')
680
+ // close is the reaping point; killing is not evidence that the child exited.
671
681
  }, timeoutMs)
672
682
  child.stdout?.on('data', (d: Buffer) => {
673
683
  out += String(d)
@@ -679,3 +689,100 @@ export function runTick(
679
689
  child.on('close', (code) => done(code === 0))
680
690
  })
681
691
  }
692
+
693
+ /**
694
+ * One lightweight Reminder due tick (agent-self-reminder 4.1). It is NOT a patrol: `remind-tick.mjs`
695
+ * reads one bounded snapshot, commits due queue entries under the authority lock only when something is
696
+ * actually due, and never runs the project scan. One child per interval, asynchronous for the same
697
+ * reason the patrol tick is: a due tick must not freeze the console's input line.
698
+ */
699
+ export function runRemindTick(
700
+ script: string,
701
+ root: string,
702
+ stateDir: string,
703
+ pulseStartedAt: string,
704
+ tickLog: string,
705
+ timeoutMs = 30000,
706
+ children?: Set<ReturnType<typeof spawn>>,
707
+ ): Promise<{ ok: boolean; output: string }> {
708
+ return new Promise((resolve) => {
709
+ let child: ReturnType<typeof spawn>
710
+ try {
711
+ child = spawn(process.execPath, [
712
+ script, '--root', root, '--state-dir', stateDir, '--pulse-started', pulseStartedAt, '--quiet', '--json',
713
+ ], { cwd: root, env: cleanIdentityEnv(), stdio: ['ignore', 'pipe', 'pipe'], detached: true })
714
+ children?.add(child)
715
+ } catch (e) {
716
+ resolve({ ok: false, output: (e as Error).message })
717
+ return
718
+ }
719
+ let out = ''
720
+ let settled = false
721
+ const done = (ok: boolean): void => {
722
+ if (settled) return
723
+ settled = true
724
+ clearTimeout(timer)
725
+ children?.delete(child)
726
+ let meaningful = !ok
727
+ if (ok && out.trim()) {
728
+ try {
729
+ const result = JSON.parse(out)
730
+ meaningful = (result.admitted?.length ?? 0) > 0 || (result.swept?.length ?? 0) > 0
731
+ } catch { meaningful = true }
732
+ }
733
+ if (meaningful && out.trim()) {
734
+ try { appendFileSync(tickLog, `${new Date().toISOString()} remind-tick: ${out}`) } catch { /* a log that cannot be written must not kill the panel */ }
735
+ }
736
+ resolve({ ok, output: out })
737
+ }
738
+ const timer = setTimeout(() => {
739
+ signalPulseChild(child, 'SIGKILL')
740
+ // Reap on close, not on the timeout callback.
741
+ }, timeoutMs)
742
+ child.stdout?.on('data', (d: Buffer) => { out += String(d) })
743
+ child.stderr?.on('data', (d: Buffer) => { out += String(d) })
744
+ child.on('error', () => done(false))
745
+ child.on('close', (code) => done(code === 0))
746
+ })
747
+ }
748
+
749
+ /** One serialized Reminder-only recovery decision. It never runs the ordinary project patrol. */
750
+ export function runReminderRecovery(
751
+ cli: string,
752
+ root: string,
753
+ tickLog: string,
754
+ timeoutMs = 30000,
755
+ children?: Set<ReturnType<typeof spawn>>,
756
+ ): Promise<{ ok: boolean; output: string }> {
757
+ return new Promise((resolve) => {
758
+ let child: ReturnType<typeof spawn>
759
+ try {
760
+ child = spawn('bash', [cli, '--root', root, '__remind-recover'], {
761
+ cwd: root, env: cleanIdentityEnv(), stdio: ['ignore', 'pipe', 'pipe'], detached: true,
762
+ })
763
+ children?.add(child)
764
+ } catch (e) {
765
+ resolve({ ok: false, output: (e as Error).message })
766
+ return
767
+ }
768
+ let out = ''
769
+ let settled = false
770
+ const done = (ok: boolean): void => {
771
+ if (settled) return
772
+ settled = true
773
+ clearTimeout(timer)
774
+ children?.delete(child)
775
+ if (out.trim()) {
776
+ try { appendFileSync(tickLog, `${new Date().toISOString()} reminder-recovery: ${out}`) } catch { /* logging must not kill the panel */ }
777
+ }
778
+ resolve({ ok, output: out })
779
+ }
780
+ const timer = setTimeout(() => {
781
+ signalPulseChild(child, 'SIGKILL')
782
+ }, timeoutMs)
783
+ child.stdout?.on('data', (d: Buffer) => { out += String(d) })
784
+ child.stderr?.on('data', (d: Buffer) => { out += String(d) })
785
+ child.on('error', () => done(false))
786
+ child.on('close', (code) => done(code === 0))
787
+ })
788
+ }
@@ -1343,6 +1343,21 @@ function replyRowLabel(e: ReplyEntry): string {
1343
1343
  return e.available ? `#${e.no} ${e.title}` : ''
1344
1344
  }
1345
1345
 
1346
+ /** Reader's local clock: compact for rows/summary, full date and actual offset for the viewer. */
1347
+ function replyTimeLabel(at: string | undefined, full = false): string {
1348
+ if (!at) return ''
1349
+ const when = new Date(at)
1350
+ if (Number.isNaN(when.getTime())) return ''
1351
+ const pad = (n: number): string => String(n).padStart(2, '0')
1352
+ const compact = `${pad(when.getMonth() + 1)}-${pad(when.getDate())} ${pad(when.getHours())}:${pad(when.getMinutes())}`
1353
+ if (!full) return compact
1354
+ const offsetMinutes = -when.getTimezoneOffset()
1355
+ const offsetSign = offsetMinutes >= 0 ? '+' : '-'
1356
+ const absoluteOffset = Math.abs(offsetMinutes)
1357
+ const offset = `${offsetSign}${pad(Math.floor(absoluteOffset / 60))}:${pad(absoluteOffset % 60)}`
1358
+ return `${String(when.getFullYear()).padStart(4, '0')}-${compact} ${offset}`
1359
+ }
1360
+
1346
1361
  /** The nav row of page 5: Older / Newer / `r` (the same actions `←`/`→` and `r` fire). */
1347
1362
  function replyNavLine(ctx: Ctx, innerW: number): PlacedLine {
1348
1363
  const { s } = ctx
@@ -1414,11 +1429,13 @@ function replyListBlock(ctx: Ctx): Block | null {
1414
1429
  const active = i === focus
1415
1430
  const cursor = active ? s.settingsCursor : ' '
1416
1431
  const head = ` ${cursor} `
1432
+ const at = e.available ? replyTimeLabel(e.at) : ''
1417
1433
  const bodyLine: Line = e.available
1418
1434
  ? ln(
1419
1435
  seg(head, 'accent'),
1420
1436
  seg(replyRowLabel(e), active ? 'selected' : 'text'),
1421
1437
  seg(` · ${e.from}`, 'dim'),
1438
+ ...(at ? [seg(` · ${at}`, 'dim')] : []),
1422
1439
  )
1423
1440
  : ln(
1424
1441
  seg(head, 'accent'),
@@ -1475,9 +1492,11 @@ function replyViewerBlock(ctx: Ctx): Block | null {
1475
1492
  if (data.available === false) {
1476
1493
  return build([nav, { line: truncLine(ln(seg(` ${s.replyBodyMissing}`, 'warn')), innerW) }, backLine], { no, total: 0, visible: 0, offset: 0 })
1477
1494
  }
1495
+ const at = replyTimeLabel(data.at, true)
1496
+ const declared = fill(at ? s.replyDeclared : s.replyDeclaredShort, { from: data.from, at })
1478
1497
  const meta: PlacedLine[] = [
1479
1498
  { line: truncLine(ln(seg(` ${data.title}`, 'heading')), innerW) },
1480
- { line: truncLine(ln(seg(` ${fill(s.replyDeclared, { from: data.from, at: data.at })}`, 'dim')), innerW) },
1499
+ { line: truncLine(ln(seg(` ${declared}`, 'dim')), innerW) },
1481
1500
  { line: truncLine(ln(seg(` ${s.replyBodyHint} · ${data.bytes} B`, 'dim')), innerW) },
1482
1501
  ]
1483
1502
  const doc = markdownMemo(`reply:${no}`, data.display_text ?? '', innerW)
@@ -1513,9 +1532,12 @@ function replySummaryBlock(ctx: Ctx): Block | null {
1513
1532
  line.push(seg(text, 'text'))
1514
1533
  hits.push({ start: x, end: x + dispWidth(text), action: { kind: 'reply-open-latest', no: entry.no } })
1515
1534
  x += dispWidth(text)
1516
- const at = ` · ${entry.at}`
1517
- line.push(seg(at, 'dim'))
1518
- x += dispWidth(at)
1535
+ const at = replyTimeLabel(entry.at)
1536
+ if (at) {
1537
+ const suffix = ` · ${at}`
1538
+ line.push(seg(suffix, 'dim'))
1539
+ x += dispWidth(suffix)
1540
+ }
1519
1541
  } else if (d.state === 'empty') {
1520
1542
  line.push(seg(s.replyEmpty, 'dim'))
1521
1543
  } else {
@@ -41,7 +41,10 @@ import {
41
41
  findTeamCli,
42
42
  loadPanelData,
43
43
  panelDirOf,
44
+ runRemindTick,
45
+ runReminderRecovery,
44
46
  runTick,
47
+ signalPulseChild,
45
48
  type BlockName,
46
49
  } from './data.js'
47
50
  import type { DataOptions, DataResult, PanelCache } from './data.js'
@@ -267,9 +270,17 @@ if (mode === 'palette') {
267
270
  process.exit(0)
268
271
  }
269
272
 
270
- // ---------------------------------------------------------------- the tick loop (owned here)
273
+ // ---------------------------------------------------------------- Pulse scheduling (one patrol + one recovery)
271
274
  let lastTick = 0
272
275
  const tickLog = argOf('tick-log') || `${root}/.pi/team/state/watchdog.tick.log`
276
+ const pulseChildren = new Set<ReturnType<typeof spawn>>()
277
+ let patrolRun: ReturnType<typeof runTick> | null = null
278
+ let recoveryRun: ReturnType<typeof runReminderRecovery> | null = null
279
+ let admissionRun: ReturnType<typeof runRemindTick> | null = null
280
+ let recoveryPending = false
281
+ let recoverySeen = ''
282
+ let pendingRecoverySignature = ''
283
+ let pulseStopping: Promise<unknown> | null = null
273
284
 
274
285
  function tickDue(): boolean {
275
286
  if (noPulse || tickEvery <= 0) return false
@@ -281,10 +292,79 @@ function tickDue(): boolean {
281
292
  return false
282
293
  }
283
294
 
295
+ function scheduleRecovery(): void {
296
+ if (!teamCli || !recoveryPending) return
297
+ if (patrolRun || recoveryRun || admissionRun) return
298
+ recoveryPending = false
299
+ recoverySeen = pendingRecoverySignature
300
+ recoveryRun = runReminderRecovery(teamCli, root, tickLog, 30000, pulseChildren)
301
+ void recoveryRun.finally(() => {
302
+ recoveryRun = null
303
+ if (recoveryPending) scheduleRecovery()
304
+ })
305
+ }
306
+
307
+ function schedulePatrol(): void {
308
+ if (!teamCli || patrolRun || recoveryRun) return
309
+ patrolRun = runTick(teamCli, root, tickLog, 180000, pulseChildren)
310
+ void patrolRun.finally(() => {
311
+ patrolRun = null
312
+ recoverySeen = '' // at most one recheck for the same queued IDs after each full patrol
313
+ if (recoveryPending) scheduleRecovery()
314
+ })
315
+ }
316
+
284
317
  async function runTickIfDue(): Promise<void> {
285
- if (!tickDue()) return
286
- if (!teamCli) return
287
- await runTick(teamCli, root, tickLog)
318
+ if (!tickDue() || !teamCli || patrolRun || recoveryRun) return
319
+ schedulePatrol()
320
+ if (patrolRun) await patrolRun
321
+ }
322
+
323
+ // The due tick remains independent of a long patrol. Its result sets one coalesced recovery bit;
324
+ // recovery runs after the active patrol/recovery, never as an ordinary backlog nudge or second patrol.
325
+ const remindEvery = Math.max(1, Number(process.env.TEAM_REMIND_TICK_SECS ?? 10) || 10)
326
+ const remindStartedAt = new Date().toISOString()
327
+ const remindScript = teamCli ? join(dirname(teamCli), 'remind-tick.mjs') : ''
328
+ let lastRemind = 0
329
+
330
+ function remindDue(): boolean {
331
+ if (noPulse || !remindScript) return false
332
+ const now = Date.now()
333
+ if (lastRemind === 0 || now - lastRemind >= remindEvery * 1000) {
334
+ lastRemind = now
335
+ return true
336
+ }
337
+ return false
338
+ }
339
+
340
+ async function runRemindIfDue(): Promise<void> {
341
+ if (!remindDue() || admissionRun) return
342
+ admissionRun = runRemindTick(remindScript, root, stateDir, remindStartedAt, tickLog, 30000, pulseChildren)
343
+ try {
344
+ const result = await admissionRun
345
+ if (result.output.trim()) {
346
+ try {
347
+ const tick = JSON.parse(result.output)
348
+ const signature = Array.isArray(tick.recoveryIds) ? tick.recoveryIds.join(',') : ''
349
+ if (tick.recoveryRequired === true && signature !== recoverySeen) {
350
+ recoveryPending = true
351
+ pendingRecoverySignature = signature
352
+ }
353
+ }
354
+ catch { /* the child already logged a visible failure; the next interval re-reads the authority */ }
355
+ }
356
+ } finally { admissionRun = null }
357
+ scheduleRecovery()
358
+ }
359
+
360
+ async function stopPulseChildren(): Promise<void> {
361
+ recoveryPending = false
362
+ for (const child of pulseChildren) signalPulseChild(child, 'SIGTERM')
363
+ if (!pulseStopping) {
364
+ const runs = [patrolRun, recoveryRun, admissionRun].filter((run): run is NonNullable<typeof run> => Boolean(run))
365
+ pulseStopping = Promise.allSettled(runs).then(() => { pulseChildren.clear() })
366
+ }
367
+ await pulseStopping
288
368
  }
289
369
 
290
370
  function frameOf(res: DataResult, activity: boolean, scroll?: number): FrameInput {
@@ -393,10 +473,14 @@ async function main(): Promise<void> {
393
473
 
394
474
  if (mode === 'headless') {
395
475
  // The tick loop with no renderer. `team monitor --headless` is the bash loop (lock + drift
396
- // reexec); this branch serves a direct bundle invocation and keeps the same cadence.
476
+ // reexec); this branch serves a direct bundle invocation and keeps the same non-overlap rules.
477
+ const stop = async (code: number): Promise<void> => { await stopPulseChildren(); process.exit(code) }
478
+ process.on('SIGTERM', () => { void stop(143) })
479
+ process.on('SIGHUP', () => { void stop(129) })
397
480
  for (;;) {
398
- await runTickIfDue()
399
- sleepSync(Math.max(1, tickEvery || refresh) * 1000)
481
+ void runTickIfDue()
482
+ void runRemindIfDue()
483
+ await new Promise(resolve => setTimeout(resolve, remindEvery * 1000))
400
484
  }
401
485
  }
402
486
 
@@ -485,6 +569,7 @@ async function main(): Promise<void> {
485
569
 
486
570
  const reload = (): FrameInput => {
487
571
  void runTickIfDue()
572
+ void runRemindIfDue()
488
573
  void cache.refresh().then(adopt)
489
574
  return current
490
575
  }
@@ -975,18 +1060,22 @@ async function main(): Promise<void> {
975
1060
  }
976
1061
  }
977
1062
  process.on('exit', restoreTerminal)
978
- process.on('SIGTERM', () => {
1063
+ let pulseShutdown = false
1064
+ const shutdownPulse = async (code: number): Promise<void> => {
1065
+ if (pulseShutdown) return
1066
+ pulseShutdown = true
979
1067
  restoreTerminal()
980
- process.exit(143)
981
- })
982
- process.on('SIGHUP', () => {
983
- restoreTerminal()
984
- process.exit(129)
985
- })
1068
+ await stopPulseChildren()
1069
+ cache.dispose()
1070
+ process.exit(code)
1071
+ }
1072
+ process.on('SIGTERM', () => { void shutdownPulse(143) })
1073
+ process.on('SIGHUP', () => { void shutdownPulse(129) })
986
1074
 
987
1075
  if (once) await runTickIfDue()
988
1076
  await app.waitUntilExit()
989
1077
  restoreTerminal()
1078
+ await stopPulseChildren()
990
1079
  cache.dispose()
991
1080
  process.exit(0)
992
1081
  }
@@ -0,0 +1,261 @@
1
+ // PM-only Reminder tool identity, authority invocation and live capability evidence (P442).
2
+ // Reminder data itself stays in state-authority.mjs: this file never reads or writes reminders/state.json.
3
+ // Invalid identities fail before runReminderAuthority is called. The separate evidence file is only a
4
+ // freshness-bounded report from this extension instance; it is not proof of model visibility or tool use.
5
+ import { closeSync, constants as C, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
6
+ import { spawn, spawnSync } from 'node:child_process'
7
+ import { createHash, randomUUID } from 'node:crypto'
8
+ import { join } from 'node:path'
9
+ import { isDeepStrictEqual } from 'node:util'
10
+ import { ancestor, processIdentity, proofPid, readRegular, resolvePMIdentity, safeDirectory, tmuxEvidence } from './reply-capture.mjs'
11
+
12
+ export const REMIND_CAPABILITY_TTL_MS = 20000
13
+ export const remindCapabilitySourceFiles = ['extension/team-remind.ts', 'scripts/remind-capability.mjs', 'scripts/reply-capture.mjs', 'scripts/replies.mjs']
14
+ const digest = value => createHash('sha256').update(value).digest('hex')
15
+ export const remindCapabilityFingerprint = hashes => digest(JSON.stringify(remindCapabilitySourceFiles.map(file => [file, hashes[file]])))
16
+ export function remindCapabilityDiskFingerprint(skill) {
17
+ const hashes = Object.fromEntries(remindCapabilitySourceFiles.map(file => [file, digest(readFileSync(join(skill, file)))]))
18
+ return remindCapabilityFingerprint(hashes)
19
+ }
20
+
21
+ function regular(path, flags, mode = 0o600) {
22
+ const fd = openSync(path, flags | C.O_NOFOLLOW | C.O_NONBLOCK, mode)
23
+ const st = fstatSync(fd)
24
+ const unsafe = !st.isFile() ? 'is not a regular file' : st.uid !== process.getuid() ? 'is not owned by this process' : ''
25
+ if (unsafe) { closeSync(fd); throw new Error(`unsafe regular file: ${path} ${unsafe}`) }
26
+ return fd
27
+ }
28
+
29
+ export function configValue(text, key) {
30
+ const match = new RegExp(`^\\s*(?:export\\s+)?${key}=(.*)\\s*$`, 'm').exec(text)
31
+ if (!match) return null
32
+ const raw = match[1].trim()
33
+ const quoted = /^(["'])(.*)\1(?:[ \t]+#.*)?$/.exec(raw)
34
+ if (quoted) return quoted[2]
35
+ return raw.replace(/[ \t]+#.*$/, '').trimEnd()
36
+ }
37
+
38
+ function verifyConfiguration(identity) {
39
+ const text = readRegular(identity.config)
40
+ for (const [key, expected] of [['TEAM_SESSION', identity.tmux.session], ['TEAM_PM_WINDOW', identity.tmux.window]]) {
41
+ const actual = configValue(text, key)
42
+ if (actual !== expected) throw new Error(`PM config ${key} does not match the directed launch`)
43
+ }
44
+ for (const key of ['TEAM_PM_CMD', 'TEAM_PM_BIN']) {
45
+ const value = configValue(text, key)
46
+ if (value !== null && value !== '') throw new Error(`custom PM adapter has no team_remind contract (${key})`)
47
+ }
48
+ }
49
+
50
+ function launchRecord(identity, required = false) {
51
+ const path = join(identity.state, 'pm-launch.env')
52
+ let text
53
+ try { text = readRegular(path) } catch (e) {
54
+ if (e.code === 'ENOENT' && !required) return { nonce: null, time: null }
55
+ throw e
56
+ }
57
+ const record = {}
58
+ for (const line of text.split('\n')) {
59
+ if (!line) continue
60
+ const match = /^([a-z_]+)=(.*)$/.exec(line)
61
+ if (!match || Object.hasOwn(record, match[1])) throw new Error('invalid PM launch record')
62
+ record[match[1]] = match[2]
63
+ }
64
+ if (record.metadata_version !== '1' || record.project !== identity.root || record.window !== identity.tmux.window ||
65
+ !/^[A-Za-z0-9._-]+$/.test(record.nonce ?? '') || !Number.isFinite(Date.parse(record.time)) ||
66
+ !['fresh', 'continued'].includes(record.mode) || typeof record.resume_key !== 'string' || !record.resume_key) {
67
+ throw new Error('PM launch record does not belong to this project/window or is unreadable')
68
+ }
69
+ // The record is published after Pi starts. It cannot predate this process by more than the same
70
+ // one-second floor used by the PM spawn proof; an older record belongs to an earlier PM launch.
71
+ const stat = readFileSync(`/proc/${identity.pid}/stat`, 'utf8')
72
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/)
73
+ const btime = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'))?.[1]
74
+ const ticksResult = spawnSync('getconf', ['CLK_TCK'], { encoding: 'utf8' })
75
+ if (ticksResult.error || ticksResult.status !== 0) throw new Error('process clock evidence unavailable')
76
+ const started = (Number(btime) + Number(fields[19]) / Number(ticksResult.stdout.trim())) * 1000
77
+ if (lstatSync(path).mtimeMs + 1000 < started) throw new Error('PM launch record predates this process')
78
+ return { nonce: record.nonce, time: record.time }
79
+ }
80
+
81
+ /** Current directed PM proof plus the late-published launch nonce (which may be absent at session_start). */
82
+ export function resolveRemindIdentity(context, env = process.env, { requireLaunch = false, checkConfiguration = true } = {}) {
83
+ const identity = resolvePMIdentity(context, env)
84
+ if (checkConfiguration) verifyConfiguration(identity)
85
+ const launch = launchRecord(identity, requireLaunch)
86
+ return { ...identity, launchNonce: launch.nonce, launchTime: launch.time }
87
+ }
88
+
89
+ export function sameRemindIdentity(a, b) {
90
+ return isDeepStrictEqual(
91
+ [a.root, a.state, a.config, a.sessionId, a.sessionFile, a.pid, a.starttime, a.tmux, a.launchNonce],
92
+ [b.root, b.state, b.config, b.sessionId, b.sessionFile, b.pid, b.starttime, b.tmux, b.launchNonce],
93
+ )
94
+ }
95
+
96
+ function currentLaunchProof(identity) {
97
+ if (proofPid(join(identity.state, 'pm.pid.spawn'), identity.pid, identity.root)) return true
98
+ return proofPid(join(identity.state, 'pm.pid'), identity.pid, identity.root) &&
99
+ /^(argv|spawn)$/.test(readRegular(join(identity.state, 'pm.pid.proof')).trim())
100
+ }
101
+
102
+ /** Fixed-lock atomic evidence update. A delayed shutdown may remove only its own generation. */
103
+ export function updateRemindCapability(identity, change, { create = true } = {}) {
104
+ safeDirectory(identity.root)
105
+ safeDirectory(identity.state)
106
+ const directory = join(identity.state, 'remind-tool')
107
+ safeDirectory(directory, create)
108
+ const dir = openSync(directory, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW)
109
+ const expected = fstatSync(dir)
110
+ const at = name => `/proc/self/fd/${dir}/${name}`
111
+ let lock, temp
112
+ try {
113
+ lock = regular(at('capability.lock'), C.O_RDWR | C.O_CREAT)
114
+ const held = spawnSync('flock', ['-x', '3'], { stdio: ['ignore', 'ignore', 'ignore', lock] })
115
+ if (held.error || held.status !== 0) throw new Error('capability flock unavailable')
116
+ let current = null
117
+ try { const fd = regular(at('current.json'), C.O_RDONLY); try { current = JSON.parse(readFileSync(fd, 'utf8')) } finally { closeSync(fd) } }
118
+ catch (e) { if (e.code !== 'ENOENT') throw e }
119
+ const next = change(current)
120
+ if (next === undefined) return
121
+ if (next === null) {
122
+ try { unlinkSync(at('current.json')) } catch (e) { if (e.code !== 'ENOENT') throw e }
123
+ } else {
124
+ temp = `.current-${randomUUID()}`
125
+ const fd = regular(at(temp), C.O_WRONLY | C.O_CREAT | C.O_EXCL)
126
+ try { writeFileSync(fd, JSON.stringify(next) + '\n'); fsyncSync(fd) } finally { closeSync(fd) }
127
+ renameSync(at(temp), at('current.json')); temp = null
128
+ }
129
+ safeDirectory(directory)
130
+ const actual = lstatSync(directory)
131
+ if (actual.dev !== expected.dev || actual.ino !== expected.ino) throw new Error('capability directory replaced')
132
+ fsyncSync(dir)
133
+ } finally {
134
+ if (temp) unlinkSync(at(temp))
135
+ if (lock !== undefined) closeSync(lock)
136
+ closeSync(dir)
137
+ }
138
+ }
139
+
140
+ export function publishRemindCapability(identity, { generation, extensionVersion, status, exposure, reason = null }) {
141
+ const record = {
142
+ version: 1,
143
+ at: new Date().toISOString(),
144
+ status,
145
+ exposure,
146
+ reason,
147
+ generation,
148
+ extensionVersion,
149
+ root: identity.root,
150
+ state: identity.state,
151
+ config: identity.config,
152
+ sessionId: identity.sessionId,
153
+ sessionFile: identity.sessionFile,
154
+ pid: identity.pid,
155
+ starttime: identity.starttime,
156
+ cwd: identity.cwd,
157
+ launchNonce: identity.launchNonce,
158
+ launchTime: identity.launchTime,
159
+ tmux: identity.tmux,
160
+ }
161
+ updateRemindCapability(identity, () => record)
162
+ }
163
+
164
+ export function removeRemindCapability(identity, generation) {
165
+ updateRemindCapability(identity, current => current?.generation === generation ? null : undefined, { create: false })
166
+ }
167
+
168
+ /** Doctor reads only this evidence plus live process/tmux/launch proof, never the Reminder snapshot. */
169
+ export function inspectRemindCapability({ root, state, config, session, window, skill }) {
170
+ let disk
171
+ try { disk = remindCapabilityDiskFingerprint(skill) } catch (e) { return { state: 'unknown', reason: `disk:${e.code ?? e.name}` } }
172
+ let runtime
173
+ try { runtime = JSON.parse(readRegular(join(state, 'remind-tool/current.json'))) }
174
+ catch (e) { return { disk, state: 'unknown', reason: `evidence:${e.code ?? e.name}` } }
175
+ const base = { disk, loaded: runtime.extensionVersion, generation: runtime.generation, sessionId: runtime.sessionId, at: runtime.at }
176
+ try {
177
+ if (runtime.version !== 1 || !['registered', 'error', 'hidden'].includes(runtime.status) ||
178
+ runtime.root !== realpathSync(root) || runtime.state !== realpathSync(state) || runtime.config !== realpathSync(config)) {
179
+ throw new Error('mismatched evidence')
180
+ }
181
+ const age = Date.now() - Date.parse(runtime.at)
182
+ if (!Number.isFinite(age) || age < -1000 || age > REMIND_CAPABILITY_TTL_MS) throw new Error('stale evidence')
183
+ if (runtime.extensionVersion !== disk) throw new Error('loaded source differs from disk')
184
+ const life = processIdentity(runtime.pid)
185
+ if (life.dead || life.zombie || !life.starttime || life.starttime !== runtime.starttime || realpathSync(`/proc/${runtime.pid}/cwd`) !== runtime.cwd) {
186
+ throw new Error('dead/reused/foreign process')
187
+ }
188
+ const actual = tmuxEvidence(runtime.tmux.socket, runtime.tmux.pane)
189
+ // A config mismatch makes the generated session/window differ from the live pane by definition.
190
+ // Error evidence still requires the same live process/pane; ready/hidden evidence also matches current config names.
191
+ if (!isDeepStrictEqual(actual, runtime.tmux) || !ancestor(actual.panePid, runtime.pid) ||
192
+ (runtime.status !== 'error' && (actual.session !== session || actual.window !== window))) {
193
+ throw new Error('pane/session changed')
194
+ }
195
+ if (!currentLaunchProof(runtime)) throw new Error('current PM launch proof missing')
196
+ const launch = launchRecord(runtime, true)
197
+ // Pi can publish its first capability record before team up publishes the launch nonce. A null value
198
+ // is adopted only with this same live process/launch proof; a later conflicting nonce is not.
199
+ if (runtime.launchNonce !== null && launch.nonce !== runtime.launchNonce) throw new Error('PM launch nonce changed')
200
+ if (runtime.status === 'error') return { ...base, state: 'error', reason: runtime.reason ?? 'extension bootstrap failed' }
201
+ if (runtime.status === 'hidden') return { ...base, state: 'unknown', reason: runtime.reason ?? 'tool is hidden in the current session' }
202
+ if (runtime.status === 'registered' && runtime.exposure === 'direct') {
203
+ return { ...base, state: 'ready', reason: `extension reported registered/active at ${runtime.at}` }
204
+ }
205
+ return { ...base, state: 'unknown', reason: 'evidence does not report direct registration' }
206
+ } catch (e) { return { ...base, state: 'unknown', reason: e.message } }
207
+ }
208
+
209
+ function authorityArgs(action, params) {
210
+ const args = []
211
+ if (action === 'add') {
212
+ args.push('remind-add', '--source', 'pm-tool')
213
+ if (params.at !== undefined) args.push('--at', String(params.at))
214
+ if (params.after !== undefined) args.push('--after', String(params.after))
215
+ if (params.key !== undefined) args.push('--key', String(params.key))
216
+ if (params.task !== undefined) args.push('--task', String(params.task))
217
+ } else if (action === 'list') {
218
+ args.push('remind-list')
219
+ if (params.all === true) args.push('--all')
220
+ } else if (action === 'show' || action === 'cancel') {
221
+ args.push(`remind-${action}`, '--id', String(params.id ?? ''))
222
+ } else throw new Error(`team_remind: unknown action ${action}`)
223
+ args.push('--json')
224
+ return args
225
+ }
226
+
227
+ /** Invoke the one existing authority; no project/owner/state/recipient field crosses the tool schema. */
228
+ export async function runReminderAuthority({ identity, skill, action, params, signal }) {
229
+ if (!identity || !skill) throw new Error('team_remind: verified PM identity is required')
230
+ let input = Buffer.alloc(0)
231
+ if (action === 'add') {
232
+ if (typeof params.message !== 'string') throw new Error('team_remind: message must be a string')
233
+ input = Buffer.from(params.message, 'utf8')
234
+ if (input.toString('utf8') !== params.message) throw new Error('team_remind: message is not valid UTF-8')
235
+ }
236
+ const script = join(skill, 'scripts/state-authority.mjs')
237
+ const args = [script, '--cli', identity.root, identity.state, ...authorityArgs(action, params)]
238
+ const env = { ...process.env, TEAM_ROOT: identity.root, TEAM_MAIN_ROOT: identity.root,
239
+ TEAM_STATE_DIR: identity.state, TEAM_CONFIG_FILE: identity.config }
240
+ const child = spawn(process.execPath, args, { cwd: identity.root, env, stdio: ['pipe', 'pipe', 'pipe'] })
241
+ const stdout = [], stderr = []
242
+ child.stdout.on('data', chunk => stdout.push(chunk))
243
+ child.stderr.on('data', chunk => stderr.push(chunk))
244
+ const onAbort = () => child.kill('SIGTERM')
245
+ try {
246
+ signal?.addEventListener('abort', onAbort, { once: true })
247
+ child.stdin.end(input)
248
+ const code = await new Promise((resolve, reject) => {
249
+ child.once('error', reject)
250
+ child.once('close', resolve)
251
+ })
252
+ const out = Buffer.concat(stdout).toString('utf8')
253
+ const err = Buffer.concat(stderr).toString('utf8')
254
+ let result
255
+ try { result = JSON.parse(out) } catch { throw new Error(`team_remind authority failed (rc=${code}): ${err || out || 'no result'}`) }
256
+ if (code !== 0 && result.ok !== false) throw new Error(`team_remind authority failed (rc=${code}): ${err || 'no refusal result'}`)
257
+ return result
258
+ } finally {
259
+ signal?.removeEventListener('abort', onAbort)
260
+ }
261
+ }