@jjanczur/tyran 0.1.31 → 0.1.33

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.
@@ -62,9 +62,9 @@
62
62
  * It is never interpolated into another command and never expanded.
63
63
  */
64
64
  import { spawn } from 'node:child_process';
65
- import { realpathSync } from 'node:fs';
65
+ import { realpathSync, statSync } from 'node:fs';
66
66
  import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
67
- import { tmpdir } from 'node:os';
67
+ import { homedir, tmpdir } from 'node:os';
68
68
  import { basename, dirname, join, resolve as resolvePath } from 'node:path';
69
69
  import { fileURLToPath } from 'node:url';
70
70
 
@@ -110,8 +110,83 @@ const MAX_FINDINGS_SHOWN = 10;
110
110
  export const MAX_PATH_CHARS = 120;
111
111
  export const MAX_RULE_CHARS = 60;
112
112
 
113
- /** Where the scanner lives. An operator may point at a pinned build. */
114
- export const GITLEAKS_BIN = () => process.env.TYRAN_GITLEAKS_BIN || 'gitleaks';
113
+ /**
114
+ * Where the scanner lives, in order of authority.
115
+ *
116
+ * 1. TYRAN_GITLEAKS_BIN — the operator pointing at a build they chose.
117
+ * 2. `gitleaks` on PATH — the machine's own, if it has one.
118
+ * 3. ~/.tyran/bin/gitleaks — the pinned build `scripts/ensure-gitleaks.mjs`
119
+ * fetched and checksummed, for a machine that had none.
120
+ *
121
+ * Step 3 exists because the prerequisite was the wall. This gate refuses
122
+ * every commit and push until a scanner exists, and it refuses rather than
123
+ * warning for a reason that has not changed — but the design assumed the
124
+ * operator could install a binary, and for the people now adopting Tyran that
125
+ * is often false: no Homebrew, no admin rights, Windows. Their realistic
126
+ * response to "install gitleaks and re-run" is to switch this hook off, and a
127
+ * gate nobody can satisfy protects nothing.
128
+ *
129
+ * It is the HOME directory and deliberately not `<repo>/.tyran/bin/`, which
130
+ * was the first shape of this and is worse in a way worth recording: a path
131
+ * inside the repository travels with a clone, so a planted binary that
132
+ * reports clean on everything would arrive with the checkout — an attack the
133
+ * tracked-only rule for `.gitleaksignore` already exists to prevent, reopened
134
+ * through a file that is not even in a diff. Under the home directory the
135
+ * scanner is the operator's machine, exactly like PATH, and one install
136
+ * serves every repository on it.
137
+ *
138
+ * PATH is consulted BEFORE it: a gitleaks the operator installed themselves
139
+ * is their decision, and a newer one should not be silently displaced by
140
+ * whatever version Tyran happens to pin.
141
+ */
142
+ export function gitleaksBin() {
143
+ const explicit = process.env.TYRAN_GITLEAKS_BIN;
144
+ if (typeof explicit === 'string' && explicit !== '') return explicit;
145
+ if (onPath('gitleaks')) return 'gitleaks';
146
+ return managedScanner() ?? 'gitleaks';
147
+ }
148
+
149
+ /** Backwards-compatible alias: this was a zero-argument arrow. */
150
+ export const GITLEAKS_BIN = gitleaksBin;
151
+
152
+ /**
153
+ * Is a name resolvable through PATH? Checked by looking rather than by
154
+ * spawning: this runs before every scan, and a spawn to answer "does a spawn
155
+ * work" costs more than the lookup it is standing in for.
156
+ */
157
+ function onPath(name) {
158
+ const entries = String(process.env.PATH ?? '').split(process.platform === 'win32' ? ';' : ':');
159
+ const names = process.platform === 'win32' ? [`${name}.exe`, `${name}.cmd`, name] : [name];
160
+ for (const dir of entries) {
161
+ if (dir === '') continue;
162
+ for (const candidate of names) {
163
+ try {
164
+ if (statSync(join(dir, candidate)).isFile()) return true;
165
+ } catch { /* not here; keep looking */ }
166
+ }
167
+ }
168
+ return false;
169
+ }
170
+
171
+ /**
172
+ * The pinned build under the operator's home, or null.
173
+ *
174
+ * Every failure returns null rather than throwing: this runs inside a gate
175
+ * whose refusal is the product, and an unreadable home directory must degrade
176
+ * to the ordinary "gitleaks is not installed" refusal — which already carries
177
+ * instructions — never take the session down with an unhandled error.
178
+ */
179
+ function managedScanner() {
180
+ try {
181
+ const home = homedir();
182
+ if (typeof home !== 'string' || home === '') return null;
183
+ const name = process.platform === 'win32' ? 'gitleaks.exe' : 'gitleaks';
184
+ const path = join(home, '.tyran', 'bin', name);
185
+ return statSync(path).isFile() ? path : null;
186
+ } catch {
187
+ return null;
188
+ }
189
+ }
115
190
 
116
191
  /** Suppression files, honoured ONLY when git tracks them. See `suppression`. */
117
192
  export const SUPPRESSION_FILES = Object.freeze({
@@ -125,9 +200,22 @@ export const SUPPRESSION_FILES = Object.freeze({
125
200
  /**
126
201
  * Characters at which one shell command can end and another begin.
127
202
  *
128
- * Quoting is deliberately NOT honoured: splitting inside a quoted string can
129
- * only produce MORE candidate segments, never fewer, and more candidates is
130
- * the direction this gate wants to be wrong in.
203
+ * QUOTING is deliberately NOT honoured, and that is not laziness — it is the
204
+ * only safe reading. Splitting inside a quoted string can only produce MORE
205
+ * candidate segments, never fewer, and more candidates is the direction this
206
+ * gate wants to be wrong in. A quote-aware lexer is worse than this one:
207
+ * measured, `git commit -m "it's the source of truth" ; git push origin main`
208
+ * has its apostrophe close the double quote, swallows the `;`, and the push
209
+ * becomes INVISIBLE — the gate reads the verb as `commit`, runs no
210
+ * deployment-class check, and scans the commit instead of the push range.
211
+ * This repository's own commit messages say "source of truth" constantly.
212
+ *
213
+ * BACKSLASH ESCAPES are honoured, because unlike quoting they cannot hide a
214
+ * separator. In all three shell contexts — unquoted, single-quoted,
215
+ * double-quoted — `\<sep>` is never an operator, so consuming it can only
216
+ * remove a split the shell would not have made. Verified against `/bin/sh`
217
+ * with a side-effect oracle over 34 join constructions: zero cases where the
218
+ * shell ran a second command and this lexer kept one segment.
131
219
  */
132
220
  export const SEPARATORS = ';&|\n\r()`{}<>';
133
221
 
@@ -221,8 +309,22 @@ export function splitSegments(command) {
221
309
  const folded = stripHeredocBodies(command).replace(/\\\r?\n/g, ' ');
222
310
  const out = [];
223
311
  let current = '';
312
+ let escaped = false;
224
313
  for (const ch of folded) {
225
- if (SEPARATORS.includes(ch)) {
314
+ // ORDER IS LOAD-BEARING. This branch must come first so an escaped
315
+ // backslash consumes itself: without it `echo a\\; git push origin main`
316
+ // reads the real `;` as escaped and the push disappears. Measured — it is
317
+ // the most likely way to get this patch subtly wrong.
318
+ if (escaped) {
319
+ escaped = false;
320
+ current += ch;
321
+ } else if (ch === '\\') {
322
+ escaped = true;
323
+ // KEPT, not dropped: `tokensOf` strips backslashes downstream and
324
+ // `isLiteralPath` inspects this text, so removing it here would change
325
+ // what every consumer sees for a reason unrelated to splitting.
326
+ current += ch;
327
+ } else if (SEPARATORS.includes(ch)) {
226
328
  out.push(current);
227
329
  current = '';
228
330
  } else {
@@ -1028,6 +1130,23 @@ export async function isTracked(repo, path, { runner, timeoutMs }) {
1028
1130
  * unexamined. Reproduced on the first attempt: the range counted 0 commits
1029
1131
  * while origin held none of them.
1030
1132
  */
1133
+ /**
1134
+ * The branch HEAD is on, or null when git cannot say (detached HEAD, a repo
1135
+ * with no commits, git unavailable). Null becomes a placeholder in the remedy
1136
+ * rather than a wrong branch name: a command that looks runnable and is not
1137
+ * is worse than one that visibly needs a word filled in.
1138
+ */
1139
+ async function currentBranch(repo, { runner, timeoutMs }) {
1140
+ try {
1141
+ const r = await runner('git', ['-C', repo, 'symbolic-ref', '--quiet', '--short', 'HEAD'], { timeoutMs });
1142
+ if (r.spawned !== true || r.timedOut === true || r.code !== 0) return null;
1143
+ const name = String(r.stdout ?? '').trim();
1144
+ return name === '' ? null : name;
1145
+ } catch {
1146
+ return null;
1147
+ }
1148
+ }
1149
+
1031
1150
  export async function pushRange(repo, remote, refs, { runner, timeoutMs }) {
1032
1151
  const listed = await git(['-C', repo, 'remote'], { runner, timeoutMs, what: 'listing remotes' });
1033
1152
  const remotes = String(listed).trim().split('\n').filter((r) => r !== '');
@@ -1036,11 +1155,28 @@ export async function pushRange(repo, remote, refs, { runner, timeoutMs }) {
1036
1155
  if (remotes.length === 1) target = remotes[0];
1037
1156
  else if (remotes.length === 0) target = null;
1038
1157
  else {
1158
+ // Hand over the command, do not describe its shape.
1159
+ //
1160
+ // This refusal is CORRECT — excluding commits present on any remote let
1161
+ // a key held on a private upstream reach a public origin unscanned — but
1162
+ // it was reported twice from two installs as a false positive, and both
1163
+ // reporters worked around it rather than satisfying it. The reason is
1164
+ // visible in the old text: `git push <remote> <branch>` is a template,
1165
+ // and the operator has to work out both halves while being told no.
1166
+ //
1167
+ // Everything needed to write the real line is already in hand here, so
1168
+ // it is written. A remedy you can paste is a different object from a
1169
+ // remedy you have to translate, and this gate's whole cost is paid in
1170
+ // the moments people spend deciding whether to route around it.
1171
+ const branch = await currentBranch(repo, { runner, timeoutMs });
1172
+ const ref = branch === null ? '<branch>' : branch;
1173
+ const lines = remotes.map((r) => ` git push ${r} HEAD:refs/heads/${ref}`).join('\n');
1039
1174
  throw new ScanFailure(
1040
1175
  `this push does not name which of ${remotes.length} remotes it targets (${remotes.join(', ')})`,
1041
- 'name the remote explicitly (`git push <remote> <branch>`). Excluding commits that exist ' +
1042
- 'on ANY remote would let a commit held on a private remote be published to a public one ' +
1043
- 'without ever being scanned — measured, not hypothetical.',
1176
+ 'name the remote — one of these is the command you meant:\n' +
1177
+ `${lines}\n` +
1178
+ 'Excluding commits that exist on ANY remote would let a commit held on a private remote ' +
1179
+ 'be published to a public one without ever being scanned — measured, not hypothetical.',
1044
1180
  );
1045
1181
  }
1046
1182
  }
@@ -65,6 +65,7 @@ import { forJournal, locateJournal } from './evidence-gate.mjs';
65
65
  import { resolveRepoRoot } from './session-start.mjs';
66
66
  import { isUnsupervised, actorOf, stripMessageArguments, MESSAGE_ARGUMENT_RE } from './policy-gate.mjs';
67
67
  import { splitSegments, tokensOf } from './secrets-gate.mjs';
68
+ import { readPlatformUsage, SIDECAR_RELPATH, SIDECAR_FRESH_MS } from '../../scripts/usage-source.mjs';
68
69
  import { PASS, field, main, runGate } from './hook-io.mjs';
69
70
 
70
71
  /** Own budget, below the 8 s hooks.json timeout. All I/O here is small local
@@ -72,10 +73,12 @@ import { PASS, field, main, runGate } from './hook-io.mjs';
72
73
  export const DEADLINE_MS = 4000;
73
74
 
74
75
  export const MARKER_RELPATH = join('.tyran', 'state', 'paused-until.json');
75
- export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
76
76
 
77
- /** Telemetry older than this is unknown, and unknown fails open. */
78
- export const SIDECAR_FRESH_MS = 10 * 60 * 1000;
77
+ // Re-exported rather than re-declared. These had three spellings of the path
78
+ // and two of the window across the writer, the scheduler and this gate —
79
+ // nothing fails while they agree, and when they stop agreeing the symptom is
80
+ // a configured pause that silently never fires. `usage-source.mjs` owns them.
81
+ export { SIDECAR_RELPATH, SIDECAR_FRESH_MS } from '../../scripts/usage-source.mjs';
79
82
 
80
83
  const MAX_SMALL_FILE_BYTES = 64 * 1024;
81
84
  const MAX_CONFIG_BYTES = 256 * 1024;
@@ -123,13 +126,36 @@ export function readLimits(repoRoot) {
123
126
  }
124
127
  }
125
128
 
126
- /** The sidecar, or null when absent/stale/garbage. `nowMs` injected. */
127
- export function readSidecar(repoRoot, nowMs, freshMs = SIDECAR_FRESH_MS) {
129
+ /**
130
+ * The sidecar, or null when absent/stale/garbage. `nowMs` injected.
131
+ *
132
+ * FALLS BACK to the platform's own usage cache in `~/.claude.json` when the
133
+ * sidecar is absent or stale, because on a real machine it is ALWAYS absent:
134
+ * only the statusline writes it, the statusline writes only when the platform
135
+ * payload carries `rate_limits`, and that block is not always sent. Measured
136
+ * on an install running `mode: 'pause'` — no sidecar had ever been written,
137
+ * and the pause had never once been able to fire. The gate fails open, so
138
+ * nothing said so.
139
+ *
140
+ * The statusline stays FIRST when it works: it is session-scoped and refreshed
141
+ * every few seconds, where the platform cache is refreshed on its own schedule
142
+ * and was measured 83 minutes old under continuous use. `platform-usage.mjs`
143
+ * explains why an old reading is still safe to pause on and never safe to
144
+ * resume on; `lower_bound` on the returned document is how that reaches here.
145
+ */
146
+ export function readSidecar(repoRoot, nowMs, freshMs = SIDECAR_FRESH_MS, readPlatform = readPlatformUsage) {
128
147
  const doc = readSmallJson(join(repoRoot, SIDECAR_RELPATH));
129
- if (doc === null) return null;
130
- const writtenAt = Date.parse(typeof doc.written_at === 'string' ? doc.written_at : '');
131
- if (!Number.isFinite(writtenAt) || nowMs - writtenAt > freshMs) return null;
132
- return doc;
148
+ if (doc !== null) {
149
+ const writtenAt = Date.parse(typeof doc.written_at === 'string' ? doc.written_at : '');
150
+ if (Number.isFinite(writtenAt) && nowMs - writtenAt <= freshMs) return doc;
151
+ }
152
+ try {
153
+ return readPlatform({ nowMs });
154
+ } catch {
155
+ // Telemetry is consulted, never depended on. A gate that throws here
156
+ // stops the repository's work over a file it was only reading.
157
+ return null;
158
+ }
133
159
  }
134
160
 
135
161
  function windowOf(doc, key) {
@@ -146,13 +172,17 @@ function windowOf(doc, key) {
146
172
  * refill just hits the weekly wall again.
147
173
  */
148
174
  export function trippedWindow(sidecar, limits) {
175
+ // Carried onto the verdict so the marker can record which channel produced
176
+ // it. A reading from the platform cache is a LOWER BOUND on current usage:
177
+ // enough to stop on, never enough to start on.
178
+ const bound = sidecar?.lower_bound === true;
149
179
  const weekly = windowOf(sidecar, 'seven_day');
150
180
  if (weekly !== null && weekly.used_percentage >= limits.weekly_pause_at_percent) {
151
- return { window: 'seven_day', ...weekly };
181
+ return { window: 'seven_day', lower_bound: bound, ...weekly };
152
182
  }
153
183
  const fiveHour = windowOf(sidecar, 'five_hour');
154
184
  if (fiveHour !== null && fiveHour.used_percentage >= limits.pause_at_percent) {
155
- return { window: 'five_hour', ...fiveHour };
185
+ return { window: 'five_hour', lower_bound: bound, ...fiveHour };
156
186
  }
157
187
  return null;
158
188
  }
@@ -182,7 +212,11 @@ export function markerOf(tripped, limits, nowMs, sessionId, init) {
182
212
  long_wait_policy: limits.long_wait,
183
213
  session_id: typeof sessionId === 'string' && SESSION_ID_RE.test(sessionId) ? sessionId : null,
184
214
  init: init ?? null,
185
- source: 'sidecar',
215
+ // WHICH channel said so, and whether the figure was a lower bound. The
216
+ // scheduler must not treat a bound as a measurement when deciding to
217
+ // RESUME: "at least 97%" is a reason to stop and never a reason to start.
218
+ source: tripped.lower_bound === true ? 'claude.json' : 'sidecar',
219
+ lower_bound: tripped.lower_bound === true,
186
220
  };
187
221
  }
188
222
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
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": {
@@ -1,5 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { FORBIDDEN } from './invisible.mjs';
3
+ // Interpolated into the client script below rather than typed there as a
4
+ // literal. It was a literal `1`, cost.mjs bumped to 2, and the Spend tab
5
+ // started rejecting the very payload its own server was sending — the whole
6
+ // tab replaced by "a format this page does not know". ADR-21 exactly: one
7
+ // answer, one place. No cycle: cost.mjs does not import this file.
8
+ import { COST_SCHEMA } from './cost.mjs';
3
9
  /**
4
10
  * board-html — the one page an operator stares at overnight.
5
11
  *
@@ -185,6 +191,31 @@ pre.how .c{color:var(--muted)}
185
191
  .comp span{display:flex;align-items:center;justify-content:center;font-family:var(--mono);font-size:.63rem;color:var(--bg);font-weight:700;white-space:nowrap;overflow:hidden}
186
192
  .comp .s-cache_read{background:var(--brass)}
187
193
  .comp .s-cache_write{background:var(--steel)}
194
+ /* The 1-hour write is its own segment because it is its own PRICE — 2x base
195
+ input against the 5-minute write's 1.25x. Without a distinct colour the
196
+ most expensive caching decision on the page is invisible. */
197
+ .comp .s-cache_write_1h{background:var(--ink)}
198
+ /* ---- initiatives ---- */
199
+ .inits{display:flex;flex-direction:column;gap:.3rem;margin:.5rem 0}
200
+ .initrow{display:grid;grid-template-columns:minmax(0,1.6fr) 5rem auto minmax(0,1fr);
201
+ gap:.6rem;align-items:center;padding:.35rem .5rem;border-radius:4px}
202
+ /* An initiative nobody can move without the operator is the one thing on this
203
+ section worth catching an eye. */
204
+ .initrow.waiting{background:color-mix(in srgb,var(--brass) 12%,transparent)}
205
+ .initrow .il{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
206
+ .initrow .islug{color:var(--muted);margin-left:.4rem;font-size:.85em}
207
+ .initrow .ib{height:6px;background:var(--line);border-radius:3px;overflow:hidden}
208
+ .initrow .ib i{display:block;height:100%;background:var(--sage)}
209
+ .initrow .iv,.initrow .iw{color:var(--muted);font-size:.9em;white-space:nowrap}
210
+ .initrow .iw.warn{color:var(--brass);font-weight:600}
211
+
212
+ /* ---- the per-day series ---- */
213
+ .days{display:flex;align-items:flex-end;gap:2px;height:74px;margin:.5rem 0 .3rem;
214
+ overflow-x:auto;padding-bottom:2px}
215
+ .day{flex:1 0 6px;min-width:6px;height:100%;display:flex;align-items:flex-end}
216
+ .day i{display:block;width:100%;background:var(--brass);border-radius:1px 1px 0 0}
217
+ /* Outside the chosen window: context, not absence. */
218
+ .day.out i{background:var(--line)}
188
219
  .comp .s-output{background:var(--sage)}
189
220
  .comp .s-input{background:var(--muted)}
190
221
  .compkey{display:flex;flex-wrap:wrap;gap:.85rem;font-family:var(--mono);font-size:.66rem;color:var(--muted);margin-top:.3rem}
@@ -283,6 +314,18 @@ if (data.schema !== 1) {
283
314
  var errors = data.errors || [];
284
315
  var cost = null;
285
316
  var costError = null;
317
+ var spendWindow = '30d';
318
+
319
+ // How the period reads to a person. The window carries machine dates; a
320
+ // reader wants "last 30 days", and for the billing period the actual start
321
+ // date, because that is the number they can check against their invoice.
322
+ var windowLabel = function (payload) {
323
+ var w = payload && payload.window;
324
+ if (!w) return 'all time';
325
+ if (w.name === 'period') return 'this billing period, since ' + w.from;
326
+ if (w.name === '30d') return 'last 30 days';
327
+ return w.from + ' to ' + w.to;
328
+ };
286
329
 
287
330
  // The queue count, in the browser tab. The whole point of this page is that
288
331
  // you can leave it open while agents work overnight, and a background tab
@@ -543,6 +586,59 @@ if (data.schema !== 1) {
543
586
  ov.appendChild(first);
544
587
  }
545
588
 
589
+ // ---- initiatives, and the ones that have stopped moving ----------------
590
+ //
591
+ // MEASURED, and the reason this section exists rather than an archive: of 63
592
+ // real journals, 43 were waiting on a question nobody answered and only 6
593
+ // were finished-and-archivable. The board was not cluttered with completed
594
+ // work; it was full of ABANDONED work, and archiving the finished 6 would
595
+ // have removed the only initiatives at 100% and pulled the headline
596
+ // percentage down.
597
+ //
598
+ // "Waiting" is the initiative's own count of open operator questions. The
599
+ // idle time is computed HERE, from last_ts, because the payload is
600
+ // byte-compared and reads no clock — the same split the agent strip uses.
601
+ var inits = Array.isArray(data.initiatives) ? data.initiatives : [];
602
+ if (inits.length > 0) {
603
+ var stalled = inits.filter(function (i) { return i.waiting > 0; }).sort(function (a, b) {
604
+ return (ageMsOf(b.last_ts) || 0) - (ageMsOf(a.last_ts) || 0);
605
+ });
606
+ ov.appendChild(el('h2', null, 'Initiatives'));
607
+ if (stalled.length > 0) {
608
+ ov.appendChild(el('div', 'hint',
609
+ stalled.length + ' of ' + inits.length + ' are waiting on an answer from you. ' +
610
+ 'Longest-waiting first — an initiative with an open question does not move until it is answered.'));
611
+ }
612
+ var table = el('div', 'inits');
613
+ var ordered = stalled.concat(inits.filter(function (i) { return !(i.waiting > 0); }));
614
+ ordered.forEach(function (i) {
615
+ var row = el('div', i.waiting > 0 ? 'initrow waiting' : 'initrow');
616
+ // The TITLE, which the journal has carried all along while this page
617
+ // showed a directory slug.
618
+ var label = el('div', 'il');
619
+ label.appendChild(el('b', null, i.title || i.name));
620
+ if (i.title) label.appendChild(el('span', 'islug', i.name));
621
+ row.appendChild(label);
622
+ var bar = el('div', 'ib');
623
+ var fill = el('i');
624
+ fill.style.width = (typeof i.percent === 'number' ? i.percent : 0) + '%';
625
+ bar.appendChild(fill);
626
+ row.appendChild(bar);
627
+ var counts = i.merged + '/' + i.tickets + ' merged';
628
+ // Named only when there is something to name. A findings count of zero
629
+ // on every row is noise that teaches the eye to skip the column.
630
+ if (i.findings > 0) counts += ' \u00b7 ' + i.findings + ' finding' + (i.findings === 1 ? '' : 's');
631
+ row.appendChild(el('div', 'iv', counts));
632
+ var age = ageMsOf(i.last_ts);
633
+ row.appendChild(el('div', i.waiting > 0 ? 'iw warn' : 'iw',
634
+ i.waiting > 0
635
+ ? i.waiting + ' waiting on you \u00b7 quiet ' + ago(i.last_ts)
636
+ : (age === null ? '' : 'last moved ' + ago(i.last_ts))));
637
+ table.appendChild(row);
638
+ });
639
+ ov.appendChild(table);
640
+ }
641
+
546
642
  ov.appendChild(el('h2', null, 'Agents'));
547
643
  // Named, not implied by the order: the strip is sorted stalest-first by the
548
644
  // server, and a reader who does not know that reads the first chip as the
@@ -776,6 +872,21 @@ if (data.schema !== 1) {
776
872
  send.setAttribute('type', 'button');
777
873
  var useDefault = hasDefault ? el('button', 'sbtn', 'Take the default') : null;
778
874
  if (useDefault) useDefault.setAttribute('type', 'button');
875
+ // The recommendation was already shown, as TEXT, and the only way to
876
+ // accept it was to retype it into the box below it. For an operator who
877
+ // is not an engineer that gap is most of the difficulty of the whole
878
+ // page: the agent has said what it thinks should happen and the human is
879
+ // asked to transcribe it. This fills the box instead of submitting, so
880
+ // the wording stays editable and the answer is still deliberate.
881
+ var useRec = a.recommendation ? el('button', 'sbtn', 'Use the recommendation') : null;
882
+ if (useRec) {
883
+ useRec.setAttribute('type', 'button');
884
+ useRec.addEventListener('click', function () {
885
+ input.value = a.recommendation;
886
+ input.focus();
887
+ holdRefresh();
888
+ });
889
+ }
779
890
  var status = el('div', 'sstat');
780
891
 
781
892
  var submit = function (text) {
@@ -818,6 +929,7 @@ if (data.schema !== 1) {
818
929
 
819
930
  box.appendChild(input);
820
931
  acts.appendChild(send);
932
+ if (useRec) acts.appendChild(useRec);
821
933
  if (useDefault) acts.appendChild(useDefault);
822
934
  box.appendChild(acts);
823
935
  box.appendChild(status);
@@ -854,6 +966,15 @@ if (data.schema !== 1) {
854
966
  sp.appendChild(spBody);
855
967
  spBody.appendChild(el('div', 'hint', 'Spend is read from the transcripts Claude Code already writes, and it is served rather than embedded — open this board with "board.mjs --serve" to see it. Over file:// there is no server, so this tab stays empty.'));
856
968
 
969
+ // Mirrors compositionLabel in cost.mjs. Restated rather than imported
970
+ // because this file is a browser bundle with no module graph — the two are
971
+ // pinned equal by a test so the drift is caught rather than lived with.
972
+ var compLabel = function (kind) {
973
+ if (kind === 'cache_write') return 'cache write (5 min)';
974
+ if (kind === 'cache_write_1h') return 'cache write (1 hour)';
975
+ return kind.replace(/_/g, ' ');
976
+ };
977
+
857
978
  var chart = function (allRows, key, metric, dimKeys) {
858
979
  var box = el('div', 'chart');
859
980
  // Ranked by the metric on screen, not by the one the server sorted by:
@@ -934,12 +1055,54 @@ if (data.schema !== 1) {
934
1055
  toggle.appendChild(button);
935
1056
  });
936
1057
  header.appendChild(toggle);
1058
+
1059
+ // The period the numbers describe. A plan is billed MONTHLY, so an
1060
+ // all-time total has nothing to compare against; these two windows do.
1061
+ // "this period" is offered only when the subscription date was readable,
1062
+ // because a period guessed from an assumed anniversary is wrong for
1063
+ // almost everyone.
1064
+ var periods = [['30d', 'last 30 days'], ['all', 'all time']];
1065
+ if (cost.subscription && cost.subscription.created_at) {
1066
+ periods.splice(1, 0, ['period', 'this billing period']);
1067
+ }
1068
+ var picker = el('div', 'toggle');
1069
+ periods.forEach(function (pair) {
1070
+ var button = el('button', null, pair[1]);
1071
+ button.setAttribute('type', 'button');
1072
+ button.setAttribute('aria-pressed', spendWindow === pair[0] ? 'true' : 'false');
1073
+ button.addEventListener('click', function () { loadCost(pair[0], metric); });
1074
+ picker.appendChild(button);
1075
+ });
1076
+ header.appendChild(picker);
937
1077
  into.appendChild(header);
938
1078
 
939
1079
  var tiles = el('div', 'tiles');
940
1080
  tiles.appendChild(tile('tokens', fmtTokens(t.tokens || 0), (t.requests || 0) + ' requests'));
941
1081
  tiles.appendChild(tile('cost through the API', fmtUsd(t.usd),
942
1082
  cost.rate_card ? 'rate card ' + cost.rate_card : 'no rate card set', 'lead'));
1083
+ // What the API-equivalent figure is actually WORTH knowing against. On a
1084
+ // subscription the marginal cost of a token is zero, so the dollar total
1085
+ // above is true of the API and false of the operator's bank account —
1086
+ // shown alone it invites exactly the wrong conclusion. Rendered only when
1087
+ // the plan is known; a guess here would be worse than the silence.
1088
+ var w = cost.window;
1089
+ var sub = cost.subscription;
1090
+ if (sub && typeof sub.monthly_usd === 'number') {
1091
+ // The multiple is shown ONLY under a month-shaped window. Against an
1092
+ // all-time total it would be off by however long this machine has been
1093
+ // running Claude Code — measured at 6.9x when the honest figure was
1094
+ // about 11x — so under "all time" the tile states the span and stops.
1095
+ var monthly = w && (w.name === '30d' || w.name === 'period') && typeof t.usd === 'number';
1096
+ var note = sub.label;
1097
+ if (monthly && sub.monthly_usd > 0) {
1098
+ note += ' — the API cost of ' + windowLabel(cost) + ' is ' +
1099
+ (t.usd / sub.monthly_usd).toFixed(1) + 'x that';
1100
+ } else if (cost.covers && cost.covers.days) {
1101
+ note += ' — the total above covers ' + cost.covers.days +
1102
+ ' day' + (cost.covers.days === 1 ? '' : 's');
1103
+ }
1104
+ tiles.appendChild(tile('you pay', fmtUsd(sub.monthly_usd) + '/mo', note, 'lead'));
1105
+ }
943
1106
  tiles.appendChild(tile('conductor overhead', (t.conductor_token_share || 0) + '%', 'of tokens, no ticket'));
944
1107
  tiles.appendChild(tile('attributed', (cov.attributed || 0) + ' / ' + (cov.agent_transcripts || 0),
945
1108
  (cov.unattributed || 0) + ' agent(s) without a ticket'));
@@ -967,13 +1130,47 @@ if (data.schema !== 1) {
967
1130
  var legend = el('span', null);
968
1131
  legend.appendChild(el('i', 's-' + c.kind));
969
1132
  legend.appendChild(el('span', null,
970
- c.kind.replace('_', ' ') + ' ' + (metric === 'usd' ? fmtUsd(c.usd) : fmtTokens(c.tokens))));
1133
+ compLabel(c.kind) + ' ' + (metric === 'usd' ? fmtUsd(c.usd) : fmtTokens(c.tokens))));
971
1134
  key.appendChild(legend);
972
1135
  });
973
1136
  into.appendChild(bar);
974
1137
  into.appendChild(key);
975
1138
  }
976
1139
 
1140
+ // The series. Every other view on this tab is a snapshot, so nothing has
1141
+ // ever been able to answer "am I getting cheaper" — the single question a
1142
+ // spend page exists for. Always the FULL history regardless of the window:
1143
+ // a chart that shrank with the window could not show you that last month
1144
+ // was worse, which is the comparison worth having.
1145
+ var series = cost.per_day || [];
1146
+ if (series.length > 1) {
1147
+ into.appendChild(el('h3', null, 'By day'));
1148
+ var peak = 0;
1149
+ series.forEach(function (d) {
1150
+ var v = metric === 'usd' ? (d.usd || 0) : d.tokens;
1151
+ if (v > peak) peak = v;
1152
+ });
1153
+ var days = el('div', 'days');
1154
+ series.forEach(function (d) {
1155
+ var value = metric === 'usd' ? (d.usd || 0) : d.tokens;
1156
+ var col = el('div', 'day');
1157
+ var bar = el('i');
1158
+ bar.style.height = (peak > 0 ? Math.max(2, (value / peak) * 100) : 0) + '%';
1159
+ // Inside the window is the emphasis; outside it is context, not
1160
+ // absence — the days either side are exactly what makes the window
1161
+ // legible as a choice.
1162
+ if (w && (d.day < w.from || d.day > w.to)) col.className = 'day out';
1163
+ col.appendChild(bar);
1164
+ col.setAttribute('title', d.day + ' \u2014 ' + fmtTokens(d.tokens) + ' tokens' +
1165
+ (typeof d.usd === 'number' ? ' \u00b7 ' + fmtUsd(d.usd) : ''));
1166
+ days.appendChild(col);
1167
+ });
1168
+ into.appendChild(days);
1169
+ into.appendChild(el('div', 'hint',
1170
+ series[0].day + ' to ' + series[series.length - 1].day + ' \u00b7 ' +
1171
+ series.length + ' day(s) with recorded activity \u00b7 hover a bar for its total'));
1172
+ }
1173
+
977
1174
  [['By model', cost.by_model || [], 'model', []],
978
1175
  ['By agent type', cost.by_agent_type || [], 'agent_type', ['conductor']],
979
1176
  ['By ticket', cost.by_ticket || [], 'ticket', ['conductor', 'unattributed']]].forEach(function (spec) {
@@ -1030,8 +1227,13 @@ if (data.schema !== 1) {
1030
1227
  clear(spBody);
1031
1228
  spBody.appendChild(el('div', 'err', why));
1032
1229
  };
1033
- if (typeof fetch === 'function') {
1034
- fetch('cost.json', { headers: { accept: 'application/json' } })
1230
+ // Re-fetches with a chosen window. The server recomputes rather than the
1231
+ // page filtering, because only the server has the per-day buckets and a
1232
+ // page that filtered a total it was handed could only ever subtract wrong.
1233
+ var loadCost = function (window, metric) {
1234
+ if (typeof fetch !== 'function') return;
1235
+ spendWindow = window;
1236
+ fetch('cost.json?window=' + encodeURIComponent(window), { headers: { accept: 'application/json' } })
1035
1237
  .then(function (r) {
1036
1238
  // 404 is not a failure, it is an ANSWER: no such route, so this page
1037
1239
  // is not being served by the board server — a copy on a docs site, a
@@ -1050,7 +1252,7 @@ if (data.schema !== 1) {
1050
1252
  showCostFailure('Spend could not be read: ' + ((payload && payload.error) || 'the server refused the request') + '.');
1051
1253
  return;
1052
1254
  }
1053
- if (!payload || payload.schema !== 1) {
1255
+ if (!payload || payload.schema !== ${COST_SCHEMA}) {
1054
1256
  showCostFailure('Spend was served in a format this page does not know (schema ' +
1055
1257
  ((payload && payload.schema) || 'absent') + ') — regenerate the board with the Tyran that served it.');
1056
1258
  return;
@@ -1071,11 +1273,14 @@ if (data.schema !== 1) {
1071
1273
  return;
1072
1274
  }
1073
1275
  cost = payload;
1074
- renderSpend(spBody, 'tokens');
1276
+ renderSpend(spBody, metric || 'tokens');
1075
1277
  var t = cost.totals || {};
1278
+ // CLEARED first: this runs again on every window change, and appending
1279
+ // left one "Spend" heading and one tile stacked up per click.
1280
+ clear(ovSpend);
1076
1281
  var strip = el('div', 'tiles');
1077
1282
  strip.appendChild(tile('spend so far', fmtUsd(t.usd),
1078
- fmtTokens(t.tokens || 0) + ' tokens · see the Spend tab'));
1283
+ fmtTokens(t.tokens || 0) + ' tokens · ' + windowLabel(cost) + ' · see the Spend tab'));
1079
1284
  ovSpend.appendChild(el('h2', null, 'Spend'));
1080
1285
  ovSpend.appendChild(strip);
1081
1286
  })
@@ -1085,7 +1290,12 @@ if (data.schema !== 1) {
1085
1290
  if (String(location.protocol) === 'file:') return;
1086
1291
  showCostFailure('Spend could not be read: the board server did not answer. It is served, never embedded — start it with: npx @jjanczur/tyran board --dir .tyran --serve');
1087
1292
  });
1088
- }
1293
+ };
1294
+
1295
+ // The DEFAULT is 30 days, not all time: a plan is billed monthly, so a
1296
+ // month-shaped window is the only one an operator can compare against the
1297
+ // price without doing arithmetic. All time remains one click away.
1298
+ loadCost('30d', 'tokens');
1089
1299
 
1090
1300
  // ---- settings ---------------------------------------------------------
1091
1301
  //