@jjanczur/tyran 0.1.28 → 0.1.30

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.28",
14
+ "version": "0.1.30",
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.28",
3
+ "version": "0.1.30",
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,126 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.30 — 2026-08-17
4
+
5
+ The first release built on an outside contribution. It fixes a spend ledger
6
+ that was confidently reporting the wrong session, and it is also the release
7
+ where the "change both surfaces" rule caught itself being broken.
8
+
9
+ ### Spend, when the conductor ran from somewhere else
10
+
11
+ Measured on a real run: a Claude Code Desktop session operated on a repo
12
+ through absolute paths and worktrees, but was itself started in a sibling
13
+ folder. `cost.mjs` derives a transcript directory from the repo path and falls
14
+ back to scanning every project directory for a `cwd` match — both assume the
15
+ conductor ran *from* the repo, and neither one held here. A different,
16
+ unrelated `claude` run had once been started inside the repo (for the trust
17
+ dialog), so the direct lookup found a directory and stopped there. The board's
18
+ Spend tab rendered that unrelated session — 17 requests, one model, "0 agents
19
+ attributed", conductor overhead 100% — as if it were the whole initiative,
20
+ with nothing on the page saying that ~66 agent transcripts and 2 300 requests
21
+ were sitting elsewhere.
22
+
23
+ Two operator-named overrides, both resolved by `cost.mjs` itself so
24
+ `board.mjs --serve` gets them for free: a repeatable `--transcripts <dir>` on
25
+ the command line, and `spend.transcript_dirs` in `.tyran/config.yaml`. Either
26
+ replaces the derived-slug / cwd-probe resolution outright; a given directory
27
+ that does not exist is reported in the new `transcript_dirs_missing` field
28
+ rather than dropped. The Spend tab now shows a hint — pointing at both
29
+ overrides — whenever it finds zero agent transcripts while the board itself
30
+ lists running agents, which is the shape this failure actually has: a tab that
31
+ renders, with honest numbers about the wrong session.
32
+
33
+ Contributed by [@FreddyFormosa](https://github.com/FreddyFormosa) in
34
+ [#66](https://github.com/jjanczur/tyran/pull/66), found on a 14-ticket
35
+ production run — the failure above is his measurement, not a constructed one.
36
+
37
+ ### The half of "change both, always" that got left out
38
+
39
+ That contribution updated `docs/board.md`, `docs/configuration.md` and
40
+ `docs/cost.md` and left `board.mdx`, `configuration.mdx` and `cost.mdx`
41
+ untouched, which is precisely the divergence `CLAUDE.md` names — "docs/*.md
42
+ and site/src/content/docs/*.mdx publish the same claims. Change both, always."
43
+ All three pages are now mirrored, cross-links rewritten relative
44
+ (`../cost/#when-resolution-fails`) so the Pages build keeps its `/tyran` base
45
+ prefix.
46
+
47
+ Worth naming because of *how* it was caught: not by review, but by CI going
48
+ red on a different claim entirely. The README said 1405 unit tests and the
49
+ suite had 1417, and that check lives in the workflow rather than in the suite
50
+ — no test inside the suite can run the suite — so `node --test` reported green
51
+ locally right up to the point the pull request was opened. The number is now
52
+ 1417, measured rather than typed. The .mdx gap was found while fixing it.
53
+
54
+ ## 0.1.29 — 2026-08-16
55
+
56
+ Tyran has videos. Five cuts, and a page that says which one to send.
57
+
58
+ ### The slate
59
+
60
+ A 3:20 explainer, a 3:53 first-session tutorial, and three vertical shorts —
61
+ the mistake, the board, the retrospective. Built with Hyperframes (HTML in,
62
+ deterministic MP4 out) and a Gemini voiceover, with burned-in captions and an
63
+ `.srt` sidecar each.
64
+
65
+ They are not five lengths of one video, which is the point of
66
+ [`docs/videos.md`](docs/videos.md): each answers a different question, and the
67
+ shorts and the tutorial fail at each other's jobs. The explainer argues, the
68
+ tutorial instructs, the board short shows rather than argues, and the retro
69
+ short is the only one whose subject is restraint.
70
+
71
+ ### The written surfaces now say what the video says
72
+
73
+ The README and the landing hero were accurate and abstract where the explainer
74
+ is concrete. Both now open on the same sentence it does — your most expensive
75
+ model renaming a variable in the same chat it judged an authentication
76
+ boundary — and carry the manager framing through to the board, the bill and the
77
+ retro. Two descriptions of one product drifting apart is the defect this repo
78
+ calls ADR-21, and the video is now the widest-reach description of Tyran, so it
79
+ is the one the prose should agree with.
80
+
81
+ ### The claims in the explainer, checked against the code
82
+
83
+ Every spoken claim was audited (`NOTES-REQUESTS.md` §10). Nine are exact, and
84
+ several turn out to be near-verbatim quotes of the mechanism's own
85
+ documentation: the four-question interview batch, the reviewer that ships with
86
+ no editing tools, the role floor applied after both the risk shift and the
87
+ override, and the three-to-knowledge / five-to-law ladder.
88
+
89
+ Two are not, and are recorded rather than quietly left:
90
+
91
+ - **"cheap tier, read only"** — the scout is granted `Bash`. *"You change
92
+ nothing"* is the first line of its instructions, which is the one form of
93
+ guarantee this project refuses to accept anywhere else. The fix is a
94
+ read-only agent class in the policy gate, not a rewording.
95
+ - **"this is not an estimate, it is the bill"** — the figures are exactly what
96
+ the sandbox board shows (404 requests, 4.53M tokens, 54.9% conductor) and the
97
+ rollup computing them is the real one, but the usage feeding it is authored,
98
+ and the board honestly labels those models `sample-large` / `sample-small`.
99
+ Publishing a real `cost.json` into the sandbox makes the line true and makes
100
+ the sandbox a better artefact than the video.
101
+
102
+ ### What is in the repository, and what is not
103
+
104
+ The video *sources* are tracked — compositions, the voiceover pipeline, the
105
+ scripts, the storyboards — because they are text and they are how a cut gets
106
+ rebuilt. The renders are not. They come to roughly 430 MB, and this repository
107
+ is what `/plugin marketplace add jjanczur/tyran` clones, so committing them
108
+ would put marketing video into every install of the plugin. Git LFS was
109
+ considered and rejected on the same ground: a clone without `git-lfs` gets
110
+ pointer files, which breaks both the Pages build and the install.
111
+
112
+ `assets/video/` carries 1.1 MB of poster frames and caption sidecars, which is
113
+ everything the README and the docs page actually reference. The cuts live on
114
+ YouTube, and their IDs live in exactly one file,
115
+ `site/src/data/videos.json`.
116
+
117
+ Tyran's own secrets gate refused the first attempt at that commit — the payload
118
+ was past the 4 MiB it can scan inside its budget, and it refuses rather than
119
+ scanning a prefix, because a partial scan that reports nothing looks exactly
120
+ like a clean one. That is the gate behaving as designed, and it is what forced
121
+ the question of which bytes really needed to be in the tree. Two MP4s turned
122
+ out to be referenced by nothing.
123
+
3
124
  ## 0.1.28 — 2026-08-15
4
125
 
5
126
  A maintenance release: the documentation site's dependencies, and three
package/README.md CHANGED
@@ -14,6 +14,7 @@
14
14
  <p align="center">
15
15
  <b><a href="https://jjanczur.github.io/tyran/">📖 Documentation</a></b> ·
16
16
  <a href="https://jjanczur.github.io/tyran/getting-started/">Getting started</a> ·
17
+ <a href="https://jjanczur.github.io/tyran/videos/">Videos</a> ·
17
18
  <a href="https://jjanczur.github.io/tyran/architecture/">Architecture</a> ·
18
19
  <a href="https://github.com/jjanczur/tyran/releases/latest">Releases</a>
19
20
  </p>
@@ -22,41 +23,53 @@
22
23
 
23
24
  ## What Tyran is
24
25
 
25
- Every long Claude Code session ends the same way. The context fills up, the
26
- plan is somewhere in the scrollback, and *"the tests pass"* is a sentence
27
- rather than something you can check. Start a new session and you start
28
- explaining from the beginning.
26
+ Your most expensive model just renamed a variable. In the same chat, it judged
27
+ an authentication boundary.
29
28
 
30
- Tyran is an orchestrator. You describe a task; it interviews you until the goal
31
- is unambiguous, sizes it, plans it, and hands each piece to a **dedicated
32
- subagent with fresh context and a model tier matched to how hard that piece
33
- actually is** — cheap for a mechanical sweep, expensive for a security
34
- boundary, never one model for a whole session. They run in parallel, as an
35
- Agent Team where the platform offers one.
29
+ One chat, one model, every job — that is why the bill is high and the work gets
30
+ worse. The context fills up, the plan is somewhere in the scrollback, and
31
+ *"the tests pass"* is a sentence rather than something you can check.
32
+
33
+ **You didn't install a tool. You hired a manager.** You describe the work once;
34
+ he interviews you until the goal is unambiguous — batches of at most four
35
+ questions, each with his recommendation — turns the plan into tickets on a
36
+ board, and hands each piece to a **dedicated subagent with fresh context and a
37
+ model tier matched to how hard that piece actually is.** A good manager doesn't
38
+ put a principal engineer on a grep: a scout reads the repo on the cheap tier,
39
+ implementers take one story each on their own branch, the reviewer has no
40
+ editing tools at all, and security review always gets the strongest tier — a
41
+ floor no cost profile or flag can lower.
36
42
 
37
43
  That is a cost lever and a quality lever at the same time. The conductor holds
38
44
  the plan and never accumulates its agents' transcripts, which is where the
39
45
  tokens in a long session actually go; and an agent that never saw the last six
40
46
  failed attempts cannot inherit them, so the second opinion is a real one.
41
47
 
48
+ **Nothing you say is lost.** Remember something halfway through a run and say
49
+ it — it doesn't land in the scrollback, it becomes a ticket. Every decision,
50
+ spawn, report, merge and open question is appended to a journal **committed to
51
+ your repo**, so a restart, a compaction and a colleague on another branch all
52
+ read the same thing.
53
+
42
54
  **It learns your repo while it works.** Setup reads how the repo is really
43
55
  worked — stack, validation commands, how things get deployed — rather than
44
- asking you to describe it. A retrospective after every initiative writes what
45
- it learnt into `.tyran/knowledge/`, and a failure that repeats graduates out of
46
- `MISTAKES.md` into a rule. Meanwhile every decision, spawn, report, merge and
47
- open question is appended to a journal **committed to your repo**, so a
48
- restart, a compaction and a colleague on another branch all read the same
49
- thing.
50
-
51
- All of it is one plugin, and it comes with a **dashboard**: what every agent is
52
- doing right now, which questions are waiting on you, and what the work cost —
53
- in the tokens the platform itself reported, per model, per agent and per
54
- ticket.
55
-
56
- Underneath, **deterministic hooks hold the line**: a report with no raw command
57
- output is rejected, every write is classified against a policy file you own
58
- before it happens, and a commit carrying a secret is refused. Mechanisms rather
59
- than instructions — which is the whole argument.
56
+ asking you to describe it. After every initiative the team runs a retrospective
57
+ on itself, and what it changes is Tyran, never your product code. The same
58
+ failure three times becomes knowledge pasted into every matching handoff; five
59
+ times and it becomes a rule in your `CLAUDE.md`, carrying the dates that earned
60
+ it. Most retros correctly change nothing.
61
+
62
+ All of it lands on one page — a **board**: what every agent is doing right now,
63
+ which questions are waiting on you (answer them there and the run carries on),
64
+ and what the work cost, in the tokens the platform itself reported, per model,
65
+ per agent and per ticket. The conductor gets its own row, so its overhead never
66
+ hides inside the total.
67
+
68
+ Underneath, **a hook decides before the tool ever runs** — none of this is a
69
+ prompt asking nicely. A report with no raw command output is refused: it blocks
70
+ silence, not forgery. Every write is classified against a policy file you own.
71
+ And a commit carrying a secret is refused, even inside a markdown file.
72
+ Mechanisms rather than instructions — which is the whole argument.
60
73
 
61
74
  <p align="center">
62
75
  <img src="assets/board-demo.gif" width="100%" alt="The Tyran dashboard, recorded live, moving through four of its tabs: Overview with what is waiting on you and the strip of running agents each showing the time since it last signalled; Board, where selecting a ticket opens its initiative, agents and spend; Waiting on you, the open questions above the commands that answer them; and Spend, toggling the same split between tokens and cost">
@@ -68,6 +81,31 @@ than instructions — which is the whole argument.
68
81
  lanes, select a card.
69
82
  </p>
70
83
 
84
+ ### Watch it
85
+
86
+ <table>
87
+ <tr>
88
+ <td width="50%" align="center">
89
+ <a href="https://youtu.be/ThulYtbYNXI"><img src="assets/video/a-explainer-16x9.jpg" width="100%" alt="Still from the Tyran explainer: the routing table, with each role resolving to a model tier"></a><br>
90
+ <b><a href="https://youtu.be/ThulYtbYNXI">You Didn't Install a Tool — You Hired a Manager</a></b><br>
91
+ 3:20 · the whole argument, end to end
92
+ </td>
93
+ <td width="50%" align="center">
94
+ <a href="https://youtu.be/vr49hKk9G8g"><img src="assets/video/a-onboarding-16x9.jpg" width="100%" alt="Still from the Tyran onboarding video: the install commands typed into a terminal"></a><br>
95
+ <b><a href="https://youtu.be/vr49hKk9G8g">Your First Session</a></b><br>
96
+ 3:53 · install, run, read the board
97
+ </td>
98
+ </tr>
99
+ </table>
100
+
101
+ <p align="center">
102
+ Three 60-second cuts too —
103
+ <a href="https://www.youtube.com/shorts/2EgRBR0fVRo">the mistake</a> ·
104
+ <a href="https://www.youtube.com/shorts/HKePDLkYDqA">the board</a> ·
105
+ <a href="https://www.youtube.com/shorts/EMcPJj7c0mk">the retro</a> —
106
+ and <a href="https://jjanczur.github.io/tyran/videos/">which to send when</a>.
107
+ </p>
108
+
71
109
  ## What it gives you
72
110
 
73
111
  - **Reports that carry evidence, or are refused.** A `SubagentStop` hook
@@ -259,7 +297,7 @@ enforces the cap (4352 of 5000 characters). What each one assumes, when it
259
297
  fires and who invokes it, is in
260
298
  [skills and agents](https://jjanczur.github.io/tyran/skills/); the prompts
261
299
  themselves are in [`skills/`](skills/) and [`agents/`](agents/). Behind all of
262
- it: 1405 unit tests, run with `node --test "tests/**/*.test.mjs"`.
300
+ it: 1417 unit tests, run with `node --test "tests/**/*.test.mjs"`.
263
301
 
264
302
  ## Documentation
265
303
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.28",
3
+ "version": "0.1.30",
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": {
@@ -858,6 +858,37 @@ if (data.schema !== 1) {
858
858
  return box;
859
859
  };
860
860
 
861
+ // A PURE function on purpose: no DOM, so a test can extract this one
862
+ // function's source out of the page and evaluate it standalone, without a
863
+ // browser, and check what it decides for a payload it never had to fetch.
864
+ //
865
+ // Two callers, one decision. renderSpend calls this once spend loaded
866
+ // normally; the cost-fetch handler below calls it BEFORE the early return
867
+ // on a payload with transcripts_found false — a directory named in
868
+ // transcript_dirs_missing is exactly as real a fact when nothing was
869
+ // found at all as when something was, and a single function neither call
870
+ // site can restate differently is what keeps that true.
871
+ var spendResolutionHints = function (payload) {
872
+ var hints = [];
873
+ var missing = (payload && payload.transcript_dirs_missing) || [];
874
+ if (missing.length > 0) {
875
+ var noun = missing.length === 1 ? 'directory' : 'directories';
876
+ hints.push('Given transcript ' + noun + ' not found: ' + missing.join(', ') + '.');
877
+ }
878
+ // Only on the branch that never reaches renderSpend at all: when spend
879
+ // WAS found, "no transcripts" would be false and misleading — the tab
880
+ // renders its own numbers and, if it turns out zero agents were among
881
+ // them, the separate agents-vs-coverage hint inside renderSpend covers it.
882
+ if (payload && payload.transcripts_found === false) {
883
+ hints.push(
884
+ 'No transcripts found for this repo. If the conductor ran from another working directory, ' +
885
+ 'point the board at that session: board.mjs --serve --transcripts <dir> or set ' +
886
+ 'spend.transcript_dirs in .tyran/config.yaml.'
887
+ );
888
+ }
889
+ return hints;
890
+ };
891
+
861
892
  var renderSpend = function (into, metric) {
862
893
  clear(into);
863
894
  var t = cost.totals || {};
@@ -932,6 +963,27 @@ if (data.schema !== 1) {
932
963
  ' oversized record(s) were skipped; their tokens are missing from every figure here.');
933
964
  }
934
965
  into.appendChild(el('div', 'caveat', notes.join(' ')));
966
+
967
+ // Zero agent transcripts while the board itself lists agents is not "no
968
+ // agents ran" — it is the resolved directory being the WRONG one. A
969
+ // conductor session started from a working directory other than the repo
970
+ // it operates on files its transcript under a project directory no
971
+ // derivation from the repo path reaches, and this is the one place an
972
+ // operator would otherwise have no reason to suspect it: the tab renders,
973
+ // the totals are honest numbers, and they are honest numbers about the
974
+ // wrong session.
975
+ if ((cov.agent_transcripts || 0) === 0 && agents.length > 0) {
976
+ into.appendChild(el('div', 'hint',
977
+ 'No agent transcripts found where this repo\\u2019s transcripts are expected. If the conductor ' +
978
+ 'ran from another working directory, point the board at that session: board.mjs --serve ' +
979
+ '--transcripts <dir> or set spend.transcript_dirs in .tyran/config.yaml.'));
980
+ }
981
+ // cost.transcripts_found is true whenever this function runs at all, so
982
+ // spendResolutionHints only ever contributes the missing-dirs line here
983
+ // — the "no transcripts found" line is reachable exclusively through the
984
+ // fetch handler's own call below, on the branch that never reaches this
985
+ // function.
986
+ spendResolutionHints(cost).forEach(function (h) { into.appendChild(el('div', 'hint', h)); });
935
987
  };
936
988
 
937
989
  // Spend is FETCHED, never embedded: it is derived from transcripts under
@@ -973,7 +1025,21 @@ if (data.schema !== 1) {
973
1025
  ((payload && payload.schema) || 'absent') + ') — regenerate the board with the Tyran that served it.');
974
1026
  return;
975
1027
  }
976
- if (!payload.transcripts_found) return; // genuinely nothing to show
1028
+ if (!payload.transcripts_found) {
1029
+ // Genuinely nothing to roll up — but the explanation still has to
1030
+ // reach the page. This used to be a silent early return that left
1031
+ // spBody carrying the "open with --serve" hint written before the
1032
+ // fetch even started, unconditionally wrong once the fetch answers:
1033
+ // it made the everyday single-typo spend.transcript_dirs case
1034
+ // (payload carries transcript_dirs_missing but no coverage at all,
1035
+ // since renderSpend — the only other place that hint used to live
1036
+ // — never runs on this branch) look exactly like a repo that had
1037
+ // never been served at all. Reviewed and reproduced live via
1038
+ // cost.json before this fix.
1039
+ clear(spBody);
1040
+ spendResolutionHints(payload).forEach(function (h) { spBody.appendChild(el('div', 'hint', h)); });
1041
+ return;
1042
+ }
977
1043
  cost = payload;
978
1044
  renderSpend(spBody, 'tokens');
979
1045
  var t = cost.totals || {};
package/scripts/board.mjs CHANGED
@@ -20,7 +20,8 @@
20
20
  * initiative reads as "all is well" exactly when it is not.
21
21
  *
22
22
  * CLI:
23
- * node board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>] [--write]]
23
+ * node board.mjs [--dir <.tyran>] [--check]
24
+ * [--serve [--port <n>] [--write] [--transcripts <dir>]...]
24
25
  * Exit: 0 ok · 1 drift (--check) · 2 usage/IO
25
26
  */
26
27
  import { existsSync, readdirSync, statSync, readFileSync } from 'node:fs';
@@ -561,9 +562,12 @@ function handleSettingsWrite(dir, route, body) {
561
562
 
562
563
  const BOOLEAN_FLAGS = ['check', 'serve', 'write'];
563
564
  const VALUE_FLAGS = ['dir', 'port'];
565
+ // Repeatable, unlike VALUE_FLAGS: sources are the union over every directory
566
+ // given, exactly like cost.mjs's own `--transcripts`.
567
+ const REPEATABLE_FLAGS = ['transcripts'];
564
568
 
565
569
  function parseArgs(argv) {
566
- const flags = { dir: '.tyran', port: 4173, check: false, serve: false, write: false };
570
+ const flags = { dir: '.tyran', port: 4173, check: false, serve: false, write: false, transcripts: [] };
567
571
  for (let i = 0; i < argv.length; i += 1) {
568
572
  const arg = argv[i];
569
573
  if (!arg.startsWith('--')) throw new UsageError(`unexpected argument "${arg}"`);
@@ -574,6 +578,11 @@ function parseArgs(argv) {
574
578
  if (value === undefined) throw new UsageError(`flag --${name} needs a value`);
575
579
  flags[name] = name === 'port' ? Number(value) : value;
576
580
  i += 1;
581
+ } else if (REPEATABLE_FLAGS.includes(name)) {
582
+ const value = argv[i + 1];
583
+ if (value === undefined) throw new UsageError(`flag --${name} needs a value`);
584
+ flags[name].push(value);
585
+ i += 1;
577
586
  } else throw new UsageError(`unknown flag --${name}`);
578
587
  }
579
588
  if (!Number.isInteger(flags.port) || flags.port <= 0 || flags.port > 65535) {
@@ -589,13 +598,23 @@ function main() {
589
598
  } catch (err) {
590
599
  if (!(err instanceof UsageError)) throw err;
591
600
  console.error(`board: ${err.message}`);
592
- console.error('usage: board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>] [--write]]');
601
+ console.error(
602
+ 'usage: board.mjs [--dir <.tyran>] [--check] ' +
603
+ '[--serve [--port <n>] [--write] [--transcripts <dir>]...]'
604
+ );
593
605
  process.exit(2);
594
606
  }
595
607
  if (flags.write && !flags.serve) {
596
608
  console.error('board: --write only means anything with --serve (it is what the served page may edit)');
597
609
  process.exit(2);
598
610
  }
611
+ if (flags.transcripts.length > 0 && !flags.serve) {
612
+ console.error(
613
+ 'board: --transcripts only means anything with --serve (it is what /cost.json reads instead of ' +
614
+ 'the derived transcript directory)'
615
+ );
616
+ process.exit(2);
617
+ }
599
618
  const dir = resolve(flags.dir);
600
619
  if (!existsSync(dir)) {
601
620
  console.error(`board: no such directory ${dir}`);
@@ -717,7 +736,11 @@ function main() {
717
736
  if (req.url === '/cost.json') {
718
737
  let body;
719
738
  try {
720
- body = costJson(costReport({ tyranDir: dir }));
739
+ // `flags.transcripts` is [] unless the operator started this
740
+ // server with `--transcripts`; costReport falls through to
741
+ // `spend.transcript_dirs` and then the derived directory on its
742
+ // own, so an empty array here changes nothing for the common case.
743
+ body = costJson(costReport({ tyranDir: dir, transcriptDirs: flags.transcripts }));
721
744
  } catch (err) {
722
745
  // A cost failure must never take the board down with it: the
723
746
  // board answers "what is going on", and that answer does not
package/scripts/cost.mjs CHANGED
@@ -35,6 +35,7 @@
35
35
  *
36
36
  * CLI:
37
37
  * node cost.mjs [--dir <.tyran>] [--session <id>] [--json] [--projects <dir>]
38
+ * [--transcripts <dir>]...
38
39
  * Exit: 0 ok · 2 usage/IO
39
40
  */
40
41
  import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
@@ -345,6 +346,64 @@ function findTranscriptDir(want, projectsRoot) {
345
346
  return null;
346
347
  }
347
348
 
349
+ /**
350
+ * Where BOTH `transcriptDirFor` heuristics fail: a conductor session started
351
+ * from a working directory OTHER than the repo it operates on — Claude Code
352
+ * Desktop opened in a sibling folder, working the repo through absolute paths
353
+ * and worktrees. The computed slug does not match (it is derived from the
354
+ * conductor's own cwd, not the repo path), and the cwd probe does not match
355
+ * either (every record in that transcript carries the CONDUCTOR's cwd, never
356
+ * the repo's). Measured: a `claude` run once started inside the repo for the
357
+ * trust dialog left a directory the direct lookup matched and stopped at,
358
+ * while ~66 agent transcripts and 2 300 requests sat under the conductor's
359
+ * real project dir with nothing on the board pointing at them.
360
+ *
361
+ * A leading `~` expanded to the home directory — the same narrow rule
362
+ * `main_writable_paths` uses in `config.yaml`, so a transcript dir is written
363
+ * the way an operator already writes every other out-of-repo path in this
364
+ * file.
365
+ */
366
+ function expandHome(p) {
367
+ if (p === '~') return homedir();
368
+ if (p.startsWith('~/')) return join(homedir(), p.slice(2));
369
+ return p;
370
+ }
371
+
372
+ /**
373
+ * The parsed `.tyran/config.yaml`, or null when it is absent or will not
374
+ * parse. Shared by every config-driven reader below (pricing, the transcript
375
+ * override) so there is one place that opens and parses the file, not two
376
+ * loaders that quietly drift apart.
377
+ */
378
+ function loadConfigDoc(tyranDir) {
379
+ try {
380
+ return parse(readFileSync(join(tyranDir, 'config.yaml'), 'utf8'));
381
+ } catch {
382
+ return null;
383
+ }
384
+ }
385
+
386
+ /**
387
+ * `spend.transcript_dirs` out of an ALREADY-PARSED config doc — the middle
388
+ * tier of the transcript-dir precedence (CLI `--transcripts` > this > the
389
+ * derived-slug / cwd-probe fallback above). Operator-written, never
390
+ * scanner-inferred, exactly like `pricing:` and `limits:`: a doc that carries
391
+ * nothing here simply falls through to the fallback, same as an absent block.
392
+ *
393
+ * Takes the parsed doc rather than `tyranDir` so `costReport` can read
394
+ * `config.yaml` once and hand the same doc to this and to `pricingOf` —
395
+ * two readers opening and parsing the same file on every call was the
396
+ * reviewed nit this signature exists to close.
397
+ */
398
+ function spendTranscriptDirsOf(doc) {
399
+ const spend = doc !== null && typeof doc === 'object' ? doc.spend : undefined;
400
+ const list =
401
+ spend !== null && typeof spend === 'object' && Array.isArray(spend.transcript_dirs)
402
+ ? spend.transcript_dirs
403
+ : [];
404
+ return list.filter((d) => typeof d === 'string' && d.trim() !== '');
405
+ }
406
+
348
407
  /** Every transcript belonging to this repo: the sessions and their agents. */
349
408
  export function listSources(transcriptDir, sessionFilter) {
350
409
  const out = [];
@@ -644,6 +703,10 @@ export function renderReport(report) {
644
703
  if (report.unpriced.length > 0) {
645
704
  out.push(`Unpriced models (counted in tokens, absent from every amount): ${report.unpriced.join(', ')}`);
646
705
  }
706
+ if ((report.transcript_dirs_missing ?? []).length > 0) {
707
+ const noun = report.transcript_dirs_missing.length === 1 ? 'directory' : 'directories';
708
+ out.push(`Given transcript ${noun} not found: ${report.transcript_dirs_missing.join(', ')}`);
709
+ }
647
710
  return out.join('\n') + '\n';
648
711
  }
649
712
 
@@ -654,14 +717,16 @@ export function costJson(report) {
654
717
 
655
718
  /* ---------------------------------- CLI ---------------------------------- */
656
719
 
657
- function loadPricing(tyranDir) {
658
- try {
659
- return pricingOf(parse(readFileSync(join(tyranDir, 'config.yaml'), 'utf8')));
660
- } catch {
661
- // A config that will not parse is doctor's problem to report, not this
662
- // reader's problem to refuse over: tokens are still worth counting.
663
- return { rate_card: null, models: Object.create(null) };
664
- }
720
+ /**
721
+ * The rate card out of an ALREADY-PARSED config doc — see `spendTranscriptDirsOf`
722
+ * for why this takes a doc instead of `tyranDir` and reading the file itself.
723
+ * A config that will not parse is doctor's problem to report, not this
724
+ * reader's problem to refuse over: tokens are still worth counting.
725
+ * `pricingOf(null)` already reads as "no pricing block" (see schema.mjs), so
726
+ * an absent/unparseable doc needs no separate branch here.
727
+ */
728
+ function pricingOfDoc(doc) {
729
+ return pricingOf(doc ?? {});
665
730
  }
666
731
 
667
732
  function readCache(path) {
@@ -683,20 +748,21 @@ function writeAtomic(path, text) {
683
748
  renameSync(tmp, path);
684
749
  }
685
750
 
686
- /** Build the report for a repo. Exported so the board server reuses it. */
687
- export function costReport({ tyranDir, projectsRoot, session = null, repoRoot = null } = {}) {
688
- const root = repoRoot ?? resolve(tyranDir, '..');
689
- const dir = transcriptDirFor(root, projectsRoot ?? join(homedir(), '.claude', 'projects'));
690
- const pricing = loadPricing(tyranDir);
691
- if (dir === null) {
692
- const empty = rollup([], pricing, {});
693
- empty.transcripts_found = false;
694
- return empty;
695
- }
751
+ /**
752
+ * The scan-and-persist tail shared by every path through `costReport`: fold
753
+ * `sources` against the on-disk cache, roll it up, attach the fields callers
754
+ * read straight off the report, and write the sidecar. One function so the
755
+ * caching contract — persisted here, not only in the `--json` branch, so the
756
+ * served board benefits too — cannot drift between the derived-dir path and
757
+ * the explicit-dirs path below.
758
+ */
759
+ function finishReport({ sources, pricing, tyranDir, session, transcriptDirsUsed, transcriptDirsMissing }) {
696
760
  const cachePath = join(tyranDir, 'state', COST_FILE);
697
- const { scanned, unreadable, reused } = scanAll(listSources(dir, session), readCache(cachePath));
761
+ const { scanned, unreadable, reused } = scanAll(sources, readCache(cachePath));
698
762
  const report = rollup(scanned, pricing, { unreadable, reused });
699
763
  report.transcripts_found = true;
764
+ report.transcript_dirs = transcriptDirsUsed;
765
+ report.transcript_dirs_missing = transcriptDirsMissing;
700
766
  report.session = session;
701
767
  report.sources = scanned.map((s) => ({
702
768
  path: s.path,
@@ -738,12 +804,90 @@ export function costReport({ tyranDir, projectsRoot, session = null, repoRoot =
738
804
  return report;
739
805
  }
740
806
 
807
+ /**
808
+ * Build the report for a repo. Exported so the board server reuses it.
809
+ *
810
+ * `transcriptDirs` is the explicit override — the fix for a conductor that
811
+ * ran from a working directory other than the repo it operates on (see the
812
+ * comment above `expandHome`). Precedence, highest first: the `transcriptDirs`
813
+ * this caller passed in (the CLI's repeatable `--transcripts`) · `.tyran/
814
+ * config.yaml`'s `spend.transcript_dirs` · the derived-slug / cwd-probe
815
+ * fallback `transcriptDirFor` already does. Reading the config tier HERE
816
+ * rather than in every caller is what lets `board.mjs --serve` honour
817
+ * `spend:` with no `--transcripts` flag at all — one precedence order, read
818
+ * once, for both the CLI and the served page.
819
+ *
820
+ * A dir that does not exist is never silently dropped: it is reported in
821
+ * `transcript_dirs_missing` on the returned report, and if EVERY given dir is
822
+ * missing the report reads exactly like "no transcripts found" — gaps are
823
+ * reported, never zeroed (property 3 above).
824
+ */
825
+ export function costReport({ tyranDir, projectsRoot, session = null, repoRoot = null, transcriptDirs = [] } = {}) {
826
+ const root = repoRoot ?? resolve(tyranDir, '..');
827
+ // Read ONCE and handed to both readers below: `pricingOfDoc` and
828
+ // `spendTranscriptDirsOf` used to each open and parse config.yaml
829
+ // themselves, which meant every `costReport` call — including the ones
830
+ // `board.mjs --serve` makes per request — read the same file twice.
831
+ const configDoc = loadConfigDoc(tyranDir);
832
+ const pricing = pricingOfDoc(configDoc);
833
+
834
+ const given = transcriptDirs.length > 0 ? transcriptDirs : spendTranscriptDirsOf(configDoc);
835
+ // De-duplicated: two spellings of the same directory (a repeated flag, or a
836
+ // flag that repeats what the config already says) must not double-count
837
+ // every transcript under it.
838
+ const explicit = [...new Set(given.map((d) => resolve(expandHome(d))))];
839
+
840
+ if (explicit.length > 0) {
841
+ const present = explicit.filter((d) => existsSync(d));
842
+ const missing = explicit.filter((d) => !existsSync(d));
843
+ if (present.length === 0) {
844
+ const empty = rollup([], pricing, {});
845
+ empty.transcripts_found = false;
846
+ empty.transcript_dirs = [];
847
+ empty.transcript_dirs_missing = missing;
848
+ return empty;
849
+ }
850
+ const sources = present.flatMap((dir) => listSources(dir, session));
851
+ return finishReport({
852
+ sources,
853
+ pricing,
854
+ tyranDir,
855
+ session,
856
+ transcriptDirsUsed: present,
857
+ transcriptDirsMissing: missing,
858
+ });
859
+ }
860
+
861
+ const dir = transcriptDirFor(root, projectsRoot ?? join(homedir(), '.claude', 'projects'));
862
+ if (dir === null) {
863
+ const empty = rollup([], pricing, {});
864
+ empty.transcripts_found = false;
865
+ empty.transcript_dirs = [];
866
+ empty.transcript_dirs_missing = [];
867
+ return empty;
868
+ }
869
+ return finishReport({
870
+ sources: listSources(dir, session),
871
+ pricing,
872
+ tyranDir,
873
+ session,
874
+ transcriptDirsUsed: [dir],
875
+ transcriptDirsMissing: [],
876
+ });
877
+ }
878
+
741
879
  function parseArgs(argv) {
742
- const flags = { dir: '.tyran', session: null, projects: null, json: false };
880
+ const flags = { dir: '.tyran', session: null, projects: null, json: false, transcripts: [] };
743
881
  for (let i = 0; i < argv.length; i += 1) {
744
882
  const arg = argv[i];
745
883
  if (arg === '--json') flags.json = true;
746
- else if (arg === '--dir' || arg === '--session' || arg === '--projects') {
884
+ else if (arg === '--transcripts') {
885
+ const value = argv[i + 1];
886
+ if (value === undefined || value.startsWith('--')) throw new UsageError(`${arg} needs a value`);
887
+ // Repeatable: sources are the union over every directory given.
888
+ flags.transcripts.push(value);
889
+ i += 1;
890
+ } else if (arg === '--dir' || arg === '--session' || arg === '--projects') {
747
891
  const value = argv[i + 1];
748
892
  if (value === undefined || value.startsWith('--')) throw new UsageError(`${arg} needs a value`);
749
893
  flags[arg.slice(2)] = value;
@@ -759,7 +903,10 @@ function main(argv) {
759
903
  flags = parseArgs(argv);
760
904
  } catch (err) {
761
905
  console.error(String(err.message ?? err));
762
- console.error('usage: cost.mjs [--dir <.tyran>] [--session <id>] [--projects <dir>] [--json]');
906
+ console.error(
907
+ 'usage: cost.mjs [--dir <.tyran>] [--session <id>] [--projects <dir>] ' +
908
+ '[--transcripts <dir>]... [--json]'
909
+ );
763
910
  return 2;
764
911
  }
765
912
  const tyranDir = resolve(flags.dir);
@@ -767,12 +914,27 @@ function main(argv) {
767
914
  console.error(`cost: no such directory: ${tyranDir}`);
768
915
  return 2;
769
916
  }
770
- const report = costReport({ tyranDir, projectsRoot: flags.projects, session: flags.session });
917
+ const report = costReport({
918
+ tyranDir,
919
+ projectsRoot: flags.projects,
920
+ session: flags.session,
921
+ transcriptDirs: flags.transcripts,
922
+ });
771
923
  if (report.transcripts_found === false) {
772
- console.error(
773
- 'cost: no transcripts found for this repo under the Claude Code projects directory.\n' +
774
- 'Spend is read from the transcripts the platform writes; nothing here estimates it.'
775
- );
924
+ // Two different gaps, two different sentences: a `--transcripts` (or
925
+ // `spend.transcript_dirs`) dir that does not exist is an operator typo,
926
+ // not the same "nothing to find" as the derived directory being absent.
927
+ if ((report.transcript_dirs_missing ?? []).length > 0) {
928
+ console.error(
929
+ 'cost: none of the given transcript directories exist:\n' +
930
+ report.transcript_dirs_missing.map((d) => ` - ${d}`).join('\n')
931
+ );
932
+ } else {
933
+ console.error(
934
+ 'cost: no transcripts found for this repo under the Claude Code projects directory.\n' +
935
+ 'Spend is read from the transcripts the platform writes; nothing here estimates it.'
936
+ );
937
+ }
776
938
  return 2;
777
939
  }
778
940
  if (flags.json) {
@@ -68,7 +68,7 @@ export function validateConfig(doc) {
68
68
  const errors = [];
69
69
  if (!isPlainObject(doc)) return ['config must be a mapping'];
70
70
 
71
- const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'limits', 'pricing'];
71
+ const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'limits', 'pricing', 'spend'];
72
72
  for (const key of Object.keys(doc)) {
73
73
  if (!known.includes(key)) errors.push(`${key}: unknown top-level key`);
74
74
  }
@@ -229,6 +229,32 @@ export function validateConfig(doc) {
229
229
  }
230
230
  }
231
231
 
232
+ // Where cost.mjs should look for THIS repo's transcripts, when the
233
+ // derived-slug / cwd-probe fallback lands on the wrong session — a
234
+ // conductor that ran from a working directory other than the repo it
235
+ // operates on. Operator-written, never scanner-inferred, exactly like
236
+ // `pricing:` and `limits:` above, and optional for the same reason: absence
237
+ // means the existing fallback resolution applies, unchanged.
238
+ if ('spend' in doc) {
239
+ if (!isPlainObject(doc.spend)) errors.push('spend: must be a mapping');
240
+ else {
241
+ const spend = doc.spend;
242
+ if ('transcript_dirs' in spend) {
243
+ if (!Array.isArray(spend.transcript_dirs)) {
244
+ errors.push('spend.transcript_dirs: must be a list of directory paths');
245
+ } else {
246
+ spend.transcript_dirs.forEach((d, i) => {
247
+ if (!isNonEmptyString(d)) errors.push(`spend.transcript_dirs[${i}]: must be a non-empty path`);
248
+ });
249
+ }
250
+ }
251
+ const knownSpend = ['transcript_dirs'];
252
+ for (const key of Object.keys(spend)) {
253
+ if (!knownSpend.includes(key)) errors.push(`spend.${key}: unknown key`);
254
+ }
255
+ }
256
+ }
257
+
232
258
  return errors;
233
259
  }
234
260