@jjanczur/tyran 0.1.31 → 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.
@@ -60,6 +60,7 @@ import { checkStop } from './stop-check.mjs';
60
60
  import { readJournal } from './journal.mjs';
61
61
  import { GATE_PASS } from './project.mjs';
62
62
  import { withKeepAwake } from './keepawake.mjs';
63
+ import { SIDECAR_RELPATH, SIDECAR_FRESH_MS } from './usage-source.mjs';
63
64
  import { limitsOf } from './schema.mjs';
64
65
  import { parse } from './yaml-lite.mjs';
65
66
  import { escapeInvisible } from './invisible.mjs';
@@ -67,13 +68,12 @@ import { escapeInvisible } from './invisible.mjs';
67
68
  export const MARKER_RELPATH = join('.tyran', 'state', 'paused-until.json');
68
69
  export const RESUME_STATE_RELPATH = join('.tyran', 'state', 'resume.json');
69
70
  export const RESUME_LOG_RELPATH = join('.tyran', 'state', 'resume.log');
70
- export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
71
+ export { SIDECAR_RELPATH, SIDECAR_FRESH_MS } from './usage-source.mjs';
71
72
 
72
73
  export const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
73
74
  /** Short enough that an overslept machine fires soon after waking. */
74
75
  export const MAX_SLEEP_CHUNK_MS = 15 * 60 * 1000;
75
76
  /** Telemetry older than this is unknown; unknown means proceed. */
76
- export const SIDECAR_FRESH_MS = 10 * 60 * 1000;
77
77
  /** Babysitting ladder after a resume that visibly did not take. */
78
78
  export const RESUME_BACKOFFS_MS = Object.freeze([5 * 60 * 1000, 30 * 60 * 1000, 60 * 60 * 1000]);
79
79
  /** Hard ceiling on a single `claude -p` attempt before the babysitter reclaims it. */
@@ -0,0 +1,255 @@
1
+ /**
2
+ * pricing — the shipped list-price rate card, and what the subscription costs.
3
+ *
4
+ * Before this file, `pricing:` was hand-authored or absent, and absent was the
5
+ * normal case: a fresh install reported every figure as an em dash, and the
6
+ * whole Spend tab answered "how many tokens" but never "how much". Asking a
7
+ * non-engineer to transcribe fourteen models × four rates into YAML was never
8
+ * going to happen, so the numbers ship.
9
+ *
10
+ * TWO PROPERTIES MAKE THIS SMALL ENOUGH TO KEEP HONEST:
11
+ *
12
+ * 1. **Cache rates are fixed multiples of base input**, published as such:
13
+ * a 5-minute write is 1.25x, a 1-hour write is 2x, a read is 0.1x. Every
14
+ * row of the published table satisfies this exactly — checked in the tests,
15
+ * not assumed — so only `input` and `output` are written down here. Four
16
+ * numbers per model would be four chances to mistype one.
17
+ * 2. **The 1M context window is standard-priced.** "Claude 4.6 and later
18
+ * models include the full 1M token context window at standard pricing",
19
+ * so `claude-opus-5[1m]` is the same rate as `claude-opus-5` and the
20
+ * context variant can be normalised away rather than modelled.
21
+ *
22
+ * WHAT THIS DELIBERATELY DOES NOT MODEL, because guessing would be worse than
23
+ * an honest gap, and each of these makes the real bill HIGHER than reported:
24
+ *
25
+ * - **Fast mode** (Opus 5 / 4.8) is $10 in / $50 out, double standard. It is
26
+ * not visible in a transcript, so a fast-mode session is under-reported.
27
+ * - **US-pinned inference** (`inference_geo: "us"`) is a 1.1x multiplier on
28
+ * every category, also not in a transcript.
29
+ * - **Server-side tool charges** — web search is $10 per 1,000 searches on
30
+ * top of tokens. The ledger counts tokens, so those are missing.
31
+ * - **The Batch API's 50% discount**, which Claude Code does not use.
32
+ *
33
+ * Every one of those is a modifier on a session shape Claude Code does not
34
+ * normally produce, and naming them here is cheaper than a reader discovering
35
+ * their bill is larger than the board's number and concluding the board lies.
36
+ *
37
+ * Prices change. `RATE_CARD_ID` travels with every amount the ledger prints,
38
+ * so a stale figure is identifiable rather than merely wrong, and an operator
39
+ * who wants different numbers still writes `pricing:` — a config block always
40
+ * wins over these defaults.
41
+ */
42
+
43
+ /** Published multipliers on the base input rate. Not a guess — the pricing
44
+ * page states them as the definition of the cache columns. */
45
+ export const CACHE_MULTIPLIERS = Object.freeze({
46
+ cache_write: 1.25, // a 5-minute cache write
47
+ cache_write_1h: 2, // a 1-hour cache write
48
+ cache_read: 0.1, // a cache hit or refresh
49
+ });
50
+
51
+ /**
52
+ * The label that travels with every priced amount. Bump it when the numbers
53
+ * below change, so a cached `state/cost.json` from an older card is visibly
54
+ * older rather than silently different.
55
+ */
56
+ export const RATE_CARD_ID = 'list-2026-08';
57
+
58
+ /**
59
+ * Base input and output, $ per million tokens, keyed by NORMALISED model.
60
+ * Retired models are kept: a ledger reads historical transcripts, and dropping
61
+ * a rate would silently move old spend into the unpriced column.
62
+ */
63
+ export const LIST_PRICES = Object.freeze({
64
+ 'fable-5': { input: 10, output: 50 },
65
+ 'mythos-5': { input: 10, output: 50 },
66
+ 'opus-5': { input: 5, output: 25 },
67
+ 'opus-4-8': { input: 5, output: 25 },
68
+ 'opus-4-7': { input: 5, output: 25 },
69
+ 'opus-4-6': { input: 5, output: 25 },
70
+ 'opus-4-5': { input: 5, output: 25 },
71
+ 'opus-4-1': { input: 15, output: 75 },
72
+ 'opus-4': { input: 15, output: 75 },
73
+ 'sonnet-5': { input: 2, output: 10 },
74
+ 'sonnet-4-6': { input: 3, output: 15 },
75
+ 'sonnet-4-5': { input: 3, output: 15 },
76
+ 'sonnet-4': { input: 3, output: 15 },
77
+ 'haiku-4-5': { input: 1, output: 5 },
78
+ 'haiku-3-5': { input: 0.8, output: 4 },
79
+ });
80
+
81
+ /**
82
+ * What a bare family name resolves to. The CLI accepts `opus` and resolves it
83
+ * to the current generation; a transcript can carry either spelling, and in
84
+ * measured data the bare form is rare but not zero (12 of 4840 requests).
85
+ * Pricing it as the current generation is what the CLI actually did.
86
+ */
87
+ const BARE_ALIASES = Object.freeze({
88
+ opus: 'opus-5',
89
+ sonnet: 'sonnet-5',
90
+ haiku: 'haiku-4-5',
91
+ fable: 'fable-5',
92
+ mythos: 'mythos-5',
93
+ });
94
+
95
+ /**
96
+ * A transcript's `message.model` reduced to a rate-card key.
97
+ *
98
+ * Real values seen in live transcripts, all of which must land somewhere:
99
+ * `claude-opus-5`, `claude-opus-5[1m]`, `claude-opus-4-8`, `claude-fable-5`,
100
+ * `claude-sonnet-5`, `claude-haiku-4-5-20251001`, `opus`, `sonnet`,
101
+ * `<synthetic>`. The last is not a model and must NOT resolve — a synthetic
102
+ * record carries no tokens and pricing it would invent spend.
103
+ */
104
+ export function normalizeModel(id) {
105
+ if (typeof id !== 'string') return null;
106
+ let key = id.trim().toLowerCase();
107
+ if (key === '' || key.startsWith('<')) return null;
108
+ // `[1m]` and friends are context-window variants, and long context is
109
+ // standard-priced, so the variant carries no rate information.
110
+ key = key.replace(/\[[^\]]*\]$/, '');
111
+ key = key.replace(/^claude-/, '');
112
+ // A trailing release date (`-20251001`) identifies a snapshot, not a price.
113
+ key = key.replace(/-\d{8}$/, '');
114
+ key = key.replace(/-v\d+$/, '');
115
+ if (Object.prototype.hasOwnProperty.call(BARE_ALIASES, key)) return BARE_ALIASES[key];
116
+ return Object.prototype.hasOwnProperty.call(LIST_PRICES, key) ? key : null;
117
+ }
118
+
119
+ /**
120
+ * The five rates for one model id, or null when it is not a model we price.
121
+ * Null is not zero — the ledger's `unpriced` list depends on that distinction.
122
+ */
123
+ export function ratesFor(id) {
124
+ const key = normalizeModel(id);
125
+ if (key === null) return null;
126
+ const { input, output } = LIST_PRICES[key];
127
+ return {
128
+ input,
129
+ cache_write: scaled(input, CACHE_MULTIPLIERS.cache_write),
130
+ cache_write_1h: scaled(input, CACHE_MULTIPLIERS.cache_write_1h),
131
+ cache_read: scaled(input, CACHE_MULTIPLIERS.cache_read),
132
+ output,
133
+ };
134
+ }
135
+
136
+ /**
137
+ * One rate times its multiplier, rounded to the precision the published table
138
+ * actually uses.
139
+ *
140
+ * Binary floating point makes `3 * 0.1` into `0.30000000000000004`, and while
141
+ * the error is ~1e-17 of a dollar and could never move an amount, the number
142
+ * is also PRINTED — in the rate card the board shows and in any config this
143
+ * seeds. A rate that renders as `0.30000000000000004` reads as a bug in the
144
+ * money, which costs more trust than the digits are worth. Six decimal places
145
+ * is exact for every value in the table (the longest is 18.75).
146
+ */
147
+ function scaled(base, multiplier) {
148
+ return Math.round(base * multiplier * 1e6) / 1e6;
149
+ }
150
+
151
+ /**
152
+ * A rate table for exactly the model ids observed, so the ledger prices the
153
+ * spellings it actually saw rather than the ones we happened to anticipate.
154
+ * Unknown ids are simply absent, which is what puts them in `unpriced`.
155
+ */
156
+ export function defaultRateCard(modelIds) {
157
+ const table = Object.create(null);
158
+ for (const id of modelIds) {
159
+ const rates = ratesFor(id);
160
+ if (rates !== null) table[id] = rates;
161
+ }
162
+ return table;
163
+ }
164
+
165
+ // ------------------------------------------------------------ subscription
166
+
167
+ /**
168
+ * List price per month, in USD, for the plans Claude Code reports.
169
+ *
170
+ * This is what makes "what would this have cost on the API" mean something:
171
+ * on its own the API-equivalent figure is a number with nothing to compare it
172
+ * to, and a subscriber's real marginal cost per token is zero.
173
+ */
174
+ export const SUBSCRIPTION_USD = Object.freeze({
175
+ pro: 20,
176
+ max_5x: 100,
177
+ max_20x: 200,
178
+ });
179
+
180
+ /** How each plan should be named to a human. */
181
+ export const PLAN_LABELS = Object.freeze({
182
+ pro: 'Pro',
183
+ max_5x: 'Max 5x',
184
+ max_20x: 'Max 20x',
185
+ });
186
+
187
+ /**
188
+ * The plan, from the tier string Claude Code stores.
189
+ *
190
+ * Measured shape: `oauthAccount.organizationRateLimitTier` reads
191
+ * `default_claude_max_20x`. Matching is deliberately loose about the prefix
192
+ * and strict about the multiplier, because the prefix is the platform's
193
+ * business and the multiplier is the part that changes the price.
194
+ */
195
+ /**
196
+ * The start of the subscription period containing `now`, given the day the
197
+ * subscription was created — `YYYY-MM-DD`, or null when it cannot be derived.
198
+ *
199
+ * A plan is billed monthly on its anniversary, so "what have I spent this
200
+ * period" means "since the most recent anniversary at or before today". That
201
+ * is the only window whose comparison against the monthly price needs no
202
+ * arithmetic from the reader.
203
+ *
204
+ * SHORT MONTHS ARE THE WHOLE DIFFICULTY. A subscription created on the 31st
205
+ * has no 31st in February, and naive date maths rolls that into March 3rd —
206
+ * which lands in the FUTURE and produces a period that has not begun. Every
207
+ * overflowing day clamps to the last day of its month instead, which is what
208
+ * billing does. Tested at every boundary, because this is wrong once a year
209
+ * and silently.
210
+ */
211
+ export function periodStart(createdAt, now) {
212
+ // Strings only. `new Date(null)` is epoch zero, not an invalid date, so a
213
+ // null subscription date would otherwise produce a confident 1970
214
+ // anniversary and a window sweeping in everything ever recorded.
215
+ if (typeof createdAt !== 'string' || typeof now !== 'string') return null;
216
+ const created = new Date(createdAt);
217
+ const at = new Date(now);
218
+ if (!Number.isFinite(created.getTime()) || !Number.isFinite(at.getTime())) return null;
219
+ if (at < created) return null;
220
+
221
+ const anniversary = created.getUTCDate();
222
+ // Candidate: the anniversary within the current month. If that is still in
223
+ // the future, the period began in the previous month.
224
+ let year = at.getUTCFullYear();
225
+ let month = at.getUTCMonth();
226
+ if (clampedDay(year, month, anniversary) > at.getUTCDate()) {
227
+ month -= 1;
228
+ if (month < 0) {
229
+ month = 11;
230
+ year -= 1;
231
+ }
232
+ }
233
+ const day = clampedDay(year, month, anniversary);
234
+ const iso = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
235
+ // Never earlier than the subscription itself: the first period starts the
236
+ // day it was created, not on an anniversary that predates it.
237
+ const createdDay = createdAt.slice(0, 10);
238
+ return iso < createdDay ? createdDay : iso;
239
+ }
240
+
241
+ /** `day`, or the last day of that month when the month is too short for it. */
242
+ function clampedDay(year, month, day) {
243
+ const lastOfMonth = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
244
+ return Math.min(day, lastOfMonth);
245
+ }
246
+
247
+ export function planOfTier(tier) {
248
+ if (typeof tier !== 'string') return null;
249
+ const key = tier.trim().toLowerCase();
250
+ if (key === '') return null;
251
+ if (/max[_-]?20x/.test(key)) return 'max_20x';
252
+ if (/max[_-]?5x/.test(key)) return 'max_5x';
253
+ if (/\bpro\b|_pro$|^pro_/.test(key)) return 'pro';
254
+ return null;
255
+ }
@@ -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