teamsmith 0.4.5 → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +37 -1
  4. package/skills/teamsmith/SKILL.md +32 -23
  5. package/skills/teamsmith/extension/team-bg.ts +12 -11
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +149 -5
  7. package/skills/teamsmith/extension/team-notify.ts +20 -13
  8. package/skills/teamsmith/extension/team-remind.ts +189 -0
  9. package/skills/teamsmith/extension/team-reply.ts +4 -7
  10. package/skills/teamsmith/references/migration.md +101 -0
  11. package/skills/teamsmith/references/openspec.md +43 -27
  12. package/skills/teamsmith/references/protocol.md +28 -18
  13. package/skills/teamsmith/references/reminders.md +133 -98
  14. package/skills/teamsmith/references/troubleshooting.md +12 -7
  15. package/skills/teamsmith/references/workflows.md +85 -34
  16. package/skills/teamsmith/scripts/lib/cmd-agents.sh +28 -5
  17. package/skills/teamsmith/scripts/lib/cmd-project.sh +100 -15
  18. package/skills/teamsmith/scripts/lib/cmd-remind.sh +135 -10
  19. package/skills/teamsmith/scripts/lib/cmd-review.sh +42 -4
  20. package/skills/teamsmith/scripts/lib/cmd-update.sh +90 -88
  21. package/skills/teamsmith/scripts/lib/cmd-watch.sh +322 -159
  22. package/skills/teamsmith/scripts/lib/common.sh +156 -26
  23. package/skills/teamsmith/scripts/panel/panel.js +182 -182
  24. package/skills/teamsmith/scripts/panel/src/data.ts +113 -6
  25. package/skills/teamsmith/scripts/panel/src/layout.ts +26 -4
  26. package/skills/teamsmith/scripts/panel/src/main.tsx +103 -14
  27. package/skills/teamsmith/scripts/remind-capability.mjs +261 -0
  28. package/skills/teamsmith/scripts/remind-store.mjs +404 -17
  29. package/skills/teamsmith/scripts/remind-tick.mjs +105 -0
  30. package/skills/teamsmith/scripts/reminder-delivery.mjs +76 -0
  31. package/skills/teamsmith/scripts/reply-capture.mjs +8 -9
  32. package/skills/teamsmith/scripts/state-authority.mjs +334 -20
  33. package/skills/teamsmith/scripts/strings/commands.tsv +3 -3
  34. package/skills/teamsmith/scripts/strings/help.en.tsv +12 -12
  35. package/skills/teamsmith/scripts/strings/help.zh.tsv +12 -12
  36. package/skills/teamsmith/scripts/team +4 -3
  37. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +13 -11
  38. package/skills/teamsmith/templates/DECISIONS.md.tmpl +2 -2
  39. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +3 -3
  40. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +19 -14
  41. package/skills/teamsmith/templates/memory-seed.md.tmpl +2 -2
  42. package/skills/teamsmith/templates/pm-prompt.md.tmpl +36 -18
  43. package/skills/teamsmith/templates/report.md.tmpl +33 -0
  44. package/skills/teamsmith/tests/bg-ledger-harness.mjs +217 -33
  45. package/skills/teamsmith/tests/bg-ledger.sh +24 -10
  46. package/skills/teamsmith/tests/checkout-shape-probe.sh +7 -6
  47. package/skills/teamsmith/tests/death-cause.sh +5 -0
  48. package/skills/teamsmith/tests/fixtures/remind-adversarial-delay.ts +27 -0
  49. package/skills/teamsmith/tests/fixtures/remind-tool-provider.ts +65 -0
  50. package/skills/teamsmith/tests/help-surface.sh +14 -151
  51. package/skills/teamsmith/tests/isolation-ledger.sh +89 -0
  52. package/skills/teamsmith/tests/key-replies-ui.sh +53 -0
  53. package/skills/teamsmith/tests/key-replies.sh +307 -106
  54. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +17 -1
  55. package/skills/teamsmith/tests/lib/routes-pages.sh +243 -0
  56. package/skills/teamsmith/tests/live-capture-probe.sh +12 -2
  57. package/skills/teamsmith/tests/loop-inventory.tsv +1 -0
  58. package/skills/teamsmith/tests/panel-b3-stub.sh +9 -2
  59. package/skills/teamsmith/tests/pulse-nudge-key.sh +5 -0
  60. package/skills/teamsmith/tests/remind-adversarial-faults.mjs +163 -0
  61. package/skills/teamsmith/tests/remind-adversarial-faults.sh +26 -0
  62. package/skills/teamsmith/tests/remind-adversarial-real.sh +27 -0
  63. package/skills/teamsmith/tests/remind-cli.sh +108 -3
  64. package/skills/teamsmith/tests/remind-delivery-node.mjs +189 -0
  65. package/skills/teamsmith/tests/remind-delivery.sh +699 -0
  66. package/skills/teamsmith/tests/remind-lifecycle.sh +197 -0
  67. package/skills/teamsmith/tests/remind-pulse.sh +199 -0
  68. package/skills/teamsmith/tests/remind-recovery-real.sh +5 -0
  69. package/skills/teamsmith/tests/remind-recovery-unit.sh +118 -0
  70. package/skills/teamsmith/tests/remind-tool-node.mjs +159 -0
  71. package/skills/teamsmith/tests/remind-tool-real.mjs +754 -0
  72. package/skills/teamsmith/tests/remind-tool-real.sh +5 -0
  73. package/skills/teamsmith/tests/reply-capture-real.mjs +93 -2
  74. package/skills/teamsmith/tests/routes.sh +213 -293
  75. package/skills/teamsmith/tests/section-paths.tsv +14 -12
  76. package/skills/teamsmith/tests/smoke.sh +876 -130
  77. package/skills/teamsmith/tests/state-authority.sh +392 -28
  78. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +58 -8
  79. package/skills/teamsmith/tests/tmux-identity-leak.sh +12 -16
  80. package/skills/teamsmith-init/SKILL.md +5 -5
  81. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
@@ -10,13 +10,21 @@
10
10
  // transitions. What a person sees is *derived* from that truth on every read -- `scheduled` gains the
11
11
  // clock-derived `derived-due` view, and no counter is stored a second time, so a hand-corrected snapshot
12
12
  // or a later Pulse admission is visible without a migration.
13
+
14
+ import { randomUUID } from 'node:crypto';
13
15
  //
14
- // Scope of this slice: the durable create/list/show/cancel lifecycle and the derived views. Batching,
15
- // intent, delivery, observation, Standby and Pulse admission belong to 3.x/4.x; their phases are
16
- // validated and derived here already so a snapshot written by those slices reads correctly, but nothing
17
- // in this file produces them.
16
+ // Scopes: 2.x is the durable create/list/show/cancel lifecycle and the derived views (P409); 4.1/3.1/3.2
17
+ // add the delivery path here (P423): due admission (`queued`), the one frozen batch intent, the correlated
18
+ // observation that closes it, the explicit unknown outcome and the operator's acknowledgment. Everything
19
+ // still happens inside state-authority.mjs's single flock transaction; this file stays filesystem-free and
20
+ // the Pi call itself is *not* here (the caller sends after intent and reports the matching event back).
18
21
 
19
22
  const PHASES = new Set(['scheduled', 'queued', 'intent', 'observed', 'unknown', 'cancelled', 'resolved']);
23
+ // A batch is the one durable delivery decision: at most one is outstanding until it is observed or an
24
+ // operator acknowledges it, and its single right is what may clear one Standby generation.
25
+ const BATCH_PHASES = new Set(['intent', 'observed', 'unknown', 'resolved']);
26
+ const OBSERVE_DEADLINE_MS = 60000; // after intent, no correlated event within 60s = unknown, never a resend
27
+ const OVERDUE_LAG_MS = 30000; // normal polling delay is not overdue; 30s of admission lag is
20
28
  // Terminal = the outcome is known and the reminder can no longer fire. A key survives `unknown` (a
21
29
  // delivery attempt is outstanding, so the logical reminder is still "in play") and is released by any
22
30
  // terminal phase (design: "A key remains reserved for scheduled, queued, intent and unknown records").
@@ -135,6 +143,284 @@ function normSource(source) {
135
143
  return { source: value };
136
144
  }
137
145
 
146
+ // ---------------------------------------------------------------- delivery (P423 · 3.1/3.2/4.1)
147
+ // `peek` is the only classification a caller may do without the lock: it answers "is there anything to
148
+ // commit right now" from a whole snapshot read (rename is atomic, so an unlocked read never sees half a
149
+ // file). Every decision that changes the snapshot still runs inside the transaction below.
150
+ export function peekReminders(snapshot, nowMs) {
151
+ if (!snapshot || !Array.isArray(snapshot.reminders)) return { due: [], queued: [], staleIntent: [] };
152
+ const due = [];
153
+ const queued = [];
154
+ const staleIntent = [];
155
+ for (const record of snapshot.reminders) {
156
+ if (record.phase === 'scheduled' && Number.isFinite(msOf(record.dueAt)) && msOf(record.dueAt) <= nowMs) due.push(record.id);
157
+ if (record.phase === 'queued') queued.push(record.id);
158
+ }
159
+ for (const batch of Array.isArray(snapshot.batches) ? snapshot.batches : []) {
160
+ if (batch.phase === 'intent' && Number.isFinite(msOf(batch.intentAt)) && nowMs - msOf(batch.intentAt) >= OBSERVE_DEADLINE_MS) staleIntent.push(batch.id);
161
+ }
162
+ return { due, queued, staleIntent };
163
+ }
164
+
165
+ function findBatch(snapshot, id) {
166
+ return snapshot.batches.find(batch => batch.id === id) ?? null;
167
+ }
168
+
169
+ function parseBatchId(id, projectId) {
170
+ const prefix = `bat-${projectId}-`;
171
+ if (typeof id !== 'string' || !id.startsWith(prefix)) return null;
172
+ const tail = id.slice(prefix.length);
173
+ if (!/^[1-9][0-9]*$/.test(tail)) return null;
174
+ const seq = Number(tail);
175
+ return Number.isSafeInteger(seq) ? { seq } : null;
176
+ }
177
+
178
+ // The single outstanding delivery, if any. `unknown` is still outstanding: an operator has to inspect the
179
+ // batch before the next one may be frozen (design: "Only one batch is outstanding until observed or
180
+ // explicitly acknowledged"). A late correlated observation closes it too -- that is not a resend.
181
+ function outstandingBatch(snapshot) {
182
+ return snapshot.batches.find(batch => batch.phase === 'intent' || batch.phase === 'unknown') ?? null;
183
+ }
184
+
185
+ // After the deadline, an intent without a correlated event is `unknown`: absence of an event is not proof
186
+ // that nothing entered the session, so the members stop being independently sendable and nothing resends.
187
+ function sweepStaleIntents(snapshot, nowMs) {
188
+ const swept = [];
189
+ for (const batch of snapshot.batches) {
190
+ if (batch.phase !== 'intent' || !Number.isFinite(msOf(batch.intentAt))) continue;
191
+ if (nowMs - msOf(batch.intentAt) < OBSERVE_DEADLINE_MS) continue;
192
+ batch.phase = 'unknown';
193
+ batch.unknownAt = iso(nowMs);
194
+ for (const id of batch.members) {
195
+ const record = snapshot.reminders.find(item => item.id === id);
196
+ if (record && record.phase === 'intent') { record.phase = 'unknown'; record.unknownAt = batch.unknownAt; }
197
+ }
198
+ note(snapshot, nowMs, 'remind-unknown', { batch: batch.id, ids: batch.members.slice(), detail: 'no correlated wake within 60s; no automatic resend' });
199
+ swept.push(batch.id);
200
+ }
201
+ return swept;
202
+ }
203
+
204
+ // 4.1: commit each due Reminder's queue identity, order and enqueue time. Runs for both Pulse shapes and
205
+ // is independent of PM availability and Standby; a repeated scan never creates a second queue entry.
206
+ function admitReminders(snapshot, request, nowMs) {
207
+ const pulseStartedAt = typeof request.pulseStartedAt === 'string' ? request.pulseStartedAt : '';
208
+ const startedMs = Number.isFinite(msOf(pulseStartedAt)) ? msOf(pulseStartedAt) : null;
209
+ const swept = sweepStaleIntents(snapshot, nowMs);
210
+ const due = snapshot.reminders
211
+ .filter(record => record.phase === 'scheduled' && Number.isFinite(msOf(record.dueAt)) && msOf(record.dueAt) <= nowMs)
212
+ .sort((a, b) => (msOf(a.dueAt) - msOf(b.dueAt)) || (a.seq - b.seq));
213
+ const admitted = [];
214
+ const overdue = [];
215
+ for (const record of due) {
216
+ const dueMs = msOf(record.dueAt);
217
+ record.phase = 'queued';
218
+ record.queuedAt = iso(nowMs);
219
+ record.queueSeq = snapshot.sequences.queue;
220
+ snapshot.sequences.queue += 1;
221
+ record.overdue = (startedMs !== null && dueMs < startedMs) || nowMs - dueMs > OVERDUE_LAG_MS;
222
+ if (record.overdue) overdue.push(record.id);
223
+ admitted.push(record.id);
224
+ }
225
+ if (pulseStartedAt && (admitted.length || swept.length)) {
226
+ snapshot.pulse = { startedAt: pulseStartedAt, lastAdmitAt: iso(nowMs) };
227
+ }
228
+ if (admitted.length) {
229
+ note(snapshot, nowMs, 'remind-admit', { ids: admitted, detail: `due <= ${iso(nowMs)}; overdue ${overdue.length}` });
230
+ }
231
+ return {
232
+ ok: true, now: iso(nowMs),
233
+ admitted, overdue, swept,
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
+ outstanding: outstandingBatch(snapshot)?.id ?? null,
238
+ };
239
+ }
240
+
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
+ function intentBatch(snapshot, request, nowMs) {
245
+ const swept = sweepStaleIntents(snapshot, nowMs);
246
+ const outstanding = outstandingBatch(snapshot);
247
+ if (outstanding) {
248
+ return {
249
+ ok: true, action: 'wait', now: iso(nowMs), batch: outstanding.id, swept,
250
+ reason: outstanding.phase === 'unknown'
251
+ ? `batch ${outstanding.id} is unknown: inspect it and run \`team remind resolve ${outstanding.id} --ack-unknown\`; nothing is resent`
252
+ : `batch ${outstanding.id} is already in flight (intent at ${outstanding.intentAt})`,
253
+ };
254
+ }
255
+ const queued = snapshot.reminders
256
+ .filter(record => record.phase === 'queued')
257
+ .sort((a, b) => ((a.queueSeq ?? 0) - (b.queueSeq ?? 0)) || (a.seq - b.seq));
258
+ if (!queued.length) return { ok: true, action: 'idle', now: iso(nowMs), swept };
259
+ const session = typeof request.session === 'string' ? request.session.trim() : '';
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)' };
261
+ const seq = snapshot.sequences.batch;
262
+ snapshot.sequences.batch = seq + 1;
263
+ const batch = {
264
+ id: `bat-${snapshot.project.id}-${seq}`,
265
+ seq,
266
+ nonce: randomUUID(),
267
+ phase: 'intent',
268
+ intentAt: iso(nowMs),
269
+ // Bound before the call: whatever the snapshot says now is the only generation this wake may clear.
270
+ generation: snapshot.standby.on ? snapshot.standby.generation : 'off',
271
+ target: { session, pid: Number.isSafeInteger(request.pid) ? request.pid : null },
272
+ members: queued.map(record => record.id),
273
+ right: 'unspent',
274
+ rightSpentBy: null,
275
+ attempts: 1,
276
+ lastError: null,
277
+ observedAt: null,
278
+ unknownAt: null,
279
+ resolvedAt: null,
280
+ outcome: null,
281
+ };
282
+ for (const record of queued) {
283
+ record.phase = 'intent';
284
+ record.batchId = batch.id;
285
+ record.intentAt = batch.intentAt;
286
+ }
287
+ snapshot.batches.push(batch);
288
+ note(snapshot, nowMs, 'remind-intent', {
289
+ batch: batch.id, ids: batch.members.slice(), detail: `standby generation ${batch.generation}; session ${session}`,
290
+ });
291
+ return {
292
+ ok: true, action: 'send', now: iso(nowMs), swept,
293
+ batch: {
294
+ id: batch.id, nonce: batch.nonce, generation: batch.generation, intentAt: batch.intentAt, session,
295
+ members: queued.map(record => ({
296
+ id: record.id, dueAt: record.dueAt, enqueuedAt: record.queuedAt, overdue: Boolean(record.overdue),
297
+ source: record.source, task: record.task, key: record.key, message: record.message,
298
+ })),
299
+ },
300
+ };
301
+ }
302
+
303
+ // 3.2: the one atomic outcome. Observation, the consumed right, the generation-checked automatic off and
304
+ // the audit all commit in this same snapshot, so a replay is a no-op and a newer generation always wins.
305
+ function observeBatch(snapshot, request, nowMs) {
306
+ const id = String(request.id ?? '');
307
+ const batch = findBatch(snapshot, id);
308
+ if (!batch) {
309
+ const parsed = parseBatchId(id, snapshot.project.id);
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
+ };
317
+ }
318
+ if (typeof request.nonce !== 'string' || request.nonce !== batch.nonce) {
319
+ return { ok: false, refusal: 'nonce-mismatch', reason: `the observed message does not carry the nonce of ${batch.id} (identity unknown; no right consumed)` };
320
+ }
321
+ const session = typeof request.session === 'string' ? request.session.trim() : '';
322
+ if (!session || batch.target?.session !== session) {
323
+ return { ok: false, refusal: 'session-mismatch', reason: `${batch.id} was frozen for session ${batch.target?.session ?? '(none)'}, not '${session || '(none)'}'` };
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
+ }
332
+ if (batch.phase === 'resolved') return { ok: false, refusal: 'already-resolved', reason: `${batch.id} was acknowledged as unknown; it cannot be reopened` };
333
+ if (batch.right === 'spent' || batch.phase === 'observed') {
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' };
335
+ }
336
+ if (batch.phase !== 'intent' && batch.phase !== 'unknown') {
337
+ return { ok: false, refusal: `bad-phase`, reason: `${batch.id} is ${batch.phase}; only an intent or an unknown batch can be observed` };
338
+ }
339
+ let standby = 'already-off';
340
+ if (batch.generation === 'off') standby = 'already-off';
341
+ else if (!snapshot.standby.on) standby = 'already-off';
342
+ else if (snapshot.standby.generation === batch.generation) {
343
+ snapshot.standby = { on: false, generation: snapshot.standby.generation, reason: null, since: iso(nowMs), migrated: true };
344
+ standby = 'auto-off';
345
+ } else standby = 'generation-ambiguous';
346
+ batch.phase = 'observed';
347
+ batch.observedAt = iso(nowMs);
348
+ batch.right = 'spent';
349
+ batch.rightSpentBy = 'wake';
350
+ batch.outcome = { standby };
351
+ for (const mid of batch.members) {
352
+ const record = snapshot.reminders.find(item => item.id === mid);
353
+ if (!record) continue;
354
+ record.phase = 'observed';
355
+ record.observedAt = batch.observedAt;
356
+ record.endedAt = batch.observedAt;
357
+ }
358
+ note(snapshot, nowMs, 'remind-observed', {
359
+ batch: batch.id, ids: batch.members.slice(),
360
+ sources: batch.members.map(mid => snapshot.reminders.find(item => item.id === mid)?.source ?? '?'),
361
+ detail: `standby ${standby} (bound generation ${batch.generation})`,
362
+ });
363
+ return { ok: true, outcome: 'observed', now: iso(nowMs), batch: batch.id, standby, generation: batch.generation, ids: batch.members.slice() };
364
+ }
365
+
366
+ // A synchronous refusal from the session API is not a receipt: the batch becomes unknown (visible, no
367
+ // automatic resend) so the next delivery waits for an operator instead of blindly sending it twice.
368
+ function failBatch(snapshot, request, nowMs) {
369
+ const id = String(request.id ?? '');
370
+ const batch = findBatch(snapshot, id);
371
+ if (!batch) return { ok: false, refusal: 'unknown-batch', reason: `'${id}' is not a batch of this project` };
372
+ if (typeof request.nonce !== 'string' || request.nonce !== batch.nonce) {
373
+ return { ok: false, refusal: 'nonce-mismatch', reason: `the failed attempt does not carry the nonce of ${batch.id}` };
374
+ }
375
+ if (batch.right === 'spent') {
376
+ return { ok: true, outcome: 'already-observed', now: iso(nowMs), batch: batch.id, reason: 'a wake was already observed; the failure is recorded but nothing is reopened' };
377
+ }
378
+ if (batch.phase !== 'intent') {
379
+ return { ok: true, outcome: 'already-unknown', now: iso(nowMs), batch: batch.id, reason: `${batch.id} is already ${batch.phase}` };
380
+ }
381
+ const reason = String(request.reason ?? '').slice(0, 400) || 'the session API refused the message';
382
+ batch.phase = 'unknown';
383
+ batch.unknownAt = iso(nowMs);
384
+ batch.attempts = (batch.attempts ?? 1) + 1;
385
+ batch.lastError = reason;
386
+ for (const mid of batch.members) {
387
+ const record = snapshot.reminders.find(item => item.id === mid);
388
+ if (record && record.phase === 'intent') { record.phase = 'unknown'; record.unknownAt = batch.unknownAt; }
389
+ }
390
+ note(snapshot, nowMs, 'remind-send-failed', { batch: batch.id, ids: batch.members.slice(), detail: reason });
391
+ return { ok: true, outcome: 'unknown', now: iso(nowMs), batch: batch.id, ids: batch.members.slice(), reason };
392
+ }
393
+
394
+ // The operator's explicit acknowledgment of an inspected unknown batch: close every member, burn the one
395
+ // remaining right and do not resend. It does not assert whether delivery happened.
396
+ function resolveBatch(snapshot, request, nowMs) {
397
+ const id = String(request.id ?? '');
398
+ const batch = findBatch(snapshot, id);
399
+ if (!batch) return { ok: false, refusal: 'unknown-batch', reason: `'${id}' is not a batch of this project` };
400
+ if (batch.phase === 'resolved') {
401
+ return { ok: true, outcome: 'already-resolved', now: iso(nowMs), batch: batch.id, ids: batch.members.slice() };
402
+ }
403
+ if (batch.phase === 'intent') {
404
+ return { ok: false, refusal: 'in-flight', reason: `${batch.id} is still an intent (no observation yet); wait for the 60s deadline or check ${snapshot.project.stateRoot}/reminders/state.json` };
405
+ }
406
+ if (batch.phase === 'observed') {
407
+ return { ok: false, refusal: 'already-observed', reason: `${batch.id} was observed at ${batch.observedAt}; there is nothing uncertain to acknowledge` };
408
+ }
409
+ batch.phase = 'resolved';
410
+ batch.resolvedAt = iso(nowMs);
411
+ batch.right = 'spent';
412
+ batch.rightSpentBy = 'resolve';
413
+ for (const mid of batch.members) {
414
+ const record = snapshot.reminders.find(item => item.id === mid);
415
+ if (!record) continue;
416
+ record.phase = 'resolved';
417
+ record.resolvedAt = batch.resolvedAt;
418
+ record.endedAt = batch.resolvedAt;
419
+ }
420
+ note(snapshot, nowMs, 'remind-resolved', { batch: batch.id, ids: batch.members.slice(), detail: 'operator acknowledged an unknown batch; nothing resent' });
421
+ return { ok: true, outcome: 'resolved', now: iso(nowMs), batch: batch.id, ids: batch.members.slice(), right: 'spent' };
422
+ }
423
+
138
424
  // ---------------------------------------------------------------- views (derived, never stored)
139
425
  function viewOf(record, nowMs) {
140
426
  if (record.phase === 'scheduled') return msOf(record.dueAt) <= nowMs ? 'derived-due' : 'scheduled';
@@ -158,6 +444,9 @@ function viewOfRecord(record, nowMs) {
158
444
  message: record.message,
159
445
  endedAt: record.endedAt ?? null,
160
446
  batchId: record.batchId ?? null,
447
+ queuedAt: record.queuedAt ?? null,
448
+ intentAt: record.intentAt ?? null,
449
+ overdue: record.overdue === undefined ? null : Boolean(record.overdue),
161
450
  };
162
451
  }
163
452
 
@@ -209,6 +498,47 @@ export function validateReminders(snapshot, failWith) {
209
498
  if (isTerminal(record.phase) && (typeof record.endedAt !== 'string' || !Number.isFinite(msOf(record.endedAt)))) {
210
499
  bad(`terminal Reminder ${record.id} has no ended time`);
211
500
  }
501
+ if (record.batchId !== null && record.batchId !== undefined && typeof record.batchId !== 'string') {
502
+ bad(`Reminder ${record.id} has an unreadable batch id`);
503
+ }
504
+ for (const field of ['queuedAt', 'intentAt', 'unknownAt']) {
505
+ if (record[field] !== undefined && record[field] !== null && !Number.isFinite(msOf(record[field]))) {
506
+ bad(`Reminder ${record.id} has an unreadable ${field}`);
507
+ }
508
+ }
509
+ }
510
+ // The batches are the delivery truth, so they are validated with the same care: a batch that names a
511
+ // member it does not own, a right that is neither spent nor unspent, or a sequence at the high-water
512
+ // would let a resend decision be made from a contradiction.
513
+ const batchWater = snapshot.sequences.batch;
514
+ const batchIds = new Set();
515
+ for (const batch of snapshot.batches) {
516
+ if (typeof batch.id !== 'string') bad('a batch record has no id');
517
+ const parsed = parseBatchId(batch.id, snapshot.project.id);
518
+ if (!parsed) bad(`invalid batch id: ${batch.id}`);
519
+ if (parsed.seq >= batchWater) bad(`batch ${batch.id} claims sequence ${parsed.seq} at or above the issued high-water ${batchWater - 1}`);
520
+ if (batch.seq !== parsed.seq) bad(`batch ${batch.id} carries seq ${batch.seq}, its id says ${parsed.seq}`);
521
+ if (batchIds.has(batch.id)) bad(`duplicate batch id: ${batch.id}`);
522
+ batchIds.add(batch.id);
523
+ if (!BATCH_PHASES.has(batch.phase)) bad(`batch ${batch.id} has an unknown phase: ${batch.phase}`);
524
+ if (typeof batch.nonce !== 'string' || !batch.nonce) bad(`batch ${batch.id} has no correlation nonce`);
525
+ if (typeof batch.intentAt !== 'string' || !Number.isFinite(msOf(batch.intentAt))) bad(`batch ${batch.id} has an unreadable intent time`);
526
+ if (!Number.isSafeInteger(batch.generation) && batch.generation !== 'off') bad(`batch ${batch.id} has an unreadable Standby binding`);
527
+ if (batch.right !== 'unspent' && batch.right !== 'spent') bad(`batch ${batch.id} has an unreadable right: ${batch.right}`);
528
+ if (batch.rightSpentBy !== null && !['wake', 'resolve'].includes(batch.rightSpentBy)) bad(`batch ${batch.id} has an unreadable right holder: ${batch.rightSpentBy}`);
529
+ if (!Number.isSafeInteger(batch.attempts) || batch.attempts < 1) bad(`batch ${batch.id} has an unreadable attempt count`);
530
+ if (!Array.isArray(batch.members) || !batch.members.length) bad(`batch ${batch.id} has no members`);
531
+ for (const mid of batch.members) {
532
+ const record = snapshot.reminders.find(item => item.id === mid);
533
+ if (!record) bad(`batch ${batch.id} names a member that is not in the snapshot: ${mid}`);
534
+ else if (record.batchId !== batch.id) bad(`batch ${batch.id} names ${mid}, whose record says ${record.batchId}`);
535
+ }
536
+ }
537
+ for (const record of snapshot.reminders) {
538
+ if (record.batchId === null || record.batchId === undefined) continue;
539
+ const batch = snapshot.batches.find(item => item.id === record.batchId);
540
+ if (!batch) bad(`Reminder ${record.id} names a batch that is not in the snapshot: ${record.batchId}`);
541
+ else if (!batch.members.includes(record.id)) bad(`Reminder ${record.id} claims ${record.batchId}, which does not list it`);
212
542
  }
213
543
  if (snapshot.audit.some(entry => !entry || typeof entry !== 'object' || typeof entry.op !== 'string' ||
214
544
  typeof entry.at !== 'string' || !Number.isFinite(msOf(entry.at)))) {
@@ -232,26 +562,50 @@ function parseId(id, projectId) {
232
562
  function endedMs(record) { return msOf(record.endedAt ?? record.createdAt); }
233
563
 
234
564
  function pruneHistory(snapshot, nowMs) {
235
- const terminal = snapshot.reminders.filter(record => isTerminal(record.phase));
236
- 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));
237
584
  const keep = new Set();
238
585
  for (let i = 0; i < ranked.length; i++) {
239
586
  if (i < TERMINAL_KEEP && nowMs - endedMs(ranked[i]) <= RETENTION_MS) keep.add(ranked[i].id);
240
587
  }
241
- const dropped = terminal.filter(record => !keep.has(record.id));
242
- if (dropped.length) {
243
- const ids = new Set(dropped.map(record => record.id));
244
- snapshot.reminders = snapshot.reminders.filter(record => !ids.has(record.id));
245
- 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;
246
600
  snapshot.audit.push({
247
- at: iso(nowMs), op: 'retention-prune', count: dropped.length,
248
- ids: dropped.slice().sort((a, b) => b.seq - a.seq).slice(0, 20).map(record => record.id),
249
- 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`,
250
604
  });
251
605
  }
252
606
  const audit = snapshot.audit.filter(entry => nowMs - msOf(entry.at) <= RETENTION_MS);
253
607
  snapshot.audit = audit.length > AUDIT_KEEP ? audit.slice(audit.length - AUDIT_KEEP) : audit;
254
- return dropped.length;
608
+ return droppedCount;
255
609
  }
256
610
 
257
611
  function note(snapshot, nowMs, op, fields) {
@@ -400,6 +754,9 @@ function listReminders(snapshot, request, nowMs) {
400
754
  const terminal = snapshot.reminders.filter(record => isTerminal(record.phase))
401
755
  .sort((a, b) => (endedMs(b) - endedMs(a)) || (b.seq - a.seq))
402
756
  .map(record => viewOfRecord(record, nowMs));
757
+ const batchCounts = { intent: 0, observed: 0, unknown: 0, resolved: 0 };
758
+ for (const batch of snapshot.batches) batchCounts[batch.phase] = (batchCounts[batch.phase] ?? 0) + 1;
759
+ const outstanding = outstandingBatch(snapshot);
403
760
  return {
404
761
  ok: true,
405
762
  now: iso(nowMs),
@@ -412,6 +769,8 @@ function listReminders(snapshot, request, nowMs) {
412
769
  terminal: all ? terminal : [],
413
770
  terminalTotal: terminal.length,
414
771
  terminalShown: all,
772
+ outstanding: outstanding ? { id: outstanding.id, phase: outstanding.phase, intentAt: outstanding.intentAt, members: outstanding.members.slice() } : null,
773
+ batchCounts,
415
774
  };
416
775
  }
417
776
 
@@ -421,11 +780,19 @@ export function applyReminder(snapshot, request, nowMs) {
421
780
  case 'remind-list': return listReminders(snapshot, request, nowMs);
422
781
  case 'remind-show': return showReminder(snapshot, request, nowMs);
423
782
  case 'remind-cancel': return cancelReminder(snapshot, request, nowMs);
783
+ case 'remind-admit': return admitReminders(snapshot, request, nowMs);
784
+ case 'remind-intent': return intentBatch(snapshot, request, nowMs);
785
+ case 'remind-observe': return observeBatch(snapshot, request, nowMs);
786
+ case 'remind-fail': return failBatch(snapshot, request, nowMs);
787
+ case 'remind-resolve': return resolveBatch(snapshot, request, nowMs);
424
788
  default: fail(`unknown reminder operation: ${request.op}`);
425
789
  }
426
790
  }
427
791
 
428
- export const REMIND_OPS = new Set(['remind-add', 'remind-list', 'remind-show', 'remind-cancel']);
792
+ export const REMIND_OPS = new Set([
793
+ 'remind-add', 'remind-list', 'remind-show', 'remind-cancel',
794
+ 'remind-admit', 'remind-intent', 'remind-observe', 'remind-fail', 'remind-resolve',
795
+ ]);
429
796
 
430
797
  // ---------------------------------------------------------------- presentation
431
798
  // Tokens (id, phase/view names, source, times) stay machine-shaped: they are the same words the spec and
@@ -470,6 +837,12 @@ function renderList(result) {
470
837
  `提醒 · ${activeN} 条活跃 · 已签发 ${result.highWater} · 已修剪 ${result.pruned} · 现在 ${result.now}`,
471
838
  `视图 ${VIEWS.map(view => `${view}=${c[view] ?? 0}`).join(' ')}`,
472
839
  ];
840
+ if (result.outstanding) {
841
+ const ob = result.outstanding;
842
+ lines.push(ob.phase === 'unknown'
843
+ ? `批次 ${ob.id} · unknown(未确认送达:检查后 team remind resolve ${ob.id} --ack-unknown;不会自动重发)`
844
+ : `批次 ${ob.id} · intent(已冻结,等唤醒回执;冻结于 ${ob.intentAt})`);
845
+ }
473
846
  if (!activeN && !result.terminalTotal) {
474
847
  lines.push('(还没有提醒:team remind add --after 20m --message "…")');
475
848
  return lines.join('\n') + '\n';
@@ -495,16 +868,29 @@ function renderShow(result) {
495
868
  if (!result.ok) return `team remind show:${result.reason}\n`;
496
869
  const record = result.reminder;
497
870
  const ended = record.endedAt ? `\n 结束 ${record.endedAt}` : '';
871
+ const queued = record.queuedAt ? `\n 入队 ${record.queuedAt}${record.overdue ? '(补发:到期时巡检没在看)' : ''}` : '';
872
+ const batch = record.batchId ? `\n 批次 ${record.batchId}` : '';
498
873
  return [
499
874
  `${record.id} · ${record.view}(phase ${record.phase})`,
500
875
  ` 到期 ${record.dueAt}`,
501
876
  ` 创建 ${record.createdAt}${ended}`,
502
877
  ` 视图 ${record.view}`,
503
878
  ` 归属 owner ${record.owner}${record.key ? ` · key ${record.key}` : ''} · 来源 ${record.source}${record.task ? ` · task ${record.task}` : ''}`,
879
+ `${queued}${batch}`.replace(/^\n/, ''),
504
880
  ' 正文(逐字,未截断):',
505
881
  record.message,
506
882
  '',
507
- ].join('\n');
883
+ ].filter(line => line !== '').join('\n');
884
+ }
885
+
886
+ function renderResolve(result) {
887
+ if (result.outcome === 'resolved') {
888
+ return `已确认未知批次 ${result.batch}(${result.ids.length} 条:${result.ids.join(' ')}):已关闭、不再重发,也不声称送达过\n`;
889
+ }
890
+ if (result.outcome === 'already-resolved') {
891
+ return `批次 ${result.batch} 早已确认过(${result.ids.length} 条);这次没有改动\n`;
892
+ }
893
+ return `team remind resolve:${result.reason}\n`;
508
894
  }
509
895
 
510
896
  function renderCancel(result) {
@@ -524,6 +910,7 @@ export function renderRemind(op, result) {
524
910
  case 'remind-list': return renderList(result);
525
911
  case 'remind-show': return renderShow(result);
526
912
  case 'remind-cancel': return renderCancel(result);
913
+ case 'remind-resolve': return renderResolve(result);
527
914
  default: return JSON.stringify(result) + '\n';
528
915
  }
529
916
  }
@@ -0,0 +1,105 @@
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: [], recoveryRequired: false, recoveryIds: [] })}\n`);
74
+ return;
75
+ }
76
+ const due = seen.reminders.due.length;
77
+ const stale = seen.reminders.staleIntent.length;
78
+ if (!due && !stale) {
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`);
81
+ return;
82
+ }
83
+ const result = await request({ ...context, stateRoot: seen.stateRoot }, {
84
+ op: 'remind-admit',
85
+ pulseStartedAt: opts.pulseStarted || new Date().toISOString(),
86
+ });
87
+ const admitted = result.admitted ?? [];
88
+ const swept = result.swept ?? [];
89
+ if (admitted.length || swept.length) {
90
+ log(seen.stateRoot, `admit n=${admitted.length} overdue=${(result.overdue ?? []).length} ` +
91
+ `ids=${admitted.join('|') || '-'} unknown=${swept.join('|') || '-'} queue=${result.queue}`);
92
+ }
93
+ result.recoveryRequired = (result.queue ?? 0) > 0 && !result.outstanding;
94
+ result.recoveryIds = result.recoveryRequired ? (result.queuedIds ?? []) : [];
95
+ if (opts.json) process.stdout.write(`${JSON.stringify(result)}\n`);
96
+ else if (!opts.quiet && admitted.length) {
97
+ process.stdout.write(`remind: 到点入队 ${admitted.length} 条(${admitted.join(' ')})\n`);
98
+ }
99
+ }
100
+
101
+ main().catch(e => {
102
+ const message = String((e && e.message) || e);
103
+ process.stderr.write(/^remind-tick:/.test(message) ? `${message}\n` : `remind-tick: ${message}\n`);
104
+ process.exitCode = 1;
105
+ });