dsh-triage 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/serve.js CHANGED
@@ -1,10 +1,14 @@
1
1
  /**
2
- * `dsh-triage serve` — the local control panel (M4 / `docs/specs/M4-surface.md` §2).
2
+ * `dsh-triage serve` — the local panel (M4 / `docs/specs/M4-surface.md` §2).
3
3
  *
4
- * WHAT IT IS: a read-only window onto the evidence this repo already produces. It lists
5
- * `data/results/*.json`, shows the conclusion and the reasons behind it, and links the
6
- * artifact + its `.sha256`. It deliberately does NOT re-judge anything: a panel that
7
- * invents conclusions would be a second engine with its own drift.
4
+ * WHAT IT IS (R49): the first screen is the answer — is this profile broken, which row, what
5
+ * do I type. `GET /api/summary` carries that projection; the ledger and the `data/results`
6
+ * artifacts live behind two tabs. Before R49 the first screen was a table of artifact names,
7
+ * which is the repo's evidence discipline, not the user's question.
8
+ *
9
+ * It deliberately does NOT re-judge anything: `summary` is built by the same module the CLI
10
+ * uses, from the same `loadAuditData()` object. A panel that invented conclusions would be a
11
+ * second engine with its own drift.
8
12
  *
9
13
  * WHY ZERO DEPENDENCIES: same discipline as the gates (`docs/adr/0003`). A panel that
10
14
  * needs a build step or a framework is a panel that breaks when someone reinstalls.
@@ -15,13 +19,14 @@
15
19
  * - `POST` is refused unless the caller started the process with `--allow-execute`, and
16
20
  * even then this version only answers 501 — running a probe from a browser is a later
17
21
  * step, not a happy accident;
18
- * - artifact names are validated and served from a listing (no path traversal).
22
+ * - artifact names are validated and served from a listing (no path traversal);
23
+ * - every value the page renders is escaped; the page ships no remote assets (CSP below).
19
24
  */
20
25
  import { createServer } from 'node:http';
21
26
  import { randomBytes, timingSafeEqual } from 'node:crypto';
22
27
  import { createHash } from 'node:crypto';
23
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
24
- import { join } from 'node:path';
28
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
29
+ import { isAbsolute, join, relative } from 'node:path';
25
30
  const TOKEN_COOKIE = 'triage_token';
26
31
  const MAX_ARTIFACT_BYTES = 2 * 1024 * 1024;
27
32
  /* -------------------------------- artifacts -------------------------------- */
@@ -48,13 +53,24 @@ export function summarizeArtifact(resultsDir, name) {
48
53
  }
49
54
  let payload = null;
50
55
  try {
51
- const parsed = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
52
- payload = typeof parsed === 'object' && parsed !== null ? parsed : null;
56
+ // Same 2MB ceiling as the detail route: a stray multi-hundred-MB file in the results
57
+ // directory must not be read into memory just because the listing refreshed.
58
+ if (bytes <= MAX_ARTIFACT_BYTES) {
59
+ const parsed = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
60
+ payload = typeof parsed === 'object' && parsed !== null ? parsed : null;
61
+ }
53
62
  }
54
63
  catch {
55
64
  payload = null;
56
65
  }
66
+ // Recorders name their outcome differently: `passed` (smoke/card), `ok` (gates),
67
+ // `expectation_met` (cases). Reading only one of them made two thirds of the listing say
68
+ // "no conclusion" for artifacts that do state one.
69
+ const flag = ['passed', 'ok', 'expectation_met']
70
+ .map((key) => payload?.[key])
71
+ .find((value) => typeof value === 'boolean');
57
72
  const conclusion = readString(payload, ['conclusion']) ??
73
+ (typeof flag === 'boolean' ? (flag ? 'passed' : 'failed') : null) ??
58
74
  readString(payload, ['judged', 'state']) ??
59
75
  readString(payload, ['render', 'status']) ??
60
76
  readString(payload, ['render', 'state']);
@@ -91,6 +107,29 @@ function readSha256File(path) {
91
107
  return null;
92
108
  }
93
109
  }
110
+ /**
111
+ * Resolve an artifact name to a real path inside `resultsDir`, or `null`.
112
+ *
113
+ * The name regex already refuses separators and `..`; this is the second lock. A symlink or
114
+ * NTFS junction planted inside the results directory must not become a read anywhere else on
115
+ * disk, and a file over the 2MB ceiling is refused before it is opened.
116
+ */
117
+ export function resolveArtifact(resultsDir, name) {
118
+ const path = join(resultsDir, name);
119
+ try {
120
+ if (!existsSync(path) || statSync(path).size > MAX_ARTIFACT_BYTES)
121
+ return null;
122
+ const root = realpathSync(resultsDir);
123
+ const real = realpathSync(path);
124
+ const rel = relative(root, real);
125
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel))
126
+ return null;
127
+ return real;
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ }
94
133
  function readString(value, path) {
95
134
  let cursor = value;
96
135
  for (const key of path) {
@@ -100,6 +139,15 @@ function readString(value, path) {
100
139
  }
101
140
  return typeof cursor === 'string' && cursor !== '' ? cursor : null;
102
141
  }
142
+ function readEnvHeadline(payload) {
143
+ const env = typeof payload['env'] === 'object' && payload['env'] !== null ? payload['env'] : null;
144
+ return {
145
+ dsh: readString(env, ['dsh']),
146
+ profile: readString(env, ['profile']),
147
+ platform: readString(env, ['platform']),
148
+ arch: readString(env, ['arch']),
149
+ };
150
+ }
103
151
  /* --------------------------------- server ---------------------------------- */
104
152
  export function createPanelServer(options) {
105
153
  const token = randomBytes(18).toString('base64url');
@@ -109,7 +157,11 @@ export function createPanelServer(options) {
109
157
  token,
110
158
  allowExecute,
111
159
  locale: options.locale ?? 'zh',
112
- audit: options.audit ?? null,
160
+ // One scan at a time: a profile read is fs-bound and synchronous, so ten tabs refreshing
161
+ // together would otherwise queue ten full scans on the event loop. Concurrent callers
162
+ // share the in-flight scan; the next request after it settles starts a fresh one (no TTL,
163
+ // no stale verdict).
164
+ audit: options.audit == null ? null : singleFlight(options.audit),
113
165
  };
114
166
  const server = createServer((request, response) => {
115
167
  // `handle` is async since T-406 (the audit route reads a profile); a rejected promise
@@ -166,7 +218,10 @@ async function handle(request, response, context) {
166
218
  response.writeHead(200, {
167
219
  'content-type': 'text/html; charset=utf-8',
168
220
  // No remote assets: the panel has to work offline and on a locked-down machine.
169
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; script-src 'unsafe-inline'",
221
+ // `connect-src 'self'` is load-bearing: without it `default-src 'none'` also blocks the
222
+ // page's own `fetch()` calls, and the panel renders an empty shell (found by actually
223
+ // opening it in a browser, R49 — the smoke script had never used one).
224
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; script-src 'unsafe-inline'; connect-src 'self'",
170
225
  'cache-control': 'no-store',
171
226
  'set-cookie': `${TOKEN_COOKIE}=${context.token}; HttpOnly; SameSite=Strict; Path=/`,
172
227
  });
@@ -195,9 +250,9 @@ async function handle(request, response, context) {
195
250
  sendJson(response, 400, { error: 'artifact name must be a plain *.json file name' });
196
251
  return;
197
252
  }
198
- const path = join(context.resultsDir, name);
199
- if (!existsSync(path) || statSync(path).size > MAX_ARTIFACT_BYTES) {
200
- sendJson(response, 404, { error: 'artifact not found (or larger than 2MB)' });
253
+ const path = resolveArtifact(context.resultsDir, name);
254
+ if (path === null) {
255
+ sendJson(response, 404, { error: 'artifact not found, larger than 2MB, or outside the results directory' });
201
256
  return;
202
257
  }
203
258
  let payload;
@@ -220,10 +275,29 @@ async function handle(request, response, context) {
220
275
  });
221
276
  return;
222
277
  }
278
+ if (url.pathname === '/api/summary') {
279
+ if (context.audit === null) {
280
+ // The panel was started with `--no-audit`. Say which switch brings it back; never
281
+ // render "0 rows" for a profile nobody read.
282
+ sendJson(response, 501, { error: 'the panel was started with --no-audit; drop the flag to read the current profile' });
283
+ return;
284
+ }
285
+ const started = Date.now();
286
+ const snapshot = await context.audit();
287
+ const ms = Date.now() - started;
288
+ if (!snapshot.ok) {
289
+ sendJson(response, 409, { error: snapshot.message }, { 'x-triage-audit-ms': String(ms) });
290
+ return;
291
+ }
292
+ // One scan, two shapes: the answer and the env it was measured on. The page renders the
293
+ // answer; `env` is here so the first screen can say *which* profile it is talking about.
294
+ sendJson(response, 200, { summary: snapshot.summary, env: readEnvHeadline(snapshot.payload), ms }, { 'x-triage-audit-ms': String(ms) });
295
+ return;
296
+ }
223
297
  if (url.pathname === '/api/audit') {
224
298
  if (context.audit === null) {
225
299
  // 501, not 200 with an empty ledger: "the route is off" is information the user needs.
226
- sendJson(response, 501, { error: 'audit is not enabled; restart the panel with `dsh-triage serve --audit`' });
300
+ sendJson(response, 501, { error: 'audit is off (the panel was started with --no-audit); drop the flag to read the current profile' });
227
301
  return;
228
302
  }
229
303
  // Measured 2026-10-28 on a 156-row real profile: 376–690ms, synchronously (the scan is
@@ -245,6 +319,27 @@ async function handle(request, response, context) {
245
319
  sendJson(response, 404, { error: `no route ${url.pathname}` });
246
320
  }
247
321
  /* --------------------------------- helpers --------------------------------- */
322
+ /**
323
+ * Share one in-flight scan between concurrent requests.
324
+ *
325
+ * Deliberately has no TTL: once the scan settles the next caller re-reads the profile, so the
326
+ * panel never shows a verdict older than the last click. This only prevents *pile-up*, not
327
+ * staleness.
328
+ */
329
+ function singleFlight(run) {
330
+ let inFlight = null;
331
+ return () => {
332
+ if (inFlight !== null)
333
+ return inFlight;
334
+ const started = run();
335
+ inFlight = started;
336
+ const clear = () => {
337
+ inFlight = null;
338
+ };
339
+ started.then(clear, clear);
340
+ return started;
341
+ };
342
+ }
248
343
  function sameToken(presented, expected) {
249
344
  if (presented === null)
250
345
  return false;
@@ -279,154 +374,941 @@ export function sha256OfText(text) {
279
374
  return createHash('sha256').update(text).digest('hex');
280
375
  }
281
376
  /**
282
- * The page is intentionally plain: one table, a detail pane, no framework, no remote
283
- * assets. Everything it shows comes from `/api/artifacts` and `/api/artifact`.
377
+ * The page (R50): three layers, nothing else.
378
+ *
379
+ * status — one sentence and one number, the width of the text, no boxes;
380
+ * issues — the rows that need a decision, one line each;
381
+ * commands — the exact strings to type, one click each.
382
+ *
383
+ * Everything the answer rests on (the artifact ledger and the raw `audit --json`
384
+ * payload) stays one Tab away instead of competing with it. The detail level is a real
385
+ * switch, not a matter of taste: `simple` hides the ledger entirely and says every issue
386
+ * in everyday words; `advanced` keeps the ledger, the six counters and audit's own wording.
387
+ *
388
+ * No framework, no remote assets, no inline event handlers: everything is built from the two
389
+ * JSON routes and escaped on the way in (see `esc` below). `data-copy` buttons carry the exact
390
+ * command text, so "what do I type" is one click instead of a transcription.
284
391
  */
285
392
  export function renderPanelHtml(locale) {
286
- const copy = locale === 'zh'
287
- ? {
288
- title: '分诊台 · 证据面板',
289
- lede: '只读:这里显示的是 data/results 里已有的产物,不重新判定任何东西。',
290
- refresh: '刷新',
291
- empty: '没有找到产物。用 --results <目录> 指向别的位置,或先跑一次 record_* 脚本。',
292
- name: '产物',
293
- kind: '类型',
294
- subject: '对象',
295
- conclusion: '结论',
296
- at: '生成时间',
297
- hash: 'sha256',
298
- pick: '点一行看详情',
299
- readOnly: '只读模式',
300
- composition: '当前组合(audit,与 CLI 同一个引擎)',
301
- compositionOff: '未启用 /api/audit:用 `dsh-triage serve --audit` 重启面板才显示当前组合',
302
- compositionFailed: '读不到当前组合',
303
- }
304
- : {
305
- title: 'Triage · evidence panel',
306
- lede: 'Read-only: this lists artifacts already in data/results. It does not re-judge anything.',
307
- refresh: 'Refresh',
308
- empty: 'No artifacts found. Point --results at another directory, or run a record_* script first.',
309
- name: 'Artifact',
310
- kind: 'Kind',
311
- subject: 'Subject',
312
- conclusion: 'Conclusion',
313
- at: 'Generated',
314
- hash: 'sha256',
315
- pick: 'Pick a row to see the payload',
316
- readOnly: 'read-only',
317
- composition: 'Current composition (audit, same engine as the CLI)',
318
- compositionOff: '/api/audit is not enabled: restart with `dsh-triage serve --audit` to see the current composition',
319
- compositionFailed: 'the composition could not be read',
320
- };
393
+ const copy = panelCopy(locale);
394
+ // The copy is static, but `<` is escaped anyway: a future string must never be able to
395
+ // close the `<script>` block it is injected into.
396
+ const copyJson = JSON.stringify(copy).replace(/</g, '\\u003c');
321
397
  return `<!doctype html>
322
- <html lang="${locale}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
398
+ <html lang="${locale}" data-theme="auto"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
323
399
  <title>${copy.title}</title>
324
400
  <style>
325
- :root { color-scheme: light dark; --line:#8884; --muted:#888; }
326
- body { font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif; margin:0; padding:24px; max-width:1200px; }
327
- h1 { font-size:18px; margin:0 0 6px; }
328
- p.lede { color:var(--muted); margin:0 0 18px; }
329
- .bar { display:flex; gap:12px; align-items:center; margin-bottom:12px; }
330
- .badge { border:1px solid var(--line); border-radius:999px; padding:2px 10px; color:var(--muted); font-size:12px; }
331
- table { border-collapse:collapse; width:100%; }
332
- th,td { text-align:left; padding:6px 8px; border-bottom:1px solid var(--line); vertical-align:top; }
333
- th { font-size:12px; color:var(--muted); font-weight:600; }
334
- tbody tr { cursor:pointer; } tbody tr:hover { background:#8881; }
335
- code { font-family:ui-monospace,SFMono-Regular,Consolas,monospace; font-size:12px; }
336
- #detail { margin-top:18px; }
337
- #composition { border:1px solid var(--line); border-radius:8px; padding:10px 12px; margin-bottom:14px; }
338
- #composition h2 { font-size:13px; margin:0 0 6px; color:var(--muted); }
339
- pre { background:#8881; padding:12px; border-radius:8px; overflow:auto; max-height:60vh; }
340
- .ok { color:#2b8a3e; } .bad { color:#c92a2a; } .warn { color:#e8590c; } .unknown { color:#868e96; }
401
+ :root {
402
+ color-scheme: light dark;
403
+ --bg:#fcfcfc; --fg:#1b1b1b; --muted:#6f7278; --line:#e4e4e4; --soft:#f3f3f3;
404
+ --ok:#0f7a52; --warn:#95591a; --bad:#b42318;
405
+ }
406
+ @media (prefers-color-scheme: dark) {
407
+ :root[data-theme="auto"] {
408
+ --bg:#151516; --fg:#e8e8e8; --muted:#8d9096; --line:#2b2b2c; --soft:#1e1e1f;
409
+ --ok:#4fbf8b; --warn:#d3a04a; --bad:#e07a72;
410
+ }
411
+ }
412
+ :root[data-theme="dark"] {
413
+ --bg:#151516; --fg:#e8e8e8; --muted:#8d9096; --line:#2b2b2c; --soft:#1e1e1f;
414
+ --ok:#4fbf8b; --warn:#d3a04a; --bad:#e07a72;
415
+ }
416
+ :root[data-theme="light"] { color-scheme:light; }
417
+ :root[data-theme="dark"] { color-scheme:dark; }
418
+ * { box-sizing:border-box; }
419
+ html,body { margin:0; }
420
+ body {
421
+ background:var(--bg); color:var(--fg); min-height:100vh;
422
+ font:14px/1.6 ui-sans-serif,system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
423
+ -webkit-font-smoothing:antialiased;
424
+ }
425
+ h1,h2,h3 { margin:0; font-weight:600; }
426
+ code,pre,.mono,input,select { font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace; }
427
+ button { font:inherit; color:inherit; background:none; border:none; padding:0; cursor:pointer; }
428
+ :focus-visible { outline:1.5px solid var(--fg); outline-offset:2px; }
429
+ .grow { flex:1; }
430
+ .hint { color:var(--muted); font-size:11.5px; }
431
+
432
+ /* ---------------------------------- bar ---------------------------------- */
433
+ .bar {
434
+ position:sticky; top:0; z-index:20; display:flex; align-items:center; gap:14px; flex-wrap:wrap;
435
+ padding:0 24px; min-height:52px; background:var(--bg); border-bottom:1px solid var(--line);
436
+ }
437
+ .brand { font-weight:650; letter-spacing:.01em; }
438
+ .brand span { margin-left:7px; color:var(--muted); font-size:11px; font-weight:500; letter-spacing:.1em; text-transform:uppercase; }
439
+ .env { display:flex; gap:14px; flex-wrap:wrap; color:var(--muted); font-size:12px; }
440
+ .env .mono { font-size:11.5px; }
441
+ .env b { font-weight:500; color:var(--fg); }
442
+ .seg { display:flex; border:1px solid var(--line); border-radius:4px; overflow:hidden; }
443
+ .seg button { padding:4px 11px; font-size:12.5px; color:var(--muted); }
444
+ .seg button + button { border-left:1px solid var(--line); }
445
+ .seg button[aria-pressed="true"] { background:var(--soft); color:var(--fg); font-weight:600; }
446
+ .btn { border:1px solid var(--line); border-radius:4px; padding:4px 11px; font-size:12.5px; background:var(--bg); }
447
+ .btn:hover { background:var(--soft); }
448
+ .btn.primary { background:var(--fg); color:var(--bg); border-color:var(--fg); }
449
+ .btn.primary:hover { opacity:.86; }
450
+ .btn.tiny { padding:2px 8px; font-size:12px; }
451
+ .btn.quiet { border-color:transparent; color:var(--muted); padding:2px 6px; }
452
+ .btn.quiet:hover { color:var(--fg); background:var(--soft); }
453
+
454
+ main { max-width:900px; margin:0 auto; padding:0 24px 120px; }
455
+
456
+ /* --------------------------------- status -------------------------------- */
457
+ .status { padding:26px 0 22px; border-bottom:1px solid var(--line); }
458
+ .status-line { display:flex; align-items:center; gap:10px; }
459
+ .sig { width:8px; height:8px; border-radius:2px; background:var(--muted); flex:0 0 auto; }
460
+ .status.ok .sig { background:var(--ok); }
461
+ .status.attention .sig { background:var(--warn); }
462
+ .status.broken .sig { background:var(--bad); }
463
+ .status h1 { font-size:17px; line-height:1.5; font-weight:600; letter-spacing:-.01em; overflow-wrap:anywhere; }
464
+ .figure { margin-left:auto; display:flex; align-items:baseline; gap:5px; flex:0 0 auto; }
465
+ .figure b { font-size:22px; font-weight:600; line-height:1; font-variant-numeric:tabular-nums; }
466
+ .figure span { color:var(--muted); font-size:11.5px; }
467
+ .meta { margin:8px 0 0; color:var(--muted); font-size:12px; overflow-wrap:anywhere; }
468
+ .actions { display:flex; align-items:center; gap:12px; flex-wrap:wrap; margin-top:16px; }
469
+ .actions:empty { display:none; }
470
+ .actions .note { color:var(--muted); font-size:12px; }
471
+ .actions .note .mono { font-size:11.5px; }
472
+
473
+ /* --------------------------- six counters (advanced) --------------------- */
474
+ .counts { display:flex; flex-wrap:wrap; align-items:baseline; margin-top:18px; padding-top:12px; border-top:1px solid var(--line); }
475
+ .count { display:inline-flex; align-items:baseline; gap:5px; padding:1px 0; font-size:12px; color:var(--muted); border-radius:3px; }
476
+ .count + .count { margin-left:16px; padding-left:16px; border-left:1px solid var(--line); }
477
+ .count b { font-size:13px; font-weight:600; color:var(--fg); font-variant-numeric:tabular-nums; }
478
+ .count.bad b { color:var(--bad); }
479
+ .count.warn b { color:var(--warn); }
480
+ .count.ok b { color:var(--ok); }
481
+ .count.static { cursor:default; }
482
+ .count[data-filter]:hover { color:var(--fg); }
483
+ .count[aria-pressed="true"] { color:var(--fg); background:var(--soft); padding-left:6px; padding-right:6px; }
484
+ .count[aria-pressed="true"] b { text-decoration:underline; text-underline-offset:3px; }
485
+
486
+ /* --------------------------------- blocks -------------------------------- */
487
+ .block { margin-top:28px; }
488
+ .block-head { display:flex; align-items:baseline; gap:10px; margin-bottom:4px; }
489
+ .block-head h2 { font-size:12px; font-weight:600; letter-spacing:.06em; color:var(--muted); }
490
+ .block-head .num { font-size:12px; color:var(--muted); font-variant-numeric:tabular-nums; }
491
+ .list > :first-child { border-top:none; }
492
+ .empty { padding:14px 0; color:var(--muted); font-size:12.5px; }
493
+
494
+ .issue { display:flex; align-items:flex-start; gap:12px; padding:11px 0; border-top:1px solid var(--line); }
495
+ .kbadge { flex:0 0 46px; font-size:11.5px; line-height:1.7; color:var(--muted); }
496
+ .kbadge.bad { color:var(--bad); }
497
+ .kbadge.warn { color:var(--warn); }
498
+ .itext { flex:1; min-width:0; }
499
+ .iid { display:block; font-size:12.5px; font-weight:550; overflow-wrap:anywhere; }
500
+ .iline { display:block; margin-top:2px; color:var(--muted); font-size:12.5px; overflow-wrap:anywhere; }
501
+ .issue .btn { flex:0 0 auto; margin-top:1px; }
502
+ .more { padding:10px 0 0; color:var(--muted); font-size:12px; }
503
+
504
+ .cmd { display:flex; align-items:center; gap:12px; padding:9px 0; border-top:1px solid var(--line); }
505
+ .clabel { flex:0 0 116px; color:var(--muted); font-size:12px; }
506
+ .cmd code { flex:1; min-width:0; overflow:auto; white-space:nowrap; font-size:12.5px; }
507
+
508
+ /* ---------------------------------- tabs --------------------------------- */
509
+ .tabs { display:flex; align-items:center; gap:18px; margin:34px 0 14px; border-bottom:1px solid var(--line); }
510
+ .tabs button { padding:8px 0; margin-bottom:-1px; font-size:12.5px; color:var(--muted); border-bottom:2px solid transparent; }
511
+ .tabs button[aria-selected="true"] { color:var(--fg); border-bottom-color:var(--fg); }
512
+ .tabs .num { margin-left:6px; font-size:11.5px; color:var(--muted); font-variant-numeric:tabular-nums; }
513
+
514
+ .toolbar { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:12px; }
515
+ .toolbar input[type="search"] {
516
+ flex:1 1 240px; min-width:160px; padding:6px 9px; font-size:12.5px;
517
+ border:1px solid var(--line); border-radius:4px; background:var(--bg); color:inherit;
518
+ }
519
+ .toolbar select {
520
+ padding:6px 8px; font-size:12.5px; max-width:190px;
521
+ border:1px solid var(--line); border-radius:4px; background:var(--bg); color:inherit;
522
+ }
523
+
524
+ /* --------------------------------- table --------------------------------- */
525
+ .table-wrap { border:1px solid var(--line); border-radius:4px; overflow:auto; max-height:60vh; }
526
+ table { border-collapse:separate; border-spacing:0; width:100%; table-layout:fixed; }
527
+ thead th {
528
+ position:sticky; top:0; z-index:1; padding:8px 10px; text-align:left; white-space:nowrap;
529
+ font-size:11.5px; font-weight:600; color:var(--muted); background:var(--bg); border-bottom:1px solid var(--line);
530
+ }
531
+ thead th[data-sort] { cursor:pointer; user-select:none; }
532
+ thead th[data-sort]:hover { color:var(--fg); }
533
+ thead th .arrow { margin-left:4px; font-size:9px; opacity:.6; }
534
+ tbody td { padding:7px 10px; vertical-align:top; font-size:12.5px; border-bottom:1px solid var(--line); overflow-wrap:anywhere; }
535
+ tbody td.name { word-break:break-all; }
536
+ tbody tr:last-child td { border-bottom:none; }
537
+ tbody tr { cursor:pointer; }
538
+ tbody tr:hover td { background:var(--soft); }
539
+ tbody tr:focus-visible { outline:1.5px solid var(--fg); outline-offset:-2px; }
540
+ tbody .empty { padding:22px 10px; }
541
+ th:nth-child(1),td:nth-child(1) { width:36%; }
542
+ th:nth-child(2),td:nth-child(2) { width:9%; }
543
+ th:nth-child(3),td:nth-child(3) { width:13%; }
544
+ th:nth-child(4),td:nth-child(4) { width:8%; }
545
+ th:nth-child(5),td:nth-child(5) { width:18%; font-variant-numeric:tabular-nums; }
546
+ th:nth-child(6),td:nth-child(6) { width:16%; }
547
+ .tag { font-size:11.5px; font-weight:600; }
548
+ .tag.ok { color:var(--ok); }
549
+ .tag.bad { color:var(--bad); }
550
+ .tag.warn { color:var(--warn); }
551
+ .tag.muted { color:var(--muted); }
552
+
553
+ /* ---------------------------------- raw ---------------------------------- */
554
+ pre { margin:0; }
555
+ #tab-raw pre, #drawer-body {
556
+ padding:12px; font-size:12px; line-height:1.55; overflow:auto; max-height:62vh;
557
+ white-space:pre-wrap; overflow-wrap:anywhere;
558
+ border:1px solid var(--line); border-radius:4px;
559
+ }
560
+
561
+ /* -------------------------------- drawer --------------------------------- */
562
+ #drawer {
563
+ position:fixed; top:0; right:0; height:100%; width:min(540px,100vw); z-index:40;
564
+ display:flex; flex-direction:column; gap:10px; padding:14px 18px 18px;
565
+ background:var(--bg); border-left:1px solid var(--line);
566
+ }
567
+ #drawer[hidden] { display:none; }
568
+ #drawer header { display:flex; align-items:center; gap:10px; }
569
+ #drawer h3 { flex:1; min-width:0; font-size:12.5px; font-weight:600; overflow-wrap:anywhere; }
570
+ .drawer-actions { display:flex; gap:8px; flex-wrap:wrap; }
571
+ #drawer-body { flex:1; min-height:0; max-height:none; }
572
+ #scrim { position:fixed; inset:0; z-index:30; background:#00000026; }
573
+ #scrim[hidden] { display:none; }
574
+
575
+ .toast {
576
+ position:fixed; left:24px; bottom:20px; z-index:50; padding:5px 12px; border-radius:3px;
577
+ background:var(--fg); color:var(--bg); font-size:12.5px;
578
+ opacity:0; pointer-events:none; transition:opacity .14s;
579
+ }
580
+ .toast.on { opacity:1; }
581
+
582
+ /* ------------------------------ view switch ------------------------------ */
583
+ body[data-view="advanced"] .only-simple { display:none !important; }
584
+ body[data-view="simple"] .only-advanced { display:none !important; }
585
+ body[data-view="simple"] #counts,
586
+ body[data-view="simple"] nav.tabs,
587
+ body[data-view="simple"] #tab-evidence,
588
+ body[data-view="simple"] #tab-raw { display:none !important; }
589
+ @media (max-width:640px) {
590
+ .figure { margin-left:0; }
591
+ .status-line { flex-wrap:wrap; }
592
+ .clabel { flex-basis:100%; }
593
+ }
594
+ @media (prefers-reduced-motion: reduce) { * { transition:none !important; } }
341
595
  </style></head>
342
- <body>
343
- <h1>${copy.title}</h1>
344
- <p class="lede">${copy.lede}</p>
345
- <section id="composition">
346
- <h2>${copy.composition}</h2>
347
- <div id="composition-body" class="badge" data-off="${copy.compositionOff}" data-failed="${copy.compositionFailed}">…</div>
348
- </section>
349
- <div class="bar">
350
- <button id="refresh">${copy.refresh}</button>
351
- <span class="badge" id="mode">${copy.readOnly}</span>
352
- <span class="badge" id="count"></span>
596
+ <body data-view="simple">
597
+
598
+ <header class="bar">
599
+ <span class="brand">${copy.brand}<span>triage</span></span>
600
+ <span class="env">
601
+ <span class="mono" id="pill-dsh">dsh …</span>
602
+ <span class="mono" id="pill-profile">profile …</span>
603
+ <span id="pill-mode">${copy.readOnly}</span>
604
+ </span>
605
+ <span class="grow"></span>
606
+ <div class="seg" role="group" aria-label="${copy.viewLabel}">
607
+ <button id="view-simple" aria-pressed="true">${copy.viewSimple}</button>
608
+ <button id="view-advanced" aria-pressed="false">${copy.viewAdvanced}</button>
353
609
  </div>
354
- <table>
355
- <thead><tr>
356
- <th>${copy.name}</th><th>${copy.kind}</th><th>${copy.subject}</th>
357
- <th>${copy.conclusion}</th><th>${copy.at}</th><th>${copy.hash}</th>
358
- </tr></thead>
359
- <tbody id="rows"></tbody>
360
- </table>
361
- <div id="detail"><p class="lede">${copy.pick}</p></div>
610
+ <button class="btn" id="theme" title="${copy.themeTitle}" aria-label="${copy.themeTitle}">${copy.themes.auto}</button>
611
+ <button class="btn primary" id="refresh" title="${copy.refreshTitle}">${copy.refresh}</button>
612
+ </header>
613
+
614
+ <main>
615
+ <section class="status pending" id="hero" aria-live="polite">
616
+ <div class="status-line">
617
+ <span class="sig" aria-hidden="true"></span>
618
+ <h1 id="headline">${copy.loading}</h1>
619
+ <span class="figure only-simple"><b id="figure-value">—</b><span id="figure-unit">${copy.figureOk}</span></span>
620
+ </div>
621
+ <p class="meta" id="sub">${copy.loadingSub}</p>
622
+ <div class="actions" id="hero-actions"></div>
623
+ <div class="counts" id="counts"></div>
624
+ </section>
625
+
626
+ <section class="block">
627
+ <div class="block-head">
628
+ <h2>${copy.issues}</h2>
629
+ <span class="num" id="issues-count"></span>
630
+ <span class="grow"></span>
631
+ <button class="btn quiet" id="issues-more" hidden>${copy.showAll}</button>
632
+ </div>
633
+ <div class="list" id="issues"></div>
634
+ </section>
635
+
636
+ <section class="block">
637
+ <div class="block-head">
638
+ <h2>${copy.next}</h2>
639
+ <span class="grow"></span>
640
+ <button class="btn quiet" id="copy-report">${copy.copyReport}</button>
641
+ </div>
642
+ <div class="list" id="next"></div>
643
+ </section>
644
+
645
+ <nav class="tabs" role="tablist">
646
+ <button role="tab" data-tab="evidence" aria-selected="false">${copy.evidence}<span class="num" id="ev-count"></span></button>
647
+ <button role="tab" data-tab="raw" aria-selected="false">${copy.raw}</button>
648
+ <span class="grow"></span>
649
+ <span class="hint" id="kbd-hint"></span>
650
+ </nav>
651
+
652
+ <section id="tab-evidence" hidden>
653
+ <div class="toolbar">
654
+ <input id="search" type="search" placeholder="${copy.searchPlaceholder}" aria-label="${copy.searchPlaceholder}">
655
+ <select id="kind" aria-label="${copy.allKinds}"><option value="">${copy.allKinds}</option></select>
656
+ <select id="conclusion" aria-label="${copy.allConclusions}"><option value="">${copy.allConclusions}</option></select>
657
+ <span class="grow"></span>
658
+ <span class="hint" id="ev-shown"></span>
659
+ </div>
660
+ <div class="table-wrap">
661
+ <table>
662
+ <thead><tr>
663
+ <th data-sort="name">${copy.name}<span class="arrow"></span></th>
664
+ <th data-sort="kind">${copy.kind}<span class="arrow"></span></th>
665
+ <th data-sort="subject">${copy.subject}<span class="arrow"></span></th>
666
+ <th data-sort="conclusion">${copy.conclusion}<span class="arrow"></span></th>
667
+ <th data-sort="generated_at">${copy.at}<span class="arrow"></span></th>
668
+ <th>${copy.hash}</th>
669
+ </tr></thead>
670
+ <tbody id="rows"></tbody>
671
+ </table>
672
+ </div>
673
+ </section>
674
+
675
+ <section id="tab-raw" hidden><pre id="raw">…</pre></section>
676
+ </main>
677
+
678
+ <aside id="drawer" hidden aria-hidden="true" tabindex="-1">
679
+ <header><h3 id="drawer-title"></h3><button class="btn" id="drawer-close">${copy.close}</button></header>
680
+ <div class="drawer-actions" id="drawer-actions"></div>
681
+ <pre id="drawer-body"></pre>
682
+ </aside>
683
+ <div id="scrim" hidden></div>
684
+ <div class="toast" id="toast" role="status"></div>
685
+
362
686
  <script>
363
- const esc = (v) => String(v ?? '').replace(/[&<>"]/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
364
- const tone = (c) => ({go:'ok', blocked:'bad', risky:'warn', unknown:'unknown', rendered:'ok', blank:'bad'}[c] ?? '');
365
- async function load() {
366
- const response = await fetch('/api/artifacts');
367
- const data = await response.json();
368
- document.getElementById('count').textContent = data.count + ' artifacts';
369
- document.getElementById('mode').textContent = data.readOnly ? ${JSON.stringify(copy.readOnly)} : 'actions enabled';
370
- const rows = document.getElementById('rows');
371
- rows.innerHTML = '';
372
- if (data.count === 0) {
373
- rows.innerHTML = '<tr><td colspan="6">' + ${JSON.stringify(copy.empty)} + '</td></tr>';
687
+ const COPY = ${copyJson};
688
+ const esc = (v) => String(v == null ? '' : v).replace(/[&<>"']/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
689
+ const $ = (id) => document.getElementById(id);
690
+ const NUM = (n) => (typeof n === 'number' ? n.toLocaleString() : '—');
691
+ const TONE = { go:'ok', passed:'ok', rendered:'ok', blocked:'bad', failed:'bad', blank:'bad', risky:'warn', unknown:'muted' };
692
+ const KIND_TONE = { denied:'bad', collision:'bad', duplicate:'warn', unknown:'muted', unreadable:'bad' };
693
+
694
+ const state = { summary: null, env: {}, ms: null, view: 'simple', artifacts: [], issueFilter: null, showAll: false, query: '', kind: '', conclusion: '', sort: { key: 'generated_at', dir: 'desc' }, evidenceLoaded: false, rawLoaded: false, drawerName: null };
695
+
696
+ let toastTimer = null;
697
+ function toast(text) {
698
+ const el = $('toast');
699
+ el.textContent = text;
700
+ el.classList.add('on');
701
+ clearTimeout(toastTimer);
702
+ toastTimer = setTimeout(() => el.classList.remove('on'), 1500);
703
+ }
704
+
705
+ async function copyText(text) {
706
+ try { await navigator.clipboard.writeText(text); return true; }
707
+ catch (e) {
708
+ const area = document.createElement('textarea');
709
+ area.value = text; area.style.position = 'fixed'; area.style.opacity = '0';
710
+ document.body.appendChild(area); area.select();
711
+ let ok = false;
712
+ try { ok = document.execCommand('copy'); } catch (ignored) { ok = false; }
713
+ area.remove();
714
+ return ok;
715
+ }
716
+ }
717
+
718
+ document.addEventListener('click', async (event) => {
719
+ const target = event.target.closest('[data-copy]');
720
+ if (target === null) return;
721
+ const ok = await copyText(target.getAttribute('data-copy'));
722
+ toast(ok ? COPY.copied : COPY.copyFailed);
723
+ });
724
+
725
+ /* ------------------------------- theme ---------------------------------- */
726
+ const THEME_ORDER = ['auto', 'light', 'dark'];
727
+ function applyTheme(value) {
728
+ const next = THEME_ORDER.indexOf(value) >= 0 ? value : 'auto';
729
+ document.documentElement.setAttribute('data-theme', next);
730
+ $('theme').textContent = COPY.themes[next] || next;
731
+ try { localStorage.setItem('triage-theme', next); } catch (e) {}
732
+ }
733
+ function cycleTheme() {
734
+ const now = document.documentElement.getAttribute('data-theme') || 'auto';
735
+ applyTheme(THEME_ORDER[(THEME_ORDER.indexOf(now) + 1) % THEME_ORDER.length]);
736
+ }
737
+ let initialTheme = 'auto';
738
+ try {
739
+ const savedTheme = localStorage.getItem('triage-theme');
740
+ if (savedTheme) initialTheme = savedTheme;
741
+ } catch (e) {}
742
+ applyTheme(initialTheme);
743
+
744
+ /* ------------------------------ summary ---------------------------------- */
745
+ function envLine() {
746
+ const parts = [];
747
+ const s = state.summary;
748
+ if (state.env.dsh) parts.push('dsh ' + state.env.dsh);
749
+ if (state.env.profile) parts.push('profile ' + state.env.profile);
750
+ if (state.env.platform) parts.push(state.env.platform + '/' + (state.env.arch || '?'));
751
+ if (state.ms !== null) parts.push(COPY.checked.replace('{ms}', String(state.ms)));
752
+ if (s && s.counts && s.counts.rows > s.counts.judged) {
753
+ const template = state.view === 'simple' ? COPY.unjudgedSimple : COPY.unjudged;
754
+ parts.push(template.replace('{n}', NUM(s.counts.rows - s.counts.judged)));
755
+ }
756
+ return parts.join(' · ');
757
+ }
758
+
759
+ /** The number next to the one-line verdict: the same thing the sentence counts. */
760
+ function headlineFigure(summary) {
761
+ const c = summary.counts;
762
+ if (summary.tone === 'broken') return { value: c.denied + c.collisions, unit: COPY.figureBroken };
763
+ if (summary.tone === 'attention') return { value: c.unknown + c.duplicateCopies + c.errors, unit: COPY.figurePending };
764
+ return { value: 0, unit: COPY.figureOk };
765
+ }
766
+
767
+ function count(label, value, tone, filter) {
768
+ const cls = 'count' + (tone ? ' ' + tone : '');
769
+ if (filter === null) {
770
+ return '<span class="' + cls + ' static"><b>' + esc(NUM(value)) + '</b>' + esc(label) + '</span>';
771
+ }
772
+ const pressed = state.issueFilter === filter;
773
+ return '<button class="' + cls + '" data-filter="' + esc(filter) + '" aria-pressed="' + String(pressed) + '">' +
774
+ '<b>' + esc(NUM(value)) + '</b>' + esc(label) + '</button>';
775
+ }
776
+
777
+ function renderSummary() {
778
+ const s = state.summary;
779
+ const hero = $('hero');
780
+ hero.className = 'status ' + s.tone;
781
+ // Simple view says the same thing without jargon; advanced keeps the wording audit prints.
782
+ $('headline').textContent = state.view === 'simple' ? s.plain : s.headline;
783
+ const figure = headlineFigure(s);
784
+ $('figure-value').textContent = NUM(figure.value);
785
+ $('figure-unit').textContent = figure.unit;
786
+ $('copy-report').hidden = false;
787
+ $('sub').textContent = envLine();
788
+ renderHeroAction();
789
+ $('pill-dsh').innerHTML = 'dsh <b>' + esc(state.env.dsh || COPY.unknownValue) + '</b>';
790
+ $('pill-profile').innerHTML = 'profile <b>' + esc(state.env.profile || COPY.unknownValue) + '</b>';
791
+ const c = s.counts;
792
+ $('counts').innerHTML =
793
+ count(COPY.chips.rows, c.rows, '', null) +
794
+ count(COPY.chips.judged, c.judged, '', null) +
795
+ count(COPY.chips.go, c.go, c.go > 0 ? 'ok' : '', 'go') +
796
+ count(COPY.chips.denied, c.denied, c.denied > 0 ? 'bad' : '', 'denied') +
797
+ count(COPY.chips.unknown, c.unknown, c.unknown > 0 ? 'warn' : '', 'unknown') +
798
+ count(COPY.chips.collisions, c.collisions, c.collisions > 0 ? 'bad' : '', 'collision');
799
+ renderIssues();
800
+ renderNext();
801
+ }
802
+
803
+ /** One obvious next action, chosen from the verdict itself. Nothing is executed for the user. */
804
+ function renderHeroAction() {
805
+ const s = state.summary;
806
+ const box = $('hero-actions');
807
+ if (!s || !s.issues) { box.innerHTML = ''; return; }
808
+ const fixable = s.issues.find((issue) => issue.fix !== null && issue.fix !== '');
809
+ if (fixable) {
810
+ box.innerHTML = '<button class="btn primary" data-copy="' + esc(fixable.fix) + '">' + esc(COPY.actionFix) + '</button>' +
811
+ '<span class="note"><span class="mono">' + esc(fixable.id) + '</span> · ' + esc(COPY.actionFixHint) + '</span>';
374
812
  return;
375
813
  }
376
- for (const item of data.artifacts) {
377
- const tr = document.createElement('tr');
378
- tr.innerHTML = '<td><code>' + esc(item.name) + '</code></td><td>' + esc(item.kind) + '</td><td>' + esc(item.subject) +
379
- '</td><td class="' + tone(item.conclusion) + '">' + esc(item.conclusion) + '</td><td>' + esc(item.generated_at) +
380
- '</td><td><code>' + esc((item.sha256 ?? '').slice(0, 12)) + '</code></td>';
381
- tr.onclick = () => show(item.name);
382
- rows.appendChild(tr);
814
+ box.innerHTML = '<button class="btn primary" data-copy="' + esc(reportText()) + '">' + esc(COPY.actionCopy) + '</button>' +
815
+ '<span class="note">' + esc(COPY.actionCopyHint) + '</span>';
816
+ }
817
+
818
+ function issuesMatching() {
819
+ const s = state.summary;
820
+ if (!s) return [];
821
+ const filter = state.issueFilter;
822
+ if (filter === null) return s.issues.slice();
823
+ const kinds = filter === 'duplicate' ? ['duplicate', 'unreadable'] : [filter];
824
+ return s.issues.filter((issue) => kinds.indexOf(issue.kind) >= 0);
825
+ }
826
+
827
+ function renderIssues() {
828
+ const s = state.summary;
829
+ const box = $('issues');
830
+ const all = issuesMatching();
831
+ const filtered = state.issueFilter !== null;
832
+ const list = filtered || state.showAll ? all : all.slice(0, 12);
833
+ const total = filtered ? all.length : all.length + (s.more || 0);
834
+ $('issues-count').textContent = total === 0 ? '' : String(total);
835
+ $('issues-more').hidden = filtered || state.showAll || all.length <= 12;
836
+ if (list.length === 0) {
837
+ box.innerHTML = '<div class="empty">' + esc(filtered ? COPY.noFiltered : COPY.noIssues) + '</div>';
838
+ return;
383
839
  }
840
+ box.innerHTML = list.map((issue) => {
841
+ const tone = KIND_TONE[issue.kind] || 'muted';
842
+ const label = COPY.kindLabels[issue.kind] || issue.kind;
843
+ const fix = issue.fix === null || issue.fix === ''
844
+ ? ''
845
+ : '<button class="btn tiny" data-copy="' + esc(issue.fix) + '" title="' + esc(issue.fix) + '">' + esc(COPY.copy) + '</button>';
846
+ return '<div class="issue"><span class="kbadge ' + tone + '">' + esc(label) + '</span>' +
847
+ '<div class="itext"><span class="iid mono">' + esc(issue.id) + '</span>' +
848
+ '<span class="iline only-simple">' + esc(issue.plain) + '</span>' +
849
+ '<span class="iline only-advanced">' + esc(issue.line) + '</span></div>' +
850
+ fix + '</div>';
851
+ }).join('') +
852
+ (filtered ? '' : s.more > 0 ? '<div class="more">' + esc(COPY.more.replace('{n}', String(s.more))) + '</div>' : '');
384
853
  }
385
- async function show(name) {
386
- const response = await fetch('/api/artifact?name=' + encodeURIComponent(name));
387
- const data = await response.json();
388
- document.getElementById('detail').innerHTML =
389
- '<h1>' + esc(name) + '</h1><p class="lede"><code>' + esc(data.sha256 ?? 'no .sha256') + '</code></p><pre>' +
390
- esc(JSON.stringify(data.payload ?? data, null, 2)) + '</pre>';
854
+
855
+ function renderNext() {
856
+ const steps = state.summary ? state.summary.next.filter((step) => step.command !== 'dsh-triage serve') : [];
857
+ $('next').innerHTML = steps.length === 0
858
+ ? '<div class="empty">' + esc(COPY.noNext) + '</div>'
859
+ : steps.map((step) =>
860
+ '<div class="cmd"><span class="clabel">' + esc(step.label) + '</span><code>' + esc(step.command) + '</code>' +
861
+ '<button class="btn tiny" data-copy="' + esc(step.command) + '">' + esc(COPY.copy) + '</button></div>').join('');
391
862
  }
392
- document.getElementById('refresh').onclick = load;
393
- /**
394
- * T-406: the current composition, straight from /api/audit.
395
- *
396
- * Three answers are kept apart on purpose: disabled (501), unreadable (409 + message), and a
397
- * real ledger. Collapsing them would let a broken profile look like a clean one.
398
- */
399
- async function loadAudit() {
400
- const body = document.getElementById('composition-body');
863
+
864
+ function reportText() {
865
+ const s = state.summary;
866
+ if (!s) return '';
867
+ const c = s.counts;
868
+ const lines = [envLine(), COPY.reportTitle + ' ' + s.headline,
869
+ ' ' + [COPY.chips.rows + ' ' + NUM(c.rows), COPY.chips.judged + ' ' + NUM(c.judged),
870
+ COPY.chips.go + ' ' + NUM(c.go), COPY.chips.denied + ' ' + NUM(c.denied),
871
+ COPY.chips.unknown + ' ' + NUM(c.unknown), COPY.chips.collisions + ' ' + NUM(c.collisions)].join(' · ')];
872
+ if (c.rows > c.judged) lines.push(' ' + COPY.unjudged.replace('{n}', NUM(c.rows - c.judged)));
873
+ if (s.issues.length) {
874
+ lines.push('', COPY.issues + ':');
875
+ for (const issue of s.issues) lines.push(' ' + issue.id + ' — ' + issue.line + (issue.fix ? ' [' + issue.fix + ']' : ''));
876
+ if (s.more > 0) lines.push(' ' + COPY.more.replace('{n}', String(s.more)));
877
+ }
878
+ if (s.next.length) {
879
+ lines.push('', COPY.next + ':');
880
+ for (const step of s.next) lines.push(' ' + step.command + ' ' + step.label);
881
+ }
882
+ return lines.join('\\n');
883
+ }
884
+
885
+ /** Reset the first screen to a state that is not a verdict (off, unreadable, still loading). */
886
+ function resetHero(tone, sentence, meta) {
887
+ state.summary = null;
888
+ $('hero').className = 'status ' + tone;
889
+ $('headline').textContent = sentence;
890
+ $('sub').textContent = meta || '';
891
+ $('figure-value').textContent = '';
892
+ $('figure-unit').textContent = '';
893
+ $('hero-actions').innerHTML = '';
894
+ $('counts').innerHTML = '';
895
+ $('issues-count').textContent = '';
896
+ $('issues-more').hidden = true;
897
+ $('copy-report').hidden = true;
898
+ $('next').innerHTML = '<div class="empty">' + esc(COPY.noNext) + '</div>';
899
+ }
900
+
901
+ async function loadSummary() {
401
902
  let response;
903
+ try { response = await fetch('/api/summary'); }
904
+ catch (error) {
905
+ resetHero('broken', COPY.failed + ': ' + error.message, '');
906
+ return;
907
+ }
908
+ if (response.status === 501) {
909
+ resetHero('pending', COPY.off, '');
910
+ $('issues').innerHTML = '<div class="empty">' + esc(COPY.offIssues) + '</div>';
911
+ $('pill-mode').textContent = COPY.readOnly;
912
+ return;
913
+ }
914
+ let body;
915
+ try { body = await response.json(); } catch (error) { body = {}; }
916
+ if (!response.ok) {
917
+ resetHero('broken', COPY.failed + ': ' + (body.error || response.status), '');
918
+ $('issues').innerHTML = '<div class="empty">' + esc(COPY.failed) + '</div>';
919
+ return;
920
+ }
921
+ state.summary = body.summary;
922
+ state.env = body.env || {};
923
+ state.ms = typeof body.ms === 'number' ? body.ms : null;
924
+ renderSummary();
925
+ }
926
+
927
+ /* ------------------------------ evidence --------------------------------- */
928
+ function fillSelects() {
929
+ const kinds = {};
930
+ const conclusions = {};
931
+ for (const item of state.artifacts) {
932
+ kinds[item.kind] = (kinds[item.kind] || 0) + 1;
933
+ const key = item.conclusion == null ? '∅' : item.conclusion;
934
+ conclusions[key] = (conclusions[key] || 0) + 1;
935
+ }
936
+ const kindSel = $('kind');
937
+ const keepKind = state.kind;
938
+ kindSel.innerHTML = '<option value="">' + esc(COPY.allKinds) + '</option>' +
939
+ Object.keys(kinds).sort().map((k) => '<option value="' + esc(k) + '">' + esc(k) + ' (' + kinds[k] + ')</option>').join('');
940
+ kindSel.value = keepKind;
941
+ const conSel = $('conclusion');
942
+ const keepCon = state.conclusion;
943
+ conSel.innerHTML = '<option value="">' + esc(COPY.allConclusions) + '</option>' +
944
+ Object.keys(conclusions).sort().map((k) => '<option value="' + esc(k) + '">' + esc(COPY.conclusions[k] || k) + ' (' + conclusions[k] + ')</option>').join('');
945
+ conSel.value = keepCon;
946
+ }
947
+
948
+ function visibleArtifacts() {
949
+ const q = state.query.trim().toLowerCase();
950
+ const out = state.artifacts.filter((item) => {
951
+ if (state.kind && item.kind !== state.kind) return false;
952
+ const con = item.conclusion == null ? '∅' : item.conclusion;
953
+ if (state.conclusion && con !== state.conclusion) return false;
954
+ if (!q) return true;
955
+ return (item.name + ' ' + item.kind + ' ' + (item.subject || '') + ' ' + con).toLowerCase().indexOf(q) >= 0;
956
+ });
957
+ const key = state.sort.key;
958
+ const dir = state.sort.dir === 'asc' ? 1 : -1;
959
+ out.sort((a, b) => {
960
+ const av = a[key] == null ? '' : String(a[key]);
961
+ const bv = b[key] == null ? '' : String(b[key]);
962
+ if (av === bv) return a.name < b.name ? -1 : 1;
963
+ return av < bv ? -dir : dir;
964
+ });
965
+ return out;
966
+ }
967
+
968
+ /** The table shows one line per stamp; the full ISO value stays in the cell's title. */
969
+ function shortStamp(value) {
970
+ if (!value) return '';
971
+ return String(value).replace('T', ' ').replace(/\\.\\d+Z?$/, '').replace(/Z$/, '');
972
+ }
973
+
974
+ function renderRows() {
975
+ const rows = visibleArtifacts();
976
+ const tbody = $('rows');
977
+ $('ev-shown').textContent = state.artifacts.length === 0 ? '' :
978
+ COPY.shown.replace('{shown}', String(rows.length)).replace('{total}', String(state.artifacts.length));
979
+ if (rows.length === 0) {
980
+ tbody.innerHTML = '<tr><td colspan="6"><div class="empty">' +
981
+ esc(state.artifacts.length === 0 ? COPY.empty : COPY.shown.replace('{shown}', '0').replace('{total}', String(state.artifacts.length))) +
982
+ '</div></td></tr>';
983
+ return;
984
+ }
985
+ tbody.innerHTML = rows.map((item) => {
986
+ const tone = TONE[item.conclusion] || 'muted';
987
+ const label = item.conclusion == null ? COPY.noPayload : (COPY.conclusions[item.conclusion] || item.conclusion);
988
+ return '<tr tabindex="0" data-name="' + esc(item.name) + '" title="' + esc(NUM(item.bytes) + ' bytes') + '">' +
989
+ '<td class="mono name">' + esc(item.name) + '</td>' +
990
+ '<td>' + esc(item.kind) + '</td>' +
991
+ '<td>' + esc(item.subject || '') + '</td>' +
992
+ '<td><span class="tag ' + tone + '">' + esc(label) + '</span></td>' +
993
+ '<td class="mono" title="' + esc(item.generated_at || '') + '">' + esc(shortStamp(item.generated_at)) + '</td>' +
994
+ '<td class="mono">' + esc((item.sha256 || '').slice(0, 12)) + '</td></tr>';
995
+ }).join('');
996
+ for (const th of document.querySelectorAll('thead th[data-sort]')) {
997
+ const arrow = th.querySelector('.arrow');
998
+ if (arrow) arrow.textContent = th.getAttribute('data-sort') === state.sort.key ? (state.sort.dir === 'asc' ? '▲' : '▼') : '';
999
+ }
1000
+ }
1001
+
1002
+ async function loadEvidence(force) {
1003
+ if (state.evidenceLoaded && !force) return;
1004
+ const response = await fetch('/api/artifacts');
1005
+ const data = await response.json();
1006
+ state.artifacts = data.artifacts || [];
1007
+ state.evidenceLoaded = true;
1008
+ $('pill-mode').textContent = data.readOnly ? COPY.readOnly : COPY.actionsEnabled;
1009
+ $('ev-count').textContent = String(data.count == null ? state.artifacts.length : data.count);
1010
+ fillSelects();
1011
+ renderRows();
1012
+ }
1013
+
1014
+ async function openDrawer(name) {
1015
+ state.drawerName = name;
1016
+ $('drawer-title').textContent = name;
1017
+ $('drawer-body').textContent = COPY.picking;
1018
+ $('drawer-actions').innerHTML = '';
1019
+ $('drawer').hidden = false;
1020
+ $('drawer').setAttribute('aria-hidden', 'false');
1021
+ $('scrim').hidden = false;
1022
+ $('drawer').focus();
1023
+ let data = null;
402
1024
  try {
403
- response = await fetch('/api/audit');
1025
+ const response = await fetch('/api/artifact?name=' + encodeURIComponent(name));
1026
+ const body = await response.json();
1027
+ if (!response.ok) { $('drawer-body').textContent = COPY.artifactFailed + ': ' + (body.error || response.status); return; }
1028
+ data = body;
404
1029
  } catch (error) {
405
- body.textContent = body.dataset.failed + ': ' + error.message;
1030
+ $('drawer-body').textContent = COPY.artifactFailed + ': ' + error.message;
406
1031
  return;
407
1032
  }
408
- if (response.status === 501) { body.textContent = body.dataset.off; return; }
1033
+ const sha = data.sha256 || '';
1034
+ const payload = data.payload == null ? null : data.payload;
1035
+ const text = payload == null ? (data.error || COPY.noPayload) : JSON.stringify(payload, null, 2);
1036
+ $('drawer-actions').innerHTML =
1037
+ '<button class="btn tiny" data-copy="' + esc(name) + '">' + esc(COPY.copyName) + '</button>' +
1038
+ (sha ? '<button class="btn tiny" data-copy="' + esc(sha) + '">' + esc(COPY.copySha) + '</button>' : '') +
1039
+ (payload == null ? '' : '<button class="btn tiny" data-copy="' + esc(text) + '">' + esc(COPY.copyJson) + '</button>');
1040
+ $('drawer-body').textContent = text;
1041
+ }
1042
+
1043
+ function closeDrawer() {
1044
+ state.drawerName = null;
1045
+ $('drawer').hidden = true;
1046
+ $('drawer').setAttribute('aria-hidden', 'true');
1047
+ $('scrim').hidden = true;
1048
+ }
1049
+
1050
+ async function loadRaw() {
1051
+ const response = await fetch('/api/audit');
409
1052
  if (!response.ok) {
410
- const detail = await response.json().catch(() => ({}));
411
- body.textContent = body.dataset.failed + ': ' + (detail.error ?? response.status);
1053
+ let detail = {};
1054
+ try { detail = await response.json(); } catch (e) {}
1055
+ $('raw').textContent = COPY.failed + ': ' + (detail.error || response.status);
412
1056
  return;
413
1057
  }
414
1058
  const data = await response.json();
415
- const verdicts = data.row_verdicts ?? [];
416
- const counts = {};
417
- for (const verdict of verdicts) counts[verdict.conclusion] = (counts[verdict.conclusion] ?? 0) + 1;
418
- const parts = [
419
- 'dsh ' + ((data.env ?? {}).dsh ?? 'unknown'),
420
- 'profile ' + ((data.env ?? {}).profile ?? 'unknown'),
421
- verdicts.length + ' rows',
422
- ];
423
- for (const key of ['blocked', 'risky', 'unknown', 'go']) if (counts[key]) parts.push(key + ' ' + counts[key]);
424
- parts.push('collisions ' + ((data.collisions ?? []).length));
425
- body.textContent = parts.join(' · ');
426
- }
427
- load();
428
- loadAudit();
1059
+ $('raw').textContent = JSON.stringify(data, null, 2);
1060
+ state.rawLoaded = true;
1061
+ }
1062
+
1063
+ /* -------------------------------- tabs ----------------------------------- */
1064
+ function selectTab(name, updateHash) {
1065
+ for (const button of document.querySelectorAll('nav.tabs button')) {
1066
+ button.setAttribute('aria-selected', String(button.dataset.tab === name));
1067
+ }
1068
+ $('tab-evidence').hidden = name !== 'evidence';
1069
+ $('tab-raw').hidden = name !== 'raw';
1070
+ if (name === 'evidence' && !state.evidenceLoaded) loadEvidence(false);
1071
+ if (name === 'raw' && !state.rawLoaded) loadRaw();
1072
+ if (updateHash !== false && location.hash !== '#' + name) history.replaceState(null, '', '#' + name);
1073
+ }
1074
+
1075
+ /* ------------------------------- events ---------------------------------- */
1076
+ document.addEventListener('click', (event) => {
1077
+ const chip = event.target.closest('.count[data-filter]');
1078
+ if (chip !== null) {
1079
+ const filter = chip.getAttribute('data-filter');
1080
+ state.issueFilter = state.issueFilter === filter ? null : filter;
1081
+ if (state.summary) renderSummary();
1082
+ return;
1083
+ }
1084
+ const row = event.target.closest('tbody tr[data-name]');
1085
+ if (row !== null) openDrawer(row.getAttribute('data-name'));
1086
+ });
1087
+ document.addEventListener('keydown', (event) => {
1088
+ const typing = /^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement.tagName);
1089
+ if (event.key === 'Escape') {
1090
+ if (state.drawerName !== null) { closeDrawer(); return; }
1091
+ if (typing) document.activeElement.blur();
1092
+ return;
1093
+ }
1094
+ if (typing) {
1095
+ if (event.key === 'Enter' && document.activeElement.id === 'search') { renderRows(); }
1096
+ return;
1097
+ }
1098
+ if (event.key === '/') { event.preventDefault(); applyView('advanced'); selectTab('evidence'); $('search').focus(); return; }
1099
+ if (event.key === 'r' || event.key === 'R') { refresh(); return; }
1100
+ if (event.key === 'l' || event.key === 'L') { cycleTheme(); return; }
1101
+ if (event.key === '?') { toast(COPY.kbdHint); return; }
1102
+ if (event.key === '1') { applyView('advanced'); selectTab('evidence'); return; }
1103
+ if (event.key === '2') { applyView('advanced'); selectTab('raw'); return; }
1104
+ });
1105
+ document.addEventListener('keydown', (event) => {
1106
+ if (event.key !== 'Enter') return;
1107
+ const row = document.activeElement;
1108
+ if (row && row.matches && row.matches('tbody tr[data-name]')) openDrawer(row.getAttribute('data-name'));
1109
+ });
1110
+
1111
+ function applyView(view) {
1112
+ state.view = view;
1113
+ document.body.setAttribute('data-view', view);
1114
+ $('view-simple').setAttribute('aria-pressed', String(view === 'simple'));
1115
+ $('view-advanced').setAttribute('aria-pressed', String(view === 'advanced'));
1116
+ try { localStorage.setItem('triage-view', view); } catch (e) {}
1117
+ if (state.summary) renderSummary();
1118
+ if (view === 'advanced') {
1119
+ // The detailed view without a tab open is a tab bar with nothing under it; open the
1120
+ // ledger, but do not rewrite a deep link the user followed to get here.
1121
+ if ($('tab-evidence').hidden && $('tab-raw').hidden) selectTab('evidence', false);
1122
+ else if (!state.evidenceLoaded) loadEvidence(false);
1123
+ }
1124
+ }
1125
+ $('view-simple').onclick = () => applyView('simple');
1126
+ $('view-advanced').onclick = () => applyView('advanced');
1127
+
1128
+ $('theme').onclick = cycleTheme;
1129
+ $('refresh').onclick = () => refresh();
1130
+ $('drawer-close').onclick = closeDrawer;
1131
+ $('scrim').onclick = closeDrawer;
1132
+ $('issues-more').onclick = () => { state.issueFilter = null; state.showAll = true; renderIssues(); };
1133
+ $('copy-report').onclick = async () => toast((await copyText(reportText())) ? COPY.copied : COPY.copyFailed);
1134
+ $('search').oninput = () => { state.query = $('search').value; renderRows(); };
1135
+ $('kind').onchange = () => { state.kind = $('kind').value; renderRows(); };
1136
+ $('conclusion').onchange = () => { state.conclusion = $('conclusion').value; renderRows(); };
1137
+ for (const th of document.querySelectorAll('thead th[data-sort]')) {
1138
+ th.onclick = () => {
1139
+ const key = th.getAttribute('data-sort');
1140
+ state.sort = state.sort.key === key
1141
+ ? { key: key, dir: state.sort.dir === 'asc' ? 'desc' : 'asc' }
1142
+ : { key: key, dir: key === 'generated_at' ? 'desc' : 'asc' };
1143
+ renderRows();
1144
+ };
1145
+ }
1146
+ for (const button of document.querySelectorAll('nav.tabs button')) {
1147
+ button.onclick = () => selectTab(button.dataset.tab);
1148
+ }
1149
+
1150
+ function refresh() {
1151
+ loadSummary();
1152
+ if (state.evidenceLoaded) loadEvidence(true);
1153
+ if (state.rawLoaded) loadRaw();
1154
+ }
1155
+
1156
+ $('kbd-hint').textContent = COPY.kbdHint;
1157
+ // A link can carry the view, the theme and an artifact (see #theme= / #artifact= below), and
1158
+ // combinations with an ampersand, for screenshots and docs. A deep link overrides the saved
1159
+ // preferences without overwriting them, so "open it the way I had it" never sticks.
1160
+ try {
1161
+ const savedView = localStorage.getItem('triage-view');
1162
+ if (savedView === 'advanced' || savedView === 'simple') applyView(savedView);
1163
+ } catch (e) {}
1164
+ const deepLinks = location.hash.replace(/^#/, '').split('&').map((part) => '#' + part);
1165
+ for (const link of deepLinks) {
1166
+ if (link.indexOf('#theme=') === 0) { applyTheme(link.slice('#theme='.length)); continue; }
1167
+ if (link.indexOf('#artifact=') === 0) {
1168
+ applyView('advanced');
1169
+ selectTab('evidence');
1170
+ openDrawer(decodeURIComponent(link.slice('#artifact='.length)));
1171
+ continue;
1172
+ }
1173
+ if (link === '#advanced' || link === '#simple') { applyView(link.slice(1)); continue; }
1174
+ if (link === '#evidence' || link === '#raw') { selectTab(link.slice(1)); }
1175
+ }
1176
+ loadSummary();
429
1177
  </script>
430
1178
  </body></html>`;
431
1179
  }
1180
+ function panelCopy(locale) {
1181
+ if (locale === 'en') {
1182
+ return {
1183
+ title: 'Triage · evidence panel',
1184
+ brand: 'Triage',
1185
+ readOnly: 'read-only',
1186
+ actionsEnabled: 'actions enabled',
1187
+ refresh: 'Re-check',
1188
+ refreshTitle: 'Read the profile again (r)',
1189
+ themeTitle: 'Theme: auto → light → dark (l)',
1190
+ themes: { auto: 'auto', light: 'light', dark: 'dark' },
1191
+ loading: 'Reading the profile',
1192
+ loadingSub: '',
1193
+ issues: 'Issues',
1194
+ next: 'Commands',
1195
+ showAll: 'Show all',
1196
+ copyReport: 'Copy all',
1197
+ evidence: 'Artifacts',
1198
+ raw: 'Raw JSON',
1199
+ name: 'Artifact',
1200
+ kind: 'Kind',
1201
+ subject: 'Subject',
1202
+ conclusion: 'Conclusion',
1203
+ at: 'Generated',
1204
+ hash: 'sha256',
1205
+ empty: 'No artifacts here. Point --results at another directory, or run a record_* script first.',
1206
+ noIssues: 'Nothing in this composition needs a decision.',
1207
+ noFiltered: 'No issue of this kind.',
1208
+ noNext: 'No command to run.',
1209
+ more: '{n} more not shown (the summary is capped; dsh-triage audit --json has all of them)',
1210
+ copy: 'Copy',
1211
+ copied: 'Copied',
1212
+ copyFailed: 'Press Ctrl+C',
1213
+ off: 'Started with --no-audit: this panel does not read the profile. Drop the flag to see the verdict.',
1214
+ offIssues: 'not read (--no-audit)',
1215
+ failed: 'the profile could not be read',
1216
+ unknownValue: 'unknown',
1217
+ unjudged: 'the other {n} rows declare no DSH range at all',
1218
+ searchPlaceholder: 'Search name / kind / subject',
1219
+ allKinds: 'All kinds',
1220
+ allConclusions: 'Any conclusion',
1221
+ shown: '{shown} of {total}',
1222
+ picking: 'loading…',
1223
+ noPayload: 'no conclusion',
1224
+ close: 'Close',
1225
+ copyName: 'Copy name',
1226
+ copySha: 'Copy sha256',
1227
+ copyJson: 'Copy JSON',
1228
+ artifactFailed: 'could not read this artifact',
1229
+ reportTitle: 'Verdict',
1230
+ kbdHint: '/ search · r re-check · l theme · Esc close',
1231
+ viewLabel: 'Detail level',
1232
+ viewSimple: 'Simple',
1233
+ viewAdvanced: 'Detailed',
1234
+ actionFix: 'Copy the fix command',
1235
+ actionFixHint: 'paste it into a terminal',
1236
+ actionCopy: 'Copy the result',
1237
+ actionCopyHint: 'for an issue or a chat',
1238
+ figureBroken: 'to fix',
1239
+ figurePending: 'to check',
1240
+ figureOk: 'issues',
1241
+ checked: 'checked in {ms} ms',
1242
+ unjudgedSimple: '{n} more plugins never say which versions they support, so they cannot be judged',
1243
+ conclusions: { go: 'go', passed: 'passed', rendered: 'rendered', blocked: 'blocked', failed: 'failed', blank: 'blank', risky: 'risky', unknown: 'cannot tell', '∅': 'no conclusion' },
1244
+ chips: { rows: 'rows', judged: 'judged', go: 'go', denied: 'denied', unknown: 'cannot tell', collisions: 'collisions' },
1245
+ kindLabels: { denied: 'denied', collision: 'collision', duplicate: 'duplicate', unknown: 'unknown', unreadable: 'unreadable' },
1246
+ };
1247
+ }
1248
+ return {
1249
+ title: '分诊台 · 证据面板',
1250
+ brand: '分诊台',
1251
+ readOnly: '只读',
1252
+ actionsEnabled: '可执行',
1253
+ refresh: '重新检查',
1254
+ refreshTitle: '重新读取当前 profile(r)',
1255
+ themeTitle: '主题:自动 → 浅色 → 深色(l)',
1256
+ themes: { auto: '自动', light: '浅色', dark: '深色' },
1257
+ loading: '正在读取 profile',
1258
+ loadingSub: '',
1259
+ issues: '问题',
1260
+ next: '命令',
1261
+ showAll: '显示全部',
1262
+ copyReport: '复制全文',
1263
+ evidence: '产物',
1264
+ raw: '原始 JSON',
1265
+ name: '产物',
1266
+ kind: '类型',
1267
+ subject: '对象',
1268
+ conclusion: '结论',
1269
+ at: '时间',
1270
+ hash: 'sha256',
1271
+ empty: '这里没有产物。用 --results <目录> 指向别处,或先跑一次 record_* 脚本。',
1272
+ noIssues: '这套组合里没有要处理的行。',
1273
+ noFiltered: '这一类里没有要处理的行。',
1274
+ noNext: '没有要跑的命令。',
1275
+ more: '另有 {n} 条没显示(摘要只列前几条,全量见 dsh-triage audit --json)',
1276
+ copy: '复制',
1277
+ copied: '已复制',
1278
+ copyFailed: '复制失败,请手动选中',
1279
+ off: '面板以 --no-audit 启动,不读取当前 profile。去掉该参数就能看到结论。',
1280
+ offIssues: '未读取(--no-audit)',
1281
+ failed: '读不到当前 profile',
1282
+ unknownValue: '未知',
1283
+ unjudged: '其余 {n} 行不声明任何 DSH 区间',
1284
+ searchPlaceholder: '搜索产物名 / 类型 / 对象',
1285
+ allKinds: '全部类型',
1286
+ allConclusions: '全部结论',
1287
+ shown: '显示 {shown} / {total}',
1288
+ picking: '读取中…',
1289
+ noPayload: '无结论',
1290
+ close: '关闭',
1291
+ copyName: '复制名称',
1292
+ copySha: '复制 sha256',
1293
+ copyJson: '复制 JSON',
1294
+ artifactFailed: '读不到这份产物',
1295
+ reportTitle: '结论',
1296
+ kbdHint: '/ 搜索 · r 重新检查 · l 主题 · Esc 关闭',
1297
+ viewLabel: '详细程度',
1298
+ viewSimple: '简单',
1299
+ viewAdvanced: '详细',
1300
+ actionFix: '复制修复命令',
1301
+ actionFixHint: '粘贴到终端执行',
1302
+ actionCopy: '复制这份结果',
1303
+ actionCopyHint: '贴到 issue 或聊天里',
1304
+ figureBroken: '处会坏',
1305
+ figurePending: '处待确认',
1306
+ figureOk: '处问题',
1307
+ checked: '检查用时 {ms} 毫秒',
1308
+ unjudgedSimple: '另外 {n} 个插件没声明支持的版本,判不了',
1309
+ conclusions: { go: '正常', passed: '通过', rendered: '渲染正常', blocked: '被拒', failed: '失败', blank: '白屏', risky: '有风险', unknown: '判不了', '∅': '无结论' },
1310
+ chips: { rows: '行', judged: '有判定', go: '正常', denied: '被拒', unknown: '判不了', collisions: '冲突' },
1311
+ kindLabels: { denied: '被拒', collision: '冲突', duplicate: '重复', unknown: '判不了', unreadable: '读不到' },
1312
+ };
1313
+ }
432
1314
  //# sourceMappingURL=serve.js.map