@jjanczur/tyran 0.1.17 → 0.1.18

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.17",
14
+ "version": "0.1.18",
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.17",
3
+ "version": "0.1.18",
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,79 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.18 — 2026-08-14
4
+
5
+ ### The spend ledger: nobody could say what a run cost
6
+
7
+ `node scripts/cost.mjs` reports what the work cost, in tokens the platform
8
+ itself reported, per model, per agent type and per ticket. It **reads, it never
9
+ instruments**: every number comes from the `message.usage` records Claude Code
10
+ already writes under `~/.claude/projects/`, so there is no hook, no probe, no
11
+ new event type and nothing to keep in sync.
12
+
13
+ It is deliberately **not a projection**, and that is the decision the rest
14
+ follows from. Its inputs are machine-local and differ per clone, so two people
15
+ with the same journal legitimately get different numbers — which is exactly
16
+ what a byte-exact `--check` would report as drift. `cost.json` is therefore
17
+ never committed (it joins the runtime files `.tyran/.gitignore` excludes),
18
+ never byte-compared, and never merged into `board.json`.
19
+
20
+ **Tokens are facts; money is an opinion.** Only tokens are counted. Money comes
21
+ from an operator-written `pricing:` block, and the card's name travels with
22
+ every amount — a figure that cannot say which card produced it is not a
23
+ measurement. Absent pricing gives tokens and no money, which is the honest
24
+ default: Tyran does not know what anyone pays. All four rate keys are required
25
+ per model, because a table carrying three would price the fourth at zero,
26
+ silently, and cache reads alone were measured at roughly three quarters of a
27
+ real session's cost.
28
+
29
+ Gaps are reported rather than zeroed: `unpriced` models are counted in tokens
30
+ and absent from every amount, `unattributed` agents are the ones whose task
31
+ description carried no ticket id, `unreadable` transcripts are named. A model
32
+ that billed zero tokens is not reported as unpriced — that would be a permanent
33
+ false warning about something that cannot cost anything. And partial pricing is
34
+ a partial sum: an amount is blank only when nothing in the row is priced at
35
+ all, because a real rate card always misses something and nulling the grand
36
+ total over one absent row would leave every figure blank forever.
37
+
38
+ The conductor is its own row. Its context is not attributable to any ticket and
39
+ was measured between 44% and 86% of a tree's tokens, so a per-ticket table that
40
+ omitted it would present a fraction of the bill as the cost of the work. That
41
+ share is reported in tokens, never dollars: a partial rate card prices only some
42
+ models, so a dollar share is a ratio over whichever subset happened to be
43
+ priced — the same tree read 86% by tokens and 99% by dollars.
44
+
45
+ Ticket attribution cost nothing to add. The conductor already puts the ticket id
46
+ at the head of a `Task` description; the reader takes it back out of the agent's
47
+ `.meta.json`. No journal change, no event-set change, and an agent whose
48
+ description omits the id lands in a visible `unattributed` bucket rather than
49
+ being guessed at.
50
+
51
+ `board.html` gains a **Spend** section, and it **fetches `cost.json` rather than
52
+ embedding it** — a deliberate amendment to the page's "self-contained, no
53
+ network" description. It is still zero external hosts and zero CDNs; what it
54
+ makes is one same-origin request to loopback. Over `file://` there is no server,
55
+ the request fails, and the section never appears, so `board.json` and
56
+ `board.html` keep their byte-exact `--check` contract and carry no machine-local
57
+ data. The `/cost.json` route is covered by the existing `Host` pin (a foreign
58
+ `Host` gets 403, verified) and returns 503 rather than taking the board down if
59
+ the cost read fails.
60
+
61
+ Transcripts reach tens of megabytes and the page refreshes every 30 seconds, so
62
+ the reader streams in chunks and caches per source file keyed on `(path, mtime,
63
+ size)`. A finished agent's transcript never changes, so only the running
64
+ session's file is re-read. Measured cold: a 226-transcript tree totalling 6.86
65
+ billion tokens scans in 1.7 s.
66
+
67
+ Also reachable as `npx @jjanczur/tyran cost`. Exit 0 ok · 2 usage, I/O, or no
68
+ transcripts found — spend is read, and nothing here estimates it.
69
+
70
+ **Upgrading: regenerate your board.** `board.html` gained the Spend section, so
71
+ its BYTES changed even though its contract did not. A repo that committed a
72
+ board rendered by an earlier version will see `board.mjs --check` report drift —
73
+ and `doctor --state` report `projection-drift` — until you run
74
+ `node scripts/board.mjs --dir .tyran` and commit the result. `board.json` and
75
+ `BOARD.md` are byte-identical to 0.1.17.
76
+
3
77
  ## 0.1.17 — 2026-08-14
4
78
 
5
79
  ### A race test that picked a winner
package/README.md CHANGED
@@ -359,7 +359,7 @@ Published on npm as [`@jjanczur/tyran`](https://www.npmjs.com/package/@jjanczur/
359
359
  command stays `tyran` either way; only the registry name is scoped, the same
360
360
  pattern as `@angular/cli` giving you `ng`. `bin/tyran.mjs` exposes the same
361
361
  scripts the plugin's hooks and skills already call — `doctor`, `scan-repo`,
362
- `tiers`, `journal`, `schema`, `knowledge`, `board`, `answer`, `overnight`, `statusline`, `stop-check`,
362
+ `tiers`, `journal`, `schema`, `knowledge`, `board`, `cost`, `answer`, `overnight`, `statusline`, `stop-check`,
363
363
  `scan-control-chars`, `desc-budget` — for a shell or a CI job with no Claude
364
364
  Code session. Zero dependencies; `--help` lists them.
365
365
 
@@ -444,6 +444,11 @@ underlying script does.
444
444
  - [x] Read-only dashboard: the kanban board — `BOARD.md`/`board.json` next to
445
445
  every journal, one cross-initiative `board.html` in the landing page's
446
446
  own palette, refreshed on every subagent stop, plus `board.mjs --serve`
447
+ - [x] The spend ledger: what the work actually cost, read out of the
448
+ transcripts Claude Code already writes — tokens per model, per agent type
449
+ and per ticket, money only under a rate card you write, and a Spend
450
+ section the board fetches rather than embeds — see
451
+ [docs/cost.md](docs/cost.md)
447
452
  - [x] The mistakes ledger: `MISTAKES.md` at your repo root — what went wrong
448
453
  here and how often — where three occurrences of one signature graduate a
449
454
  lesson into `.tyran/knowledge/` and five write a rule into your
package/bin/tyran.mjs CHANGED
@@ -88,6 +88,10 @@ export const COMMANDS = {
88
88
  'board.mjs',
89
89
  'Render the cross-initiative kanban board — BOARD.md, board.json and the board.html dashboard — from the journals under .tyran/state/.',
90
90
  ],
91
+ cost: [
92
+ 'cost.mjs',
93
+ 'What the work cost, in tokens the platform reported — per model, per agent type and per ticket, priced by your own rate card.',
94
+ ],
91
95
  answer: [
92
96
  'answer.mjs',
93
97
  'Write the sheet of questions waiting on you, then fold your answers back into the journal.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
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": {
@@ -78,6 +78,35 @@ h2{font-family:var(--display);color:var(--heading);font-size:1.05rem;margin:1.5r
78
78
  .card .note{color:var(--muted);font-size:.78rem;display:block}
79
79
  .empty{color:var(--hairline);font-size:.8rem}
80
80
  footer{margin-top:2rem;color:var(--muted);font-size:.75rem;border-top:1px solid var(--hairline-soft);padding-top:.6rem}
81
+ .spend-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:.8rem}
82
+ .toggle{display:flex;gap:.25rem;margin-left:auto}
83
+ .toggle button{font-family:var(--mono);font-size:.7rem;letter-spacing:.06em;text-transform:uppercase;background:var(--bg-raised);color:var(--muted);border:1px solid var(--hairline);border-radius:.35rem;padding:.2rem .6rem;cursor:pointer}
84
+ .toggle button[aria-pressed="true"]{background:var(--gold-low);border-color:var(--gold);color:var(--gold-bright)}
85
+ .toggle button:focus-visible{outline:2px solid var(--glow);outline-offset:2px}
86
+ .tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));gap:.6rem;margin:.6rem 0}
87
+ .stile{background:var(--bg-raised);border:1px solid var(--hairline);border-radius:.55rem;padding:.6rem .8rem}
88
+ .stile .lbl{display:block;font-family:var(--mono);font-size:.65rem;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}
89
+ .stile .big{display:block;font-family:var(--mono);font-size:1.35rem;color:var(--heading);font-variant-numeric:tabular-nums;line-height:1.25}
90
+ .stile .sub{display:block;font-family:var(--mono);font-size:.7rem;color:var(--muted)}
91
+ .stile.gold{background:var(--gold-low);border-color:var(--gold)}
92
+ .stile.gold .big{color:var(--gold-bright)}
93
+ .comp{display:flex;height:1.5rem;border:1px solid var(--hairline);border-radius:.35rem;overflow:hidden}
94
+ .comp span{display:flex;align-items:center;justify-content:center;font-family:var(--mono);font-size:.65rem;color:var(--bg);font-weight:700;white-space:nowrap;overflow:hidden}
95
+ .comp .s-cache_read{background:var(--gold)}
96
+ .comp .s-cache_write{background:var(--glow)}
97
+ .comp .s-output{background:var(--green)}
98
+ .comp .s-input{background:var(--muted)}
99
+ .compkey{display:flex;flex-wrap:wrap;gap:.9rem;font-family:var(--mono);font-size:.68rem;color:var(--muted);margin-top:.35rem}
100
+ .compkey i{display:inline-block;width:.6rem;height:.6rem;border-radius:.15rem;margin-right:.3rem}
101
+ .chart{display:flex;flex-direction:column;gap:.28rem;margin-top:.4rem}
102
+ .chartrow{display:grid;grid-template-columns:minmax(7rem,14rem) 1fr auto;gap:.6rem;align-items:center;font-size:.8rem}
103
+ .chartrow .rl{font-family:var(--mono);color:var(--heading);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
104
+ .chartrow .rb{background:var(--bg-sunken);border-radius:.25rem;height:.85rem;overflow:hidden}
105
+ .chartrow .rb i{display:block;height:100%;background:var(--gold);border-radius:.25rem}
106
+ .chartrow.dim .rl{color:var(--muted);font-style:italic}
107
+ .chartrow.dim .rb i{background:var(--hairline)}
108
+ .chartrow .rv{font-family:var(--mono);font-variant-numeric:tabular-nums;color:var(--text);min-width:5.5rem;text-align:right}
109
+ .caveat{color:var(--muted);font-size:.78rem;margin-top:.5rem}
81
110
  `;
82
111
 
83
112
  /**
@@ -187,6 +216,171 @@ if (data.schema !== 1) {
187
216
  });
188
217
  app.appendChild(lanesWrap);
189
218
 
219
+ var fmtTokens = function (n) {
220
+ if (n >= 1e9) return (n / 1e9).toFixed(2) + ' B';
221
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + ' M';
222
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + ' k';
223
+ return String(n);
224
+ };
225
+ // An amount that rounds to nothing still cost something. Printing $0.00
226
+ // there reads as free, which is the one reading that would change a
227
+ // routing decision for the wrong reason.
228
+ var fmtUsd = function (v) {
229
+ if (v === null || v === undefined) return '—';
230
+ if (v > 0 && v < 0.01) return '<$0.01';
231
+ return '$' + v.toFixed(2);
232
+ };
233
+
234
+ var tile = function (label, big, sub, cls) {
235
+ var box = el('div', cls ? 'stile ' + cls : 'stile');
236
+ box.appendChild(el('span', 'lbl', label));
237
+ box.appendChild(el('span', 'big', big));
238
+ box.appendChild(el('span', 'sub', sub));
239
+ return box;
240
+ };
241
+
242
+ // One ranked bar chart. The bar is the comparison; the number beside it is
243
+ // the fact. A row whose models have no rate shows no bar at all rather than
244
+ // a zero-length one, because "not priced" and "cost nothing" must not look
245
+ // the same.
246
+ var chart = function (allRows, key, metric, dimKeys) {
247
+ var box = el('div', 'chart');
248
+ // Ranked by the metric on screen, not by the one the server happened to
249
+ // sort by. In cost view a cheap-and-chatty row was being listed above an
250
+ // expensive-and-terse one — the precise inversion of the routing signal
251
+ // this view exists to give. Rows with no price sort last.
252
+ var valueOf = function (r) { return metric === 'usd' ? r.usd : r.tokens; };
253
+ var rows = allRows.slice().sort(function (a, b) {
254
+ var av = valueOf(a);
255
+ var bv = valueOf(b);
256
+ if (typeof av !== 'number' && typeof bv !== 'number') return 0;
257
+ if (typeof av !== 'number') return 1;
258
+ if (typeof bv !== 'number') return -1;
259
+ return bv - av || String(a[key]).localeCompare(String(b[key]));
260
+ });
261
+ var values = rows.map(valueOf);
262
+ var max = 0;
263
+ values.forEach(function (v) { if (typeof v === 'number' && v > max) max = v; });
264
+ rows.forEach(function (r, i) {
265
+ var value = values[i];
266
+ var unpriced = metric === 'usd' && (value === null || value === undefined);
267
+ var dim = unpriced || dimKeys.indexOf(r[key]) !== -1;
268
+ var row = el('div', dim ? 'chartrow dim' : 'chartrow');
269
+ row.appendChild(el('div', 'rl', r[key]));
270
+ var track = el('div', 'rb');
271
+ var fill = el('i');
272
+ fill.style.width = (max > 0 && typeof value === 'number' ? (value / max) * 100 : 0) + '%';
273
+ track.appendChild(fill);
274
+ row.appendChild(track);
275
+ row.appendChild(el('div', 'rv', metric === 'usd' ? fmtUsd(value) : fmtTokens(value)));
276
+ box.appendChild(row);
277
+ });
278
+ return box;
279
+ };
280
+
281
+ var renderSpend = function (into, cost, metric) {
282
+ while (into.firstChild) into.removeChild(into.firstChild);
283
+ var t = cost.totals || {};
284
+ var cov = cost.coverage || {};
285
+
286
+ var header = el('div', 'spend-head');
287
+ header.appendChild(el('h2', null, 'Spend'));
288
+ var toggle = el('div', 'toggle');
289
+ [['tokens', 'tokens'], ['usd', 'cost']].forEach(function (pair) {
290
+ var button = el('button', null, pair[1]);
291
+ button.setAttribute('type', 'button');
292
+ button.setAttribute('aria-pressed', metric === pair[0] ? 'true' : 'false');
293
+ button.addEventListener('click', function () { renderSpend(into, cost, pair[0]); });
294
+ toggle.appendChild(button);
295
+ });
296
+ header.appendChild(toggle);
297
+ into.appendChild(header);
298
+
299
+ var tiles = el('div', 'tiles');
300
+ tiles.appendChild(tile('tokens', fmtTokens(t.tokens || 0), (t.requests || 0) + ' requests'));
301
+ tiles.appendChild(tile(
302
+ 'cost through the API', fmtUsd(t.usd),
303
+ cost.rate_card ? 'rate card ' + cost.rate_card : 'no rate card set', 'gold'));
304
+ tiles.appendChild(tile(
305
+ 'conductor overhead', (t.conductor_token_share || 0) + '%', 'of tokens, no ticket'));
306
+ tiles.appendChild(tile(
307
+ 'attributed', (cov.attributed || 0) + ' / ' + (cov.agent_transcripts || 0),
308
+ (cov.unattributed || 0) + ' agent(s) without a ticket'));
309
+ into.appendChild(tiles);
310
+
311
+ // The composition is the point of the whole section: cache reads dominate
312
+ // the bill, so the lever is context size and turn count, not model price.
313
+ var comp = (cost.composition || []).slice().sort(function (a, b) {
314
+ return metric === 'usd' ? (b.usd || 0) - (a.usd || 0) : b.tokens - a.tokens;
315
+ });
316
+ var compTotal = 0;
317
+ comp.forEach(function (c) { compTotal += metric === 'usd' ? (c.usd || 0) : c.tokens; });
318
+ if (compTotal > 0) {
319
+ var bar = el('div', 'comp');
320
+ var key = el('div', 'compkey');
321
+ comp.forEach(function (c) {
322
+ var value = metric === 'usd' ? (c.usd || 0) : c.tokens;
323
+ if (value <= 0) return;
324
+ var pct = Math.round((value / compTotal) * 100);
325
+ var seg = el('span', 's-' + c.kind, pct >= 8 ? pct + '%' : '');
326
+ // Normalised to a share, not set to the raw value: flex-grow below 1
327
+ // does not fill its container, and dollar amounts are routinely
328
+ // fractions. Measured — the cost view drew a bar 13% of the width
329
+ // while the token view, whose values are thousands, filled it.
330
+ seg.style.flex = String((value / compTotal) * 100);
331
+ bar.appendChild(seg);
332
+ var legend = el('span', null);
333
+ var swatch = el('i', 's-' + c.kind);
334
+ legend.appendChild(swatch);
335
+ legend.appendChild(el('span', null,
336
+ c.kind.replace('_', ' ') + ' ' + (metric === 'usd' ? fmtUsd(c.usd) : fmtTokens(c.tokens))));
337
+ key.appendChild(legend);
338
+ });
339
+ into.appendChild(bar);
340
+ into.appendChild(key);
341
+ }
342
+
343
+ [['By model', cost.by_model || [], 'model', []],
344
+ ['By agent type', cost.by_agent_type || [], 'agent_type', ['conductor']],
345
+ ['By ticket', cost.by_ticket || [], 'ticket', ['conductor', 'unattributed']]].forEach(function (spec) {
346
+ into.appendChild(el('h3', null, spec[0]));
347
+ into.appendChild(chart(spec[1], spec[2], metric, spec[3]));
348
+ });
349
+
350
+ var notes = [];
351
+ notes.push('Conductor context is not attributable to any ticket; it is shown as its own row so the rows sum to the total.');
352
+ if ((cov.unattributed || 0) > 0) {
353
+ notes.push(cov.unattributed + ' agent(s) carry no ticket id in their task description and are grouped as unattributed.');
354
+ }
355
+ if ((cost.unpriced || []).length > 0) {
356
+ notes.push('Counted in tokens but absent from every amount, having no rate: ' + cost.unpriced.join(', ') + '.');
357
+ }
358
+ // A gap the page must never keep to itself: a transcript appended to while
359
+ // it is read ends in a partial record, so the number above is low by an
360
+ // amount only this line reports.
361
+ if ((cov.malformed || 0) > 0 || (cov.skipped_lines || 0) > 0) {
362
+ notes.push((cov.malformed || 0) + ' unparseable and ' + (cov.skipped_lines || 0) +
363
+ ' oversized record(s) were skipped; their tokens are missing from every figure here.');
364
+ }
365
+ into.appendChild(el('div', 'caveat', notes.join(' ')));
366
+ };
367
+
368
+ // Spend is FETCHED, never embedded. It is derived from transcripts under the
369
+ // operator's home directory — machine-local, different in every clone — so
370
+ // writing it into board.json would break the byte-exact --check contract and
371
+ // make two people with one journal disagree. Opened over file:// there is no
372
+ // server, the request fails, and the section simply never appears.
373
+ var spendAt = el('div');
374
+ app.appendChild(spendAt);
375
+ if (typeof fetch === 'function') {
376
+ fetch('cost.json', { headers: { accept: 'application/json' } })
377
+ .then(function (r) { return r.ok ? r.json() : null; })
378
+ .then(function (cost) {
379
+ if (cost && cost.schema === 1 && cost.transcripts_found) renderSpend(spendAt, cost, 'tokens');
380
+ })
381
+ .catch(function () { /* no server: the board is complete without it */ });
382
+ }
383
+
190
384
  // An initiative the board could not read is the one thing this page must
191
385
  // never omit: a missing card is indistinguishable from an initiative with
192
386
  // no work, which is the "all is well" reading the board exists to prevent.
package/scripts/board.mjs CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  } from './project.mjs';
42
42
  import { jsonEscapeInvisible } from './invisible.mjs';
43
43
  import { renderBoardHtml } from './board-html.mjs';
44
+ import { COST_SCHEMA, costJson, costReport } from './cost.mjs';
44
45
 
45
46
  export const BOARD_HTML_FILE = 'board.html';
46
47
 
@@ -261,8 +262,14 @@ function main() {
261
262
  const outDir = join(dir, 'state');
262
263
 
263
264
  if (flags.serve) {
264
- // Read-only, loopback-only, re-rendered per request so it is always
265
- // fresh. No filesystem path is ever derived from the URL.
265
+ // Loopback-only, re-rendered per request so it is always fresh. No
266
+ // filesystem path is ever derived from the URL.
267
+ //
268
+ // Not quite read-only, and the exception is worth stating rather than
269
+ // discovering: `/cost.json` refreshes the machine-local spend cache at
270
+ // `state/cost.json`. Nothing else is written, and that file is a
271
+ // gitignored runtime artefact — no journal, no projection, nothing
272
+ // committed.
266
273
  const server = createServer((req, res) => {
267
274
  try {
268
275
  // Binding to loopback is not enough on its own: any web page the
@@ -277,6 +284,28 @@ function main() {
277
284
  res.end('forbidden: this board answers to 127.0.0.1 only\n');
278
285
  return;
279
286
  }
287
+ // Spend is served, never rendered into the artefacts. It is derived
288
+ // from transcripts under the operator's home directory — machine-local
289
+ // by nature — so putting it in board.json would make two clones of one
290
+ // journal disagree and break the byte-exact `--check` contract. The
291
+ // page fetches this route and simply omits the section when the fetch
292
+ // fails, which is what happens over file://.
293
+ if (req.url === '/cost.json') {
294
+ let body;
295
+ try {
296
+ body = costJson(costReport({ tyranDir: dir }));
297
+ } catch (err) {
298
+ // A cost failure must never take the board down with it: the
299
+ // board answers "what is going on", and that answer does not
300
+ // depend on knowing what it cost.
301
+ res.writeHead(503, { 'content-type': 'application/json; charset=utf-8' });
302
+ res.end(JSON.stringify({ schema: COST_SCHEMA, error: String(err?.message ?? err) }) + '\n');
303
+ return;
304
+ }
305
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
306
+ res.end(body);
307
+ return;
308
+ }
280
309
  const { files } = renderAll(dir);
281
310
  if (req.url === '/' || req.url === '/index.html') {
282
311
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });