@jjanczur/tyran 0.1.29 → 0.1.31

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.
@@ -83,6 +83,117 @@ export const DATA_REQUIRED = Object.freeze({
83
83
  error: ['class'],
84
84
  });
85
85
 
86
+ /**
87
+ * Per-type keys that some consumer actually READS. Descriptive, not enforced.
88
+ *
89
+ * `append` does not and must not check this: `data may always carry extra
90
+ * keys` is a promise this file makes, the evidence gate relies on it for four
91
+ * of its own keys, and every journal ever written would fail retroactively if
92
+ * it became a rule. Measured on one real install: 130 distinct (event, key)
93
+ * pairs across 39 initiatives, and the long tail is deliberate annotation —
94
+ * `init.created.hardware`, `retro.entry.proposed_as_diffs`, `spawn.stories`.
95
+ *
96
+ * What this map is FOR is the narrow case hiding in that tail: a key that was
97
+ * MEANT to be read and is not, because it was misspelled. `next_step` for
98
+ * `next_steps` is accepted, ignored, and leaves the resume surface empty while
99
+ * the agent that wrote it believes it recorded something. Doctor compares
100
+ * unread keys against this map and reports only the near-misses; the rest are
101
+ * counted, because they are the contract working rather than a defect.
102
+ *
103
+ * `null` means "free-form on purpose": the fold keeps the whole `data` object
104
+ * for these, so there is no such thing as a key it does not read.
105
+ */
106
+ export const DATA_KNOWN = Object.freeze({
107
+ 'init.created': null,
108
+ 'plan.accepted': null,
109
+ 'ticket.created': Object.freeze(['id', 'title', 'text', 'deps']),
110
+ 'ticket.status': Object.freeze(['ticket', 'column', 'reason', 'until']),
111
+ spawn: Object.freeze(['agent', 'role', 'model', 'ticket', 'worktree']),
112
+ report: Object.freeze(['agent', 'verdict', 'ticket', 'text', 'note', 'evidence', 'closed_by']),
113
+ progress: Object.freeze(['agent', 'state', 'ticket', 'detail', 'next']),
114
+ // Row two is the evidence gate's own, written on every SubagentStop; row
115
+ // three is `answer.mjs` closing an operator question. Both are Tyran writing
116
+ // to its own journal, so leaving either out would have every install report
117
+ // its own normal operation back at itself.
118
+ gate: Object.freeze([
119
+ 'kind', 'result', 'evidence', 'evidence_ref', 'ticket', 'question', 'recommendation', 'default',
120
+ 'reason', 'signals', 'code', 'would_be', 'initiative_inferred_from',
121
+ 'answer', 'answer_mode', 'decision', 'via',
122
+ ]),
123
+ review: Object.freeze(['ticket', 'verdict', 'by']),
124
+ merge: Object.freeze(['ticket', 'sha', 'mode']),
125
+ // `ask`/`ticket` come from `answer.mjs` closing an operator question;
126
+ // `signature`/`occurrences`/`path` from `mistakes.mjs` recording a promoted
127
+ // rule. Tyran's OWN writers, so leaving them out would have every install
128
+ // that has ever answered a question or run a retrospective report its own
129
+ // normal operation back at itself.
130
+ decision: Object.freeze(['id', 'text', 'ask', 'ticket', 'signature', 'occurrences', 'path']),
131
+ finding: Object.freeze(['area', 'claim', 'proof', 'id', 'ticket', 'confidence']),
132
+ 'lease.acquired': Object.freeze(['resource', 'holder', 'mode']),
133
+ 'lease.released': Object.freeze(['resource', 'holder']),
134
+ checkpoint: Object.freeze(['phase', 'next_steps']),
135
+ 'retro.entry': Object.freeze(['kind', 'target', 'confidence']),
136
+ error: Object.freeze(['class', 'detail', 'ticket']),
137
+ });
138
+
139
+ /**
140
+ * Is `typo` one edit away from `known`? Insert, delete or substitute.
141
+ *
142
+ * Deliberately distance ONE and nothing looser. At two, `note` matches `next`
143
+ * and the check starts inventing typos in correct journals — and this feeds a
144
+ * finding that fails the check, so a false positive costs an operator a red
145
+ * doctor on a healthy repo, which is how a check gets switched off.
146
+ */
147
+ export function isOneEditApart(typo, known) {
148
+ if (typo === known) return false;
149
+ const [a, b] = typo.length <= known.length ? [typo, known] : [known, typo];
150
+ if (b.length - a.length > 1) return false;
151
+ let i = 0;
152
+ let j = 0;
153
+ let edits = 0;
154
+ while (i < a.length && j < b.length) {
155
+ if (a[i] === b[j]) { i += 1; j += 1; continue; }
156
+ if (++edits > 1) return false;
157
+ if (a.length === b.length) i += 1;
158
+ j += 1;
159
+ }
160
+ return edits + (b.length - j) + (a.length - i) <= 1;
161
+ }
162
+
163
+ /**
164
+ * Keys no consumer reads, split into the two that need different sentences.
165
+ *
166
+ * `nearMisses` are almost certainly misspellings of a key that IS read —
167
+ * the accept-then-ignore failure, worth a finding each. `unread` is everything
168
+ * else: counted, never dropped (ADR-19 correction 1), and not called a defect,
169
+ * because carrying extra keys is what the envelope promises.
170
+ *
171
+ * Short keys are exempt from the near-miss test: at three characters or fewer
172
+ * almost anything is one edit from something.
173
+ */
174
+ export function unreadDataKeys(events) {
175
+ const unread = new Map(); // "ev.key" -> count
176
+ const nearMisses = new Map(); // "ev.key" -> {ev, key, meant, count}
177
+ for (const event of events) {
178
+ const known = DATA_KNOWN[event?.ev];
179
+ if (known === undefined || known === null) continue;
180
+ const data = event.data;
181
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) continue;
182
+ for (const key of Object.keys(data)) {
183
+ if (known.includes(key)) continue;
184
+ const id = `${event.ev}.${key}`;
185
+ unread.set(id, (unread.get(id) ?? 0) + 1);
186
+ if (key.length < 4) continue;
187
+ const meant = known.find((k) => k.length >= 4 && isOneEditApart(key, k));
188
+ if (meant === undefined) continue;
189
+ const hit = nearMisses.get(id) ?? { ev: event.ev, key, meant, count: 0 };
190
+ hit.count += 1;
191
+ nearMisses.set(id, hit);
192
+ }
193
+ }
194
+ return { unread, nearMisses: [...nearMisses.values()].sort((a, b) => (a.ev + a.key).localeCompare(b.ev + b.key)) };
195
+ }
196
+
86
197
  /**
87
198
  * Closed VALUE sets inside `data`, for the same reason the event set is
88
199
  * closed: an unknown value must be a loud rejection at append time, not a
@@ -331,6 +442,74 @@ export function pairSpawns(events) {
331
442
  return { open, orphanReports, badNames, pairs, unusable, ambiguous };
332
443
  }
333
444
 
445
+ /**
446
+ * The one `checkpoint.phase` value that MEANS something to a reader.
447
+ *
448
+ * `phase` is otherwise free text — the field carries epic labels (`E2`),
449
+ * lifecycle notes (`resumed`, `usage-limit-pause`) and whatever else a
450
+ * conductor finds useful, and it stays that way. This single value is
451
+ * reserved: it says the initiative is over, which is the one thing a
452
+ * projection cannot infer from any other event. Nothing in `EVENT_TYPES`
453
+ * closes an initiative, so before this an initiative could be wound up with
454
+ * its spawns still open, and every consumer went on calling those agents
455
+ * live for as long as the journal survived.
456
+ *
457
+ * Compared case-insensitively and trimmed, because it is written by hand.
458
+ */
459
+ export const CLOSED_PHASE = 'closed';
460
+
461
+ /** Does this checkpoint's phase declare the initiative over? */
462
+ export function isClosingPhase(phase) {
463
+ return typeof phase === 'string' && phase.trim().toLowerCase() === CLOSED_PHASE;
464
+ }
465
+
466
+ /**
467
+ * How long an open spawn may stand, in JOURNAL time, before it is stale.
468
+ *
469
+ * Lives here rather than in either consumer because both `doctor.mjs` and
470
+ * `project.mjs` have to answer the same question and neither may own it:
471
+ * doctor imports the projection, so the projection cannot import doctor back.
472
+ * It is the same reasoning `pairSpawns` above records — the projection used to
473
+ * compute "who is still working" with a rule of its own, and the operator got
474
+ * two contradictory pictures. Staleness was the half of that answer still
475
+ * written twice: doctor said an agent had been abandoned while the board went
476
+ * on calling it `running` forever.
477
+ */
478
+ export const DEFAULT_STALE_HOURS = 4;
479
+
480
+ /** Hours between two ISO timestamps, or null if either is unparseable. */
481
+ export function hoursBetween(fromTs, toTs) {
482
+ const from = Date.parse(fromTs);
483
+ const to = Date.parse(toTs);
484
+ if (Number.isNaN(from) || Number.isNaN(to)) return null;
485
+ return (to - from) / 3_600_000;
486
+ }
487
+
488
+ /**
489
+ * Is this open spawn stale, measured against the initiative's own movement?
490
+ *
491
+ * `reference` is the journal's latest timestamp, NOT the wall clock, and that
492
+ * is the whole point: staleness here means "the initiative moved on without
493
+ * it", which is a property of the recorded history and reads the same in six
494
+ * months as it does now. A wall-clock rule would instead call every agent in
495
+ * a finished initiative stale the moment you walked away from it.
496
+ *
497
+ * That also keeps `board.json` byte-exact under `--check`: the answer is
498
+ * derived from event timestamps, so two clones of one journal agree. The
499
+ * `age-fresh/warm/cold/dead` colours on the HTML page are a DIFFERENT
500
+ * question — "how long since it last spoke, right now, in the reader's own
501
+ * timezone" — computed client-side precisely because the artefact may not
502
+ * read a clock. An agent can be `age-dead` (quiet for hours) without being
503
+ * stale, and stale without being `age-dead`.
504
+ *
505
+ * Returns the age alongside the verdict so a caller that reports the number
506
+ * does not recompute it — the same additive shape `pairSpawns` returns.
507
+ */
508
+ export function spawnStaleness(spawnTs, reference, staleHours = DEFAULT_STALE_HOURS) {
509
+ const ageHours = reference === null || reference === undefined ? null : hoursBetween(spawnTs, reference);
510
+ return { ageHours, stale: ageHours !== null && ageHours >= staleHours, staleHours };
511
+ }
512
+
334
513
  /** Agents whose `spawn` has no matching `report` or `review` yet — the "still working" set. */
335
514
  export function openSpawns(file) {
336
515
  const { open } = pairSpawns(readJournal(file).events);
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * migrate — the repairs doctor can only ever REPORT.
4
+ *
5
+ * Every other finding doctor raises comes with a remedy the operator can run.
6
+ * `state-legacy-initiatives-dir` came with a sentence instead: "relocate the
7
+ * contents by hand, one initiative directory at a time". That is not a remedy,
8
+ * it is an instruction to do a careful thing carefully, and the installs that
9
+ * carry the finding are by definition the ones nobody has touched since 0.1.8.
10
+ *
11
+ * ## Why this is a separate script and not part of setup
12
+ *
13
+ * Moving an initiative's authored history is not a step that may happen as a
14
+ * side effect of something else. `scan-repo.mjs` seeds files that do not exist
15
+ * yet; this MOVES files that do, and the difference is the whole of the
16
+ * argument. So it is explicit, never automatic, never invoked by a hook, and
17
+ * it does nothing at all until asked twice — once by running it, once with
18
+ * `--apply`.
19
+ *
20
+ * ## The three rules it does not break
21
+ *
22
+ * 1. **Nothing is ever overwritten.** A destination that already exists is a
23
+ * CONFLICT: reported, skipped, and left exactly as it was, on both sides.
24
+ * Merging two directories that share a name is a decision only the
25
+ * operator can make, and making it silently would destroy the evidence
26
+ * needed to make it correctly.
27
+ * 2. **Nothing is ever deleted.** The legacy directory is removed only when
28
+ * it is empty, and only because it then holds nothing to lose. Anything
29
+ * skipped keeps its home.
30
+ * 3. **Everything is counted and named** (ADR-19 correction 1), including on
31
+ * a clean run. "Moved 4, skipped 0" and silence are different reports, and
32
+ * only one of them is evidence.
33
+ *
34
+ * Usage:
35
+ * node scripts/migrate.mjs [--dir <.tyran>] # say what WOULD move
36
+ * node scripts/migrate.mjs [--dir <.tyran>] --apply # move it
37
+ *
38
+ * Exit: 0 nothing to do or done · 1 conflicts were skipped · 2 usage or I/O.
39
+ */
40
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmdirSync, statSync } from 'node:fs';
41
+ import { join, resolve } from 'node:path';
42
+
43
+ import { escapeInvisible } from './invisible.mjs';
44
+
45
+ /** The pre-0.1.9 home of the initiative directories. */
46
+ export const LEGACY_DIR = 'initiatives';
47
+ /** Where they live now. */
48
+ export const STATE_DIR = 'state';
49
+
50
+ const show = (value) => escapeInvisible(String(value));
51
+
52
+ function isDirectory(path) {
53
+ try {
54
+ return statSync(path).isDirectory();
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * What moving this `.tyran` would do, without doing any of it.
62
+ *
63
+ * Pure apart from reading the directory listing, so the dry run and the real
64
+ * run are the SAME computation — a preview produced by different code from the
65
+ * thing it previews is a preview of nothing.
66
+ *
67
+ * Returns `{ moves, conflicts, legacy, present }`, where a move is
68
+ * `{ name, from, to }` and a conflict additionally carries `why`.
69
+ */
70
+ export function planMigration(dir) {
71
+ const root = resolve(dir);
72
+ const legacy = join(root, LEGACY_DIR);
73
+ const state = join(root, STATE_DIR);
74
+ if (!isDirectory(legacy)) return { moves: [], conflicts: [], legacy, state, present: false };
75
+
76
+ const moves = [];
77
+ const conflicts = [];
78
+ // Sorted, so two runs on one tree report in the same order and a diff of two
79
+ // reports is about the tree rather than about readdir's mood.
80
+ for (const name of readdirSync(legacy).sort()) {
81
+ const from = join(legacy, name);
82
+ const to = join(state, name);
83
+ if (existsSync(to)) {
84
+ conflicts.push({
85
+ name,
86
+ from,
87
+ to,
88
+ why: isDirectory(to)
89
+ ? 'an initiative of this name already lives under state/ — merging them is a decision only you can make'
90
+ : 'a FILE of this name already exists under state/',
91
+ });
92
+ continue;
93
+ }
94
+ moves.push({ name, from, to });
95
+ }
96
+ return { moves, conflicts, legacy, state, present: true };
97
+ }
98
+
99
+ /**
100
+ * Carry out a plan. Idempotent: a second run finds nothing left to move and
101
+ * reports exactly that, which is what makes it safe to re-run after fixing a
102
+ * conflict by hand.
103
+ */
104
+ export function applyMigration(plan) {
105
+ const done = [];
106
+ for (const move of plan.moves) {
107
+ mkdirSync(plan.state, { recursive: true });
108
+ // `renameSync` and not a copy: a copy leaves two copies of an append-only
109
+ // journal on disk, and the next writer picks whichever path it was given.
110
+ // Same filesystem is the normal case; EXDEV is reported, not worked around
111
+ // silently, because a cross-device move here means `.tyran/` is stitched
112
+ // together from two mounts and the operator needs to know that.
113
+ renameSync(move.from, move.to);
114
+ done.push(move);
115
+ }
116
+ // Only when empty, and only after the moves: this removes a directory that
117
+ // by construction now holds nothing.
118
+ let removed = false;
119
+ if (plan.present && readdirSync(plan.legacy).length === 0) {
120
+ rmdirSync(plan.legacy);
121
+ removed = true;
122
+ }
123
+ return { done, removed };
124
+ }
125
+
126
+ export function renderPlan(plan, { applied = false, removed = false } = {}) {
127
+ const lines = [];
128
+ if (!plan.present) {
129
+ lines.push(`migrate: no ${LEGACY_DIR}/ under ${show(plan.legacy.replace(/\/[^/]+$/, ''))} — nothing to migrate`);
130
+ return lines.join('\n');
131
+ }
132
+ const verb = applied ? 'moved' : 'would move';
133
+ for (const m of plan.moves) lines.push(` ${verb} ${show(m.name)} ${show(m.from)} -> ${show(m.to)}`);
134
+ for (const c of plan.conflicts) lines.push(` SKIP ${show(c.name)} ${show(c.why)}`);
135
+ lines.push(
136
+ `migrate: ${plan.moves.length} ${applied ? 'moved' : 'to move'}, ${plan.conflicts.length} skipped` +
137
+ (removed ? `, ${LEGACY_DIR}/ removed (it was empty)` : ''),
138
+ );
139
+ if (!applied && plan.moves.length > 0) lines.push('migrate: re-run with --apply to move them');
140
+ if (plan.conflicts.length > 0) {
141
+ lines.push(
142
+ 'migrate: a skipped initiative is left untouched on BOTH sides. Merge it by hand, then re-run — ' +
143
+ 'this script never overwrites and never deletes.',
144
+ );
145
+ }
146
+ return lines.join('\n');
147
+ }
148
+
149
+ function usage(message) {
150
+ if (message) console.error(`migrate: ${message}`);
151
+ console.error('usage: node scripts/migrate.mjs [--dir <.tyran>] [--apply]');
152
+ process.exit(2);
153
+ }
154
+
155
+ function main(argv) {
156
+ const args = argv.slice(2);
157
+ for (const arg of args) {
158
+ if (!['--dir', '--apply'].includes(arg) && arg.startsWith('--')) usage(`unknown flag ${arg}`);
159
+ }
160
+ const i = args.indexOf('--dir');
161
+ if (i !== -1 && args[i + 1] === undefined) usage('--dir needs a path');
162
+ const dir = i === -1 ? '.tyran' : args[i + 1];
163
+ const apply = args.includes('--apply');
164
+
165
+ let plan;
166
+ try {
167
+ plan = planMigration(dir);
168
+ } catch (error) {
169
+ console.error(`migrate: could not read ${show(dir)}: ${error.message}`);
170
+ process.exit(2);
171
+ }
172
+ if (!apply) {
173
+ console.log(renderPlan(plan));
174
+ process.exit(0);
175
+ }
176
+ let result;
177
+ try {
178
+ result = applyMigration(plan);
179
+ } catch (error) {
180
+ console.error(`migrate: ${error.message}`);
181
+ console.error('migrate: nothing after the failure was attempted; re-running is safe.');
182
+ process.exit(2);
183
+ }
184
+ console.log(renderPlan(plan, { applied: true, removed: result.removed }));
185
+ // A conflict is the one outcome that still needs a human, so it is the one
186
+ // that must not exit 0 — an automated caller has to be able to tell "done"
187
+ // from "done except for the part that mattered".
188
+ process.exit(plan.conflicts.length > 0 ? 1 : 0);
189
+ }
190
+
191
+ if (import.meta.url === `file://${process.argv[1]}`) main(process.argv);
@@ -28,7 +28,7 @@ import {
28
28
  } from 'node:fs';
29
29
  import { dirname, join, resolve } from 'node:path';
30
30
  import { fileURLToPath } from 'node:url';
31
- import { readJournal, pairSpawns } from './journal.mjs';
31
+ import { readJournal, pairSpawns, spawnStaleness, isClosingPhase, DEFAULT_STALE_HOURS } from './journal.mjs';
32
32
  import { escapeInvisible, jsonEscapeInvisible } from './invisible.mjs';
33
33
 
34
34
  /** Projection file names. Both are fully generated — never hand-edited. */
@@ -51,6 +51,26 @@ const GENERATED_HEADER =
51
51
  */
52
52
  export const GATE_PASS = new Set(['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered']);
53
53
 
54
+ /**
55
+ * Gate results that mean the gate SAID NO — as opposed to not having answered.
56
+ *
57
+ * Enumerated rather than derived as "anything that is not a pass", which was
58
+ * the first shape of this and was wrong in a way the demo fixture caught at
59
+ * once: it classified `open` — a gate that has not run yet — as a refusal, so
60
+ * every pending gate carried a permanent objection it had never raised. A mark
61
+ * that fires on everything says nothing, which is the same argument the board
62
+ * makes for only ageing the lanes where standing still IS the defect.
63
+ *
64
+ * A refusal spelled some way this set has never seen is therefore missed
65
+ * rather than invented. That is the safer direction: a missing mark leaves the
66
+ * reader where they already were, while a false one sends them to re-open a
67
+ * decision nobody ever objected to.
68
+ */
69
+ export const GATE_REFUSAL = new Set([
70
+ 'deny', 'denied', 'fail', 'failed', 'red', 'refuse', 'refused',
71
+ 'reject', 'rejected', 'changes-requested', 'changes_requested', 'changes-needed', 'blocked',
72
+ ]);
73
+
54
74
  /** A gate result that means "a human owes an answer" — the board's queue. */
55
75
  export const WAITING_RE = /^waiting[_-]?on[_-]?(operator|owner|human)$/i;
56
76
  /** A gate kind that means "paused on the subscription window" (overnight mode). */
@@ -185,6 +205,31 @@ function sortByKey(items, keyOf) {
185
205
  .map(([item]) => item);
186
206
  }
187
207
 
208
+ /**
209
+ * The first of several near-synonymous descriptive keys that actually carries
210
+ * text, or null when none does.
211
+ *
212
+ * `data` may always carry extra keys (journal.mjs), and agents improvise: the
213
+ * same sentence arrives as `text` from one and `note` from another. Reading
214
+ * one and ignoring the rest is how prose gets written and never read.
215
+ *
216
+ * `evidence` may be a LIST — docs/journal.md's `evidence[]` — so a list of
217
+ * strings is joined rather than stringified into `[object Object]`. An empty
218
+ * string and a whitespace-only string are not text; falling through to the
219
+ * next candidate is better than rendering a blank cell that looks like a
220
+ * missing feature.
221
+ */
222
+ function firstText(...values) {
223
+ for (const value of values) {
224
+ if (typeof value === 'string' && value.trim() !== '') return value;
225
+ if (Array.isArray(value)) {
226
+ const parts = value.filter((v) => typeof v === 'string' && v.trim() !== '');
227
+ if (parts.length > 0) return parts.join(' · ');
228
+ }
229
+ }
230
+ return null;
231
+ }
232
+
188
233
  /** A Markdown table, or an explicitly empty marker — never a hidden section. */
189
234
  function table(headers, rows) {
190
235
  if (rows.length === 0) return '_none_\n';
@@ -304,6 +349,11 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
304
349
  // `ticket.status` events naming a ticket no other event mentions
305
350
  unknownOverrides: [],
306
351
  unknownErrorTickets: [],
352
+ // Spawns a closing checkpoint closed without a report of their own.
353
+ // Counted and named rather than silently flipped (ADR-19 correction 1):
354
+ // an agent that never reported is a hole in the record, and a close is
355
+ // the moment to say so, not to tidy it away.
356
+ closedBySpawn: [],
307
357
  };
308
358
 
309
359
  /**
@@ -409,6 +459,8 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
409
459
  status: 'running',
410
460
  verdict: null,
411
461
  reportTs: null,
462
+ // Set only by a closing checkpoint — see the `checkpoint` fold.
463
+ closedTs: null,
412
464
  };
413
465
  // An unusable name is NOT a correlator, so pairSpawns excludes it — and
414
466
  // this row must say so. The two answers that were available were
@@ -455,7 +507,24 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
455
507
  }
456
508
  if (data.ticket != null) {
457
509
  const t = ticketOf(data.ticket, ts);
458
- t.report = { verdict: data.verdict ?? null, ts, by: data.agent ?? actor };
510
+ t.report = {
511
+ verdict: data.verdict ?? null,
512
+ ts,
513
+ by: data.agent ?? actor,
514
+ // WHAT the agent said, not just whether it passed.
515
+ //
516
+ // Agents write prose on a report — `text`, `note`, `evidence` —
517
+ // and this fold read none of it, so a verdict of `changes-needed`
518
+ // arrived on the board with the reason it was written next to it
519
+ // silently discarded. `decision` already folds `data.text` and
520
+ // `gate` already folds `evidence_ref ?? evidence`; a report was
521
+ // the one carrier of description that wrote to nowhere.
522
+ //
523
+ // One field, coalesced in the order agents actually use, because
524
+ // three near-synonyms rendered as three separate rows is how the
525
+ // same answer ends up in three places (ADR-21).
526
+ text: firstText(data.text, data.note, data.evidence),
527
+ };
459
528
  t.override = null; // a lifecycle event outranks a hand-set lane
460
529
  t.error = null;
461
530
  }
@@ -514,9 +583,13 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
514
583
  case 'gate': {
515
584
  const kind = String(data.kind ?? '(no kind)');
516
585
  const prev = state.gates.get(kind);
586
+ const result = data.result ?? null;
587
+ // A refusal is a gate that SAID NO, not one that has yet to answer —
588
+ // see GATE_REFUSAL for why this is a named set rather than "not a pass".
589
+ const refused = GATE_REFUSAL.has(String(result ?? '').trim().toLowerCase());
517
590
  state.gates.set(kind, {
518
591
  kind,
519
- result: data.result ?? null,
592
+ result,
520
593
  ts,
521
594
  evidence: data.evidence_ref ?? data.evidence ?? null,
522
595
  // extra data keys are legal on append; the ask fields ride along so
@@ -527,6 +600,20 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
527
600
  recommendation: data.recommendation ?? null,
528
601
  default: data.default ?? null,
529
602
  count: (prev?.count ?? 0) + 1,
603
+ // Gate results are keyed by `kind`, so the latest one wins the slot —
604
+ // and a re-run that passes therefore ERASED the refusal that came
605
+ // before it. That is precisely the signal a gate exists to raise:
606
+ // "the security gate denied this, then someone re-ran it green" and
607
+ // "the security gate has only ever passed" rendered identically, and
608
+ // the second reading is the one an operator took away.
609
+ //
610
+ // `count` already survived, so the VOLUME was never lost — only the
611
+ // verdict. So this is additive and narrow: the last refusal is kept
612
+ // beside the current result, never instead of it, and the counter is
613
+ // left exactly as it was.
614
+ lastRefusal: refused
615
+ ? { result, ts, evidence: data.evidence_ref ?? data.evidence ?? null, ticket: data.ticket ?? null }
616
+ : prev?.lastRefusal ?? null,
530
617
  });
531
618
  break;
532
619
  }
@@ -572,9 +659,34 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
572
659
  else state.mismatchedReleases.push({ resource: key, by: data.holder ?? null, holder: held?.holder ?? null, ts });
573
660
  break;
574
661
  }
575
- case 'checkpoint':
662
+ case 'checkpoint': {
576
663
  state.checkpoint = { phase: data.phase ?? null, nextSteps: data.next_steps, ts, actor };
664
+ // A closing checkpoint closes the initiative's still-open spawns.
665
+ //
666
+ // This fold used to record the checkpoint and nothing else, so an
667
+ // initiative could be explicitly wound up while three agents that
668
+ // never reported stayed `running` in every artefact forever. No other
669
+ // event closes an initiative, which is why the meaning has to hang on
670
+ // this one reserved phase value.
671
+ //
672
+ // Only spawns folded BEFORE this point: the pass runs in event order,
673
+ // so an agent spawned after the checkpoint is a new incarnation and
674
+ // keeps its own lifecycle. And only `running` ones — a spawn already
675
+ // paired with a report, or excluded for an unusable name, has an
676
+ // answer of its own that this must not overwrite.
677
+ if (isClosingPhase(data.phase)) {
678
+ for (const a of state.agents) {
679
+ if (a.status !== 'running') continue;
680
+ a.status = 'closed with the initiative (no report)';
681
+ // Not a report: the agent never filed one, and pretending it did
682
+ // would put a verdict on the row that nobody earned. The time is
683
+ // when the initiative ended, which is what "since" means here.
684
+ a.closedTs = ts;
685
+ state.closedBySpawn.push({ agent: a.agent, ticket: a.ticket ?? null, spawnTs: a.spawnTs, ts });
686
+ }
687
+ }
577
688
  break;
689
+ }
578
690
  case 'retro.entry':
579
691
  state.retro.push({ kind: data.kind ?? null, target: data.target ?? null, confidence: data.confidence ?? null, ts });
580
692
  break;
@@ -678,7 +790,7 @@ export const APPROVING_RE = /^approv|^lgtm$|^pass/i;
678
790
  * in-progress > ready (all deps merged; an UNKNOWN dep counts unmet — a
679
791
  * typo must refuse to schedule, not schedule) > backlog.
680
792
  */
681
- export function boardOf(state) {
793
+ export function boardOf(state, { staleHours = DEFAULT_STALE_HOURS } = {}) {
682
794
  const lanes = new Map(LANES.map((lane) => [lane, []]));
683
795
  const runningByTicket = new Map();
684
796
  for (const a of state.agents) {
@@ -792,6 +904,11 @@ export function boardOf(state) {
792
904
  // board dropped it.
793
905
  worked_by: sortedUnique(t.agents),
794
906
  since: t.lastTs,
907
+ // What the agent SAID when it handed the ticket back, not only whether
908
+ // it passed. A `changes-needed` card used to arrive with its reason
909
+ // discarded at fold time, so the board could say a ticket had come back
910
+ // and never why — the one thing the reader opens the card for.
911
+ report_text: t.report?.text ?? null,
795
912
  annotation: annotations.length > 0 ? annotations.join(' · ') : null,
796
913
  });
797
914
  }
@@ -801,11 +918,30 @@ export function boardOf(state) {
801
918
  .map((a) => {
802
919
  const signal = state.progressByAgent.get(a.agent) ?? null;
803
920
  const evidence = state.evidenceByAgent.get(a.agent) ?? null;
921
+ // Doctor's rule, imported rather than restated (ADR-21). Nothing here
922
+ // ever downgraded a spawn, so an agent that never reported stayed
923
+ // `running` forever and the header counted week-old ghosts as live —
924
+ // while doctor, reading the same journal, had been calling them
925
+ // abandoned the whole time. Two answers, one question.
926
+ //
927
+ // Measured against `state.lastTs`, the journal's own latest event, so
928
+ // this stays clock-free like the rest of `boardOf`: `board.json` is
929
+ // byte-compared by `--check`, and a wall-clock verdict would make two
930
+ // clones of one journal disagree. It is also the more useful meaning —
931
+ // stale is "the initiative moved on without it", not "you looked late".
932
+ const { ageHours, stale } = spawnStaleness(a.spawnTs, state.lastTs, staleHours);
804
933
  return {
805
934
  agent: a.agent,
806
935
  role: a.role,
807
936
  ticket: a.ticket,
808
- state: signal?.state ?? 'running',
937
+ // `blocked` outranks `stale`: it is the agent's own account of why it
938
+ // stopped, and it is what the waiting-operator tile counts. Staleness
939
+ // is what we infer when there is no such account.
940
+ state: signal?.state === 'blocked' ? 'blocked' : stale ? 'stale' : signal?.state ?? 'running',
941
+ // Carried separately as well, because `state` is one slot and a
942
+ // consumer may want the verdict without losing what the agent said.
943
+ stale,
944
+ open_hours: ageHours === null ? null : Math.round(ageHours * 10) / 10,
809
945
  detail: signal?.detail ?? null,
810
946
  next: signal?.next ?? null,
811
947
  last_signal: signal?.ts ?? a.spawnTs,
@@ -970,6 +1106,17 @@ export function warnings(state) {
970
1106
  for (const { raw, problem } of state.unusableAgentNames) {
971
1107
  out.push(`unusable data.agent ${inlinePlain(raw)}: ${problem} — excluded from spawn/report pairing`);
972
1108
  }
1109
+ // A close that closed something is a fact about the record, not bookkeeping:
1110
+ // these agents never said how their work ended, and the checkpoint decided
1111
+ // for them. Naming them is what makes the difference between "finished" and
1112
+ // "stopped being tracked" visible after the fact.
1113
+ for (const { agent, ticket } of state.closedBySpawn) {
1114
+ out.push(
1115
+ `agent ${inlinePlain(agent)} was still open when the initiative closed${
1116
+ ticket == null ? '' : ` (ticket ${inlinePlain(ticket)})`
1117
+ } — closed by the checkpoint, with no report of its own`,
1118
+ );
1119
+ }
973
1120
  // The state ADR-18 makes unrepresentable through `append`, and which the
974
1121
  // projection no longer silently guesses at now that ticket-first is gone.
975
1122
  for (const { agent, count } of state.ambiguousAgents) {
@@ -1094,14 +1241,19 @@ function renderState(state) {
1094
1241
  );
1095
1242
 
1096
1243
  parts.push('\n## All gates\n\n');
1244
+ // "Last refusal" is the column that makes a re-run visible. The latest
1245
+ // result wins the row, so a gate that denied and was then re-run green read
1246
+ // exactly like a gate that had never objected to anything — the one reading
1247
+ // an operator must not be given by accident.
1097
1248
  parts.push(
1098
1249
  table(
1099
- ['Gate', 'Latest result', 'Events', 'At'],
1250
+ ['Gate', 'Latest result', 'Events', 'At', 'Last refusal'],
1100
1251
  sortByKey([...state.gates.values()], (g) => g.kind).map((g) => [
1101
1252
  inline(g.kind),
1102
1253
  inline(g.result),
1103
1254
  String(g.count),
1104
1255
  inline(g.ts),
1256
+ g.lastRefusal == null ? inline(null) : `${inline(g.lastRefusal.result)} at ${inline(g.lastRefusal.ts)}`,
1105
1257
  ]),
1106
1258
  ),
1107
1259
  );