@jjanczur/tyran 0.1.30 → 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.
@@ -11,7 +11,7 @@
11
11
  {
12
12
  "name": "tyran",
13
13
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
14
- "version": "0.1.30",
14
+ "version": "0.1.31",
15
15
  "source": "./",
16
16
  "author": {
17
17
  "name": "Jacek Janczura",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tyran",
3
- "version": "0.1.30",
3
+ "version": "0.1.31",
4
4
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
5
5
  "author": {
6
6
  "name": "Jacek Janczura",
package/CHANGELOG.md CHANGED
@@ -1,5 +1,140 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.31 — 2026-08-17
4
+
5
+ Seven things the journal had recorded and nothing was reading. The theme is
6
+ one defect wearing different clothes: an answer that was available, a
7
+ consumer that never asked for it, and a surface that reported confidence
8
+ instead of the gap.
9
+
10
+ ### Four things the fold recorded and threw away
11
+
12
+ Each of these was a question an operator asked the board, got a confident
13
+ answer to, and the answer was wrong in the same direction: everything looked
14
+ fine.
15
+
16
+ **An agent the initiative moved on without now reads `stale`, not `running`.**
17
+ Nothing in the projection ever downgraded a spawn, so an agent that never
18
+ reported stayed `running` in every artefact for as long as the journal
19
+ survived, and the board's header counted week-old ghosts as live work. Doctor
20
+ had been calling those same spawns abandoned the whole time, from the same
21
+ events — two answers to one question, which is the defect ADR-21 is named
22
+ after and which `pairSpawns` had already been through once for the adjacent
23
+ question of who is still working.
24
+
25
+ There is now one predicate, `journal.spawnStaleness`, and both consumers call
26
+ it; doctor's copy is gone rather than kept in sync. It could not live in
27
+ doctor, which imports the projection, so it sits in `journal.mjs` beside
28
+ `pairSpawns` where both already reach.
29
+
30
+ The threshold is journal time — measured against the initiative's own latest
31
+ event, never the wall clock. That is what `spawn-stale` has always meant, and
32
+ it is the only version that keeps `board.json` byte-exact under `--check`.
33
+ `blocked` still outranks `stale`, because that is the agent's own account of
34
+ why it stopped. The `age-fresh/warm/cold/dead` colours on the page are a
35
+ different question and keep their own vocabulary: an agent can be quiet for
36
+ hours without being stale, and stale while chattering every minute.
37
+
38
+ **A closing checkpoint closes the spawns it leaves open.** No event type
39
+ closed an initiative, so one could be explicitly wound up with three agents
40
+ that never reported still running forever. `checkpoint` with `phase: closed`
41
+ — the one reserved value in an otherwise free-text field — now closes that
42
+ initiative's still-open spawns at fold time, and only the ones folded before
43
+ it, so an agent spawned afterwards keeps its own lifecycle. They are closed,
44
+ never reported: no verdict is invented for an agent that never filed one, and
45
+ each is named in the warnings rather than tidied away.
46
+
47
+ **A gate that passes after refusing no longer erases the refusal.** Results
48
+ are keyed by `kind`, so a re-run won the slot, and *"security denied this,
49
+ then someone re-ran it green"* rendered identically to *"security has only
50
+ ever passed"*. The event count always survived, so the volume was never lost
51
+ — only the verdict. The last refusal is kept beside the current result and
52
+ gets its own column in `STATE.md`. A refusal is a named set (`deny`, `fail`,
53
+ `rejected`, …) rather than "anything that is not a pass": the first draft was
54
+ the latter, and the demo fixture caught it at once, marking every `open` gate
55
+ as carrying a permanent objection it had never raised.
56
+
57
+ **A report carries what the agent said, not only its verdict.** `decision`
58
+ folds its `text` and `gate` folds its `evidence`; `report` was the one carrier
59
+ of description that wrote to nowhere, so a `changes-needed` card reached the
60
+ board with the reason it came back discarded at fold time. One field reads
61
+ `text`, then `note`, then `evidence`, because agents improvise the key.
62
+
63
+ The board header now says *open* rather than *running* and names the stale
64
+ count beside it — the agents are still counted and still in the strip, but an
65
+ open spawn and live work are not the same fact and the tile was asserting the
66
+ second from the first.
67
+
68
+ ### The two findings doctor could only ever report
69
+
70
+ `state-legacy-initiatives-dir` shipped with a remedy that read "relocate the
71
+ contents by hand, one initiative directory at a time". That is advice, not a
72
+ remedy, and the installs carrying the finding are by definition the ones
73
+ nobody has touched since 0.1.8. `scripts/migrate.mjs` does the move.
74
+
75
+ It is explicit and never automatic, because it MOVES an append-only history
76
+ rather than seeding a file that does not exist yet — the same reason it is not
77
+ a step inside setup. It previews by default and does nothing until asked twice.
78
+ It never overwrites: a name that already exists under `state/` is a conflict,
79
+ reported and skipped and left untouched on **both** sides, because merging two
80
+ directories that share a name is a decision only the operator can make and
81
+ making it silently would destroy the evidence needed to make it correctly. It
82
+ never deletes anything it did not itself empty. It is idempotent, and it exits
83
+ 1 while any conflict stands, so an automated caller can tell "done" from "done
84
+ except for the part that mattered".
85
+
86
+ **`mistakes-file-missing`** (`info`) splits an absence that used to be one
87
+ thing. Deleting `MISTAKES.md` is the documented opt-out and still produces no
88
+ finding at all — a tool that nags about a file you deliberately removed is a
89
+ tool you switch off, and that would cost the gates sitting next to it. But an
90
+ install created before the ledger existed never declined anything; nobody
91
+ offered. Git is the only witness that can tell those apart, so the finding
92
+ fires only where git can answer AND has never seen the file. Where there is no
93
+ repository, or no git, it says nothing rather than guessing — a guess there
94
+ nags precisely the operator who already opted out.
95
+
96
+ Neither is an alarm, but for different reasons.
97
+ `state-legacy-initiatives-dir` stays a `warning` — a legacy layout genuinely
98
+ hides initiative files from every mechanical consumer — and what changed is
99
+ that it finally has a remedy rather than a paragraph of advice.
100
+ `mistakes-file-missing` is `info` because nothing is broken at all: it is an
101
+ offer, and the only absence it will ever break silence about is the one
102
+ nobody chose.
103
+
104
+ ### Accept-then-ignore, ended without nagging
105
+
106
+ `append` accepts any key inside `data` and always will: *"data may always
107
+ carry extra keys"* is a promise the envelope makes, the evidence gate relies
108
+ on it for four of its own, and turning it into a rule would fail every journal
109
+ ever written the moment they were re-validated. So this is a report, never a
110
+ refusal — and it is deliberately not the whole report.
111
+
112
+ Measured on one real install: **130 distinct (event, key) pairs across 39
113
+ initiatives**, and the long tail of that is deliberate annotation —
114
+ `init.created.hardware`, `retro.entry.proposed_as_diffs`, `spawn.stories`.
115
+ Naming all of it as findings would report the extension mechanism working as
116
+ designed, on every healthy repo, and doctor's own severity notes already argue
117
+ where that ends: a check that is red during normal operation is a check people
118
+ learn to skip — and this one sits next to the gates.
119
+
120
+ The defect hiding in that tail is narrower and worth a warning each.
121
+ **`journal-key-near-miss`** reports a key one edit from the key consumers
122
+ actually read: `next_step` for `next_steps` is accepted, never read, and never
123
+ reported, so the resume surface is empty while the agent that wrote it
124
+ believes it recorded something. Distance one and nothing looser — at two,
125
+ `note` matches `next` and the check starts inventing typos in correct
126
+ journals. Keys of three characters or fewer are exempt for the same reason.
127
+
128
+ **`journal-key-unread`** (`info`) counts and names the rest, so nothing is
129
+ dropped (ADR-19 correction 1) and "recorded" stays distinguishable from
130
+ "recorded AND read" — without turning a documented contract into 130 rows of
131
+ alarm.
132
+
133
+ `DATA_KNOWN` in `journal.mjs` is the map of what each event type's consumers
134
+ read, and it sits next to `DATA_REQUIRED` because both answer "what is in
135
+ `data`". It is descriptive: an incomplete entry can only under-report, never
136
+ invent a finding.
137
+
3
138
  ## 0.1.30 — 2026-08-17
4
139
 
5
140
  The first release built on an outside contribution. It fixes a spend ledger
package/README.md CHANGED
@@ -297,7 +297,7 @@ enforces the cap (4352 of 5000 characters). What each one assumes, when it
297
297
  fires and who invokes it, is in
298
298
  [skills and agents](https://jjanczur.github.io/tyran/skills/); the prompts
299
299
  themselves are in [`skills/`](skills/) and [`agents/`](agents/). Behind all of
300
- it: 1417 unit tests, run with `node --test "tests/**/*.test.mjs"`.
300
+ it: 1451 unit tests, run with `node --test "tests/**/*.test.mjs"`.
301
301
 
302
302
  ## Documentation
303
303
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.30",
3
+ "version": "0.1.31",
4
4
  "description": "Command-line scripts for the Tyran task conductor (doctor, journal, schema, and repo tooling) for CI and terminals outside Claude Code. Installing this package does NOT install the Claude Code plugin — add that separately with `/plugin marketplace add jjanczur/tyran` inside Claude Code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -98,6 +98,12 @@ h3{font-family:var(--font);color:var(--heading);font-size:.85rem;margin:1.1rem 0
98
98
  .agent .age-fresh{color:var(--sage)}
99
99
  .agent .age-warm{color:var(--brass-bright)}
100
100
  .agent .age-cold{color:var(--clay)}
101
+ /* Stale is a SERVER verdict in journal time, so it marks the whole chip rather
102
+ than joining the wall-clock age colours below — two different questions must
103
+ not share one vocabulary. Muted border, not red: an abandoned agent is a
104
+ bookkeeping fact, while the red below is "this died mid-flight". */
105
+ .agent.stale{border-left-color:var(--brass);opacity:.82}
106
+ .agent .stale-mark{color:var(--brass-bright);font-weight:600}
101
107
  /* A dead agent gets the only bold red on the page: three hours of silence is
102
108
  a different event from thirty minutes, and it used to share a colour. */
103
109
  .agent .age-dead{color:var(--clay-bright);font-weight:700}
@@ -423,9 +429,20 @@ if (data.schema !== 1) {
423
429
  var strip = el('div', 'agents');
424
430
  if (agents.length === 0) strip.appendChild(el('div', 'empty', 'none running'));
425
431
  agents.forEach(function (a) {
426
- var chip = el('div', 'agent');
432
+ var chip = el('div', 'agent' + (a.stale ? ' stale' : ''));
427
433
  chip.appendChild(el('div', 'name', a.agent + (a.role ? ' · ' + a.role : '')));
428
434
  chip.appendChild(el('div', null, (a.init ? a.init + ' · ' : '') + (a.ticket || 'no ticket') + ' · ' + a.state));
435
+ // NOT the same statement as the age lines below, and the wording keeps
436
+ // them apart on purpose. Those are wall-clock: "how long since it spoke,
437
+ // right now, where you are sitting". This one is journal time and comes
438
+ // from the server, where doctor's own threshold computed it — "the
439
+ // initiative moved on without it", which is still true tomorrow and is
440
+ // the same for every reader of this journal. An agent can be quiet for
441
+ // hours without being stale, and stale while chattering every minute.
442
+ if (a.stale) {
443
+ chip.appendChild(el('div', 'stale-mark',
444
+ 'STALE — open ' + (a.open_hours === null ? '?' : a.open_hours) + ' h of journal time'));
445
+ }
429
446
  if (a.detail) chip.appendChild(el('div', 'note', a.detail));
430
447
  // What the agent said it would do next. It has been in board.json since
431
448
  // the fold learned to read progress events, and the strip has never
@@ -473,7 +490,16 @@ if (data.schema !== 1) {
473
490
  var ovTiles = el('div', 'tiles');
474
491
  ovTiles.appendChild(tile('waiting on you', String(asks.length),
475
492
  asks.length === 0 ? 'nothing blocked on a decision' : 'answer them on the next tab', asks.length > 0 ? 'lead' : null));
476
- ovTiles.appendChild(tile('agents running', String(agents.length), 'across ' + (totals.initiatives || 0) + ' initiative(s)'));
493
+ // The headline number is the LIVE one. "Agents running" counted every open
494
+ // spawn, so an initiative abandoned a week ago reported a busy fleet; the
495
+ // stale ones are still counted, still listed in the strip, and now said out
496
+ // loud rather than folded into a figure that reads as live work.
497
+ var staleCount = totals.agents_stale || 0;
498
+ ovTiles.appendChild(tile('agents running', String(agents.length - staleCount),
499
+ staleCount > 0
500
+ ? staleCount + ' more stale · across ' + (totals.initiatives || 0) + ' initiative(s)'
501
+ : 'across ' + (totals.initiatives || 0) + ' initiative(s)',
502
+ staleCount > 0 ? 'lead' : null));
477
503
  // An initiative with no tickets used to read "0% · 0 of 0 merged", which is
478
504
  // exactly what a fully stalled one reads. Nothing-started and
479
505
  // nothing-finished are different situations and deserve different words.
@@ -605,6 +631,10 @@ if (data.schema !== 1) {
605
631
  // is already done — precisely when the running-agents list is empty.
606
632
  row('worked by', card.worked_by && card.worked_by.length ? card.worked_by.join(', ') : null);
607
633
  row('note', card.annotation);
634
+ // What the agent SAID when it handed this back. The verdict alone told you
635
+ // a ticket had come back and never why, which is the one thing the card is
636
+ // opened for.
637
+ row('reported', card.report_text);
608
638
  row('last event', card.since ? ago(card.since) + ' (' + card.since + ')' : null);
609
639
  if (cost) {
610
640
  var hit = (cost.by_ticket || []).filter(function (r) { return r.ticket === card.id; })[0];
package/scripts/board.mjs CHANGED
@@ -263,6 +263,12 @@ export function crossBoard({ initiatives, errors, warned = [], stop = null }) {
263
263
  totals: {
264
264
  initiatives: initiatives.length,
265
265
  agents: agents.length,
266
+ // Of those, how many the journal has moved on without. `agents` counts
267
+ // OPEN spawns, which is what it has always counted and what the strip
268
+ // lists — but presenting that number as "running" made a week-old ghost
269
+ // indistinguishable from an agent working right now, and an overnight
270
+ // operator reads this tile before anything else on the page.
271
+ agents_stale: agents.filter((a) => a.stale === true).length,
266
272
  merged,
267
273
  tickets,
268
274
  percent: tickets === 0 ? 0 : Math.round((merged / tickets) * 100),
@@ -306,8 +312,12 @@ export function crossJson(payload) {
306
312
  export function renderCrossMd(payload) {
307
313
  const parts = [GENERATED_MD_HEADER, '# BOARD — all initiatives\n\n'];
308
314
  const t = payload.totals;
315
+ // "open", not "running": the headline used to assert that every open spawn
316
+ // was live work, and the stale ones are named right after it rather than
317
+ // being quietly dropped from the count (ADR-19 correction 1).
309
318
  parts.push(
310
- `**${t.agents} agent(s) running across ${t.initiatives} initiative(s) · ` +
319
+ `**${t.agents} agent(s) open across ${t.initiatives} initiative(s)` +
320
+ `${t.agents_stale > 0 ? `, ${t.agents_stale} stale` : ''} · ` +
311
321
  `${t.merged}/${t.tickets} tickets merged (${t.percent}%) · as of ${inline(payload.as_of)}**\n`,
312
322
  );
313
323
  // First, and above the pause: a STOP outranks everything. It is the one
@@ -39,7 +39,16 @@ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'n
39
39
  import { join, dirname, resolve, basename } from 'node:path';
40
40
  import { fileURLToPath } from 'node:url';
41
41
  import { checkHooks, DEFAULT_PLUGIN_ROOT } from './hooks-check.mjs';
42
- import { readJournal, validateJournal, pairSpawns, tail } from './journal.mjs';
42
+ import {
43
+ readJournal,
44
+ validateJournal,
45
+ pairSpawns,
46
+ tail,
47
+ hoursBetween,
48
+ spawnStaleness,
49
+ unreadDataKeys,
50
+ DEFAULT_STALE_HOURS,
51
+ } from './journal.mjs';
43
52
  import {
44
53
  boardOf,
45
54
  checkFile,
@@ -59,8 +68,14 @@ import { parseMistakes, countSignatures, fenceState, KNOWLEDGE_THRESHOLD, MISTAK
59
68
  /** Severity order is also the report order. `info` never fails the check. */
60
69
  export const SEVERITIES = Object.freeze(['error', 'warning', 'info']);
61
70
 
62
- /** Default: an agent open this long without the journal moving on is stuck. */
63
- export const DEFAULT_STALE_HOURS = 4;
71
+ /**
72
+ * Default: an agent open this long without the journal moving on is stuck.
73
+ *
74
+ * Re-exported, not redefined. The threshold and the comparison both live in
75
+ * `journal.mjs` so the board renders doctor's answer instead of computing a
76
+ * second one — `--stale-hours` still moves it for this report alone.
77
+ */
78
+ export { DEFAULT_STALE_HOURS };
64
79
 
65
80
  const JOURNAL_FILE = 'journal.jsonl';
66
81
 
@@ -222,6 +237,16 @@ export const SEVERITY_BY_CODE = Object.freeze(
222
237
  // red during normal operation is a check people learn to skip.
223
238
  'mistakes-unreadable': 'warning',
224
239
  'mistakes-repeat-unpromoted': 'info',
240
+ // `info`, and it fires only where git proves the file NEVER existed —
241
+ // a deletion is the documented opt-out and stays silent. See
242
+ // `absentMistakes` for why the two need telling apart at all.
243
+ 'mistakes-file-missing': 'info',
244
+ // Data keys nothing reads. The near miss is a WARNING because it is silent
245
+ // data loss and a healthy journal has none; the plain count is `info`
246
+ // because extra keys are what the envelope promises, and a warning per
247
+ // improvised key would be red on every healthy repo.
248
+ 'journal-key-near-miss': 'warning',
249
+ 'journal-key-unread': 'info',
225
250
  'claude-md-fence-missing': 'info',
226
251
  // overnight mode
227
252
  'limit-pause-active': 'info',
@@ -300,12 +325,8 @@ function isDirectory(path) {
300
325
  }
301
326
  }
302
327
 
303
- function hoursBetween(fromTs, toTs) {
304
- const from = Date.parse(fromTs);
305
- const to = Date.parse(toTs);
306
- if (Number.isNaN(from) || Number.isNaN(to)) return null;
307
- return (to - from) / 3_600_000;
308
- }
328
+ // `hoursBetween` is imported from journal.mjs, next to the staleness rule it
329
+ // serves — see the note on `spawnStaleness` for why that rule cannot live here.
309
330
 
310
331
  // -------------------------------------------------------- policy analysis
311
332
 
@@ -521,6 +542,7 @@ function checkInitiative(stateDir, name, { now, staleHours }) {
521
542
  }
522
543
  };
523
544
  guard('journal integrity', () => journalIntegrity(journalPath, at, read));
545
+ guard('data keys nothing reads', () => unreadKeyFindings(at, events));
524
546
  guard('one initiative per file', () => initiativeScope(journalPath, at, name, events));
525
547
  guard('open spawns', () => spawnFindings(journalPath, at, name, events, reference, staleHours));
526
548
  guard('operator asks', () => askFindings(journalPath, at, read, reference));
@@ -702,6 +724,61 @@ function closeSpawnHint(journalPath, init, agent) {
702
724
  : `node scripts/journal.mjs close-spawn ${sq(journalPath)} ${sq(slug)} ${sq(agent)} --reason "<why>"`;
703
725
  }
704
726
 
727
+ /** How many unread keys are named before the rest are counted instead. */
728
+ const MAX_NAMED_KEYS = 12;
729
+
730
+ /**
731
+ * Data keys nothing reads — the end of accept-then-ignore, minus the nagging.
732
+ *
733
+ * `append` accepts any key by design, and it must: `data may always carry
734
+ * extra keys` is the envelope's promise, the evidence gate writes four of its
735
+ * own, and turning it into a rule would fail every journal ever written. So
736
+ * this is a REPORT, never a refusal, and it splits into two sentences because
737
+ * the two situations are not the same failure.
738
+ *
739
+ * A NEAR MISS is the defect: `next_step` for `next_steps` is accepted,
740
+ * ignored, and leaves the resume surface empty while the agent that wrote it
741
+ * believes it recorded something. That is worth a warning each, because it is
742
+ * silent data loss and a healthy journal has none.
743
+ *
744
+ * Everything else is the contract working. Measured on one real install: 130
745
+ * distinct (event, key) pairs across 39 initiatives, nearly all of it
746
+ * deliberate annotation. Those are COUNTED — never dropped, ADR-19 correction
747
+ * 1 — at `info`, in one line, because a warning per improvised key would go
748
+ * red on every healthy repo and a check that is red during normal operation is
749
+ * a check people learn to skip.
750
+ */
751
+ function unreadKeyFindings(at, events) {
752
+ const { unread, nearMisses } = unreadDataKeys(events);
753
+ const findings = nearMisses.map((m) =>
754
+ finding(
755
+ 'journal-key-near-miss',
756
+ at,
757
+ `${m.count} ${show(m.ev)} event(s) carry \`${show(m.key)}\`, one edit from \`${show(m.meant)}\`, which is ` +
758
+ 'the key consumers actually read. A misspelled key is accepted, never read, and never reported — ' +
759
+ 'the writer believes it recorded something and nothing did',
760
+ `node scripts/journal.mjs query ${sq(at)} --ev ${sq(m.ev)} # then correct the writer; the journal is append-only, so past events keep the typo`,
761
+ ),
762
+ );
763
+ // Named minus the near-misses: those already have a finding of their own,
764
+ // and listing them twice would read as twice as many problems.
765
+ const rest = [...unread.keys()].filter((id) => !nearMisses.some((m) => `${m.ev}.${m.key}` === id)).sort();
766
+ if (rest.length > 0) {
767
+ const shown = rest.slice(0, MAX_NAMED_KEYS).map((id) => `${id} x${unread.get(id)}`).join(', ');
768
+ findings.push(
769
+ finding(
770
+ 'journal-key-unread',
771
+ at,
772
+ `${rest.length} data key(s) that no consumer reads: ${show(shown)}` +
773
+ (rest.length > MAX_NAMED_KEYS ? ` (+${rest.length - MAX_NAMED_KEYS} more)` : '') +
774
+ '. Extra keys are legal and this is not a defect — it is what the envelope promises. Stated so ' +
775
+ 'that "recorded" and "recorded AND read" stay distinguishable',
776
+ ),
777
+ );
778
+ }
779
+ return findings;
780
+ }
781
+
705
782
  /** How long a self-reported `blocked` may stand before it is a finding. */
706
783
  export const DEFAULT_BLOCKED_HOURS = 1;
707
784
 
@@ -722,7 +799,10 @@ function spawnFindings(journalPath, at, dirName, events, reference, staleHours)
722
799
  const signals = lastSignals(events);
723
800
  for (const agent of sortedNames(open.keys())) {
724
801
  for (const spawn of open.get(agent)) {
725
- const age = reference === null ? null : hoursBetween(spawn.ts, reference);
802
+ // The shared rule, not a local one: the board reads the same predicate,
803
+ // so an agent doctor calls abandoned can never still read `running`
804
+ // there. `--stale-hours` moves the threshold for this report alone.
805
+ const { ageHours: age, stale } = spawnStaleness(spawn.ts, reference, staleHours);
726
806
  const where = `${show(spawn.data.ticket ?? 'no ticket')}, role ${show(spawn.data.role)}`;
727
807
  // `lastSignals` is keyed by agent NAME, and ADR-18 permits a name to be
728
808
  // re-spawned once its previous spawn is closed — so the latest signal
@@ -745,7 +825,7 @@ function spawnFindings(journalPath, at, dirName, events, reference, staleHours)
745
825
  closeSpawnHint(journalPath, spawn.init ?? dirName, agent),
746
826
  ),
747
827
  );
748
- } else if (age !== null && age >= staleHours) {
828
+ } else if (stale) {
749
829
  findings.push(
750
830
  finding(
751
831
  'spawn-stale',
@@ -1289,9 +1369,56 @@ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
1289
1369
  * owned by `mistakes.mjs`, the same discipline doctor already follows for
1290
1370
  * `validateKnowledge` and `pairSpawns` (ADR-18).
1291
1371
  */
1292
- export function mistakesFindings(repoRoot) {
1372
+
1373
+ /**
1374
+ * Absence, split into the two situations that look identical on disk.
1375
+ *
1376
+ * Deleting the file is the documented opt-out and it stays silent — a tool
1377
+ * that nags about a file you deliberately removed is a tool you disable, and
1378
+ * that argument has not changed. But an install created before this ledger
1379
+ * existed never made that choice: there is nothing to opt out of, nobody was
1380
+ * ever offered the file, and silence there is not respect for a decision, it
1381
+ * is a feature the operator has never heard of.
1382
+ *
1383
+ * Git is the only witness that can tell the two apart. A file with history is
1384
+ * one somebody had and removed; a file with no history in a repo git can read
1385
+ * never existed. When git cannot answer at all — no repository, no git on the
1386
+ * PATH — this says NOTHING, because a guess here would nag exactly the
1387
+ * operator who already opted out.
1388
+ *
1389
+ * `info`, never a warning: nothing is broken, and the check exists to make an
1390
+ * offer rather than to report a defect.
1391
+ */
1392
+ function absentMistakes(repoRoot, path, run) {
1393
+ const checked = `${MISTAKES_FILE}: absent`;
1394
+ if (run === null) return { findings: [], checked };
1395
+ // The same probe `untrackedTyranDir` uses, for the same reason: `run`
1396
+ // returns '' for "git said nothing" and for "git is not here", and those
1397
+ // need opposite conclusions.
1398
+ if (run(['rev-parse', '--is-inside-work-tree']).trim() !== 'true') {
1399
+ return { findings: [], checked: `${checked} (no git here to say whether it ever existed)` };
1400
+ }
1401
+ const history = run(['log', '--max-count=1', '--format=%H', '--', MISTAKES_FILE]).trim();
1402
+ if (history !== '') {
1403
+ return { findings: [], checked: `${checked} — deleted deliberately, which IS the opt-out` };
1404
+ }
1405
+ return {
1406
+ findings: [
1407
+ finding(
1408
+ 'mistakes-file-missing',
1409
+ show(path),
1410
+ `no ${MISTAKES_FILE}, and git has never seen one — this repository predates the incident ledger ` +
1411
+ 'rather than having opted out of it. Nothing is broken; the ledger is what turns a mistake that ' +
1412
+ 'happened three times into a rule that stops the fourth',
1413
+ `node scripts/scan-repo.mjs --dir ${sq(repoRoot)} --ensure-policy # seeds it from the shipped template; deleting it again is the opt-out, and this will not put it back on its own`,
1414
+ ),
1415
+ ],
1416
+ checked: `${checked} — never existed`,
1417
+ };
1418
+ }
1419
+ export function mistakesFindings(repoRoot, run = null) {
1293
1420
  const path = join(repoRoot, MISTAKES_FILE);
1294
- if (!existsSync(path)) return { findings: [], checked: `${MISTAKES_FILE}: absent` };
1421
+ if (!existsSync(path)) return absentMistakes(repoRoot, path, run);
1295
1422
 
1296
1423
  let parsed;
1297
1424
  try {
@@ -1656,13 +1783,18 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1656
1783
  'legacy layout — initiative files (PLAN.md, NOTES.md, RETRO.md, locks/) live under ' +
1657
1784
  'state/<initiative>/ since 0.1.9. Mechanical consumers read only state/, so anything ' +
1658
1785
  'kept here is invisible to the projections, the retrospective and the session summary',
1659
- `ls -la ${sq(legacyDir)} # relocate the contents by hand, one initiative directory at a time, into ${sq(join(dir, 'state'))} — see https://jjanczur.github.io/tyran/journal/`,
1786
+ // Was "relocate the contents by hand, one initiative directory at a
1787
+ // time" — which is advice, not a remedy, on the one class of install
1788
+ // that by definition nobody has touched since 0.1.8. The script says
1789
+ // what it WOULD move until asked twice, never overwrites, and never
1790
+ // deletes anything it did not empty.
1791
+ `node scripts/migrate.mjs --dir ${sq(dir)} # what it would move; add --apply to move it`,
1660
1792
  ),
1661
1793
  );
1662
1794
  }
1663
1795
  checked.push(`initiatives/ (legacy): ${isDirectory(legacyDir) ? 'PRESENT' : 'absent'}`);
1664
1796
 
1665
- const mistakes = mistakesFindings(repoRoot);
1797
+ const mistakes = mistakesFindings(repoRoot, gitRun);
1666
1798
  findings.push(...mistakes.findings);
1667
1799
  checked.push(mistakes.checked);
1668
1800
 
@@ -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
  );