loopengine 0.4.4 → 0.4.6

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.
@@ -1,8 +1,11 @@
1
- // The console's Inbox: /inbox lists every workflow run as a case, the ones
2
- // waiting on a person first (?open=1 shows only those); /inbox?case=<id> opens one, with what it was
3
- // given, what the agent did, what it asks now (answer, approve, approve
4
- // as changed, deny) and who decided what (web/inbox-admin.ts behind
5
- // /inbox/*). An approver or viewer sees only this page; a viewer can't
1
+ // The console's Inbox, for acting: /inbox shows what needs a person
2
+ // (Needs you, however long it has waited, the longest first) and every
3
+ // case from the last 7 days (Recent: done automatically, decided by
4
+ // someone, or failed); older cases are searched in Audit. A case is its
5
+ // own page, /cases/<id> (?back= is where its back link goes): what it
6
+ // was given, what the agent did, what it asks now (answer, approve,
7
+ // approve as changed, deny), who decided what, and Save as eval case
8
+ // (web/inbox-admin.ts behind /inbox/*). An approver or viewer sees only this page; a viewer can't
6
9
  // decide. Like the other console pages, its inline script avoids
7
10
  // backslashes and template placeholders, since it lives inside a template
8
11
  // literal.
@@ -72,6 +75,12 @@ export const inboxPageHtml = `<!doctype html>
72
75
  }
73
76
  .ib-step details summary { cursor: pointer; font-size: 12.5px; color: var(--ink-muted); }
74
77
  .ib-who { font-size: 13px; display: grid; gap: 4px; }
78
+ .ib-late { color: var(--warn); font-weight: 700; }
79
+ .ib-older { margin: 0; font-size: 12.5px; }
80
+ .ib-suggest { display: grid; gap: 8px; border-top: 1px solid var(--line); padding-top: 10px; }
81
+ .ib-suggest[hidden] { display: none; }
82
+ .ib-suggest h4 { margin: 0; font-size: 13px; }
83
+ .ib-suggest-row { display: flex; gap: 10px; align-items: flex-start; justify-content: space-between; font-size: 13px; }
75
84
  .ib-reason { color: var(--ink-muted); margin: 2px 0 0 12px; }
76
85
  .ib-change { display: grid; gap: 2px; margin: 2px 0 0 12px; font-size: 12.5px; }
77
86
  .ib-change del { color: var(--bad); }
@@ -119,7 +128,15 @@ ${renderMarkdownScript}
119
128
  var ELLIPSIS = String.fromCharCode(8230);
120
129
  var DOT = ' ' + String.fromCharCode(183) + ' ';
121
130
  var params = new URLSearchParams(location.search);
122
- var state = { open: params.get('open') === '1', q: params.get('q') || '', workflow: params.get('workflow') || '' };
131
+ // Needs you (waiting on a person, however long) or Recent (the last 7
132
+ // days); none asked: needs you when anything waits.
133
+ var state = { view: params.get('open') === '1' ? 'needs' : params.get('view') || '', q: params.get('q') || '', workflow: params.get('workflow') || '' };
134
+ // A case's own page is /cases/<id>; ?back= is where its back link goes.
135
+ var caseMatch = location.pathname.match(/^[/]cases[/]([^/]+)$/);
136
+ var caseId = caseMatch ? decodeURIComponent(caseMatch[1]) : '';
137
+ var back = params.get('back');
138
+ if (!back || back.charAt(0) !== '/' || back.charAt(1) === '/') back = '/inbox';
139
+ var fullAccess = !document.querySelector('.le-app.le-inbox-only');
123
140
  var role = 'owner';
124
141
  var workflows = {};
125
142
 
@@ -139,6 +156,27 @@ ${renderMarkdownScript}
139
156
  function when(iso) { return iso ? new Date(iso).toLocaleString() : ''; }
140
157
  function canDecide() { return role !== 'viewer'; }
141
158
 
159
+ // How long a case has waited: "Waiting 3 h", "Waiting 12 days".
160
+ function waitedFor(ms) {
161
+ var h = Math.floor(ms / 3600000);
162
+ if (h < 1) return 'Waiting ' + Math.max(1, Math.floor(ms / 60000)) + ' min';
163
+ if (h < 48) return 'Waiting ' + h + ' h';
164
+ return 'Waiting ' + Math.floor(h / 24) + ' days';
165
+ }
166
+ // What happened in a recent case.
167
+ function outcomeHtml(item) {
168
+ var o = item.outcome || '';
169
+ var cls = o === 'Failed' ? 'bad' : o === 'Running' ? 'run' : /^Denied/.test(o) ? 'bad' : /^Changed/.test(o) ? 'warn' : 'good';
170
+ return '<span class="ib-state ' + cls + '">' + esc(o) + '</span>';
171
+ }
172
+ // A case's page, coming back here.
173
+ function caseHref(id) {
174
+ return '/cases/' + encodeURIComponent(id) + '?back=' + encodeURIComponent(pageUrl());
175
+ }
176
+ function backLabel() {
177
+ return back.indexOf('/audit') === 0 ? 'Audit' : back.indexOf('/agents') === 0 ? 'Workflow' : 'Inbox';
178
+ }
179
+
142
180
  function stateHtml(item) {
143
181
  if (item.waiting && item.waiting.length) return '<span class="ib-state warn">' + (item.waiting.indexOf('approval') !== -1 ? 'Needs approval' : 'Question') + '</span>';
144
182
  if (item.status === 'running') return '<span class="ib-state run">Running</span>';
@@ -149,14 +187,14 @@ ${renderMarkdownScript}
149
187
 
150
188
  function listUrl() {
151
189
  var q = new URLSearchParams();
152
- if (state.open) q.set('open', '1');
190
+ q.set('view', state.view || 'auto');
153
191
  if (state.q) q.set('q', state.q);
154
192
  if (state.workflow) q.set('workflow', state.workflow);
155
193
  return '/inbox/items?' + q.toString();
156
194
  }
157
195
  function pageUrl() {
158
196
  var q = new URLSearchParams();
159
- if (state.open) q.set('open', '1');
197
+ if (state.view) q.set('view', state.view);
160
198
  if (state.q) q.set('q', state.q);
161
199
  if (state.workflow) q.set('workflow', state.workflow);
162
200
  var s = q.toString();
@@ -167,23 +205,30 @@ ${renderMarkdownScript}
167
205
  var items = data.items || [];
168
206
  (data.workflows || []).forEach(function (w) { workflows[w.id] = w.title; });
169
207
  var options = Object.keys(workflows).sort(function (a, b) { return workflows[a].localeCompare(workflows[b]); }).map(function (id) { return '<option value="' + esc(id) + '"' + (id === state.workflow ? ' selected' : '') + '>' + esc(workflows[id]) + '</option>'; }).join('');
208
+ state.view = data.view || state.view || 'recent';
209
+ var needs = state.view === 'needs';
170
210
  var rows = items.map(function (i) {
171
- return '<a class="ib-row" href="/inbox?case=' + encodeURIComponent(i.id) + '">' +
211
+ var waited = i.waitingSince ? Date.now() - new Date(i.waitingSince).getTime() : 0;
212
+ var side = needs
213
+ ? stateHtml(i) + '<span class="' + (waited > 3 * 86400000 ? 'ib-late' : '') + '">' + esc(waitedFor(waited)) + '</span>'
214
+ : outcomeHtml(i) + '<span>' + esc(ago(i.lastActivity)) + '</span>';
215
+ return '<a class="ib-row" href="' + caseHref(i.id) + '">' +
172
216
  '<span class="le-dot' + (i.waiting.length ? ' warn' : i.status === 'running' ? '' : ' idle') + '" aria-hidden="true"></span>' +
173
217
  '<span style="min-width:0"><div class="ib-row-title">' + esc(i.title) + '</div>' +
174
- '<div class="ib-row-meta">' + esc(i.workflowTitle) + DOT + esc(i.agent) + (i.lastBy ? DOT + 'last decided by ' + esc(i.lastBy) : '') + '</div></span>' +
175
- '<span class="ib-row-side">' + stateHtml(i) + '<span>' + esc(ago(i.startedAt)) + '</span></span></a>';
218
+ '<div class="ib-row-meta">' + esc(i.workflowTitle) + DOT + esc(i.agent) + DOT + 'started ' + esc(ago(i.startedAt)) + '</div></span>' +
219
+ '<span class="ib-row-side">' + side + '</span></a>';
176
220
  }).join('');
177
221
  page.innerHTML =
178
222
  '<div class="ib-bar">' +
179
- '<span class="ib-filter" role="group" aria-label="Show"><button type="button" data-open="0" aria-pressed="' + !state.open + '">All</button><button type="button" data-open="1" aria-pressed="' + state.open + '">Needs you (' + (data.open || 0) + ')</button></span>' +
223
+ '<span class="ib-filter" role="group" aria-label="Show"><button type="button" data-view="needs" aria-pressed="' + needs + '">Needs you (' + (data.open || 0) + ')</button><button type="button" data-view="recent" aria-pressed="' + !needs + '">Recent</button></span>' +
180
224
  '<select id="ibWorkflow" aria-label="Workflow"><option value="">All workflows</option>' + options + '</select>' +
181
225
  '<input id="ibSearch" type="search" placeholder="Search cases, inputs or people" value="' + esc(state.q) + '" aria-label="Search">' +
182
226
  '</div>' +
183
227
  (items.length ? '<div class="ib-list">' + rows + '</div>'
184
- : '<div class="ib-list"><p class="ib-empty">' + (state.open ? 'Nothing needs you right now. Questions and approvals from your agents land here.' : 'No cases yet. Each workflow run shows here.') + '</p></div>');
185
- var buttons = page.querySelectorAll('[data-open]');
186
- for (var b = 0; b < buttons.length; b++) buttons[b].addEventListener('click', function (ev) { state.open = ev.currentTarget.getAttribute('data-open') === '1'; refreshList(); });
228
+ : '<div class="ib-list"><p class="ib-empty">' + (needs ? 'Nothing needs you right now. Questions and approvals from your agents land here, however long ago they were asked.' : 'Nothing in the last 7 days. Every run shows here for a week: done automatically, decided by someone, or failed.') + '</p></div>') +
229
+ (needs ? '' : '<p class="hint ib-older">Showing the last 7 days.' + (fullAccess ? ' Older cases: <a class="ib-link" href="/audit?tab=cases">search all cases in Audit</a>.' : '') + '</p>');
230
+ var buttons = page.querySelectorAll('[data-view]');
231
+ for (var b = 0; b < buttons.length; b++) buttons[b].addEventListener('click', function (ev) { state.view = ev.currentTarget.getAttribute('data-view'); refreshList(); });
187
232
  page.querySelector('#ibWorkflow').addEventListener('change', function (ev) { state.workflow = ev.currentTarget.value; refreshList(); });
188
233
  var search = page.querySelector('#ibSearch');
189
234
  var timer = null;
@@ -324,7 +369,7 @@ ${renderMarkdownScript}
324
369
  var run = c.run;
325
370
  var status = run ? stateHtml({ waiting: c.pending.map(function (p) { return p.kind; }), status: run.status }) : stateHtml({ waiting: c.pending.map(function (p) { return p.kind; }), status: 'awaiting_approval' });
326
371
  page.innerHTML =
327
- '<a class="ib-back" href="' + pageUrl() + '">' + String.fromCharCode(8592) + ' Inbox</a>' +
372
+ '<a class="ib-back" href="' + esc(back) + '">' + String.fromCharCode(8592) + ' ' + backLabel() + '</a>' +
328
373
  '<div class="ib-case-head"><h2>' + esc(c.title) + '</h2><div class="ib-chips">' + status + '<span>' + caseLinks(c) + (run ? DOT + 'started ' + esc(when(run.started_at)) + (run.source ? ' by ' + esc(run.source === 'webhook' ? 'a webhook' : run.source === 'schedule' ? 'a schedule' : run.source === 'console' ? 'Run now' : run.source === 'api' ? 'an app' : run.source) : '') : '') + '</span></div></div>' +
329
374
  c.pending.map(pendingHtml).join('') +
330
375
  (run && run.params ? '<div class="ib-card"><h3>Inputs</h3>' + kvHtml(run.params) + '</div>' : '') +
@@ -332,12 +377,78 @@ ${renderMarkdownScript}
332
377
  (run ? decidedHtml(run) : '') +
333
378
  (run && run.result ? '<div class="ib-card"><h3>Result</h3><div class="ib-md">' + renderMarkdownPreview(run.result) + '</div></div>' : '') +
334
379
  (run && run.error ? '<div class="ib-card"><h3>Failed</h3><p class="error">' + esc(run.error) + '</p></div>' : '') +
335
- exportHtml(c);
380
+ exportHtml(c) +
381
+ evalCaseHtml(c);
336
382
  var print = page.querySelector('[data-act="print"]');
337
383
  if (print) print.addEventListener('click', function () { window.print(); });
384
+ wireEvalCase(c);
338
385
  wireCase(c);
339
386
  }
340
387
 
388
+ // Save this run as one of its workflow's eval cases (owners, admins and
389
+ // editors): a test it must keep passing. Then the checklist items it
390
+ // suggests, from what people corrected in it, to add or not.
391
+ function evalCaseHtml(c) {
392
+ var run = c.run;
393
+ if (!fullAccess || !run || !run.workflow_id || run.status !== 'done') return '';
394
+ return '<div class="ib-card ib-eval"><h3>Eval case</h3>' +
395
+ '<p class="hint" style="margin:0">Save this run as a test its workflow must keep passing after every change to its brief. Runs where a person denied or changed something, or that went wrong, make the best tests.</p>' +
396
+ '<div class="ib-actions"><button type="button" class="ib-btn plain" data-act="save-case">Save as eval case</button><span class="hint ib-eval-result" role="status"></span></div>' +
397
+ '<div class="ib-suggest" hidden></div></div>';
398
+ }
399
+ function evalBase(c) {
400
+ return '/agents/' + encodeURIComponent(c.agent) + '/workflows/' + encodeURIComponent(c.workflowId) + '/evals';
401
+ }
402
+ function wireEvalCase(c) {
403
+ var btn = page.querySelector('[data-act="save-case"]');
404
+ if (!btn) return;
405
+ var result = page.querySelector('.ib-eval-result');
406
+ var suggest = page.querySelector('.ib-suggest');
407
+ // Already a case: say so.
408
+ fetch(evalBase(c), { headers: { accept: 'application/json' } })
409
+ .then(function (r) { return r.ok ? r.json() : null; })
410
+ .then(function (ev) {
411
+ if (ev && (ev.cases || []).some(function (k) { return k.fromRun === c.id; })) { btn.disabled = true; btn.textContent = 'Saved as an eval case'; }
412
+ }).catch(function () {});
413
+ btn.addEventListener('click', function () {
414
+ btn.disabled = true;
415
+ result.textContent = 'Saving' + ELLIPSIS;
416
+ fetch(evalBase(c) + '/cases', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runId: c.id }) })
417
+ .then(function (r) { return r.json().then(function (b) { if (!r.ok) throw new Error(b.error || 'Could not save'); return b; }); })
418
+ .then(function (b) {
419
+ btn.textContent = 'Saved as an eval case';
420
+ result.innerHTML = 'Saved. <a class="ib-link" href="/agents/config?agent=' + encodeURIComponent(c.agent) + '&tab=workflows&workflow=' + encodeURIComponent(c.workflowId) + '&wtab=evidence">See its eval cases</a>';
421
+ showSuggestions(c, b.suggestions || [], b.criteria || []);
422
+ })
423
+ .catch(function (err) { btn.disabled = false; result.textContent = err.message; });
424
+ });
425
+ }
426
+ function showSuggestions(c, suggestions, criteria) {
427
+ var box = page.querySelector('.ib-suggest');
428
+ var have = criteria.map(function (k) { return k.text; });
429
+ var fresh = suggestions.filter(function (s) { return have.indexOf(s.text) === -1; });
430
+ if (!fresh.length) return;
431
+ box.hidden = false;
432
+ box.innerHTML = '<h4>Add to its checklist?</h4><p class="hint" style="margin:0">From what people corrected in this run. Each becomes a check every eval case is judged on.</p>' +
433
+ fresh.map(function (s, i) { return '<div class="ib-suggest-row"><span>' + esc(s.text) + '</span><button type="button" class="ib-btn plain" data-suggest="' + i + '">Add</button></div>'; }).join('');
434
+ box.addEventListener('click', function (ev) {
435
+ var b = ev.target.closest('[data-suggest]');
436
+ if (!b) return;
437
+ b.disabled = true;
438
+ var s = fresh[Number(b.getAttribute('data-suggest'))];
439
+ fetch(evalBase(c), { headers: { accept: 'application/json' } })
440
+ .then(function (r) { return r.json(); })
441
+ .then(function (ev2) {
442
+ var list = (ev2.criteria || []).map(function (k) { return { text: k.text, kind: k.kind, value: k.value }; });
443
+ list.push({ text: s.text, kind: s.kind });
444
+ return fetch(evalBase(c) + '/criteria', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ criteria: list }) });
445
+ })
446
+ .then(function (r) { return r.json().then(function (body) { if (!r.ok) throw new Error(body.error || 'Could not add it'); }); })
447
+ .then(function () { b.textContent = 'Added'; })
448
+ .catch(function (err) { b.disabled = false; b.textContent = err.message; });
449
+ });
450
+ }
451
+
341
452
  function send(card, path, body) {
342
453
  var result = card.querySelector('.ib-result');
343
454
  var buttons = card.querySelectorAll('button');
@@ -404,19 +515,25 @@ ${renderMarkdownScript}
404
515
  }
405
516
 
406
517
  function openCase() {
407
- var id = new URLSearchParams(location.search).get('case');
408
- return fetch('/inbox/cases/' + encodeURIComponent(id), { headers: { accept: 'application/json' } })
518
+ return fetch('/inbox/cases/' + encodeURIComponent(caseId), { headers: { accept: 'application/json' } })
409
519
  .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
410
- .then(renderCase)
411
- .catch(function (err) { page.innerHTML = '<a class="ib-back" href="/inbox">' + String.fromCharCode(8592) + ' Inbox</a><p class="error">Could not open this case: ' + esc(err.message) + '</p>'; });
520
+ .then(function (c) { document.title = c.title + ' ' + String.fromCharCode(183) + ' Case'; renderCase(c); })
521
+ .catch(function (err) { page.innerHTML = '<a class="ib-back" href="' + esc(back) + '">' + String.fromCharCode(8592) + ' ' + backLabel() + '</a><p class="error">Could not open this case: ' + esc(err.message) + '</p>'; });
412
522
  }
413
523
 
414
524
  function start() {
415
- if (new URLSearchParams(location.search).get('case')) openCase();
525
+ // A case's page is about that case, wherever it was opened from.
526
+ if (caseId) {
527
+ var head = document.querySelector('.le-head h1');
528
+ var lede = document.querySelector('.le-head p');
529
+ if (head) head.textContent = 'Case';
530
+ if (lede) lede.textContent = 'One run in full: what it was given, what the agent did step by step, who decided what, and what came of it.';
531
+ }
532
+ if (caseId) openCase();
416
533
  else refreshList();
417
534
  // The list keeps itself current while it's open.
418
535
  setInterval(function () {
419
- if (document.hidden || new URLSearchParams(location.search).get('case')) return;
536
+ if (document.hidden || caseId) return;
420
537
  if (document.activeElement && document.activeElement.id === 'ibSearch') return;
421
538
  refreshList();
422
539
  }, 15000);
@@ -0,0 +1,8 @@
1
+ import type { WorkflowAudit } from './workflow-audit.js';
2
+ export declare function workflowAuditReportHtml(audit: WorkflowAudit, options: {
3
+ generatedAt: string;
4
+ by: string;
5
+ jsonHref: string;
6
+ caseHref: (runId: string) => string;
7
+ pageHref: string;
8
+ }): string;
@@ -0,0 +1,129 @@
1
+ // A workflow's audit report (web/workflow-audit.ts) as a page to read,
2
+ // print, or save as a PDF from the browser's print dialog: the summary,
3
+ // the numbers, who decided what, every denial and change with its reason,
4
+ // how the brief changed (line by line), other settings changed, every
5
+ // case, and whether the log checks out. Rendered here, with no script, so
6
+ // the printed copy is exactly what's shown.
7
+ import { devUiCss } from './dev-ui-styles.js';
8
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
9
+ const when = (iso) => new Date(iso).toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }) + ' UTC';
10
+ const day = (iso) => new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' });
11
+ const pct = (part, whole) => (whole ? `${Math.round((100 * part) / whole)}%` : '—');
12
+ const plural = (n, word) => `${n} ${n === 1 ? word : `${word}s`}`;
13
+ const dollars = (usd) => `$${usd >= 0.1 ? usd.toFixed(2) : usd >= 0.001 ? usd.toFixed(3) : usd > 0 ? '0.001' : '0'}`;
14
+ function countsRow(label, c) {
15
+ return `<tr><td>${label}</td><td>${c.runs}</td><td>${c.done}</td><td>${c.failed} <span class="hint">(${pct(c.failed, c.runs)})</span></td><td>${c.decided}</td><td>${c.approved - c.changed}</td><td>${c.changed}</td><td>${c.denied}</td><td>${c.answered}</td></tr>`;
16
+ }
17
+ const STATUS = { done: 'Done', error: 'Failed', awaiting_approval: 'Waiting', running: 'Running' };
18
+ export function workflowAuditReportHtml(audit, options) {
19
+ const w = audit.workflow;
20
+ const v = audit.verification;
21
+ const c = audit.counts;
22
+ const versions = audit.versions.map((ver) => `
23
+ <div class="ar-version">
24
+ <h3>Version ${ver.number} <span class="hint">${ver.changedInPeriod ? `saved ${esc(when(ver.at))}` : `in use when the period began (saved ${esc(day(ver.at))})`}${ver.by ? ` by ${esc(ver.by)}` : ''}${ver.reason ? ` · ${esc(ver.reason)}` : ''}</span></h3>
25
+ <p class="hint">${ver.counts.runs ? `${plural(ver.counts.runs, 'run')} on it · ${ver.counts.failed} failed · ${plural(ver.counts.decided, 'request')} decided, ${ver.counts.changed + ver.counts.denied} changed or denied` : 'No runs on it in this period.'}</p>
26
+ ${ver.diff ? `<div class="ar-diff">${ver.diff.removed.map((l) => `<div class="del">− ${esc(l)}</div>`).join('')}${ver.diff.added.map((l) => `<div class="ins">+ ${esc(l)}</div>`).join('')}${!ver.diff.added.length && !ver.diff.removed.length ? '<div class="hint">No line changed (spacing only).</div>' : ''}</div>` : ''}
27
+ </div>`).join('');
28
+ const overruled = audit.overruled.map((d) => `<tr>
29
+ <td>${esc(when(d.at))}</td><td>${d.approved ? 'Changed, then approved' : 'Denied'}</td><td><code>${esc(d.tool)}</code></td><td>${esc(d.by ?? '')}</td>
30
+ <td>${d.reason ? `“${esc(d.reason)}”` : ''}${(d.changes ?? []).map((ch) => `<div><code>${esc(ch.field)}</code>: <del>${esc(ch.from)}</del> → <ins>${esc(ch.to)}</ins></div>`).join('')}</td>
31
+ <td><a href="${esc(options.caseHref(d.runId))}">case</a></td></tr>`).join('');
32
+ const people = audit.people.map((p) => `<tr><td>${esc(p.by)}</td><td>${p.approved}</td><td>${p.changed}</td><td>${p.denied}</td><td>${p.answered}</td></tr>`).join('');
33
+ const cases = audit.cases.slice(0, 500).map((k) => `<tr><td>${esc(when(k.at))}</td><td>${STATUS[k.status] ?? esc(k.status)}</td><td>${esc(k.inputs)}</td><td>${k.briefVersion ? `v${k.briefVersion}` : ''}</td><td>${esc(k.decidedBy.join(', '))}</td><td class="ar-outcome">${esc(k.outcome)}</td><td><a href="${esc(options.caseHref(k.runId))}">open</a></td></tr>`).join('');
34
+ const changes = audit.changes.map((ch) => `<li>${esc(when(ch.at))} · ${esc(ch.label)}${ch.by ? ` · ${esc(ch.by)}` : ''}</li>`).join('');
35
+ return `<!doctype html>
36
+ <html lang="en">
37
+ <head>
38
+ <meta charset="utf-8">
39
+ <meta name="viewport" content="width=device-width, initial-scale=1">
40
+ <title>Audit report: ${esc(w.title)}</title>
41
+ <style>${devUiCss}
42
+ body { background: var(--bg); }
43
+ .ar { max-width: 960px; margin: 0 auto; padding: 32px 24px 64px; display: grid; gap: 28px; font-size: 14px; }
44
+ .ar header { display: grid; gap: 6px; border-bottom: 1px solid var(--line); padding-bottom: 18px; }
45
+ .ar h1 { margin: 0; font-size: 24px; letter-spacing: -0.01em; }
46
+ .ar h2 { margin: 0 0 10px; font-size: 16px; }
47
+ .ar h3 { margin: 0 0 4px; font-size: 14px; }
48
+ .ar-meta { display: flex; flex-wrap: wrap; gap: 4px 18px; color: var(--ink-muted); font-size: 13px; }
49
+ .ar-tools { display: flex; gap: 8px; flex-wrap: wrap; }
50
+ .ar-tools a, .ar-tools button { font-size: 13px; font-weight: 600; text-decoration: none; padding: 6px 12px; border: 1px solid var(--line); border-radius: 8px; color: var(--accent-ink); background: var(--bg); }
51
+ .ar-check { padding: 10px 14px; border-radius: 10px; background: var(--good-soft); color: var(--good); font-weight: 600; }
52
+ .ar-check.bad { background: var(--bad-soft); color: var(--bad); }
53
+ .ar-summary { margin: 0; padding-left: 20px; display: grid; gap: 6px; line-height: 1.5; }
54
+ .ar table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
55
+ .ar th { text-align: left; font-weight: 600; color: var(--ink-muted); border-bottom: 1px solid var(--line); padding: 6px 8px; }
56
+ .ar td { border-bottom: 1px solid var(--line); padding: 6px 8px; vertical-align: top; }
57
+ .ar-outcome { max-width: 280px; }
58
+ .ar-version { border-left: 2px solid var(--line); padding: 2px 0 2px 12px; margin-bottom: 14px; }
59
+ .ar-diff { font-family: var(--font-mono); font-size: 12px; white-space: pre-wrap; display: grid; gap: 1px; margin-top: 6px; }
60
+ .ar-diff .del { background: var(--bad-soft); color: var(--bad); padding: 1px 6px; }
61
+ .ar-diff .ins { background: var(--good-soft); color: var(--good); padding: 1px 6px; }
62
+ .ar del { color: var(--bad); }
63
+ .ar ins { color: var(--good); text-decoration: none; }
64
+ .ar ul { margin: 0; padding-left: 20px; display: grid; gap: 4px; }
65
+ .hint { color: var(--ink-muted); font-weight: 400; }
66
+ @page { margin: 16mm 14mm; }
67
+ @media print {
68
+ .ar-check, .ar-diff .del, .ar-diff .ins { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
69
+ .ar-tools { display: none; }
70
+ .ar { padding: 0; max-width: none; }
71
+ .ar section { break-inside: avoid-page; }
72
+ .ar table { break-inside: auto; }
73
+ .ar tr { break-inside: avoid; }
74
+ .ar a { color: inherit; text-decoration: none; }
75
+ }
76
+ </style>
77
+ </head>
78
+ <body>
79
+ <div class="ar">
80
+ <header>
81
+ <div class="ar-tools"><a href="${esc(options.pageHref)}">← Audit</a><button type="button" onclick="window.print()">Print or save as PDF</button><a href="${esc(options.jsonHref)}" download>Download JSON</a></div>
82
+ <h1>Audit report: ${esc(w.title)}</h1>
83
+ <div class="ar-meta"><span>Workflow <code>${esc(w.id)}</code></span><span>Agent ${esc(w.agentLabel)}</span><span>${esc(day(audit.period.since))} to ${esc(day(audit.period.until))}</span></div>
84
+ <div class="ar-meta"><span>Made ${esc(when(options.generatedAt))} by ${esc(options.by)}</span></div>
85
+ </header>
86
+
87
+ <section>
88
+ <div class="ar-check${v.ok ? '' : ' bad'}">${v.ok
89
+ ? `Audit log verified: ${v.events.toLocaleString('en-US')} events check out.${v.last ? ` <span class="hint">Latest event #${v.last.id}, hash ${esc(v.last.hash)}</span>` : ''}`
90
+ : `Audit log broken at event #${v.broken?.id}: the record after it can't be relied on.`}</div>
91
+ </section>
92
+
93
+ <section>
94
+ <h2>Summary</h2>
95
+ <ul class="ar-summary">${audit.summary.map((s) => `<li>${esc(s)}</li>`).join('')}</ul>
96
+ </section>
97
+
98
+ <section>
99
+ <h2>Runs and decisions</h2>
100
+ <table><thead><tr><th></th><th>Runs</th><th>Done</th><th>Failed</th><th>Decided</th><th>Approved as asked</th><th>Changed</th><th>Denied</th><th>Questions answered</th></tr></thead>
101
+ <tbody>${countsRow('All', c)}${audit.versions.filter((ver) => ver.counts.runs).map((ver) => countsRow(`Brief v${ver.number}`, ver.counts)).join('')}</tbody></table>
102
+ ${audit.cost ? `<p class="hint">Model cost ${dollars(audit.cost.totalUsd)}, ${dollars(audit.cost.perRunUsd)} a run${audit.cost.pricedRuns < c.runs ? ` (${audit.cost.pricedRuns} of ${c.runs} runs priced)` : ''}.</p>` : ''}
103
+ </section>
104
+
105
+ ${people ? `<section><h2>Who decided</h2><table><thead><tr><th>Person</th><th>Approved as asked</th><th>Changed, then approved</th><th>Denied</th><th>Answered</th></tr></thead><tbody>${people}</tbody></table></section>` : ''}
106
+
107
+ <section>
108
+ <h2>Denied or changed</h2>
109
+ ${overruled ? `<table><thead><tr><th>When</th><th>Decision</th><th>Action</th><th>By</th><th>Reason or change</th><th></th></tr></thead><tbody>${overruled}</tbody></table>` : '<p class="hint">None: every request was approved as the agent asked.</p>'}
110
+ </section>
111
+
112
+ <section>
113
+ <h2>The brief</h2>
114
+ ${versions || '<p class="hint">No versions recorded.</p>'}
115
+ </section>
116
+
117
+ <section>
118
+ <h2>Settings changed</h2>
119
+ ${changes ? `<ul>${changes}</ul>` : '<p class="hint">None in this period.</p>'}
120
+ </section>
121
+
122
+ <section>
123
+ <h2>Cases (${audit.cases.length})</h2>
124
+ ${cases ? `<table><thead><tr><th>Started</th><th>Outcome</th><th>Inputs</th><th>Brief</th><th>Decided by</th><th>Result</th><th></th></tr></thead><tbody>${cases}</tbody></table>${audit.cases.length > 500 ? '<p class="hint">The 500 most recent are listed; the JSON has them all.</p>' : ''}` : '<p class="hint">None.</p>'}
125
+ </section>
126
+ </div>
127
+ </body>
128
+ </html>`;
129
+ }
@@ -0,0 +1,116 @@
1
+ import type { AuditEvent, ChainCheck, Version } from '../core/audit-store.js';
2
+ import type { WorkflowRun } from '../core/workflow-runs.js';
3
+ export interface AuditCounts {
4
+ runs: number;
5
+ done: number;
6
+ failed: number;
7
+ /** Still running or waiting for a decision. */
8
+ open: number;
9
+ decided: number;
10
+ approved: number;
11
+ /** Approved after a person changed what it would do. */
12
+ changed: number;
13
+ denied: number;
14
+ answered: number;
15
+ feedback: number;
16
+ bad: number;
17
+ unedited: number;
18
+ }
19
+ export interface AuditPerson {
20
+ by: string;
21
+ approved: number;
22
+ changed: number;
23
+ denied: number;
24
+ answered: number;
25
+ }
26
+ export interface AuditDecision {
27
+ at: string;
28
+ runId: string;
29
+ tool: string;
30
+ by?: string;
31
+ approved: boolean;
32
+ edited: boolean;
33
+ reason?: string;
34
+ /** For a change: each field, from what the agent asked to what ran. */
35
+ changes?: {
36
+ field: string;
37
+ from: string;
38
+ to: string;
39
+ }[];
40
+ }
41
+ export interface AuditVersion {
42
+ number: number;
43
+ at: string;
44
+ by?: string;
45
+ reason?: string;
46
+ /** Saved within the period (else it was in use when it began). */
47
+ changedInPeriod: boolean;
48
+ /** Its runs in the period. */
49
+ counts: AuditCounts;
50
+ /** Lines added and removed against the version before it. */
51
+ diff?: {
52
+ added: string[];
53
+ removed: string[];
54
+ };
55
+ }
56
+ export interface AuditCase {
57
+ runId: string;
58
+ at: string;
59
+ inputs: string;
60
+ status: WorkflowRun['status'];
61
+ briefVersion?: number;
62
+ decidedBy: string[];
63
+ outcome: string;
64
+ }
65
+ export interface WorkflowAudit {
66
+ workflow: {
67
+ agent: string;
68
+ agentLabel: string;
69
+ id: string;
70
+ title: string;
71
+ };
72
+ period: {
73
+ since: string;
74
+ until: string;
75
+ };
76
+ counts: AuditCounts;
77
+ people: AuditPerson[];
78
+ /** Denied, or changed before approving: the decisions worth reading. */
79
+ overruled: AuditDecision[];
80
+ versions: AuditVersion[];
81
+ changes: {
82
+ at: string;
83
+ by?: string;
84
+ label: string;
85
+ }[];
86
+ cost?: {
87
+ totalUsd: number;
88
+ perRunUsd: number;
89
+ pricedRuns: number;
90
+ };
91
+ cases: AuditCase[];
92
+ verification: ChainCheck;
93
+ /** The audit in sentences, most important first. */
94
+ summary: string[];
95
+ }
96
+ export interface WorkflowAuditInput {
97
+ workflow: WorkflowAudit['workflow'];
98
+ since: string;
99
+ until: string;
100
+ /** Its runs that started in the period. */
101
+ runs: WorkflowRun[];
102
+ /** Each run's cost in US dollars, where known. */
103
+ costs: Map<string, number>;
104
+ /** Every brief version, any order. */
105
+ versions: Version[];
106
+ /** Its settings changes (events of kind "change") in the period. */
107
+ changes: AuditEvent[];
108
+ verification: ChainCheck;
109
+ }
110
+ /** Lines in `after` and not `before`, and the reverse (a line diff by
111
+ * longest common subsequence, for briefs of a few hundred lines). */
112
+ export declare function lineDiff(before: string, after: string): {
113
+ added: string[];
114
+ removed: string[];
115
+ };
116
+ export declare function buildWorkflowAudit(input: WorkflowAuditInput): WorkflowAudit;