@jjanczur/tyran 0.1.30 → 0.1.32

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.
@@ -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
  );
@@ -390,7 +390,126 @@ export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
390
390
  });
391
391
  }
392
392
 
393
- return { config, languages, packageManager: manager, claudeMd, questions };
393
+ const scan = { config, languages, packageManager: manager, claudeMd, questions };
394
+ return { ...scan, plain: plainQuestion(scan) };
395
+ }
396
+
397
+ /**
398
+ * The `questions` array above is the machine contract, and it is written for
399
+ * someone who knows what an autonomy class is. Most operators do not. Sales
400
+ * and marketing people are running this now, on repositories whose secrets are
401
+ * nobody's crown jewels, and four questions phrased as `field: source` is where
402
+ * they stop.
403
+ *
404
+ * So this is the SAME scan, said once, in ordinary words: one question, and a
405
+ * list of things Tyran decided for itself with the reason attached.
406
+ *
407
+ * Exactly one thing is worth asking a non-expert, and it is the only one the
408
+ * repository genuinely cannot answer: **how far may this go without me?** The
409
+ * other three flagged fields are not decisions a non-expert can make — the
410
+ * package manager is a fact, the validation commands are a fact or a gap, and
411
+ * the CLAUDE.md line is a paste. Those become statements. A question someone
412
+ * cannot answer is not a safeguard; it is a place to give up.
413
+ *
414
+ * P3 is not offered. It is never inferred (see `detectAutonomy`), and putting
415
+ * "let me deploy to production" in a menu is a way of inferring it — a menu
416
+ * makes every item look like a normal choice. It stays something a person says
417
+ * in their own words, and the closing note says so.
418
+ */
419
+ export function plainQuestion(scan) {
420
+ const autonomy = scan.config.autonomy;
421
+ const validation = scan.config.validation;
422
+
423
+ // P2 is returned by `detectAutonomy` on exactly one path — a staging-class
424
+ // branch AND CI — so the value alone tells us the second option is real
425
+ // here. Offering "put it on the test site" to a repo with no test site
426
+ // would be inventing infrastructure.
427
+ const hasStaging = autonomy.value === 'P2';
428
+
429
+ const options = [
430
+ {
431
+ value: 'P1',
432
+ label: 'Show me everything before it counts',
433
+ detail:
434
+ 'I do the work on a separate copy and then open a request for you to look at. ' +
435
+ 'Nothing reaches the main version of this project unless you say yes.',
436
+ },
437
+ ];
438
+ if (hasStaging) {
439
+ options.push({
440
+ value: 'P2',
441
+ label: 'That, and you can put things on the test site',
442
+ detail:
443
+ 'Everything above, plus I can publish to the testing area on my own. ' +
444
+ 'Anything a customer could see still waits for you.',
445
+ });
446
+ }
447
+
448
+ const derived = [];
449
+ if (Array.isArray(validation.value) && validation.value.length > 0) {
450
+ derived.push(
451
+ `I will check my own work by running ${validation.value.map((c) => `\`${c}\``).join(' and ')}, ` +
452
+ 'which this project already defines.',
453
+ );
454
+ } else {
455
+ // Not a question. Nobody can name a test command that does not exist, and
456
+ // asking makes the absence look like the operator's failing rather than
457
+ // the repository's state.
458
+ derived.push(
459
+ 'I could not find a command that runs this project\'s checks — I looked in package.json and the ' +
460
+ 'Makefile. Until you tell me one, I cannot prove my own work here, and I will say so every time ' +
461
+ 'rather than implying it passed.',
462
+ );
463
+ }
464
+ if (scan.packageManager?.value) {
465
+ derived.push(`This project uses \`${scan.packageManager.value}\`, which I read from the files themselves.`);
466
+ }
467
+ if (scan.languages.length > 0) {
468
+ derived.push(`It is mostly ${scan.languages.slice(0, 3).join(', ')}.`);
469
+ }
470
+ if (scan.claudeMd.present && !scan.claudeMd.hasMistakesPointer) {
471
+ derived.push(
472
+ 'One line in your CLAUDE.md would make every session here record its own mistakes. ' +
473
+ 'I am not adding it myself — it is your file — but I will show you the line.',
474
+ );
475
+ }
476
+
477
+ return {
478
+ question: 'How far should I go on my own before checking with you?',
479
+ // The evidence is the scanner's own sentence, softened. Keeping the raw
480
+ // `source` here too means the plain version is never the only record: a
481
+ // reader who wants the git numbers can still have them.
482
+ because: plainEvidence(autonomy),
483
+ evidence: autonomy.source,
484
+ options,
485
+ recommended: autonomy.value,
486
+ derived,
487
+ note:
488
+ 'Anything beyond this — releasing to the live site, for instance — is something you would have to ' +
489
+ 'tell me in your own words, and I will never assume it. You can change any of this later on the ' +
490
+ "dashboard's Settings tab; you do not have to edit a file.",
491
+ };
492
+ }
493
+
494
+ /** The autonomy `source` line, restated for someone who does not read git. */
495
+ function plainEvidence(autonomy) {
496
+ const source = autonomy.source;
497
+ if (source.startsWith('not a git repository')) {
498
+ return 'This folder is not tracked by git, so there is no history to learn from — I am starting careful.';
499
+ }
500
+ if (source.startsWith('no commit history')) {
501
+ return 'This project has no history yet, so there is nothing to learn from — I am starting careful.';
502
+ }
503
+ if (autonomy.value === 'P2') {
504
+ return 'This project has a testing area separate from the live one, and checks that run automatically.';
505
+ }
506
+ const merges = /: (\d+) of the last (\d+)|: (\d+)\/(\d+)/.exec(source);
507
+ if (merges) {
508
+ const done = merges[1] ?? merges[3];
509
+ const total = merges[2] ?? merges[4];
510
+ return `Of the last ${total} changes to this project, ${done} were reviewed by a person before they landed.`;
511
+ }
512
+ return 'I could not tell much from the history here, so I am starting careful.';
394
513
  }
395
514
 
396
515
  /**
@@ -213,8 +213,12 @@ export function validateConfig(doc) {
213
213
  }
214
214
  }
215
215
  for (const key of PRICING_RATE_KEYS) {
216
+ // `cache_write_1h` is the one OPTIONAL rate: cards written
217
+ // before the 1-hour price existed carry four keys, and failing
218
+ // them on upgrade would unprice a working ledger. Absent, it
219
+ // falls back to the 5-minute rate in `pricingOf`.
216
220
  if (!(key in rates)) {
217
- errors.push(`pricing.models.${model}.${key}: required`);
221
+ if (PRICING_REQUIRED_RATE_KEYS.includes(key)) errors.push(`pricing.models.${model}.${key}: required`);
218
222
  } else if (typeof rates[key] !== 'number' || !Number.isFinite(rates[key]) || rates[key] < 0) {
219
223
  errors.push(`pricing.models.${model}.${key}: must be a non-negative number (price per million tokens)`);
220
224
  }
@@ -296,7 +300,24 @@ export function limitsOf(doc) {
296
300
  * real session's cost. A partial rate card is a wrong number, not a partial
297
301
  * one.
298
302
  */
299
- export const PRICING_RATE_KEYS = Object.freeze(['input', 'cache_write', 'cache_read', 'output']);
303
+ /**
304
+ * The rate keys an amount is computed from. `cache_write` is the 5-MINUTE
305
+ * write and `cache_write_1h` the 1-hour one; they are DISJOINT counters, never
306
+ * a total and a subset, because `costOf` multiplies every key by its rate and
307
+ * sums — so an overlapping pair would silently bill the same tokens twice.
308
+ */
309
+ export const PRICING_RATE_KEYS = Object.freeze(['input', 'cache_write', 'cache_write_1h', 'cache_read', 'output']);
310
+
311
+ /**
312
+ * Rate keys a hand-written config MUST supply. `cache_write_1h` is absent from
313
+ * this list on purpose: configs predating the 1-hour rate carry four keys, and
314
+ * failing them would turn a Tyran upgrade into a silently unpriced ledger. A
315
+ * config without it prices 1-hour writes at the 5-minute rate, which is the
316
+ * best reading of "they only told us one cache-write number" — and it is
317
+ * wrong in the direction of UNDER-reporting, so it is stated in the docs
318
+ * rather than left to be inferred from a smaller bill.
319
+ */
320
+ export const PRICING_REQUIRED_RATE_KEYS = Object.freeze(['input', 'cache_write', 'cache_read', 'output']);
300
321
 
301
322
  /**
302
323
  * The pricing block, normalized — the ONE place the shape lives. Returns
@@ -317,12 +338,15 @@ export function pricingOf(doc) {
317
338
  if (isPlainObject(pricing.models)) {
318
339
  for (const [model, rates] of Object.entries(pricing.models)) {
319
340
  if (!isPlainObject(rates)) continue;
320
- const usable = PRICING_RATE_KEYS.every(
321
- (key) => typeof rates[key] === 'number' && Number.isFinite(rates[key]) && rates[key] >= 0
322
- );
341
+ const rate = (key) =>
342
+ typeof rates[key] === 'number' && Number.isFinite(rates[key]) && rates[key] >= 0 ? rates[key] : null;
343
+ const usable = PRICING_REQUIRED_RATE_KEYS.every((key) => rate(key) !== null);
323
344
  if (!usable) continue;
324
345
  const row = Object.create(null);
325
- for (const key of PRICING_RATE_KEYS) row[key] = rates[key];
346
+ for (const key of PRICING_REQUIRED_RATE_KEYS) row[key] = rates[key];
347
+ // The one optional rate. Falling back to the 5-minute write keeps a
348
+ // four-key config priced instead of dropping it into `unpriced`.
349
+ row.cache_write_1h = rate('cache_write_1h') ?? row.cache_write;
326
350
  models[model] = row;
327
351
  }
328
352
  }
@@ -31,8 +31,11 @@
31
31
  */
32
32
  import { existsSync, mkdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
33
33
  import { join, resolve } from 'node:path';
34
+ import { SIDECAR_RELPATH } from './usage-source.mjs';
34
35
 
35
- export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
36
+ // Re-exported, not re-declared: this file is the WRITER and the gate is the
37
+ // reader, and the two disagreeing is a pause that silently never fires.
38
+ export { SIDECAR_RELPATH } from './usage-source.mjs';
36
39
  const MAX_INPUT_BYTES = 1024 * 1024;
37
40
  const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
38
41
 
package/scripts/tiers.mjs CHANGED
@@ -73,6 +73,11 @@ export const EFFORT_BY_TIER = Object.freeze({
73
73
  export const ROLE_EFFORT_FLOOR = Object.freeze({
74
74
  'security-review': 'max',
75
75
  arbitration: 'high',
76
+ // Authoring a prompt is the one output nothing downstream checks: a skill
77
+ // that reads plausibly passes review, and a weak one misroutes every run
78
+ // that obeys it, quietly, for as long as it ships. Thinking harder is the
79
+ // cheapest correction available and it is paid once per skill, not per run.
80
+ authoring: 'max',
76
81
  });
77
82
 
78
83
  /**
@@ -92,6 +97,21 @@ export const ROLE_TIERS = Object.freeze({
92
97
  arbitration: { eco: 'top', balanced: 'top', full: 'top' },
93
98
  acceptance: { eco: 'deep', balanced: 'top', full: 'top' },
94
99
  retro: { eco: 'work', balanced: 'work', full: 'deep' },
100
+ // Writing a PROMPT — a skill, an agent, the conductor's own instructions.
101
+ //
102
+ // Separated from `retro` because retro does two unlike things with one
103
+ // agent: reading a ledger and folding counters, which the middle model does
104
+ // fine, and authoring the text that every future session will obey. Routing
105
+ // the whole of retro at `top` would spend the tier on bookkeeping; routing
106
+ // the authoring at `work` is the failure this row exists to prevent.
107
+ //
108
+ // `top` at EVERY profile, with a floor under it, on the same argument
109
+ // `security-review` already makes and a stronger version of it: a bad
110
+ // security verdict costs one merge, while a bad prompt misroutes every run
111
+ // that reads it, for as long as it ships. It is also the one output nothing
112
+ // downstream checks — a skill that reads plausibly passes review, and the
113
+ // cost surfaces later as work done slightly wrong, everywhere, quietly.
114
+ authoring: { eco: 'top', balanced: 'top', full: 'top' },
95
115
  bookkeeping: { eco: 'cheap', balanced: 'cheap', full: 'cheap' },
96
116
  // ADVISORY. The conductor is the operator's own session, and no plugin can
97
117
  // change a running session's model — so this row records the choice in the
@@ -112,6 +132,10 @@ export const ROLE_TIERS = Object.freeze({
112
132
  export const ROLE_FLOOR = Object.freeze({
113
133
  'security-review': 'top',
114
134
  arbitration: 'top',
135
+ // So `--profile eco --risk low` cannot quietly write the next skill on the
136
+ // cheap tier. Every other floor here protects a judgement made once; this
137
+ // one protects a judgement every later session inherits.
138
+ authoring: 'top',
115
139
  // One weak coordinator spends a whole team's budget on the wrong plan, and
116
140
  // the floor is what `--profile eco --risk low` cannot shift out of.
117
141
  conductor: 'deep',
@@ -0,0 +1,135 @@
1
+ /**
2
+ * platform-usage — subscription usage read from Claude Code's own config,
3
+ * for the case where the statusline never fires.
4
+ *
5
+ * THE PROBLEM THIS EXISTS FOR, measured rather than supposed. The usage gate
6
+ * reads `.tyran/state/usage.json`; only `statusline.mjs` writes it; the
7
+ * statusline writes only when the platform's payload carries `rate_limits`;
8
+ * and on a real machine that block is ABSENT — it is populated from
9
+ * `anthropic-ratelimit-unified-*` response headers that are not always sent.
10
+ * So no sidecar had ever been written anywhere on that machine, and a config
11
+ * carrying `limits: mode: 'pause'` had never once been able to fire. The gate
12
+ * fails open, so nothing ever said so: overnight mode was silently inert.
13
+ *
14
+ * Meanwhile `~/.claude.json` carries `cachedUsageUtilization` with the same
15
+ * two windows. Reading it removes the statusline from the critical path — and
16
+ * with it the one onboarding step no script can perform, since registering a
17
+ * statusline means writing the operator's own settings file.
18
+ *
19
+ * WHY A STALE READING IS STILL WORTH ACTING ON, which is the whole design.
20
+ * That cache is refreshed by the platform on its own schedule; measured at 83
21
+ * minutes old during heavy continuous use. Under the gate's ten-minute
22
+ * freshness rule it would be discarded every time and this would fix nothing.
23
+ *
24
+ * But usage within a window only ever goes UP. So a reading taken inside the
25
+ * window that is still running is a LOWER BOUND on usage now:
26
+ *
27
+ * - reading says >= threshold -> the true value is also >= threshold,
28
+ * so pausing is correct;
29
+ * - reading says < threshold -> the true value may be higher, so we may
30
+ * fail to pause — which is exactly what
31
+ * happens today, and is the safe direction.
32
+ *
33
+ * Acting on it is therefore never WORSE than ignoring it, and often better.
34
+ * The bound holds only while the window has not rolled: a reading of 95% taken
35
+ * before a reset says nothing about the fresh window after it, and acting on
36
+ * it would pause a session that has its full allowance. So a reading whose
37
+ * own `resets_at` has passed is discarded — that check is what makes the rest
38
+ * of this safe, and it is tested directly.
39
+ *
40
+ * Shape note: this file speaks the SIDECAR's language, not the platform's.
41
+ * `cachedUsageUtilization` reports `utilization` (0-100) and `resets_at` as an
42
+ * ISO string; the sidecar and the gate use `used_percentage` and epoch
43
+ * SECONDS. Converting here means the gate has one shape to reason about.
44
+ */
45
+ import { readFileSync } from 'node:fs';
46
+ import { homedir } from 'node:os';
47
+ import { join } from 'node:path';
48
+
49
+ /**
50
+ * Where the statusline writes and everything else reads.
51
+ *
52
+ * This path had THREE spellings — `statusline.mjs` (the writer),
53
+ * `overnight.mjs` (the scheduler) and `usage-gate.mjs` (the hook) each
54
+ * declared their own — and the freshness window had two. That is ADR-21's
55
+ * named defect in the one place it would be hardest to notice: nothing fails
56
+ * when they agree, and when they stop agreeing the symptom is a pause that
57
+ * silently never fires. Adding a fourth module here without collapsing them
58
+ * would have made it worse, so they collapse to these.
59
+ */
60
+ export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
61
+
62
+ /** Telemetry older than this is unknown, and unknown fails open. */
63
+ export const SIDECAR_FRESH_MS = 10 * 60 * 1000;
64
+
65
+ /** Where Claude Code keeps the config this reads. */
66
+ export const CLAUDE_CONFIG_RELPATH = '.claude.json';
67
+
68
+ /** Refuse to parse anything larger; measured at 65 KB on a real machine. */
69
+ const MAX_BYTES = 4 * 1024 * 1024;
70
+
71
+ /** The two windows the gate knows about, in the platform's spelling. */
72
+ const WINDOW_KEYS = Object.freeze(['five_hour', 'seven_day']);
73
+
74
+ function ownField(obj, name) {
75
+ return obj !== null && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, name)
76
+ ? obj[name]
77
+ : undefined;
78
+ }
79
+
80
+ /**
81
+ * One window, converted to the sidecar's shape, or null.
82
+ *
83
+ * `nowMs` decides whether the reading still describes a running window. A
84
+ * window whose reset has passed is not stale data, it is data about a
85
+ * DIFFERENT window, and no amount of freshness reasoning rescues it.
86
+ */
87
+ export function windowFrom(node, nowMs) {
88
+ const used = ownField(node, 'utilization');
89
+ const resetsRaw = ownField(node, 'resets_at');
90
+ if (typeof used !== 'number' || !Number.isFinite(used) || used < 0) return null;
91
+ if (typeof resetsRaw !== 'string') return null;
92
+ const resetsMs = Date.parse(resetsRaw);
93
+ if (!Number.isFinite(resetsMs)) return null;
94
+ // The bound only holds inside the window the reading was taken in.
95
+ if (resetsMs <= nowMs) return null;
96
+ return { used_percentage: used, resets_at: Math.floor(resetsMs / 1000) };
97
+ }
98
+
99
+ /**
100
+ * The platform's own usage cache, in sidecar shape, or null when it cannot be
101
+ * used. Never throws: this is read from inside a PreToolUse hook, and a hook
102
+ * that throws on a malformed config file stops the repository's work over
103
+ * telemetry it was only consulting.
104
+ *
105
+ * Measured cost: 0.29 ms to read and parse 65 KB, against the gate's 4-second
106
+ * budget and a hook process spawn that costs an order of magnitude more. No
107
+ * caching layer is warranted and none is here.
108
+ */
109
+ export function readPlatformUsage({ home = homedir(), readFile = readFileSync, nowMs = Date.now() } = {}) {
110
+ let doc;
111
+ try {
112
+ const raw = readFile(join(home, CLAUDE_CONFIG_RELPATH), 'utf8');
113
+ if (typeof raw !== 'string' || raw.length > MAX_BYTES) return null;
114
+ doc = JSON.parse(raw);
115
+ } catch {
116
+ // Absent, unreadable, not JSON, not signed in. One answer for all of them.
117
+ return null;
118
+ }
119
+ const utilization = ownField(ownField(doc, 'cachedUsageUtilization'), 'utilization');
120
+ if (utilization === null || typeof utilization !== 'object') return null;
121
+
122
+ const out = {};
123
+ for (const key of WINDOW_KEYS) {
124
+ const window = windowFrom(ownField(utilization, key), nowMs);
125
+ if (window !== null) out[key] = window;
126
+ }
127
+ if (Object.keys(out).length === 0) return null;
128
+
129
+ // `written_at` is the moment the reading is TRUE OF, which is now: the
130
+ // bound above is a statement about the present, derived from a past
131
+ // measurement. Stamping the platform's own fetch time here would hand the
132
+ // gate a document its freshness rule discards, reintroducing the bug.
133
+ // What the reading cannot support is a RESUME, and the gate is told so.
134
+ return { written_at: new Date(nowMs).toISOString(), lower_bound: true, source: 'claude.json', ...out };
135
+ }
@@ -5,7 +5,7 @@ description: The depth half of a review - the dimensions a diff is read against
5
5
  # Code review — reading depth
6
6
 
7
7
  > This is HOW a diff is read. WHAT the verdict looks like belongs to
8
- > `tyran:reviewer` — binary APPROVE or CHANGES-REQUESTED, numbered executable
8
+ > `tyran:reviewer` — APPROVE, REVISED or CHANGES-REQUESTED, numbered executable
9
9
  > counterexamples, a re-review that first checks the previous round's findings
10
10
  > are pinned as tests, and a section naming what was not checked. Do not
11
11
  > restate any of that here; two definitions of "reviewed" drift apart, and the