architecture-harness 0.17.0 → 0.18.0

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.
@@ -7,7 +7,7 @@ import { test } from "node:test";
7
7
  import { decide as dispatchDecide } from "./dispatch-guard.mjs";
8
8
  import { appendRecord, readLedger } from "./ledger.mjs";
9
9
  import { gitOut } from "./git-read.mjs";
10
- import { gateRefusal, judgeTask, noResumeReason, recordDispatch, worktreeNamed } from "./task-gate.mjs";
10
+ import { continuedStop, gateRefusal, judgeTask, noResumeReason, recordDispatch, worktreeNamed } from "./task-gate.mjs";
11
11
  import { sessionDirOf } from "./workflow-settings.mjs";
12
12
 
13
13
  const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
@@ -52,7 +52,7 @@ const dispatch = (cwd, prompt, subagent_type = "architecture:sdd-implementer", e
52
52
  ...extra,
53
53
  });
54
54
  const taskPrompt = (worktree, more = "") => `Read the brief at C:/scratch/brief.md.\nWorktree: ${worktree}\n${more}`;
55
- const implementerStop = (ws, head, branch = "feat/1-x") =>
55
+ const implementerStop = (ws, head, branch = "feat/1-x", handoff = null) =>
56
56
  appendRecord(ws.ledger, {
57
57
  type: "stop",
58
58
  session: "s",
@@ -61,6 +61,7 @@ const implementerStop = (ws, head, branch = "feat/1-x") =>
61
61
  role: "implementer",
62
62
  branch,
63
63
  head,
64
+ ...(handoff ? { handoff } : {}),
64
65
  });
65
66
  const verdict = (ws, sha, value = "APPROVED", kind = "task") =>
66
67
  appendRecord(ws.ledger, { type: "verdict", kind, verdict: value, sha, branch: "feat/1-x" });
@@ -419,3 +420,88 @@ test("an implementer that edits qc.config.json in its worktree cannot turn its o
419
420
  implementerStop(ws, commitIn(ws.linked, "b.txt"));
420
421
  assert.match(refusalOf(ws) ?? "", /no review in the ledger/);
421
422
  });
423
+
424
+ test("a fresh implementer with the HANDOFF line of the newest stop continues it without a review first", (t) => {
425
+ const ws = workspace(t);
426
+ const note = path.join(ws.tmp, "handoffs", "t1-1.md");
427
+ const moved = commitIn(ws.linked, "b.txt");
428
+ implementerStop(ws, moved, "feat/1-x", note);
429
+ assert.match(refusalOf(ws) ?? "", /no review in the ledger names/);
430
+ assert.match(refusalOf(ws) ?? "", /`HANDOFF: <note path>`/);
431
+ assert.equal(refusalOf(ws, `HANDOFF: ${note}`), null);
432
+ const { record } = judgeTask(dispatch(ws.main, taskPrompt(ws.linked, `HANDOFF: ${note}`)), ws.tmp);
433
+ assert.equal(record.handoff, note);
434
+ });
435
+
436
+ test("the continuation's own stop needs a review, and a review of the later head covers both", (t) => {
437
+ const ws = workspace(t);
438
+ const note = path.join(ws.tmp, "handoffs", "t1-1.md");
439
+ implementerStop(ws, commitIn(ws.linked, "b.txt"), "feat/1-x", note);
440
+ const later = commitIn(ws.linked, "c.txt");
441
+ implementerStop(ws, later);
442
+ assert.match(refusalOf(ws, `HANDOFF: ${note}`) ?? "", /no review in the ledger names/);
443
+ verdict(ws, later);
444
+ assert.equal(refusalOf(ws), null);
445
+ });
446
+
447
+ test("a HANDOFF line of an older stop, of another branch, or of another note does not excuse a review", (t) => {
448
+ const ws = workspace(t);
449
+ const old = path.join(ws.tmp, "handoffs", "old.md");
450
+ implementerStop(ws, commitIn(ws.linked, "b.txt"), "feat/1-x", old);
451
+ implementerStop(ws, commitIn(ws.linked, "c.txt"));
452
+ assert.match(refusalOf(ws, `HANDOFF: ${old}`) ?? "", /no review in the ledger names/);
453
+ assert.match(refusalOf(ws, `HANDOFF: ${path.join(ws.tmp, "handoffs", "other.md")}`) ?? "", /no review in the ledger names/);
454
+ assert.equal(continuedStop(readLedger(ws.ledger), "feat/2-y", old), null);
455
+ });
456
+
457
+ test("the newest stop of another branch with the named note is not a continuation of this branch", (t) => {
458
+ const ws = workspace(t);
459
+ const note = path.join(ws.tmp, "handoffs", "t1-1.md");
460
+ implementerStop(ws, commitIn(ws.linked, "b.txt"));
461
+ implementerStop(ws, "abc1234", "feat/2-y", note);
462
+ assert.equal(continuedStop(readLedger(ws.ledger), "feat/1-x", note), null);
463
+ assert.equal(continuedStop(readLedger(ws.ledger), "feat/2-y", note)?.branch, "feat/2-y");
464
+ });
465
+
466
+ test("after CHANGES_REQUIRED, a continuation of the fix round's hand-off needs no NO-RESUME line", (t) => {
467
+ const ws = workspace(t);
468
+ const reviewed = commitIn(ws.linked, "b.txt");
469
+ implementerStop(ws, reviewed);
470
+ verdict(ws, reviewed, "CHANGES_REQUIRED");
471
+ const note = path.join(ws.tmp, "handoffs", "fix-1.md");
472
+ const partial = commitIn(ws.linked, "c.txt");
473
+ implementerStop(ws, partial, "feat/1-x", note);
474
+ assert.match(refusalOf(ws) ?? "", /CHANGES_REQUIRED|no review/);
475
+ assert.equal(refusalOf(ws, `HANDOFF: ${note}`), null);
476
+ });
477
+
478
+ test("a stop that a later CHANGES_REQUIRED reviewed is no longer continued by its HANDOFF line", (t) => {
479
+ const ws = workspace(t);
480
+ const note = path.join(ws.tmp, "handoffs", "t1-1.md");
481
+ const stopped = commitIn(ws.linked, "b.txt");
482
+ implementerStop(ws, stopped, "feat/1-x", note);
483
+ assert.equal(refusalOf(ws, `HANDOFF: ${note}`), null);
484
+ verdict(ws, stopped, "CHANGES_REQUIRED");
485
+ assert.equal(continuedStop(readLedger(ws.ledger), "feat/1-x", note), null);
486
+ assert.match(refusalOf(ws, `HANDOFF: ${note}`) ?? "", /CHANGES_REQUIRED/);
487
+ assert.equal(refusalOf(ws, `HANDOFF: ${note}\nNO-RESUME: the budget is spent`), null);
488
+ });
489
+
490
+ test("a later verdict that names the stop's head ends the continuation, whatever branch it records", (t) => {
491
+ const ws = workspace(t);
492
+ const note = path.join(ws.tmp, "handoffs", "t1-1.md");
493
+ const stopped = commitIn(ws.linked, "b.txt");
494
+ implementerStop(ws, stopped, "feat/1-x", note);
495
+ appendRecord(ws.ledger, { type: "verdict", kind: "task", verdict: "CHANGES_REQUIRED", sha: stopped });
496
+ assert.equal(continuedStop(readLedger(ws.ledger), "feat/1-x", note), null);
497
+ assert.match(refusalOf(ws, `HANDOFF: ${note}`) ?? "", /CHANGES_REQUIRED/);
498
+ });
499
+
500
+ test("a later verdict on the branch ends the continuation, whatever commit it names", (t) => {
501
+ const ws = workspace(t);
502
+ const note = path.join(ws.tmp, "handoffs", "t1-1.md");
503
+ implementerStop(ws, commitIn(ws.linked, "b.txt"), "feat/1-x", note);
504
+ verdict(ws, "abc1234", "CHANGES_REQUIRED");
505
+ assert.equal(continuedStop(readLedger(ws.ledger), "feat/1-x", note), null);
506
+ assert.match(refusalOf(ws, `HANDOFF: ${note}`) ?? "", /CHANGES_REQUIRED/);
507
+ });
@@ -0,0 +1,239 @@
1
+ // `qc tokens`: what one session read and wrote, per agent type, from its transcripts. It also prices the
2
+ // same requests at the one-hour cache lifetime, at API list prices, to show which lifetime fits.
3
+
4
+ import { readdirSync, statSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { agentTypeOf, contextOf, readRequests } from "./transcript-usage.mjs";
8
+
9
+ export const RATES = { read: 0.1, write5m: 1.25, write1h: 2 };
10
+ const FIVE_MINUTES = 5 * 60_000;
11
+ const ONE_HOUR = 60 * 60_000;
12
+ export const MAIN = "main";
13
+
14
+ const readOf = (usage) => usage.cache_read_input_tokens ?? 0;
15
+ const writeOf = (usage) => usage.cache_creation_input_tokens ?? 0;
16
+ const write1hOf = (usage) => usage.cache_creation?.ephemeral_1h_input_tokens ?? 0;
17
+ const inputOf = (usage) => usage.input_tokens ?? 0;
18
+
19
+ function median(values) {
20
+ if (values.length === 0) return 0;
21
+ const sorted = [...values].sort((a, b) => a - b);
22
+ return sorted[Math.floor(sorted.length / 2)];
23
+ }
24
+
25
+ /** The observed cost of one agent's requests, the cost at a one-hour lifetime, and its gap misses, in base-input units. */
26
+ export function costsOf(requests, rates = RATES) {
27
+ let cost = 0;
28
+ let cost1h = 0;
29
+ let gapMisses = 0;
30
+ requests.forEach((request, index) => {
31
+ const { usage } = request;
32
+ const read = readOf(usage);
33
+ const write = writeOf(usage);
34
+ const w1h = write1hOf(usage);
35
+ const input = inputOf(usage);
36
+ cost += read * rates.read + (write - w1h) * rates.write5m + w1h * rates.write1h + input;
37
+ const previous = requests[index - 1];
38
+ const gap = previous && request.at !== null && previous.at !== null ? request.at - previous.at : 0;
39
+ const missed = previous !== undefined && gap > FIVE_MINUTES && write > read;
40
+ if (missed) gapMisses += 1;
41
+ if (missed && gap <= ONE_HOUR) {
42
+ const fresh = Math.max(0, contextOf(usage) - contextOf(previous.usage));
43
+ cost1h += (read + write - fresh) * rates.read + fresh * rates.write1h + input;
44
+ } else {
45
+ cost1h += read * rates.read + write * rates.write1h + input;
46
+ }
47
+ });
48
+ return { cost, cost1h, gapMisses };
49
+ }
50
+
51
+ const emptyStats = (type) => ({
52
+ type, agents: 0, calls: 0, read: 0, write5m: 0, write1h: 0, input: 0, output: 0,
53
+ contextSum: 0, maxContext: 0, firsts: [], gapMisses: 0, cost: 0, cost1h: 0,
54
+ });
55
+
56
+ function addAgent(stats, requests, rates) {
57
+ if (requests.length === 0) return;
58
+ stats.agents += 1;
59
+ stats.calls += requests.length;
60
+ for (const { usage } of requests) {
61
+ stats.read += readOf(usage);
62
+ stats.write1h += write1hOf(usage);
63
+ stats.write5m += writeOf(usage) - write1hOf(usage);
64
+ stats.input += inputOf(usage);
65
+ stats.output += usage.output_tokens ?? 0;
66
+ const context = contextOf(usage);
67
+ stats.contextSum += context;
68
+ stats.maxContext = Math.max(stats.maxContext, context);
69
+ }
70
+ const [first] = requests;
71
+ stats.firsts.push({ at: first.at, model: first.model ?? "", read: readOf(first.usage), context: contextOf(first.usage) });
72
+ const costs = costsOf(requests, rates);
73
+ stats.cost += costs.cost;
74
+ stats.cost1h += costs.cost1h;
75
+ stats.gapMisses += costs.gapMisses;
76
+ }
77
+
78
+ function byModel(firsts) {
79
+ const groups = new Map();
80
+ for (const first of firsts) groups.set(first.model, [...(groups.get(first.model) ?? []), first]);
81
+ return [...groups.values()];
82
+ }
83
+
84
+ /** The one-hour saving on first calls that found no shared prefix, though one of the same model warmed it 5 to 60 minutes before. */
85
+ function sharedPrefixCredit(firsts, rates) {
86
+ let credit = 0;
87
+ for (const group of byModel(firsts)) {
88
+ const shared = median(group.map((first) => first.read).filter((read) => read > 0));
89
+ if (shared === 0) continue;
90
+ const timed = group.filter((first) => first.at !== null).sort((a, b) => a.at - b.at);
91
+ timed.forEach((first, index) => {
92
+ const gap = index > 0 ? first.at - timed[index - 1].at : 0;
93
+ if (index > 0 && first.read === 0 && gap > FIVE_MINUTES && gap <= ONE_HOUR) credit += shared * (rates.write1h - rates.read);
94
+ });
95
+ }
96
+ return credit;
97
+ }
98
+
99
+ /** The most distinct warm first-call reads one model of the type saw: more than one means its prefix changed. */
100
+ const prefixesOf = (firsts) =>
101
+ Math.max(0, ...byModel(firsts).map((group) => new Set(group.map((first) => first.read).filter((read) => read > 0)).size));
102
+
103
+ function finish(stats, rates, credit = sharedPrefixCredit(stats.firsts, rates)) {
104
+ const sent = stats.read + stats.write5m + stats.write1h + stats.input;
105
+ const cost1h = stats.cost1h - credit;
106
+ const { firsts, ...rest } = stats;
107
+ return {
108
+ ...rest,
109
+ hitRate: sent === 0 ? 0 : stats.read / sent,
110
+ avgContext: stats.calls === 0 ? 0 : Math.round(stats.contextSum / stats.calls),
111
+ firstMedian: median(firsts.map((first) => first.context)),
112
+ prefixes: prefixesOf(firsts),
113
+ cost1h,
114
+ whatIf1h: stats.cost === 0 ? 0 : (cost1h - stats.cost) / stats.cost,
115
+ };
116
+ }
117
+
118
+ const SUMMED = ["agents", "calls", "read", "write5m", "write1h", "input", "output", "contextSum", "gapMisses", "cost", "cost1h"];
119
+
120
+ /** Per-type statistics of one session, `main` first and then by tokens read, and their total. */
121
+ export function summarizeSession({ main = [], agents = [] }, rates = RATES) {
122
+ const byType = new Map();
123
+ const statsOf = (type) => byType.get(type) ?? byType.set(type, emptyStats(type)).get(type);
124
+ if (main.length > 0) addAgent(statsOf(MAIN), main, rates);
125
+ for (const agent of agents) addAgent(statsOf(agent.type), agent.requests, rates);
126
+ const finished = [...byType.values()].map((stats) => finish(stats, rates));
127
+ const types = [
128
+ ...finished.filter((stats) => stats.type === MAIN),
129
+ ...finished.filter((stats) => stats.type !== MAIN).sort((a, b) => b.read - a.read),
130
+ ];
131
+ const sum = emptyStats("total");
132
+ for (const stats of types) {
133
+ for (const key of SUMMED) sum[key] += stats[key];
134
+ sum.maxContext = Math.max(sum.maxContext, stats.maxContext);
135
+ }
136
+ // The types' own credits are already in their cost1h, so the total takes none of its own.
137
+ return { types, total: finish(sum, rates, 0) };
138
+ }
139
+
140
+ const UNKNOWN = "unknown";
141
+
142
+ /** The folder name Claude Code gives a project: its path, with each character outside letters and digits a dash. */
143
+ export const projectKeyOf = (dir) => path.resolve(dir).replace(/[^A-Za-z0-9]/g, "-");
144
+
145
+ export const claudeDirOf = (env = process.env) => env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
146
+
147
+ function listOf(dir) {
148
+ try {
149
+ return readdirSync(dir);
150
+ } catch {
151
+ return [];
152
+ }
153
+ }
154
+
155
+ function newestSession(projectDir) {
156
+ let newest = null;
157
+ for (const name of listOf(projectDir).filter((file) => file.endsWith(".jsonl"))) {
158
+ const at = statSync(path.join(projectDir, name)).mtimeMs;
159
+ if (!newest || at > newest.at) newest = { id: name.slice(0, -".jsonl".length), at };
160
+ }
161
+ return newest?.id ?? null;
162
+ }
163
+
164
+ /** The transcripts of one session: `session`, or the newest one of the project. @returns null when there is none */
165
+ export function sessionFiles({ claudeDir, project, session = null }) {
166
+ const projectDir = path.join(claudeDir, "projects", projectKeyOf(project));
167
+ const id = session ?? newestSession(projectDir);
168
+ if (!id) return null;
169
+ const main = path.join(projectDir, `${id}.jsonl`);
170
+ const subagents = path.join(projectDir, id, "subagents");
171
+ const agents = listOf(subagents).filter((file) => /^agent-.+\.jsonl$/.test(file)).map((file) => path.join(subagents, file));
172
+ const hasMain = listOf(projectDir).includes(`${id}.jsonl`);
173
+ if (!hasMain && agents.length === 0) return null;
174
+ return { id, main: hasMain ? main : null, agents };
175
+ }
176
+
177
+ function optionsOf(args) {
178
+ const options = { session: null, project: null, claudeDir: null, json: false };
179
+ for (let index = 0; index < args.length; index += 1) {
180
+ const arg = args[index];
181
+ if (arg === "--json") options.json = true;
182
+ else if (arg === "--session") options.session = args[++index] ?? null;
183
+ else if (arg === "--project") options.project = args[++index] ?? null;
184
+ else if (arg === "--claude-dir") options.claudeDir = args[++index] ?? null;
185
+ }
186
+ return options;
187
+ }
188
+
189
+ const amount = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : String(Math.round(n)));
190
+ const percent = (x) => `${(x * 100).toFixed(1)}%`;
191
+ const signed = (x) => `${x > 0 ? "+" : ""}${(x * 100).toFixed(1)}%`;
192
+ const COLUMNS = [
193
+ ["type", 34, (s) => s.type],
194
+ ["agents", 6, (s) => String(s.agents)],
195
+ ["calls", 6, (s) => String(s.calls)],
196
+ ["read", 7, (s) => amount(s.read)],
197
+ ["w5m", 7, (s) => amount(s.write5m)],
198
+ ["w1h", 7, (s) => amount(s.write1h)],
199
+ ["input", 6, (s) => amount(s.input)],
200
+ ["output", 6, (s) => amount(s.output)],
201
+ ["hit", 6, (s) => percent(s.hitRate)],
202
+ ["avgctx", 6, (s) => amount(s.avgContext)],
203
+ ["first", 6, (s) => (s.type === "total" ? "-" : amount(s.firstMedian))],
204
+ ["maxctx", 6, (s) => amount(s.maxContext)],
205
+ ["gapmiss", 7, (s) => String(s.gapMisses)],
206
+ ["prefix", 6, (s) => (s.type === "total" ? "-" : String(s.prefixes))],
207
+ ["1h", 7, (s) => signed(s.whatIf1h)],
208
+ ];
209
+ const row = (cells) => cells.map((cell, index) => (index === 0 ? cell.padEnd(COLUMNS[0][1]) : cell.padStart(COLUMNS[index][1]))).join(" ");
210
+
211
+ const FOOTER = [
212
+ `Rates, in base-input units: read ${RATES.read}, 5m write ${RATES.write5m}, 1h write ${RATES.write1h}. These are API list prices; a subscription's usage limit may weigh them otherwise.`,
213
+ "1h: the cost change had every write used the one-hour lifetime. A negative value favors `subagentPromptCacheTtl: \"1h\"` in settings for this kind of session.",
214
+ "gapmiss: calls after a gap over five minutes that wrote more than they read. prefix: distinct warm first-call reads per model; more than 1 means the type's prefix changed.",
215
+ ];
216
+
217
+ /** `qc tokens [--session <id>] [--project <dir>] [--claude-dir <dir>] [--json]`. @returns the exit code */
218
+ export function runTokens(config, args = [], out = console.log, err = console.error) {
219
+ const options = optionsOf(args);
220
+ const project = options.project ?? config.root ?? process.cwd();
221
+ const files = sessionFiles({ claudeDir: options.claudeDir ?? claudeDirOf(), project, session: options.session });
222
+ if (!files) {
223
+ err(`qc tokens: no session transcript for ${project} under ${options.claudeDir ?? claudeDirOf()}.`);
224
+ return 1;
225
+ }
226
+ const report = summarizeSession({
227
+ main: files.main ? readRequests(files.main) : [],
228
+ agents: files.agents.map((file) => ({ type: agentTypeOf(file) ?? UNKNOWN, requests: readRequests(file) })),
229
+ });
230
+ if (options.json) {
231
+ out(JSON.stringify({ session: files.id, ...report }, null, 2));
232
+ return 0;
233
+ }
234
+ out(`qc tokens session ${files.id}`);
235
+ out(row(COLUMNS.map(([name]) => name)));
236
+ for (const stats of [...report.types, report.total]) out(row(COLUMNS.map(([, , cell]) => cell(stats))));
237
+ for (const text of FOOTER) out(text);
238
+ return 0;
239
+ }
@@ -0,0 +1,286 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { RATES, claudeDirOf, costsOf, projectKeyOf, runTokens, sessionFiles, summarizeSession } from "./tokens.mjs";
7
+ import { readRequests } from "./transcript-usage.mjs";
8
+
9
+ const MINUTE = 60_000;
10
+ const req = (id, minute, read, write, { input = 2, model = "m", w1h = 0 } = {}) => ({
11
+ id,
12
+ model,
13
+ at: minute * MINUTE,
14
+ usage: {
15
+ input_tokens: input,
16
+ cache_read_input_tokens: read,
17
+ cache_creation_input_tokens: write,
18
+ cache_creation: { ephemeral_5m_input_tokens: write - w1h, ephemeral_1h_input_tokens: w1h },
19
+ output_tokens: 5,
20
+ },
21
+ });
22
+
23
+ test("with no gap past five minutes, the one-hour lifetime only raises the write price", () => {
24
+ const { cost, cost1h, gapMisses } = costsOf([req("a", 0, 0, 1000), req("b", 1, 1000, 100)]);
25
+ assert.equal(cost, 1000 * 1.25 + 2 + 1000 * 0.1 + 100 * 1.25 + 2);
26
+ assert.equal(cost1h, 1000 * 2 + 2 + 1000 * 0.1 + 100 * 2 + 2);
27
+ assert.equal(gapMisses, 0);
28
+ });
29
+
30
+ test("a miss after a gap of five minutes to an hour becomes a read of the old context at one hour", () => {
31
+ const { cost, cost1h, gapMisses } = costsOf([req("a", 0, 0, 1000), req("b", 10, 0, 1100)]);
32
+ assert.equal(gapMisses, 1);
33
+ assert.equal(cost, 1000 * 1.25 + 2 + 1100 * 1.25 + 2);
34
+ // The second request re-sent 1,002 tokens it had sent before; only its 100 new ones are written.
35
+ assert.equal(cost1h, 1000 * 2 + 2 + (1100 - 100) * 0.1 + 100 * 2 + 2);
36
+ assert.ok(cost1h < cost);
37
+ });
38
+
39
+ test("a gap past an hour misses at either lifetime", () => {
40
+ const { cost1h, gapMisses } = costsOf([req("a", 0, 0, 1000), req("b", 90, 0, 1100)]);
41
+ assert.equal(gapMisses, 1);
42
+ assert.equal(cost1h, 1000 * 2 + 2 + 1100 * 2 + 2);
43
+ });
44
+
45
+ test("an observed one-hour write is priced as one", () => {
46
+ const { cost } = costsOf([req("a", 0, 0, 1000, { w1h: 1000 })]);
47
+ assert.equal(cost, 1000 * 2 + 2);
48
+ });
49
+
50
+ test("summarizeSession adds each type's agents, and lists main first, then by tokens read", () => {
51
+ const { types, total } = summarizeSession({
52
+ main: [req("m1", 0, 0, 500), req("m2", 1, 500, 50)],
53
+ agents: [
54
+ { type: "impl", requests: [req("i1", 0, 0, 1000), req("i2", 1, 1000, 100), req("i3", 2, 1100, 100)] },
55
+ { type: "impl", requests: [req("j1", 3, 800, 200), req("j2", 4, 1000, 100)] },
56
+ { type: "rev", requests: [req("r1", 0, 0, 300)] },
57
+ ],
58
+ });
59
+ assert.deepEqual(types.map((stats) => stats.type), ["main", "impl", "rev"]);
60
+ const impl = types[1];
61
+ assert.equal(impl.agents, 2);
62
+ assert.equal(impl.calls, 5);
63
+ assert.equal(impl.read, 0 + 1000 + 1100 + 800 + 1000);
64
+ assert.equal(impl.write5m, 1000 + 100 + 100 + 200 + 100);
65
+ assert.equal(impl.maxContext, 1100 + 100 + 2);
66
+ assert.equal(impl.hitRate, impl.read / (impl.read + impl.write5m + impl.write1h + impl.input));
67
+ assert.equal(impl.firstMedian, 1002);
68
+ assert.equal(total.calls, 2 + 5 + 1);
69
+ assert.equal(total.read, types.reduce((sum, stats) => sum + stats.read, 0));
70
+ });
71
+
72
+ test("a first call that missed a shared prefix warmed 5 to 60 minutes before reads it at one hour", () => {
73
+ const agents = [
74
+ { type: "rev", requests: [req("a", 0, 0, 1000)] },
75
+ { type: "rev", requests: [req("b", 2, 800, 200)] },
76
+ { type: "rev", requests: [req("c", 20, 0, 1000)] },
77
+ ];
78
+ const [stats] = summarizeSession({ agents }).types;
79
+ const plain = agents.reduce((sum, agent) => sum + costsOf(agent.requests).cost1h, 0);
80
+ assert.equal(stats.cost1h, plain - 800 * (RATES.write1h - RATES.read));
81
+ assert.equal(stats.prefixes, 1);
82
+ });
83
+
84
+ test("two first-call prefixes of one model in one session count as two", () => {
85
+ const agents = [
86
+ { type: "rev", requests: [req("a", 0, 800, 200)] },
87
+ { type: "rev", requests: [req("b", 1, 900, 200)] },
88
+ { type: "rev", requests: [req("c", 2, 700, 200, { model: "other" })] },
89
+ ];
90
+ assert.equal(summarizeSession({ agents }).types[0].prefixes, 2);
91
+ });
92
+
93
+ test("an empty session sums to zero without dividing by zero", () => {
94
+ const { types, total } = summarizeSession({ main: [], agents: [] });
95
+ assert.deepEqual(types, []);
96
+ assert.equal(total.hitRate, 0);
97
+ assert.equal(total.whatIf1h, 0);
98
+ });
99
+
100
+ test("a call that writes as much as it reads after a long gap is no miss", () => {
101
+ const { gapMisses, cost1h } = costsOf([req("a", 0, 0, 1000), req("b", 10, 500, 500)]);
102
+ assert.equal(gapMisses, 0);
103
+ assert.equal(cost1h, 1000 * 2 + 2 + 500 * 0.1 + 500 * 2 + 2);
104
+ });
105
+
106
+ test("a call that writes more than it reads after a gap under five minutes is no miss", () => {
107
+ const { gapMisses, cost1h } = costsOf([req("a", 0, 0, 1000), req("b", 1, 0, 1100)]);
108
+ assert.equal(gapMisses, 0);
109
+ assert.equal(cost1h, 1000 * 2 + 2 + 1100 * 2 + 2);
110
+ });
111
+
112
+ test("a shared prefix warmed more than an hour before earns no one-hour credit", () => {
113
+ const agents = [
114
+ { type: "rev", requests: [req("a", 0, 0, 1000)] },
115
+ { type: "rev", requests: [req("b", 2, 800, 200)] },
116
+ { type: "rev", requests: [req("c", 100, 0, 1000)] },
117
+ ];
118
+ const [stats] = summarizeSession({ agents }).types;
119
+ assert.equal(stats.cost1h, agents.reduce((sum, agent) => sum + costsOf(agent.requests).cost1h, 0));
120
+ });
121
+
122
+ test("the credit for a shared prefix holds at exactly one hour and not at exactly five minutes", () => {
123
+ const credited = (gap) => {
124
+ const agents = [
125
+ { type: "rev", requests: [req("a", 0, 800, 200)] },
126
+ { type: "rev", requests: [req("b", gap, 0, 1000)] },
127
+ ];
128
+ const [stats] = summarizeSession({ agents }).types;
129
+ return stats.cost1h < agents.reduce((sum, agent) => sum + costsOf(agent.requests).cost1h, 0);
130
+ };
131
+ assert.equal(credited(5), false);
132
+ assert.equal(credited(60), true);
133
+ assert.equal(credited(61), false);
134
+ });
135
+
136
+ test("the total keeps the largest context and the summed one-hour cost, and takes no credit of its own", () => {
137
+ const { types, total } = summarizeSession({
138
+ main: [req("m1", 0, 0, 500), req("m2", 1, 500, 5000)],
139
+ agents: [
140
+ { type: "rev", requests: [req("a", 0, 0, 1000)] },
141
+ { type: "rev", requests: [req("b", 2, 800, 200)] },
142
+ { type: "rev", requests: [req("c", 20, 0, 1000)] },
143
+ ],
144
+ });
145
+ assert.equal(total.maxContext, 500 + 5000 + 2);
146
+ assert.equal(total.cost1h, types.reduce((sum, stats) => sum + stats.cost1h, 0));
147
+ assert.equal(total.whatIf1h, (total.cost1h - total.cost) / total.cost);
148
+ const rev = types.find((stats) => stats.type === "rev");
149
+ const plain = costsOf([req("a", 0, 0, 1000)]).cost1h + costsOf([req("b", 2, 800, 200)]).cost1h + costsOf([req("c", 20, 0, 1000)]).cost1h;
150
+ assert.equal(rev.cost1h, plain - 800 * (RATES.write1h - RATES.read), "the shared prefix credit is in the type, once");
151
+ });
152
+
153
+ const line = (id, minute, read, write) =>
154
+ JSON.stringify({
155
+ type: "assistant",
156
+ timestamp: new Date(minute * 60_000).toISOString(),
157
+ message: { id, model: "claude-sonnet-5-5", role: "assistant", content: [], usage: { input_tokens: 2, cache_read_input_tokens: read, cache_creation_input_tokens: write, output_tokens: 5 } },
158
+ });
159
+
160
+ test("totals on a transcript with a line per content block count each request once", (t) => {
161
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-tokens-")));
162
+ t.after(() => rmSync(base, { recursive: true, force: true }));
163
+ const file = path.join(base, "agent-a1.jsonl");
164
+ const lines = [line("i1", 0, 0, 1000), line("i1", 0, 0, 1000), line("i2", 1, 1000, 100), line("i2", 1, 1000, 100), line("i2", 1, 1000, 100)];
165
+ writeFileSync(file, `${lines.join("\n")}\n`);
166
+ const { types, total } = summarizeSession({ agents: [{ type: "impl", requests: readRequests(file) }] });
167
+ assert.equal(types[0].calls, 2);
168
+ assert.equal(types[0].read, 1000);
169
+ assert.equal(types[0].write5m, 1100);
170
+ assert.equal(total.calls, 2);
171
+ assert.equal(total.output, 10);
172
+ });
173
+
174
+ function claudeDir(t) {
175
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-tokens-")));
176
+ t.after(() => rmSync(base, { recursive: true, force: true }));
177
+ return base;
178
+ }
179
+
180
+ /** A fake Claude Code folder with one project, a newer session `s1` (a main transcript and two subagents), and an older one `s0`. */
181
+ function fakeSession(t) {
182
+ const dir = claudeDir(t);
183
+ const project = path.join(dir, "repo");
184
+ const projectDir = path.join(dir, "projects", projectKeyOf(project));
185
+ const subagents = path.join(projectDir, "s1", "subagents");
186
+ mkdirSync(subagents, { recursive: true });
187
+ writeFileSync(path.join(projectDir, "s1.jsonl"), `${line("m1", 0, 0, 500)}\n`);
188
+ writeFileSync(path.join(subagents, "agent-a1.jsonl"), `${line("i1", 0, 0, 1000)}\n${line("i1", 0, 0, 1000)}\n${line("i2", 1, 1000, 100)}\n`);
189
+ writeFileSync(path.join(subagents, "agent-a1.meta.json"), JSON.stringify({ agentType: "architecture:sdd-implementer" }));
190
+ writeFileSync(path.join(subagents, "agent-a2.jsonl"), `${line("r1", 2, 0, 300)}\n`);
191
+ writeFileSync(path.join(subagents, "notes.jsonl"), `${line("z1", 3, 0, 9)}\n`);
192
+ const older = path.join(projectDir, "s0.jsonl");
193
+ writeFileSync(older, `${line("o1", 0, 0, 77)}\n`);
194
+ utimesSync(older, new Date("2020-01-01"), new Date("2020-01-01"));
195
+ return { dir, project, projectDir };
196
+ }
197
+
198
+ test("the project key replaces each character outside letters and digits with a dash", () => {
199
+ if (process.platform === "win32") assert.equal(projectKeyOf("C:\\Users\\x\\qc-mono"), "C--Users-x-qc-mono");
200
+ else assert.equal(projectKeyOf("/home/u/qc-mono"), "-home-u-qc-mono");
201
+ });
202
+
203
+ test("the project key keeps a digit", () => {
204
+ assert.match(projectKeyOf(path.join(os.tmpdir(), "repo2")), /repo2$/);
205
+ });
206
+
207
+ test("the Claude folder is the environment's, else the home folder's", () => {
208
+ assert.equal(claudeDirOf({ CLAUDE_CONFIG_DIR: "/somewhere" }), "/somewhere");
209
+ assert.equal(claudeDirOf({}), path.join(os.homedir(), ".claude"));
210
+ });
211
+
212
+ test("sessionFiles finds the newest session's main transcript and each subagent transcript", (t) => {
213
+ const { dir, project } = fakeSession(t);
214
+ const files = sessionFiles({ claudeDir: dir, project });
215
+ assert.equal(files.id, "s1");
216
+ assert.ok(files.main.endsWith("s1.jsonl"));
217
+ assert.deepEqual(files.agents.map((file) => path.basename(file)).sort(), ["agent-a1.jsonl", "agent-a2.jsonl"]);
218
+ assert.equal(sessionFiles({ claudeDir: dir, project: path.join(dir, "elsewhere") }), null);
219
+ });
220
+
221
+ test("a stray file in the subagents folder is not read as a subagent transcript", (t) => {
222
+ const { dir, project, projectDir } = fakeSession(t);
223
+ const subagents = path.join(projectDir, "s1", "subagents");
224
+ for (const stray of ["agent-notes.txt", "xagent-1.jsonl", "agent-a3.jsonl.bak"]) writeFileSync(path.join(subagents, stray), `${line("z", 4, 0, 9)}\n`);
225
+ const files = sessionFiles({ claudeDir: dir, project });
226
+ assert.deepEqual(files.agents.map((file) => path.basename(file)).sort(), ["agent-a1.jsonl", "agent-a2.jsonl"]);
227
+ });
228
+
229
+ test("sessionFiles reads a named session even when a newer one exists", (t) => {
230
+ const { dir, project } = fakeSession(t);
231
+ const files = sessionFiles({ claudeDir: dir, project, session: "s0" });
232
+ assert.equal(files.id, "s0");
233
+ assert.deepEqual(files.agents, []);
234
+ });
235
+
236
+ test("a session with subagents and no main transcript has no main, and one with neither is not found", (t) => {
237
+ const { dir, project, projectDir } = fakeSession(t);
238
+ mkdirSync(path.join(projectDir, "s2", "subagents"), { recursive: true });
239
+ writeFileSync(path.join(projectDir, "s2", "subagents", "agent-b1.jsonl"), `${line("b1", 0, 0, 5)}\n`);
240
+ const headless = sessionFiles({ claudeDir: dir, project, session: "s2" });
241
+ assert.equal(headless.main, null);
242
+ assert.equal(headless.agents.length, 1);
243
+ assert.equal(sessionFiles({ claudeDir: dir, project, session: "ghost" }), null);
244
+ });
245
+
246
+ test("qc tokens --session reads that session, and --project names the project, not the config root", (t) => {
247
+ const { dir, project } = fakeSession(t);
248
+ const lines = [];
249
+ const code = runTokens({ root: path.join(dir, "elsewhere") }, ["--claude-dir", dir, "--project", project, "--session", "s0", "--json"], (text) => lines.push(text));
250
+ assert.equal(code, 0);
251
+ const report = JSON.parse(lines.join("\n"));
252
+ assert.equal(report.session, "s0");
253
+ assert.deepEqual(report.types.map((stats) => stats.type), ["main"]);
254
+ assert.equal(report.types[0].write5m, 77);
255
+ });
256
+
257
+ test("qc tokens --json reports each type once per request, and an agent with no meta as unknown", (t) => {
258
+ const { dir, project } = fakeSession(t);
259
+ const lines = [];
260
+ const code = runTokens({ root: project }, ["--claude-dir", dir, "--json"], (text) => lines.push(text));
261
+ assert.equal(code, 0);
262
+ const report = JSON.parse(lines.join("\n"));
263
+ assert.equal(report.session, "s1");
264
+ const byType = Object.fromEntries(report.types.map((stats) => [stats.type, stats]));
265
+ assert.deepEqual(Object.keys(byType), ["main", "architecture:sdd-implementer", "unknown"]);
266
+ assert.equal(byType["architecture:sdd-implementer"].calls, 2);
267
+ assert.equal(byType.unknown.calls, 1);
268
+ });
269
+
270
+ test("qc tokens prints a table with a footer that names the rates", (t) => {
271
+ const { dir, project } = fakeSession(t);
272
+ const lines = [];
273
+ assert.equal(runTokens({ root: project }, ["--claude-dir", dir, "--session", "s1"], (text) => lines.push(text)), 0);
274
+ const text = lines.join("\n");
275
+ assert.match(text, /architecture:sdd-implementer/);
276
+ assert.match(text, /total/);
277
+ assert.match(text, /API list prices/);
278
+ assert.match(text, /subagentPromptCacheTtl/);
279
+ });
280
+
281
+ test("qc tokens with no session to read says so and exits 1", (t) => {
282
+ const dir = claudeDir(t);
283
+ const errors = [];
284
+ assert.equal(runTokens({ root: path.join(dir, "none") }, ["--claude-dir", dir], () => {}, (text) => errors.push(text)), 1);
285
+ assert.match(errors.join("\n"), /no session/);
286
+ });