aiinfra-tools 0.4.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 (53) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +30 -0
  3. package/bin/aiinfra.mjs +12 -0
  4. package/fleetops/deploy/grafana-dashboard.json +71 -0
  5. package/fleetops/docs/SHADOW.md +25 -2
  6. package/fleetops/package.json +1 -1
  7. package/fleetops/src/api.mjs +8 -0
  8. package/fleetops/src/schema.mjs +3 -0
  9. package/fleetops/src/shadow-quality.mjs +107 -0
  10. package/fleetops/src/shadow.mjs +12 -6
  11. package/fleetops/tools/cmd/help.mjs +4 -1
  12. package/fleetops/tools/cmd/shadow.mjs +14 -2
  13. package/fleetscope/build.mjs +1 -0
  14. package/fleetscope/dist/index.html +92 -3
  15. package/fleetscope/package.json +1 -1
  16. package/fleetscope/src/index.src.html +17 -1
  17. package/gpu-health/package.json +1 -1
  18. package/gpu-ledger/package.json +1 -1
  19. package/harness-ledger/README.md +48 -0
  20. package/harness-ledger/integrations/README.md +11 -0
  21. package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
  22. package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
  23. package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
  24. package/harness-ledger/package.json +1 -1
  25. package/harness-ledger/src/advise.mjs +410 -0
  26. package/harness-ledger/src/assess.mjs +66 -0
  27. package/harness-ledger/src/doctor.mjs +202 -0
  28. package/harness-ledger/src/engine-metrics.mjs +35 -0
  29. package/harness-ledger/src/importers.mjs +14 -3
  30. package/harness-ledger/src/lint.mjs +115 -0
  31. package/harness-ledger/src/mooncake.mjs +83 -0
  32. package/harness-ledger/src/profile.mjs +164 -0
  33. package/harness-ledger/src/record.mjs +2 -2
  34. package/harness-ledger/src/suggest.mjs +177 -0
  35. package/harness-ledger/src/trajectory.mjs +81 -0
  36. package/harness-ledger/src/workload-demo.mjs +100 -0
  37. package/harness-ledger/tools/harness-ledger.mjs +224 -5
  38. package/hybrid-tracing/package.json +1 -1
  39. package/inference-sizer/build.mjs +1 -0
  40. package/inference-sizer/dist/index.html +95 -5
  41. package/inference-sizer/package.json +1 -1
  42. package/inference-sizer/src/index.src.html +7 -0
  43. package/inference-sizer/src/model.js +5 -2
  44. package/inference-sizer/src/suggest.js +70 -0
  45. package/inference-sizer/src/ui.js +13 -3
  46. package/mcp/README.md +3 -0
  47. package/mcp/server.mjs +22 -0
  48. package/package.json +5 -2
  49. package/schemas/README.md +3 -0
  50. package/schemas/commands.mjs +7 -0
  51. package/schemas/harness-ledger.advise.schema.json +1102 -0
  52. package/schemas/harness-ledger.assess.schema.json +2823 -0
  53. package/schemas/harness-ledger.suggest.schema.json +326 -0
package/CHANGELOG.md CHANGED
@@ -3,6 +3,102 @@
3
3
  All notable changes. Versions follow [Semantic Versioning](https://semver.org/); before 1.0, a minor version may
4
4
  change the `--json` output, and when it does the change is listed here (see [schemas/](schemas/README.md)).
5
5
 
6
+ ## 0.5.0 (2026-11-29)
7
+
8
+ Optimize across the stack, and raise what is worth changing where people already work. `aiinfra assess`, `advise`
9
+ (with a dry run and a CI gate), `quality`, `suggest` and `prompt-lint` are new commands. The repository is now a
10
+ GitHub Action, and there are new integrations for Claude Code and the LiteLLM gateway. The Inference Sizer and
11
+ FleetScope pages show suggestions beside the answer. New `--json` output: `harness-ledger.advise`,
12
+ `harness-ledger.assess` and `harness-ledger.suggest`. No existing output changed. One prediction did change: the Sizer's
13
+ operating point now counts prefix-cache hits, so predicted TTFT is shorter for workloads that reuse prompts.
14
+
15
+ ### New: suggestions where people already look
16
+
17
+ Suggestions are now raised once each, in the tools people already use, and what people decide about them is
18
+ remembered (#89). Two public data formats are new inputs. New `--json` output: `harness-ledger.suggest`. No existing output
19
+ changed.
20
+
21
+ - **`aiinfra suggest`** turns the optimizer's and the doctor's findings into suggestions.
22
+ - Each suggestion carries its effect, its risk, whether the effect is counted from the traces or modelled, the
23
+ sessions most affected, and the dry-run command.
24
+ - A suggestion is raised once, and again only when its effect grows by half.
25
+ - `accept`, `dismiss`, `snooze` and `reopen` record what people decided. `--watch` re-runs on a rolling window.
26
+ - Sinks: a fleetops store, Slack and Lark/Feishu webhooks, and Langfuse comments on the affected sessions. Slack,
27
+ Lark and Langfuse send only with `--live`.
28
+ - **Claude Code:** `aiinfra claude-code-hook` works as SessionEnd, SessionStart and Stop hooks. It shows the last
29
+ session's cache misses and tool-output waste, and warns once per problem as it happens. A status line shows the
30
+ live cache hit rate and avoidable spend. Both are local, keep counts only, and never block a session.
31
+ - **Prompt lint:** `aiinfra prompt-lint` (`harness-ledger lint`) catches prompt templates and request bodies that will
32
+ miss the prefix cache:
33
+ - a per-call variable before static text;
34
+ - a literal timestamp or id in the prefix;
35
+ - a missing Anthropic cache breakpoint.
36
+
37
+ The GitHub Action gets `comment: true`: one pull request comment per step, updated in place.
38
+ - **LiteLLM gateway:** a proxy callback that reports, live, each request that breaks its session's prompt prefix and
39
+ why. It uses the same causes as the doctor, and a test checks that both name the same breaks. It writes Prometheus
40
+ counters and one log line per template and cause. It never changes or blocks a request.
41
+ - **Grafana:** a `suggestion` record kind, `/api/suggestions` on `fleetops serve`, and an **Optimization suggestions**
42
+ panel on the fleetops dashboard.
43
+ - **Inference Sizer and FleetScope pages:**
44
+ - The Sizer shows "What would change this": the same request re-planned with one change at a time (FP8/FP4 weights,
45
+ FP8 KV, speculative decoding, prefix caching, a shorter context), with GPUs and $/month.
46
+ - FleetScope shows "What to try": one-click what-ifs from the first bottleneck that its Ask box runs.
47
+ - **Inputs:**
48
+ - Agent trajectories with full message lists (SWE-agent, OpenHands datasets). Their request bodies feed the doctor.
49
+ - Mooncake-format serving traces: hit rate by cache size, and random against prefix-aware routing.
50
+ - `harness-ledger mooncake --requests` writes your own traffic as a Mooncake trace with no text, for AIPerf.
51
+ - **MCP:** `list_suggestions` (read-only). The server now has 23 tools.
52
+ - **Workload profile:** "fresh tokens per output token" now counts cache writes as prefilled, so some classes'
53
+ prefill/decode bound changes on data with large cache writes.
54
+
55
+ ### New: optimize across the stack
56
+
57
+ Ask for a metric and get every change across the stack that moves it (#88). You can dry-run any combination of them, gate it
58
+ in CI, and check that answers didn't get worse. New `--json` output: `harness-ledger.advise` and `harness-ledger.assess`.
59
+ No existing output changed.
60
+
61
+ - **`aiinfra assess`** gives one report: workload classes (critical, realtime, agentic, reasoning, batch) with
62
+ input:output token ratios and what bounds each; the prefix-cache doctor; and the optimizer for each goal. Text,
63
+ Markdown (`--md`, for a job summary) or JSON.
64
+ - **`aiinfra advise --goal ttft|tpot|e2e|cost|gpus|throughput`** covers changes in every layer:
65
+ - prompt layout, cache lifetime, tool-output caps, on-demand tool definitions, cold compaction, step caps and
66
+ reasoning budgets;
67
+ - batch off-peak and priority scheduling;
68
+ - prefix-aware routing, FP8/FP4 weights, FP8 KV and speculative decoding;
69
+ - disaggregation, other GPUs and other models.
70
+
71
+ Each change is measured on the recorded calls changed as it would change them, or on the Inference Sizer's operating
72
+ point when self-hosted. The answer gives three combinations (best, at no extra cost, no quality risk). `--apply`
73
+ runs a dry run with how to make and verify each change, `--fail-if 'ttft>+5%'` exits 3 when a bound is crossed, and
74
+ `--out` writes the change set.
75
+ - **Prefix-cache doctor** (`harness-ledger doctor`):
76
+ - hit rate now against what is reachable;
77
+ - from request bodies, which part of the prompt breaks the cache (`system-dynamic`, `tools-reordered`,
78
+ `json-key-order`, `whitespace`, `history-edited`, …) and a template lint;
79
+ - priced tool-output caps, cold compaction and the warm-compaction break-even;
80
+ - the engine's own hit rate from vLLM or SGLang metrics (`--engine-metrics FILE|URL`).
81
+ - **Quality gate** (`aiinfra quality`, `fleetops shadow quality`) replays real tasks with pass checks on both endpoints.
82
+ The checks are contains, regex, exact, number and json. Results are paired by task, with a non-inferiority bound
83
+ (`--max-drop` points). `shadow compare --quality` rolls back on a drop and extends the test when the result is
84
+ unsettled.
85
+ - **GitHub Action**: the repository's `action.yml` runs any of these, writes the Markdown report to the job summary and
86
+ fails the job on a failed gate.
87
+ - **MCP**: `workload_assess` and `optimize_metric` (read-only; `simulate` runs the dry run). The server now has 22 tools.
88
+ - **Records**: `llm_call` keeps `ttftS` (time to first token) when the source has it.
89
+ - **Inference Sizer**: the operating point (used by `fleetops shadow plan` and the validations) now counts prefix-cache
90
+ hits. Only the uncached part of a prompt is prefilled, as the sizing already assumed. Predictions for workloads with a
91
+ cache hit rate give a shorter TTFT than before.
92
+
93
+ ### Fixed
94
+
95
+ - **Paths on Windows:** harness-ledger expands a leading `~` to the home folder itself. Command Prompt and PowerShell
96
+ pass `~` through unexpanded, so before this `aiinfra suggest ~/.claude/projects` failed there with ENOENT. (#90)
97
+ - **Models without an example price:** when most calls are on a model the example price table doesn't list, such as a
98
+ newer Claude model, costs are now in relative units, with a note saying so. Before, every change on those calls
99
+ saved $0, so `suggest` raised nothing. When nothing clears the bar, `suggest` now says why: the closest changes, the
100
+ `--min-gain` threshold, and missing timings. (#90)
101
+
6
102
  ## 0.4.0 (2026-11-29)
7
103
 
8
104
  The services now deploy anywhere with one command, and the catalog is current. `deploy/cloud/up.sh` puts fleetops,
package/README.md CHANGED
@@ -102,6 +102,36 @@ All skills need Node.js 22+ and nothing else.
102
102
 
103
103
  **Changing a tool.** The skill folders carry copies of the tools' code (`scripts/`), docs (`references/`) and examples (`assets/`), so each folder works on its own. After editing a tool, run `node scripts/build-skills.mjs`. CI fails while the copies are out of date. `node --test scripts/test-skills.mjs` runs each skill's documented commands from an isolated copy.
104
104
 
105
+ ## Optimize across the stack
106
+
107
+ `aiinfra assess traces/` reads agent logs or traces once and gives four things:
108
+
109
+ - the workload's classes (critical, realtime, agentic, reasoning, batch), with input:output token ratios and what bounds
110
+ each;
111
+ - why the prefix cache misses: which part of the prompt breaks it, and the engine's own hit rate against what the traces
112
+ could reuse;
113
+ - for each goal, every change across prompt, cache, harness, context, agent, model, model options, serving, GPU and
114
+ scheduling that moves it;
115
+ - the best combinations of those changes.
116
+
117
+ `aiinfra advise --goal ttft --apply …` dry-runs a combination and gates it in CI with `--fail-if`; the repository is
118
+ also a GitHub Action. `aiinfra quality` replays real tasks on both endpoints and blocks a drop in success rate. See
119
+ [docs/OPTIMIZE.md](docs/OPTIMIZE.md).
120
+
121
+ `aiinfra suggest` raises those changes where people already look, once each, and remembers what was accepted,
122
+ dismissed or snoozed. The places are:
123
+
124
+ - Claude Code, through a hook and a status line;
125
+ - pull requests, with a prompt lint and one comment kept up to date;
126
+ - the LiteLLM gateway, live, per request;
127
+ - a Grafana panel;
128
+ - Slack and Lark/Feishu cards;
129
+ - comments on Langfuse sessions;
130
+ - beside the answer in the Inference Sizer and FleetScope pages.
131
+
132
+ It reads your own logs, public agent trajectories (SWE-agent, OpenHands) and Mooncake serving traces. See
133
+ [docs/SUGGEST.md](docs/SUGGEST.md).
134
+
105
135
  ## Workload Intelligence
106
136
 
107
137
  FleetOps now includes a [workload profiler](fleetops/docs/WORKLOADS.md) with six synthetic application profiles (coding agents, chat, report generation, RAG search, deep research and autocomplete). It can inspect existing request logs or FleetOps request records, report workload fingerprints and export privacy-conscious session replay CSVs compatible with FleetScope.
package/bin/aiinfra.mjs CHANGED
@@ -21,10 +21,20 @@ export const TOOLS = {
21
21
  'workload-profile': { file: 'fleetops/tools/workload-profile.mjs', what: 'profile and synthesize application workloads (agents, chat, RAG…)' },
22
22
  'fix-skew': { file: 'hybrid-tracing/tools/fix-skew.mjs', what: 'estimate and remove clock skew from OTLP traces' },
23
23
  'skew-corrector': { file: 'hybrid-tracing/tools/skew-corrector.mjs', what: 'run the skew-corrector service' },
24
+ 'claude-code-hook': { file: 'harness-ledger/integrations/claude-code/aiinfra-hook.mjs', what: 'Claude Code hook: cache misses and tool-output waste shown in Claude Code (--print-settings)' },
25
+ 'claude-code-statusline': { file: 'harness-ledger/integrations/claude-code/aiinfra-statusline.mjs', what: 'Claude Code status line: the session\'s cache hit rate and avoidable spend' },
24
26
  mcp: { file: 'mcp/server.mjs', what: 'run every tool as an MCP server over stdio (for Claude, Cursor and other MCP clients)' },
25
27
  };
26
28
  TOOLS.report = { file: 'bin/report.mjs', what: 'plan → verify → account on one page: sizer prediction, last shadow verdict, calibration, agent economics' };
27
29
  TOOLS.demo = { file: 'fleetops/tools/loop-demo.mjs', what: 'the whole loop on a real week of a GPU cluster: observe → diagnose → simulate → approve → optimize → verify' };
30
+ // commands that are one tool's subcommand, promoted to the top level: `aiinfra assess …` is `aiinfra harness-ledger assess …`
31
+ export const SHORTCUTS = {
32
+ assess: { tool: 'harness-ledger', args: ['assess'], what: 'one report: workload classes and token ratios, prefix-cache doctor, the optimizer per goal' },
33
+ advise: { tool: 'harness-ledger', args: ['advise'], what: 'every change across the stack that moves TTFT, TPOT, cost or GPUs; best combinations; a dry run' },
34
+ suggest: { tool: 'harness-ledger', args: ['suggest'], what: 'the changes worth making, raised once and remembered; to Grafana, Slack, Lark or Langfuse' },
35
+ 'prompt-lint': { tool: 'harness-ledger', args: ['lint'], what: 'prompt templates and request bodies that will miss the prefix cache' },
36
+ quality: { tool: 'fleetops', args: ['shadow', 'quality'], what: 'replay real tasks on the baseline and candidate endpoints; block a drop in success rate' },
37
+ };
28
38
  const ALIASES = { 'inference-sizer': 'sizer', 'gpu-ledger': 'ledger', harness: 'harness-ledger', tracing: 'fix-skew', 'hybrid-tracing': 'fix-skew' };
29
39
  const version = () => JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
30
40
 
@@ -32,6 +42,7 @@ function help() {
32
42
  const w = Math.max(...Object.keys(TOOLS).map(k => k.length));
33
43
  return `aiinfra ${version()}: AIInfraTools from one command\n\nUsage: aiinfra <tool> [args…] (every tool takes --help; most take --json)\n\n` +
34
44
  Object.entries(TOOLS).map(([k, t]) => ` ${k.padEnd(w)} ${t.what}`).join('\n') +
45
+ '\n\nShortcuts:\n' + Object.entries(SHORTCUTS).map(([k, x]) => ` ${k.padEnd(w)} ${x.what} (${x.tool} ${x.args.join(' ')})`).join('\n') +
35
46
  `\n\nAlso: aiinfra version · aiinfra path <tool> (the script's path, for skills and scripts)\nDocs: https://github.com/hardikashah-eng/AIInfraTools\n`;
36
47
  }
37
48
 
@@ -40,6 +51,7 @@ export function main(argv) {
40
51
  if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(help()); return 0; }
41
52
  if (cmd === 'version' || cmd === '--version' || cmd === '-v') { process.stdout.write(version() + '\n'); return 0; }
42
53
  if (cmd === 'path') { const t = TOOLS[ALIASES[rest[0]] || rest[0]]; if (!t) { process.stderr.write(`unknown tool: ${rest[0]}\n`); return 2; } process.stdout.write(path.join(ROOT, t.file) + '\n'); return 0; }
54
+ if (SHORTCUTS[cmd]) return main([SHORTCUTS[cmd].tool, ...SHORTCUTS[cmd].args, ...rest]);
43
55
  const t = TOOLS[ALIASES[cmd] || cmd];
44
56
  if (!t) { process.stderr.write(`aiinfra: unknown tool "${cmd}"\n\n${help()}`); return 2; }
45
57
  const r = spawnSync(process.execPath, [path.join(ROOT, t.file), ...rest], { stdio: 'inherit' });
@@ -261,6 +261,77 @@
261
261
  ]
262
262
  }
263
263
  ]
264
+ },
265
+ {
266
+ "id": 6,
267
+ "type": "table",
268
+ "title": "Optimization suggestions",
269
+ "description": "Open suggestions from aiinfra suggest --store: the change, what it moves, its risk and the dry-run command. Accept, dismiss or snooze with aiinfra suggest accept|dismiss|snooze ID.",
270
+ "gridPos": {
271
+ "x": 0,
272
+ "y": 24,
273
+ "w": 24,
274
+ "h": 9
275
+ },
276
+ "targets": [
277
+ {
278
+ "datasource": {
279
+ "type": "yesoreyeram-infinity-datasource",
280
+ "uid": "${DS_FLEETOPS}"
281
+ },
282
+ "refId": "A",
283
+ "type": "json",
284
+ "source": "url",
285
+ "parser": "backend",
286
+ "format": "table",
287
+ "url": "/api/suggestions?status=open",
288
+ "url_options": {
289
+ "method": "GET"
290
+ },
291
+ "columns": [
292
+ {
293
+ "selector": "layer",
294
+ "text": "layer",
295
+ "type": "string"
296
+ },
297
+ {
298
+ "selector": "title",
299
+ "text": "change",
300
+ "type": "string"
301
+ },
302
+ {
303
+ "selector": "goal",
304
+ "text": "goal",
305
+ "type": "string"
306
+ },
307
+ {
308
+ "selector": "effectPct",
309
+ "text": "effect",
310
+ "type": "string"
311
+ },
312
+ {
313
+ "selector": "risk",
314
+ "text": "risk",
315
+ "type": "string"
316
+ },
317
+ {
318
+ "selector": "confidence",
319
+ "text": "from",
320
+ "type": "string"
321
+ },
322
+ {
323
+ "selector": "command",
324
+ "text": "dry run",
325
+ "type": "string"
326
+ },
327
+ {
328
+ "selector": "id",
329
+ "text": "id",
330
+ "type": "string"
331
+ }
332
+ ]
333
+ }
334
+ ]
264
335
  }
265
336
  ]
266
337
  }
@@ -7,8 +7,9 @@ GPUs, an engine version or its configuration, networking, topology, or the servi
7
7
  fleetops shadow plan --baseline-config h100.json --candidate-config b200.json --trace sessions.jsonl --rps 4 --out plan.json
8
8
  fleetops shadow replay --trace sessions.jsonl --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live
9
9
  fleetops shadow answers --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live --out answers.json
10
+ fleetops shadow quality --tasks tasks.jsonl --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live
10
11
  fleetops shadow compare --baseline variant=baseline,source=shadow-replay --candidate variant=candidate,source=shadow-replay \
11
- --plan plan.json --answers answers.json --baseline-gpus 8 --baseline-rate 2.5 --candidate-gpus 8 --candidate-rate 5
12
+ --plan plan.json --answers answers.json --quality .fleetops/shadow/quality.json --baseline-gpus 8 --baseline-rate 2.5 --candidate-gpus 8 --candidate-rate 5
12
13
  fleetops shadow baseline save --name chat --select pool=chat --from 2026-11-01 --to 2026-11-08
13
14
  fleetops shadow watch --name chat --select pool=chat --from 2026-11-24
14
15
  fleetops shadow demo # a candidate that looks faster and isn't
@@ -226,7 +227,29 @@ It reports:
226
227
 
227
228
  Fewer than 98% identical, or a mean log-prob drift over 0.05, is "different", and the decision is roll back however fast
228
229
  the candidate is. Some changes are expected to alter outputs, such as a new quantization. For those, set
229
- `--gates gates.json` with `{ "answers": { "match": 0.9 } }` and check quality separately.
230
+ `--gates gates.json` with `{ "answers": { "match": 0.9 } }` and check quality with the quality gate.
231
+
232
+ ## Quality gate
233
+
234
+ Identical tokens are the wrong bar for a change that is meant to alter outputs (FP8 or FP4 weights, an FP8 KV cache, a
235
+ new model, a capped tool output or a compacted context upstream). What matters is whether the candidate still solves the
236
+ tasks. `shadow quality` replays real evaluation tasks on both endpoints at temperature 0 and checks each answer:
237
+
238
+ ```jsonl
239
+ {"id": "refund-policy", "prompt": "Can I return an opened item after 40 days?", "check": {"type": "contains", "value": "30 days"}}
240
+ {"id": "sum", "messages": [{"role": "user", "content": "What is 17 * 23?"}], "check": {"type": "number", "value": 391}}
241
+ {"id": "json", "prompt": "Return the order as JSON with id and status.", "check": {"type": "json", "value": {"status": "shipped"}}}
242
+ ```
243
+
244
+ Checks: `contains`, `not-contains`, `regex`, `exact`, `number` (within `tol`), `json` (parses; with `value`, those keys
245
+ match). The comparison is paired by task: only the tasks one arm solved and the other didn't carry information. The gate
246
+ is a non-inferiority test on the difference in success rate: the candidate passes when the lower 95% bound of
247
+ (candidate − baseline) is above −`--max-drop` points (2 by default). A clear drop is **worse** and `compare --quality`
248
+ rolls back; an unsettled result with fewer than `--min-tasks` (20) or a wide interval is **inconclusive**, and the
249
+ decision is to extend the test, with an estimate of how many more tasks would settle it. Endpoint errors count as
250
+ failures. Nothing is sent without `--live`, and only task ids, pass/fail and counts are written (no prompts or answers).
251
+
252
+ `harness-ledger advise` marks the changes that carry quality risk; its dry run names this gate as the next step for them.
230
253
 
231
254
  ## Safety
232
255
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fleetops",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "Shared data layer, continuous calibration, root-cause analysis and safe optimization across the AIInfraTools utilities.",
@@ -7,6 +7,7 @@
7
7
  // GET /api/diagnose?symptom=S&from=T&to=T[&pool=P&job=J&nodes=a,b]
8
8
  // GET /api/goodput?from=T&to=T[&job=J&format=html|md] training goodput (unscoped or infra tokens)
9
9
  // GET /api/tune?from=T&to=T[&format=md] tuning recommendations (unscoped or infra tokens)
10
+ // GET /api/suggestions[?status=open&from=T] aiinfra suggest's suggestions, the latest record per id
10
11
  // Grafana: the Infinity data source (JSON, backend parser) reads /api/series and /api/incidents directly; see
11
12
  // deploy/grafana-dashboard.json.
12
13
  import { whereFrom } from './store.mjs';
@@ -48,6 +49,13 @@ export function handleApi(store, who, method, rawUrl) {
48
49
  const recs = scoped(q.kind, store.query(q.kind, { from, to, where: whereFrom(u.searchParams.getAll('where')) }), to).slice(0, limit);
49
50
  return json(recs, recs.length);
50
51
  }
52
+ if (p === '/api/suggestions') {
53
+ const latest = new Map();
54
+ for (const r of scoped('suggestion', store.query('suggestion', { from: time(q.from), to: time(q.to) }), time(q.to))) { const cur = latest.get(r.id); if (!cur || r.t >= cur.t) latest.set(r.id, r); }
55
+ const recs = [...latest.values()].filter(r => !q.status || r.status === q.status).sort((a, b) => Math.abs(b.effect || 0) - Math.abs(a.effect || 0))
56
+ .map(r => Object.assign({}, r, { effectPct: r.effect != null ? `${r.effect > 0 ? '+' : ''}${(100 * r.effect).toFixed(1)}%` : '', time: new Date(r.t * 1000).toISOString() }));
57
+ return json(recs, recs.length);
58
+ }
51
59
  if (p === '/api/series') {
52
60
  const kind = q.kind || 'device', field = q.field, step = Math.max(1, num(q.step, 60)), agg = AGG[q.agg || 'avg'];
53
61
  if (!field || !agg) return { status: 400, type: 'text/plain', body: 'field is required; agg is avg|max|min|sum|count|p50|p99\n' };
@@ -31,6 +31,8 @@
31
31
  // check a node check before admission (tools/admit-node.sh): { node, check: dcgm-diag|rvs-diag|nccl-allreduce|burn-in|pcie|gpu-count, ok?, value?, unit?, detail? }
32
32
  // admission a node's admission verdict: { node, verdict: admit|reject|incomplete, failed, missing, by? }
33
33
  // rollout a step of a version rollout: { id, event: applied|verified|rolled-back|halted, stage, field, version, nodes }
34
+ // suggestion a change worth making, from aiinfra suggest: { id, change, status: open|accepted|dismissed|snoozed, layer, title,
35
+ // goal, effect, saves, risk, confidence, command, sessions } (the latest per id is current: /api/suggestions)
34
36
  // Later PRs add calibration, drift, incident and optimization records.
35
37
 
36
38
  export const KINDS = {
@@ -60,6 +62,7 @@ export const KINDS = {
60
62
  check: ['node', 'check'],
61
63
  admission: ['node', 'verdict'],
62
64
  rollout: ['id', 'event'],
65
+ suggestion: ['id', 'change', 'status'],
63
66
  };
64
67
 
65
68
  export const JOB_STATUS = new Set(['ok', 'failed', 'killed', 'cancelled', 'timeout', 'retried']);
@@ -0,0 +1,107 @@
1
+ // The quality gate: replay real evaluation tasks on the baseline and the candidate endpoint and block the change when
2
+ // the candidate solves fewer of them. Latency checks say whether a change is faster; this says whether it still does
3
+ // the work (a quantized model, a capped tool output, a compacted context or a new model can all change answers).
4
+ //
5
+ // Tasks, one JSON object per line:
6
+ // { "id": "t1", "prompt": "…" | "messages": [ … ], "check": { "type": "contains", "value": "Paris" }, "maxTokens": 256 }
7
+ // Checks (on the answer text):
8
+ // contains / not-contains a substring (case-insensitive unless "case": true)
9
+ // regex a regular expression ("flags" optional)
10
+ // exact the whole answer, trimmed
11
+ // number the last number in the answer within "tol" (absolute, default 0) of "value"
12
+ // json the answer (or its first {…} block) parses as JSON; with "value", every key in value matches
13
+ // Both arms answer every task at temperature 0. The comparison is paired: each task is solved by both, neither, or one
14
+ // of the two, and only the tasks where they disagree carry information. The verdict is a non-inferiority test on the
15
+ // difference in success rate: the candidate passes when the lower 95% bound of (candidate − baseline) is above
16
+ // −maxDrop. Nothing is sent without --live; only task ids, pass/fail and counts are kept (no prompts or answers).
17
+ export const DEFAULTS = { maxDrop: 0.02, minTasks: 20, maxTokens: 512, concurrency: 8, timeoutS: 300 };
18
+
19
+ export function loadTasks(text) {
20
+ const tasks = [];
21
+ String(text).split(/\r?\n/).forEach((l, i) => {
22
+ const s = l.trim(); if (!s || s.startsWith('#')) return;
23
+ let t; try { t = JSON.parse(s); } catch { throw new Error(`tasks line ${i + 1}: not JSON`); }
24
+ if (!t.prompt && !Array.isArray(t.messages)) throw new Error(`tasks line ${i + 1}: needs "prompt" or "messages"`);
25
+ if (!t.check || !CHECKS[t.check.type]) throw new Error(`tasks line ${i + 1}: "check.type" one of ${Object.keys(CHECKS).join(', ')}`);
26
+ tasks.push({ id: String(t.id ?? `task-${i + 1}`), prompt: t.prompt, messages: t.messages, check: t.check, maxTokens: t.maxTokens });
27
+ });
28
+ const ids = new Set(); for (const t of tasks) { if (ids.has(t.id)) throw new Error(`tasks: duplicate id ${t.id}`); ids.add(t.id); }
29
+ return tasks;
30
+ }
31
+
32
+ const lastNumber = s => { const m = String(s).replace(/,(?=\d{3}\b)/g, '').match(/-?\d+(?:\.\d+)?(?:e[-+]?\d+)?/gi); return m ? Number(m[m.length - 1]) : null; };
33
+ const jsonOf = s => { try { return JSON.parse(s); } catch { const m = String(s).match(/\{[\s\S]*\}/); if (!m) return undefined; try { return JSON.parse(m[0]); } catch { return undefined; } } };
34
+ const subset = (want, got) => (want && typeof want === 'object' ? got != null && typeof got === 'object' && Object.keys(want).every(k => subset(want[k], got[k])) : want === got);
35
+ export const CHECKS = {
36
+ contains: (a, c) => (c.case ? a.includes(String(c.value)) : a.toLowerCase().includes(String(c.value).toLowerCase())),
37
+ 'not-contains': (a, c) => !CHECKS.contains(a, c),
38
+ regex: (a, c) => new RegExp(c.value, c.flags || '').test(a),
39
+ exact: (a, c) => a.trim() === String(c.value).trim(),
40
+ number: (a, c) => { const x = lastNumber(a); return x != null && Math.abs(x - Number(c.value)) <= Number(c.tol || 0); },
41
+ json: (a, c) => { const j = jsonOf(a); return j !== undefined && (c.value === undefined || subset(c.value, j)); },
42
+ };
43
+ export const check = (answer, chk) => CHECKS[chk.type](String(answer ?? ''), chk);
44
+
45
+ // one answer from an OpenAI-compatible endpoint (vLLM, SGLang, a gateway): chat completions, or plain completions
46
+ export async function ask(arm, task, { model, maxTokens = DEFAULTS.maxTokens, completions = false, fetchImpl = fetch, timeoutS = DEFAULTS.timeoutS } = {}) {
47
+ const headers = { 'content-type': 'application/json' }; if (arm.apiKey) headers.authorization = `Bearer ${arm.apiKey}`;
48
+ const base = { model: arm.model || model, max_tokens: task.maxTokens || maxTokens, temperature: 0, seed: 0 };
49
+ const prompt = task.prompt ?? task.messages.map(m => `${m.role}: ${typeof m.content === 'string' ? m.content : JSON.stringify(m.content)}`).join('\n');
50
+ const body = completions ? { ...base, prompt } : { ...base, messages: task.messages || [{ role: 'user', content: task.prompt }] };
51
+ const ac = new AbortController(), timer = setTimeout(() => ac.abort(), timeoutS * 1000);
52
+ try {
53
+ const res = await fetchImpl(arm.url.replace(/\/$/, '') + (completions ? '/v1/completions' : '/v1/chat/completions'), { method: 'POST', headers, body: JSON.stringify(body), signal: ac.signal });
54
+ if (!res.ok) return { error: `HTTP ${res.status}` };
55
+ const j = await res.json(), c = j.choices && j.choices[0];
56
+ return { text: c ? (completions ? c.text : c.message && c.message.content) ?? '' : '' };
57
+ } catch (e) { return { error: e.name === 'AbortError' ? 'timeout' : e.message }; } finally { clearTimeout(timer); }
58
+ }
59
+
60
+ // paired success rates. results: [{ id, baseline: bool, candidate: bool }]. The interval on the difference uses the
61
+ // discordant counts (lost: baseline solved it and the candidate didn't; gained: the reverse), with half a count added
62
+ // to each so that a run with no disagreements still has a width.
63
+ export function pairedQuality(results, { maxDrop = DEFAULTS.maxDrop, minTasks = DEFAULTS.minTasks } = {}) {
64
+ const n = results.length, bp = results.filter(r => r.baseline).length, cp = results.filter(r => r.candidate).length;
65
+ const lost = results.filter(r => r.baseline && !r.candidate).length, gained = results.filter(r => !r.baseline && r.candidate).length;
66
+ const diff = n ? (cp - bp) / n : 0;
67
+ const b = lost + 0.5, c = gained + 0.5, m = n + 1, d = (c - b) / m, se = Math.sqrt(Math.max(0, b + c - (c - b) ** 2 / m)) / m;
68
+ const lo = d - 1.96 * se, hi = d + 1.96 * se;
69
+ let verdict, why, more = 0;
70
+ if (n < minTasks) { verdict = 'inconclusive'; why = `${n} tasks: at least ${minTasks} are needed to judge`; more = minTasks - n; }
71
+ else if (lo > 0) { verdict = 'better'; why = `the candidate solves more tasks (+${(100 * diff).toFixed(1)} points)`; }
72
+ else if (lo >= -maxDrop) { verdict = 'same'; why = `no drop past ${(100 * maxDrop).toFixed(1)} points (95% bound ${(100 * lo).toFixed(1)})`; }
73
+ else if (hi < -maxDrop || (hi < 0 && diff <= -maxDrop)) { verdict = 'worse'; why = `the candidate solves fewer tasks (${(100 * diff).toFixed(1)} points; ${lost} lost, ${gained} gained)`; }
74
+ else {
75
+ verdict = 'inconclusive'; why = `the drop could be up to ${(100 * -lo).toFixed(1)} points: more tasks needed`;
76
+ const margin = Math.max(0.002, d + maxDrop); more = Math.max(1, Math.ceil(n * ((1.96 * se) / margin) ** 2 - n));
77
+ }
78
+ return { n, baseline: { passed: bp, rate: n ? bp / n : 0 }, candidate: { passed: cp, rate: n ? cp / n : 0 }, lost, gained, diff, lo, hi, maxDrop, verdict, why, more };
79
+ }
80
+
81
+ async function pool(items, k, f) { const out = new Array(items.length); let i = 0; await Promise.all(Array.from({ length: Math.min(k, items.length) }, async () => { while (i < items.length) { const j = i++; out[j] = await f(items[j], j); } })); return out; }
82
+
83
+ export async function runQuality(tasks, arms, { live = false, model, maxTokens, completions = false, concurrency = DEFAULTS.concurrency, maxDrop = DEFAULTS.maxDrop, minTasks = DEFAULTS.minTasks, fetchImpl = fetch, timeoutS } = {}) {
84
+ if (arms.length !== 2) throw new Error('two endpoints: baseline and candidate');
85
+ if (!live) return { dryRun: true, tasks: tasks.length, arms: arms.map(a => a.name), note: `${tasks.length} tasks × 2 endpoints at temperature 0 (${completions ? '/v1/completions' : '/v1/chat/completions'})` };
86
+ const [A, B] = arms;
87
+ const rows = await pool(tasks, concurrency, async t => {
88
+ const [a, b] = await Promise.all([ask(A, t, { model, maxTokens, completions, fetchImpl, timeoutS }), ask(B, t, { model, maxTokens, completions, fetchImpl, timeoutS })]);
89
+ return { id: t.id, baseline: !a.error && check(a.text, t.check), candidate: !b.error && check(b.text, t.check), errors: [a.error && 'baseline', b.error && 'candidate'].filter(Boolean) };
90
+ });
91
+ const q = pairedQuality(rows, { maxDrop, minTasks });
92
+ const errs = k => rows.filter(r => r.errors.includes(k)).length;
93
+ q.baseline.errors = errs('baseline'); q.candidate.errors = errs('candidate');
94
+ return Object.assign({ kind: 'fleetops.shadow-quality', dryRun: false, t: Math.floor(Date.now() / 1000) }, q, {
95
+ changed: rows.filter(r => r.baseline !== r.candidate).map(r => ({ id: r.id, baseline: r.baseline, candidate: r.candidate })) });
96
+ }
97
+
98
+ export function qualityText(q) {
99
+ if (q.dryRun) return `dry run: ${q.note}. Add --live to send them.`;
100
+ const L = [`quality: ${q.verdict.toUpperCase()}: ${q.why}`,
101
+ ` ${q.n} tasks; baseline solved ${q.baseline.passed} (${(100 * q.baseline.rate).toFixed(1)}%), candidate ${q.candidate.passed} (${(100 * q.candidate.rate).toFixed(1)}%)`,
102
+ ` difference ${(100 * q.diff).toFixed(1)} points (95% CI ${(100 * q.lo).toFixed(1)} to ${(100 * q.hi).toFixed(1)}); ${q.lost} lost, ${q.gained} gained; gate: no drop past ${(100 * q.maxDrop).toFixed(1)} points`];
103
+ if (q.baseline.errors || q.candidate.errors) L.push(` endpoint errors (counted as failures): baseline ${q.baseline.errors}, candidate ${q.candidate.errors}`);
104
+ if (q.verdict === 'inconclusive' && q.more) L.push(` about ${q.more} more tasks would settle it`);
105
+ if (q.changed && q.changed.length) L.push(` tasks that changed: ${q.changed.slice(0, 12).map(x => `${x.id} ${x.baseline ? 'lost' : 'gained'}`).join(', ')}${q.changed.length > 12 ? ` and ${q.changed.length - 12} more` : ''}`);
106
+ return L.join('\n');
107
+ }
@@ -133,9 +133,12 @@ export function compare(base0, cand0, opt = {}) {
133
133
  for (const [k, p] of Object.entries(opt.predicted)) { const m = metrics[k]; const meas = m ? (m.effect ?? null) : null; if (meas == null || !Number.isFinite(p)) continue; rows.push({ metric: k, predicted: p, measured: meas, off: (1 + meas) / (1 + p) - 1 }); }
134
134
  prediction = { rows, holds: rows.every(r => Math.abs(r.off) <= G.prediction) };
135
135
  }
136
- const d = decide(metrics, answers, prediction);
137
- // answers, prediction and infra appear only when given: absent rather than null, so their shape is part of the --json contract
138
- return Object.assign({ decision: d.decision, why: d.why, paired, requests: { baseline: base.length, candidate: cand.length }, metrics, gates: G }, answers ? { answers } : {}, prediction ? { prediction } : {}, opt.infra ? { infra: opt.infra } : {});
136
+ const quality = opt.quality && !opt.quality.dryRun ? opt.quality : null;
137
+ const d = decide(metrics, answers, prediction, { quality });
138
+ // answers, prediction, quality and infra appear only when given: absent rather than null, so their shape is part of the --json contract
139
+ return Object.assign({ decision: d.decision, why: d.why, paired, requests: { baseline: base.length, candidate: cand.length }, metrics, gates: G }, answers ? { answers } : {}, prediction ? { prediction } : {},
140
+ quality ? { quality: { n: quality.n, baseline: quality.baseline, candidate: quality.candidate, lost: quality.lost, gained: quality.gained, diff: quality.diff, lo: quality.lo, hi: quality.hi, maxDrop: quality.maxDrop, verdict: quality.verdict, why: quality.why } } : {},
141
+ opt.infra ? { infra: opt.infra } : {});
139
142
  }
140
143
 
141
144
  // errors: a difference in rate past the gate, by a one-sided two-proportion test. eb, ec: { n, k } (requests, errors)
@@ -145,15 +148,18 @@ export function errorTest(eb, ec, gate = GATES.errorRate) {
145
148
  }
146
149
 
147
150
  // promote / roll back / extend the test, from the metric verdicts (and answers and the prediction when there are any)
148
- export function decide(metrics, answers = null, prediction = null, { unit = 'requests per arm' } = {}) {
151
+ // quality: a quality-gate result (shadow-quality.mjs): fewer tasks solved rolls back, an unsettled result extends the test
152
+ export function decide(metrics, answers = null, prediction = null, { unit = 'requests per arm', quality = null } = {}) {
149
153
  const vs = Object.entries(metrics).filter(([, m]) => m && m.verdict);
150
154
  const worse = vs.filter(([, m]) => m.verdict === 'worse').map(([k]) => k), open = vs.filter(([, m]) => m.verdict === 'inconclusive').map(([k]) => k);
151
155
  let decision, why;
152
- if (answers && answers.verdict === 'different') { decision = 'roll back'; why = `answers differ (${(100 * answers.matchRate).toFixed(1)}% identical under greedy decoding)`; }
156
+ if (quality && quality.verdict === 'worse') { decision = 'roll back'; why = `quality: ${quality.why}`; }
157
+ else if (answers && answers.verdict === 'different') { decision = 'roll back'; why = `answers differ (${(100 * answers.matchRate).toFixed(1)}% identical under greedy decoding)`; }
153
158
  else if (worse.length) { decision = 'roll back'; why = `worse on ${worse.join(', ')}`; }
154
159
  else if (open.length) { decision = 'extend the test'; why = `not settled on ${open.join(', ')}: about ${Math.max(...open.map(k => metrics[k].more || 0))} more ${unit}`; }
155
160
  else if (['ttft', 'tpot', 'e2e'].every(k => !metrics[k] || metrics[k].verdict === 'no data')) { decision = 'extend the test'; why = 'no latency data to judge yet'; }
156
- else { decision = 'promote'; why = `no metric worse${vs.some(([, m]) => m.verdict === 'better') ? `; better on ${vs.filter(([, m]) => m.verdict === 'better').map(([k]) => k).join(', ')}` : ''}`; }
161
+ else if (quality && quality.verdict === 'inconclusive') { decision = 'extend the test'; why = `quality not settled: ${quality.why}`; }
162
+ else { decision = 'promote'; why = `no metric worse${vs.some(([, m]) => m.verdict === 'better') ? `; better on ${vs.filter(([, m]) => m.verdict === 'better').map(([k]) => k).join(', ')}` : ''}${quality ? `; quality ${quality.verdict} on ${quality.n} tasks` : ''}`; }
157
163
  if (prediction && !prediction.holds) why += '; the prediction was off: recalibrate the sizer for this change';
158
164
  return { decision, why };
159
165
  }
@@ -170,8 +170,11 @@ Shadow upgrades (an infra change measured against the baseline at matched load b
170
170
  the same requests to both endpoints at the same moments (dry run unless --live); results go to the store
171
171
  fleetops shadow answers --baseline URL --candidate URL [--prompts FILE] [--model M] [--live] --out answers.json
172
172
  greedy decoding on both: identical tokens, first divergence, log-probability drift
173
+ fleetops shadow quality --tasks tasks.jsonl --baseline URL --candidate URL [--model M] [--max-drop 2] [--min-tasks 20]
174
+ [--completions] [--concurrency 8] [--live] [--out quality.json]
175
+ real tasks with pass checks on both: success rates paired by task; blocks a drop past --max-drop points
173
176
  fleetops shadow compare --results FILE | --baseline SEL --candidate SEL [--from T --to T]
174
- [--plan plan.json] [--answers answers.json] [--baseline-gpus N --baseline-rate R --candidate-gpus N --candidate-rate R]
177
+ [--plan plan.json] [--answers answers.json] [--quality quality.json] [--baseline-gpus N --baseline-rate R --candidate-gpus N --candidate-rate R]
175
178
  [--baseline-nodes RE --candidate-nodes RE] [--gates gates.json] matched-load verdict: promote, roll back, extend
176
179
  with --plan: a prediction off by more than 15% refits the candidate's sizer efficiencies into
177
180
  <store>/calibration/sizer.json (--calibration F; --no-recalibrate to skip), which plan, inference-sizer --calibration
@@ -7,6 +7,7 @@ import * as Replay from '../../src/shadow-replay.mjs';
7
7
  import * as SProm from '../../src/shadow-prom.mjs';
8
8
  import * as Gate from '../../src/shadow-gate.mjs';
9
9
  import * as Canary from '../../src/shadow-canary.mjs';
10
+ import * as Quality from '../../src/shadow-quality.mjs';
10
11
  import { J, OUT, say, read, time, fmt, pctS } from './common.mjs';
11
12
 
12
13
  // ---------- shadow upgrades ----------
@@ -24,6 +25,7 @@ export function shadowText(r) {
24
25
  if (r.metrics.tokPerGpuS) L.push(` tok/s per GPU ${r.metrics.tokPerGpuS.baseline.toFixed(0)} → ${r.metrics.tokPerGpuS.candidate.toFixed(0)} (${pctS(r.metrics.tokPerGpuS.effect)}; ${r.metrics.tokPerGpuS.note})`);
25
26
  if (r.metrics.costPerMTok) L.push(` $ per M output tokens ${r.metrics.costPerMTok.baseline.toFixed(2)} → ${r.metrics.costPerMTok.candidate.toFixed(2)} (${pctS(r.metrics.costPerMTok.effect)}) ${r.metrics.costPerMTok.verdict}`);
26
27
  if (r.answers) L.push(` answers ${r.answers.identical}/${r.answers.prompts} identical under greedy decoding; log-prob drift ${r.answers.meanAbsLogprobDiff != null ? r.answers.meanAbsLogprobDiff.toFixed(3) : '–'} ${r.answers.verdict}`);
28
+ if (r.quality) L.push(` quality ${r.quality.candidate.passed}/${r.quality.n} tasks vs ${r.quality.baseline.passed}/${r.quality.n} (${pctS(r.quality.diff).replace('%', ' pts')}; ${r.quality.lost} lost, ${r.quality.gained} gained)`.padEnd(52) + ` ${r.quality.verdict}`);
27
29
  if (r.prediction) L.push('', ` prediction ${r.prediction.holds ? 'holds' : 'is off: recalibrate'}: ` + r.prediction.rows.map(x => `${x.metric} predicted ${pctS(x.predicted)}, measured ${pctS(x.measured)}`).join('; '));
28
30
  if (r.infra) L.push('', ' infra: ' + Object.entries(r.infra).map(([k, v]) => v.effect != null ? `${k} ${pctS(v.effect)}` : `${k} ${v.baseline} → ${v.candidate}`).join(', '));
29
31
  return L.join('\n');
@@ -95,13 +97,23 @@ export async function shadowCmd(store, cmd, rest, o) {
95
97
  if (J) { OUT.answers = res; return; }
96
98
  return say(res.dryRun ? `dry run: ${res.note}. Add --live to send them.` : `${res.identical}/${res.prompts} identical; first divergence at token ${res.meanFirstDivergence ?? '–'} on average; log-prob drift ${res.meanAbsLogprobDiff != null ? res.meanAbsLogprobDiff.toFixed(4) : '–'}${opt('out') ? ` → ${opt('out')}` : ''}`);
97
99
  }
100
+ if (cmd === 'quality') {
101
+ if (!opt('tasks') || !opt('baseline') || !opt('candidate')) throw new Error('--tasks FILE.jsonl --baseline URL --candidate URL [--max-drop 2] [--live]');
102
+ const tasks = Quality.loadTasks(read(opt('tasks')));
103
+ const maxDrop = num('max-drop') != null ? num('max-drop') / 100 : Quality.DEFAULTS.maxDrop;
104
+ const res = await Quality.runQuality(tasks, [arm('baseline', opt('baseline')), arm('candidate', opt('candidate'))], { live: !!o.live, model: opt('model'), maxTokens: num('max-tokens'), completions: !!o.completions,
105
+ concurrency: num('concurrency') || Quality.DEFAULTS.concurrency, maxDrop, minTasks: num('min-tasks') ?? Quality.DEFAULTS.minTasks });
106
+ if (!res.dryRun) { const f = opt('out') || path.join(dir, 'quality.json'); fs.writeFileSync(f, JSON.stringify(res, null, 1) + '\n'); res.file = f; }
107
+ if (J) { OUT.quality = res; return; }
108
+ return say(Quality.qualityText(res) + (res.file ? `\nwrote ${res.file}; fleetops shadow compare … --quality ${res.file}` : ''));
109
+ }
98
110
  if (cmd === 'compare') {
99
111
  let base, cand;
100
112
  if (opt('results')) { const rs = readJsonl(opt('results')); base = rs.filter(r => r.variant === 'baseline'); cand = rs.filter(r => r.variant === 'candidate'); }
101
113
  else { if (!opt('baseline') || !opt('candidate')) throw new Error('--results FILE, or --baseline SEL --candidate SEL'); base = requests(opt('baseline')); cand = requests(opt('candidate')); }
102
114
  if (!base.length || !cand.length) throw new Error(`no requests: ${base.length} baseline, ${cand.length} candidate`);
103
115
  const plan = json('plan'), re = k => (opt(k) ? new RegExp(opt(k)) : null);
104
- const r = Shadow.compare(base, cand, { gates: json('gates'), predicted: plan && plan.predicted, answers: json('answers'),
116
+ const r = Shadow.compare(base, cand, { gates: json('gates'), predicted: plan && plan.predicted, answers: json('answers'), quality: json('quality'),
105
117
  baseline: { gpus: num('baseline-gpus'), rate: num('baseline-rate') }, candidate: { gpus: num('candidate-gpus'), rate: num('candidate-rate') },
106
118
  infra: opt('baseline-nodes') ? Shadow.infraSignals(store, { baselineNodes: re('baseline-nodes'), candidateNodes: re('candidate-nodes'), from, to }) : null });
107
119
  fs.appendFileSync(path.join(dir, 'verdicts.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), baseline: opt('baseline') || opt('results'), candidate: opt('candidate') || opt('results'), decision: r.decision, why: r.why, metrics: r.metrics, ...(r.prediction ? { prediction: r.prediction } : {}) }) + '\n');
@@ -200,5 +212,5 @@ export async function shadowCmd(store, cmd, rest, o) {
200
212
  }
201
213
  throw new Error('fleetops shadow canary start | advance | approve | status');
202
214
  }
203
- throw new Error('fleetops shadow demo | plan | replay | answers | compare | baseline save|list | watch | prom | serve | canary');
215
+ throw new Error('fleetops shadow demo | plan | replay | answers | quality | compare | baseline save|list | watch | prom | serve | canary');
204
216
  }
@@ -13,6 +13,7 @@ const inlined = {
13
13
  // the sizer's catalog and model: FleetScope's model list comes from the catalog, its KV per token from the model
14
14
  '/*SIZERCATALOG*/': readFileSync(join(here, '../inference-sizer/src/catalog.js'), 'utf8'),
15
15
  '/*SIZERMODEL*/': readFileSync(join(here, '../inference-sizer/src/model.js'), 'utf8'),
16
+ '/*SIZERSUGGEST*/': readFileSync(join(here, '../inference-sizer/src/suggest.js'), 'utf8'),
16
17
  '/*ENGINE*/': read('src/engine.js'),
17
18
  '/*TEMPLATES*/': read('src/templates.js'),
18
19
  '/*INGEST*/': read('src/ingest.js'),