pi-spine 2.10.0 → 2.12.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.
@@ -0,0 +1,465 @@
1
+ /**
2
+ * Self-contained HTML evidence brief renderer for quota snapshots.
3
+ *
4
+ * Produces a secret-free, inline-styled HTML document from the privacy-safe
5
+ * snapshot built by `src/metrics/quota-snapshot.mjs`. All user-facing strings
6
+ * are escaped before insertion, so the report can be opened as a local file or
7
+ * served without XSS risk.
8
+ *
9
+ * This module intentionally stays offline: it does not call live provider APIs
10
+ * or read API keys. It is designed as the rendering backend for the
11
+ * `spine metrics quota --open` flow (SP-679). The helper `writeHtmlBesideJson`
12
+ * lets the CLI write a `.html` report next to the timestamped JSON snapshot.
13
+ */
14
+
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+
18
+ /**
19
+ * Escape a value for safe insertion into HTML text and attribute contexts.
20
+ *
21
+ * @param {unknown} raw
22
+ * @returns {string}
23
+ */
24
+ export function escapeHtml(raw) {
25
+ return String(raw ?? "")
26
+ .replace(/&/g, "&")
27
+ .replace(/</g, "&lt;")
28
+ .replace(/>/g, "&gt;")
29
+ .replace(/"/g, "&quot;")
30
+ .replace(/'/g, "&#39;");
31
+ }
32
+
33
+ /**
34
+ * Format a number with thousands separators and no decimal junk.
35
+ *
36
+ * @param {number | undefined} value
37
+ * @returns {string}
38
+ */
39
+ function fmtCount(value) {
40
+ if (!Number.isFinite(value)) return "—";
41
+ return new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(value);
42
+ }
43
+
44
+ /**
45
+ * Format a duration in milliseconds as human-readable seconds/milliseconds.
46
+ *
47
+ * @param {number | undefined} ms
48
+ * @returns {string}
49
+ */
50
+ function fmtDuration(ms) {
51
+ if (!Number.isFinite(ms)) return "—";
52
+ if (ms >= 1000) return `${fmtCount(ms / 1000)} s`;
53
+ return `${fmtCount(ms)} ms`;
54
+ }
55
+
56
+ /**
57
+ * Format a currency estimate in USD.
58
+ *
59
+ * @param {number | undefined} usd
60
+ * @returns {string}
61
+ */
62
+ function fmtCost(usd) {
63
+ if (!Number.isFinite(usd)) return "—";
64
+ return new Intl.NumberFormat("en-US", {
65
+ style: "currency",
66
+ currency: "USD",
67
+ maximumFractionDigits: 6,
68
+ }).format(usd);
69
+ }
70
+
71
+ /**
72
+ * CSS class suffix for a source badge.
73
+ *
74
+ * @param {string} source
75
+ * @returns {string}
76
+ */
77
+ function sourceClass(source) {
78
+ if (source === "live") return "live";
79
+ if (source === "estimate") return "estimate";
80
+ if (source === "absent") return "absent";
81
+ return "unknown";
82
+ }
83
+
84
+ /**
85
+ * Compute a numeric score for observed burn so pools can be ordered when no
86
+ * provider quota limit is known. Prefer token volume, then cost, then duration.
87
+ *
88
+ * @param {import("./quota-snapshot.mjs").PoolSnapshot} pool
89
+ * @returns {number}
90
+ */
91
+ function burnScore(pool) {
92
+ const usage = pool.usage || {};
93
+ if (Number.isFinite(usage.tokensIn) || Number.isFinite(usage.tokensOut)) {
94
+ return (usage.tokensIn || 0) + (usage.tokensOut || 0);
95
+ }
96
+ if (Number.isFinite(usage.estimatedUsd)) return usage.estimatedUsd;
97
+ return usage.durationMs || 0;
98
+ }
99
+
100
+ /**
101
+ * Compute remaining headroom when a pool carries a known limit. Most offline
102
+ * snapshots do not include provider limits, so this returns `null` and the
103
+ * report renders an honest "unknown".
104
+ *
105
+ * @param {import("./quota-snapshot.mjs").PoolSnapshot} pool
106
+ * @returns {number | null}
107
+ */
108
+ function remainingHeadroom(pool) {
109
+ if (Number.isFinite(pool.limit) && pool.limit > 0) {
110
+ // When a limit is present, choose the same usage unit as burnScore.
111
+ const usage = pool.usage || {};
112
+ let used = 0;
113
+ if (Number.isFinite(usage.tokensIn) || Number.isFinite(usage.tokensOut)) {
114
+ used = (usage.tokensIn || 0) + (usage.tokensOut || 0);
115
+ } else if (Number.isFinite(usage.estimatedUsd)) {
116
+ used = usage.estimatedUsd;
117
+ } else {
118
+ used = usage.durationMs || 0;
119
+ }
120
+ const remaining = pool.limit - used;
121
+ return Number.isFinite(remaining) ? remaining : null;
122
+ }
123
+ return null;
124
+ }
125
+
126
+ /**
127
+ * Sort pools by remaining headroom descending, with honest unknowns at the
128
+ * bottom. Unknown pools are then ordered by observed burn descending so the
129
+ * biggest consumers are surfaced first.
130
+ *
131
+ * @param {Record<string, import("./quota-snapshot.mjs").PoolSnapshot>} pools
132
+ * @returns {import("./quota-snapshot.mjs").PoolSnapshot[]}
133
+ */
134
+ function sortPoolsByHeadroom(pools) {
135
+ return Object.values(pools).sort((a, b) => {
136
+ const aHeadroom = remainingHeadroom(a);
137
+ const bHeadroom = remainingHeadroom(b);
138
+ if (aHeadroom !== null && bHeadroom !== null) return bHeadroom - aHeadroom;
139
+ if (aHeadroom !== null) return -1;
140
+ if (bHeadroom !== null) return 1;
141
+ return burnScore(b) - burnScore(a);
142
+ });
143
+ }
144
+
145
+ /**
146
+ * Render a single row in the remaining-headroom table.
147
+ *
148
+ * @param {import("./quota-snapshot.mjs").PoolSnapshot} pool
149
+ * @returns {string}
150
+ */
151
+ function renderPoolRow(pool) {
152
+ const usage = pool.usage || {};
153
+ const headroom = remainingHeadroom(pool);
154
+ const headroomCell =
155
+ headroom !== null
156
+ ? `<td class="numeric">${escapeHtml(fmtCount(headroom))}</td>`
157
+ : `<td class="unknown">unknown</td>`;
158
+
159
+ const expectedModels = pool.expectedModels?.length
160
+ ? `<ul class="model-list">${pool.expectedModels
161
+ .map((m) => `<li>${escapeHtml(m)}</li>`)
162
+ .join("")}</ul>`
163
+ : `<span class="muted">none expected</span>`;
164
+
165
+ const observedModels = pool.observedModels?.length
166
+ ? `<ul class="model-list">${pool.observedModels
167
+ .map((m) => `<li>${escapeHtml(m)}</li>`)
168
+ .join("")}</ul>`
169
+ : `<span class="muted">none observed</span>`;
170
+
171
+ const drift = [];
172
+ if (pool.drift?.missingModels?.length) {
173
+ drift.push(`missing: ${pool.drift.missingModels.join(", ")}`);
174
+ }
175
+ if (pool.drift?.unexpectedModels?.length) {
176
+ drift.push(`unexpected: ${pool.drift.unexpectedModels.join(", ")}`);
177
+ }
178
+ const driftCell = drift.length
179
+ ? `<td class="drift">${escapeHtml(drift.join("; "))}</td>`
180
+ : `<td class="drift ok">in config</td>`;
181
+
182
+ return `
183
+ <tr>
184
+ <td class="pool-id">${escapeHtml(pool.poolId)}</td>
185
+ <td><span class="badge source-${sourceClass(pool.source)}">${escapeHtml(pool.source)}</span></td>
186
+ <td>${expectedModels}</td>
187
+ <td>${observedModels}</td>
188
+ <td class="numeric">${escapeHtml(fmtCount(usage.taskCount))}</td>
189
+ <td class="numeric">${escapeHtml(fmtDuration(usage.durationMs))}</td>
190
+ <td class="numeric">${escapeHtml(fmtCount(usage.tokensIn))}</td>
191
+ <td class="numeric">${escapeHtml(fmtCount(usage.tokensOut))}</td>
192
+ <td class="numeric">${escapeHtml(fmtCost(usage.estimatedUsd))}</td>
193
+ ${headroomCell}
194
+ ${driftCell}
195
+ </tr>
196
+ `;
197
+ }
198
+
199
+ /**
200
+ * Render a paragraph describing burn rate and ETA only when the data can
201
+ * support it. Offline snapshots usually lack quota limits and a measurement
202
+ * window, so this section is conservative and reports why it cannot estimate.
203
+ *
204
+ * @param {import("./quota-snapshot.mjs").PoolSnapshot[]} sortedPools
205
+ * @returns {string}
206
+ */
207
+ function renderBurnEta(sortedPools) {
208
+ const poolsWithLimit = sortedPools.filter((p) => remainingHeadroom(p) !== null);
209
+ if (!poolsWithLimit.length) {
210
+ return `
211
+ <p class="muted">
212
+ Burn rate and ETA are not estimable from this snapshot. Provider quota
213
+ limits are not configured, so remaining headroom is unknown. Use this
214
+ report as a burn inventory, not a forecast.
215
+ </p>
216
+ `;
217
+ }
218
+
219
+ const rows = poolsWithLimit
220
+ .map((pool) => {
221
+ const headroom = /** @type {number} */ (remainingHeadroom(pool));
222
+ const score = burnScore(pool);
223
+ const eta = score > 0 && headroom > 0 ? "estimable" : "at or over limit";
224
+ return `
225
+ <tr>
226
+ <td class="pool-id">${escapeHtml(pool.poolId)}</td>
227
+ <td class="numeric">${escapeHtml(fmtCount(score))}</td>
228
+ <td class="numeric">${escapeHtml(fmtCount(headroom))}</td>
229
+ <td>${escapeHtml(eta)}</td>
230
+ </tr>
231
+ `;
232
+ })
233
+ .join("");
234
+
235
+ return `
236
+ <p>Headroom is known for the pools below, but ETA still requires a stable
237
+ measurement window. Treat these as rough indicators.</p>
238
+ <table class="data">
239
+ <thead>
240
+ <tr>
241
+ <th>Pool</th>
242
+ <th>Observed burn</th>
243
+ <th>Remaining headroom</th>
244
+ <th>ETA status</th>
245
+ </tr>
246
+ </thead>
247
+ <tbody>
248
+ ${rows}
249
+ </tbody>
250
+ </table>
251
+ `;
252
+ }
253
+
254
+ /**
255
+ * Render a self-contained HTML evidence brief from a quota snapshot.
256
+ *
257
+ * @param {import("./quota-snapshot.mjs").QuotaSnapshot} snapshot
258
+ * @returns {string}
259
+ */
260
+ export function renderQuotaHtml(snapshot) {
261
+ const generatedAt = snapshot?.generatedAt || new Date().toISOString();
262
+ const source = snapshot?.snapshotSource || "absent";
263
+ const pools = snapshot?.pools || {};
264
+ const sortedPools = sortPoolsByHeadroom(pools);
265
+ const poolCount = sortedPools.length;
266
+ const estimateCount = sortedPools.filter((p) => p.source === "estimate").length;
267
+ const absentCount = sortedPools.filter((p) => p.source === "absent").length;
268
+ const liveCount = sortedPools.filter((p) => p.source === "live").length;
269
+
270
+ const rows = sortedPools.map(renderPoolRow).join("");
271
+
272
+ const html = `<!DOCTYPE html>
273
+ <html lang="en">
274
+ <head>
275
+ <meta charset="UTF-8">
276
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
277
+ <title>Quota Headroom Report</title>
278
+ <style>
279
+ :root {
280
+ color-scheme: light dark;
281
+ --bg: #ffffff;
282
+ --fg: #1a1a1a;
283
+ --muted: #666666;
284
+ --border: #d1d5db;
285
+ --accent: #2563eb;
286
+ --badge-live: #16a34a;
287
+ --badge-estimate: #ca8a04;
288
+ --badge-absent: #6b7280;
289
+ --badge-unknown: #9ca3af;
290
+ --drift: #b91c1c;
291
+ --ok: #15803d;
292
+ }
293
+ @media (prefers-color-scheme: dark) {
294
+ :root {
295
+ --bg: #0b0f19;
296
+ --fg: #e5e7eb;
297
+ --muted: #9ca3af;
298
+ --border: #374151;
299
+ --accent: #60a5fa;
300
+ --badge-live: #22c55e;
301
+ --badge-estimate: #facc15;
302
+ --badge-absent: #9ca3af;
303
+ --badge-unknown: #6b7280;
304
+ --drift: #f87171;
305
+ --ok: #4ade80;
306
+ }
307
+ }
308
+ body {
309
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
310
+ line-height: 1.5;
311
+ margin: 0;
312
+ padding: 1.5rem;
313
+ background: var(--bg);
314
+ color: var(--fg);
315
+ }
316
+ header.masthead {
317
+ border-bottom: 1px solid var(--border);
318
+ padding-bottom: 1rem;
319
+ margin-bottom: 1.5rem;
320
+ }
321
+ h1 { margin: 0 0 0.25rem; font-size: 1.5rem; }
322
+ .claim { color: var(--muted); margin: 0 0 1rem; }
323
+ .meta { display: flex; flex-wrap: wrap; gap: 1rem; font-size: 0.9rem; color: var(--muted); }
324
+ .badge {
325
+ display: inline-block;
326
+ padding: 0.1rem 0.4rem;
327
+ border-radius: 0.25rem;
328
+ font-size: 0.75rem;
329
+ font-weight: 600;
330
+ text-transform: uppercase;
331
+ letter-spacing: 0.02em;
332
+ color: #fff;
333
+ background: var(--badge-unknown);
334
+ }
335
+ .badge.source-live { background: var(--badge-live); }
336
+ .badge.source-estimate { background: var(--badge-estimate); }
337
+ .badge.source-absent { background: var(--badge-absent); }
338
+ section { margin-bottom: 2rem; }
339
+ h2 { font-size: 1.15rem; margin: 0 0 0.75rem; }
340
+ table.data {
341
+ width: 100%;
342
+ border-collapse: collapse;
343
+ font-size: 0.9rem;
344
+ }
345
+ table.data th, table.data td {
346
+ border: 1px solid var(--border);
347
+ padding: 0.5rem 0.6rem;
348
+ text-align: left;
349
+ vertical-align: top;
350
+ }
351
+ table.data th { background: rgba(0,0,0,0.03); font-weight: 600; }
352
+ @media (prefers-color-scheme: dark) { table.data th { background: rgba(255,255,255,0.05); } }
353
+ .numeric { text-align: right; font-variant-numeric: tabular-nums; }
354
+ .pool-id { font-weight: 600; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
355
+ .model-list { list-style: none; margin: 0; padding: 0; }
356
+ .model-list li { padding: 0.05rem 0; }
357
+ .muted { color: var(--muted); }
358
+ .drift { color: var(--drift); }
359
+ .drift.ok { color: var(--ok); }
360
+ .unknown { color: var(--muted); font-style: italic; }
361
+ details {
362
+ border: 1px solid var(--border);
363
+ border-radius: 0.375rem;
364
+ padding: 0.75rem 1rem;
365
+ }
366
+ summary { cursor: pointer; font-weight: 600; }
367
+ details dl { margin: 0.75rem 0 0; }
368
+ details dt { font-weight: 600; }
369
+ details dd { margin: 0 0 0.5rem 1rem; color: var(--muted); }
370
+ </style>
371
+ </head>
372
+ <body>
373
+ <header class="masthead">
374
+ <h1>Quota Headroom Report</h1>
375
+ <p class="claim">Evidence brief built from an offline quota snapshot. No API keys or prompt bodies are included.</p>
376
+ <div class="meta">
377
+ <span>Snapshot: <time datetime="${escapeHtml(generatedAt)}">${escapeHtml(generatedAt)}</time></span>
378
+ <span>Source: <span class="badge source-${sourceClass(source)}">${escapeHtml(source)}</span></span>
379
+ <span>Pools: ${escapeHtml(poolCount)}</span>
380
+ <span>Live: ${escapeHtml(liveCount)}</span>
381
+ <span>Estimate: ${escapeHtml(estimateCount)}</span>
382
+ <span>Absent: ${escapeHtml(absentCount)}</span>
383
+ </div>
384
+ </header>
385
+ <main>
386
+ <section>
387
+ <h2>Remaining Headroom</h2>
388
+ <table class="data">
389
+ <thead>
390
+ <tr>
391
+ <th>Pool</th>
392
+ <th>Source</th>
393
+ <th>Expected models (config)</th>
394
+ <th>Observed models</th>
395
+ <th>Tasks</th>
396
+ <th>Duration</th>
397
+ <th>Tokens in</th>
398
+ <th>Tokens out</th>
399
+ <th>Est. cost</th>
400
+ <th>Remaining headroom</th>
401
+ <th>Drift</th>
402
+ </tr>
403
+ </thead>
404
+ <tbody>
405
+ ${rows}
406
+ </tbody>
407
+ </table>
408
+ </section>
409
+ <section>
410
+ <h2>Burn / ETA</h2>
411
+ ${renderBurnEta(sortedPools)}
412
+ </section>
413
+ <details>
414
+ <summary>Caveats &amp; Glossary</summary>
415
+ <dl>
416
+ <dt>Source</dt>
417
+ <dd>Where the usage numbers came from. <strong>estimate</strong> means observed task metrics; <strong>absent</strong> means no tasks were recorded for that pool; <strong>live</strong> is reserved for future provider-probe enrichment.</dd>
418
+ <dt>Expected models</dt>
419
+ <dd>Models configured for active agent roles in <code>spine-config.json</code>.</dd>
420
+ <dt>Observed models</dt>
421
+ <dd>Models that actually appeared in <code>.spine/run-metrics.jsonl</code> task records.</dd>
422
+ <dt>Remaining headroom</dt>
423
+ <dd>Provider quota minus observed usage. Offline snapshots do not include provider limits, so this is reported as <em>unknown</em> rather than invented.</dd>
424
+ <dt>Drift</dt>
425
+ <dd>Models observed that were not expected, or expected models that were not observed.</dd>
426
+ <dt>Privacy</dt>
427
+ <dd>This report contains no API keys, prompt bodies, or auth file contents.</dd>
428
+ </dl>
429
+ </details>
430
+ </main>
431
+ </body>
432
+ </html>`;
433
+
434
+ return html;
435
+ }
436
+
437
+ /**
438
+ * Derive the HTML report path that corresponds to a JSON snapshot report.
439
+ *
440
+ * @param {string} jsonPath
441
+ * @returns {string}
442
+ */
443
+ export function htmlReportPathForJson(jsonPath) {
444
+ const { dir, name } = path.parse(jsonPath);
445
+ return path.join(dir, `${name}.html`);
446
+ }
447
+
448
+ /**
449
+ * Write an HTML report next to a JSON snapshot file.
450
+ *
451
+ * This is the integration point for SP-679 (`spine metrics quota --open`). The
452
+ * CLI can render the snapshot, write the JSON, then call this helper to create
453
+ * a self-contained HTML file in the same directory.
454
+ *
455
+ * @param {string} jsonPath
456
+ * @param {string} html
457
+ * @param {object} [deps]
458
+ * @param {typeof import("node:fs")} [deps.fs]
459
+ */
460
+ export function writeHtmlBesideJson(jsonPath, html, { fs: fsDep = fs } = {}) {
461
+ const htmlPath = htmlReportPathForJson(jsonPath);
462
+ fsDep.mkdirSync(path.dirname(htmlPath), { recursive: true });
463
+ fsDep.writeFileSync(htmlPath, html, "utf8");
464
+ return htmlPath;
465
+ }