loopengine 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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.anchors ? `, and ${v.anchors} anchor${v.anchors === 1 ? '' : 's'} kept at ${esc(v.anchoredAt ?? 'loopengine.co')} match` : ''}.${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,120 @@
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
+ anchoredAt?: string;
94
+ };
95
+ /** The audit in sentences, most important first. */
96
+ summary: string[];
97
+ }
98
+ export interface WorkflowAuditInput {
99
+ workflow: WorkflowAudit['workflow'];
100
+ since: string;
101
+ until: string;
102
+ /** Its runs that started in the period. */
103
+ runs: WorkflowRun[];
104
+ /** Each run's cost in US dollars, where known. */
105
+ costs: Map<string, number>;
106
+ /** Every brief version, any order. */
107
+ versions: Version[];
108
+ /** Its settings changes (events of kind "change") in the period. */
109
+ changes: AuditEvent[];
110
+ verification: ChainCheck & {
111
+ anchoredAt?: string;
112
+ };
113
+ }
114
+ /** Lines in `after` and not `before`, and the reverse (a line diff by
115
+ * longest common subsequence, for briefs of a few hundred lines). */
116
+ export declare function lineDiff(before: string, after: string): {
117
+ added: string[];
118
+ removed: string[];
119
+ };
120
+ export declare function buildWorkflowAudit(input: WorkflowAuditInput): WorkflowAudit;
@@ -0,0 +1,208 @@
1
+ const short = (text, max) => {
2
+ const flat = text.replace(/\s+/g, ' ').trim();
3
+ return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
4
+ };
5
+ function counts(runs) {
6
+ const ds = runs.flatMap((r) => r.decisions ?? []);
7
+ const fs = runs.flatMap((r) => (r.feedback ? [r.feedback] : []));
8
+ return {
9
+ runs: runs.length,
10
+ done: runs.filter((r) => r.status === 'done').length,
11
+ failed: runs.filter((r) => r.status === 'error').length,
12
+ open: runs.filter((r) => r.status === 'running' || r.status === 'awaiting_approval').length,
13
+ decided: ds.length,
14
+ approved: ds.filter((d) => d.approved).length,
15
+ changed: ds.filter((d) => d.approved && d.edited).length,
16
+ denied: ds.filter((d) => !d.approved).length,
17
+ answered: runs.reduce((n, r) => n + (r.answers?.length ?? 0), 0),
18
+ feedback: fs.length,
19
+ bad: fs.filter((f) => f.verdict === 'bad').length,
20
+ unedited: fs.filter((f) => f.edit === 'none' && f.verdict !== 'bad').length,
21
+ };
22
+ }
23
+ const show = (v) => short(v === undefined ? '(none)' : typeof v === 'string' ? v : JSON.stringify(v), 200);
24
+ function fieldChanges(before, after) {
25
+ if (!before || !after || typeof before !== 'object' || typeof after !== 'object')
26
+ return undefined;
27
+ const b = before;
28
+ const a = after;
29
+ const fields = [...new Set([...Object.keys(b), ...Object.keys(a)])].filter((k) => JSON.stringify(b[k]) !== JSON.stringify(a[k]));
30
+ return fields.map((field) => ({ field, from: show(b[field]), to: show(a[field]) }));
31
+ }
32
+ /** Lines in `after` and not `before`, and the reverse (a line diff by
33
+ * longest common subsequence, for briefs of a few hundred lines). */
34
+ export function lineDiff(before, after) {
35
+ const a = before.split('\n');
36
+ const b = after.split('\n');
37
+ if (a.length * b.length > 4_000_000) {
38
+ const setA = new Set(a);
39
+ const setB = new Set(b);
40
+ return { added: b.filter((l) => !setA.has(l) && l.trim()), removed: a.filter((l) => !setB.has(l) && l.trim()) };
41
+ }
42
+ const table = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
43
+ for (let i = a.length - 1; i >= 0; i--) {
44
+ for (let j = b.length - 1; j >= 0; j--)
45
+ table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
46
+ }
47
+ const added = [];
48
+ const removed = [];
49
+ let i = 0;
50
+ let j = 0;
51
+ while (i < a.length && j < b.length) {
52
+ if (a[i] === b[j]) {
53
+ i++;
54
+ j++;
55
+ }
56
+ else if (table[i + 1][j] >= table[i][j + 1])
57
+ removed.push(a[i++]);
58
+ else
59
+ added.push(b[j++]);
60
+ }
61
+ removed.push(...a.slice(i));
62
+ added.push(...b.slice(j));
63
+ return { added: added.filter((l) => l.trim()), removed: removed.filter((l) => l.trim()) };
64
+ }
65
+ const pct = (part, whole) => `${Math.round((100 * part) / whole)}%`;
66
+ const plural = (n, word, many = `${word}s`) => `${n.toLocaleString('en-US')} ${n === 1 ? word : many}`;
67
+ // Dollars: to the cent, or to a tenth of a cent under ten cents.
68
+ const dollars = (usd) => `$${usd >= 0.1 ? usd.toFixed(2) : usd >= 0.001 ? usd.toFixed(3) : usd > 0 ? '0.001' : '0'}`;
69
+ // Someone's words in quotes, without their own final full stop.
70
+ const quote = (text, max) => `“${short(text, max).replace(/[.!]+$/, '')}”`;
71
+ const day = (iso) => new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
72
+ export function buildWorkflowAudit(input) {
73
+ const runs = [...input.runs].sort((a, b) => a.started_at.localeCompare(b.started_at));
74
+ const total = counts(runs);
75
+ // Who decided what.
76
+ const people = new Map();
77
+ const person = (by) => people.get(by) ?? people.set(by, { by, approved: 0, changed: 0, denied: 0, answered: 0 }).get(by);
78
+ for (const r of runs) {
79
+ for (const d of r.decisions ?? []) {
80
+ if (!d.by)
81
+ continue;
82
+ const p = person(d.by);
83
+ if (!d.approved)
84
+ p.denied++;
85
+ else if (d.edited)
86
+ p.changed++;
87
+ else
88
+ p.approved++;
89
+ }
90
+ for (const a of r.answers ?? [])
91
+ if (a.by)
92
+ person(a.by).answered++;
93
+ }
94
+ const overruled = runs.flatMap((r) => (r.decisions ?? [])
95
+ .filter((d) => !d.approved || d.edited)
96
+ .map((d) => {
97
+ const changes = d.edited ? fieldChanges(d.before, d.after) : undefined;
98
+ return { at: d.at, runId: r.run_id, tool: d.tool, ...(d.by ? { by: d.by } : {}), approved: d.approved, edited: Boolean(d.edited), ...(d.reason ? { reason: d.reason } : {}), ...(changes?.length ? { changes } : {}) };
99
+ }));
100
+ // The brief: the version in use when the period began, and each saved in it.
101
+ const all = [...input.versions].sort((a, b) => a.number - b.number);
102
+ const atStart = all.filter((v) => v.at < input.since).at(-1);
103
+ const shown = all.filter((v) => v === atStart || (v.at >= input.since && v.at <= input.until));
104
+ const versions = shown.map((v) => {
105
+ const previous = all.filter((x) => x.number < v.number).at(-1);
106
+ const changedInPeriod = v.at >= input.since;
107
+ return {
108
+ number: v.number,
109
+ at: v.at,
110
+ ...(v.by ? { by: v.by } : {}),
111
+ ...(v.reason ? { reason: v.reason } : {}),
112
+ changedInPeriod,
113
+ counts: counts(runs.filter((r) => r.versions?.brief === v.number)),
114
+ ...(changedInPeriod && previous ? { diff: lineDiff(previous.content, v.content) } : {}),
115
+ };
116
+ });
117
+ const priced = runs.filter((r) => input.costs.has(r.run_id));
118
+ const totalUsd = priced.reduce((n, r) => n + input.costs.get(r.run_id), 0);
119
+ const cost = priced.length ? { totalUsd, perRunUsd: totalUsd / priced.length, pricedRuns: priced.length } : undefined;
120
+ const cases = [...runs].reverse().map((r) => ({
121
+ runId: r.run_id,
122
+ at: r.started_at,
123
+ inputs: short(Object.entries(r.params ?? {}).map(([k, v]) => `${k}: ${v}`).join(' · '), 160),
124
+ status: r.status,
125
+ ...(r.versions?.brief ? { briefVersion: r.versions.brief } : {}),
126
+ decidedBy: [...new Set([...(r.decisions ?? []), ...(r.answers ?? [])].map((d) => d.by).filter((b) => Boolean(b)))],
127
+ outcome: short(r.status === 'error' ? r.error ?? '' : r.result ?? '', 200),
128
+ }));
129
+ const changes = input.changes.map((e) => ({ at: e.at, ...(e.by ? { by: e.by } : {}), label: typeof e.data.label === 'string' ? e.data.label : 'Changed a setting' }));
130
+ // ---- The summary, in sentences. ----
131
+ const summary = [];
132
+ const v = input.verification;
133
+ summary.push(v.ok
134
+ ? `The audit log checks out: ${plural(v.events, 'event')} verified${v.anchors ? `, matching ${plural(v.anchors, 'anchor')} kept at ${v.anchoredAt ?? 'loopengine.co'}` : ''}.`
135
+ : `The audit log does not check out: it's broken at event #${v.broken?.id}. Treat this report's record as unreliable from there on.`);
136
+ if (!total.runs)
137
+ summary.push('It didn’t run in this period.');
138
+ else {
139
+ summary.push(`${plural(total.runs, 'run')}: ${total.done} done, ${total.failed} failed${total.open ? `, ${total.open} still open` : ''}${total.runs && total.failed ? ` (${pct(total.failed, total.runs)} failed)` : ''}.`);
140
+ if (total.decided) {
141
+ const asAsked = total.approved - total.changed;
142
+ summary.push(`People decided ${plural(total.decided, 'request')}: ${asAsked} approved as asked, ${total.changed} changed before approving, ${total.denied} denied.`);
143
+ }
144
+ else
145
+ summary.push('Nothing needed a person’s approval.');
146
+ const reasons = [...new Set(overruled.filter((d) => !d.approved && d.reason).map((d) => quote(d.reason, 80)))].slice(0, 3);
147
+ if (reasons.length)
148
+ summary.push(`Reasons given for denials include ${reasons.join(', ')}.`);
149
+ if (total.answered)
150
+ summary.push(`It asked, and people answered, ${plural(total.answered, 'question')}.`);
151
+ if (total.feedback)
152
+ summary.push(`Feedback on ${plural(total.feedback, 'result')}: ${total.unedited} used unedited, ${total.bad} marked bad.`);
153
+ }
154
+ // The brief: each change in a sentence when there are one or two, else
155
+ // one sentence for them all; and what changed in how people judged its
156
+ // work, from the version before to the one after.
157
+ const saved = versions.filter((x) => x.changedInPeriod);
158
+ const effect = (from, to) => {
159
+ const rate = (c) => (c.decided >= 3 ? (c.changed + c.denied) / c.decided : undefined);
160
+ const before = from && rate(from.counts);
161
+ const after = rate(to.counts);
162
+ if (before !== undefined && after !== undefined)
163
+ return `; requests changed or denied went from ${Math.round(before * 100)}% to ${Math.round(after * 100)}%`;
164
+ if (from && from.counts.runs >= 3 && to.counts.runs >= 3)
165
+ return `; failures went from ${pct(from.counts.failed, from.counts.runs)} to ${pct(to.counts.failed, to.counts.runs)}`;
166
+ return '';
167
+ };
168
+ const ran = (x) => x.counts.runs > 0;
169
+ if (saved.length && saved.length <= 2) {
170
+ for (const ver of saved) {
171
+ const previous = versions.filter((x) => x.number < ver.number).at(-1);
172
+ const what = ver.diff ? ` (${plural(ver.diff.added.length, 'line')} added, ${ver.diff.removed.length} removed)` : '';
173
+ const first = !previous && ver.number === 1;
174
+ summary.push(first
175
+ ? `The brief was first recorded, as version 1, on ${day(ver.at)}.`
176
+ : `The brief changed to version ${ver.number} on ${day(ver.at)}${ver.by ? ` by ${ver.by}` : ''}${ver.reason ? `, ${quote(ver.reason, 60)}` : ''}${what}${effect(previous, ver)}.`);
177
+ }
178
+ }
179
+ else if (saved.length > 2) {
180
+ const latest = saved.at(-1);
181
+ const people = [...new Set(saved.map((x) => x.by).filter((b) => Boolean(b)))];
182
+ const start = versions.find((x) => !x.changedInPeriod);
183
+ const firstRan = versions.find(ran);
184
+ const lastRan = [...versions].reverse().find(ran);
185
+ const change = firstRan && lastRan && firstRan !== lastRan ? effect(firstRan, lastRan).replace(/^; /, ` From version ${firstRan.number} to ${lastRan.number}, `) : '';
186
+ summary.push(`The brief changed ${saved.length} times${start ? `, from version ${start.number}` : ''} to version ${latest.number}, last on ${day(latest.at)}${people.length ? `, by ${people.join(', ')}` : ''}.${change ? `${change}.` : ''}`);
187
+ }
188
+ else if (versions.length)
189
+ summary.push(`The brief stayed at version ${versions[0].number} all period.`);
190
+ const otherChanges = changes.filter((c) => !/^Edited the workflow$|^Restored brief version/.test(c.label));
191
+ if (otherChanges.length)
192
+ summary.push(`${plural(otherChanges.length, 'other setting change')}: ${[...new Set(otherChanges.map((c) => c.label.toLowerCase()))].slice(0, 4).join(', ')}.`);
193
+ if (cost)
194
+ summary.push(`It cost ${dollars(cost.totalUsd)} in model calls${cost.pricedRuns < total.runs ? ` (for the ${plural(cost.pricedRuns, 'run')} with a known price)` : ''}, ${dollars(cost.perRunUsd)} a run.`);
195
+ return {
196
+ workflow: input.workflow,
197
+ period: { since: input.since, until: input.until },
198
+ counts: total,
199
+ people: [...people.values()].sort((a, b) => b.approved + b.changed + b.denied + b.answered - (a.approved + a.changed + a.denied + a.answered)),
200
+ overruled,
201
+ versions,
202
+ changes,
203
+ ...(cost ? { cost } : {}),
204
+ cases,
205
+ verification: input.verification,
206
+ summary,
207
+ };
208
+ }
@@ -55,12 +55,21 @@ export interface EvalCheck {
55
55
  pass: boolean;
56
56
  reason?: string;
57
57
  }
58
+ export interface StandIn {
59
+ tool: string;
60
+ input: Record<string, unknown>;
61
+ replayed: boolean;
62
+ }
58
63
  export interface EvalCaseResult {
59
64
  caseId: string;
60
65
  result?: string;
61
66
  error?: string;
62
67
  /** The tools the test run called. */
63
68
  tools?: string[];
69
+ /** The calls a test run doesn't make (they'd change something, or
70
+ * need approval): each with whether it got its reply from the case's
71
+ * own run, or a note to assume it worked. */
72
+ standIns?: StandIn[];
64
73
  checks?: EvalCheck[];
65
74
  /** Rounds from before criteria: a 1-5 score. */
66
75
  score?: number;
@@ -164,11 +173,13 @@ export interface EvalRunDeps {
164
173
  model: string;
165
174
  judgeLabel: string;
166
175
  judge: ModelCall;
167
- /** One test run of the workflow with these inputs: its result, and
168
- * the tools it called. */
169
- runCase(params: Record<string, string>): Promise<{
176
+ /** One test run of the workflow for this case (its inputs, and the run
177
+ * it came from to replay): its result, the tools it called, and the
178
+ * calls it didn't make. */
179
+ runCase(c: EvalCase): Promise<{
170
180
  result: string;
171
181
  tools: string[];
182
+ standIns?: StandIn[];
172
183
  }>;
173
184
  }
174
185
  /** Runs every case once and scores it, recording progress as it goes.
@@ -306,7 +306,7 @@ export function startEvalRound(deps) {
306
306
  for (const c of cases) {
307
307
  let run;
308
308
  try {
309
- run = await deps.runCase(c.params);
309
+ run = await deps.runCase(c);
310
310
  }
311
311
  catch (err) {
312
312
  run = { error: err instanceof Error ? err.message : String(err) };
@@ -314,7 +314,7 @@ export function startEvalRound(deps) {
314
314
  const checks = await checkCase(deps.judge, { instructions: deps.instructions, criteria, reference: c.reference ?? '', run });
315
315
  results.push({
316
316
  caseId: c.id,
317
- ...('error' in run ? { error: run.error } : { result: run.result.slice(0, 20000), tools: [...new Set(run.tools)] }),
317
+ ...('error' in run ? { error: run.error } : { result: run.result.slice(0, 20000), tools: [...new Set(run.tools)], ...(run.standIns?.length ? { standIns: run.standIns.slice(0, 50) } : {}) }),
318
318
  checks,
319
319
  });
320
320
  const now = readEvals(deps.agentDir, deps.workflowId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.4.3",
3
+ "version": "0.4.5",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",
@@ -45,6 +45,8 @@
45
45
  "dist/core/secret-store.d.ts",
46
46
  "dist/core/trusted-proxy.js",
47
47
  "dist/core/trusted-proxy.d.ts",
48
+ "dist/core/audit-anchor.js",
49
+ "dist/core/audit-anchor.d.ts",
48
50
  "dist/core/audit-store.js",
49
51
  "dist/core/audit-store.d.ts",
50
52
  "dist/core/workspace-roles.js",