aiinfra-tools 0.2.0 → 0.3.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.
Files changed (157) hide show
  1. package/CHANGELOG.md +210 -0
  2. package/README.md +14 -3
  3. package/bin/aiinfra.mjs +5 -2
  4. package/bin/report.mjs +177 -0
  5. package/fleetops/README.md +33 -1
  6. package/fleetops/deploy/shadow-gate/argo-analysistemplate.yaml +34 -0
  7. package/fleetops/deploy/shadow-gate/argo-rollout-example.yaml +38 -0
  8. package/fleetops/deploy/shadow-gate/flagger-canary.yaml +34 -0
  9. package/fleetops/deploy/shadow-gate/judge.yaml +51 -0
  10. package/fleetops/deploy/shadow-gate/llmd-canary-example.yaml +35 -0
  11. package/fleetops/deploy/shadow-gate/podmonitor-vllm.yaml +20 -0
  12. package/fleetops/deploy/shadow-live/README.md +33 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +121 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +48 -0
  16. package/fleetops/docs/ADMISSION.md +9 -9
  17. package/fleetops/docs/FABRIC-STORAGE.md +1 -1
  18. package/fleetops/docs/SERVING.md +11 -1
  19. package/fleetops/docs/SHADOW.md +250 -0
  20. package/fleetops/docs/SIGNALS.md +5 -2
  21. package/fleetops/docs/WORKLOADS.md +1 -1
  22. package/fleetops/package.json +7 -4
  23. package/fleetops/src/adapters/fabric.mjs +19 -7
  24. package/fleetops/src/adapters/live.mjs +38 -5
  25. package/fleetops/src/adapters/logs.mjs +10 -7
  26. package/fleetops/src/adapters/nvsentinel.mjs +95 -0
  27. package/fleetops/src/adapters/topology.mjs +53 -1
  28. package/fleetops/src/admission.mjs +26 -18
  29. package/fleetops/src/api.mjs +2 -1
  30. package/fleetops/src/bundle.mjs +3 -0
  31. package/fleetops/src/calibrate.mjs +1 -1
  32. package/fleetops/src/detect.mjs +1 -1
  33. package/fleetops/src/export.mjs +5 -1
  34. package/fleetops/src/goodput.mjs +0 -2
  35. package/fleetops/src/incidents.mjs +1 -2
  36. package/fleetops/src/ingest.mjs +1 -1
  37. package/fleetops/src/inject.mjs +2 -2
  38. package/fleetops/src/live.mjs +2 -1
  39. package/fleetops/src/llmd.mjs +7 -3
  40. package/fleetops/src/optimize.mjs +1 -1
  41. package/fleetops/src/power.mjs +7 -7
  42. package/fleetops/src/procure.mjs +67 -0
  43. package/fleetops/src/rca.mjs +1 -1
  44. package/fleetops/src/rollout.mjs +1 -1
  45. package/fleetops/src/schema.mjs +3 -2
  46. package/fleetops/src/security.mjs +1 -1
  47. package/fleetops/src/serving.mjs +21 -9
  48. package/fleetops/src/shadow-canary.mjs +74 -0
  49. package/fleetops/src/shadow-gate.mjs +49 -0
  50. package/fleetops/src/shadow-prom.mjs +205 -0
  51. package/fleetops/src/shadow-replay.mjs +147 -0
  52. package/fleetops/src/shadow.mjs +291 -0
  53. package/fleetops/src/stats.mjs +14 -0
  54. package/fleetops/src/traces.mjs +0 -5
  55. package/fleetops/tests/fixtures/real/README.md +5 -0
  56. package/fleetops/tools/admit-node.sh +51 -16
  57. package/fleetops/tools/amd-admit.py +111 -0
  58. package/fleetops/tools/cmd/calibrate.mjs +61 -0
  59. package/fleetops/tools/cmd/capacity.mjs +116 -0
  60. package/fleetops/tools/cmd/common.mjs +32 -0
  61. package/fleetops/tools/cmd/data.mjs +343 -0
  62. package/fleetops/tools/cmd/help.mjs +243 -0
  63. package/fleetops/tools/cmd/incidents.mjs +216 -0
  64. package/fleetops/tools/cmd/rollout.mjs +122 -0
  65. package/fleetops/tools/cmd/server.mjs +122 -0
  66. package/fleetops/tools/cmd/serving.mjs +95 -0
  67. package/fleetops/tools/cmd/shadow.mjs +204 -0
  68. package/fleetops/tools/cmd/training.mjs +79 -0
  69. package/fleetops/tools/collect.sh +6 -1
  70. package/fleetops/tools/fleetops.mjs +18 -1308
  71. package/fleetops/tools/loop-demo.mjs +1 -1
  72. package/fleetops/tools/workload-profile.mjs +0 -1
  73. package/fleetscope/README.md +5 -1
  74. package/fleetscope/build.mjs +1 -0
  75. package/fleetscope/dist/index.html +295 -26
  76. package/fleetscope/docs/AGENTIC.md +89 -0
  77. package/fleetscope/docs/PLANNING.md +4 -2
  78. package/fleetscope/docs/VALIDATION-AGENTIC.md +37 -0
  79. package/fleetscope/package.json +4 -3
  80. package/fleetscope/src/agentic.js +288 -0
  81. package/fleetscope/src/ask.js +0 -1
  82. package/fleetscope/src/cluster-ui.js +1 -0
  83. package/fleetscope/src/engine.js +10 -11
  84. package/fleetscope/src/index.src.html +9 -5
  85. package/fleetscope/src/inference-ui.js +1 -0
  86. package/fleetscope/src/ingest.js +89 -3
  87. package/fleetscope/src/optimize.js +11 -5
  88. package/fleetscope/src/plan.js +1 -1
  89. package/fleetscope/src/training-ui.js +1 -0
  90. package/fleetscope/tools/agentic.mjs +148 -0
  91. package/fleetscope/tools/tracelab-data.mjs +27 -0
  92. package/gpu-health/README.md +13 -2
  93. package/gpu-health/docs/CONFIG.md +29 -1
  94. package/gpu-health/package.json +7 -4
  95. package/gpu-health/src/actions.mjs +16 -3
  96. package/gpu-health/src/analyze.mjs +3 -0
  97. package/gpu-health/src/config.mjs +3 -0
  98. package/gpu-health/src/executors.mjs +9 -4
  99. package/gpu-health/src/health.mjs +1 -1
  100. package/gpu-health/src/ingest.mjs +27 -3
  101. package/gpu-health/src/platforms.mjs +109 -0
  102. package/gpu-health/src/vendors.mjs +12 -5
  103. package/gpu-health/tools/gpu-health.mjs +6 -4
  104. package/gpu-ledger/README.md +3 -1
  105. package/gpu-ledger/package.json +12 -4
  106. package/gpu-ledger/src/adapters.mjs +3 -2
  107. package/gpu-ledger/src/cloud.mjs +104 -0
  108. package/gpu-ledger/src/core.mjs +12 -10
  109. package/gpu-ledger/tools/ledger.mjs +8 -2
  110. package/harness-ledger/README.md +152 -0
  111. package/harness-ledger/docs/FORMATS.md +114 -0
  112. package/harness-ledger/docs/METHOD.md +133 -0
  113. package/harness-ledger/docs/VALIDATION-ECONOMICS.md +59 -0
  114. package/harness-ledger/docs/VALIDATION-SWEBENCH.md +26 -0
  115. package/harness-ledger/docs/VALIDATION-TRACELAB.md +56 -0
  116. package/harness-ledger/package.json +19 -0
  117. package/harness-ledger/src/demo.mjs +115 -0
  118. package/harness-ledger/src/economics.mjs +184 -0
  119. package/harness-ledger/src/gpu.mjs +80 -0
  120. package/harness-ledger/src/html.mjs +63 -0
  121. package/harness-ledger/src/importers.mjs +247 -0
  122. package/harness-ledger/src/ledger.mjs +128 -0
  123. package/harness-ledger/src/opencost.mjs +55 -0
  124. package/harness-ledger/src/outcomes.mjs +67 -0
  125. package/harness-ledger/src/prices.mjs +75 -0
  126. package/harness-ledger/src/record.mjs +52 -0
  127. package/harness-ledger/src/waste.mjs +136 -0
  128. package/harness-ledger/tools/harness-ledger.mjs +199 -0
  129. package/harness-ledger/tools/validate-economics.mjs +69 -0
  130. package/harness-ledger/tools/validate-swebench.mjs +57 -0
  131. package/harness-ledger/tools/validate-tracelab.mjs +74 -0
  132. package/hybrid-tracing/package.json +4 -3
  133. package/hybrid-tracing/tools/fix-skew.mjs +1 -1
  134. package/inference-sizer/README.md +5 -1
  135. package/inference-sizer/build.mjs +1 -0
  136. package/inference-sizer/dist/index.html +205 -22
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  139. package/inference-sizer/package.json +4 -3
  140. package/inference-sizer/src/accelerators.js +172 -0
  141. package/inference-sizer/src/catalog.js +7 -20
  142. package/inference-sizer/src/fit-ui.js +1 -1
  143. package/inference-sizer/src/index.src.html +3 -0
  144. package/inference-sizer/src/model.js +22 -1
  145. package/inference-sizer/tools/validate-agentx.mjs +110 -0
  146. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  147. package/mcp/README.md +6 -1
  148. package/mcp/server.mjs +34 -0
  149. package/package.json +9 -4
  150. package/schemas/README.md +3 -0
  151. package/schemas/aiinfra.report.schema.json +474 -0
  152. package/schemas/commands.mjs +14 -0
  153. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  154. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  155. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  156. package/schemas/harness-ledger.economics.schema.json +567 -0
  157. package/schemas/sizer.list.schema.json +15 -2
@@ -0,0 +1,52 @@
1
+ // The llm_call record: one model request made by an agent harness, whatever harness made it.
2
+ //
3
+ // { kind: 'llm_call', t (epoch s), harness ('claude-code'|'codex'|'otel'|'openinference'|'langfuse'|…),
4
+ // session, agent? (subagent or agent name), parent? (parent session), id (dedupe key), traceId?, spanId?,
5
+ // model?, provider?,
6
+ // input total input tokens, cached ones included (the OpenTelemetry GenAI meaning of gen_ai.usage.input_tokens)
7
+ // cacheRead, cacheWrite parts of input served from / written to the provider's prompt cache (null = not reported)
8
+ // output, reasoning? output tokens; reasoning is part of output when the provider reports it
9
+ // toolsOffered? [names] tool definitions sent with the request (null = the harness doesn't log them)
10
+ // toolDefTokens? estimated tokens of those definitions
11
+ // toolCalls [{ name, id?, argHash?, resultTokens?, error? }] tools the response asked for, with what came back
12
+ // finish?, error?, durS?, costUSD? (when the harness recorded a cost), outcome? ('success'|'failure') }
13
+ //
14
+ // Records hold counts, names and hashes only. No prompt, completion, argument or tool-result text is kept: the
15
+ // importers read transcripts that can hold anything, and what they write out has to be safe to share.
16
+ import { createHash } from 'node:crypto';
17
+
18
+ export const num = v => (v == null || v === '' || !Number.isFinite(Number(v)) ? null : Number(v));
19
+ export const hash = s => createHash('sha256').update(typeof s === 'string' ? s : JSON.stringify(s ?? null)).digest('hex').slice(0, 16);
20
+ // A rough token count for text we don't have a tokenizer for: about 4 characters per token for English and code.
21
+ export const estTokens = v => { if (v == null) return 0; const s = typeof v === 'string' ? v : JSON.stringify(v); return Math.ceil(s.length / 4); };
22
+ export const toSec = v => {
23
+ if (v == null || v === '') return null;
24
+ if (Array.isArray(v)) return Number(v[0]) + Number(v[1] || 0) / 1e9; // [seconds, nanos] (OTel JS hrtime)
25
+ if (typeof v === 'number') return v > 1e17 ? v / 1e9 : v > 1e14 ? v / 1e6 : v > 1e11 ? v / 1e3 : v; // ns, µs, ms or s
26
+ if (/^\d+$/.test(String(v))) return toSec(Number(v));
27
+ const t = Date.parse(v); return Number.isFinite(t) ? t / 1000 : null;
28
+ };
29
+ export const fresh = c => Math.max(0, (c.input || 0) - (c.cacheRead || 0) - (c.cacheWrite || 0));
30
+
31
+ export function call(o) {
32
+ const r = { kind: 'llm_call', t: o.t, harness: o.harness, session: o.session ?? 'unknown', id: o.id, model: o.model ?? null,
33
+ input: o.input || 0, cacheRead: o.cacheRead ?? null, cacheWrite: o.cacheWrite ?? null, output: o.output || 0, toolCalls: o.toolCalls || [] };
34
+ for (const k of ['agent', 'parent', 'traceId', 'spanId', 'provider', 'reasoning', 'toolsOffered', 'toolDefTokens', 'finish', 'error', 'durS', 'costUSD', 'outcome', 'source'])
35
+ if (o[k] != null && o[k] !== '') r[k] = o[k];
36
+ return r;
37
+ }
38
+
39
+ // One record per id; later lines of the same response replace earlier ones (Claude Code writes a line per content
40
+ // block, each repeating the response's usage).
41
+ export function dedupe(calls) {
42
+ const by = new Map();
43
+ for (const c of calls) {
44
+ const k = `${c.harness}|${c.session}|${c.id}`, prev = by.get(k);
45
+ if (!prev) { by.set(k, c); continue; }
46
+ const tools = [...prev.toolCalls]; for (const tc of c.toolCalls) if (!tools.some(x => x.id && x.id === tc.id)) tools.push(tc);
47
+ by.set(k, { ...prev, ...c, t: Math.min(prev.t, c.t), output: Math.max(prev.output, c.output), toolCalls: tools });
48
+ }
49
+ return [...by.values()].sort((a, b) => a.t - b.t);
50
+ }
51
+
52
+ export const sessionsOf = calls => { const m = new Map(); for (const c of calls) { const k = `${c.harness}|${c.session}`; if (!m.has(k)) m.set(k, []); m.get(k).push(c); } for (const v of m.values()) v.sort((a, b) => a.t - b.t); return m; };
@@ -0,0 +1,136 @@
1
+ // Where a harness wastes model resources. Each check reads priced llm_call records of one session and returns
2
+ // findings: { cause, harness, session, agent, model, at (call id), t, tokens, cost, note, detail }.
3
+ //
4
+ // fullPrice the part of tokens processed at full price (prefilled, or generated); the rest is context re-read from
5
+ // the prompt cache, cheap per token but still occupying the context window and KV cache
6
+ // tokens model work that needn't have happened: input processed at full price that a prompt cache should have
7
+ // served (that's prefill compute on a self-hosted model), tool output beyond what the agent needed, carried
8
+ // through every later call, repeated calls, retries of failing calls.
9
+ // cost what that work cost at the call's own prices (list prices, the harness's recorded cost, or GPU time).
10
+ //
11
+ // The causes:
12
+ // cache-miss the next call re-sent the previous call's context without reading it from cache: the prefix
13
+ // changed (a timestamp or reordered tools in the system prompt, edited history, a parameter or
14
+ // tool-set switch) or the harness didn't mark it cacheable
15
+ // cache-expired the same, after a pause longer than the cache's lifetime (a slow tool, a human away)
16
+ // cache-write-unread tokens written to cache (billed at a premium) that no later call read
17
+ // tool-output-bloat a tool result far larger than a summary would be, re-sent in every later call
18
+ // repeated-tool-call the same tool with the same arguments again in one session (sometimes deliberate: a test
19
+ // re-run after an edit; the report shows which tools so it can be judged)
20
+ // error-loop three or more calls in a row whose tool calls all failed, with the same tool
21
+ // failed-call a model call that errored but still used tokens
22
+ // unused-tools tool definitions sent with every call that the session never used
23
+ // model-tier (candidate) a short routing call on a large model whose price file names a cheaper model to try,
24
+ // counted only where it saves money even after the cheaper model re-reads the context uncached
25
+ //
26
+ // Causes can overlap on one call (a bloated tool result re-sent uncached); a call's findings are scaled so their cost
27
+ // never exceeds what the call cost.
28
+ import { sessionsOf, fresh } from './record.mjs';
29
+ import { costWith } from './prices.mjs';
30
+
31
+ export const DEFAULTS = { cacheTtlS: 300, minMissTokens: 1024, missTolerance: 0.02, compaction: 0.5, bigResultTokens: 8000, keepResultTokens: 1500,
32
+ loopMin: 3, tierMaxOutput: 300, repeatWindow: 25, repeatIgnore: /todo|plan|task|think|ask|question|exit/i };
33
+
34
+ const priceOf = c => c.price || { in: 0, read: 0, write: 0, out: 0 };
35
+ const isCompaction = (prev, cur, o) => cur.input < prev.input * (1 - o.compaction);
36
+
37
+ export function analyzeSession(calls, opts = {}) {
38
+ const o = { ...DEFAULTS, ...opts }, out = [];
39
+ const base = c => ({ harness: c.harness, session: c.session, agent: c.agent || 'main', model: c.model, at: c.id, t: c.t });
40
+ // chains: consecutive calls of one model (side calls on other models — titles, summaries — run their own chain)
41
+ const chains = new Map(); for (const c of calls) { const k = c.model || '?'; if (!chains.has(k)) chains.set(k, []); chains.get(k).push(c); }
42
+ const carriedAfter = new Map(); // call → how many later calls in its chain carry its context (until compaction)
43
+ for (const chain of chains.values()) {
44
+ for (let i = 0; i < chain.length; i++) {
45
+ let k = 0; for (let j = i + 1; j < chain.length; j++) { if (isCompaction(chain[j - 1], chain[j], o)) break; k++; }
46
+ carriedAfter.set(chain[i], k);
47
+ }
48
+ for (let i = 1; i < chain.length; i++) {
49
+ const prev = chain[i - 1], cur = chain[i];
50
+ if (cur.cacheRead == null || prev.error || cur.error || isCompaction(prev, cur, o)) continue;
51
+ const prefix = Math.min(prev.input, cur.input), missed = prefix - (cur.cacheRead || 0);
52
+ if (missed < Math.max(o.minMissTokens, o.missTolerance * prefix)) continue;
53
+ const p = priceOf(cur), w = Math.min(missed, cur.cacheWrite || 0), cost = Math.max(0, w * p.write + (missed - w) * p.in - missed * p.read);
54
+ const gap = cur.t - prev.t, expired = gap > o.cacheTtlS;
55
+ out.push({ ...base(cur), cause: expired ? 'cache-expired' : 'cache-miss', tokens: missed, fullPrice: missed, cost,
56
+ note: expired ? `${Math.round(gap)} s after the previous call; the cache lasts ~${o.cacheTtlS} s` : `${Math.round(100 * (cur.cacheRead || 0) / prefix)}% of the previous context came from cache`,
57
+ detail: { prefix, cacheRead: cur.cacheRead || 0, gapS: gap } });
58
+ }
59
+ for (let i = 0; i < chain.length; i++) {
60
+ const c = chain[i], p = priceOf(c);
61
+ if (!(c.cacheWrite > 0) || !(p.write > p.in)) continue;
62
+ const next = chain.slice(i + 1).find(n => n.t - c.t <= o.cacheTtlS && (n.cacheRead || 0) > 0);
63
+ if (next) continue;
64
+ out.push({ ...base(c), cause: 'cache-write-unread', tokens: 0, fullPrice: 0, cost: c.cacheWrite * (p.write - p.in),
65
+ note: i === chain.length - 1 ? 'last call of the session wrote to cache' : 'nothing read it before it expired', detail: { cacheWrite: c.cacheWrite } });
66
+ }
67
+ }
68
+ // tools: bloat, repeats, error loops
69
+ const seen = [], used = new Set();
70
+ calls.forEach((c, i) => {
71
+ const p = priceOf(c), k = carriedAfter.get(c) || 0, laterPrice = c.cacheRead != null ? p.read : p.in;
72
+ for (const tc of c.toolCalls) {
73
+ used.add(tc.name);
74
+ if (tc.resultTokens > o.bigResultTokens) {
75
+ const excess = tc.resultTokens - o.keepResultTokens;
76
+ out.push({ ...base(c), cause: 'tool-output-bloat', tool: tc.name, tokens: excess * (1 + k), fullPrice: c.cacheRead != null ? excess : excess * (1 + k), cost: excess * p.in + excess * k * laterPrice,
77
+ note: `${tc.name} returned ~${Math.round(tc.resultTokens / 1000)}k tokens, carried through ${k} later call${k === 1 ? '' : 's'}`, detail: { resultTokens: tc.resultTokens, carried: k } });
78
+ }
79
+ if (tc.argHash && !o.repeatIgnore.test(tc.name)) {
80
+ const prior = seen.slice(-o.repeatWindow).find(s => s.name === tc.name && s.argHash === tc.argHash && !s.error);
81
+ if (prior) {
82
+ const res = tc.resultTokens || 0, outShare = (c.output || 0) / Math.max(1, c.toolCalls.length);
83
+ out.push({ ...base(c), cause: 'repeated-tool-call', tool: tc.name, tokens: res * (1 + k) + outShare, fullPrice: (c.cacheRead != null ? res : res * (1 + k)) + outShare, cost: res * p.in + res * k * laterPrice + outShare * p.out,
84
+ note: `${tc.name} called again with the same arguments`, detail: { resultTokens: res, carried: k } });
85
+ }
86
+ }
87
+ seen.push(tc);
88
+ }
89
+ if (c.error && (c.input || c.output)) out.push({ ...base(c), cause: 'failed-call', tokens: c.input + c.output, fullPrice: fresh(c) + c.output, cost: c.cost || 0, note: `call failed: ${c.error}` });
90
+ });
91
+ // error loops: runs of calls whose tool calls all failed, same tool
92
+ for (let i = 0; i < calls.length;) {
93
+ const failing = c => c.toolCalls.length > 0 && c.toolCalls.every(t => t.error);
94
+ if (!failing(calls[i])) { i++; continue; }
95
+ const tool = calls[i].toolCalls[0].name; let j = i;
96
+ while (j < calls.length && failing(calls[j]) && calls[j].toolCalls[0].name === tool) j++;
97
+ if (j - i >= o.loopMin) for (const c of calls.slice(i + 2, j))
98
+ out.push({ ...base(c), cause: 'error-loop', tool, tokens: (c.input || 0) + (c.output || 0), fullPrice: fresh(c) + (c.output || 0), cost: c.cost || 0, note: `${j - i} calls in a row with ${tool} failing` });
99
+ i = j;
100
+ }
101
+ // unused tool definitions
102
+ for (const c of calls) {
103
+ if (!c.toolsOffered || !c.toolsOffered.length || !c.toolDefTokens) continue;
104
+ const unused = c.toolsOffered.filter(n => !used.has(n)); if (!unused.length) continue;
105
+ const tokens = c.toolDefTokens * unused.length / c.toolsOffered.length, p = priceOf(c);
106
+ const cached = (c.cacheRead || 0) > tokens;
107
+ out.push({ ...base(c), cause: 'unused-tools', tokens, fullPrice: cached ? 0 : tokens, cost: tokens * (cached ? p.read : p.in),
108
+ note: `${unused.length} of ${c.toolsOffered.length} tools never used in this session`, detail: { unused: unused.slice(0, 20) } });
109
+ }
110
+ // model tier candidates
111
+ for (const c of calls) {
112
+ if (!c.downshift || !c.cheaper || c.error || (c.output || 0) > o.tierMaxOutput || c.toolCalls.length !== 1 || (c.reasoning || 0) > 0) continue;
113
+ // a prompt cache belongs to one model: on the cheaper model the whole context is prefilled again
114
+ const save = (c.cost || 0) - (costWith({ ...c, cacheRead: 0, cacheWrite: 0 }, c.cheaper) || 0);
115
+ if (save > 0) out.push({ ...base(c), cause: 'model-tier', tokens: 0, fullPrice: 0, cost: save, note: `short ${c.toolCalls[0].name} routing call; try ${c.downshift}`, candidate: true });
116
+ }
117
+ // a call's findings never cost more than the call
118
+ const byCall = new Map(); for (const f of out) { const k = f.at; if (!byCall.has(k)) byCall.set(k, []); byCall.get(k).push(f); }
119
+ const byId = new Map(calls.map(c => [c.id, c]));
120
+ for (const [k, fs] of byCall) {
121
+ const c = byId.get(k), real = fs.filter(f => !f.candidate);
122
+ const cap = c && c.cost, sum = real.reduce((s, f) => s + f.cost, 0); if (cap != null && sum > cap && sum > 0) for (const f of real) f.cost *= cap / sum;
123
+ // tokens: a later call carries a result forward, so bloat and repeats can exceed this call's own tokens; only
124
+ // the overlap between causes on the same call's own input is capped
125
+ const own = c ? (c.input || 0) + (c.output || 0) : Infinity, inCall = real.filter(f => f.cause.startsWith('cache') || f.cause === 'failed-call' || f.cause === 'error-loop' || f.cause === 'unused-tools');
126
+ const ts = inCall.reduce((s, f) => s + f.tokens, 0); if (ts > own && ts > 0) for (const f of inCall) { f.tokens *= own / ts; f.fullPrice *= own / ts; }
127
+ }
128
+ return out;
129
+ }
130
+
131
+ export function analyze(calls, opts = {}) {
132
+ const findings = [];
133
+ for (const sess of sessionsOf(calls).values()) findings.push(...analyzeSession(sess, opts));
134
+ return findings;
135
+ }
136
+ export { fresh };
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env node
2
+ // harness-ledger: where agent harnesses waste model resources, across harnesses. See README.md.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import zlib from 'node:zlib';
7
+ import readline from 'node:readline';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { importText, detect, IMPORTERS, tracelabCall } from '../src/importers.mjs';
10
+ import { dedupe } from '../src/record.mjs';
11
+ import { ledger, text, loadOutcomes } from '../src/ledger.mjs';
12
+ import { DEFAULT_PRICES } from '../src/prices.mjs';
13
+ import { html } from '../src/html.mjs';
14
+ import { demoInputs } from '../src/demo.mjs';
15
+ import { tasksFromSwebench, tasksFromRows, outcomeReport, outcomeText } from '../src/outcomes.mjs';
16
+ import { economics, economicsText } from '../src/economics.mjs';
17
+ import { fromRest as opencostRest, fromPrometheus as opencostProm, toSelfHostPrice } from '../src/opencost.mjs';
18
+
19
+ const HELP = `harness-ledger: where agent harnesses waste model resources (tokens, dollars, GPU time), across harnesses.
20
+
21
+ harness-ledger scan [--since 7d] [--claude DIR] [--codex DIR] find local Claude Code and Codex logs and report on them
22
+ harness-ledger report PATH… [options] report on logs, traces or exports (files or folders)
23
+ harness-ledger import PATH… [--format F] --out calls.jsonl convert to llm_call records (counts only, safe to share)
24
+ harness-ledger outcomes PATH… [--json] outcome-labelled task runs (SWE-bench per_instance_details.json,
25
+ or tasks as JSON/CSV): cost per success, spend on failures, call caps
26
+ harness-ledger economics PATH… [--outcomes FILE] [self-host options] [--json] cost per resolved task, fixes ranked by
27
+ what they save per resolved task, and self-host vs API
28
+ harness-ledger demo [--html FILE] [--json] three harnesses and a vLLM fleet, synthetic
29
+ harness-ledger formats what it reads
30
+
31
+ Inputs (detected from the file; --format to force):
32
+ claude-code Claude Code transcripts: ~/.claude/projects/<project>/*.jsonl (subagents included)
33
+ codex Codex CLI/IDE rollouts: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl
34
+ otel OpenTelemetry GenAI or OpenInference spans: OTLP JSON or one span per line (any instrumented harness)
35
+ langfuse Langfuse observation exports (JSON or JSON lines)
36
+ tracelab the TraceLab coding-agent trace (syfi_coding_trace.jsonl.gz: Claude Code and Codex, streamed)
37
+ calls.jsonl llm_call records written by "import"
38
+
39
+ Report options:
40
+ --prices FILE $/M tokens per model (input, cacheRead, cacheWrite, output, tier, downshift); defaults are examples;
41
+ --prices relative prices every model in the same units (cache read 0.1, write 1.25, output 5)
42
+ --engine FILE the serving engine's OTLP traces (vLLM llm_request spans) to charge self-hosted calls GPU time
43
+ --replicas FILE { "<pod>": { "gpus": 8, "gpuType": "H100", "rate": 2.5 } } or gpu-ledger usage records
44
+ --gpu-prices FILE gpu-ledger's price file, for replicas without a rate
45
+ --outcomes FILE session → success/failure (JSON object or CSV session,outcome): cost per successful task
46
+ --since 7d|ISO only calls after this --harness NAME label OTel/Langfuse input
47
+ --cache-ttl S (300) --big-result TOKENS (8000) --json --html FILE --calls-out FILE
48
+
49
+ Economics options (with the report options above):
50
+ --self-host-model ID --gpu ID an open model and GPU from the Inference Sizer catalog (deepseek-v3 on H200, …): the
51
+ same workload sized for the busiest day's peak (compute and KV working set)
52
+ --ttft MS (2000) --tpot MS (50) the targets it is sized for; --no-spare drops the sizer's spare node
53
+ --kv-offload [--cpu-kv-gb 375] [--pcie-gbs 64] hold the KV working set beyond HBM in host memory, reloaded over PCIe,
54
+ when a reload fits the TTFT target and PCIe has room
55
+ --calibration FILE measured engine efficiencies (fleetops calibrate, or a promoted shadow upgrade's
56
+ <store>/calibration/sizer.json) instead of spec-sheet defaults
57
+ --gpu-rate $/GPU-h what a GPU-hour costs you: monthly cost, which is cheaper, and the volume where it flips
58
+ --self-host-success-rate R the open model's task success rate (e.g. from SWE-bench); --api-success-rate R when
59
+ there are no outcomes; --token-scale K when the open model makes K× the calls per task
60
+ --self-host-price FILE measured self-host prices instead of sizing: { input, cacheRead?, output } $ per M tokens
61
+ --opencost FILE|URL OpenCost's measured cost per token instead: its /inferenceCost/total answer (a saved file,
62
+ or the OpenCost URL), or --opencost-prom URL for its llm_cost_per_million_tokens gauges;
63
+ --opencost-model NAME --opencost-namespace NS pick the deployment (allocation basis)
64
+ --days N | --tasks-per-day N the period the input covers, or the volume to plan for
65
+ --unit-price $ (with --prices relative) dollars per relative unit (a million fresh input tokens) for the break-even
66
+ --demo the synthetic demo input
67
+ `;
68
+
69
+ function args(argv) {
70
+ const o = { _: [] };
71
+ for (let i = 0; i < argv.length; i++) {
72
+ const a = argv[i];
73
+ if (a.startsWith('--')) { const [k, v] = a.slice(2).split('='); if (v != null) o[k] = v; else if (argv[i + 1] != null && !argv[i + 1].startsWith('--')) o[k] = argv[++i]; else o[k] = true; }
74
+ else o._.push(a);
75
+ }
76
+ return o;
77
+ }
78
+ const read = f => { const b = fs.readFileSync(f); return (f.endsWith('.gz') ? zlib.gunzipSync(b) : b).toString('utf8'); };
79
+ const readJson = f => JSON.parse(read(f));
80
+ function walk(p, out = []) {
81
+ const st = fs.statSync(p);
82
+ if (st.isDirectory()) { for (const e of fs.readdirSync(p)) if (!e.startsWith('.') || e === '.claude' || e === '.codex') walk(path.join(p, e), out); }
83
+ else if (/\.(jsonl|json|ndjson)(\.gz)?$/.test(p)) out.push(p);
84
+ return out;
85
+ }
86
+ function since(v) {
87
+ if (!v) return -Infinity;
88
+ const m = String(v).match(/^(\d+(?:\.\d+)?)([hdw])$/); if (m) return Date.now() / 1000 - Number(m[1]) * { h: 3600, d: 86400, w: 604800 }[m[2]];
89
+ const t = Date.parse(v); if (!Number.isFinite(t)) throw new Error(`--since: can't read ${v}`); return t / 1000;
90
+ }
91
+
92
+ // Large line-per-call traces (TraceLab is 650 MB inflated) are streamed instead of read whole.
93
+ async function streamLines(f, each) {
94
+ const s = fs.createReadStream(f), rl = readline.createInterface({ input: f.endsWith('.gz') ? s.pipe(zlib.createGunzip()) : s, crlfDelay: Infinity });
95
+ for await (const l of rl) { if (!l.trim()) continue; let o; try { o = JSON.parse(l); } catch { continue; } each(o); }
96
+ }
97
+ function head(f, n = 65536) {
98
+ const fd = fs.openSync(f, 'r'), b = Buffer.alloc(n), k = fs.readSync(fd, b, 0, n, 0); fs.closeSync(fd);
99
+ if (!f.endsWith('.gz')) return b.subarray(0, k).toString('utf8');
100
+ try { return zlib.gunzipSync(b.subarray(0, k), { finishFlush: zlib.constants.Z_SYNC_FLUSH }).toString('utf8'); } catch { return ''; }
101
+ }
102
+ async function load(paths, o) {
103
+ const files = paths.flatMap(p => walk(p)), calls = [], skipped = [];
104
+ for (const f of files) {
105
+ if ((o.format || detect(head(f), f)) === 'tracelab') { await streamLines(f, x => { const c = x && x.input_tokens_total != null && tracelabCall(x); if (c) calls.push(c); }); continue; }
106
+ const txt = read(f);
107
+ if (/^\s*\{"kind":"llm_call"/.test(txt)) { for (const l of txt.split(/\r?\n/)) if (l.trim()) calls.push(JSON.parse(l)); continue; }
108
+ const kind = o.format || detect(txt, f);
109
+ if (!kind) { skipped.push(f); continue; }
110
+ try { calls.push(...importText(txt, { kind, file: f, harness: o.harness })); } catch (e) { skipped.push(`${f} (${e.message})`); }
111
+ }
112
+ const from = since(o.since);
113
+ return { calls: dedupe(calls).filter(c => c.t == null || c.t >= from), files: files.length, skipped };
114
+ }
115
+
116
+ function report(calls, o, extra = {}) {
117
+ if (!calls.length) { process.stderr.write('harness-ledger: no model calls found in the input\n'); return 1; }
118
+ const opts = { prices: o.prices === 'relative' ? 'relative' : o.prices ? readJson(o.prices) : DEFAULT_PRICES, outcomes: extra.outcomes || loadOutcomes(o.outcomes ? read(o.outcomes) : null),
119
+ engineSpans: extra.engine || (o.engine ? read(o.engine) : null), replicas: extra.replicas || (o.replicas ? readJson(o.replicas) : null), gpuPrices: o['gpu-prices'] ? readJson(o['gpu-prices']) : {} };
120
+ if (o['cache-ttl']) opts.cacheTtlS = Number(o['cache-ttl']);
121
+ if (o['big-result']) opts.bigResultTokens = Number(o['big-result']);
122
+ const r = ledger(calls, opts);
123
+ if (o['calls-out']) fs.writeFileSync(o['calls-out'], r.calls.map(c => JSON.stringify(c)).join('\n') + '\n');
124
+ if (o.html) { fs.writeFileSync(o.html, html(r.report)); process.stderr.write(`wrote ${o.html}\n`); }
125
+ if (o.json) process.stdout.write(JSON.stringify({ ...r.report, findings: o.findings ? r.findings : undefined }, null, 2) + '\n');
126
+ else if (!o.html || o.text) process.stdout.write(text(r.report));
127
+ return 0;
128
+ }
129
+
130
+ export async function main(argv) {
131
+ const o = args(argv), [cmd, ...paths] = o._;
132
+ if (!cmd || o.help || cmd === 'help') { process.stdout.write(HELP); return 0; }
133
+ if (cmd === 'formats') { process.stdout.write(HELP.slice(HELP.indexOf('Inputs'), HELP.indexOf('Report options'))); return 0; }
134
+ if (cmd === 'demo') {
135
+ const d = demoInputs(), calls = d.files.flatMap(f => importText(f.text, { file: f.name }));
136
+ return report(calls, o, { engine: d.engine, replicas: d.replicas, outcomes: new Map(Object.entries(d.outcomes)) });
137
+ }
138
+ if (cmd === 'scan') {
139
+ const home = os.homedir(), dirs = [o.claude || path.join(process.env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'projects'), o.codex || path.join(process.env.CODEX_HOME || path.join(home, '.codex'), 'sessions')].filter(d => fs.existsSync(d));
140
+ if (!dirs.length) { process.stderr.write('harness-ledger scan: no ~/.claude/projects or ~/.codex/sessions here; pass --claude DIR or --codex DIR, or use "report PATH"\n'); return 1; }
141
+ const { calls, files, skipped } = await load(dirs, { ...o, since: o.since || '30d' });
142
+ process.stderr.write(`scanned ${files} files in ${dirs.join(', ')}${skipped.length ? `; ${skipped.length} not recognised` : ''}\n`);
143
+ return report(calls, o);
144
+ }
145
+ if (cmd === 'economics') {
146
+ let calls, extra = {};
147
+ if (o.demo) { const d = demoInputs(); calls = d.files.flatMap(f => importText(f.text, { file: f.name })); extra = { engine: d.engine, replicas: d.replicas, outcomes: new Map(Object.entries(d.outcomes)) }; }
148
+ else { if (!paths.length) { process.stderr.write('harness-ledger economics: give files or folders (or --demo)\n'); return 2; } ({ calls } = await load(paths, o)); }
149
+ if (!calls.length) { process.stderr.write('harness-ledger: no model calls found in the input\n'); return 1; }
150
+ const opts = { prices: o.prices === 'relative' ? 'relative' : o.prices ? readJson(o.prices) : DEFAULT_PRICES, outcomes: extra.outcomes || loadOutcomes(o.outcomes ? read(o.outcomes) : null),
151
+ engineSpans: extra.engine || (o.engine ? read(o.engine) : null), replicas: extra.replicas || (o.replicas ? readJson(o.replicas) : null), gpuPrices: o['gpu-prices'] ? readJson(o['gpu-prices']) : {} };
152
+ if (o['cache-ttl']) opts.cacheTtlS = Number(o['cache-ttl']);
153
+ const r = ledger(calls, opts), n = k => (o[k] != null && o[k] !== true ? Number(o[k]) : undefined);
154
+ let selfHostPrice = o['self-host-price'] ? readJson(o['self-host-price']) : null;
155
+ const ocPick = { model: o['opencost-model'] || null, namespace: o['opencost-namespace'] || null };
156
+ if (o.opencost) {
157
+ const src = String(o.opencost);
158
+ const j = /^https?:\/\//.test(src) ? await (await fetch(`${src.replace(/\/$/, '')}/inferenceCost/total?window=${o['opencost-window'] || '7d'}&aggregate=model_name,namespace&costBasis=allocation`)).json() : readJson(src);
159
+ selfHostPrice = toSelfHostPrice(opencostRest(j, ocPick));
160
+ } else if (o['opencost-prom']) selfHostPrice = toSelfHostPrice(await opencostProm(String(o['opencost-prom']), { ...ocPick, window: o['opencost-window'] || '24h' }));
161
+ const E = economics(r.calls, r.report, { model: o['self-host-model'] || undefined, gpu: o.gpu || undefined, ttft: n('ttft'), tpot: n('tpot'), gpuRate: n('gpu-rate'),
162
+ selfSuccessRate: n('self-host-success-rate'), apiSuccessRate: n('api-success-rate'), tokenScale: n('token-scale'), days: n('days'), tasksPerDay: n('tasks-per-day'), unitPrice: n('unit-price'),
163
+ selfHostPrice, cacheTtlS: opts.cacheTtlS, spare: !o['no-spare'], calibration: o.calibration ? readJson(o.calibration) : null, kvOffload: !!o['kv-offload'], cpuKvGB: n('cpu-kv-gb'), pcieGBs: n('pcie-gbs') });
164
+ process.stdout.write(o.json ? JSON.stringify(E, null, 1) + '\n' : economicsText(E));
165
+ return 0;
166
+ }
167
+ if (cmd === 'outcomes') {
168
+ if (!paths.length) { process.stderr.write('harness-ledger outcomes: give per_instance_details.json files, folders of them, or task JSON/CSV\n'); return 2; }
169
+ const tasks = [];
170
+ for (const f of paths.flatMap(p => walk(p)).concat(paths.flatMap(p => (fs.statSync(p).isDirectory() ? fs.readdirSync(p).filter(x => x.endsWith('.csv')).map(x => path.join(p, x)) : p.endsWith('.csv') ? [p] : [])))) {
171
+ const run = path.basename(f).replace(/\.(json|csv)(\.gz)?$/, '').replace(/^per_instance_details$/, path.basename(path.dirname(f)));
172
+ if (f.endsWith('.csv')) { const [h, ...ls] = read(f).trim().split(/\r?\n/); const ks = h.split(',').map(x => x.trim()); tasks.push(...tasksFromRows(ls.map(l => Object.fromEntries(l.split(',').map((v, i) => [ks[i], v.trim()]))), { run })); continue; }
173
+ const j = readJson(f);
174
+ if (Array.isArray(j)) { tasks.push(...tasksFromRows(j, { run })); continue; }
175
+ // a sibling metadata.yaml (SWE-bench experiments layout) names the model
176
+ const meta = [f.replace(/\.json$/, '.yaml'), path.join(path.dirname(f), 'metadata.yaml')].find(x => fs.existsSync(x));
177
+ const name = meta && (read(meta).match(/^\s*name:\s*(.+)$/m) || [])[1];
178
+ tasks.push(...tasksFromSwebench(j, { run, model: name ? name.trim() : null }));
179
+ }
180
+ const R = outcomeReport(tasks);
181
+ process.stdout.write(o.json ? JSON.stringify(R, null, 1) + '\n' : outcomeText(R));
182
+ return R.runs.length ? 0 : 1;
183
+ }
184
+ if (cmd === 'import' || cmd === 'report') {
185
+ if (!paths.length) { process.stderr.write(`harness-ledger ${cmd}: give files or folders\n`); return 2; }
186
+ if (o.format && !IMPORTERS[o.format]) { process.stderr.write(`--format: one of ${Object.keys(IMPORTERS).join(', ')}\n`); return 2; }
187
+ const { calls, files, skipped } = await load(paths, o);
188
+ if (skipped.length) process.stderr.write(`not recognised (pass --format): ${skipped.slice(0, 5).join(', ')}${skipped.length > 5 ? ` and ${skipped.length - 5} more` : ''}\n`);
189
+ if (cmd === 'report') return report(calls, o);
190
+ const body = calls.map(c => JSON.stringify(c)).join('\n') + (calls.length ? '\n' : '');
191
+ if (o.out) { fs.writeFileSync(o.out, body); process.stderr.write(`${calls.length} calls from ${files} files → ${o.out}\n`); } else process.stdout.write(body);
192
+ return 0;
193
+ }
194
+ process.stderr.write(`harness-ledger: unknown command "${cmd}"\n\n${HELP}`); return 2;
195
+ }
196
+
197
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
198
+ main(process.argv.slice(2)).then(c => { process.exitCode = c; }, e => { process.stderr.write(`harness-ledger: ${e.message}\n`); process.exitCode = 1; });
199
+ }
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+ // Agent unit economics on real data: the TraceLab trace's workload (8,058 Claude Code and Codex sessions over ten months,
3
+ // with real arrivals, prompt growth and the providers' cache accounting) against self-hosting open models, with task
4
+ // success rates and calls per task for those models from SWE-bench Verified (same scaffold, same 500 tasks).
5
+ //
6
+ // node tools/validate-economics.mjs [--file syfi_coding_trace.jsonl.gz] [--markdown|--json]
7
+ //
8
+ // Prices: the API side in relative units (fresh input 1, cache read 0.1, cache write 1.25, output 5 per million tokens)
9
+ // turned into dollars at a stated price per unit ($3: a Sonnet-class list price for fresh input). The self-host side
10
+ // is GPUs from the Inference Sizer; the result is the GPU-hour price under which self-hosting is cheaper, so no GPU
11
+ // price is assumed for it. Where a GPU price is needed (the volume at which self-hosting wins) the rates are stated.
12
+ import fs from 'node:fs';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { loadCalls } from './validate-tracelab.mjs';
15
+ import { fetchRuns, SOURCE as SWE } from './validate-swebench.mjs';
16
+ import { tasksFromSwebench } from '../src/outcomes.mjs';
17
+ import { ledger } from '../src/ledger.mjs';
18
+ import { economics } from '../src/economics.mjs';
19
+ import { tracelabFile, TRACELAB } from '../../fleetscope/tools/tracelab-data.mjs';
20
+
21
+ const API_RUN = 'Claude 4.5 Sonnet (high)', OPEN = [{ run: 'DeepSeek V3.2 (high)', model: 'deepseek-v3' }, { run: 'Kimi K2.5 (high)', model: 'kimi-k2' }];
22
+ const GPUS = ['H200', 'B200'], UNIT = 3, RATES = [2, 3, 4];
23
+
24
+ export function swebenchStats(runs) {
25
+ const by = Object.fromEntries(runs.map(r => { const ts = tasksFromSwebench(r.details, { run: r.run, model: r.model }); return [r.model, { rate: ts.filter(t => t.outcome === 'success').length / ts.length, calls: ts.reduce((a, t) => a + t.calls, 0) / ts.length, tasks: ts.length }]; }));
26
+ return by;
27
+ }
28
+
29
+ export async function run(file) {
30
+ const calls = await loadCalls(file), r = ledger(calls, { prices: 'relative' });
31
+ const swe = swebenchStats(fetchRuns()), api = swe[API_RUN];
32
+ const rows = [];
33
+ for (const o of OPEN) for (const gpu of GPUS) for (const tokenScale of [1, +(swe[o.run].calls / api.calls).toFixed(2)]) {
34
+ const base = { model: o.model, gpu, ttft: 2000, tpot: 50, unitPrice: UNIT, apiSuccessRate: api.rate, selfSuccessRate: swe[o.run].rate, tokenScale };
35
+ const E = economics(r.calls, r.report, base), S = E.selfHost;
36
+ const cross = RATES.map(rate => { const x = economics(r.calls, r.report, { ...base, gpuRate: rate }).selfHost; return { rate, burst: x.volume && x.volume.from, typical: x.volumeTypical && x.volumeTypical.from }; });
37
+ rows.push({ open: o.run, model: o.model, gpu, tokenScale, burstiness: S.peak.calls / Math.max(1, S.typicalDay ? S.typicalDay.calls : 1), gpus: S.gpus, typicalGpus: S.typicalDay && S.typicalDay.gpus, bound: S.bound, breakEven: S.breakEvenGpuRate, quality: S.qualityRatio, overContextShare: S.overContextShare, cross });
38
+ }
39
+ const E0 = economics(r.calls, r.report, {});
40
+ return { source: { tracelab: TRACELAB, swebench: SWE }, volume: E0.volume, fixes: E0.fixes.rows, api: { run: API_RUN, ...api }, open: OPEN.map(o => ({ ...o, ...swe[o.run] })), rows, unit: UNIT, rates: RATES };
41
+ }
42
+
43
+ const P = x => (x == null ? '–' : `${(100 * x).toFixed(x < 0.1 ? 1 : 0)}%`), $ = x => (x == null ? '–' : '$' + (x >= 0.1 ? x.toFixed(2) : x.toPrecision(2)));
44
+ const X = x => (x == null ? 'never (to 256×)' : `${x < 1 ? x.toFixed(2) : x.toFixed(1)}×`);
45
+ export function markdown(R) {
46
+ const v = R.volume, L = ['# Agent unit economics: self-hosting vs the API, on a real agent workload', '',
47
+ `Generated by \`node harness-ledger/tools/validate-economics.mjs --markdown\`. Workload: [TraceLab](https://github.com/uw-syfi/TraceLab) ${R.source.tracelab.release} (${R.source.tracelab.license}; ${R.source.tracelab.citation}), ${Math.round(v.days)} days of day-to-day Claude Code and Codex use: ${v.sessionsPerDay.toFixed(1)} sessions and ${Math.round(v.callsPerDay).toLocaleString('en-US')} model calls a day, with real arrivals, prompt growth and each provider's cache accounting. Task success and calls per task: SWE-bench Verified, mini-SWE-agent 2.x, one run per model (SWE-bench experiments at \`${R.source.swebench.commit.slice(0, 12)}\`).`, '',
48
+ `API cost is in relative units (fresh input 1, cache read 0.1, cache write 1.25, output 5 per million tokens) at **$${R.unit} per unit**, a Sonnet-class list price for fresh input; that comes to about $${Math.round(v.apiMonthly * R.unit).toLocaleString('en-US')} a month. The self-hosted side is the same workload sized by the Inference Sizer through FleetScope's agentic path (compute and the KV working set, at TTFT 2 s and TPOT 50 ms, for the busiest day's peak, whole 8-GPU nodes plus one spare) and kept on all month. Cost per resolved task scales by each model's SWE-bench resolution rate against ${R.api.run} (${P(R.api.rate)}).`, '',
49
+ '## The GPU-hour price under which self-hosting is cheaper', '',
50
+ '| Open model (SWE-bench resolved) | GPU | Calls per task vs the API model | GPUs: busiest day / typical day | **Break-even $/GPU-hour** | Calls over the model\'s context |', '| --- | --- | --- | --- | --- | --- |'];
51
+ for (const x of R.rows) { const o = R.open.find(y => y.run === x.open); L.push(`| ${x.open} (${P(o.rate)}) | ${x.gpu} | ${x.tokenScale === 1 ? 'same' : `${x.tokenScale}× (SWE-bench calls ratio)`} | ${x.gpus} / ${x.typicalGpus ?? '–'} | **${$(x.breakEven)}** | ${P(x.overContextShare)} |`); }
52
+ L.push('', `## The volume at which self-hosting wins, at a stated GPU-hour price`, '', `Volume as a multiple of this workload. "Own bursts" scales the trace as it is (its busiest day had about ${Math.round(R.rows[0].burstiness)}× its median day's calls); "typical" sizes on a median day's shape, as many teams' bursts that don't line up would look.`, '',
53
+ '| Open model | GPU | Calls per task | ' + R.rates.map(r => `$${r}/GPU-h: own bursts / typical`).join(' | ') + ' |', '| --- | --- | --- |' + R.rates.map(() => ' --- |').join(''));
54
+ for (const x of R.rows) L.push(`| ${x.open} | ${x.gpu} | ${x.tokenScale === 1 ? 'same' : x.tokenScale + '×'} | ${x.cross.map(c => `${X(c.burst)} / ${X(c.typical)}`).join(' | ')} |`);
55
+ L.push('', '## What it says', '',
56
+ `- **At one team's volume the API wins.** Self-hosting a frontier-size open model needs at least two whole nodes (one serving, one spare) whatever the load, so at this workload's volume it is cheaper only below the GPU-hour prices above, far under the $2–4 used in the volume table.`,
57
+ `- **The crossover is a volume, and bursts move it.** On B200 at $3/GPU-hour self-hosting wins from about ${X(R.rows.find(x => x.gpu === 'B200' && x.tokenScale === 1).cross.find(c => c.rate === 3).burst)} this volume with this team's bursts, or ${X(R.rows.find(x => x.gpu === 'B200' && x.tokenScale === 1).cross.find(c => c.rate === 3).typical)} if peaks were flatter. Pooling many teams onto one fleet is what makes self-hosting pay.`,
58
+ `- **Calls per task move the crossover, not the floor.** On SWE-bench DeepSeek V3.2 makes ${R.rows.find(x => x.model === 'deepseek-v3' && x.tokenScale !== 1).tokenScale}× the calls per task of ${R.api.run}. At one team's volume that changes nothing (the two-node floor carries it); at the volumes where self-hosting could win it pushes the crossover out, because the open model has to serve that many more calls for the same work.`,
59
+ `- **Context is a hard limit, not a cost.** ${P(R.rows[0].overContextShare)} of this workload's calls are longer than DeepSeek V3's or Kimi K2's 128k context. They are capped here, which flatters self-hosting: those sessions would need compaction, or a model with a longer context.`, '',
60
+ '## Fixes before any of this', '', `Avoidable spend in this workload (relative units, as in VALIDATION-TRACELAB.md), worth doing whichever way the model is served:`, '', '| Fix | Share of spend |', '| --- | --- |',
61
+ ...R.fixes.slice(0, 5).map(f => `| ${f.label} | ${P(f.share)} |`), '',
62
+ '## Limits', '', '- TraceLab has no task outcomes, so cost per resolved task uses SWE-bench resolution rates, from a different (benchmark) workload with one scaffold.', '- The open model is assumed to make as many calls per task as the API model unless a row says otherwise; the SWE-bench calls ratio is a proxy measured on a benchmark, with calls of the same shape.', '- Self-hosted cost is GPUs only (no power, staff or networking beyond the GPU-hour price), and the sizer\'s production defaults (whole nodes, one spare). `--no-spare` drops the spare.', '');
63
+ return L.join('\n');
64
+ }
65
+
66
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
67
+ const a = process.argv.slice(2), fi = a.indexOf('--file');
68
+ tracelabFile(fi >= 0 ? a[fi + 1] : undefined).then(run).then(R => console.log(a.includes('--json') ? JSON.stringify(R, null, 1) : markdown(R))).catch(e => { console.error(`validate-economics: ${e.message}`); process.exitCode = 1; });
69
+ }
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ // Cost per successful task, spend on failed tasks, and what call caps would save, on SWE-bench Verified runs of one agent
3
+ // scaffold (mini-SWE-agent 2.x) across models, from the SWE-bench experiments repository's per-instance results (cost,
4
+ // API calls, resolved). The data is fetched at a pinned commit and cached; it is not copied into this repository.
5
+ //
6
+ // node tools/validate-swebench.mjs [--markdown|--json]
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { execFileSync } from 'node:child_process';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { tasksFromSwebench, outcomeReport } from '../src/outcomes.mjs';
13
+
14
+ export const SOURCE = { repo: 'https://github.com/SWE-bench/experiments', commit: '40f164d5b8f1d249bf95a6df8b74b577fd8e519d', dir: 'evaluation/verified', match: /_mini-v2\.\d+\.\d+_/ };
15
+
16
+ export function fetchRuns(cache = path.join(os.homedir(), '.cache', 'aiinfra-tools', 'swebench', SOURCE.commit.slice(0, 12))) {
17
+ const index = path.join(cache, 'runs.json');
18
+ if (fs.existsSync(index)) return JSON.parse(fs.readFileSync(index, 'utf8'));
19
+ const repo = path.join(cache, 'repo'); fs.mkdirSync(repo, { recursive: true });
20
+ const git = (...a) => execFileSync('git', a, { cwd: repo, stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28, timeout: 900000 }).toString();
21
+ if (!fs.existsSync(path.join(repo, '.git'))) { git('init', '-q'); git('remote', 'add', 'origin', SOURCE.repo); }
22
+ git('fetch', '-q', '--depth', '1', '--filter=tree:0', 'origin', SOURCE.commit);
23
+ const runs = [];
24
+ for (const d of git('ls-tree', '--name-only', SOURCE.commit, SOURCE.dir + '/').split('\n').filter(x => SOURCE.match.test(x))) {
25
+ let details, meta = '';
26
+ try { details = JSON.parse(git('show', `${SOURCE.commit}:${d}/per_instance_details.json`)); } catch { continue; }
27
+ try { meta = git('show', `${SOURCE.commit}:${d}/metadata.yaml`); } catch { /* optional */ }
28
+ const name = (meta.match(/^\s*name:\s*(.+)$/m) || [])[1];
29
+ runs.push({ run: path.basename(d), model: name ? name.trim() : path.basename(d), details });
30
+ }
31
+ fs.rmSync(repo, { recursive: true, force: true });
32
+ fs.writeFileSync(index, JSON.stringify(runs));
33
+ return runs;
34
+ }
35
+
36
+ export function run(runs) { return outcomeReport(runs.flatMap(r => tasksFromSwebench(r.details, { run: r.run, model: r.model }))); }
37
+
38
+ const P = x => (x == null ? '–' : `${(100 * x).toFixed(0)}%`), D = x => (x == null ? '–' : x >= 1 ? `$${x.toFixed(2)}` : `$${x.toFixed(3)}`);
39
+ export function markdown(R) {
40
+ const L = ['# Cost per successful task on SWE-bench Verified', '',
41
+ `Generated by \`node harness-ledger/tools/validate-swebench.mjs --markdown\`. Data: per-instance results (cost, API calls, resolved) of ${R.runs.length} runs of mini-SWE-agent 2.x on SWE-bench Verified's 500 tasks, one run per model, from the [SWE-bench experiments repository](${SOURCE.repo}) at commit \`${SOURCE.commit.slice(0, 12)}\`.${R.skipped.length ? ` Skipped for missing outcomes or costs: ${R.skipped.join(', ')}.` : ''} Same scaffold and tasks, so the differences are the models'.`, '',
42
+ '| Model | Resolved | Cost per task | **Cost per resolved task** | Spend on unresolved tasks | Calls: resolved / unresolved (mean) | Best call cap losing ≤1 point |', '| --- | --- | --- | --- | --- | --- | --- |'];
43
+ for (const r of R.runs) L.push(`| ${r.model} | ${P(r.rate)} | ${D(r.costPerTask)} | **${D(r.costPerSuccess)}** | ${P(r.failShare)} | ${Math.round(r.calls.success.mean)} / ${Math.round(r.calls.failure.mean)} | ${r.best1pt ? `${r.best1pt.cap} calls: ${P(r.best1pt.saved)} saved, ${r.best1pt.rateLossPts.toFixed(1)} pts lost` : '–'} |`);
44
+ const p = R.pooled;
45
+ L.push('', '## What it says', '',
46
+ `- **Failed tasks take a large share of the spend.** The median run spends ${P(p.medianFailShare)} of its budget on tasks it doesn't resolve. That is the number "cost per task" hides and "cost per resolved task" shows.`,
47
+ `- **Failures don't stand out early by length.** Unresolved tasks take ${p.callsRatio.toFixed(2)}× the calls of resolved ones (median across runs). A cap on calls that loses at most one point of resolution rate saves a median of ${P(p.medianBest1ptSaved)}. Stopping failures early needs a signal other than step count (repeated failing tool calls, no progress on tests).`,
48
+ (() => { const top = Math.max(...R.runs.map(r => r.rate)), near = R.runs.filter(r => r.rate >= top - 0.05), lo = near.reduce((a, r) => (r.costPerSuccess < a.costPerSuccess ? r : a)), hi = near.reduce((a, r) => (r.costPerSuccess > a.costPerSuccess ? r : a));
49
+ return `- **The model is the big lever.** Among the runs within 5 points of the best resolution rate, cost per resolved task ranges from ${D(lo.costPerSuccess)} (${lo.model}, ${P(lo.rate)}) to ${D(hi.costPerSuccess)} (${hi.model}, ${P(hi.rate)}): ${(hi.costPerSuccess / lo.costPerSuccess).toFixed(0)}×. List prices and how many calls and tokens each model needs both count. Costs are as the runs recorded them (API list prices at the time).`; })(), '',
50
+ 'Cap estimates assume every call of a task costs the task\'s average. Later calls carry more context and cost more, so real savings from a cap are somewhat larger than shown; a resolved task that needed more calls than the cap is counted as lost.', '');
51
+ return L.join('\n');
52
+ }
53
+
54
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
55
+ const R = run(fetchRuns());
56
+ console.log(process.argv.includes('--json') ? JSON.stringify(R, null, 1) : markdown(R));
57
+ }
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ // harness-ledger on real coding-agent use: the public TraceLab trace (8,058 Claude Code and Codex sessions, 665,453 model
3
+ // calls, with the providers' own cache accounting). Reports where the tokens went by cause and harness, how the prompt
4
+ // cache behaves as the pause between calls grows (the evidence behind the cache-expired check), and how much the totals
5
+ // move with the two thresholds that matter most.
6
+ //
7
+ // node tools/validate-tracelab.mjs [--file syfi_coding_trace.jsonl.gz] [--markdown|--json]
8
+ import fs from 'node:fs';
9
+ import zlib from 'node:zlib';
10
+ import readline from 'node:readline';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { tracelabCall } from '../src/importers.mjs';
13
+ import { dedupe, sessionsOf } from '../src/record.mjs';
14
+ import { ledger } from '../src/ledger.mjs';
15
+ import { tracelabFile, TRACELAB } from '../../fleetscope/tools/tracelab-data.mjs';
16
+
17
+ export async function loadCalls(file) {
18
+ const s = fs.createReadStream(file), rl = readline.createInterface({ input: file.endsWith('.gz') ? s.pipe(zlib.createGunzip()) : s, crlfDelay: Infinity });
19
+ const out = [];
20
+ for await (const l of rl) { if (!l.trim()) continue; const c = tracelabCall(JSON.parse(l)); if (c) out.push(c); }
21
+ return dedupe(out);
22
+ }
23
+
24
+ // share of calls that read ≥90% of the previous context from cache, by the pause before them (one model chain per session)
25
+ export function cacheByGap(calls, bins = [[0, 60], [60, 300], [300, 600], [600, 1800], [1800, 3600], [3600, Infinity]]) {
26
+ const st = {};
27
+ for (const cs of sessionsOf(calls).values()) {
28
+ const chains = new Map(); for (const c of cs) { const k = c.model; if (!chains.has(k)) chains.set(k, []); chains.get(k).push(c); }
29
+ for (const ch of chains.values()) for (let i = 1; i < ch.length; i++) {
30
+ const p = ch[i - 1], c = ch[i];
31
+ if (c.input < p.input * 0.5 || p.input < 4096 || c.cacheRead == null) continue;
32
+ const g = c.t - (p.t + (p.durS || 0)), b = bins.findIndex(([a, z]) => g >= a && g < z); if (b < 0) continue;
33
+ const k = `${c.harness}|${b}`; st[k] = st[k] || { harness: c.harness, from: bins[b][0], to: bins[b][1], n: 0, hit: 0 };
34
+ st[k].n++; if (c.cacheRead >= 0.9 * Math.min(p.input, c.input)) st[k].hit++;
35
+ }
36
+ }
37
+ return Object.values(st).sort((a, b) => a.harness.localeCompare(b.harness) || a.from - b.from);
38
+ }
39
+
40
+ export async function run(file) {
41
+ const calls = await loadCalls(file);
42
+ const base = ledger(calls.map(c => ({ ...c, toolCalls: c.toolCalls.map(t => ({ ...t })) })), { prices: 'relative' }).report;
43
+ const alt = ledger(calls.map(c => ({ ...c, toolCalls: c.toolCalls.map(t => ({ ...t })) })), { prices: 'relative', cacheTtlS: 3600, bigResultTokens: 20000 }).report;
44
+ return { source: TRACELAB, report: base, sensitivity: { cacheTtlS: 3600, bigResultTokens: 20000, avoidableShare: alt.totals.avoidableShare, byCause: alt.byCause.map(c => ({ cause: c.cause, cost: c.cost, findings: c.findings })) }, cacheByGap: cacheByGap(calls) };
45
+ }
46
+
47
+ const P = x => (x == null ? '–' : `${(100 * x).toFixed(x < 0.1 ? 1 : 0)}%`), N = n => (n >= 1e9 ? (n / 1e9).toFixed(2) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'k' : String(Math.round(n)));
48
+ const span = (a, z) => (z === Infinity ? `over ${a / 60} min` : a < 60 ? `under ${z} s` : `${a < 120 ? a + ' s' : a / 60 + ' min'}–${z / 60} min`);
49
+ export function markdown(R) {
50
+ const r = R.report, t = r.totals;
51
+ const L = ['# harness-ledger on real coding-agent use (TraceLab)', '',
52
+ `Generated by \`node harness-ledger/tools/validate-tracelab.mjs --markdown\`. Data: [TraceLab](https://github.com/uw-syfi/TraceLab) ${R.source.release} (${R.source.license}; ${R.source.citation}): ${t.sessions.toLocaleString('en-US')} sessions and ${t.calls.toLocaleString('en-US')} model calls of day-to-day Claude Code and Codex use, with each provider's own cache accounting and the tool calls (names, result sizes, errors). Costs are in relative units (\`--prices relative\`: fresh input 1, cache read 0.1, cache write 1.25, output 5 per million tokens), so harnesses and models compare on the same footing; real prices change the scale, not the shape.`, '',
53
+ `**${P(t.avoidableShare)} of the spend was avoidable.** ${N(t.tokens)} tokens were processed, ${P(t.cacheRead / t.input)} of input from the prompt cache. The avoidable part is ${N(t.avoidableFullPrice)} tokens processed at full price and ${N(t.avoidableTokens - t.avoidableFullPrice)} tokens of context re-read from cache.`, '',
54
+ '| Cause | Share of avoidable cost | Findings | Tokens at full price | Context re-read |', '| --- | --- | --- | --- | --- |',
55
+ ...r.byCause.filter(c => !c.candidate).map(c => `| ${c.label} | ${P(c.cost / t.avoidableCost)} | ${c.findings.toLocaleString('en-US')} | ${N(c.fullPrice)} | ${N(c.tokens - c.fullPrice)} |`), '',
56
+ '| Harness | Sessions | Avoidable share of its cost | Input from cache |', '| --- | --- | --- | --- |',
57
+ ...r.byHarness.map(h => `| ${h.harness} | ${h.sessions.toLocaleString('en-US')} | ${P(h.avoidableCost / h.cost)} | ${P(h.cacheHit)} |`), '',
58
+ '## The prompt cache after a pause', '', 'Share of calls that read at least 90% of the previous context from cache, by the pause before the call (contexts over 4k tokens; compactions excluded):', '',
59
+ '| Pause | ' + [...new Set(R.cacheByGap.map(x => x.harness))].join(' | ') + ' |', '| --- |' + [...new Set(R.cacheByGap.map(x => x.harness))].map(() => ' --- |').join('')];
60
+ const hs = [...new Set(R.cacheByGap.map(x => x.harness))], spans = [...new Set(R.cacheByGap.map(x => x.from))].sort((a, b) => a - b);
61
+ for (const f of spans) { const row = hs.map(h => { const x = R.cacheByGap.find(y => y.harness === h && y.from === f); return x ? `${P(x.hit / x.n)} (${x.n.toLocaleString('en-US')})` : '–'; }); const any = R.cacheByGap.find(y => y.from === f); L.push(`| ${span(f, any.to)} | ${row.join(' | ')} |`); }
62
+ L.push('', 'Claude Code\'s hit rate falls by about half once the pause passes five minutes (the default cache lifetime) and to almost nothing after an hour; Codex decays more gradually. That is what the cache-expired check measures: pauses where the context had to be prefilled again. Whether all of it is avoidable depends on what keeping the cache costs: a one-hour cache write is priced at 2× input against 1.25× for five minutes, which pays back on the first re-read after a pause of 5–60 minutes.', '',
63
+ '## Tools behind the oversized output', '', '| Tool | Results over the threshold | Context re-read because of them |', '| --- | --- | --- |',
64
+ ...r.byTool.filter(x => x.cause === 'tool-output-bloat').slice(0, 8).map(x => `| ${x.tool} | ${x.count.toLocaleString('en-US')} | ${N(x.tokens)} |`), '',
65
+ '## How much the thresholds matter', '',
66
+ `With a one-hour cache lifetime instead of five minutes, and 20k tokens instead of 8k as the oversized-output threshold, the avoidable share is ${P(R.sensitivity.avoidableShare)} (vs ${P(t.avoidableShare)}): most of what was "expired" is then counted as plain cache misses, and fewer tool results count as oversized. The total barely moves; which label it gets depends on what you assume the provider's cache lifetime is.`, '',
67
+ '## What this trace can\'t show', '', '- TraceLab records tool names and result sizes but not arguments, so repeated tool calls can\'t be detected.', '- It doesn\'t record the tool definitions sent with each call (unused tools) or task outcomes (cost per successful task); see VALIDATION-SWEBENCH.md for outcomes.', '');
68
+ return L.join('\n');
69
+ }
70
+
71
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
72
+ const a = process.argv.slice(2), fi = a.indexOf('--file');
73
+ tracelabFile(fi >= 0 ? a[fi + 1] : undefined).then(run).then(R => console.log(a.includes('--json') ? JSON.stringify(R, null, 1) : markdown(R))).catch(e => { console.error(`validate-tracelab: ${e.message}`); process.exitCode = 1; });
74
+ }