teamsmith 0.4.3 → 0.4.6

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 (44) hide show
  1. package/README.md +4 -4
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +33 -1
  4. package/skills/teamsmith/SKILL.md +1 -1
  5. package/skills/teamsmith/extension/team-bg.ts +7 -8
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +136 -3
  7. package/skills/teamsmith/references/protocol.md +2 -3
  8. package/skills/teamsmith/references/reminders.md +55 -12
  9. package/skills/teamsmith/references/workflows.md +1 -3
  10. package/skills/teamsmith/scripts/lib/cmd-agents.sh +18 -1
  11. package/skills/teamsmith/scripts/lib/cmd-project.sh +12 -9
  12. package/skills/teamsmith/scripts/lib/cmd-remind.sh +49 -10
  13. package/skills/teamsmith/scripts/lib/cmd-update.sh +90 -88
  14. package/skills/teamsmith/scripts/lib/cmd-watch.sh +281 -155
  15. package/skills/teamsmith/scripts/lib/common.sh +74 -14
  16. package/skills/teamsmith/scripts/panel/panel.js +134 -134
  17. package/skills/teamsmith/scripts/panel/src/data.ts +51 -0
  18. package/skills/teamsmith/scripts/panel/src/layout.ts +10 -0
  19. package/skills/teamsmith/scripts/panel/src/main.tsx +27 -0
  20. package/skills/teamsmith/scripts/remind-store.mjs +362 -6
  21. package/skills/teamsmith/scripts/remind-tick.mjs +102 -0
  22. package/skills/teamsmith/scripts/reminder-delivery.mjs +76 -0
  23. package/skills/teamsmith/scripts/reply-capture.mjs +53 -8
  24. package/skills/teamsmith/scripts/state-authority.mjs +265 -17
  25. package/skills/teamsmith/scripts/strings/commands.tsv +3 -3
  26. package/skills/teamsmith/scripts/strings/help.en.tsv +12 -12
  27. package/skills/teamsmith/scripts/strings/help.zh.tsv +12 -12
  28. package/skills/teamsmith/scripts/team +3 -3
  29. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +2 -3
  30. package/skills/teamsmith/templates/pm-prompt.md.tmpl +11 -5
  31. package/skills/teamsmith/tests/death-cause.sh +5 -0
  32. package/skills/teamsmith/tests/help-surface.sh +15 -150
  33. package/skills/teamsmith/tests/isolation-ledger.sh +85 -0
  34. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +17 -1
  35. package/skills/teamsmith/tests/live-capture-probe.sh +63 -0
  36. package/skills/teamsmith/tests/pulse-nudge-key.sh +5 -0
  37. package/skills/teamsmith/tests/remind-delivery-node.mjs +176 -0
  38. package/skills/teamsmith/tests/remind-delivery.sh +611 -0
  39. package/skills/teamsmith/tests/section-paths.tsv +6 -6
  40. package/skills/teamsmith/tests/smoke.sh +397 -107
  41. package/skills/teamsmith/tests/state-authority.sh +246 -26
  42. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +58 -8
  43. package/skills/teamsmith/tests/tmux-identity-leak.sh +12 -16
  44. package/skills/teamsmith-init/SKILL.md +1 -1
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // remind-tick.mjs — Pulse's lightweight Reminder due tick (change: agent-self-reminder 4.1 · P423).
3
+ //
4
+ // Both Pulse shapes run this same entry roughly every ten seconds, independently of the full patrol's
5
+ // cadence: the console spawns it from its own timer, the headless loop calls it between patrols. It is not
6
+ // a second daemon and it never scans the project or calls a model — it reads one bounded snapshot and, if
7
+ // something is due, commits the queue entries under the authority lock.
8
+ //
9
+ // The unlocked `peek` in front is only a wake-up test: with nothing due it exits after one file read and
10
+ // no lock (a project without reminders costs one small read per tick). Every decision that changes state
11
+ // happens inside `request()`, the same flock transaction the CLI and the PM watcher use.
12
+ //
13
+ // Usage: remind-tick.mjs --root <project-root> --state-dir <state-root>
14
+ // [--pulse-started <ISO instant>] [--quiet] [--json]
15
+ // Exit: 0 = tick done (nothing due, or admitted); 1 = an explicit state/lock/identity error (stderr says
16
+ // which; the pulse records it and keeps its own cadence); 2 = bad usage.
17
+
18
+ import { appendFileSync, readFileSync, statSync, writeFileSync } from 'node:fs';
19
+ import path from 'node:path';
20
+ import { peek, request } from './state-authority.mjs';
21
+
22
+ const LOG_MAX_BYTES = 256 * 1024;
23
+
24
+ function usage() {
25
+ process.stderr.write('usage: remind-tick.mjs --root <project-root> --state-dir <state-root> ' +
26
+ '[--pulse-started <ISO instant>] [--quiet] [--json]\n');
27
+ }
28
+
29
+ function parse(argv) {
30
+ const opts = { root: '', stateDir: '', pulseStarted: '', quiet: false, json: false };
31
+ for (let i = 0; i < argv.length; i++) {
32
+ const token = argv[i];
33
+ const value = () => {
34
+ const v = argv[++i];
35
+ if (v === undefined) throw new Error(`${token} needs a value`);
36
+ return v;
37
+ };
38
+ switch (token) {
39
+ case '--root': opts.root = value(); break;
40
+ case '--state-dir': opts.stateDir = value(); break;
41
+ case '--pulse-started': opts.pulseStarted = value(); break;
42
+ case '--quiet': opts.quiet = true; break;
43
+ case '--json': opts.json = true; break;
44
+ case '-h': case '--help': usage(); process.exit(0); break;
45
+ default: throw new Error(`unknown argument ${token}`);
46
+ }
47
+ }
48
+ if (!opts.root) throw new Error('--root is required');
49
+ if (!opts.stateDir) throw new Error('--state-dir is required');
50
+ return opts;
51
+ }
52
+
53
+ // A durable, bounded line per tick that actually committed something: "why did the PM wake up" has to be
54
+ // answerable from the disk, not from a process that has already exited.
55
+ function log(stateRoot, line) {
56
+ const file = path.join(stateRoot, 'reminders.log');
57
+ try {
58
+ appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
59
+ if (statSync(file).size > LOG_MAX_BYTES) {
60
+ const kept = readFileSync(file, 'utf8').split('\n').slice(-400).join('\n');
61
+ writeFileSync(file, kept);
62
+ }
63
+ } catch (e) {
64
+ process.stderr.write(`remind-tick: could not append ${file} (${e.code ?? e.message}); the admission is committed, only the log line is missing\n`);
65
+ }
66
+ }
67
+
68
+ async function main() {
69
+ const opts = parse(process.argv.slice(2));
70
+ const context = { cwd: opts.root, mainRoot: opts.root, stateRoot: opts.stateDir };
71
+ const seen = await peek(context);
72
+ if (!seen.pinned) {
73
+ if (opts.json) process.stdout.write(`${JSON.stringify({ ok: true, pinned: false, admitted: [] })}\n`);
74
+ return;
75
+ }
76
+ const due = seen.reminders.due.length;
77
+ const stale = seen.reminders.staleIntent.length;
78
+ if (!due && !stale) {
79
+ if (opts.json) process.stdout.write(`${JSON.stringify({ ok: true, pinned: true, admitted: [], swept: [] })}\n`);
80
+ return;
81
+ }
82
+ const result = await request({ ...context, stateRoot: seen.stateRoot }, {
83
+ op: 'remind-admit',
84
+ pulseStartedAt: opts.pulseStarted || new Date().toISOString(),
85
+ });
86
+ const admitted = result.admitted ?? [];
87
+ const swept = result.swept ?? [];
88
+ if (admitted.length || swept.length) {
89
+ log(seen.stateRoot, `admit n=${admitted.length} overdue=${(result.overdue ?? []).length} ` +
90
+ `ids=${admitted.join('|') || '-'} unknown=${swept.join('|') || '-'} queue=${result.queue}`);
91
+ }
92
+ if (opts.json) process.stdout.write(`${JSON.stringify(result)}\n`);
93
+ else if (!opts.quiet && admitted.length) {
94
+ process.stdout.write(`remind: 到点入队 ${admitted.length} 条(${admitted.join(' ')})\n`);
95
+ }
96
+ }
97
+
98
+ main().catch(e => {
99
+ const message = String((e && e.message) || e);
100
+ process.stderr.write(/^remind-tick:/.test(message) ? `${message}\n` : `remind-tick: ${message}\n`);
101
+ process.exitCode = 1;
102
+ });
@@ -0,0 +1,76 @@
1
+ // reminder-delivery.mjs — the presentation and match half of the Reminder wake (P423 · agent-self-reminder
2
+ // 3.1/3.2). The delivery *decisions* (admission, the frozen batch, observation, unknown, resolve) live in
3
+ // remind-store.mjs inside the authority transaction; this file only answers two questions, both pure:
4
+ //
5
+ // reminderContent(batch) what exact text goes into the session (full text per Reminder, never clipped)
6
+ // matchesObservation(message, batch) is this the event that proves *our* message entered the run
7
+ //
8
+ // The caller (the PM's inbox watcher) writes the intent, then calls pi.sendMessage with this content and
9
+ // these details, then reports the matching `message_start` back to the transaction. A return value, a
10
+ // thrown error or a deferred action never becomes success on its own: only the correlated event does.
11
+
12
+ export const REMINDER_CUSTOM_TYPE = 'team-reminder';
13
+
14
+ const oneLine = (text, limit) => String(text).replace(/\s*\n\s*/g, ' ').slice(0, limit);
15
+
16
+ function attributes(member) {
17
+ const parts = [`source ${member.source ?? 'cli'}`];
18
+ if (member.task) parts.push(`task ${member.task}`);
19
+ if (member.key) parts.push(`key ${member.key}`);
20
+ return parts.join(' · ');
21
+ }
22
+
23
+ /** The complete batch as one message. Nothing is shortened; ids and times are the durable record's. */
24
+ export function reminderContent(batch) {
25
+ const attempted = batch.attemptedAt ?? batch.intentAt ?? new Date().toISOString();
26
+ const head = [
27
+ `[teamsmith reminder] ${batch.id} · ${batch.members.length} reminder${batch.members.length === 1 ? '' : 's'}`,
28
+ `Nonce: ${batch.nonce}`,
29
+ ];
30
+ const bodies = batch.members.map(member => [
31
+ `ID: ${member.id}`,
32
+ `Due: ${member.dueAt}`,
33
+ `Enqueued: ${member.enqueuedAt ?? '-'}${member.overdue ? ' (overdue: the patrol queued it late)' : ''}`,
34
+ `Attempted: ${attempted}`,
35
+ `From: ${attributes(member)}`,
36
+ '',
37
+ member.message,
38
+ ].join('\n'));
39
+ return `${head.join('\n')}\n\n${bodies.join('\n\n---\n\n')}\n\n---\n` +
40
+ 'This message is a scheduled reminder this project\'s PM created earlier. The project and task state may have ' +
41
+ 'changed since it was scheduled: check the current state before you continue.\n';
42
+ }
43
+
44
+ /** The machine-side identity of the same message: what the observation must match, never model-visible. */
45
+ export function reminderDetails(batch) {
46
+ return {
47
+ batchId: batch.id,
48
+ nonce: batch.nonce,
49
+ members: batch.members.map(member => member.id),
50
+ generation: batch.generation,
51
+ };
52
+ }
53
+
54
+ /**
55
+ * True only for the public `message_start` of THIS batch's custom message: same custom type, same batch id,
56
+ * same nonce, same member set. A same-named message from another sender, an assistant/user message or a
57
+ * batch whose details are absent is not an observation.
58
+ */
59
+ export function matchesObservation(message, batch) {
60
+ if (!message || typeof message !== 'object') return false;
61
+ if (message.role !== 'custom' || message.customType !== REMINDER_CUSTOM_TYPE) return false;
62
+ const details = message.details;
63
+ if (!details || typeof details !== 'object') return false;
64
+ if (details.batchId !== batch.id || details.nonce !== batch.nonce) return false;
65
+ if (!Array.isArray(details.members)) return false;
66
+ const expected = batch.members.map(member => (typeof member === 'string' ? member : member.id));
67
+ if (details.members.length !== expected.length) return false;
68
+ return expected.every((id, index) => details.members[index] === id);
69
+ }
70
+
71
+ /** One bounded log line for the watcher's ledger: what was decided, never the reminder text. */
72
+ export function deliveryLogLine(batch, outcome) {
73
+ const ids = batch.members.map(member => (typeof member === 'string' ? member : member.id));
74
+ return `reminder ${outcome} batch=${batch.id} n=${ids.length} ids=${ids.join('|')} ` +
75
+ `generation=${batch.generation} attempted=${oneLine(batch.attemptedAt ?? batch.intentAt ?? '-', 40)}`;
76
+ }
@@ -114,6 +114,11 @@ function derivedTitle(body) {
114
114
  }
115
115
 
116
116
  /** No mutation outside exact original control ranges; character offsets are NOT UTF-8 byte offsets. */
117
+ const TAG_PREFIX = /^\u00a7\d+\u00a7\s*/
118
+ /** What a host may legitimately change about a reply we just produced: the leading tag it asked for,
119
+ * and trailing whitespace left behind by removing the control line. Nothing else is compared. */
120
+ const normalizeReplyText = text => String(text).replace(TAG_PREFIX, '').replace(/\s+$/, '')
121
+
117
122
  export function parseReply(message) {
118
123
  const blocks = Array.isArray(message.content) ? message.content : []
119
124
  const original = blocks.filter(b => b.type === 'text').map(b => b.text).join('')
@@ -328,6 +333,23 @@ function writerOutcome(result, record) {
328
333
  return { status: 'uncertain', reason: 'inconsistent-outcome' }
329
334
  }
330
335
 
336
+ /**
337
+ * Another extension may rewrite the finalized message after ours returns -- magic-context, for one,
338
+ * removes the leading `§N§` tag it asked for. Compare the reply text with that tag normalized away,
339
+ * because the entry id already names the message; requiring byte equality bound nothing and dropped
340
+ * every reply on a machine that runs a second message_end transform.
341
+ */
342
+ function sameReplyMessage(a, b) {
343
+ if (!a || !b || a.role !== b.role || !Array.isArray(a.content) || !Array.isArray(b.content)) return false
344
+ if (a.content.length !== b.content.length) return false
345
+ return a.content.every((item, i) => {
346
+ const other = b.content[i]
347
+ if (!item || !other || item.type !== other.type) return false
348
+ if (item.type !== 'text') return isDeepStrictEqual(item, other)
349
+ return normalizeReplyText(item.text) === normalizeReplyText(other.text)
350
+ })
351
+ }
352
+
331
353
  /** Pi event state, deliberately independent of the host. Only view.entry/branch of the actual current session bind a source. */
332
354
  export class ReplyCapture {
333
355
  constructor({ identity, journal = new CaptureJournal(identity), current, verify, writer, owner, diagnostic }) {
@@ -336,7 +358,17 @@ export class ReplyCapture {
336
358
  this.running = new Set()
337
359
  }
338
360
  memoryHost(view) { return this.current() && sameIdentity(this.identity, view.identity) }
339
- eligibleHost(view) { return this.memoryHost(view) && this.verify() }
361
+ // Re-proving identity costs a git/tmux/getconf round trip; doing it on every event made a transient
362
+ // shell failure look like a refused host, which dropped the reply. Prove once per turn and reuse it.
363
+ eligibleHost(view) {
364
+ if (!this.memoryHost(view)) return false
365
+ const a = this.activity
366
+ if (a && typeof a.verified === 'boolean') return a.verified
367
+ let ok = false
368
+ try { ok = !!this.verify() } catch { ok = false }
369
+ if (a) a.verified = ok
370
+ return ok
371
+ }
340
372
  report(reason, entryId = '') {
341
373
  try { this.diagnostic({ reason, entryId, path: this.journal.path }) }
342
374
  catch { /* An unavailable diagnostic sink must not block final message cleanup. */ }
@@ -377,8 +409,8 @@ export class ReplyCapture {
377
409
  // that never grew. Name it, with the same diagnostic sink that records a mismatched binding.
378
410
  if (!this.eligibleHost(view)) { this.report('ineligible-at-turn'); return }
379
411
  const entry = view.entry(event.messageEntryId)
380
- if (!event.messageEntryId || entry?.type !== 'message' || !isDeepStrictEqual(entry.message, latest.message) ||
381
- !isDeepStrictEqual(event.message, latest.message) || !branchWitness(view, a.startLeaf, event.messageEntryId)) {
412
+ if (!event.messageEntryId || entry?.type !== 'message' || !sameReplyMessage(entry.message, latest.message) ||
413
+ !sameReplyMessage(event.message, latest.message) || !branchWitness(view, a.startLeaf, event.messageEntryId)) {
382
414
  latest.intent = null // A bad binding cannot be repaired by another event or current-leaf inference.
383
415
  this.report('binding-mismatch', event.messageEntryId)
384
416
  return
@@ -413,7 +445,8 @@ export class ReplyCapture {
413
445
  }
414
446
  reset() { this.activity = null }
415
447
  recover(view) {
416
- if (this.activity || !this.eligibleHost(view)) return
448
+ if (this.activity) { this.report('recover-skip:busy'); return }
449
+ if (!this.eligibleHost(view)) { this.report('recover-skip:ineligible'); return }
417
450
  let records
418
451
  try {
419
452
  records = this.journal.transact(snapshot => {
@@ -425,9 +458,17 @@ export class ReplyCapture {
425
458
  record.reason = 'attempt-owner-exited'
426
459
  }
427
460
  }
428
- return Object.values(snapshot.sources).filter(record => record.status === 'eligible' &&
461
+ const all = Object.values(snapshot.sources)
462
+ const keep = all.filter(record => record.status === 'eligible' &&
429
463
  branchWitness(view, record.startLeaf, record.entryId, record.settledLeaf) &&
430
- isDeepStrictEqual(view.entry(record.entryId)?.message, record.message))
464
+ sameReplyMessage(view.entry(record.entryId)?.message, record.message))
465
+ for (const record of all) {
466
+ if (record.status !== 'eligible' || keep.includes(record)) continue
467
+ const why = !branchWitness(view, record.startLeaf, record.entryId, record.settledLeaf) ? 'not-on-branch'
468
+ : 'text-differs'
469
+ this.report(`recover-skipped:${why}`, record.entryId)
470
+ }
471
+ return keep
431
472
  })
432
473
  } catch (e) {
433
474
  if (e.code !== 'ENOENT') this.report(`recovery:${e.code ?? e.name}`)
@@ -436,7 +477,10 @@ export class ReplyCapture {
436
477
  for (const record of records) this.attempt(record, view)
437
478
  }
438
479
  attempt(record, view) {
439
- if (this.activity || !this.eligibleHost(view)) return
480
+ if (this.activity || !this.eligibleHost(view)) {
481
+ this.report(this.activity ? 'attempt-busy' : 'attempt-ineligible', record.entryId)
482
+ return
483
+ }
440
484
  const token = randomUUID()
441
485
  const key = sourceKey(this.identity, record.entryId)
442
486
  try {
@@ -447,7 +491,8 @@ export class ReplyCapture {
447
491
  stored.attempt = { token, ...this.owner, at: new Date().toISOString() }
448
492
  return true
449
493
  })
450
- if (!acquired || !this.eligibleHost(view)) return
494
+ if (!acquired) { this.report('attempt-cas-lost', record.entryId); return }
495
+ if (!this.eligibleHost(view)) { this.report('attempt-ineligible', record.entryId); return }
451
496
  } catch (e) { this.report(`attempting:${e.code ?? e.name}`, record.entryId); return }
452
497
  // Durable CAS above is the barrier, including a crash right before this invocation.
453
498
  const work = Promise.resolve().then(() => {