aiinfra-tools 0.3.0 → 0.5.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 (65) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +43 -0
  3. package/bin/aiinfra.mjs +12 -0
  4. package/fleetops/deploy/grafana-dashboard.json +71 -0
  5. package/fleetops/deploy/shadow-live/README.md +8 -0
  6. package/fleetops/deploy/shadow-live/kit.yaml +2 -0
  7. package/fleetops/deploy/shadow-live/run.sh +6 -1
  8. package/fleetops/docs/SHADOW.md +25 -2
  9. package/fleetops/package.json +1 -1
  10. package/fleetops/src/api.mjs +8 -0
  11. package/fleetops/src/ingest.mjs +9 -2
  12. package/fleetops/src/schema.mjs +3 -0
  13. package/fleetops/src/serving.mjs +11 -1
  14. package/fleetops/src/shadow-quality.mjs +107 -0
  15. package/fleetops/src/shadow.mjs +12 -6
  16. package/fleetops/tools/cmd/help.mjs +4 -1
  17. package/fleetops/tools/cmd/shadow.mjs +14 -2
  18. package/fleetscope/build.mjs +4 -0
  19. package/fleetscope/dist/index.html +809 -4
  20. package/fleetscope/package.json +1 -1
  21. package/fleetscope/src/engine.js +19 -2
  22. package/fleetscope/src/index.src.html +23 -1
  23. package/gpu-health/package.json +1 -1
  24. package/gpu-ledger/package.json +1 -1
  25. package/harness-ledger/README.md +48 -0
  26. package/harness-ledger/integrations/README.md +11 -0
  27. package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
  28. package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
  29. package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
  30. package/harness-ledger/package.json +1 -1
  31. package/harness-ledger/src/advise.mjs +410 -0
  32. package/harness-ledger/src/assess.mjs +66 -0
  33. package/harness-ledger/src/doctor.mjs +202 -0
  34. package/harness-ledger/src/engine-metrics.mjs +35 -0
  35. package/harness-ledger/src/importers.mjs +14 -3
  36. package/harness-ledger/src/lint.mjs +115 -0
  37. package/harness-ledger/src/mooncake.mjs +83 -0
  38. package/harness-ledger/src/profile.mjs +164 -0
  39. package/harness-ledger/src/record.mjs +2 -2
  40. package/harness-ledger/src/suggest.mjs +177 -0
  41. package/harness-ledger/src/trajectory.mjs +81 -0
  42. package/harness-ledger/src/workload-demo.mjs +100 -0
  43. package/harness-ledger/tools/harness-ledger.mjs +224 -5
  44. package/hybrid-tracing/package.json +1 -1
  45. package/inference-sizer/build.mjs +1 -0
  46. package/inference-sizer/dist/index.html +192 -17
  47. package/inference-sizer/docs/CATALOG.md +71 -0
  48. package/inference-sizer/docs/METHOD.md +1 -1
  49. package/inference-sizer/package.json +1 -1
  50. package/inference-sizer/src/accelerators.js +23 -1
  51. package/inference-sizer/src/catalog.js +49 -3
  52. package/inference-sizer/src/index.src.html +7 -0
  53. package/inference-sizer/src/model.js +29 -9
  54. package/inference-sizer/src/suggest.js +70 -0
  55. package/inference-sizer/src/ui.js +14 -4
  56. package/inference-sizer/tools/validate-agentx.mjs +8 -2
  57. package/inference-sizer/tools/validate-inferencex.mjs +1 -1
  58. package/mcp/README.md +3 -0
  59. package/mcp/server.mjs +22 -0
  60. package/package.json +3 -1
  61. package/schemas/README.md +3 -0
  62. package/schemas/commands.mjs +7 -0
  63. package/schemas/harness-ledger.advise.schema.json +1102 -0
  64. package/schemas/harness-ledger.assess.schema.json +2823 -0
  65. package/schemas/harness-ledger.suggest.schema.json +326 -0
@@ -0,0 +1,410 @@
1
+ // The optimizer: ask for a metric (TTFT, TPOT, end-to-end latency, cost, GPUs, throughput) and get every change across
2
+ // the stack that moves it, each priced by the same models the other tools use, then the best combination, and a dry run
3
+ // of any set of changes before anything ships.
4
+ //
5
+ // Layers and levers (each applies only where the traces show it can matter):
6
+ // prompt prompt-layout every cache miss the waste checks attribute to a broken prefix becomes a hit
7
+ // cache cache-lifetime misses after a pause past the cache lifetime become hits (1-hour writes on APIs,
8
+ // KV offload or retention on self-hosted engines)
9
+ // harness tool-output-cap oversized tool results trimmed before they enter the context, and every later call
10
+ // re-sends less
11
+ // unused-tools tool definitions loaded on demand instead of sent with every call
12
+ // context compact-cold compaction after pauses past the cache lifetime, when the next call is cold anyway
13
+ // agent step-cap stop sessions after N calls (only with outcomes: it costs successes, counted exactly)
14
+ // model output-budget reasoning effort or output caps on the reasoning class (costs quality: gate it)
15
+ // model-alt another model from the catalog (--alt-models; quality: gate it)
16
+ // model options (self-hosted) fp8-weights / fp4-weights, fp8-kv, spec-decode (speculative decoding: MTP or a draft)
17
+ // serving prefix-routing requests routed to the replica holding their prefix (when the engine's own hit rate
18
+ // trails what the traces could reuse); disaggregate (prefill/decode split)
19
+ // GPU gpu-<id> the same number of GPUs of another type; add-replica one more instance
20
+ // scheduling priority interactive classes ahead of batch (non-preemptive priority queueing)
21
+ // batch-offpeak batch traffic moved out of the peak (and a batch discount where the provider has one)
22
+ //
23
+ // Workload levers transform the recorded calls themselves (trace-level), so cost, token mix, cache hit rate and the
24
+ // peak the fleet must serve all come from the changed trace. Serving levers change the Inference Sizer's inputs. Every
25
+ // scenario is then measured the same way:
26
+ // hosted API cost from the calls' prices; latency from a fit of each call's duration to its fresh input, cached input
27
+ // and output tokens (when the trace has durations and the fit explains them)
28
+ // self-hosted the sizer's operating point at the fleet's size and the busiest minute's arrival rate: TTFT, TPOT and
29
+ // end-to-end latency, how close to saturation, the GPUs needed to meet the targets (compute and the KV
30
+ // working set, from FleetScope's agentic sizing), and cost from the GPU-hour price
31
+ // Everything is a model: the dry run says what to expect, and the shadow test and quality gate check it before rollout.
32
+ import { createRequire } from 'node:module';
33
+ import { sessionsOf, fresh } from './record.mjs';
34
+ import { costWith } from './prices.mjs';
35
+ import { rowsOf, sizerSettings, busiestDay, period, exactCaps } from './economics.mjs';
36
+ import { classify } from './profile.mjs';
37
+
38
+ const require = createRequire(import.meta.url);
39
+ const A = require('../../fleetscope/src/agentic.js'), M = require('../../inference-sizer/src/model.js'), CAT = require('../../inference-sizer/src/catalog.js');
40
+ const HOURS = 730;
41
+ const sum = (xs, f) => xs.reduce((a, x) => a + (f(x) || 0), 0);
42
+
43
+ export const GOALS = {
44
+ ttft: { label: 'TTFT', unit: 'ms', lower: true }, tpot: { label: 'TPOT', unit: 'ms', lower: true }, e2e: { label: 'end-to-end latency', unit: 'ms', lower: true },
45
+ cost: { label: 'cost per month', unit: '$', lower: true }, gpus: { label: 'GPUs to meet the targets', unit: '', lower: true }, throughput: { label: 'peak requests/s the fleet can serve', unit: 'req/s', lower: false },
46
+ };
47
+ export const DEFAULTS = { cacheTtlS: 300, toolKeep: 1500, bigResult: 8000, compactKeep: 0.2, compactMin: 8000, outputCut: 0.3, specAccept: 0.7, specTokens: 3, batchDiscount: 0, onehourWritePremium: 0.75 };
48
+
49
+ // ---------- the API latency model: duration ≈ a + b·fresh + c·cached + d·output, fitted on the calls ----------
50
+ function solve(X, y) { // least squares by normal equations (few features)
51
+ const k = X[0].length, A2 = Array.from({ length: k }, () => new Float64Array(k + 1));
52
+ for (let i = 0; i < X.length; i++) for (let a = 0; a < k; a++) { for (let b = 0; b < k; b++) A2[a][b] += X[i][a] * X[i][b]; A2[a][k] += X[i][a] * y[i]; }
53
+ for (let c = 0; c < k; c++) { let p = c; for (let r = c + 1; r < k; r++) if (Math.abs(A2[r][c]) > Math.abs(A2[p][c])) p = r; [A2[c], A2[p]] = [A2[p], A2[c]]; if (Math.abs(A2[c][c]) < 1e-12) return null;
54
+ for (let r = 0; r < k; r++) if (r !== c) { const f = A2[r][c] / A2[c][c]; for (let j = c; j <= k; j++) A2[r][j] -= f * A2[c][j]; } }
55
+ return A2.map((row, i) => row[k] / row[i]);
56
+ }
57
+ // Prefilled tokens are everything not read from the cache (cache writes are prefilled too). When the trace records time
58
+ // to first token (ttftS), TTFT is fitted on it directly; otherwise on the whole duration, whose input part is the TTFT.
59
+ export const prefilled = c => Math.max(0, (c.input || 0) - (c.cacheRead || 0));
60
+ export function fitLatency(calls) {
61
+ const direct = calls.filter(c => c.ttftS > 0 && !c.error && Number.isFinite(c.ttftS)).length >= 30;
62
+ const y0 = c => (direct ? c.ttftS : c.durS);
63
+ const rows = calls.filter(c => y0(c) > 0 && !c.error && Number.isFinite(y0(c)));
64
+ if (rows.length < 30) return { ok: false, why: `${rows.length} calls with durations (need 30)` };
65
+ let feats = direct ? ['fresh', 'cached'] : ['fresh', 'cached', 'output'], tied = false;
66
+ const val = (c, f) => (f === 'fresh' ? prefilled(c) + (tied ? 0.1 * (c.cacheRead || 0) : 0) : f === 'cached' ? c.cacheRead || 0 : c.output || 0) / 1000;
67
+ for (let tries = 0; tries < 3; tries++) {
68
+ const X = rows.map(c => [1, ...feats.map(f => val(c, f))]), y = rows.map(y0), b = solve(X, y);
69
+ if (!b) return { ok: false, why: 'durations don\'t vary with tokens' };
70
+ const neg = feats.filter((f, i) => b[i + 1] < 0);
71
+ if (neg.length) { feats = feats.filter(f => !neg.includes(f)); continue; }
72
+ // a cached token can't take longer than a fresh one: if the fit says so, the two are confounded (long sessions are
73
+ // both cached and slow); fall back to cached tokens at a tenth of a fresh one's time
74
+ const fi = feats.indexOf('fresh'), ci = feats.indexOf('cached');
75
+ if (fi >= 0 && ci >= 0 && b[ci + 1] > b[fi + 1]) { feats = feats.filter(f => f !== 'cached'); tied = true; continue; }
76
+ const mean = y.reduce((a, v) => a + v, 0) / y.length, pred = X.map(x => x.reduce((a, v, i) => a + v * b[i], 0));
77
+ const ss = y.reduce((a, v, i) => a + (v - pred[i]) ** 2, 0), st = y.reduce((a, v) => a + (v - mean) ** 2, 0), r2 = st ? 1 - ss / st : 0;
78
+ const coef = Object.fromEntries([['base', b[0]], ...feats.map((f, i) => [f, b[i + 1] / 1000])]); // seconds per token
79
+ if (tied && coef.fresh != null) coef.cached = coef.fresh * 0.1;
80
+ if (direct) { // the output rate from durations, when they are there too
81
+ const d = calls.filter(c => c.durS > c.ttftS && c.output > 0 && !c.error);
82
+ coef.output = d.length >= 30 ? d.reduce((a, c) => a + (c.durS - c.ttftS), 0) / d.reduce((a, c) => a + c.output, 0) : null;
83
+ }
84
+ return { ok: r2 >= 0.3, r2, n: rows.length, coef, tied, source: direct ? 'ttft' : 'duration', why: r2 >= 0.3 ? null : `durations are explained poorly by token counts (R² ${r2.toFixed(2)})` };
85
+ }
86
+ return { ok: false, why: 'no stable fit' };
87
+ }
88
+
89
+ // ---------- the self-hosted operating point at a fleet size ----------
90
+ const memo = new Map();
91
+ function planOf(s) {
92
+ const k = JSON.stringify([s.modelId, s.gpuId, s.wprec, s.kvprec, s.avgIn, s.peakIn, s.avgOut, s.peakOut, s.prefixHit, s.ttft, s.tpot, s.dau, s.mode, s.ctx]);
93
+ if (!memo.has(k)) { if (memo.size > 2000) memo.clear(); memo.set(k, M.plan(s, { noSens: true })); }
94
+ return memo.get(k);
95
+ }
96
+ // cfg: the deployment's layout (TP/EP per instance). A fleet keeps its layout when the workload changes; only a change of
97
+ // model, GPU or precision picks a new one.
98
+ export function layoutFor(s) {
99
+ const md = M.derive(s), r = planOf(s);
100
+ return (r.agg.best && r.agg.best.c) || M.configs(s, md).find(cf => M.memInfo(s, md, cf).fitsW) || null;
101
+ }
102
+ export function atFleet(s, gpus, lam, cfg = null) {
103
+ const md = M.derive(s), c = cfg || layoutFor(s);
104
+ if (!c) return { fits: false };
105
+ const N = Math.max(1, Math.floor(gpus / c.g)), li = lam / N, mi = M.memInfo(s, md, c), cap = Math.max(1, Math.floor(M.decodeCap(s, md, c, mi)));
106
+ const thr = B => { const o = M.operatingPoint(s, md, c, B); return { o, lam: B / (s.avgOut * o.tpot + o.ttft) }; };
107
+ const top = thr(cap);
108
+ if (!(top.lam >= li)) return { fits: true, saturated: true, util: li / top.lam, N, g: c.g, gpus: N * c.g, maxRps: top.lam * N };
109
+ let lo = 1, hi = cap; while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (thr(mid).lam >= li) hi = mid; else lo = mid; }
110
+ const B = thr(lo).lam >= li ? lo : hi, { o } = thr(B), ps = M.prefillStats(s, md, c);
111
+ const rho = Math.min(0.85, o.prefillShare), wait = rho * (Math.min(s.avgIn, s.ctx) / ps.cap) / (2 * (1 - rho));
112
+ return { fits: true, saturated: false, ttft: o.ttft, tpot: o.tpot, e2e: o.ttft + s.avgOut * o.tpot, B, N, g: c.g, gpus: N * c.g, util: li / top.lam, maxRps: top.lam * N, prefillShare: o.prefillShare, wait, step: o.step, label: M.decodeLabel(c) };
113
+ }
114
+ // speculative decoding: k drafted tokens verified in one step; E accepted per step at acceptance α. A memory-bound step
115
+ // barely grows with k+1 tokens; a compute-bound one grows with them. The draft itself costs a little (MTP heads: a layer).
116
+ export function specFactor(st, { accept = 0.7, tokens = 3 } = {}) {
117
+ const E = (1 - accept ** (tokens + 1)) / (1 - accept), base = Math.max(st.tm, st.tc) + st.comm + st.ovh;
118
+ const t = Math.max(st.tm * 1.05, st.tc * (tokens + 1)) + st.comm + st.ovh + 0.05 * Math.max(st.tm, st.tc);
119
+ return { E, factor: t / E / base };
120
+ }
121
+
122
+ // ---------- scenarios ----------
123
+ const clone = calls => calls.map(c => ({ ...c }));
124
+ function priceOf(c) { return c.price || null; }
125
+ export function measure(calls, S, ctx) {
126
+ const P = period(calls, ctx.days), mon = x => x / P.days * 30.4;
127
+ const callCost = c => { const p = priceOf(c); return (p ? costWith(c, p) : c.cost || 0) * (c.discount ? 1 - c.discount : 1) + (c.extraCost || 0); };
128
+ const inp = sum(calls, c => c.input), cached = sum(calls, c => c.cacheRead);
129
+ const m = { calls: calls.length, freshPerCall: sum(calls, fresh) / Math.max(1, calls.length), inputPerCall: inp / Math.max(1, calls.length), outputPerCall: sum(calls, c => c.output) / Math.max(1, calls.length), cacheHit: inp ? cached / inp : 0 };
130
+ if (S.mode === 'api') {
131
+ m.cost = mon(sum(calls, callCost));
132
+ if (ctx.latency && ctx.latency.ok) {
133
+ const L = ctx.latency.coef, live = calls, n = Math.max(1, live.length); // no shared fleet: moving batch doesn't change API latency
134
+ const first = c => L.base + (L.fresh || 0) * prefilled(c) + (L.cached || 0) * (c.cacheRead || 0);
135
+ m.ttft = 1000 * sum(live, first) / n; m.e2e = 1000 * sum(live, c => first(c) + (L.output || 0) * (c.output || 0)) / n; m.tpot = L.output ? 1000 * L.output : null;
136
+ }
137
+ return m;
138
+ }
139
+ // self-hosted: the busiest day's peak minute, from the changed calls (off-peak batch excluded from the peak)
140
+ // token mix from every call; arrival rate from the calls still in the peak (moving batch changes when, not what)
141
+ const s0 = Object.assign({}, ctx.settings(S)), all = rowsOf(calls), day = busiestDay(all), st0 = A.workloadStats(day, { cacheTtlS: ctx.cacheTtlS });
142
+ if (!st0) return m;
143
+ let st = st0;
144
+ if (calls.some(c => c.offpeak)) { const live = busiestDay(rowsOf(calls.filter(c => !c.offpeak))), sl = live.length ? A.workloadStats(live, { cacheTtlS: ctx.cacheTtlS }) : null; st = Object.assign({}, st0, { rps: sl ? sl.rps : { mean: 0, p50: 0, p95: 0, max: 0 } }); }
145
+ const hit = S.hitOverride != null ? S.hitOverride : S.hitScale != null ? st.cacheHit * S.hitScale : st.cacheHit;
146
+ const stats = Object.assign({}, st, { cacheHit: hit });
147
+ const s = Object.assign({}, s0, { avgIn: Math.round(st.isl.mean), peakIn: Math.round(st.isl.p99), avgOut: Math.round(st.osl.mean), peakOut: Math.round(st.osl.p99), ctx: Math.max(s0.ctx || 0, Math.round(st.isl.p99 + st.osl.p99)),
148
+ prefixHit: Math.round(100 * hit), concSource: 'dau', dau: Math.max(1, st.rps.p95 * 86400), rpu: 1, peakFactor: 1, mode: S.disagg ? 'disagg' : s0.mode });
149
+ const need = A.sizeFor(stats, s, M, { kvOffload: !!S.kvOffload });
150
+ m.gpus = need.gpus; m.bound = need.bound; m.cacheHit = hit; // the engine's hit rate is what the fleet serves
151
+ const gpus = S.gpus || ctx.fleetGpus || need.gpus;
152
+ const hw = [s.modelId, s.gpuId, s.wprec, s.kvprec].join('|');
153
+ if (!ctx.layouts.has(hw)) ctx.layouts.set(hw, layoutFor(s));
154
+ const op = gpus ? atFleet(s, gpus + (S.addGpus || 0), st.rps.p95, ctx.layouts.get(hw)) : { fits: false };
155
+ m.fleetGpus = op.gpus ?? gpus; m.rps = st.rps.p95; m.instanceGpus = op.g || null;
156
+ if (op.fits && !op.saturated) {
157
+ let tpot = op.tpot, ttft = op.ttft;
158
+ if (S.spec) { const sf = specFactor(op.step, S.spec); tpot *= sf.factor; m.specAccepted = sf.E; }
159
+ // interactive classes first: their queue wait shrinks with only their own load ahead of them
160
+ if (S.priority && ctx.interactiveShare > 0 && ctx.interactiveShare < 1) { const rho = Math.min(0.85, op.prefillShare), rh = rho * ctx.interactiveShare; ttft = ttft - op.wait + op.wait * (1 - rho) / (1 - rh); m.ttftScope = 'interactive classes'; }
161
+ m.ttft = 1000 * ttft; m.tpot = 1000 * tpot; m.e2e = 1000 * (ttft + s.avgOut * tpot); m.util = op.util; m.throughput = op.maxRps; m.layout = op.label;
162
+ } else if (op.saturated) { m.saturated = true; m.util = op.util; m.throughput = op.maxRps; }
163
+ const rate = S.gpuRate ?? ctx.gpuRate ?? (ctx.gpuPrice(S.gpu) || null);
164
+ // cost: the GPUs this workload needs at the targets (a change that needs fewer GPUs lets the fleet shrink), or the
165
+ // fleet plus what a change adds; latency is measured at the fleet as it is
166
+ const billed = S.addGpus ? m.fleetGpus : need.gpus;
167
+ m.cost = rate != null && billed ? billed * rate * HOURS : null;
168
+ m.layout = m.layout || null;
169
+ return m;
170
+ }
171
+
172
+ // ---------- levers ----------
173
+ const per = (findings, causes) => { const m = new Map(); for (const f of findings) if (causes.includes(f.cause)) { const a = m.get(f.at) || []; a.push(f); m.set(f.at, a); } return m; };
174
+ function chainsOf(calls) { return [...sessionsOf(calls).values()]; }
175
+ export function LEVERS(ctx) {
176
+ const L = [], add = l => L.push(l), api = ctx.mode === 'api';
177
+ const missBy = per(ctx.findings, ['cache-miss']), expBy = per(ctx.findings, ['cache-expired']);
178
+ add({ id: 'prompt-layout', layer: 'prompt', title: 'Keep the prompt prefix byte-identical within a session (static first, dynamic last)', risk: 'none', effort: 'code',
179
+ applies: () => (missBy.size ? true : 'no cache misses from a broken prefix in these calls'),
180
+ calls: cs => { for (const c of cs) { const fs = missBy.get(c.id); if (!fs) continue; const t = sum(fs, f => f.tokens); c.cacheRead = (c.cacheRead || 0) + t; c.cacheWrite = Math.max(0, (c.cacheWrite || 0) - t); } },
181
+ how: { harness: 'move timestamps, ids and per-call values to the end of the latest message; send tools in a fixed order; serialize JSON with sorted keys' }, verify: 'prefix-cache doctor on new request logs: no system-dynamic or tools-reordered breaks' });
182
+ add({ id: 'cache-lifetime', layer: 'cache', title: api ? 'Keep the cache through long pauses: 1-hour cache writes' : 'Keep paused sessions\' KV: offload it to host memory instead of evicting it', risk: 'none', effort: api ? 'config' : 'infra',
183
+ applies: () => (expBy.size ? true : `no pauses past the ${ctx.cacheTtlS} s cache lifetime cost a miss`),
184
+ calls: cs => { for (const c of cs) { const fs = expBy.get(c.id); if (!fs) continue; const t = sum(fs, f => f.tokens); c.cacheRead = (c.cacheRead || 0) + t; c.cacheWrite = Math.max(0, (c.cacheWrite || 0) - t); if (api && c.price) c.extraCost = (c.extraCost || 0) + t * c.price.in * ctx.o.onehourWritePremium; } },
185
+ serving: S => { if (!api) S.kvOffload = true; },
186
+ how: api ? { harness: 'write the cache with a 1-hour lifetime on the prefix that outlives pauses (where the API offers it)' } : { vllm: 'a KV connector that offloads to host memory (e.g. LMCache)', sglang: 'hierarchical cache (host memory tier)' },
187
+ verify: api ? 'harness-ledger: cache-expired findings drop' : 'fleetops shadow: TTFT of returning sessions' });
188
+ const bigs = ctx.calls.some(c => c.toolCalls.some(t => t.resultTokens > ctx.o.bigResult));
189
+ add({ id: 'tool-output-cap', layer: 'harness', title: `Cap tool results at ~${ctx.o.toolKeep.toLocaleString('en-US')} tokens (summarize or paginate the rest)`, risk: 'quality', effort: 'code',
190
+ applies: () => (bigs ? true : `no tool result over ${ctx.o.bigResult.toLocaleString('en-US')} tokens`),
191
+ calls: cs => {
192
+ for (const chain of chainsOf(cs)) {
193
+ let cut = 0, pending = 0; // cut: trimmed tokens now part of the cached context; pending: last call's trimmed results
194
+ for (let i = 0; i < chain.length; i++) {
195
+ const c = chain[i];
196
+ if (i && c.input < chain[i - 1].input * 0.5) { cut = 0; pending = 0; } // compaction: nothing carried any more
197
+ c.input = Math.max(1, c.input - cut - pending);
198
+ c.cacheRead = Math.max(0, Math.min(c.input, (c.cacheRead || 0) - cut));
199
+ c.cacheWrite = Math.max(0, Math.min(c.input - c.cacheRead, c.cacheWrite || 0));
200
+ cut += pending; pending = 0;
201
+ for (const t of c.toolCalls) if (t.resultTokens > ctx.o.bigResult) pending += t.resultTokens - ctx.o.toolKeep;
202
+ }
203
+ }
204
+ },
205
+ how: { harness: 'truncate or summarize tool output above the cap; return a pointer (path, line range, page) for the rest' }, verify: 'quality gate on real tasks (a capped result can hide what the agent needed)' });
206
+ const offered = ctx.calls.some(c => c.toolsOffered && c.toolDefTokens);
207
+ add({ id: 'unused-tools', layer: 'harness', title: 'Load tool definitions on demand (tool search) instead of sending every tool with every call', risk: 'none', effort: 'code',
208
+ applies: () => (offered && ctx.findings.some(f => f.cause === 'unused-tools') ? true : 'no unused tool definitions in these calls'),
209
+ calls: cs => { const used = new Map(); for (const c of cs) { const k = `${c.harness}|${c.session}`; if (!used.has(k)) used.set(k, new Set()); for (const t of c.toolCalls) used.get(k).add(t.name); }
210
+ for (const c of cs) { if (!c.toolsOffered || !c.toolDefTokens) continue; const u = used.get(`${c.harness}|${c.session}`), drop = c.toolDefTokens * c.toolsOffered.filter(x => !u.has(x)).length / c.toolsOffered.length; c.input = Math.max(1, c.input - drop); c.cacheRead = Math.max(0, (c.cacheRead || 0) - drop); } },
211
+ how: { harness: 'expose a tool-search tool and load definitions when the agent asks for them' }, verify: 'harness-ledger: unused-tools findings drop' });
212
+ const cold = chainsOf(ctx.calls).some(ch => ch.some((c, i) => i && c.t - ch[i - 1].t > ctx.cacheTtlS && c.input >= 2 * ctx.o.compactMin));
213
+ add({ id: 'compact-cold', layer: 'context', title: `Compact long contexts after pauses past the cache lifetime (to ~${Math.round(100 * ctx.o.compactKeep)}%)`, risk: 'quality', effort: 'code',
214
+ applies: () => (cold ? true : 'no long context restarts cold after a pause'),
215
+ calls: cs => {
216
+ for (const chain of chainsOf(cs)) {
217
+ let cut = 0;
218
+ for (let i = 0; i < chain.length; i++) {
219
+ const c = chain[i], prev = chain[i - 1];
220
+ if (i && c.input < prev.input * 0.5) cut = 0;
221
+ if (cut) { c.input = Math.max(1, c.input - cut); c.cacheRead = Math.max(0, (c.cacheRead || 0) - cut); }
222
+ if (i && c.t - prev.t > ctx.cacheTtlS && c.input >= 2 * ctx.o.compactMin) {
223
+ const keep = Math.max(ctx.o.compactMin, c.input * ctx.o.compactKeep), drop = c.input - keep;
224
+ c.output += keep; // the summary, generated from the context this call prefills anyway
225
+ cut += drop;
226
+ }
227
+ }
228
+ }
229
+ },
230
+ how: { harness: 'when a session resumes after the cache has expired, summarize it first and continue from the summary' }, verify: 'quality gate on long tasks' });
231
+ const caps = ctx.outcomes ? exactCaps(ctx.calls) : null, cap = caps && caps.filter(c => c.rateLossPts <= 1).sort((a, b) => b.saved - a.saved)[0];
232
+ add({ id: 'step-cap', layer: 'agent', title: cap ? `Stop sessions after ${cap.cap} calls (${cap.successesLost} successes lost)` : 'Stop runaway sessions after N calls', risk: 'successes', effort: 'config',
233
+ applies: () => (cap && cap.saved > 0 ? true : ctx.outcomes ? 'no cap saves without losing more than a point of success rate' : 'needs outcomes (--outcomes) to count the successes a cap costs'),
234
+ calls: cs => { const seen = new Map(); for (const c of cs) { const k = `${c.harness}|${c.session}`; const n = (seen.get(k) || 0) + 1; seen.set(k, n); if (n > cap.cap) c.drop = true; } return cs.filter(c => !c.drop); },
235
+ how: { harness: `max ${cap ? cap.cap : 'N'} model calls per task (or a spend limit)` }, verify: 'outcomes before and after' });
236
+ const reasoning = ctx.calls.some(c => c.cls === 'reasoning' && (c.reasoning || 0) > 0);
237
+ add({ id: 'output-budget', layer: 'model', title: `Lower reasoning effort or cap output on the reasoning class (−${Math.round(100 * ctx.o.outputCut)}% reasoning tokens)`, risk: 'quality', effort: 'config',
238
+ applies: () => (reasoning ? true : 'no reasoning-heavy calls'),
239
+ calls: cs => { for (const c of cs) if (c.cls === 'reasoning' && c.reasoning) { const cut = c.reasoning * ctx.o.outputCut; c.output = Math.max(1, c.output - cut); c.reasoning -= cut; } },
240
+ how: { harness: 'reasoning_effort lower, or max_tokens on calls whose answers are short' }, verify: 'quality gate on reasoning tasks' });
241
+ const batch = ctx.calls.some(c => c.cls === 'batch');
242
+ add({ id: 'batch-offpeak', layer: 'scheduling', title: `Move batch traffic out of the peak${ctx.o.batchDiscount ? ` (and use the provider's batch discount, ${Math.round(100 * ctx.o.batchDiscount)}%)` : ''}`, risk: 'none', effort: 'config',
243
+ applies: () => (batch ? true : 'no batch traffic'),
244
+ calls: cs => { for (const c of cs) if (c.cls === 'batch') { c.offpeak = true; if (api && ctx.o.batchDiscount) c.discount = ctx.o.batchDiscount; } },
245
+ how: { harness: 'schedule batch jobs outside the busiest hours, or submit them through a batch endpoint' }, verify: 'peak arrivals in fleetops / live-twin' });
246
+ if (api) return L;
247
+ // ---------- serving, model options, GPU, scheduling (self-hosted) ----------
248
+ const s0 = ctx.settings({ gpu: ctx.gpu, model: ctx.model });
249
+ add({ id: 'prefix-routing', layer: 'serving', title: 'Route each session to the replica that holds its prefix (prefix-aware routing / session affinity)', risk: 'none', effort: 'infra',
250
+ applies: () => (ctx.server && ctx.server.hitRate != null && ctx.potential != null && ctx.potential - ctx.server.hitRate > 0.05 ? true : 'the engine\'s hit rate is not below what the traces could reuse (or no --engine-metrics)'),
251
+ serving: S => { S.hitOverride = ctx.server.hitRate + 0.9 * (ctx.potential - ctx.server.hitRate); }, // routing recovers most, not all, of the gap
252
+ how: { 'llm-d': 'the endpoint picker\'s prefix-cache scorer (precise, from KV events)', dynamo: 'KV-aware router', vllm: 'session affinity at the gateway (hash on session id)' }, verify: 'engine prefix-cache hit rate, then fleetops shadow' });
253
+ const wprec = ctx.wprec || s0.wprec || 'bf16';
254
+ if (wprec === 'bf16' && s0.tfFp8) add({ id: 'fp8-weights', layer: 'model-options', title: 'FP8 weights', risk: 'quality', effort: 'config', exclusive: 'wprec', applies: () => true, serving: S => { S.wprec = 'fp8'; }, how: { vllm: '--quantization fp8 (or an FP8 checkpoint)' }, verify: 'fleetops shadow answers + quality gate' });
255
+ if (wprec !== 'fp4' && s0.tfFp4) add({ id: 'fp4-weights', layer: 'model-options', title: 'FP4 weights (NVFP4/MXFP4)', risk: 'quality', effort: 'config', exclusive: 'wprec', applies: () => true, serving: S => { S.wprec = 'fp4'; }, how: { vllm: 'an NVFP4 or MXFP4 checkpoint' }, verify: 'fleetops shadow answers + quality gate' });
256
+ if ((ctx.kvprec || s0.kvprec) !== 'fp8') add({ id: 'fp8-kv', layer: 'model-options', title: 'FP8 KV cache', risk: 'quality', effort: 'config', applies: () => true, serving: S => { S.kvprec = 'fp8'; }, how: { vllm: '--kv-cache-dtype fp8', sglang: '--kv-cache-dtype fp8_e5m2' }, verify: 'quality gate' });
257
+ if (!ctx.specOn) add({ id: 'spec-decode', layer: 'model-options', title: `Speculative decoding (${ctx.o.specTokens} drafted tokens, ${Math.round(100 * ctx.o.specAccept)}% acceptance assumed)`, risk: 'none', effort: 'config', applies: () => true,
258
+ serving: S => { S.spec = { accept: ctx.o.specAccept, tokens: ctx.o.specTokens }; }, how: { vllm: '--speculative-config with num_speculative_tokens (MTP heads where the model ships them, else a small draft model)' }, verify: 'fleetops shadow: TPOT; acceptance rate from the engine' });
259
+ add({ id: 'priority', layer: 'scheduling', title: 'Interactive classes ahead of batch (priority scheduling)', risk: 'none', effort: 'config',
260
+ applies: () => (ctx.interactiveShare > 0 && ctx.interactiveShare < 1 && batch ? true : 'needs interactive and batch traffic sharing the fleet'),
261
+ serving: S => { S.priority = true; }, how: { vllm: '--scheduling-policy priority, with a priority per request class' }, verify: 'fleetops shadow: TTFT by class' });
262
+ add({ id: 'disaggregate', layer: 'serving', title: 'Disaggregated prefill/decode', risk: 'none', effort: 'infra', applies: () => true, serving: S => { S.disagg = true; },
263
+ how: { 'llm-d': 'P/D disaggregation with NIXL', dynamo: 'disaggregated serving' }, verify: 'fleetops shadow', note: 'measured as GPUs needed for the targets; TTFT and TPOT at your fleet are modelled for aggregated serving' });
264
+ add({ id: 'add-replica', layer: 'gpu', title: `One more instance (+${(ctx.baseline && ctx.baseline.g) || 8} GPUs)`, risk: 'none', effort: 'infra', applies: () => true, serving: (S, m) => { S.addGpus = (m && m.g) || 8; }, how: { k8s: 'replicas + 1' }, verify: 'fleetops shadow' });
265
+ for (const g of ctx.altGpus) add({ id: `gpu-${g}`, layer: 'gpu', title: `Move to ${g} (the same number of GPUs)`, risk: 'none', effort: 'infra', exclusive: 'gpu', applies: () => true, serving: S => { S.gpu = g; }, how: { k8s: `node pool of ${g}` }, verify: 'fleetops shadow, then gpu-health' });
266
+ for (const m of ctx.altModels) add({ id: `model-${m}`, layer: 'model', title: `Serve ${m} instead`, risk: 'quality', effort: 'infra', exclusive: 'model', applies: () => true, serving: S => { S.model = m; }, how: { k8s: `a deployment of ${m}` }, verify: 'quality gate first, then fleetops shadow' });
267
+ return L;
268
+ }
269
+
270
+ export function scenario(ids, ctx) {
271
+ const levers = ids.map(id => ctx.levers.find(l => l.id === id)).filter(Boolean);
272
+ let cs = clone(ctx.calls);
273
+ const S = { mode: ctx.mode, gpu: ctx.gpu, model: ctx.model, gpus: ctx.fleetGpus, wprec: ctx.wprec, kvprec: ctx.kvprec, hitOverride: ctx.mode === 'api' ? null : ctx.baseHit, spec: ctx.specOn ? { accept: ctx.o.specAccept, tokens: ctx.o.specTokens } : null };
274
+ for (const l of levers) if (l.calls) { const r = l.calls(cs); if (Array.isArray(r)) cs = r; }
275
+ for (const l of levers) if (l.serving) l.serving(S, ctx.baseline);
276
+ // a workload lever's hit-rate change rides on top of the engine's own rate: scale it, don't replace it
277
+ if (ctx.mode !== 'api' && ctx.baseHit != null && !levers.some(l => l.id === 'prefix-routing')) {
278
+ const traceHit = sum(cs, c => c.cacheRead) / Math.max(1, sum(cs, c => c.input));
279
+ S.hitOverride = Math.min(0.99, ctx.baseHit * (ctx.traceHit ? traceHit / ctx.traceHit : 1));
280
+ }
281
+ return measure(cs, S, ctx);
282
+ }
283
+
284
+ const change = (a, b) => (a == null || b == null ? null : a === 0 ? null : (b - a) / Math.abs(a));
285
+ const better = (goal, a, b) => { const g = GOALS[goal], c = change(a, b); return c == null ? null : g.lower ? -c : c; };
286
+
287
+ export function advise(calls, report, findings, opt = {}) {
288
+ const o = Object.assign({}, DEFAULTS, opt);
289
+ const goal = o.goal || 'ttft'; if (!GOALS[goal]) throw new Error(`goal: one of ${Object.keys(GOALS).join(', ')}`);
290
+ const mode = o.model || o.gpu ? 'self-host' : 'api';
291
+ classify(calls, { classMap: o.classMap });
292
+ const interactive = sum(calls.filter(c => c.cls === 'realtime' || c.cls === 'critical'), fresh) / Math.max(1, sum(calls, fresh));
293
+ const settings = S => Object.assign(sizerSettings({ model: S.model || o.model || 'deepseek-v3', gpu: S.gpu || o.gpu || 'H200', ttft: o.ttft || 2000, tpot: o.tpot || 50, spare: false, calibration: o.calibration }), S.wprec ? { wprec: S.wprec } : {}, S.kvprec ? { kvprec: S.kvprec } : {});
294
+ const gpuPrice = id => { const g = CAT.GPUS.find(x => x.id === (id || o.gpu)); return g && g.price ? g.price : null; };
295
+ const traceHit = sum(calls, c => c.cacheRead) / Math.max(1, sum(calls, c => c.input));
296
+ const ctx = { layouts: new Map(), o, goal, mode, calls, findings, report, outcomes: report && report.outcomes && report.outcomes.known > 0, cacheTtlS: o.cacheTtlS, days: o.days, settings, gpuPrice, gpuRate: o.gpuRate ?? null,
297
+ model: o.model, gpu: o.gpu, wprec: o.wprec, kvprec: o.kvprec, specOn: !!o.specOn, interactiveShare: interactive, server: o.server || null, potential: o.potential ?? null,
298
+ altGpus: [].concat(o.altGpus || []), altModels: [].concat(o.altModels || []), traceHit, baseHit: mode === 'api' ? null : o.server && o.server.hitRate != null ? o.server.hitRate : traceHit, fleetGpus: o.fleetGpus || null };
299
+ if (ctx.potential == null) ctx.potential = traceHit; // what the clients' own cache accounting shows is reusable
300
+ ctx.latency = mode === 'api' ? fitLatency(calls) : null;
301
+ if (mode !== 'api' && !ctx.fleetGpus) { const m0 = measure(clone(calls), { mode, gpu: o.gpu, model: o.model, wprec: o.wprec, kvprec: o.kvprec, hitOverride: ctx.baseHit }, ctx); ctx.fleetGpus = m0.gpus; ctx.fleetFromSizer = true; }
302
+ if (mode !== 'api' && !o.altGpus) ctx.altGpus = defaultAltGpus(o.gpu);
303
+ ctx.levers = [];
304
+ const base = scenario([], ctx); ctx.baseline = { g: base.instanceGpus || 8 };
305
+ ctx.levers = LEVERS(ctx);
306
+ const keys = mode === 'api' ? ['cost', 'ttft', 'e2e', 'cacheHit', 'freshPerCall', 'outputPerCall'] : ['ttft', 'tpot', 'e2e', 'gpus', 'throughput', 'cost', 'cacheHit', 'util'];
307
+ const levers = [], notApplicable = [];
308
+ for (const l of ctx.levers) {
309
+ const ok = l.applies(); if (ok !== true) { notApplicable.push({ id: l.id, layer: l.layer, why: ok }); continue; }
310
+ const m = scenario([l.id], ctx);
311
+ levers.push({ id: l.id, layer: l.layer, title: l.title, risk: l.risk, effort: l.effort, exclusive: l.exclusive || null, note: l.note || null, how: l.how, verify: l.verify,
312
+ effect: Object.fromEntries(keys.map(k => [k, { before: base[k] ?? null, after: m[k] ?? null, change: change(base[k], m[k]) }])), gain: better(goal, base[goal], m[goal]), saturated: !!m.saturated });
313
+ const moved = keys.some(k => Math.abs(levers.at(-1).effect[k].change || 0) >= 0.001) || m.saturated !== !!base.saturated;
314
+ if (!moved) { levers.pop(); notApplicable.push({ id: l.id, layer: l.layer, why: 'no measurable effect on this workload' }); }
315
+ }
316
+ levers.sort((a, b) => (b.gain ?? -Infinity) - (a.gain ?? -Infinity));
317
+ const bundle = (filter, costCap = o.maxCostIncrease) => {
318
+ const pool = levers.filter(l => (l.gain ?? 0) > 0.005 && filter(l)), chosen = [], steps = []; let cur = base;
319
+ for (let round = 0; round < 8 && pool.length; round++) {
320
+ let best = null;
321
+ for (const l of pool) {
322
+ if (chosen.includes(l.id) || (l.exclusive && chosen.some(id => (levers.find(x => x.id === id) || {}).exclusive === l.exclusive))) continue;
323
+ const m = scenario([...chosen, l.id], ctx), g = better(goal, cur[goal], m[goal]);
324
+ if (costCap != null && goal !== 'cost' && base.cost && m.cost != null && (m.cost - base.cost) / base.cost > costCap + 1e-9) continue;
325
+ if (g != null && g > 0.005 && (!best || g > best.g)) best = { l, m, g };
326
+ }
327
+ if (!best) break;
328
+ chosen.push(best.l.id); steps.push({ add: best.l.id, [goal]: best.m[goal], gain: best.g }); cur = best.m;
329
+ }
330
+ return { levers: chosen, steps, after: cur, gain: better(goal, base[goal], cur[goal]) };
331
+ };
332
+ const out = { kind: 'harness-ledger.advise', goal, goalLabel: GOALS[goal].label, mode, costUnit: report && report.pricing && report.pricing.currency === 'units' ? 'units' : 'USD', model: o.model || null, gpu: o.gpu || null, targets: mode === 'api' ? null : { ttft: o.ttft || 2000, tpot: o.tpot || 50 },
333
+ fleet: mode === 'api' ? null : { gpus: ctx.fleetGpus, fromSizer: !!ctx.fleetFromSizer }, latencyModel: ctx.latency, baseline: base, levers, notApplicable,
334
+ bundles: { best: bundle(() => true), noExtraCost: goal === 'cost' ? null : bundle(() => true, Math.min(0, o.maxCostIncrease ?? 0)), safe: bundle(l => l.risk === 'none') }, maxCostIncrease: o.maxCostIncrease ?? null, assumptions: assumptions(ctx) };
335
+ if (o.apply) out.dryRun = dryRun([].concat(o.apply), ctx, base, keys);
336
+ if (o.failIf && out.dryRun) out.gate = gate(o.failIf, out.dryRun);
337
+ return out;
338
+ }
339
+ function defaultAltGpus(id) {
340
+ const g = CAT.GPUS.find(x => x.id === id); if (!g) return [];
341
+ return CAT.GPUS.filter(x => x.kind !== 'tpu' && x.id !== g.id && x.vendor === g.vendor && x.hbmTBs > g.hbmTBs && x.price).sort((a, b) => a.hbmTBs - b.hbmTBs).slice(0, 2).map(x => x.id);
342
+ }
343
+ function assumptions(ctx) {
344
+ const A2 = ['Each lever is evaluated on your recorded calls changed as the lever would change them; the effects are model estimates to verify with fleetops shadow and the quality gate.'];
345
+ const T = ctx.report && ctx.report.totals;
346
+ if (ctx.report && ctx.report.pricing && ctx.report.pricing.currency === 'units') A2.push('Prices are relative (a million fresh input tokens = 1 unit; cache reads 0.1, writes 1.25, output 5): cost changes are right as shares, not as dollars. Pass --prices FILE for dollars.');
347
+ else if (ctx.mode === 'api' && T && T.unpricedCalls) A2.push(`${T.unpricedCalls} of ${T.calls} calls have no price (${(T.unpricedModels || []).slice(0, 4).join(', ') || 'unknown models'}): their cost counts as zero. Pass --prices FILE, or --prices relative, or --model and --gpu to price them as self-hosted.`);
348
+ if (ctx.mode === 'api') A2.push(ctx.latency && ctx.latency.ok ? `Latency: a fit of ${ctx.latency.source === 'ttft' ? 'recorded time to first token to prefilled and cached input tokens' : 'call duration to prefilled input, cached input and output tokens'} (R² ${ctx.latency.r2.toFixed(2)}, ${ctx.latency.n} calls)${ctx.latency.tied ? ', with a cached token taken as a tenth of a fresh one (the fit couldn\'t separate them)' : ''}; ${ctx.latency.source === 'ttft' ? '' : '; TTFT is its input part'}.` : `No latency model: ${ctx.latency ? ctx.latency.why : 'no durations'}; cost and token levers only.`);
349
+ else A2.push(`Self-hosted on ${ctx.gpu} serving ${ctx.model}, ${ctx.fleetGpus} GPUs${ctx.fleetFromSizer ? ' (the sizer\'s answer for the targets; pass --gpus for your fleet)' : ''}, at the busiest minute's arrival rate; TTFT/TPOT from the Inference Sizer's operating point; cost is the GPUs needed for the targets at ${ctx.gpuRate != null ? `$${ctx.gpuRate}/GPU-h` : 'the catalog\'s GPU-hour price (--gpu-rate for yours)'}.`);
350
+ if (ctx.levers.some(l => l.id === 'spec-decode')) A2.push(`Speculative decoding: ${ctx.o.specTokens} drafted tokens at ${Math.round(100 * ctx.o.specAccept)}% acceptance (--spec-accept to change; measure the real rate in a shadow test).`);
351
+ if (ctx.server) A2.push(`Engine prefix-cache hit rate ${Math.round(100 * ctx.server.hitRate)}% (from --engine-metrics) is the self-hosted baseline; workload levers scale it.`);
352
+ return A2;
353
+ }
354
+
355
+ export function dryRun(ids, ctx, base, keys) {
356
+ const unknown = ids.filter(id => !ctx.levers.some(l => l.id === id));
357
+ if (unknown.length) throw new Error(`unknown change ${unknown.join(', ')}: one of ${ctx.levers.map(l => l.id).join(', ')}`);
358
+ const after = scenario(ids, ctx);
359
+ const changes = ids.map(id => { const l = ctx.levers.find(x => x.id === id); return { id, layer: l.layer, title: l.title, risk: l.risk, how: l.how, verify: l.verify }; });
360
+ return { applied: ids, before: Object.fromEntries(keys.map(k => [k, base[k] ?? null])), after: Object.fromEntries(keys.map(k => [k, after[k] ?? null])), change: Object.fromEntries(keys.map(k => [k, change(base[k], after[k])])), saturated: !!after.saturated, changes,
361
+ next: ['fleetops shadow plan/replay/compare on the changed endpoint', ...(changes.some(c => c.risk !== 'none') ? ['fleetops shadow quality on real tasks (these changes can change answers)'] : [])] };
362
+ }
363
+
364
+ // "ttft>+5%", "cost>+0%", "gpus>12": fail when the dry run moves a metric past the bound
365
+ export function gate(spec, D) {
366
+ const fails = [];
367
+ for (const cond of String(spec).split(',').map(x => x.trim()).filter(Boolean)) {
368
+ const m = cond.match(/^([a-zA-Z]+)\s*(>=|<=|>|<)\s*([+-]?\d+(?:\.\d+)?)(%?)$/); if (!m) throw new Error(`--fail-if "${cond}": metric>+5% or metric>value`);
369
+ const [, k, op, v, isPct] = m, val = isPct ? D.change[k] : D.after[k], bound = isPct ? Number(v) / 100 : Number(v);
370
+ if (val == null) continue;
371
+ const bad = op === '>' ? val > bound : op === '>=' ? val >= bound : op === '<' ? val < bound : val <= bound;
372
+ if (bad) fails.push({ condition: cond, value: val });
373
+ }
374
+ return { pass: !fails.length, fails };
375
+ }
376
+
377
+ // ---------- text ----------
378
+ const fmtV = (k, v) => (v == null || !Number.isFinite(v) ? '–' : k === 'cost' ? (v >= 1e4 ? '$' + Math.round(v).toLocaleString('en-US') : '$' + v.toFixed(v >= 100 ? 0 : 2)) : k === 'cacheHit' || k === 'util' ? `${(100 * v).toFixed(0)}%` : k === 'ttft' || k === 'tpot' || k === 'e2e' ? `${v >= 100 ? Math.round(v) : v.toFixed(1)} ms` : k === 'throughput' ? v.toFixed(1) : v >= 1e3 ? `${(v / 1e3).toFixed(1)}k` : `${Math.round(v)}`);
379
+ const fmtC = c => (c == null ? '' : `${c > 0 ? '+' : ''}${(100 * c).toFixed(Math.abs(c) < 0.1 ? 1 : 0)}%`);
380
+ export function adviseText(R) {
381
+ // relative prices (no price for the model): cost in units of a million fresh input tokens, not dollars
382
+ const fv = (k, v) => (k === 'cost' && R.costUnit === 'units' && Number.isFinite(v) ? `${v >= 100 ? Math.round(v).toLocaleString('en-US') : v.toFixed(1)} units` : fmtV(k, v));
383
+ const L = [], g = R.goal, b = R.baseline;
384
+ L.push(`Optimize ${R.goalLabel}${R.mode === 'api' ? ' (hosted API)' : ` (self-hosted ${R.model} on ${R.fleet.gpus} × ${R.gpu})`}: now ${fv(g, b[g])}${b.ttftScope ? '' : ''}`);
385
+ if (b.saturated) L.push(' the fleet is over capacity at the busiest minute: latency is unbounded until something below adds capacity or removes load');
386
+ L.push('', 'Every change that moves it (alone, on your recorded calls):', ' ' + 'change'.padEnd(18) + 'layer'.padEnd(15) + g.padStart(9) + ' risk ' + 'also');
387
+ const others = R.mode === 'api' ? ['cost', 'cacheHit'] : ['tpot', 'gpus', 'cost'].filter(k => k !== g);
388
+ const flat = R.levers.filter(l => l.gain == null || Math.abs(l.effect[g].change || 0) < 0.001);
389
+ for (const l of R.levers.filter(x => !flat.includes(x))) {
390
+ const e = l.effect, also = others.filter(k => k !== g && e[k] && e[k].change && Math.abs(e[k].change) >= 0.01).map(k => `${k} ${fmtC(e[k].change)}`).join(', ');
391
+ L.push(` ${l.id.padEnd(18)}${l.layer.padEnd(15)}${(l.gain == null ? '–' : fmtC(e[g].change)).padStart(9)} ${l.risk.padEnd(10)} ${also}${l.saturated ? ' (still over capacity)' : ''}`);
392
+ }
393
+ if (flat.length) L.push(` no effect on ${g}: ${flat.map(l => { const e = l.effect, also = others.filter(k => e[k] && Math.abs(e[k].change || 0) >= 0.01).map(k => `${k} ${fmtC(e[k].change)}`); return also.length ? `${l.id} (${also.join(', ')})` : l.id; }).join(', ')}`);
394
+ for (const [name, B] of [[R.maxCostIncrease != null ? `Best combination (cost up at most ${fmtC(R.maxCostIncrease)})` : 'Best combination', R.bundles.best], ['At no extra cost', R.bundles.noExtraCost], ['No quality risk', R.bundles.safe]]) {
395
+ if (!B || !B.levers.length) continue;
396
+ if (name === 'At no extra cost' && B.levers.join() === R.bundles.best.levers.join()) continue;
397
+ const dc = g !== 'cost' && b.cost && B.after.cost != null ? `, cost ${fmtC((B.after.cost - b.cost) / b.cost)}` : '';
398
+ L.push('', `${name}: ${B.levers.join(' + ')} → ${fv(g, B.after[g])} (${fmtC(change(b[g], B.after[g]))}${dc})`);
399
+ }
400
+ if (R.dryRun) {
401
+ const D = R.dryRun; L.push('', `Dry run of ${D.applied.join(' + ')}:`);
402
+ for (const k of Object.keys(D.before)) L.push(` ${k.padEnd(13)} ${fv(k, D.before[k]).padStart(10)} → ${fv(k, D.after[k]).padEnd(10)} ${fmtC(D.change[k])}`);
403
+ L.push('', ' How to make each change:'); for (const c of D.changes) L.push(` ${c.id}: ${Object.entries(c.how || {}).map(([k, v]) => `${k}: ${v}`).join('; ')} → verify: ${c.verify}`);
404
+ L.push(` Then: ${D.next.join('; ')}`);
405
+ if (R.gate) L.push('', R.gate.pass ? 'Gate: pass' : `Gate: FAIL (${R.gate.fails.map(f => f.condition).join(', ')})`);
406
+ } else if (R.bundles.best.levers.length) L.push('', `Dry run: --apply ${R.bundles.best.levers.join(',')}`);
407
+ if (R.notApplicable.length) L.push('', 'Not applicable here: ' + R.notApplicable.map(x => `${x.id} (${x.why})`).join('; '));
408
+ L.push('', ...R.assumptions.map(a => `Note: ${a}`));
409
+ return L.join('\n') + '\n';
410
+ }
@@ -0,0 +1,66 @@
1
+ // One-command assessment: the workload profile (classes and token ratios), the prefix-cache doctor, and the optimizer
2
+ // for each goal asked for, in one report (text, Markdown for a CI job summary, or JSON).
3
+ import { profile, profileText, ratio } from './profile.mjs';
4
+ import { doctor, doctorText } from './doctor.mjs';
5
+ import { advise, adviseText, GOALS } from './advise.mjs';
6
+
7
+ const pct = x => (x == null || !Number.isFinite(x) ? '–' : `${(100 * x).toFixed(Math.abs(x) < 0.1 ? 1 : 0)}%`);
8
+ const sgn = x => (x == null || !Number.isFinite(x) ? '–' : `${x > 0 ? '+' : ''}${pct(x)}`);
9
+ const usd = x => (x == null || !Number.isFinite(x) ? '–' : x >= 1e4 ? `$${Math.round(x).toLocaleString('en-US')}` : `$${x.toFixed(2)}`);
10
+
11
+ // opt: { classMap, cacheTtlS, requests, server (engine prefix-cache metrics), goals: ['ttft','cost'], ...advise options }
12
+ export function assess(r, opt = {}) {
13
+ const cacheTtlS = opt.cacheTtlS || 300;
14
+ const P = profile(r.calls, { classMap: opt.classMap, cacheTtlS });
15
+ const D = doctor(r.calls, r.findings, { requests: opt.requests || null, engine: opt.server || null, cacheTtlS, potential: null });
16
+ if (D.server) { D.server.potential = D.hit.all ? D.hit.all.hit : null; D.server.gap = D.server.potential != null ? D.server.potential - D.server.hitRate : null; }
17
+ const goals = [].concat(opt.goals || ['ttft', 'cost']).filter(g => GOALS[g]);
18
+ const optimize = {};
19
+ for (const g of goals) optimize[g] = advise(r.calls, r.report, r.findings, Object.assign({}, opt, { goal: g, cacheTtlS, apply: undefined, failIf: undefined }));
20
+ const t = P.total;
21
+ const costUnit = Object.values(optimize)[0] ? Object.values(optimize)[0].costUnit : 'USD';
22
+ const summary = { costUnit, calls: t.calls, sessions: t.sessions, inOut: t.output ? t.input / t.output : null, cachedShare: t.cachedShare, reachable: D.hit.all ? D.hit.all.achievable : null,
23
+ engineHit: D.server ? D.server.hitRate : null, cost: r.report.totals ? r.report.totals.cost : null, avoidable: r.report.totals ? r.report.totals.avoidableCost : null,
24
+ classes: P.classes.map(c => ({ class: c.class, calls: c.calls, share: c.share.calls, inOut: c.output ? c.input / c.output : null, bound: c.bound })),
25
+ goals: Object.fromEntries(goals.map(g => { const A = optimize[g], b = A.bundles.best; return [g, { now: A.baseline[g] ?? null, best: b.levers.length ? b.after[g] : null, levers: b.levers, change: b.gain == null ? null : (GOALS[g].lower ? -b.gain : b.gain) }]; })) };
26
+ return { kind: 'aiinfra.assess', generated: new Date().toISOString(), mode: opt.model || opt.gpu ? 'self-host' : 'api', summary, profile: P, doctor: D, optimize };
27
+ }
28
+
29
+ const fmtGoal = (g, v, unit) => (v == null || !Number.isFinite(v) ? '–' : g === 'cost' ? (unit === 'units' ? `${v >= 100 ? Math.round(v).toLocaleString('en-US') : v.toFixed(1)} units` : usd(v)) : g === 'ttft' || g === 'tpot' || g === 'e2e' ? `${v >= 100 ? Math.round(v) : v.toFixed(1)} ms` : g === 'throughput' ? `${v.toFixed(1)} req/s` : `${Math.round(v)}`);
30
+ const fmtK = (k, v, unit) => (k === 'cacheHit' || k === 'util' ? pct(v) : fmtGoal(k, v, unit));
31
+ export function assessText(A, money) {
32
+ const S = A.summary, L = [];
33
+ L.push(`Assessment: ${S.calls} calls in ${S.sessions} sessions; input:output ${ratio(S.inOut, 1)}; ${pct(S.cachedShare)} of input from cache (${pct(S.reachable)} reachable)${S.engineHit != null ? `; engine prefix cache ${pct(S.engineHit)}` : ''}`);
34
+ for (const [g, x] of Object.entries(S.goals)) L.push(` ${GOALS[g].label}: ${fmtGoal(g, x.now, S.costUnit)}${x.levers.length ? ` → ${fmtGoal(g, x.best, S.costUnit)} (${sgn(x.change)}) with ${x.levers.join(' + ')}` : ' (no change found that moves it)'}`);
35
+ L.push('', profileText(A.profile).trimEnd(), '', doctorText(A.doctor, money).trimEnd());
36
+ for (const g of Object.keys(A.optimize)) L.push('', adviseText(A.optimize[g]).trimEnd());
37
+ return L.join('\n') + '\n';
38
+ }
39
+
40
+ // GitHub-flavoured Markdown: a job summary or a PR comment
41
+ export function assessMarkdown(A) {
42
+ const S = A.summary, L = [];
43
+ L.push('## AIInfraTools assessment', '', `${S.calls.toLocaleString('en-US')} calls in ${S.sessions.toLocaleString('en-US')} sessions · input:output **${ratio(S.inOut, 1)}** · **${pct(S.cachedShare)}** of input from cache (${pct(S.reachable)} reachable)${S.engineHit != null ? ` · engine prefix cache **${pct(S.engineHit)}**` : ''}`, '');
44
+ L.push('| Goal | Now | Best combination | After | Change |', '|---|---|---|---|---|');
45
+ for (const [g, x] of Object.entries(S.goals)) L.push(`| ${GOALS[g].label} | ${fmtGoal(g, x.now, S.costUnit)} | ${x.levers.length ? x.levers.map(l => `\`${l}\``).join(' + ') : '–'} | ${fmtGoal(g, x.best, S.costUnit)} | ${sgn(x.change)} |`);
46
+ L.push('', '### Workload classes', '', '| Class | Calls | Share | In:out | From cache | Bound |', '|---|---|---|---|---|---|');
47
+ for (const c of A.profile.classes) L.push(`| ${c.class} | ${c.calls} | ${pct(c.share.calls)} | ${ratio(c.input, c.output)} | ${pct(c.cachedShare)} | ${c.bound} |`);
48
+ const adv = A.doctor.advice.slice(0, 6);
49
+ if (adv.length) { L.push('', '### Prefix cache', ''); for (const x of adv) L.push(`- **[${x.layer}]** ${x.text}${x.saves ? ` — saves ${usd(x.saves)}` : ''}`); }
50
+ for (const [g, R] of Object.entries(A.optimize)) {
51
+ L.push('', `### Every change that moves ${R.goalLabel}`, '', `| Change | Layer | ${g} | Risk |`, '|---|---|---|---|');
52
+ for (const l of R.levers.filter(x => x.gain != null && Math.abs(x.effect[g].change || 0) >= 0.001)) L.push(`| \`${l.id}\` | ${l.layer} | ${sgn(l.effect[g].change)} | ${l.risk} |`);
53
+ }
54
+ L.push('', `<sub>Model estimates from recorded calls; verify with \`fleetops shadow\` and the quality gate before rollout.</sub>`);
55
+ return L.join('\n') + '\n';
56
+ }
57
+
58
+ export function adviseMarkdown(R) {
59
+ const L = [`## ${R.goalLabel}: dry run`, ''];
60
+ if (R.dryRun) {
61
+ const D = R.dryRun; L.push(`Changes: ${D.applied.map(x => `\`${x}\``).join(' + ')}`, '', '| Metric | Before | After | Change |', '|---|---|---|---|');
62
+ for (const k of Object.keys(D.before)) L.push(`| ${k} | ${fmtK(k, D.before[k], R.costUnit)} | ${fmtK(k, D.after[k], R.costUnit)} | ${sgn(D.change[k])} |`);
63
+ if (R.gate) L.push('', R.gate.pass ? '**Gate: pass**' : `**Gate: FAIL** — ${R.gate.fails.map(f => `\`${f.condition}\``).join(', ')}`);
64
+ } else L.push('No changes applied (--apply).');
65
+ return L.join('\n') + '\n';
66
+ }