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
@@ -23,8 +23,6 @@ const PHASES = new Set(['scheduled', 'queued', 'intent', 'observed', 'unknown',
23
23
  // A batch is the one durable delivery decision: at most one is outstanding until it is observed or an
24
24
  // operator acknowledges it, and its single right is what may clear one Standby generation.
25
25
  const BATCH_PHASES = new Set(['intent', 'observed', 'unknown', 'resolved']);
26
- const BATCH_LIMIT = 8; // design: at most eight Reminders in one message
27
- const BATCH_SPACING_MS = 5000; // design: at most one batch submission per five seconds
28
26
  const OBSERVE_DEADLINE_MS = 60000; // after intent, no correlated event within 60s = unknown, never a resend
29
27
  const OVERDUE_LAG_MS = 30000; // normal polling delay is not overdue; 30s of admission lag is
30
28
  // Terminal = the outcome is known and the reminder can no longer fire. A key survives `unknown` (a
@@ -234,13 +232,15 @@ function admitReminders(snapshot, request, nowMs) {
234
232
  ok: true, now: iso(nowMs),
235
233
  admitted, overdue, swept,
236
234
  queue: snapshot.reminders.filter(record => record.phase === 'queued').length,
235
+ queuedIds: snapshot.reminders.filter(record => record.phase === 'queued')
236
+ .sort((a, b) => ((a.queueSeq ?? 0) - (b.queueSeq ?? 0)) || (a.seq - b.seq)).map(record => record.id),
237
237
  outstanding: outstandingBatch(snapshot)?.id ?? null,
238
238
  };
239
239
  }
240
240
 
241
- // 3.1: freeze up to eight queued Reminders into ONE batch and bind the current Standby generation, before
242
- // any Pi call. Returns the whole payload so the caller sends exactly what was frozen (full text, byte for
243
- // byte) and nothing else.
241
+ // 3.1: freeze every currently queued Reminder into ONE batch and bind the current Standby generation,
242
+ // before any Pi call. Returns the whole payload so the caller sends exactly what was frozen (full text,
243
+ // byte for byte) and nothing else. The next batch is eligible as soon as this outcome settles.
244
244
  function intentBatch(snapshot, request, nowMs) {
245
245
  const swept = sweepStaleIntents(snapshot, nowMs);
246
246
  const outstanding = outstandingBatch(snapshot);
@@ -252,14 +252,9 @@ function intentBatch(snapshot, request, nowMs) {
252
252
  : `batch ${outstanding.id} is already in flight (intent at ${outstanding.intentAt})`,
253
253
  };
254
254
  }
255
- const last = snapshot.batches[snapshot.batches.length - 1];
256
- if (last && Number.isFinite(msOf(last.intentAt)) && nowMs - msOf(last.intentAt) < BATCH_SPACING_MS) {
257
- return { ok: true, action: 'spacing', now: iso(nowMs), retryAt: iso(msOf(last.intentAt) + BATCH_SPACING_MS), swept };
258
- }
259
255
  const queued = snapshot.reminders
260
256
  .filter(record => record.phase === 'queued')
261
- .sort((a, b) => ((a.queueSeq ?? 0) - (b.queueSeq ?? 0)) || (a.seq - b.seq))
262
- .slice(0, BATCH_LIMIT);
257
+ .sort((a, b) => ((a.queueSeq ?? 0) - (b.queueSeq ?? 0)) || (a.seq - b.seq));
263
258
  if (!queued.length) return { ok: true, action: 'idle', now: iso(nowMs), swept };
264
259
  const session = typeof request.session === 'string' ? request.session.trim() : '';
265
260
  if (!session) return { ok: false, refusal: 'bad-session', reason: 'the batch intent needs the verified PM session id (which session may observe the wake)' };
@@ -312,7 +307,13 @@ function observeBatch(snapshot, request, nowMs) {
312
307
  const batch = findBatch(snapshot, id);
313
308
  if (!batch) {
314
309
  const parsed = parseBatchId(id, snapshot.project.id);
315
- return { ok: false, refusal: parsed ? 'history-pruned' : 'unknown-batch', reason: `'${id}' is not a batch of this project` };
310
+ if (!parsed || parsed.seq >= snapshot.sequences.batch) {
311
+ return { ok: false, refusal: 'unknown-batch', reason: `'${id}' is not a batch issued by this project` };
312
+ }
313
+ return {
314
+ ok: false, refusal: 'history-pruned',
315
+ reason: `'${id}' left the retained batch history (issued high-water ${snapshot.sequences.batch - 1}); it cannot be reopened or resent`,
316
+ };
316
317
  }
317
318
  if (typeof request.nonce !== 'string' || request.nonce !== batch.nonce) {
318
319
  return { ok: false, refusal: 'nonce-mismatch', reason: `the observed message does not carry the nonce of ${batch.id} (identity unknown; no right consumed)` };
@@ -321,6 +322,13 @@ function observeBatch(snapshot, request, nowMs) {
321
322
  if (!session || batch.target?.session !== session) {
322
323
  return { ok: false, refusal: 'session-mismatch', reason: `${batch.id} was frozen for session ${batch.target?.session ?? '(none)'}, not '${session || '(none)'}'` };
323
324
  }
325
+ // The batch id and nonce alone do not identify the whole frozen message: a same-named custom event
326
+ // carrying a different member list is not the observation of this batch. Check the durable member
327
+ // order inside the same authority transaction so this also holds for a late event after a restart.
328
+ if (!Array.isArray(request.members) || request.members.length !== batch.members.length ||
329
+ request.members.some((id, index) => id !== batch.members[index])) {
330
+ return { ok: false, refusal: 'member-mismatch', reason: `the observed message does not carry the exact frozen member identities of ${batch.id}; no right consumed` };
331
+ }
324
332
  if (batch.phase === 'resolved') return { ok: false, refusal: 'already-resolved', reason: `${batch.id} was acknowledged as unknown; it cannot be reopened` };
325
333
  if (batch.right === 'spent' || batch.phase === 'observed') {
326
334
  return { ok: true, outcome: 'duplicate', now: iso(nowMs), batch: batch.id, right: batch.right, reason: 'this batch already spent its one right; no second off' };
@@ -520,7 +528,6 @@ export function validateReminders(snapshot, failWith) {
520
528
  if (batch.rightSpentBy !== null && !['wake', 'resolve'].includes(batch.rightSpentBy)) bad(`batch ${batch.id} has an unreadable right holder: ${batch.rightSpentBy}`);
521
529
  if (!Number.isSafeInteger(batch.attempts) || batch.attempts < 1) bad(`batch ${batch.id} has an unreadable attempt count`);
522
530
  if (!Array.isArray(batch.members) || !batch.members.length) bad(`batch ${batch.id} has no members`);
523
- if (batch.members.length > BATCH_LIMIT) bad(`batch ${batch.id} carries more than ${BATCH_LIMIT} members`);
524
531
  for (const mid of batch.members) {
525
532
  const record = snapshot.reminders.find(item => item.id === mid);
526
533
  if (!record) bad(`batch ${batch.id} names a member that is not in the snapshot: ${mid}`);
@@ -555,26 +562,50 @@ function parseId(id, projectId) {
555
562
  function endedMs(record) { return msOf(record.endedAt ?? record.createdAt); }
556
563
 
557
564
  function pruneHistory(snapshot, nowMs) {
558
- const terminal = snapshot.reminders.filter(record => isTerminal(record.phase));
559
- const ranked = terminal.slice().sort((a, b) => (endedMs(b) - endedMs(a)) || (b.seq - a.seq));
565
+ // A retained batch needs every member for validation and late-event correlation, so batches and
566
+ // their terminal members compact as one unit. Intent/unknown batches and every unspent right stay.
567
+ const terminalBatches = snapshot.batches.filter(batch =>
568
+ (batch.phase === 'observed' || batch.phase === 'resolved') && batch.right === 'spent' &&
569
+ batch.members.every(id => {
570
+ const record = snapshot.reminders.find(item => item.id === id);
571
+ return record && isTerminal(record.phase);
572
+ }));
573
+ const batchEndedMs = batch => msOf(batch.observedAt ?? batch.resolvedAt ?? batch.intentAt);
574
+ const rankedBatches = terminalBatches.slice().sort((a, b) => (batchEndedMs(b) - batchEndedMs(a)) || (b.seq - a.seq));
575
+ const keepBatches = new Set();
576
+ for (let i = 0; i < rankedBatches.length; i++) {
577
+ if (i < TERMINAL_KEEP && nowMs - batchEndedMs(rankedBatches[i]) <= RETENTION_MS) keepBatches.add(rankedBatches[i].id);
578
+ }
579
+ const droppedBatches = terminalBatches.filter(batch => !keepBatches.has(batch.id));
580
+ const droppedBatchIds = new Set(droppedBatches.map(batch => batch.id));
581
+
582
+ const standalone = snapshot.reminders.filter(record => isTerminal(record.phase) && !record.batchId);
583
+ const ranked = standalone.slice().sort((a, b) => (endedMs(b) - endedMs(a)) || (b.seq - a.seq));
560
584
  const keep = new Set();
561
585
  for (let i = 0; i < ranked.length; i++) {
562
586
  if (i < TERMINAL_KEEP && nowMs - endedMs(ranked[i]) <= RETENTION_MS) keep.add(ranked[i].id);
563
587
  }
564
- const dropped = terminal.filter(record => !keep.has(record.id));
565
- if (dropped.length) {
566
- const ids = new Set(dropped.map(record => record.id));
567
- snapshot.reminders = snapshot.reminders.filter(record => !ids.has(record.id));
568
- snapshot.pruned += dropped.length;
588
+ const droppedStandalone = standalone.filter(record => !keep.has(record.id));
589
+ const droppedStandaloneIds = new Set(droppedStandalone.map(record => record.id));
590
+ const droppedCount = droppedStandalone.length + droppedBatches.reduce((n, batch) => n + batch.members.length, 0);
591
+ if (droppedCount) {
592
+ const droppedIds = [
593
+ ...droppedStandalone,
594
+ ...droppedBatches.flatMap(batch => batch.members.map(id => snapshot.reminders.find(record => record.id === id)).filter(Boolean)),
595
+ ];
596
+ snapshot.reminders = snapshot.reminders.filter(record =>
597
+ record.batchId ? !droppedBatchIds.has(record.batchId) : !droppedStandaloneIds.has(record.id));
598
+ snapshot.batches = snapshot.batches.filter(batch => !droppedBatchIds.has(batch.id));
599
+ snapshot.pruned += droppedCount;
569
600
  snapshot.audit.push({
570
- at: iso(nowMs), op: 'retention-prune', count: dropped.length,
571
- ids: dropped.slice().sort((a, b) => b.seq - a.seq).slice(0, 20).map(record => record.id),
572
- detail: `kept the newest ${TERMINAL_KEEP} terminal outcomes inside 30 days; the sequence high-water never moves back`,
601
+ at: iso(nowMs), op: 'retention-prune', count: droppedCount,
602
+ ids: droppedIds.sort((a, b) => b.seq - a.seq).slice(0, 20).map(record => record.id),
603
+ detail: `kept the newest ${TERMINAL_KEEP} terminal outcomes inside 30 days; active/unknown rights stay and sequence high-water never moves back`,
573
604
  });
574
605
  }
575
606
  const audit = snapshot.audit.filter(entry => nowMs - msOf(entry.at) <= RETENTION_MS);
576
607
  snapshot.audit = audit.length > AUDIT_KEEP ? audit.slice(audit.length - AUDIT_KEEP) : audit;
577
- return dropped.length;
608
+ return droppedCount;
578
609
  }
579
610
 
580
611
  function note(snapshot, nowMs, op, fields) {
@@ -70,13 +70,14 @@ async function main() {
70
70
  const context = { cwd: opts.root, mainRoot: opts.root, stateRoot: opts.stateDir };
71
71
  const seen = await peek(context);
72
72
  if (!seen.pinned) {
73
- if (opts.json) process.stdout.write(`${JSON.stringify({ ok: true, pinned: false, admitted: [] })}\n`);
73
+ if (opts.json) process.stdout.write(`${JSON.stringify({ ok: true, pinned: false, admitted: [], recoveryRequired: false, recoveryIds: [] })}\n`);
74
74
  return;
75
75
  }
76
76
  const due = seen.reminders.due.length;
77
77
  const stale = seen.reminders.staleIntent.length;
78
78
  if (!due && !stale) {
79
- if (opts.json) process.stdout.write(`${JSON.stringify({ ok: true, pinned: true, admitted: [], swept: [] })}\n`);
79
+ const recoveryRequired = seen.reminders.queued.length > 0 && !seen.outstanding;
80
+ if (opts.json) process.stdout.write(`${JSON.stringify({ ok: true, pinned: true, admitted: [], swept: [], queue: seen.reminders.queued.length, recoveryRequired, recoveryIds: recoveryRequired ? seen.reminders.queued : [] })}\n`);
80
81
  return;
81
82
  }
82
83
  const result = await request({ ...context, stateRoot: seen.stateRoot }, {
@@ -89,6 +90,8 @@ async function main() {
89
90
  log(seen.stateRoot, `admit n=${admitted.length} overdue=${(result.overdue ?? []).length} ` +
90
91
  `ids=${admitted.join('|') || '-'} unknown=${swept.join('|') || '-'} queue=${result.queue}`);
91
92
  }
93
+ result.recoveryRequired = (result.queue ?? 0) > 0 && !result.outstanding;
94
+ result.recoveryIds = result.recoveryRequired ? (result.queuedIds ?? []) : [];
92
95
  if (opts.json) process.stdout.write(`${JSON.stringify(result)}\n`);
93
96
  else if (!opts.quiet && admitted.length) {
94
97
  process.stdout.write(`remind: 到点入队 ${admitted.length} 条(${admitted.join(' ')})\n`);
@@ -520,12 +520,12 @@ function command(bin, args, cwd) {
520
520
  if (result.error || result.status !== 0) throw new Error(`${basename(bin)} evidence unavailable`)
521
521
  return result.stdout.trim()
522
522
  }
523
- function readRegular(path) {
523
+ export function readRegular(path) {
524
524
  safeDirectory(dirname(path))
525
525
  const fd = regular(path, C.O_RDONLY)
526
526
  try { return readFileSync(fd, 'utf8') } finally { closeSync(fd) }
527
527
  }
528
- function ancestor(older, younger) {
528
+ export function ancestor(older, younger) {
529
529
  const seen = new Set()
530
530
  while (younger > 0 && !seen.has(younger)) {
531
531
  if (older === younger) return true
@@ -534,7 +534,7 @@ function ancestor(older, younger) {
534
534
  }
535
535
  return false
536
536
  }
537
- function proofPid(path, pid, root) {
537
+ export function proofPid(path, pid, root) {
538
538
  try {
539
539
  const raw = readRegular(path).trim()
540
540
  if (!/^\d+$/.test(raw) || !ancestor(Number(raw), pid)) return false
@@ -549,7 +549,7 @@ function proofPid(path, pid, root) {
549
549
  throw e
550
550
  }
551
551
  }
552
- function tmuxEvidence(socket, pane) {
552
+ export function tmuxEvidence(socket, pane) {
553
553
  const fields = command('tmux', ['-S', socket, 'display-message', '-p', '-t', pane,
554
554
  '#{socket_path}\t#{pid}\t#{pane_id}\t#{pane_pid}\t#{session_name}\t#{window_name}\t#{pane_current_path}']).split('\t')
555
555
  if (fields.length !== 7) throw new Error('incomplete tmux evidence')
@@ -568,7 +568,7 @@ export function resolvePMIdentity(context, env = process.env) {
568
568
  if (!env.TEAM_STATE_DIR || !env.TEAM_CONFIG_FILE || !env.TEAM_PM_WINDOW || !env.TEAM_SESSION) throw new Error('missing directed PM launch environment')
569
569
  const state = safeDirectory(env.TEAM_STATE_DIR), config = resolve(env.TEAM_CONFIG_FILE)
570
570
  if (config !== env.TEAM_CONFIG_FILE || realpathSync(config) !== config) throw new Error('noncanonical PM config')
571
- const configBytes = readRegular(config), configStat = lstatSync(config)
571
+ readRegular(config) // The path, type and owner remain capture boundaries; its contents do not.
572
572
  if (!context.sessionId || !context.sessionFile || !isAbsolute(context.sessionFile)) throw new Error('no persistent session identity')
573
573
  const sessionFile = join(safeDirectory(dirname(context.sessionFile)), basename(context.sessionFile))
574
574
  if (sessionFile !== context.sessionFile) throw new Error('noncanonical session path')
@@ -584,8 +584,7 @@ export function resolvePMIdentity(context, env = process.env) {
584
584
  let proof = proofPid(join(state, 'pm.pid.spawn'), process.pid, root) ? 'spawn' : ''
585
585
  if (!proof && proofPid(join(state, 'pm.pid'), process.pid, root) && /^(argv|spawn)$/.test(readRegular(join(state, 'pm.pid.proof')).trim())) proof = 'final'
586
586
  if (!proof) throw new Error('no current PM launch proof')
587
- return { root, state, config, configHash: digest(configBytes), configDev: configStat.dev, configIno: configStat.ino,
588
- sessionId: context.sessionId, sessionFile, pid: process.pid, starttime: life.starttime, cwd, tmux }
587
+ return { root, state, config, sessionId: context.sessionId, sessionFile, pid: process.pid, starttime: life.starttime, cwd, tmux }
589
588
  }
590
589
 
591
590
  /** Registry is process evidence, not a second source index. Fixed lock and atomic replacement match journal discipline. */
@@ -637,8 +636,8 @@ export function inspectRuntime({ root, state, config, session, window, skill })
637
636
  catch (e) { return { disk, state: 'unknown', reason: `registration:${e.code ?? e.name}` } }
638
637
  const base = { disk, loaded: runtime.fingerprint, generation: runtime.generation, extension: runtime.extension, sessionId: runtime.sessionId }
639
638
  try {
640
- if (runtime.root !== realpathSync(root) || runtime.state !== realpathSync(state) || runtime.config !== realpathSync(config) ||
641
- runtime.configHash !== digest(readRegular(config))) throw new Error('identity/config changed')
639
+ if (runtime.root !== realpathSync(root) || runtime.state !== realpathSync(state) || runtime.config !== realpathSync(config)) throw new Error('identity/config changed')
640
+ readRegular(config) // Keep the doctor's symlink and ownership checks without comparing configuration contents.
642
641
  const life = processIdentity(runtime.pid)
643
642
  if (life.dead || life.zombie || !life.starttime || life.starttime !== runtime.starttime || realpathSync(`/proc/${runtime.pid}/cwd`) !== runtime.cwd) throw new Error('dead/reused/foreign process')
644
643
  const actual = tmuxEvidence(runtime.tmux.socket, runtime.tmux.pane)
@@ -47,6 +47,32 @@ const STANDBY_READ_OPS = new Set(['read', 'standby-read']);
47
47
 
48
48
  const fail = message => { throw new Error(message); };
49
49
 
50
+ // One resolver feeds `team paths`, `team doctor` and every real transaction. Returning an absolute
51
+ // executable also makes the spawn below use exactly the binary that the diagnostics displayed.
52
+ export function flockResolution(env = process.env) {
53
+ const pathValue = env.PATH ?? '/usr/bin:/bin';
54
+ let candidate = null;
55
+ for (const entry of pathValue.split(':')) {
56
+ const file = path.resolve(entry || '.', 'flock');
57
+ try {
58
+ const stat = fs.statSync(file);
59
+ candidate ??= file;
60
+ fs.accessSync(file, fs.constants.X_OK);
61
+ if (stat.isFile()) return { status: 'ok', runner: file, candidate: file, detail: '' };
62
+ } catch { /* remember the first unusable match and keep looking for a usable one */ }
63
+ }
64
+ return candidate
65
+ ? { status: 'unusable', runner: '', candidate, detail: 'not an executable regular file' }
66
+ : { status: 'missing', runner: '', candidate: '', detail: 'no executable flock on PATH' };
67
+ }
68
+
69
+ function flockUnavailable(resolution) {
70
+ const repair = 'install util-linux (which provides flock), or put an executable flock on PATH; no unlocked fallback';
71
+ return resolution.status === 'unusable'
72
+ ? `flock unavailable: ${resolution.candidate} is not an executable regular file; fix its permissions or ${repair}`
73
+ : `flock unavailable: no executable flock on PATH; ${repair}`;
74
+ }
75
+
50
76
  // The project a working directory belongs to -- the same git rule as common.sh's team_dir_roots, so a
51
77
  // Node caller (Pulse, Pi) cannot be talked out of its own project by an inherited variable.
52
78
  function projectOf(cwd) {
@@ -438,9 +464,11 @@ function transaction(main, state, request) {
438
464
  function flock(lock, args, input) {
439
465
  return new Promise((resolve, reject) => {
440
466
  const startedAt = Date.now();
441
- const child = spawn('flock', ['-x', '-w', String(LOCK_WAIT_SECONDS), '-E', String(LOCK_CONFLICT_EXIT), lock,
467
+ const resolution = flockResolution();
468
+ if (!resolution.runner) { reject(new Error(flockUnavailable(resolution))); return; }
469
+ const child = spawn(resolution.runner, ['-x', '-w', String(LOCK_WAIT_SECONDS), '-E', String(LOCK_CONFLICT_EXIT), lock,
442
470
  process.execPath, SELF, ...args],
443
- { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
471
+ { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], env: { ...process.env, LC_ALL: 'C' } });
444
472
  const out = [];
445
473
  const err = [];
446
474
  child.stdout.on('data', chunk => out.push(chunk));
@@ -450,6 +478,10 @@ function flock(lock, args, input) {
450
478
  child.on('close', (code, signal) => {
451
479
  const stderr = Buffer.concat(err).toString().trim();
452
480
  if (code !== 0) {
481
+ if (/^flock:/m.test(stderr)) {
482
+ return reject(new Error(`exclusive flock failed at ${lock}: ${stderr}; ` +
483
+ 'check that this filesystem supports exclusive locks; no state was written and there is no unlocked fallback'));
484
+ }
453
485
  if (stderr) return reject(new Error(stderr));
454
486
  // Only a conflict exit that actually used up the window is a timeout. Anything else (a helper
455
487
  // killed or crashed mid-transaction) is reported as what it is, with its status.
@@ -616,7 +648,7 @@ const REMIND_FLAGS = {
616
648
  'remind-cancel': new Set(['id']),
617
649
  'remind-admit': new Set(['pulse-started']),
618
650
  'remind-intent': new Set(['session', 'pid']),
619
- 'remind-observe': new Set(['id', 'nonce', 'session']),
651
+ 'remind-observe': new Set(['id', 'nonce', 'session', 'members']),
620
652
  'remind-fail': new Set(['id', 'nonce', 'reason']),
621
653
  'remind-resolve': new Set(['id', 'ack-unknown']),
622
654
  };
@@ -626,7 +658,7 @@ const REMIND_FLAGS = {
626
658
  const REMIND_FIELD = { 'pulse-started': 'pulseStartedAt', 'ack-unknown': 'ack' };
627
659
  const REMIND_REQUIRED = {
628
660
  'remind-intent': ['session'],
629
- 'remind-observe': ['id', 'nonce', 'session'],
661
+ 'remind-observe': ['id', 'nonce', 'session', 'members'],
630
662
  'remind-fail': ['id', 'nonce'],
631
663
  'remind-resolve': ['id'],
632
664
  };
@@ -638,9 +670,18 @@ function parseRemindFlags(op, flags) {
638
670
  if (!allowed.has(name)) fail(`${op} does not accept --${name}`);
639
671
  request[REMIND_FIELD[name] ?? name] = flags[name];
640
672
  }
673
+ if (op === 'remind-observe' && request.members !== undefined) {
674
+ try {
675
+ const parsed = JSON.parse(String(request.members));
676
+ request.members = Array.isArray(parsed)
677
+ ? parsed.map(member => typeof member === 'string' ? member : String(member?.id ?? ''))
678
+ : null;
679
+ } catch { request.members = null; }
680
+ if (!request.members) fail('remind-observe --members must be a JSON array of the frozen Reminder ids');
681
+ }
641
682
  for (const name of REMIND_REQUIRED[op] ?? []) {
642
683
  const field = REMIND_FIELD[name] ?? name;
643
- if (request[field] === undefined || request[field] === '') fail(`${op} needs --${name}`);
684
+ if (request[field] === undefined || request[field] === '' || request[field] === null) fail(`${op} needs --${name}`);
644
685
  }
645
686
  if (op === 'remind-intent' && request.pid !== undefined) {
646
687
  const pid = Number(request.pid);
@@ -686,6 +727,30 @@ function renderStandby(op, result) {
686
727
 
687
728
  async function main(argv) {
688
729
  const [mode, ...rest] = argv;
730
+ if (mode === '--flock-check') {
731
+ const result = flockResolution();
732
+ const fields = [result.status, result.runner || result.candidate, result.detail]
733
+ .map(value => String(value).replace(/[\t\r\n]/g, ' '));
734
+ process.stdout.write(fields.join('\t') + '\n');
735
+ return;
736
+ }
737
+ if (mode === '--flock-lock-check') {
738
+ const [mainRoot, stateRoot] = rest;
739
+ if (!mainRoot || !stateRoot) fail('usage: state-authority.mjs --flock-lock-check <project-root> <state-root>');
740
+ const main = authorityIdentity({ cwd: mainRoot, mainRoot, stateRoot });
741
+ const pinned = readLocator(main);
742
+ if (!pinned) fail(`state authority is not initialized for ${main}; there is no authority lock to probe`);
743
+ const located = agree(pinned, main, canonical(stateRoot));
744
+ const lock = authorityLock(located.stateRoot);
745
+ if (!regular_exists(lock)) fail(`authority lock does not exist yet: ${lock}`);
746
+ const result = await flock(lock, ['--lock-probe']);
747
+ process.stdout.write(JSON.stringify(result) + '\n');
748
+ return;
749
+ }
750
+ if (mode === '--lock-probe') {
751
+ process.stdout.write(JSON.stringify({ ok: true }) + '\n');
752
+ return;
753
+ }
689
754
  if (mode === '--locator') {
690
755
  const [main, requested] = rest;
691
756
  verifyLockFile(locatorLock(main));
@@ -708,7 +773,8 @@ async function main(argv) {
708
773
  if (requestData.op === 'remind-add') {
709
774
  const message = await readMessageFromStdin();
710
775
  if (message.error) {
711
- process.stdout.write(renderRemind(requestData.op, { ok: false, refusal: 'bad-message', reason: message.error }));
776
+ const refusal = { ok: false, refusal: 'bad-message', reason: message.error };
777
+ process.stdout.write(json ? JSON.stringify(refusal, null, 2) + '\n' : renderRemind(requestData.op, refusal));
712
778
  process.exitCode = 1;
713
779
  return;
714
780
  }
@@ -131,6 +131,7 @@ case "$CMD" in
131
131
  watchdog-status) team_cmd_watchdog_status "$@" ;; # 同上
132
132
  standby) team_cmd_standby "$@" ;;
133
133
  remind) team_cmd_remind "$@" ;;
134
+ __remind-recover) team_remind_recovery "$@" ;; # 内部:Pulse 的 prompt-free Reminder-only 恢复(不进 help)
134
135
  meeting) team_cmd_meeting "$@" ;;
135
136
  version) if [ "${1:-}" = "--check" ] || [ "${1:-}" = "check" ]; then team_cmd_version_check "$@"; else team_cmd_version_brief "$@"; fi ;;
136
137
  mark-loaded) team_err "mark-loaded 已移除:会话新旧由推导得出——PM 进程启动时刻 vs skill 文件的最近改动时刻,跑 $TEAM_CLI version --check 或 $TEAM_CLI doctor"; exit 2 ;;
@@ -14,7 +14,7 @@ inventoried and preserved outside first -- the PM's job, recipe in `{{SKILL_DIR}
14
14
 
15
15
  | Role | Owns | Must not |
16
16
  |---|---|---|
17
- | PM | Briefs / roadmap / decision log, dispatch, independent verification, merging, wrap-up | Treat "the agent says it passed" as evidence |
17
+ | PM | Briefs / roadmap / decision log, dispatch, evidence acceptance, merging, wrap-up | Treat "the agent says it passed" as evidence; execute verification or archive gates |
18
18
  | agent:<name> | Exactly the brief, tests and reports, opening PR/MRs | push `main`, force-push, merge PR/MRs, touch other people's directories |
19
19
 
20
20
  Before starting, in this order: this file (especially this section), your own thread
@@ -31,9 +31,11 @@ the spec root). Read the change's proposal in `openspec/changes/<id>/` and the c
31
31
  lists, spec copies or design sections in task briefs or docs -- if it must hold, it goes into a spec.
32
32
 
33
33
  A change runs as **five phases, one brief and one owner each**: `opsx-explore`, then `opsx-propose` (planning only);
34
- a dev runs `opsx-apply`; a **different** agent runs `opsx-verify`; the PM runs `opsx-archive`. Two hard rules: **no
35
- `apply` brief before the PM's proposal review (`{{DOCS_DIR}}/reviews/<change>-proposal.md`) is ACCEPTED**, and no
36
- agent verifies its own work; the PM archives only after independent verification **and the user's confirmation**.
34
+ a dev runs `opsx-apply`; a **different** agent runs `opsx-verify`; a non-implementer worker (possibly that verifier) runs
35
+ `opsx-archive`. Two hard rules: **no `apply` brief before the PM's proposal review
36
+ (`{{DOCS_DIR}}/reviews/<change>-proposal.md`) is ACCEPTED**, and no agent verifies its own work. The PM dispatches and
37
+ accepts archive only after the same verifier's merged-revision evidence passes and the user confirms, or the PM records
38
+ a narrowly qualified proxy confirmation (small, reversible and already covered by the approved approach).
37
39
  Phase names go in the brief's `phase:` line; flags, phase-command source and pinned-toolchain caveat are in
38
40
  `{{SKILL_DIR}}/references/openspec.md`.
39
41
 
@@ -57,8 +59,8 @@ last three take `--force` + one audited line). `team change status <id>` shows t
57
59
  starts a long job and the turn ends; the completion wake-up is the normal harvest point. Do not wait inside the
58
60
  turn (`sleep`, `team wait`, a blocking harvest): the user cannot type while the PM waits. A previous session's wake-ups died with its process: find its jobs on disk
59
61
  (`state/bg.log`, `team bg list`) before awaiting or re-running them (`{{SKILL_DIR}}/references/workflows.md` §E2).
60
- - **Never claim tests passed without having run them.** The PM re-runs in an independent worktree; a false report
61
- fails the task.
62
+ - **Never claim tests passed without having run them.** The assigned non-implementer verifier runs the gates on the
63
+ PM-prepared independent checkout; the PM accepts that evidence rather than executing the gates. A false report fails the task.
62
64
  - Never write tokens/secrets into code, config, logs or commit messages; never read credential files
63
65
  (e.g. `~/.pi/agent/auth.json`).
64
66
  - **A brief declares one task category; models belong to the project, not to your seat.** The `category:` line
@@ -88,8 +90,9 @@ claim attached to a selected run. Review queues on the gate lock before its own
88
90
  Implement in scope, small commits, run the brief's acceptance commands, then write
89
91
  `{{DOCS_DIR}}/reports/<ID>-<agent>.md` with the real commands and output tails (plus flip evidence for a defect
90
92
  fix) and settle the branch: a local branch stays local, and a remote push/PR follows only the PM's authorized
91
- route. The PM verifies in an independent worktree, merges itself, sets the board and closes the task. Messages are
92
- not deliverables -- evidence lives in `{{DOCS_DIR}}/reports/`, `{{DOCS_DIR}}/reviews/` and the commits (recipes:
93
+ route. A non-implementer verifier runs `team review` on the PM-prepared independent checkout and, after the PM merges,
94
+ resumes on the merged SHA. The PM accepts that evidence, merges, and only then sets the board and closes the task.
95
+ Messages are not deliverables -- evidence lives in `{{DOCS_DIR}}/reports/`, `{{DOCS_DIR}}/reviews/` and the commits (recipes:
93
96
  `{{SKILL_DIR}}/references/workflows.md` §B dispatch, §E verification, §F merge). `{{DOCS_DIR}}/inbox/<agent>.md`
94
97
  and the knock on `{{SESSION}}:{{PM_WINDOW}}` happen at turn end automatically. Blocked, or someone else's bug:
95
98
  `bash {{SKILL_DIR}}/scripts/team notify <agent> "<one line>"` and a report that says `BLOCKED:`.
@@ -8,9 +8,9 @@
8
8
 
9
9
  ## D1 · {{TODAY}} · 决定 — 采用 teamsmith 的多 Agent 协作流程
10
10
 
11
- - **决策**:Issue → agent worktree/分支 → 报告 + 门禁 → PM 独立复验 → squash 合并。
11
+ - **决策**:Issue → agent worktree/分支 → 报告 + 门禁 → verifier 独立复验 → PM 审阅接受 → squash 合并。
12
12
  - **理由**:可追溯、并行不冲突、合并权集中在 PM(质量门禁不被绕过)。
13
- - **影响**:agent 不得 push 保护分支 / 不得 merge;PM 必须真的跑复验,不能只看报告。
13
+ - **影响**:agent 不得 push 保护分支 / 不得 merge;PM 必须审阅复验证据与 diff,不能只看报告,也不得以自己执行替代委派。
14
14
 
15
15
  ## D2 · {{TODAY}} · 暂定 — <技术栈/选型类决策>
16
16
 
@@ -6,7 +6,7 @@
6
6
  | Path | Owner | Purpose |
7
7
  |---|---|---|
8
8
  | `<path>/**` | agent:<name> | <what this directory is responsible for> |
9
- | `docs/**` | PM | Briefs / reports / verification / decisions |
9
+ | `docs/**` | PM | Briefs / reports / verification / decisions. Narrow review exception: only `team review` may write the brief-named `docs/team/reviews/<ID>.md` and `<ID>-verify.log` in the main checkout; the verifier's own report stays on its task branch, and no other manual main-checkout write is granted |
10
10
  | `.pi/**`, `AGENTS.md` | PM | Team protocol and configuration |
11
11
  | `scripts/team*`, root config (lockfile/tsconfig, ...) | PM | New dependencies → raise them in the report |
12
12
 
@@ -25,5 +25,5 @@
25
25
  1. Need a new directory? The PM updates this file (and references it in the brief).
26
26
  2. Temporary borrowing (e.g. one package handled by another agent for a phase) must be marked **temporary** in the
27
27
  brief together with the hand-over condition.
28
- | `openspec/specs/**` · `openspec/config.yaml` | PM | 规格与配置是账本的一部分 |
29
- | `openspec/changes/<change>/**` | 该 change 当前阶段的 owner(任务书明授) | propose 归提案者;apply 归实现者;archive 由 PM 执行 |
28
+ | `openspec/specs/**` · `openspec/config.yaml` | PM | 规格与配置是账本的一部分;archive 仅获任务书逐个点名的 capability spec 临时写权,不含 config |
29
+ | `openspec/changes/<change>/**` | 该 change 当前阶段的 owner(任务书明授) | propose 归提案者;apply 归实现者;archive 由非实现者 worker 在自己的 worktree/task branch 执行,仅写任务书枚举的 change、归档目标与报告 |
@@ -8,7 +8,7 @@
8
8
 
9
9
  | Role | Where | Owns | Red lines |
10
10
  |---|---|---|---|
11
- | PM | tmux `{{SESSION}}:pm` | Milestones/board/briefs/decisions; dispatch; independent verification; merging; wrap-up | Never let an agent's own account replace evidence; never write tokens into any artifact |
11
+ | PM | tmux `{{SESSION}}:pm` | Milestones/board/briefs/decisions; dispatch; evidence acceptance; merging; wrap-up | Never let an agent's own account replace evidence or execute verification/archive gates; never write tokens into any artifact |
12
12
  | agent:<name> | `{{WORKTREES_DIR}}/<name>` | Implementation + tests + report + the branch it was given | Never push the protected branch, force-push, merge, or change directories it does not own |
13
13
 
14
14
  ## Lifecycle of a task
@@ -18,14 +18,16 @@
18
18
  3. **agent**: implement in the worktree; commit in small steps; run the acceptance commands; write the report
19
19
  `{{DOCS_DIR}}/reports/<ID>-<a>.md`; settle the branch (local: the commits stay on the task branch; remote: the
20
20
  PM's authorized push/PR route). The PM is notified automatically when the turn ends (inbox + tmux wake-up).
21
- 4. **PM**: `team digest` for pending work → `team review <ID> --dir <independent checkout>` (run gates, read the
22
- diff, write `{{DOCS_DIR}}/reviews/<ID>.md`).
23
- 5. **Pass** → the PM runs git itself: squash-merge (with a PR, merge it first, then `fetch && merge --ff-only`) →
24
- `team board set <ID> done` → `team close <ID>`. **Fail** → send the concrete failure evidence back.
21
+ 4. **PM**: `team digest` for pending work → prepare an independent checkout and dispatch a non-implementer verifier.
22
+ **Verifier**: `team review <ID> --dir <checkout>` runs the gates and writes the named central record/log; the PM reads
23
+ the evidence and diff without running the gates.
24
+ 5. **Pass** → the PM runs git itself: squash-merge (with a PR, merge it first, then `fetch && merge --ff-only`) → the
25
+ same verifier resumes on the merged SHA → the PM accepts passing evidence → `team board set <ID> done` →
26
+ `team close <ID>`. **Fail** → send the concrete failure evidence back.
25
27
 
26
28
  ## Hard rules
27
29
 
28
- 1. Never claim the acceptance commands passed without having run them. The PM re-runs independently; a false report fails the task.
30
+ 1. Never claim the acceptance commands passed without having run them. The assigned verifier re-runs independently; the PM accepts the evidence; a false report fails the task.
29
31
  2. One long-lived worktree per agent (sessions are keyed by cwd; moving the path makes them un-resumable); each task gets its own branch inside it.
30
32
  3. Commit in small steps -- never one dump at the end; include the task ID and an `Agent: <name>` trailer.
31
33
  4. Only change directories assigned to you in `{{DOCS_DIR}}/OWNERSHIP.md`; cross-directory needs → write `BLOCKED:` in the report.
@@ -36,8 +38,8 @@
36
38
  ## Gates
37
39
 
38
40
  - Project gates: `{{GATES}}`
39
- - Verification uses an **independent checkout**: the PM prepares it (`git worktree add --detach`), then
40
- `team review <ID> --dir <checkout>` runs the gates and writes the evidence.
41
+ - Verification uses an **independent checkout**: the PM prepares it (`git worktree add --detach`), then the assigned
42
+ non-implementer verifier runs `team review <ID> --dir <checkout>` and the tool writes the named central record/log.
41
43
  - A brief may require stricter commands than the project gates; the brief wins. A selected run says which sections it
42
44
  did not run instead of claiming the full suite.
43
45
  - **Correctness on every change**: `openspec validate --all --strict && bash {{SKILL_DIR}}/tests/smoke.sh </dev/null`.
@@ -59,14 +61,17 @@
59
61
  ## Specs (OpenSpec)
60
62
 
61
63
  Specs and change proposals live in `openspec/` (required dependency). `openspec validate --all --strict` is part of the
62
- gate. `openspec change show <id>` reads a proposal, and the PM archives a change (`openspec archive -y <id>`) only
63
- after independent verification has landed and the user confirmed. No parallel spec system: a product promise goes into
64
- a spec, reasoning or guidance into `references/`.
64
+ gate. `openspec change show <id>` reads a proposal. The PM dispatches archive to a non-implementer worker only after
65
+ the same verifier's merged-revision evidence passes and the user confirms, or the PM records a proxy confirmation only
66
+ for a small, reversible change already covered by the approved approach. The worker runs `openspec archive -y <id>` on
67
+ its own authorized task branch. No parallel spec system: a
68
+ product promise goes into a spec, reasoning or guidance into `references/`.
65
69
 
66
70
  A change runs as **five phases, one brief and one owner each**: `opsx-explore` (an explorer) → `opsx-propose` (the same
67
- explorer, planning only) → `opsx-apply` (a dev) → `opsx-verify` (an **independent** agent) → `opsx-archive` (the PM).
68
- Two hard rules: no `apply` brief before the PM's proposal review (`{{DOCS_DIR}}/reviews/<change>-proposal.md`) is
69
- **ACCEPTED**, and no agent verifies its own work; the PM archives only after independent verification and the user's confirmation.
71
+ explorer, planning only) → `opsx-apply` (a dev) → `opsx-verify` (a **different** agent) → `opsx-archive` (a
72
+ non-implementer worker, possibly that verifier). Two hard rules: no `apply` brief before the PM's proposal review
73
+ (`{{DOCS_DIR}}/reviews/<change>-proposal.md`) is **ACCEPTED**, and no agent verifies its own work. The PM dispatches and
74
+ accepts archive only after the same verifier's merged-revision evidence and valid confirmation.
70
75
  Phase table, gates and the PM's review checklist: `{{SKILL_DIR}}/references/openspec.md`.
71
76
 
72
77
  **The change is the assignment unit** (`1 change : N tasks`, `1 task : 0..1 change`): the brief's header is the
@@ -20,8 +20,8 @@
20
20
  - Branch mode: `{{BRANCH_MODE}}`; agent worktrees: `{{WORKTREES_DIR}}/<agent>` (**never move them**: sessions are keyed by cwd).
21
21
 
22
22
  ### Working rules (the creed; cross-project)
23
- - Deliverables must be independently verifiable: an agent's report is a claim; the PM's gates on an independent
24
- checkout are the evidence.
23
+ - Deliverables must be independently verifiable: an agent's report is a claim; a non-implementer verifier runs the
24
+ gates on the PM-prepared independent checkout, and the PM accepts that evidence without executing the gates.
25
25
  - Status is a promise: `done` only after the code really landed on the protected branch; on failure keep the old state.
26
26
  - Govern less to be reliable: the skill does not wrap git/forge, the PM does not implement, the pulse only wakes.
27
27
  - Failure is information: a false green is worse than nothing; gates need hard timeouts; skips must be declared.