teamsmith 0.4.5 → 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 (43) hide show
  1. package/README.md +4 -4
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +13 -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/state-authority.mjs +265 -17
  24. package/skills/teamsmith/scripts/strings/commands.tsv +3 -3
  25. package/skills/teamsmith/scripts/strings/help.en.tsv +12 -12
  26. package/skills/teamsmith/scripts/strings/help.zh.tsv +12 -12
  27. package/skills/teamsmith/scripts/team +3 -3
  28. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +2 -3
  29. package/skills/teamsmith/templates/pm-prompt.md.tmpl +11 -5
  30. package/skills/teamsmith/tests/death-cause.sh +5 -0
  31. package/skills/teamsmith/tests/help-surface.sh +15 -150
  32. package/skills/teamsmith/tests/isolation-ledger.sh +85 -0
  33. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +17 -1
  34. package/skills/teamsmith/tests/live-capture-probe.sh +12 -2
  35. package/skills/teamsmith/tests/pulse-nudge-key.sh +5 -0
  36. package/skills/teamsmith/tests/remind-delivery-node.mjs +176 -0
  37. package/skills/teamsmith/tests/remind-delivery.sh +611 -0
  38. package/skills/teamsmith/tests/section-paths.tsv +6 -6
  39. package/skills/teamsmith/tests/smoke.sh +397 -107
  40. package/skills/teamsmith/tests/state-authority.sh +246 -26
  41. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +58 -8
  42. package/skills/teamsmith/tests/tmux-identity-leak.sh +12 -16
  43. package/skills/teamsmith-init/SKILL.md +1 -1
@@ -679,3 +679,54 @@ export function runTick(
679
679
  child.on('close', (code) => done(code === 0))
680
680
  })
681
681
  }
682
+
683
+ /**
684
+ * One lightweight Reminder due tick (agent-self-reminder 4.1). It is NOT a patrol: `remind-tick.mjs`
685
+ * reads one bounded snapshot, commits due queue entries under the authority lock only when something is
686
+ * actually due, and never runs the project scan. One child per interval, asynchronous for the same
687
+ * reason the patrol tick is: a due tick must not freeze the console's input line.
688
+ */
689
+ export function runRemindTick(
690
+ script: string,
691
+ root: string,
692
+ stateDir: string,
693
+ pulseStartedAt: string,
694
+ tickLog: string,
695
+ timeoutMs = 30000,
696
+ ): Promise<{ ok: boolean; output: string }> {
697
+ return new Promise((resolve) => {
698
+ let child: ReturnType<typeof spawn>
699
+ try {
700
+ child = spawn(process.execPath, [
701
+ script, '--root', root, '--state-dir', stateDir, '--pulse-started', pulseStartedAt, '--quiet',
702
+ ], { cwd: root, env: cleanIdentityEnv(), stdio: ['ignore', 'pipe', 'pipe'] })
703
+ } catch (e) {
704
+ resolve({ ok: false, output: (e as Error).message })
705
+ return
706
+ }
707
+ let out = ''
708
+ let settled = false
709
+ const done = (ok: boolean): void => {
710
+ if (settled) return
711
+ settled = true
712
+ clearTimeout(timer)
713
+ // Successful quiet ticks say nothing: only a failure (or an admission line) earns a log line.
714
+ if (out.trim()) {
715
+ try { appendFileSync(tickLog, `${new Date().toISOString()} remind-tick: ${out}`) } catch { /* a log that cannot be written must not kill the panel */ }
716
+ }
717
+ resolve({ ok, output: out })
718
+ }
719
+ const timer = setTimeout(() => {
720
+ try {
721
+ child.kill('SIGKILL')
722
+ } catch {
723
+ /* already gone */
724
+ }
725
+ done(false)
726
+ }, timeoutMs)
727
+ child.stdout?.on('data', (d: Buffer) => { out += String(d) })
728
+ child.stderr?.on('data', (d: Buffer) => { out += String(d) })
729
+ child.on('error', () => done(false))
730
+ child.on('close', (code) => done(code === 0))
731
+ })
732
+ }
@@ -1343,6 +1343,15 @@ function replyRowLabel(e: ReplyEntry): string {
1343
1343
  return e.available ? `#${e.no} ${e.title}` : ''
1344
1344
  }
1345
1345
 
1346
+ /** Reader's local clock, `MM-DD HH:MM`: when a reply was published, in the list itself. */
1347
+ function replyTimeLabel(at: string | undefined): string {
1348
+ if (!at) return ''
1349
+ const when = new Date(at)
1350
+ if (Number.isNaN(when.getTime())) return ''
1351
+ const pad = (n: number): string => String(n).padStart(2, '0')
1352
+ return `${pad(when.getMonth() + 1)}-${pad(when.getDate())} ${pad(when.getHours())}:${pad(when.getMinutes())}`
1353
+ }
1354
+
1346
1355
  /** The nav row of page 5: Older / Newer / `r` (the same actions `←`/`→` and `r` fire). */
1347
1356
  function replyNavLine(ctx: Ctx, innerW: number): PlacedLine {
1348
1357
  const { s } = ctx
@@ -1419,6 +1428,7 @@ function replyListBlock(ctx: Ctx): Block | null {
1419
1428
  seg(head, 'accent'),
1420
1429
  seg(replyRowLabel(e), active ? 'selected' : 'text'),
1421
1430
  seg(` · ${e.from}`, 'dim'),
1431
+ ...(replyTimeLabel(e.at) ? [seg(` · ${replyTimeLabel(e.at)}`, 'dim')] : []),
1422
1432
  )
1423
1433
  : ln(
1424
1434
  seg(head, 'accent'),
@@ -41,6 +41,7 @@ import {
41
41
  findTeamCli,
42
42
  loadPanelData,
43
43
  panelDirOf,
44
+ runRemindTick,
44
45
  runTick,
45
46
  type BlockName,
46
47
  } from './data.js'
@@ -287,6 +288,30 @@ async function runTickIfDue(): Promise<void> {
287
288
  await runTick(teamCli, root, tickLog)
288
289
  }
289
290
 
291
+ // ---------------------------------------------------------------- the lightweight Reminder due tick
292
+ // agent-self-reminder 4.1: apart from (and much more often than) the full patrol, both pulse shapes own a
293
+ // ~10s due check. It reads one bounded snapshot and only takes the authority lock when something is due;
294
+ // it never scans the project, never starts the patrol and never calls a model.
295
+ const remindEvery = Math.max(1, Number(process.env.TEAM_REMIND_TICK_SECS ?? 10) || 10)
296
+ const remindStartedAt = new Date().toISOString()
297
+ const remindScript = teamCli ? join(dirname(teamCli), 'remind-tick.mjs') : ''
298
+ let lastRemind = 0
299
+
300
+ function remindDue(): boolean {
301
+ if (noPulse || !remindScript) return false
302
+ const now = Date.now()
303
+ if (lastRemind === 0 || now - lastRemind >= remindEvery * 1000) {
304
+ lastRemind = now
305
+ return true
306
+ }
307
+ return false
308
+ }
309
+
310
+ async function runRemindIfDue(): Promise<void> {
311
+ if (!remindDue()) return
312
+ await runRemindTick(remindScript, root, stateDir, remindStartedAt, tickLog)
313
+ }
314
+
290
315
  function frameOf(res: DataResult, activity: boolean, scroll?: number): FrameInput {
291
316
  return {
292
317
  panel: res.data ?? { project: '', timestamp: '', interval: 0 },
@@ -396,6 +421,7 @@ async function main(): Promise<void> {
396
421
  // reexec); this branch serves a direct bundle invocation and keeps the same cadence.
397
422
  for (;;) {
398
423
  await runTickIfDue()
424
+ await runRemindIfDue()
399
425
  sleepSync(Math.max(1, tickEvery || refresh) * 1000)
400
426
  }
401
427
  }
@@ -485,6 +511,7 @@ async function main(): Promise<void> {
485
511
 
486
512
  const reload = (): FrameInput => {
487
513
  void runTickIfDue()
514
+ void runRemindIfDue()
488
515
  void cache.refresh().then(adopt)
489
516
  return current
490
517
  }
@@ -10,13 +10,23 @@
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 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
+ const OBSERVE_DEADLINE_MS = 60000; // after intent, no correlated event within 60s = unknown, never a resend
29
+ const OVERDUE_LAG_MS = 30000; // normal polling delay is not overdue; 30s of admission lag is
20
30
  // Terminal = the outcome is known and the reminder can no longer fire. A key survives `unknown` (a
21
31
  // delivery attempt is outstanding, so the logical reminder is still "in play") and is released by any
22
32
  // terminal phase (design: "A key remains reserved for scheduled, queued, intent and unknown records").
@@ -135,6 +145,274 @@ function normSource(source) {
135
145
  return { source: value };
136
146
  }
137
147
 
148
+ // ---------------------------------------------------------------- delivery (P423 · 3.1/3.2/4.1)
149
+ // `peek` is the only classification a caller may do without the lock: it answers "is there anything to
150
+ // commit right now" from a whole snapshot read (rename is atomic, so an unlocked read never sees half a
151
+ // file). Every decision that changes the snapshot still runs inside the transaction below.
152
+ export function peekReminders(snapshot, nowMs) {
153
+ if (!snapshot || !Array.isArray(snapshot.reminders)) return { due: [], queued: [], staleIntent: [] };
154
+ const due = [];
155
+ const queued = [];
156
+ const staleIntent = [];
157
+ for (const record of snapshot.reminders) {
158
+ if (record.phase === 'scheduled' && Number.isFinite(msOf(record.dueAt)) && msOf(record.dueAt) <= nowMs) due.push(record.id);
159
+ if (record.phase === 'queued') queued.push(record.id);
160
+ }
161
+ for (const batch of Array.isArray(snapshot.batches) ? snapshot.batches : []) {
162
+ if (batch.phase === 'intent' && Number.isFinite(msOf(batch.intentAt)) && nowMs - msOf(batch.intentAt) >= OBSERVE_DEADLINE_MS) staleIntent.push(batch.id);
163
+ }
164
+ return { due, queued, staleIntent };
165
+ }
166
+
167
+ function findBatch(snapshot, id) {
168
+ return snapshot.batches.find(batch => batch.id === id) ?? null;
169
+ }
170
+
171
+ function parseBatchId(id, projectId) {
172
+ const prefix = `bat-${projectId}-`;
173
+ if (typeof id !== 'string' || !id.startsWith(prefix)) return null;
174
+ const tail = id.slice(prefix.length);
175
+ if (!/^[1-9][0-9]*$/.test(tail)) return null;
176
+ const seq = Number(tail);
177
+ return Number.isSafeInteger(seq) ? { seq } : null;
178
+ }
179
+
180
+ // The single outstanding delivery, if any. `unknown` is still outstanding: an operator has to inspect the
181
+ // batch before the next one may be frozen (design: "Only one batch is outstanding until observed or
182
+ // explicitly acknowledged"). A late correlated observation closes it too -- that is not a resend.
183
+ function outstandingBatch(snapshot) {
184
+ return snapshot.batches.find(batch => batch.phase === 'intent' || batch.phase === 'unknown') ?? null;
185
+ }
186
+
187
+ // After the deadline, an intent without a correlated event is `unknown`: absence of an event is not proof
188
+ // that nothing entered the session, so the members stop being independently sendable and nothing resends.
189
+ function sweepStaleIntents(snapshot, nowMs) {
190
+ const swept = [];
191
+ for (const batch of snapshot.batches) {
192
+ if (batch.phase !== 'intent' || !Number.isFinite(msOf(batch.intentAt))) continue;
193
+ if (nowMs - msOf(batch.intentAt) < OBSERVE_DEADLINE_MS) continue;
194
+ batch.phase = 'unknown';
195
+ batch.unknownAt = iso(nowMs);
196
+ for (const id of batch.members) {
197
+ const record = snapshot.reminders.find(item => item.id === id);
198
+ if (record && record.phase === 'intent') { record.phase = 'unknown'; record.unknownAt = batch.unknownAt; }
199
+ }
200
+ note(snapshot, nowMs, 'remind-unknown', { batch: batch.id, ids: batch.members.slice(), detail: 'no correlated wake within 60s; no automatic resend' });
201
+ swept.push(batch.id);
202
+ }
203
+ return swept;
204
+ }
205
+
206
+ // 4.1: commit each due Reminder's queue identity, order and enqueue time. Runs for both Pulse shapes and
207
+ // is independent of PM availability and Standby; a repeated scan never creates a second queue entry.
208
+ function admitReminders(snapshot, request, nowMs) {
209
+ const pulseStartedAt = typeof request.pulseStartedAt === 'string' ? request.pulseStartedAt : '';
210
+ const startedMs = Number.isFinite(msOf(pulseStartedAt)) ? msOf(pulseStartedAt) : null;
211
+ const swept = sweepStaleIntents(snapshot, nowMs);
212
+ const due = snapshot.reminders
213
+ .filter(record => record.phase === 'scheduled' && Number.isFinite(msOf(record.dueAt)) && msOf(record.dueAt) <= nowMs)
214
+ .sort((a, b) => (msOf(a.dueAt) - msOf(b.dueAt)) || (a.seq - b.seq));
215
+ const admitted = [];
216
+ const overdue = [];
217
+ for (const record of due) {
218
+ const dueMs = msOf(record.dueAt);
219
+ record.phase = 'queued';
220
+ record.queuedAt = iso(nowMs);
221
+ record.queueSeq = snapshot.sequences.queue;
222
+ snapshot.sequences.queue += 1;
223
+ record.overdue = (startedMs !== null && dueMs < startedMs) || nowMs - dueMs > OVERDUE_LAG_MS;
224
+ if (record.overdue) overdue.push(record.id);
225
+ admitted.push(record.id);
226
+ }
227
+ if (pulseStartedAt && (admitted.length || swept.length)) {
228
+ snapshot.pulse = { startedAt: pulseStartedAt, lastAdmitAt: iso(nowMs) };
229
+ }
230
+ if (admitted.length) {
231
+ note(snapshot, nowMs, 'remind-admit', { ids: admitted, detail: `due <= ${iso(nowMs)}; overdue ${overdue.length}` });
232
+ }
233
+ return {
234
+ ok: true, now: iso(nowMs),
235
+ admitted, overdue, swept,
236
+ queue: snapshot.reminders.filter(record => record.phase === 'queued').length,
237
+ outstanding: outstandingBatch(snapshot)?.id ?? null,
238
+ };
239
+ }
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.
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 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
+ const queued = snapshot.reminders
260
+ .filter(record => record.phase === 'queued')
261
+ .sort((a, b) => ((a.queueSeq ?? 0) - (b.queueSeq ?? 0)) || (a.seq - b.seq))
262
+ .slice(0, BATCH_LIMIT);
263
+ if (!queued.length) return { ok: true, action: 'idle', now: iso(nowMs), swept };
264
+ const session = typeof request.session === 'string' ? request.session.trim() : '';
265
+ if (!session) return { ok: false, refusal: 'bad-session', reason: 'the batch intent needs the verified PM session id (which session may observe the wake)' };
266
+ const seq = snapshot.sequences.batch;
267
+ snapshot.sequences.batch = seq + 1;
268
+ const batch = {
269
+ id: `bat-${snapshot.project.id}-${seq}`,
270
+ seq,
271
+ nonce: randomUUID(),
272
+ phase: 'intent',
273
+ intentAt: iso(nowMs),
274
+ // Bound before the call: whatever the snapshot says now is the only generation this wake may clear.
275
+ generation: snapshot.standby.on ? snapshot.standby.generation : 'off',
276
+ target: { session, pid: Number.isSafeInteger(request.pid) ? request.pid : null },
277
+ members: queued.map(record => record.id),
278
+ right: 'unspent',
279
+ rightSpentBy: null,
280
+ attempts: 1,
281
+ lastError: null,
282
+ observedAt: null,
283
+ unknownAt: null,
284
+ resolvedAt: null,
285
+ outcome: null,
286
+ };
287
+ for (const record of queued) {
288
+ record.phase = 'intent';
289
+ record.batchId = batch.id;
290
+ record.intentAt = batch.intentAt;
291
+ }
292
+ snapshot.batches.push(batch);
293
+ note(snapshot, nowMs, 'remind-intent', {
294
+ batch: batch.id, ids: batch.members.slice(), detail: `standby generation ${batch.generation}; session ${session}`,
295
+ });
296
+ return {
297
+ ok: true, action: 'send', now: iso(nowMs), swept,
298
+ batch: {
299
+ id: batch.id, nonce: batch.nonce, generation: batch.generation, intentAt: batch.intentAt, session,
300
+ members: queued.map(record => ({
301
+ id: record.id, dueAt: record.dueAt, enqueuedAt: record.queuedAt, overdue: Boolean(record.overdue),
302
+ source: record.source, task: record.task, key: record.key, message: record.message,
303
+ })),
304
+ },
305
+ };
306
+ }
307
+
308
+ // 3.2: the one atomic outcome. Observation, the consumed right, the generation-checked automatic off and
309
+ // the audit all commit in this same snapshot, so a replay is a no-op and a newer generation always wins.
310
+ function observeBatch(snapshot, request, nowMs) {
311
+ const id = String(request.id ?? '');
312
+ const batch = findBatch(snapshot, id);
313
+ if (!batch) {
314
+ 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` };
316
+ }
317
+ if (typeof request.nonce !== 'string' || request.nonce !== batch.nonce) {
318
+ return { ok: false, refusal: 'nonce-mismatch', reason: `the observed message does not carry the nonce of ${batch.id} (identity unknown; no right consumed)` };
319
+ }
320
+ const session = typeof request.session === 'string' ? request.session.trim() : '';
321
+ if (!session || batch.target?.session !== session) {
322
+ return { ok: false, refusal: 'session-mismatch', reason: `${batch.id} was frozen for session ${batch.target?.session ?? '(none)'}, not '${session || '(none)'}'` };
323
+ }
324
+ if (batch.phase === 'resolved') return { ok: false, refusal: 'already-resolved', reason: `${batch.id} was acknowledged as unknown; it cannot be reopened` };
325
+ if (batch.right === 'spent' || batch.phase === 'observed') {
326
+ 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' };
327
+ }
328
+ if (batch.phase !== 'intent' && batch.phase !== 'unknown') {
329
+ return { ok: false, refusal: `bad-phase`, reason: `${batch.id} is ${batch.phase}; only an intent or an unknown batch can be observed` };
330
+ }
331
+ let standby = 'already-off';
332
+ if (batch.generation === 'off') standby = 'already-off';
333
+ else if (!snapshot.standby.on) standby = 'already-off';
334
+ else if (snapshot.standby.generation === batch.generation) {
335
+ snapshot.standby = { on: false, generation: snapshot.standby.generation, reason: null, since: iso(nowMs), migrated: true };
336
+ standby = 'auto-off';
337
+ } else standby = 'generation-ambiguous';
338
+ batch.phase = 'observed';
339
+ batch.observedAt = iso(nowMs);
340
+ batch.right = 'spent';
341
+ batch.rightSpentBy = 'wake';
342
+ batch.outcome = { standby };
343
+ for (const mid of batch.members) {
344
+ const record = snapshot.reminders.find(item => item.id === mid);
345
+ if (!record) continue;
346
+ record.phase = 'observed';
347
+ record.observedAt = batch.observedAt;
348
+ record.endedAt = batch.observedAt;
349
+ }
350
+ note(snapshot, nowMs, 'remind-observed', {
351
+ batch: batch.id, ids: batch.members.slice(),
352
+ sources: batch.members.map(mid => snapshot.reminders.find(item => item.id === mid)?.source ?? '?'),
353
+ detail: `standby ${standby} (bound generation ${batch.generation})`,
354
+ });
355
+ return { ok: true, outcome: 'observed', now: iso(nowMs), batch: batch.id, standby, generation: batch.generation, ids: batch.members.slice() };
356
+ }
357
+
358
+ // A synchronous refusal from the session API is not a receipt: the batch becomes unknown (visible, no
359
+ // automatic resend) so the next delivery waits for an operator instead of blindly sending it twice.
360
+ function failBatch(snapshot, request, nowMs) {
361
+ const id = String(request.id ?? '');
362
+ const batch = findBatch(snapshot, id);
363
+ if (!batch) return { ok: false, refusal: 'unknown-batch', reason: `'${id}' is not a batch of this project` };
364
+ if (typeof request.nonce !== 'string' || request.nonce !== batch.nonce) {
365
+ return { ok: false, refusal: 'nonce-mismatch', reason: `the failed attempt does not carry the nonce of ${batch.id}` };
366
+ }
367
+ if (batch.right === 'spent') {
368
+ 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' };
369
+ }
370
+ if (batch.phase !== 'intent') {
371
+ return { ok: true, outcome: 'already-unknown', now: iso(nowMs), batch: batch.id, reason: `${batch.id} is already ${batch.phase}` };
372
+ }
373
+ const reason = String(request.reason ?? '').slice(0, 400) || 'the session API refused the message';
374
+ batch.phase = 'unknown';
375
+ batch.unknownAt = iso(nowMs);
376
+ batch.attempts = (batch.attempts ?? 1) + 1;
377
+ batch.lastError = reason;
378
+ for (const mid of batch.members) {
379
+ const record = snapshot.reminders.find(item => item.id === mid);
380
+ if (record && record.phase === 'intent') { record.phase = 'unknown'; record.unknownAt = batch.unknownAt; }
381
+ }
382
+ note(snapshot, nowMs, 'remind-send-failed', { batch: batch.id, ids: batch.members.slice(), detail: reason });
383
+ return { ok: true, outcome: 'unknown', now: iso(nowMs), batch: batch.id, ids: batch.members.slice(), reason };
384
+ }
385
+
386
+ // The operator's explicit acknowledgment of an inspected unknown batch: close every member, burn the one
387
+ // remaining right and do not resend. It does not assert whether delivery happened.
388
+ function resolveBatch(snapshot, request, nowMs) {
389
+ const id = String(request.id ?? '');
390
+ const batch = findBatch(snapshot, id);
391
+ if (!batch) return { ok: false, refusal: 'unknown-batch', reason: `'${id}' is not a batch of this project` };
392
+ if (batch.phase === 'resolved') {
393
+ return { ok: true, outcome: 'already-resolved', now: iso(nowMs), batch: batch.id, ids: batch.members.slice() };
394
+ }
395
+ if (batch.phase === 'intent') {
396
+ 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` };
397
+ }
398
+ if (batch.phase === 'observed') {
399
+ return { ok: false, refusal: 'already-observed', reason: `${batch.id} was observed at ${batch.observedAt}; there is nothing uncertain to acknowledge` };
400
+ }
401
+ batch.phase = 'resolved';
402
+ batch.resolvedAt = iso(nowMs);
403
+ batch.right = 'spent';
404
+ batch.rightSpentBy = 'resolve';
405
+ for (const mid of batch.members) {
406
+ const record = snapshot.reminders.find(item => item.id === mid);
407
+ if (!record) continue;
408
+ record.phase = 'resolved';
409
+ record.resolvedAt = batch.resolvedAt;
410
+ record.endedAt = batch.resolvedAt;
411
+ }
412
+ note(snapshot, nowMs, 'remind-resolved', { batch: batch.id, ids: batch.members.slice(), detail: 'operator acknowledged an unknown batch; nothing resent' });
413
+ return { ok: true, outcome: 'resolved', now: iso(nowMs), batch: batch.id, ids: batch.members.slice(), right: 'spent' };
414
+ }
415
+
138
416
  // ---------------------------------------------------------------- views (derived, never stored)
139
417
  function viewOf(record, nowMs) {
140
418
  if (record.phase === 'scheduled') return msOf(record.dueAt) <= nowMs ? 'derived-due' : 'scheduled';
@@ -158,6 +436,9 @@ function viewOfRecord(record, nowMs) {
158
436
  message: record.message,
159
437
  endedAt: record.endedAt ?? null,
160
438
  batchId: record.batchId ?? null,
439
+ queuedAt: record.queuedAt ?? null,
440
+ intentAt: record.intentAt ?? null,
441
+ overdue: record.overdue === undefined ? null : Boolean(record.overdue),
161
442
  };
162
443
  }
163
444
 
@@ -209,6 +490,48 @@ export function validateReminders(snapshot, failWith) {
209
490
  if (isTerminal(record.phase) && (typeof record.endedAt !== 'string' || !Number.isFinite(msOf(record.endedAt)))) {
210
491
  bad(`terminal Reminder ${record.id} has no ended time`);
211
492
  }
493
+ if (record.batchId !== null && record.batchId !== undefined && typeof record.batchId !== 'string') {
494
+ bad(`Reminder ${record.id} has an unreadable batch id`);
495
+ }
496
+ for (const field of ['queuedAt', 'intentAt', 'unknownAt']) {
497
+ if (record[field] !== undefined && record[field] !== null && !Number.isFinite(msOf(record[field]))) {
498
+ bad(`Reminder ${record.id} has an unreadable ${field}`);
499
+ }
500
+ }
501
+ }
502
+ // The batches are the delivery truth, so they are validated with the same care: a batch that names a
503
+ // member it does not own, a right that is neither spent nor unspent, or a sequence at the high-water
504
+ // would let a resend decision be made from a contradiction.
505
+ const batchWater = snapshot.sequences.batch;
506
+ const batchIds = new Set();
507
+ for (const batch of snapshot.batches) {
508
+ if (typeof batch.id !== 'string') bad('a batch record has no id');
509
+ const parsed = parseBatchId(batch.id, snapshot.project.id);
510
+ if (!parsed) bad(`invalid batch id: ${batch.id}`);
511
+ if (parsed.seq >= batchWater) bad(`batch ${batch.id} claims sequence ${parsed.seq} at or above the issued high-water ${batchWater - 1}`);
512
+ if (batch.seq !== parsed.seq) bad(`batch ${batch.id} carries seq ${batch.seq}, its id says ${parsed.seq}`);
513
+ if (batchIds.has(batch.id)) bad(`duplicate batch id: ${batch.id}`);
514
+ batchIds.add(batch.id);
515
+ if (!BATCH_PHASES.has(batch.phase)) bad(`batch ${batch.id} has an unknown phase: ${batch.phase}`);
516
+ if (typeof batch.nonce !== 'string' || !batch.nonce) bad(`batch ${batch.id} has no correlation nonce`);
517
+ if (typeof batch.intentAt !== 'string' || !Number.isFinite(msOf(batch.intentAt))) bad(`batch ${batch.id} has an unreadable intent time`);
518
+ if (!Number.isSafeInteger(batch.generation) && batch.generation !== 'off') bad(`batch ${batch.id} has an unreadable Standby binding`);
519
+ if (batch.right !== 'unspent' && batch.right !== 'spent') bad(`batch ${batch.id} has an unreadable right: ${batch.right}`);
520
+ if (batch.rightSpentBy !== null && !['wake', 'resolve'].includes(batch.rightSpentBy)) bad(`batch ${batch.id} has an unreadable right holder: ${batch.rightSpentBy}`);
521
+ if (!Number.isSafeInteger(batch.attempts) || batch.attempts < 1) bad(`batch ${batch.id} has an unreadable attempt count`);
522
+ 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
+ for (const mid of batch.members) {
525
+ const record = snapshot.reminders.find(item => item.id === mid);
526
+ if (!record) bad(`batch ${batch.id} names a member that is not in the snapshot: ${mid}`);
527
+ else if (record.batchId !== batch.id) bad(`batch ${batch.id} names ${mid}, whose record says ${record.batchId}`);
528
+ }
529
+ }
530
+ for (const record of snapshot.reminders) {
531
+ if (record.batchId === null || record.batchId === undefined) continue;
532
+ const batch = snapshot.batches.find(item => item.id === record.batchId);
533
+ if (!batch) bad(`Reminder ${record.id} names a batch that is not in the snapshot: ${record.batchId}`);
534
+ else if (!batch.members.includes(record.id)) bad(`Reminder ${record.id} claims ${record.batchId}, which does not list it`);
212
535
  }
213
536
  if (snapshot.audit.some(entry => !entry || typeof entry !== 'object' || typeof entry.op !== 'string' ||
214
537
  typeof entry.at !== 'string' || !Number.isFinite(msOf(entry.at)))) {
@@ -400,6 +723,9 @@ function listReminders(snapshot, request, nowMs) {
400
723
  const terminal = snapshot.reminders.filter(record => isTerminal(record.phase))
401
724
  .sort((a, b) => (endedMs(b) - endedMs(a)) || (b.seq - a.seq))
402
725
  .map(record => viewOfRecord(record, nowMs));
726
+ const batchCounts = { intent: 0, observed: 0, unknown: 0, resolved: 0 };
727
+ for (const batch of snapshot.batches) batchCounts[batch.phase] = (batchCounts[batch.phase] ?? 0) + 1;
728
+ const outstanding = outstandingBatch(snapshot);
403
729
  return {
404
730
  ok: true,
405
731
  now: iso(nowMs),
@@ -412,6 +738,8 @@ function listReminders(snapshot, request, nowMs) {
412
738
  terminal: all ? terminal : [],
413
739
  terminalTotal: terminal.length,
414
740
  terminalShown: all,
741
+ outstanding: outstanding ? { id: outstanding.id, phase: outstanding.phase, intentAt: outstanding.intentAt, members: outstanding.members.slice() } : null,
742
+ batchCounts,
415
743
  };
416
744
  }
417
745
 
@@ -421,11 +749,19 @@ export function applyReminder(snapshot, request, nowMs) {
421
749
  case 'remind-list': return listReminders(snapshot, request, nowMs);
422
750
  case 'remind-show': return showReminder(snapshot, request, nowMs);
423
751
  case 'remind-cancel': return cancelReminder(snapshot, request, nowMs);
752
+ case 'remind-admit': return admitReminders(snapshot, request, nowMs);
753
+ case 'remind-intent': return intentBatch(snapshot, request, nowMs);
754
+ case 'remind-observe': return observeBatch(snapshot, request, nowMs);
755
+ case 'remind-fail': return failBatch(snapshot, request, nowMs);
756
+ case 'remind-resolve': return resolveBatch(snapshot, request, nowMs);
424
757
  default: fail(`unknown reminder operation: ${request.op}`);
425
758
  }
426
759
  }
427
760
 
428
- export const REMIND_OPS = new Set(['remind-add', 'remind-list', 'remind-show', 'remind-cancel']);
761
+ export const REMIND_OPS = new Set([
762
+ 'remind-add', 'remind-list', 'remind-show', 'remind-cancel',
763
+ 'remind-admit', 'remind-intent', 'remind-observe', 'remind-fail', 'remind-resolve',
764
+ ]);
429
765
 
430
766
  // ---------------------------------------------------------------- presentation
431
767
  // Tokens (id, phase/view names, source, times) stay machine-shaped: they are the same words the spec and
@@ -470,6 +806,12 @@ function renderList(result) {
470
806
  `提醒 · ${activeN} 条活跃 · 已签发 ${result.highWater} · 已修剪 ${result.pruned} · 现在 ${result.now}`,
471
807
  `视图 ${VIEWS.map(view => `${view}=${c[view] ?? 0}`).join(' ')}`,
472
808
  ];
809
+ if (result.outstanding) {
810
+ const ob = result.outstanding;
811
+ lines.push(ob.phase === 'unknown'
812
+ ? `批次 ${ob.id} · unknown(未确认送达:检查后 team remind resolve ${ob.id} --ack-unknown;不会自动重发)`
813
+ : `批次 ${ob.id} · intent(已冻结,等唤醒回执;冻结于 ${ob.intentAt})`);
814
+ }
473
815
  if (!activeN && !result.terminalTotal) {
474
816
  lines.push('(还没有提醒:team remind add --after 20m --message "…")');
475
817
  return lines.join('\n') + '\n';
@@ -495,16 +837,29 @@ function renderShow(result) {
495
837
  if (!result.ok) return `team remind show:${result.reason}\n`;
496
838
  const record = result.reminder;
497
839
  const ended = record.endedAt ? `\n 结束 ${record.endedAt}` : '';
840
+ const queued = record.queuedAt ? `\n 入队 ${record.queuedAt}${record.overdue ? '(补发:到期时巡检没在看)' : ''}` : '';
841
+ const batch = record.batchId ? `\n 批次 ${record.batchId}` : '';
498
842
  return [
499
843
  `${record.id} · ${record.view}(phase ${record.phase})`,
500
844
  ` 到期 ${record.dueAt}`,
501
845
  ` 创建 ${record.createdAt}${ended}`,
502
846
  ` 视图 ${record.view}`,
503
847
  ` 归属 owner ${record.owner}${record.key ? ` · key ${record.key}` : ''} · 来源 ${record.source}${record.task ? ` · task ${record.task}` : ''}`,
848
+ `${queued}${batch}`.replace(/^\n/, ''),
504
849
  ' 正文(逐字,未截断):',
505
850
  record.message,
506
851
  '',
507
- ].join('\n');
852
+ ].filter(line => line !== '').join('\n');
853
+ }
854
+
855
+ function renderResolve(result) {
856
+ if (result.outcome === 'resolved') {
857
+ return `已确认未知批次 ${result.batch}(${result.ids.length} 条:${result.ids.join(' ')}):已关闭、不再重发,也不声称送达过\n`;
858
+ }
859
+ if (result.outcome === 'already-resolved') {
860
+ return `批次 ${result.batch} 早已确认过(${result.ids.length} 条);这次没有改动\n`;
861
+ }
862
+ return `team remind resolve:${result.reason}\n`;
508
863
  }
509
864
 
510
865
  function renderCancel(result) {
@@ -524,6 +879,7 @@ export function renderRemind(op, result) {
524
879
  case 'remind-list': return renderList(result);
525
880
  case 'remind-show': return renderShow(result);
526
881
  case 'remind-cancel': return renderCancel(result);
882
+ case 'remind-resolve': return renderResolve(result);
527
883
  default: return JSON.stringify(result) + '\n';
528
884
  }
529
885
  }