teamsmith 0.4.6 → 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 (70) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +24 -0
  4. package/skills/teamsmith/SKILL.md +32 -23
  5. package/skills/teamsmith/extension/team-bg.ts +5 -3
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +14 -3
  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 +26 -15
  13. package/skills/teamsmith/references/reminders.md +153 -161
  14. package/skills/teamsmith/references/troubleshooting.md +12 -7
  15. package/skills/teamsmith/references/workflows.md +84 -31
  16. package/skills/teamsmith/scripts/lib/cmd-agents.sh +10 -4
  17. package/skills/teamsmith/scripts/lib/cmd-project.sh +88 -6
  18. package/skills/teamsmith/scripts/lib/cmd-remind.sh +88 -2
  19. package/skills/teamsmith/scripts/lib/cmd-review.sh +42 -4
  20. package/skills/teamsmith/scripts/lib/cmd-watch.sh +48 -11
  21. package/skills/teamsmith/scripts/lib/common.sh +83 -13
  22. package/skills/teamsmith/scripts/panel/panel.js +179 -179
  23. package/skills/teamsmith/scripts/panel/src/data.ts +71 -15
  24. package/skills/teamsmith/scripts/panel/src/layout.ts +20 -8
  25. package/skills/teamsmith/scripts/panel/src/main.tsx +83 -21
  26. package/skills/teamsmith/scripts/remind-capability.mjs +261 -0
  27. package/skills/teamsmith/scripts/remind-store.mjs +55 -24
  28. package/skills/teamsmith/scripts/remind-tick.mjs +5 -2
  29. package/skills/teamsmith/scripts/reply-capture.mjs +8 -9
  30. package/skills/teamsmith/scripts/state-authority.mjs +72 -6
  31. package/skills/teamsmith/scripts/team +1 -0
  32. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +11 -8
  33. package/skills/teamsmith/templates/DECISIONS.md.tmpl +2 -2
  34. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +3 -3
  35. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +19 -14
  36. package/skills/teamsmith/templates/memory-seed.md.tmpl +2 -2
  37. package/skills/teamsmith/templates/pm-prompt.md.tmpl +31 -19
  38. package/skills/teamsmith/templates/report.md.tmpl +33 -0
  39. package/skills/teamsmith/tests/bg-ledger-harness.mjs +217 -33
  40. package/skills/teamsmith/tests/bg-ledger.sh +24 -10
  41. package/skills/teamsmith/tests/checkout-shape-probe.sh +7 -6
  42. package/skills/teamsmith/tests/fixtures/remind-adversarial-delay.ts +27 -0
  43. package/skills/teamsmith/tests/fixtures/remind-tool-provider.ts +65 -0
  44. package/skills/teamsmith/tests/help-surface.sh +3 -5
  45. package/skills/teamsmith/tests/isolation-ledger.sh +6 -2
  46. package/skills/teamsmith/tests/key-replies-ui.sh +53 -0
  47. package/skills/teamsmith/tests/key-replies.sh +307 -106
  48. package/skills/teamsmith/tests/lib/routes-pages.sh +243 -0
  49. package/skills/teamsmith/tests/loop-inventory.tsv +1 -0
  50. package/skills/teamsmith/tests/panel-b3-stub.sh +9 -2
  51. package/skills/teamsmith/tests/remind-adversarial-faults.mjs +163 -0
  52. package/skills/teamsmith/tests/remind-adversarial-faults.sh +26 -0
  53. package/skills/teamsmith/tests/remind-adversarial-real.sh +27 -0
  54. package/skills/teamsmith/tests/remind-cli.sh +108 -3
  55. package/skills/teamsmith/tests/remind-delivery-node.mjs +13 -0
  56. package/skills/teamsmith/tests/remind-delivery.sh +123 -35
  57. package/skills/teamsmith/tests/remind-lifecycle.sh +197 -0
  58. package/skills/teamsmith/tests/remind-pulse.sh +199 -0
  59. package/skills/teamsmith/tests/remind-recovery-real.sh +5 -0
  60. package/skills/teamsmith/tests/remind-recovery-unit.sh +118 -0
  61. package/skills/teamsmith/tests/remind-tool-node.mjs +159 -0
  62. package/skills/teamsmith/tests/remind-tool-real.mjs +754 -0
  63. package/skills/teamsmith/tests/remind-tool-real.sh +5 -0
  64. package/skills/teamsmith/tests/reply-capture-real.mjs +93 -2
  65. package/skills/teamsmith/tests/routes.sh +213 -293
  66. package/skills/teamsmith/tests/section-paths.tsv +10 -8
  67. package/skills/teamsmith/tests/smoke.sh +484 -28
  68. package/skills/teamsmith/tests/state-authority.sh +152 -8
  69. package/skills/teamsmith-init/SKILL.md +5 -5
  70. 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)
@@ -693,13 +703,15 @@ export function runRemindTick(
693
703
  pulseStartedAt: string,
694
704
  tickLog: string,
695
705
  timeoutMs = 30000,
706
+ children?: Set<ReturnType<typeof spawn>>,
696
707
  ): Promise<{ ok: boolean; output: string }> {
697
708
  return new Promise((resolve) => {
698
709
  let child: ReturnType<typeof spawn>
699
710
  try {
700
711
  child = spawn(process.execPath, [
701
- script, '--root', root, '--state-dir', stateDir, '--pulse-started', pulseStartedAt, '--quiet',
702
- ], { cwd: root, env: cleanIdentityEnv(), stdio: ['ignore', 'pipe', 'pipe'] })
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)
703
715
  } catch (e) {
704
716
  resolve({ ok: false, output: (e as Error).message })
705
717
  return
@@ -710,19 +722,63 @@ export function runRemindTick(
710
722
  if (settled) return
711
723
  settled = true
712
724
  clearTimeout(timer)
713
- // Successful quiet ticks say nothing: only a failure (or an admission line) earns a log line.
714
- if (out.trim()) {
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()) {
715
734
  try { appendFileSync(tickLog, `${new Date().toISOString()} remind-tick: ${out}`) } catch { /* a log that cannot be written must not kill the panel */ }
716
735
  }
717
736
  resolve({ ok, output: out })
718
737
  }
719
738
  const timer = setTimeout(() => {
720
- try {
721
- child.kill('SIGKILL')
722
- } catch {
723
- /* already gone */
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 */ }
724
777
  }
725
- done(false)
778
+ resolve({ ok, output: out })
779
+ }
780
+ const timer = setTimeout(() => {
781
+ signalPulseChild(child, 'SIGKILL')
726
782
  }, timeoutMs)
727
783
  child.stdout?.on('data', (d: Buffer) => { out += String(d) })
728
784
  child.stderr?.on('data', (d: Buffer) => { out += String(d) })
@@ -1343,13 +1343,19 @@ function replyRowLabel(e: ReplyEntry): string {
1343
1343
  return e.available ? `#${e.no} ${e.title}` : ''
1344
1344
  }
1345
1345
 
1346
- /** Reader's local clock, `MM-DD HH:MM`: when a reply was published, in the list itself. */
1347
- function replyTimeLabel(at: string | undefined): string {
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
1348
  if (!at) return ''
1349
1349
  const when = new Date(at)
1350
1350
  if (Number.isNaN(when.getTime())) return ''
1351
1351
  const pad = (n: number): string => String(n).padStart(2, '0')
1352
- return `${pad(when.getMonth() + 1)}-${pad(when.getDate())} ${pad(when.getHours())}:${pad(when.getMinutes())}`
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}`
1353
1359
  }
1354
1360
 
1355
1361
  /** The nav row of page 5: Older / Newer / `r` (the same actions `←`/`→` and `r` fire). */
@@ -1423,12 +1429,13 @@ function replyListBlock(ctx: Ctx): Block | null {
1423
1429
  const active = i === focus
1424
1430
  const cursor = active ? s.settingsCursor : ' '
1425
1431
  const head = ` ${cursor} `
1432
+ const at = e.available ? replyTimeLabel(e.at) : ''
1426
1433
  const bodyLine: Line = e.available
1427
1434
  ? ln(
1428
1435
  seg(head, 'accent'),
1429
1436
  seg(replyRowLabel(e), active ? 'selected' : 'text'),
1430
1437
  seg(` · ${e.from}`, 'dim'),
1431
- ...(replyTimeLabel(e.at) ? [seg(` · ${replyTimeLabel(e.at)}`, 'dim')] : []),
1438
+ ...(at ? [seg(` · ${at}`, 'dim')] : []),
1432
1439
  )
1433
1440
  : ln(
1434
1441
  seg(head, 'accent'),
@@ -1485,9 +1492,11 @@ function replyViewerBlock(ctx: Ctx): Block | null {
1485
1492
  if (data.available === false) {
1486
1493
  return build([nav, { line: truncLine(ln(seg(` ${s.replyBodyMissing}`, 'warn')), innerW) }, backLine], { no, total: 0, visible: 0, offset: 0 })
1487
1494
  }
1495
+ const at = replyTimeLabel(data.at, true)
1496
+ const declared = fill(at ? s.replyDeclared : s.replyDeclaredShort, { from: data.from, at })
1488
1497
  const meta: PlacedLine[] = [
1489
1498
  { line: truncLine(ln(seg(` ${data.title}`, 'heading')), innerW) },
1490
- { line: truncLine(ln(seg(` ${fill(s.replyDeclared, { from: data.from, at: data.at })}`, 'dim')), innerW) },
1499
+ { line: truncLine(ln(seg(` ${declared}`, 'dim')), innerW) },
1491
1500
  { line: truncLine(ln(seg(` ${s.replyBodyHint} · ${data.bytes} B`, 'dim')), innerW) },
1492
1501
  ]
1493
1502
  const doc = markdownMemo(`reply:${no}`, data.display_text ?? '', innerW)
@@ -1523,9 +1532,12 @@ function replySummaryBlock(ctx: Ctx): Block | null {
1523
1532
  line.push(seg(text, 'text'))
1524
1533
  hits.push({ start: x, end: x + dispWidth(text), action: { kind: 'reply-open-latest', no: entry.no } })
1525
1534
  x += dispWidth(text)
1526
- const at = ` · ${entry.at}`
1527
- line.push(seg(at, 'dim'))
1528
- 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
+ }
1529
1541
  } else if (d.state === 'empty') {
1530
1542
  line.push(seg(s.replyEmpty, 'dim'))
1531
1543
  } else {
@@ -42,7 +42,9 @@ import {
42
42
  loadPanelData,
43
43
  panelDirOf,
44
44
  runRemindTick,
45
+ runReminderRecovery,
45
46
  runTick,
47
+ signalPulseChild,
46
48
  type BlockName,
47
49
  } from './data.js'
48
50
  import type { DataOptions, DataResult, PanelCache } from './data.js'
@@ -268,9 +270,17 @@ if (mode === 'palette') {
268
270
  process.exit(0)
269
271
  }
270
272
 
271
- // ---------------------------------------------------------------- the tick loop (owned here)
273
+ // ---------------------------------------------------------------- Pulse scheduling (one patrol + one recovery)
272
274
  let lastTick = 0
273
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
274
284
 
275
285
  function tickDue(): boolean {
276
286
  if (noPulse || tickEvery <= 0) return false
@@ -282,16 +292,36 @@ function tickDue(): boolean {
282
292
  return false
283
293
  }
284
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
+
285
317
  async function runTickIfDue(): Promise<void> {
286
- if (!tickDue()) return
287
- if (!teamCli) return
288
- await runTick(teamCli, root, tickLog)
318
+ if (!tickDue() || !teamCli || patrolRun || recoveryRun) return
319
+ schedulePatrol()
320
+ if (patrolRun) await patrolRun
289
321
  }
290
322
 
291
- // ---------------------------------------------------------------- the lightweight Reminder due tick
292
- // agent-self-reminder 4.1: apart from (and much more often than) the full patrol, both pulse shapes own a
293
- // ~10s due check. It reads one bounded snapshot and only takes the authority lock when something is due;
294
- // it never scans the project, never starts the patrol and never calls a model.
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.
295
325
  const remindEvery = Math.max(1, Number(process.env.TEAM_REMIND_TICK_SECS ?? 10) || 10)
296
326
  const remindStartedAt = new Date().toISOString()
297
327
  const remindScript = teamCli ? join(dirname(teamCli), 'remind-tick.mjs') : ''
@@ -308,8 +338,33 @@ function remindDue(): boolean {
308
338
  }
309
339
 
310
340
  async function runRemindIfDue(): Promise<void> {
311
- if (!remindDue()) return
312
- await runRemindTick(remindScript, root, stateDir, remindStartedAt, tickLog)
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
313
368
  }
314
369
 
315
370
  function frameOf(res: DataResult, activity: boolean, scroll?: number): FrameInput {
@@ -418,11 +473,14 @@ async function main(): Promise<void> {
418
473
 
419
474
  if (mode === 'headless') {
420
475
  // The tick loop with no renderer. `team monitor --headless` is the bash loop (lock + drift
421
- // 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) })
422
480
  for (;;) {
423
- await runTickIfDue()
424
- await runRemindIfDue()
425
- sleepSync(Math.max(1, tickEvery || refresh) * 1000)
481
+ void runTickIfDue()
482
+ void runRemindIfDue()
483
+ await new Promise(resolve => setTimeout(resolve, remindEvery * 1000))
426
484
  }
427
485
  }
428
486
 
@@ -1002,18 +1060,22 @@ async function main(): Promise<void> {
1002
1060
  }
1003
1061
  }
1004
1062
  process.on('exit', restoreTerminal)
1005
- process.on('SIGTERM', () => {
1063
+ let pulseShutdown = false
1064
+ const shutdownPulse = async (code: number): Promise<void> => {
1065
+ if (pulseShutdown) return
1066
+ pulseShutdown = true
1006
1067
  restoreTerminal()
1007
- process.exit(143)
1008
- })
1009
- process.on('SIGHUP', () => {
1010
- restoreTerminal()
1011
- process.exit(129)
1012
- })
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) })
1013
1074
 
1014
1075
  if (once) await runTickIfDue()
1015
1076
  await app.waitUntilExit()
1016
1077
  restoreTerminal()
1078
+ await stopPulseChildren()
1017
1079
  cache.dispose()
1018
1080
  process.exit(0)
1019
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
+ }