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
@@ -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
+ }
@@ -16,15 +16,21 @@
16
16
  //
17
17
  // A missing flock, a lock timeout, a corrupt/unsupported snapshot, a torn file or an identity mismatch
18
18
  // is a visible error. There is no unlocked fallback and an unreadable snapshot is never replaced by an
19
- // empty store. This slice (1.1/1.2) deliberately does NOT import or touch the legacy `standby` marker:
20
- // migration is task 1.3. `init` therefore only ever writes a fresh snapshot with Standby generation 0.
19
+ // empty store. Task 1.3 moved every Standby reader/writer here: the snapshot's `standby` slot is the only
20
+ // truth, and the legacy `<state>/standby` marker is read once by the migration (see importLegacy) and then
21
+ // retired to `<state>/standby.migrated` -- the snapshot is published before the marker is retired, so a
22
+ // crash in between replays only the retirement (`migrated` makes the import exactly-once).
23
+ //
24
+ // Reads are pure: they never publish a snapshot and never take part in the migration (the panel and the
25
+ // monitor are display paths and must not write). Until the first write, a read answers from the legacy
26
+ // marker exactly as the old readers did, so an upgrading team is never mistaken for "not on standby".
21
27
 
22
28
  import * as fs from 'node:fs';
23
29
  import path from 'node:path';
24
30
  import { randomUUID } from 'node:crypto';
25
31
  import { spawn, spawnSync } from 'node:child_process';
26
32
  import { fileURLToPath } from 'node:url';
27
- import { REMIND_OPS, applyReminder, renderRemind, validateReminders } from './remind-store.mjs';
33
+ import { REMIND_OPS, applyReminder, peekReminders, renderRemind, validateReminders } from './remind-store.mjs';
28
34
 
29
35
  const SELF = fileURLToPath(import.meta.url);
30
36
  const SNAPSHOT_VERSION = 1;
@@ -34,6 +40,10 @@ const LOCK_WAIT_SECONDS = 5;
34
40
  const LOCK_CONFLICT_EXIT = 75;
35
41
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
36
42
  const SEQUENCE_KINDS = new Set(['reminder', 'batch', 'queue']);
43
+ // Standby operations. A read is answered from the snapshot and never publishes one; the other three are
44
+ // mutations and run the legacy import first, in the same locked transaction.
45
+ const STANDBY_OPS = new Set(['standby-read', 'standby-on', 'standby-off', 'standby-import']);
46
+ const STANDBY_READ_OPS = new Set(['read', 'standby-read']);
37
47
 
38
48
  const fail = message => { throw new Error(message); };
39
49
 
@@ -201,15 +211,94 @@ function initial(locator) {
201
211
  project: { id: locator.projectId, mainRoot: locator.mainRoot, stateRoot: locator.stateRoot },
202
212
  sequences: { reminder: 1, batch: 1, queue: 1 },
203
213
  pruned: 0,
204
- // Present from version 1 so task 1.3 can migrate into the same snapshot. This slice never reads or
205
- // writes the legacy marker: generation 0 means "no authority-observed Standby yet", not "off".
206
- standby: { on: false, generation: 0, reason: null, since: null },
214
+ // `migrated` records that the legacy marker has been imported (or proven absent): an old snapshot
215
+ // without the key is unmigrated, and the next mutation imports the marker before it does anything.
216
+ standby: { on: false, generation: 0, reason: null, since: null, migrated: false },
217
+ pulse: null,
207
218
  reminders: [],
208
219
  batches: [],
209
220
  audit: [],
210
221
  };
211
222
  }
212
223
 
224
+ // ---------------------------------------------------------------- 待命(PM 主动停工)
225
+ // The legacy marker is one line: `<timestamp> <reason>` (the old writer printed `-` when it had no reason).
226
+ // It is only consulted while the snapshot says `migrated: false`, i.e. before the import has run.
227
+ const legacyMarkerFile = state => path.join(state, 'standby');
228
+
229
+ function legacyMarker(state) {
230
+ const file = legacyMarkerFile(state);
231
+ let stat;
232
+ try { stat = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
233
+ // A symlink or a directory here is not the old format: refuse it instead of importing a guess.
234
+ if (!stat.isFile()) fail(`legacy Standby marker is not a regular file: ${file}; move it aside and retry`);
235
+ const line = fs.readFileSync(file, 'utf8').split('\n', 1)[0];
236
+ const cut = line.indexOf(' ');
237
+ const since = cut === -1 ? line : line.slice(0, cut);
238
+ if (!since) fail(`legacy Standby marker is empty: ${file}; delete it if the team was not on standby`);
239
+ const reason = cut === -1 ? '-' : line.slice(cut + 1);
240
+ return { reason: reason === '' ? '-' : reason, since };
241
+ }
242
+
243
+ // Import once, inside the caller's transaction: the reason and the start time survive, and the generation
244
+ // is kept as it is -- the import is not a new on generation (a later `standby on` is). A marker that is
245
+ // still there after a completed import is leftover evidence, not truth: it is only retired, never adopted.
246
+ function importLegacy(snapshot, state) {
247
+ const marker = legacyMarker(state);
248
+ let imported = false;
249
+ if (!snapshot.standby.migrated) {
250
+ snapshot.standby = {
251
+ on: marker ? true : snapshot.standby.on,
252
+ generation: snapshot.standby.generation,
253
+ reason: marker ? marker.reason : snapshot.standby.reason,
254
+ since: marker ? marker.since : snapshot.standby.since,
255
+ migrated: true,
256
+ };
257
+ imported = Boolean(marker);
258
+ }
259
+ return { imported, marker: Boolean(marker) };
260
+ }
261
+
262
+ // The snapshot is already durable when this runs, so a failure here cannot lose the state: the marker is
263
+ // inert from now on. Say so instead of reporting the whole write as failed (the caller would retry, and a
264
+ // retried `standby on` is a new generation).
265
+ function retireLegacy(state) {
266
+ const file = legacyMarkerFile(state);
267
+ if (!regular_exists(file)) return null;
268
+ let target = path.join(state, 'standby.migrated');
269
+ for (let n = 1; exists(target); n++) target = path.join(state, `standby.migrated.${n}`);
270
+ try {
271
+ fs.renameSync(file, target);
272
+ fsyncDir(state);
273
+ return target;
274
+ } catch (e) {
275
+ process.stderr.write(`state-authority: imported ${file} but could not retire it (${e.code ?? e.message}); ` +
276
+ 'it is no longer read, remove it by hand\n');
277
+ return null;
278
+ }
279
+ }
280
+
281
+ // What readers see. While the import has not run, the marker is still the record (an upgrading team must
282
+ // not read as "off"); afterwards only the snapshot counts, even if a stale marker is still on disk.
283
+ function standbyView(snapshot, state) {
284
+ if (snapshot.standby.migrated) return { ...snapshot.standby, legacy: false };
285
+ const marker = legacyMarker(state);
286
+ if (!marker) return { ...snapshot.standby, legacy: false };
287
+ return { on: true, generation: snapshot.standby.generation, reason: marker.reason, since: marker.since, legacy: true };
288
+ }
289
+
290
+ function standbyResult(snapshot, state, extra) {
291
+ const view = standbyView(snapshot, state);
292
+ return {
293
+ ok: true, on: view.on, generation: view.generation, reason: view.reason, since: view.since,
294
+ migrated: Boolean(snapshot.standby.migrated), legacy: Boolean(view.legacy), ...extra,
295
+ };
296
+ }
297
+
298
+ function isoSeconds(ms) {
299
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z');
300
+ }
301
+
213
302
  function validate(snapshot, main, state) {
214
303
  const where = snapshotFile(state);
215
304
  if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) fail(`invalid state snapshot ${where}: not an object`);
@@ -230,6 +319,8 @@ function validate(snapshot, main, state) {
230
319
  }
231
320
  if (standby.reason !== null && typeof standby.reason !== 'string') fail(`invalid state snapshot ${where}: invalid Standby reason`);
232
321
  if (standby.since !== null && typeof standby.since !== 'string') fail(`invalid state snapshot ${where}: invalid Standby timestamp`);
322
+ // Absent means "not imported yet" (a snapshot written by 1.1/1.2); anything but a boolean is corrupt.
323
+ if (standby.migrated !== undefined && typeof standby.migrated !== 'boolean') fail(`invalid state snapshot ${where}: invalid Standby migration flag`);
233
324
  for (const key of ['reminders', 'batches', 'audit']) {
234
325
  if (!Array.isArray(snapshot[key])) fail(`invalid state snapshot ${where}: ${key} is not an array`);
235
326
  }
@@ -253,19 +344,43 @@ function summary(snapshot, created) {
253
344
  stateRoot: snapshot.project.stateRoot,
254
345
  sequences: { ...snapshot.sequences },
255
346
  pruned: snapshot.pruned,
256
- standby: { ...snapshot.standby },
347
+ standby: { ...snapshot.standby, migrated: Boolean(snapshot.standby.migrated) },
257
348
  counts: { reminders: snapshot.reminders.length, batches: snapshot.batches.length, audit: snapshot.audit.length },
258
349
  snapshot: snapshotFile(snapshot.project.stateRoot),
259
350
  };
260
351
  }
261
352
 
262
- function apply(snapshot, request, nowMs) {
353
+ function apply(snapshot, request, nowMs, state) {
263
354
  if (REMIND_OPS.has(request.op)) return applyReminder(snapshot, request, nowMs);
264
355
  switch (request.op) {
265
356
  case 'init':
266
357
  return summary(snapshot, true);
267
358
  case 'read':
268
359
  return summary(snapshot, false);
360
+ case 'standby-read':
361
+ return standbyResult(snapshot, state);
362
+ case 'standby-import':
363
+ return standbyResult(snapshot, state);
364
+ case 'standby-on': {
365
+ // Every `on` is a new, never-reused generation (an already-on team that is told to stand down again
366
+ // gets one too): a wake binds a generation, and reusing one would let a stale binding turn off a
367
+ // newer stand-down.
368
+ snapshot.standby = {
369
+ on: true,
370
+ generation: snapshot.standby.generation + 1,
371
+ reason: typeof request.reason === 'string' ? request.reason : '-',
372
+ since: isoSeconds(nowMs),
373
+ migrated: true,
374
+ };
375
+ return standbyResult(snapshot, state);
376
+ }
377
+ case 'standby-off': {
378
+ // Already off is not an error and not a transition: nothing changes, so nothing is written.
379
+ if (snapshot.standby.on) {
380
+ snapshot.standby = { on: false, generation: snapshot.standby.generation, reason: null, since: isoSeconds(nowMs), migrated: true };
381
+ }
382
+ return standbyResult(snapshot, state);
383
+ }
269
384
  case 'allocate': {
270
385
  const kind = request.kind;
271
386
  if (!SEQUENCE_KINDS.has(kind)) fail(`unknown state sequence kind: ${kind}`);
@@ -297,16 +412,26 @@ function transaction(main, state, request) {
297
412
  if (request.op === 'read') fail(`state authority is not initialized: ${file}`);
298
413
  snapshot = initial(locator);
299
414
  validate(snapshot, main, state);
415
+ // A display path (panel banner, monitor, `standby status`) must not create anything: answer from the
416
+ // legacy marker -- or "off" -- and let the first write publish the snapshot.
417
+ if (STANDBY_READ_OPS.has(request.op)) return apply(snapshot, request, Date.now(), state);
300
418
  }
301
419
  const before = JSON.stringify(snapshot);
302
- const result = apply(snapshot, request, Date.now());
420
+ // Every mutation imports the legacy marker first, inside this same transaction, so no write can land on
421
+ // a half-upgraded team. Reads never import: they only *view* the marker (see standbyView).
422
+ const migration = STANDBY_READ_OPS.has(request.op) ? { imported: false, marker: false } : importLegacy(snapshot, state);
423
+ const result = apply(snapshot, request, Date.now(), state);
303
424
  // A reminder result reports its own `created` (an idempotent key hit is created:false); every other
304
425
  // operation keeps the authority-level meaning: was this the first snapshot?
305
- if (!REMIND_OPS.has(request.op)) result.created = !hasSnapshot;
426
+ if (!REMIND_OPS.has(request.op) && !STANDBY_OPS.has(request.op)) result.created = !hasSnapshot;
306
427
  const changed = JSON.stringify(snapshot) !== before;
307
428
  // A first `init` does not mutate the object, but the fresh snapshot must still be published. A read
308
429
  // (list/show, a refused cancel) never publishes one: reading an empty authority stays a read.
309
430
  if (changed || (!hasSnapshot && request.op === 'init')) writeAtomic(file, snapshot);
431
+ // Publish first, retire second: the snapshot already records `migrated`, so a crash in between only
432
+ // replays the retirement instead of importing a second time.
433
+ const retired = migration.marker ? retireLegacy(state) : null;
434
+ if (request.op === 'standby-import') { result.imported = migration.imported; result.retired = retired; }
310
435
  return result;
311
436
  }
312
437
 
@@ -339,6 +464,34 @@ function flock(lock, args, input) {
339
464
  });
340
465
  }
341
466
 
467
+ // A whole-snapshot read WITHOUT the lock (the caller's "is there anything to commit right now" probe).
468
+ // Renames are atomic, so an unlocked reader sees either the previous or the next snapshot, never half of
469
+ // one; nothing here writes, publishes or decides -- every decision still runs inside `request()`.
470
+ export async function peek(context) {
471
+ const main = authorityIdentity(context);
472
+ const want = canonical(context.stateRoot);
473
+ const pinned = readLocator(main);
474
+ if (!pinned) {
475
+ return { pinned: false, mainRoot: main, stateRoot: want, reminders: { due: [], queued: [], staleIntent: [] }, outstanding: null };
476
+ }
477
+ if (pinned.stateRoot !== want) {
478
+ fail(`canonical state-root mismatch: pinned ${pinned.stateRoot}, requested ${want}; ` +
479
+ 'quiesce the writers and migrate the locator explicitly (never pick a second authority)');
480
+ }
481
+ const file = snapshotFile(pinned.stateRoot);
482
+ if (!snapshotPresence(file)) {
483
+ return { pinned: true, mainRoot: main, stateRoot: pinned.stateRoot, reminders: { due: [], queued: [], staleIntent: [] }, outstanding: null };
484
+ }
485
+ const snapshot = readJSON(file);
486
+ validate(snapshot, main, pinned.stateRoot);
487
+ const pending = snapshot.batches.find(batch => batch.phase === 'intent' || batch.phase === 'unknown') ?? null;
488
+ return {
489
+ pinned: true, mainRoot: main, stateRoot: pinned.stateRoot, projectId: snapshot.project.id,
490
+ reminders: peekReminders(snapshot, Date.now()),
491
+ outstanding: pending ? { id: pending.id, phase: pending.phase } : null,
492
+ };
493
+ }
494
+
342
495
  async function resolveAuthority(context) {
343
496
  const main = authorityIdentity(context);
344
497
  const want = canonical(context.stateRoot);
@@ -353,6 +506,7 @@ async function resolveAuthority(context) {
353
506
 
354
507
  // The single Node-facing entry point (the CLI below is a thin wrapper around it).
355
508
  export async function request(context, requestData) {
509
+ if (requestData.op === 'standby-read') return readStandby(context);
356
510
  const located = await resolveAuthority(context);
357
511
  const state = located.stateRoot;
358
512
  try { fs.mkdirSync(remindersDir(state), { recursive: true, mode: 0o700 }); }
@@ -360,6 +514,35 @@ export async function request(context, requestData) {
360
514
  return flock(authorityLock(state), ['--transaction', located.mainRoot, state], JSON.stringify(requestData));
361
515
  }
362
516
 
517
+ // A read must establish nothing: it never creates the locator and never publishes a snapshot. Two reasons:
518
+ // the panel and the monitor are display paths (they must not write), and a caller that merely names another
519
+ // TEAM_STATE_DIR must not capture the project's pin from under it. Which record answers the read is the
520
+ // same decision the migration makes: an unpinned project is still described by the legacy marker.
521
+ function unfiledStandby(state) {
522
+ const marker = legacyMarker(state);
523
+ return marker
524
+ ? { ok: true, on: true, generation: 0, reason: marker.reason, since: marker.since, migrated: false, legacy: true }
525
+ : { ok: true, on: false, generation: 0, reason: null, since: null, migrated: false, legacy: false };
526
+ }
527
+
528
+ async function readStandby(context) {
529
+ const main = authorityIdentity(context);
530
+ const state = canonical(context.stateRoot);
531
+ const pinned = readLocator(main);
532
+ if (!pinned) {
533
+ if (snapshotPresence(snapshotFile(state))) {
534
+ fail(`state authority is not pinned for ${main} (${locatorFile(main)} is missing) but ${snapshotFile(state)} exists; ` +
535
+ 'refusing to answer from an unpinned snapshot');
536
+ }
537
+ return unfiledStandby(state);
538
+ }
539
+ if (pinned.stateRoot !== state) {
540
+ fail(`canonical state-root mismatch: pinned ${pinned.stateRoot}, requested ${state}; ` +
541
+ 'quiesce the writers and migrate the locator explicitly (never pick a second authority)');
542
+ }
543
+ return flock(authorityLock(state), ['--transaction', main, state], JSON.stringify({ op: 'standby-read' }));
544
+ }
545
+
363
546
  export async function resolve(context) {
364
547
  return resolveAuthority(context);
365
548
  }
@@ -368,7 +551,9 @@ function parseCli(argv) {
368
551
  const [main, state, op, ...rest] = argv;
369
552
  if (!main || !state || !op) {
370
553
  fail('usage: state-authority.mjs --cli <project-root> <state-root> ' +
371
- '<resolve|init|read|allocate <kind>|remind-add|remind-list|remind-show|remind-cancel> ' +
554
+ '<resolve|init|read|allocate <kind>|standby-read|standby-on|standby-off|standby-import|' +
555
+ 'remind-add|remind-list|remind-show|remind-cancel|remind-admit|remind-intent|' +
556
+ 'remind-observe|remind-fail|remind-resolve> ' +
372
557
  '[--print <field>] [--json]');
373
558
  }
374
559
  let print = null;
@@ -393,9 +578,24 @@ function parseCli(argv) {
393
578
  flags[name] = value;
394
579
  continue;
395
580
  }
581
+ // Standby takes exactly one flag (`--reason` on `standby-on`); anything else is refused by name, so a
582
+ // typo cannot pass for a successful stand-down.
583
+ if (STANDBY_OPS.has(op) && token.startsWith('--')) {
584
+ const name = token.slice(2);
585
+ if (name === 'json') { json = true; continue; }
586
+ if (op === 'standby-on' && name === 'reason') {
587
+ const value = rest.shift();
588
+ if (value === undefined) fail('--reason needs a value');
589
+ flags.reason = value;
590
+ continue;
591
+ }
592
+ fail(`${op} does not accept --${name}`);
593
+ }
396
594
  args.push(token);
397
595
  }
398
- const requestData = REMIND_OPS.has(op) ? parseRemindFlags(op, flags) : { op };
596
+ const requestData = REMIND_OPS.has(op) ? parseRemindFlags(op, flags)
597
+ : STANDBY_OPS.has(op) ? (op === 'standby-on' ? { op, reason: flags.reason ?? '-' } : { op })
598
+ : { op };
399
599
  if (op === 'allocate') {
400
600
  requestData.kind = args.shift();
401
601
  if (!requestData.kind) fail('allocate needs a sequence kind (reminder|batch|queue)');
@@ -405,15 +605,30 @@ function parseCli(argv) {
405
605
  }
406
606
 
407
607
  // Boolean reminder flags (everything else takes a value).
408
- const REMIND_BOOL_FLAGS = { 'remind-list': new Set(['all']) };
608
+ const REMIND_BOOL_FLAGS = { 'remind-list': new Set(['all']), 'remind-resolve': new Set(['ack-unknown']) };
409
609
 
410
610
  // Exactly the flags each reminder operation accepts: an unknown flag is refused here rather than silently
411
- // ignored, so a typo cannot look like a successful create.
611
+ // ignored, so a typo cannot look like a successful create or a successful delivery step.
412
612
  const REMIND_FLAGS = {
413
613
  'remind-add': new Set(['at', 'after', 'key', 'task', 'source']),
414
614
  'remind-list': new Set(['all']),
415
615
  'remind-show': new Set(['id']),
416
616
  'remind-cancel': new Set(['id']),
617
+ 'remind-admit': new Set(['pulse-started']),
618
+ 'remind-intent': new Set(['session', 'pid']),
619
+ 'remind-observe': new Set(['id', 'nonce', 'session']),
620
+ 'remind-fail': new Set(['id', 'nonce', 'reason']),
621
+ 'remind-resolve': new Set(['id', 'ack-unknown']),
622
+ };
623
+
624
+ // The kebab-case command line is mapped to the transaction's field names in one place: the transaction
625
+ // never sees a flag it did not ask for, and a missing required field is refused by name.
626
+ const REMIND_FIELD = { 'pulse-started': 'pulseStartedAt', 'ack-unknown': 'ack' };
627
+ const REMIND_REQUIRED = {
628
+ 'remind-intent': ['session'],
629
+ 'remind-observe': ['id', 'nonce', 'session'],
630
+ 'remind-fail': ['id', 'nonce'],
631
+ 'remind-resolve': ['id'],
417
632
  };
418
633
 
419
634
  function parseRemindFlags(op, flags) {
@@ -421,9 +636,20 @@ function parseRemindFlags(op, flags) {
421
636
  const request = { op };
422
637
  for (const name of Object.keys(flags)) {
423
638
  if (!allowed.has(name)) fail(`${op} does not accept --${name}`);
424
- request[name] = flags[name];
639
+ request[REMIND_FIELD[name] ?? name] = flags[name];
640
+ }
641
+ for (const name of REMIND_REQUIRED[op] ?? []) {
642
+ const field = REMIND_FIELD[name] ?? name;
643
+ if (request[field] === undefined || request[field] === '') fail(`${op} needs --${name}`);
644
+ }
645
+ if (op === 'remind-intent' && request.pid !== undefined) {
646
+ const pid = Number(request.pid);
647
+ if (!Number.isSafeInteger(pid) || pid < 1) fail('remind-intent --pid must be a process id');
648
+ request.pid = pid;
649
+ }
650
+ if (op === 'remind-resolve' && request.ack !== true) {
651
+ fail('remind-resolve requires --ack-unknown: acknowledging an unknown batch closes it and burns its one automatic-off right');
425
652
  }
426
- if ((op === 'remind-show' || op === 'remind-cancel') && !request.id) fail(`${op} needs --id <reminder-id>`);
427
653
  return request;
428
654
  }
429
655
 
@@ -440,6 +666,24 @@ async function readMessageFromStdin() {
440
666
  return { message: text };
441
667
  }
442
668
 
669
+ // Standby is rendered here (not in the shell) so a reason keeps every byte it was given: the shell only
670
+ // prints these lines, and `--print <field>` stays the machine interface.
671
+ function renderStandby(op, result) {
672
+ const status = result.on
673
+ ? `standby: on(自 ${result.since ?? '-'},原因:${result.reason ?? '-'})`
674
+ : 'standby: off';
675
+ if (op !== 'standby-import') {
676
+ // Until the import runs, the marker is still the record: say so once, where a human reads it.
677
+ return result.legacy ? `${status}\n(旧标记还没并入统一状态:跑 team standby migrate 完成迁移)` : status;
678
+ }
679
+ if (result.imported) {
680
+ return `${status}\n迁移:state/standby 已并入统一状态(原因与时间保留,代次仍是 ${result.generation}:迁移不加代);` +
681
+ `旧标记改名为 ${result.retired ?? '(改名失败,已不再被读取)'}`;
682
+ }
683
+ if (result.retired) return `${status}\n迁移:统一状态早已并入;这次清掉了残留的旧标记(改名为 ${result.retired})`;
684
+ return `${status}\n迁移:无需迁移(统一状态已记录待命${result.on ? '开启' : '关闭'})`;
685
+ }
686
+
443
687
  async function main(argv) {
444
688
  const [mode, ...rest] = argv;
445
689
  if (mode === '--locator') {
@@ -482,13 +726,17 @@ async function main(argv) {
482
726
  if (!Object.hasOwn(result, print)) fail(`unknown output field: ${print}`);
483
727
  if (result[print] === null || typeof result[print] === 'object') fail(`output field ${print} is not scalar`);
484
728
  process.stdout.write(String(result[print]) + '\n');
729
+ } else if (STANDBY_OPS.has(requestData.op) && !json) {
730
+ process.stdout.write(renderStandby(requestData.op, result) + '\n');
485
731
  } else {
486
732
  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
487
733
  }
488
734
  return;
489
735
  }
490
736
  fail('usage: state-authority.mjs --cli <project-root> <state-root> ' +
491
- '<resolve|init|read|allocate <kind>|remind-add|remind-list|remind-show|remind-cancel> [--print <field>] [--json]');
737
+ '<resolve|init|read|allocate <kind>|standby-read|standby-on|standby-off|standby-import|' +
738
+ 'remind-add|remind-list|remind-show|remind-cancel|remind-admit|remind-intent|' +
739
+ 'remind-observe|remind-fail|remind-resolve> [--print <field>] [--json]');
492
740
  }
493
741
 
494
742
  if (process.argv[1] && path.resolve(process.argv[1]) === SELF) {
@@ -67,8 +67,8 @@ cmd reply seats reply list ;; reply show <slug> ;; reply post --from <sender> --
67
67
  cmd pulse patrol pulse up|down|restart|status|logs [--print] --print up down restart status logs watchdog watchdog-status install-watchdog uninstall-watchdog pm pulse knock - starts-process none not-reversible:the window that was started is gone once it stops - pulse team pulse status
68
68
  cmd monitor patrol monitor [--once] [--print|--json] [--width <N>] [--height <N>] [--interval <N>] [--events <K>] [--no-pulse] --once --print --json --width --height --interval --events --no-pulse - - pulse state writes-state none not-reversible:every run appends its own bookkeeping line - monitor team monitor --print --once
69
69
  cmd watch patrol watch [--once] [--interval <N>] [--ui] --once --interval --ui - - pulse state writes-state none not-reversible:every tick appends to the patrol log - watch team watch --once
70
- cmd standby patrol standby on [--reason <text>] ;; standby off ;; standby status --reason on off status - pm pulse state writes-state none not-reversible:the state it writes is a record of when it was set - standby team standby on --reason "waiting for the user"
71
- cmd remind patrol remind add --after <duration> --message <text> [--key <id>] [--task <ref>] [--json] ;; remind add --at <date-time> --message-file <file> [--key <id>] [--task <ref>] [--json] ;; remind list [--all] [--json] ;; remind show <id> [--json] ;; remind cancel <id> [--json] --after --at --message --message-file --key --task --all --json add list show cancel - pm pulse state writes-state none not-reversible:a reminder is a record: cancel marks it cancelled and the history stays - remind team remind add --after 20m --message "check the build"
70
+ cmd standby patrol standby on [--reason <text>] ;; standby off ;; standby status ;; standby migrate --reason on off status migrate - pm pulse state writes-state none not-reversible:the state it writes is a record of when it was set - standby team standby on --reason "waiting for the user"
71
+ cmd remind patrol remind add --after <duration> --message <text> [--key <id>] [--task <ref>] [--json] ;; remind add --at <date-time> --message-file <file> [--key <id>] [--task <ref>] [--json] ;; remind list [--all] [--json] ;; remind show <id> [--json] ;; remind cancel <id> [--json] ;; remind resolve <batch-id> --ack-unknown [--json] --after --at --message --message-file --key --task --all --json --ack-unknown add list show cancel resolve - pm pulse state writes-state none not-reversible:a reminder is a record: cancel marks it cancelled and the history stays - remind team remind add --after 20m --message "check the build"
72
72
  cmd up patrol up [--agents] [--fresh-pm] [--print] --agents --fresh-pm --print - - pm seat state starts-process none not-reversible:the PM session it starts keeps its own history - up team up
73
73
  cmd resume patrol resume [--agent <a>] [--all] [--dry-run] --agent --all --dry-run - - seat pm state starts-process none not-reversible:a resumed seat continues in its own session - resume team resume --all
74
74
  cmd meeting peers meeting open <slug> --with <peer> --topic <text> [--ttl <hours>] [--yes] ;; meeting say <slug> --intent <intent> <message> [--knock] ;; meeting read <slug> [--since <n>] [--peek] ;; meeting list [--all] ;; meeting inbox ;; meeting agree <slug> <option> [--note <text>] ;; meeting close <slug> --with --topic --ttl --yes --intent --knock --since --peek --all --note open say read list inbox agree close propose peer knock help - pm meetings writes-meetings needs-yes:TEAM_CONFIRM_WRITES not-reversible:the shared transcript is the record of what was said - meeting team meeting open rename --with other:pm --topic "rename the interface"
@@ -81,7 +81,7 @@ cmd merge finish merge - - - ledger - read-only none idempotent - merge team mer
81
81
  cmd pr finish pr - - - ledger - read-only none idempotent - pr team pr
82
82
  cmd gh finish gh - - - ledger - read-only none idempotent - gh team gh
83
83
  cmd gl finish gl - - - ledger - read-only none idempotent - gl team gl
84
- cmd mark-loaded versions mark-loaded [--version <X>] --version - - gate state writes-state none idempotent - mark-loaded team mark-loaded --version 0.2.0
84
+ cmd mark-loaded versions mark-loaded - - - gate - read-only none idempotent - mark-loaded team mark-loaded
85
85
  cmd version versions version [--check] --check - - gate - read-only none idempotent - version team version --check
86
86
  cmd changelog versions changelog [--since <X>] --since - - - - read-only none idempotent - changelog team changelog
87
87
  cmd reload versions reload [--done] --done - - gate state writes-state none not-reversible:every request leaves its own record - reload team reload