@jjanczur/tyran 0.1.26 → 0.1.28

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.26",
14
+ "version": "0.1.28",
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.26",
3
+ "version": "0.1.28",
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,166 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.28 — 2026-08-15
4
+
5
+ A maintenance release: the documentation site's dependencies, and three
6
+ numbers in the prose that had gone stale because nothing was watching them.
7
+
8
+ ### Five vulnerabilities, now zero
9
+
10
+ `npm audit` in `site/` reported five, three of them high, all transitive:
11
+ nanoid's infinite loop on a zero size, js-yaml, fast-uri, dompurify, and
12
+ mermaid's prototype pollution. `npm update` and `npm audit fix` clear all five
13
+ and carry astro 7.1.4 to 7.2.2, starlight 0.41.4 to 0.41.7 and playwright
14
+ 1.62.0 to 1.62.1. Lockfile only — no range in `package.json` moved, and the
15
+ plugin itself still has zero runtime dependencies, which is the property that
16
+ keeps this whole section confined to `site/`.
17
+
18
+ Verified against the built site rather than asserted: `astro check` reports 0
19
+ errors over 27 files, the build produces 18 pages, 488 of 488 root-absolute
20
+ URLs carry the `/tyran` base prefix, the browser pass finds 0 broken links and
21
+ 0 console errors across every page, and the worst mermaid contrast is 5.68:1
22
+ against a floor of 3.
23
+
24
+ **TypeScript stays on 6.** `@astrojs/check` is at its newest release, 0.9.10,
25
+ and still declares `typescript: ^5.0.0 || ^6.0.0` — and `astro check` is what
26
+ the Pages workflow runs, so accepting TS 7 breaks the deploy rather than a
27
+ test. Dependabot now ignores that major with the reason written beside it.
28
+
29
+ The four Dependabot PRs this closes had been open for ten days. They were
30
+ *security* updates, which arrive ungrouped and without the seven-day cooldown,
31
+ so four one-line lockfile changes became four review cycles nobody ran. Both
32
+ tracks are grouped now: one chore a month instead of a queue.
33
+
34
+ ### Three numbers that were wrong
35
+
36
+ The house rule is that a number in the prose is a claim, verified against the
37
+ thing it describes. These three were claims nothing verified.
38
+
39
+ - The README said **1314 unit tests**; the suite has 1405.
40
+ `docs-claims.test.mjs` pins every such claim on the docs surfaces, but each
41
+ of those is about ONE test file and is counted by running it. The README's
42
+ is about the whole suite, which no unit test can count without running the
43
+ suite from inside itself. CI now compares it against the full run it already
44
+ performs for the skipped-test check, so the guard costs nothing.
45
+ - The README said the board has **four tabs**. It has had five since 0.1.24,
46
+ and `docs/board.md` said five throughout. One surface moved, the other did
47
+ not — the failure the two-surfaces rule exists to prevent, on the one
48
+ surface that rule does not name.
49
+ - `templates/config.yaml` keeps **63** comment lines out of 90, not 60.
50
+
51
+ `assets/board-demo.gif` was recorded at 0.1.22 and moves through four tabs, so
52
+ it predates the Settings tab. Its alt text no longer claims to show the whole
53
+ page; the re-record needs a live board and a screen recorder, so it is written
54
+ down as an open item rather than quietly left wrong.
55
+
56
+ ### The browser check had been shrinking
57
+
58
+ `site/scripts/check-browser.mjs` carried a hand-written list of 14 slugs while
59
+ the site had grown to 17 pages. The three it missed — board, overnight, cost —
60
+ were the three newest, which is to say the likeliest to carry a relative link
61
+ nobody had clicked. It reads the content directory now, so the list cannot
62
+ fall behind again. All 17 pass, 18 internal links, 0 broken. A check whose
63
+ coverage silently shrinks as the thing it checks grows is worse than no check,
64
+ because it still prints OK.
65
+
66
+ Astro 7's `preview` daemonizes and returns, so the `npm run preview -- &` in
67
+ both check-script headers no longer described what happens: the server
68
+ outlives the shell that started it and needs `astro preview stop`.
69
+
70
+ ## 0.1.27 — 2026-08-15
71
+
72
+ The last four items of the munder-difflin plan, and the half of the model
73
+ fallback that was still missing. `NOTES-REQUESTS.md` §7 is now closed.
74
+
75
+ ### The board says whether the run is supposed to be running
76
+
77
+ Three agent chips reading "6 HOURS since last signal — likely dead" covered
78
+ four unrelated situations, and 0.1.25 could only tell you about one of them:
79
+ an operator `STOP`. That one is committed repo state and travels in the
80
+ artefact. The rest is machine-local and gitignored — the pause marker, the
81
+ resume watcher's pid, the usage sidecar — so `--serve` answers it at
82
+ **`/run.json`**, on exactly the argument spend already makes.
83
+
84
+ The page turns it into one banner above the tiles when any of three things is
85
+ true: a usage-limit pause is live, a pause was due to resume and has not, or
86
+ the resume watcher is not running. A damaged or missing file reads as absent —
87
+ this answers a question *about* the run and must never be the reason nobody can
88
+ see the board.
89
+
90
+ ### The queue knows what each question is holding up
91
+
92
+ Nine open questions sorted by age alone put the one gating six tickets wherever
93
+ it happened to fall. `deps` is resolved FORWARD everywhere else — a ticket is
94
+ `ready` when its dependencies are merged — and the reverse direction was never
95
+ computed at all.
96
+
97
+ Each ask now carries `blocks: {count, ids}`, walked transitively and skipping
98
+ merged tickets. The board sorts by it and **so does the answer sheet**, because
99
+ those are two renderings of one queue. Two deliberate limits:
100
+ no-recorded-default still sorts first (the only questions where saying nothing
101
+ has no safe outcome), and an initiative that declares no dependencies reports
102
+ `null` rather than `0` on every ask — an absence rendered as a measurement is
103
+ worse than saying nothing.
104
+
105
+ ### Signal is not evidence
106
+
107
+ The agent strip aged on `progress`, which an agent emits at will. An agent
108
+ looping without achieving anything therefore had the freshest chip on the
109
+ board — and, because the strip is stalest-first, sorted to the bottom.
110
+
111
+ Agents now carry both times: **`last_signal`** is what it said,
112
+ **`last_evidence`** is what it showed (a `report` with its `evidence[]`, a
113
+ `finding` with its proof, a `review` verdict). The strip sorts on evidence, and
114
+ an agent that has shown nothing ages from its **spawn** rather than from the
115
+ last thing it said — otherwise the chatty agent still outranks one that
116
+ produced something twenty minutes ago, which is the exact inversion this split
117
+ exists to correct.
118
+
119
+ No doctor finding for it, deliberately. The threshold separating "quiet because
120
+ the work is hard" from "quiet because nothing is happening" is not one this
121
+ project can pick for every repo, and a warning that fires on healthy agents is
122
+ one people learn to scroll past.
123
+
124
+ ### A ticket that failed twice is re-tried a tier higher
125
+
126
+ The escalation rule lived in the conductor's memory, which iron rule 7 already
127
+ names the least reliable store in the system: after a compaction, the ticket is
128
+ re-spawned at the tier that failed both times.
129
+
130
+ ```bash
131
+ node scripts/tiers.mjs --role implementer \
132
+ --journal .tyran/state/<init>/journal.jsonl --ticket T-3 --field json
133
+ # tiers: ESCALATED work -> deep after 2 failed attempt(s) on T-3 (ceiling deep).
134
+ ```
135
+
136
+ Capped twice over — two steps, and a ceiling of `deep`. A ticket that has
137
+ failed five times does not need the most expensive model in the table; it needs
138
+ a human, and the `changes-requested` lane already shows that. The same read
139
+ picks up any model an `error` event recorded as `model-unavailable` and feeds
140
+ it to the fallback, so **the exclusion is durable in the ledger** rather than
141
+ in a session that will be compacted. Escalation happens first and the fallback
142
+ second: a re-try asks for a stronger model, then discovers whether it is
143
+ available.
144
+
145
+ The weakness, stated rather than left to be found: "did this attempt fail" is
146
+ `APPROVING_RE`, written for lane assignment — "approved with nits" escalates
147
+ nothing and "looks fine" escalates. And a journal that cannot be read routes as
148
+ a first attempt, loudly, because routing must never depend on a readable
149
+ journal.
150
+
151
+ **Detection is still not automatic.** The limit surfaces inside a subagent's
152
+ API call where no hook can see it, so something still has to notice and write
153
+ the `error` event down. That seam is recorded in `NOTES-REQUESTS.md` rather
154
+ than papered over.
155
+
156
+ ### Left alone on purpose
157
+
158
+ `budget:` in the config schema is dead weight — validated, read by nothing —
159
+ and it stays. Removing a key from the `known` list makes every config that
160
+ carries it invalid, and an invalid config makes the policy gate refuse every
161
+ write in that repo. The cost lands on whoever set the key; the benefit is a
162
+ shorter array.
163
+
3
164
  ## 0.1.26 — 2026-08-15
4
165
 
5
166
  ### Answer a question from the board
package/README.md CHANGED
@@ -59,7 +59,7 @@ before it happens, and a commit carrying a secret is refused. Mechanisms rather
59
59
  than instructions — which is the whole argument.
60
60
 
61
61
  <p align="center">
62
- <img src="assets/board-demo.gif" width="100%" alt="The Tyran dashboard, recorded live, moving through its four tabs: Overview with what is waiting on you and the strip of running agents each showing the time since it last signalled; Board, where selecting a ticket opens its initiative, agents and spend; Waiting on you, the open questions above the commands that answer them; and Spend, toggling the same split between tokens and cost">
62
+ <img src="assets/board-demo.gif" width="100%" alt="The Tyran dashboard, recorded live, moving through four of its tabs: Overview with what is waiting on you and the strip of running agents each showing the time since it last signalled; Board, where selecting a ticket opens its initiative, agents and spend; Waiting on you, the open questions above the commands that answer them; and Spend, toggling the same split between tokens and cost">
63
63
  </p>
64
64
 
65
65
  <p align="center">
@@ -204,7 +204,7 @@ open .tyran/state/board.html # xdg-open on Linux, start on Windows
204
204
  — and inside a session you need neither command, because **`/tyran:status`
205
205
  regenerates the board and tells you where it is.**
206
206
 
207
- Four tabs, because the page answers four questions:
207
+ Five tabs, because the page answers five questions:
208
208
 
209
209
  - **Overview** — what is waiting on you, agents running, progress, and what
210
210
  needs a human (blocked lanes **and** blocked agents); then the agent strip,
@@ -220,6 +220,8 @@ Four tabs, because the page answers four questions:
220
220
  - **Spend** — tokens, the amount under your rate card, the conductor's share, a
221
221
  composition bar across input / cache write / cache read / output, and three
222
222
  ranked charts (by model, agent type, ticket) with a tokens/cost toggle.
223
+ - **Settings** — what Tyran is configured to do, every knob with the sentence
224
+ that explains it. Read-only until you pass `--write`, as above.
223
225
 
224
226
  Spend is served rather than embedded, so it is the one thing missing when you
225
227
  open the file directly — [the board](https://jjanczur.github.io/tyran/board/)
@@ -257,7 +259,7 @@ enforces the cap (4352 of 5000 characters). What each one assumes, when it
257
259
  fires and who invokes it, is in
258
260
  [skills and agents](https://jjanczur.github.io/tyran/skills/); the prompts
259
261
  themselves are in [`skills/`](skills/) and [`agents/`](agents/). Behind all of
260
- it: 1314 unit tests, run with `node --test "tests/**/*.test.mjs"`.
262
+ it: 1405 unit tests, run with `node --test "tests/**/*.test.mjs"`.
261
263
 
262
264
  ## Documentation
263
265
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
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": {
@@ -146,8 +146,16 @@ export function openAsks(tyranDir) {
146
146
  */
147
147
  export function sortAsks(asks) {
148
148
  return [...asks].sort(
149
+ // No-default FIRST, and that stays primary: those are the only questions
150
+ // where saying nothing has no safe outcome, which is a stronger claim on
151
+ // the operator than any amount of downstream work.
149
152
  (a, b) =>
150
153
  Number(a.default != null) - Number(b.default != null) ||
154
+ // Then blast radius. Nine questions sorted by age alone put the one
155
+ // gating six tickets wherever it happened to fall; `blocks` is null on a
156
+ // journal that declares no dependencies, and null sorts as zero so those
157
+ // queues keep their old order exactly.
158
+ (b.blocks?.count ?? 0) - (a.blocks?.count ?? 0) ||
151
159
  String(a.since ?? '').localeCompare(String(b.since ?? '')) ||
152
160
  naturalCompare(a.init, b.init) ||
153
161
  naturalCompare(a.kind, b.kind),
@@ -440,6 +440,15 @@ if (data.schema !== 1) {
440
440
  : ageMs >= 10800000 ? Math.round(ageMs / 3600000) + ' HOURS since last signal — likely dead'
441
441
  : Math.round(ageMs / 60000) + ' min since last signal';
442
442
  chip.appendChild(el('div', ageClass(ageMs), ageText));
443
+ // Signal is what the agent SAID; evidence is what it SHOWED. An agent
444
+ // emitting progress every few minutes while achieving nothing is the
445
+ // healthiest-looking chip on the board, and the strip is sorted by the
446
+ // first of those two, so it also sorts to the bottom.
447
+ var evMs = ageMsOf(a.last_evidence);
448
+ chip.appendChild(el('div', evMs === null ? 'age-cold' : ageClass(evMs),
449
+ evMs === null
450
+ ? 'nothing shown yet'
451
+ : (a.evidence_kind || 'evidence') + ' ' + ago(a.last_evidence)));
443
452
  strip.appendChild(chip);
444
453
  });
445
454
  return strip;
@@ -797,6 +806,7 @@ if (data.schema !== 1) {
797
806
  hasDefault ? 'decision \\u00b7 a default is recorded' : 'blocking \\u00b7 no safe default'));
798
807
  card.appendChild(el('div', 'q', a.question || '(no question recorded — gate ' + a.kind + ')'));
799
808
  [['answer with', a.kind], ['recommendation', a.recommendation], ['default', a.default],
809
+ ['blocks', a.blocks && a.blocks.count > 0 ? a.blocks.count + ' ticket(s): ' + a.blocks.ids.join(', ') : null],
800
810
  ['ticket', a.ticket], ['initiative', a.init], ['since', a.since]].forEach(function (pair) {
801
811
  if (pair[1] === null || pair[1] === undefined) return;
802
812
  var row = el('div', 'row');
@@ -1257,6 +1267,36 @@ if (data.schema !== 1) {
1257
1267
  });
1258
1268
  });
1259
1269
 
1270
+ // Machine-local run state, fetched beside spend. A 404 means this page is
1271
+ // not being served by a board server — a copy on a docs site, a file behind
1272
+ // some other host — and that is an answer, not a failure.
1273
+ fetch('run.json', { headers: { accept: 'application/json' } })
1274
+ .then(function (r) { return r.ok ? r.json() : null; })
1275
+ .then(function (run) {
1276
+ if (run === null || run.schema !== 1) return;
1277
+ var lines = [];
1278
+ if (run.paused) {
1279
+ lines.push(run.paused.overdue
1280
+ ? 'A usage-limit pause was due to resume ' + ago(run.paused.resume_at) + ' and has not.'
1281
+ : 'Paused on the ' + (run.paused.window || 'usage') + ' window at ' +
1282
+ (run.paused.used_percentage === null ? 'the threshold' : run.paused.used_percentage + '%') +
1283
+ '. Resumes ' + (run.paused.wait || 'later') + '.');
1284
+ }
1285
+ if (run.watcher && run.watcher.alive === false) {
1286
+ lines.push('The resume watcher is not running, so nothing will restart this by itself.');
1287
+ }
1288
+ if (run.usage && run.usage.stale === true) {
1289
+ lines.push('Usage telemetry is stale — the statusline helper may not be installed.');
1290
+ }
1291
+ if (lines.length === 0) return;
1292
+ var box = el('div', 'paused');
1293
+ box.appendChild(el('b', null, 'This run is not simply working. '));
1294
+ lines.forEach(function (line) { box.appendChild(el('div', 'hint', line)); });
1295
+ box.appendChild(el('div', 'hint', 'npx @jjanczur/tyran overnight status --dir .tyran'));
1296
+ ov.insertBefore(box, ov.firstChild);
1297
+ })
1298
+ .catch(function () { /* no server, or none of this applies */ });
1299
+
1260
1300
  fetch('settings.json', { headers: { accept: 'application/json' } })
1261
1301
  .then(function (r) { return r.ok ? r.json() : Promise.reject(new Error(String(r.status))); })
1262
1302
  .then(function (payload) {
package/scripts/board.mjs CHANGED
@@ -46,7 +46,8 @@ import { renderBoardError, renderBoardHtml } from './board-html.mjs';
46
46
  import { COST_SCHEMA, costJson, costReport } from './cost.mjs';
47
47
  import { SettingsError, applyPolicyClass, applySetting, readSettings } from './settings.mjs';
48
48
  import { checkStopAt } from './stop-check.mjs';
49
- import { answerOne, answerProblem, classify, openAsks, partitionAsks, reRender } from './answer.mjs';
49
+ import { runState } from './overnight.mjs';
50
+ import { answerOne, answerProblem, classify, openAsks, partitionAsks, reRender, sortAsks } from './answer.mjs';
50
51
 
51
52
  export const BOARD_HTML_FILE = 'board.html';
52
53
 
@@ -232,14 +233,25 @@ export function crossBoard({ initiatives, errors, warned = [], stop = null }) {
232
233
  for (const card of board.lanes.get(lane)) lanes[lane].push({ ...card, init: name });
233
234
  }
234
235
  }
235
- asks.sort((a, b) => String(a.since ?? '').localeCompare(String(b.since ?? '')));
236
+ // The SAME rule the answer sheet uses, imported rather than restated: the
237
+ // sheet and the page are two renderings of one queue, and two orderings
238
+ // would make an operator answer them in different sequences depending on
239
+ // which surface they happened to open (ADR-21).
240
+ const ordered = sortAsks(asks);
241
+ asks.length = 0;
242
+ asks.push(...ordered);
236
243
  // Stalest FIRST. Rendering agents in the order the journals happened to spawn
237
244
  // them puts the one that has said nothing for six hours anywhere at all,
238
245
  // including last — and the whole reason the strip carries a last-signal time
239
246
  // is that the silent agent is the one worth looking at. `last_signal` is an
240
247
  // ISO string from the journal, so ascending string order IS ascending time;
241
248
  // an agent with no signal at all sorts to the front, where it belongs.
242
- agents.sort((a, b) => String(a.last_signal ?? '').localeCompare(String(b.last_signal ?? '')));
249
+ // Sorted on EVIDENCE where there is any, falling back to the signal. An
250
+ // agent that has shown nothing for three hours belongs at the top even if it
251
+ // has been saying "working" every four minutes the whole time — which is
252
+ // exactly the case the old signal-only sort put last.
253
+ agents.sort((a, b) =>
254
+ String(a.last_evidence ?? a.since ?? '').localeCompare(String(b.last_evidence ?? b.since ?? '')));
243
255
  // Newest first: an error from four days ago is history, the one from ten
244
256
  // minutes ago is the reason you opened this page.
245
257
  logged.sort((a, b) => String(b.ts ?? '').localeCompare(String(a.ts ?? '')));
@@ -325,6 +337,9 @@ export function renderCrossMd(payload) {
325
337
  parts.push(`- **${inline(a.question ?? `(no question recorded — gate ${a.kind})`)}**\n`);
326
338
  if (a.recommendation != null) parts.push(` - recommendation: ${inline(a.recommendation)}\n`);
327
339
  if (a.default != null) parts.push(` - default: ${inline(a.default)}\n`);
340
+ if (a.blocks != null && a.blocks.count > 0) {
341
+ parts.push(` - blocks ${a.blocks.count} ticket(s): ${a.blocks.ids.map((id) => inline(id)).join(', ')}\n`);
342
+ }
328
343
  parts.push(` - ${inline(a.init)}${a.ticket != null ? ` · \`${inline(a.ticket)}\`` : ''} · since ${inline(a.since)}\n`);
329
344
  }
330
345
 
@@ -633,6 +648,20 @@ function main() {
633
648
  // `board.json` would break the byte-exact `--check` contract. Over
634
649
  // `file://` the fetch fails and the tab says how to open the board
635
650
  // with a server, which is the honest answer.
651
+ // The MACHINE-LOCAL half of "is this run supposed to be running".
652
+ // `.tyran/STOP` is committed and travels in the artefact; the pause
653
+ // marker, the resume watcher and the usage sidecar are gitignored and
654
+ // different on every machine, so they are served — the same split, and
655
+ // the same argument, spend already makes.
656
+ if (req.url === '/run.json') {
657
+ try {
658
+ sendJson(res, 200, { schema: 1, ...runState(resolve(dir, '..')) });
659
+ } catch (err) {
660
+ // A run-state failure must never take the board down with it.
661
+ sendJson(res, 503, { schema: 1, error: String(err?.message ?? err) });
662
+ }
663
+ return;
664
+ }
636
665
  if (req.url === '/settings.json') {
637
666
  sendJson(res, 200, { ...readSettings(dir), writable: flags.write });
638
667
  return;
@@ -186,6 +186,60 @@ export function scheduleDecision(marker, { forceResume = false } = {}) {
186
186
 
187
187
  // --------------------------------------------------------------- plumbing
188
188
 
189
+ /**
190
+ * The machine-local run state, for a reader that only wants to LOOK at it.
191
+ *
192
+ * Composed here rather than in the board, because these three files and the
193
+ * rules for reading them are this module's business: the marker says whether a
194
+ * pause is live, the resume state says whether a watcher is still breathing,
195
+ * and the sidecar says how full the window was when it was last written. All
196
+ * three are gitignored and different on every machine, which is why the board
197
+ * SERVES this rather than embedding it — the same argument spend makes.
198
+ *
199
+ * Everything is read defensively: a missing, oversized or unparseable file is
200
+ * simply absent. This answers a question about the run; it must never be the
201
+ * reason nobody can see the board.
202
+ */
203
+ export function runState(repo, nowMs = Date.now()) {
204
+ const marker = readSmallJson(join(repo, MARKER_RELPATH));
205
+ const resume = readSmallJson(join(repo, RESUME_STATE_RELPATH));
206
+ const sidecar = readSmallJson(join(repo, SIDECAR_RELPATH));
207
+ const resumeAtMs = marker?.resume_at ? Date.parse(marker.resume_at) : NaN;
208
+ return {
209
+ paused: marker === null ? null : {
210
+ since: typeof marker.paused_at === 'string' ? marker.paused_at : null,
211
+ window: typeof marker.window === 'string' ? marker.window : null,
212
+ used_percentage: typeof marker.used_percentage === 'number' ? marker.used_percentage : null,
213
+ resume_at: typeof marker.resume_at === 'string' ? marker.resume_at : null,
214
+ // A marker whose resume time has passed while a watcher was supposed to
215
+ // act on it is the shape of a dead watcher, and it reads as an ordinary
216
+ // pause unless something says otherwise.
217
+ overdue: Number.isFinite(resumeAtMs) && resumeAtMs < nowMs,
218
+ wait: Number.isFinite(resumeAtMs) ? humanWait(resumeAtMs - nowMs) : null,
219
+ },
220
+ watcher: resume === null ? null : {
221
+ state: typeof resume.state === 'string' ? resume.state : null,
222
+ alive: watcherAlive(resume, nowMs),
223
+ resume_at: typeof resume.resume_at === 'string' ? resume.resume_at : null,
224
+ },
225
+ usage: sidecar === null ? null : {
226
+ written_at: typeof sidecar.written_at === 'string' ? sidecar.written_at : null,
227
+ stale: !(typeof sidecar.written_at === 'string' && nowMs - Date.parse(sidecar.written_at) < SIDECAR_FRESH_MS),
228
+ five_hour: pickWindow(sidecar.five_hour),
229
+ seven_day: pickWindow(sidecar.seven_day),
230
+ },
231
+ };
232
+ }
233
+
234
+ /** Numbers and an ISO string only — never a free payload string from a hook. */
235
+ function pickWindow(w) {
236
+ if (w === null || typeof w !== 'object') return null;
237
+ return {
238
+ used_percentage: typeof w.used_percentage === 'number' ? w.used_percentage : null,
239
+ resets_at: typeof w.resets_at === 'string' ? w.resets_at : null,
240
+ };
241
+ }
242
+
189
243
  function readSmallJson(path) {
190
244
  try {
191
245
  if (!existsSync(path) || statSync(path).size > 64 * 1024) return null;
@@ -205,6 +205,21 @@ function clearBlockageBy(state, agent) {
205
205
  }
206
206
 
207
207
  /** A `review`/`merge` settles the ticket for EVERY agent blocked on it. */
208
+ /**
209
+ * Record that an agent SHOWED something, as opposed to said something.
210
+ *
211
+ * Newest wins, and only ever moves forward: events arrive in journal order, but
212
+ * a hand-edited file need not be monotonic, and an older evidence event must
213
+ * not make an agent look staler than the board already knows it is.
214
+ */
215
+ function noteEvidence(state, agent, kind, ts) {
216
+ if (agent == null) return;
217
+ const key = String(agent);
218
+ const prev = state.evidenceByAgent.get(key);
219
+ if (prev !== undefined && String(prev.ts ?? '') > String(ts ?? '')) return;
220
+ state.evidenceByAgent.set(key, { kind, ts });
221
+ }
222
+
208
223
  function clearBlockagesOn(state, ticketId) {
209
224
  for (const [key, blockage] of state.blockages) {
210
225
  // A ticketless blockage is keyed to its agent and belongs to no ticket —
@@ -264,6 +279,13 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
264
279
  ambiguousAgents: [],
265
280
  // agent name -> latest self-reported signal (last one wins)
266
281
  progressByAgent: new Map(),
282
+ // What an agent has SHOWN, as opposed to what it has said. A `progress`
283
+ // event is a heartbeat an agent emits at will; the events here each carry
284
+ // a work product — a report with its evidence[], a finding with its proof,
285
+ // a review or a merge on the agent's ticket. An agent looping without
286
+ // achieving anything can keep `progressByAgent` perfectly fresh, and used
287
+ // to sort to the BOTTOM of a strip ordered by staleness.
288
+ evidenceByAgent: new Map(),
267
289
  // agent name -> that agent's open blockage, the ticket inside the value.
268
290
  //
269
291
  // Keyed by AGENT and not by ticket, because one agent has at most one live
@@ -412,6 +434,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
412
434
  break;
413
435
  }
414
436
  case 'report': {
437
+ noteEvidence(state, data.agent ?? actor, 'report', ts);
415
438
  // A report that pairSpawns matched to a spawn has already been applied
416
439
  // to that spawn's row above — this branch only has to render what
417
440
  // pairing left over, so the two never compute the same thing twice.
@@ -458,6 +481,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
458
481
  break;
459
482
  }
460
483
  case 'finding':
484
+ noteEvidence(state, actor, 'finding', ts);
461
485
  state.findings.push({
462
486
  id: data.id ?? null,
463
487
  area: data.area ?? null,
@@ -520,6 +544,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
520
544
  // and the same correlator closes what that spawn left behind. Without
521
545
  // it a reviewer's ticketless blockage outlived its own review with no
522
546
  // later event that could ever clear it.
547
+ noteEvidence(state, data.by ?? actor, 'review', ts);
523
548
  if (data.by != null) closeAgent(state, data.by);
524
549
  break;
525
550
  }
@@ -631,7 +656,16 @@ export const LANES = Object.freeze([
631
656
  'done',
632
657
  ]);
633
658
 
634
- const APPROVING_RE = /^approv|^lgtm$|^pass/i;
659
+ /**
660
+ * A review verdict that counts as an approval.
661
+ *
662
+ * Exported because `tiers.mjs` counts FAILED attempts on a ticket to decide
663
+ * whether to escalate, and "did this attempt fail" must not have two answers
664
+ * (ADR-21). Note the asymmetry this creates, stated because someone will meet
665
+ * it: the pattern was written for lane assignment, so "approved with nits"
666
+ * reads as an approval and "looks fine" does not.
667
+ */
668
+ export const APPROVING_RE = /^approv|^lgtm$|^pass/i;
635
669
 
636
670
  /**
637
671
  * The kanban view of a folded state. PURE and clock-free: every timestamp is
@@ -658,10 +692,45 @@ export function boardOf(state) {
658
692
  (g) => PAUSED_RE.test(g.kind) && !GATE_PASS.has(String(g.result ?? '').toLowerCase()),
659
693
  ) ?? null;
660
694
 
695
+ // What each open question is HOLDING UP.
696
+ //
697
+ // `deps` is resolved forward everywhere else — a ticket is ready when its
698
+ // dependencies are merged — and the reverse direction was never computed, so
699
+ // a queue of nine questions sorted by age alone put the one gating six
700
+ // tickets wherever it happened to fall. The walk is transitive and skips
701
+ // merged tickets, which are not held up by anything.
702
+ //
703
+ // Only when the initiative declares deps at all: on a journal that records
704
+ // none, every ask would report "blocks 0", and an absence rendered as a
705
+ // measurement is worse than saying nothing.
706
+ const declaresDeps = state.ticketList.some((x) => Array.isArray(x.deps) && x.deps.length > 0);
707
+ const dependents = new Map();
708
+ if (declaresDeps) {
709
+ for (const x of state.ticketList) {
710
+ for (const d of Array.isArray(x.deps) ? x.deps.map(String) : []) {
711
+ dependents.set(d, [...(dependents.get(d) ?? []), x.id]);
712
+ }
713
+ }
714
+ }
715
+ const blockedBy = (ticket) => {
716
+ if (!declaresDeps || ticket == null) return null;
717
+ const seen = new Set();
718
+ const queue = [String(ticket)];
719
+ while (queue.length > 0) {
720
+ for (const next of dependents.get(queue.shift()) ?? []) {
721
+ if (seen.has(next) || mergedIds.has(next)) continue;
722
+ seen.add(next);
723
+ queue.push(next);
724
+ }
725
+ }
726
+ return { count: seen.size, ids: [...seen].sort(naturalCompare) };
727
+ };
728
+
661
729
  const asks = [];
662
730
  for (const g of state.openGates) {
663
731
  if (WAITING_RE.test(String(g.result ?? ''))) {
664
732
  asks.push({
733
+ blocks: blockedBy(g.ticket),
665
734
  kind: g.kind,
666
735
  ticket: g.ticket ?? null,
667
736
  question: g.question ?? null,
@@ -731,6 +800,7 @@ export function boardOf(state) {
731
800
  .filter((a) => a.status === 'running')
732
801
  .map((a) => {
733
802
  const signal = state.progressByAgent.get(a.agent) ?? null;
803
+ const evidence = state.evidenceByAgent.get(a.agent) ?? null;
734
804
  return {
735
805
  agent: a.agent,
736
806
  role: a.role,
@@ -739,6 +809,17 @@ export function boardOf(state) {
739
809
  detail: signal?.detail ?? null,
740
810
  next: signal?.next ?? null,
741
811
  last_signal: signal?.ts ?? a.spawnTs,
812
+ // What it has SHOWN. Null until it shows something, which is the
813
+ // ordinary state of an agent that has just started — the strip says
814
+ // "nothing yet" rather than implying silence.
815
+ last_evidence: evidence?.ts ?? null,
816
+ evidence_kind: evidence?.kind ?? null,
817
+ // When it started. An agent that has shown nothing is stale from its
818
+ // SPAWN, not from the last thing it said — without this an agent
819
+ // chattering every four minutes and producing nothing outranks one
820
+ // that produced something twenty minutes ago, which is the exact
821
+ // inversion the evidence split exists to correct.
822
+ since: a.spawnTs,
742
823
  };
743
824
  });
744
825
 
package/scripts/tiers.mjs CHANGED
@@ -36,6 +36,8 @@ import { fileURLToPath } from 'node:url';
36
36
  import { parse } from './yaml-lite.mjs';
37
37
  import { validateConfig, PROFILES, TIER_KEYS } from './schema.mjs';
38
38
  import { escapeInvisible } from './invisible.mjs';
39
+ import { APPROVING_RE } from './project.mjs';
40
+ import { readJournal } from './journal.mjs';
39
41
 
40
42
  /** Capability tiers, cheapest first. Index order is the escalation ladder. */
41
43
  export const TIER_ORDER = TIER_KEYS;
@@ -117,6 +119,52 @@ export const ROLE_FLOOR = Object.freeze({
117
119
 
118
120
  export const ROLES = Object.freeze(Object.keys(ROLE_TIERS));
119
121
 
122
+ /**
123
+ * The tier a fallback or an escalation may never pass.
124
+ *
125
+ * `top` is the most expensive thing Tyran can spend, and an automatic climb to
126
+ * it is a decision about money made while nobody is watching. Roles whose
127
+ * FLOOR is already `top` still resolve there — this bounds what escalation
128
+ * ADDS, not what the table asks for.
129
+ */
130
+ export const ESCALATION_CEILING = 'deep';
131
+
132
+ /** How many steps repeated failure may add, however many attempts there were. */
133
+ export const MAX_ESCALATION_STEPS = 2;
134
+
135
+ /**
136
+ * What the journal says about a ticket that is being re-tried.
137
+ *
138
+ * Both facts live in the ledger rather than in the conductor's memory, which
139
+ * iron rule 7 already names the least reliable store in the system: a session
140
+ * that compacts, or a second conductor picking the work up, otherwise re-spawns
141
+ * at the tier that has already failed twice and on the model that has already
142
+ * run out.
143
+ *
144
+ * - `attempts` counts reviews that did NOT approve. The regex is the board's
145
+ * own, imported, because "did this attempt fail" must not have two answers.
146
+ * - `unavailable` collects models an `error` event named as out of capacity.
147
+ * The convention is `{class: 'model-unavailable', model: '<alias>'}` and it
148
+ * is a convention on purpose: the failure surfaces inside a subagent's API
149
+ * call, where no hook can see it, so SOMETHING has to write it down before
150
+ * routing can act on it.
151
+ */
152
+ export function ticketHistory(events, ticket) {
153
+ const id = String(ticket);
154
+ let attempts = 0;
155
+ const unavailable = [];
156
+ for (const e of events) {
157
+ if (e?.ev === 'review' && String(e.data?.ticket) === id && !APPROVING_RE.test(String(e.data?.verdict ?? ''))) {
158
+ attempts += 1;
159
+ }
160
+ if (e?.ev === 'error' && e.data?.class === 'model-unavailable' && typeof e.data?.model === 'string') {
161
+ // NOT scoped to the ticket: a model that ran out is out for everything.
162
+ if (!unavailable.includes(e.data.model)) unavailable.push(e.data.model);
163
+ }
164
+ }
165
+ return { attempts, unavailable };
166
+ }
167
+
120
168
  function validateInputs(role, profile, risk) {
121
169
  if (!Object.hasOwn(ROLE_TIERS, role)) {
122
170
  throw new Error(`unknown role "${escapeInvisible(role)}" (known: ${ROLES.join(', ')})`);
@@ -220,23 +268,50 @@ export function resolveModel(config, role, profile, risk = 'normal', override =
220
268
  (ROLE_EFFORT_FLOOR[role] !== undefined && override.effort !== undefined && override.effort !== effort);
221
269
 
222
270
  const unavailable = normalizeUnavailable(override.unavailable);
223
- const resolved = { tier, model: aliasFor(tier), effort, floored, fell_from: null };
271
+ // Escalation first, fallback second, and the order matters: a re-try should
272
+ // ask for a stronger model, and only then discover whether that model is
273
+ // available. Doing it the other way round would fall back from a tier the
274
+ // run was never going to use.
275
+ const attempts = Number.isInteger(override.attempts) && override.attempts > 0 ? override.attempts : 0;
276
+ const climbed = attempts === 0 ? tier : escalateTier(tier, attempts);
277
+ const resolved = {
278
+ tier: climbed,
279
+ model: aliasFor(climbed),
280
+ effort,
281
+ floored,
282
+ fell_from: null,
283
+ escalated_from: climbed === tier ? null : tier,
284
+ attempts,
285
+ };
224
286
  if (unavailable.length === 0 || !unavailable.includes(resolved.model)) return resolved;
225
287
 
226
- const substitute = fallbackTier(config, role, tier, unavailable);
288
+ const substitute = fallbackTier(config, role, resolved.tier, unavailable);
227
289
  return {
290
+ ...resolved,
228
291
  tier: substitute,
229
292
  model: aliasFor(substitute),
230
293
  // Effort follows the ORIGINAL tier, not the substitute. The judgement
231
294
  // "this task needs deep reasoning" did not change because a model ran out
232
295
  // of capacity, and dropping both dials at once turns a substitution into a
233
296
  // second, unasked-for downgrade.
234
- effort,
235
- floored,
236
- fell_from: tier,
297
+ fell_from: resolved.tier,
237
298
  };
238
299
  }
239
300
 
301
+ /**
302
+ * One step up per failed attempt, capped twice over: by MAX_ESCALATION_STEPS,
303
+ * and by the ceiling. A ticket that has failed four times does not need the
304
+ * most expensive model in the table — it needs a human, and the board's
305
+ * changes-requested lane is where that is already visible.
306
+ */
307
+ function escalateTier(from, attempts) {
308
+ const ceiling = Math.min(TIER_ORDER.indexOf(ESCALATION_CEILING), TIER_ORDER.length - 1);
309
+ const start = TIER_ORDER.indexOf(from);
310
+ // Never lower a role that already resolves above the ceiling.
311
+ if (start >= ceiling) return from;
312
+ return TIER_ORDER[Math.min(start + Math.min(attempts, MAX_ESCALATION_STEPS), ceiling)];
313
+ }
314
+
240
315
  function normalizeUnavailable(value) {
241
316
  if (value === undefined || value === null) return [];
242
317
  const list = Array.isArray(value) ? value : [value];
@@ -338,7 +413,28 @@ function main() {
338
413
  const field = flag('field', 'model');
339
414
  // Repeatable: an overnight run can exhaust more than one tier.
340
415
  const unavailable = args.reduce((acc, arg, i) => (arg === '--unavailable' && args[i + 1] ? [...acc, args[i + 1]] : acc), []);
341
- const override = { tier: flag('tier', undefined), effort: flag('effort', undefined), unavailable };
416
+ // The ledger, not the conductor's memory. `--journal <path> --ticket T-n`
417
+ // counts the failed attempts on that ticket and picks up any model an error
418
+ // event has recorded as out of capacity, so a re-spawn after a compaction
419
+ // routes the same way a re-spawn before it would have.
420
+ const journalPath = flag('journal', null);
421
+ const ticket = flag('ticket', null);
422
+ let history = { attempts: 0, unavailable: [] };
423
+ if (journalPath !== null && ticket !== null) {
424
+ try {
425
+ history = ticketHistory(readJournal(resolve(journalPath)).events, ticket);
426
+ } catch (error) {
427
+ // Routing must not depend on a readable journal: a missing or damaged
428
+ // one means no history, which is the same answer as a first attempt.
429
+ console.error(`tiers: could not read ${escapeInvisible(journalPath)} (${error.message}) — routing without history`);
430
+ }
431
+ }
432
+ const override = {
433
+ tier: flag('tier', undefined),
434
+ effort: flag('effort', undefined),
435
+ unavailable: [...unavailable, ...history.unavailable],
436
+ attempts: history.attempts,
437
+ };
342
438
 
343
439
  try {
344
440
  if (role === null) {
@@ -365,6 +461,17 @@ function main() {
365
461
  }
366
462
  // A substitution that said nothing would be the routing table quietly
367
463
  // meaning something else than it says.
464
+ if (resolved.escalated_from) {
465
+ // The tier the CLIMB reached, which is what a fallback then fell FROM.
466
+ // Reporting `resolved.tier` here narrated "work -> work" whenever both
467
+ // happened, which is the one case where a reader most needs the two
468
+ // steps told apart.
469
+ const climbedTo = resolved.fell_from ?? resolved.tier;
470
+ console.error(
471
+ `tiers: ESCALATED ${resolved.escalated_from} -> ${climbedTo} after ${resolved.attempts} failed attempt(s) ` +
472
+ `on ${escapeInvisible(String(ticket))} (ceiling ${ESCALATION_CEILING}).`,
473
+ );
474
+ }
368
475
  if (resolved.fell_from !== null) {
369
476
  console.error(
370
477
  `tiers: FELL BACK ${resolved.fell_from} -> ${resolved.tier} because the ${resolved.fell_from} model is ` +