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.
@@ -17,9 +17,50 @@ export interface AuditEvent {
17
17
  kind: AuditEventKind;
18
18
  by?: string;
19
19
  data: Record<string, unknown>;
20
+ /** Its place in the hash chain: the event before's hash, and its own
21
+ * (eventHash). */
22
+ prev?: string;
23
+ hash?: string;
20
24
  }
21
25
  /** Opens (creating if need be) the database in `dir`. */
22
26
  export declare function openAuditDb(dir: string): DatabaseSync | undefined;
27
+ /** An event's hash: SHA-256 of the hash before it and its content. */
28
+ export declare function eventHash(prev: string, e: {
29
+ id: number;
30
+ at: string;
31
+ agent: string;
32
+ workflow_id?: string | null;
33
+ run_id?: string | null;
34
+ kind: string;
35
+ by?: string | null;
36
+ data: string;
37
+ }): string;
38
+ export interface ChainCheck {
39
+ ok: boolean;
40
+ /** Events checked. */
41
+ events: number;
42
+ /** The latest event, and its hash. */
43
+ last?: {
44
+ id: number;
45
+ at: string;
46
+ hash: string;
47
+ };
48
+ /** The first place the chain is broken, and how. */
49
+ broken?: {
50
+ id: number;
51
+ at?: string;
52
+ problem: 'changed' | 'missing-before';
53
+ };
54
+ }
55
+ /** Checks every event's hash, in order. */
56
+ export declare function verifyEventChain(database?: DatabaseSync | undefined): ChainCheck;
57
+ /** The latest event's id and hash: written down anywhere outside the
58
+ * workspace, it lets a later check show the log wasn't rewritten. */
59
+ export declare function latestEventHash(database?: DatabaseSync | undefined): {
60
+ id: number;
61
+ at: string;
62
+ hash: string;
63
+ } | undefined;
23
64
  export declare function schedulerDir(): string;
24
65
  /** The process-wide database; undefined where node:sqlite isn't there,
25
66
  * or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
@@ -34,7 +75,7 @@ export declare function setAuditDb(next: DatabaseSync | undefined): void;
34
75
  export declare function retentionDays(): number;
35
76
  /** Appends what someone did in or about a run. Never throws: the record
36
77
  * must not stop the work it records. */
37
- export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at'> & {
78
+ export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at' | 'prev' | 'hash'> & {
38
79
  at?: string;
39
80
  }, database?: DatabaseSync | undefined): void;
40
81
  /** A run's events, oldest first. */
@@ -154,8 +154,84 @@ export function openAuditDb(dir) {
154
154
  const db = new sqlite.DatabaseSync(path.join(dir, 'loopengine.db'));
155
155
  db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
156
156
  db.exec(SCHEMA);
157
+ chainEvents(db);
157
158
  return db;
158
159
  }
160
+ // ---------- the hash chain ----------
161
+ //
162
+ // Each event carries a hash of its own content and of the event before's
163
+ // hash, so changing or removing any event breaks every link after it
164
+ // (verifyEventChain finds where). It shows tampering, not prevents it;
165
+ // and someone who rewrites every hash after an edit isn't caught unless
166
+ // the latest hash was kept somewhere else (latestEventHash, and each
167
+ // export carries the hashes).
168
+ const GENESIS = '';
169
+ /** An event's hash: SHA-256 of the hash before it and its content. */
170
+ export function eventHash(prev, e) {
171
+ const content = JSON.stringify([e.id, e.at, e.agent, e.workflow_id ?? null, e.run_id ?? null, e.kind, e.by ?? null, e.data]);
172
+ return createHash('sha256').update(prev).update('\n').update(content).digest('hex');
173
+ }
174
+ // Adds the chain's columns to a database from before them, and chains any
175
+ // event without a hash (those recorded before), in order.
176
+ function chainEvents(db) {
177
+ const columns = db.prepare('PRAGMA table_info(events)').all().map((c) => c.name);
178
+ if (!columns.includes('hash')) {
179
+ db.exec('ALTER TABLE events ADD COLUMN prev TEXT; ALTER TABLE events ADD COLUMN hash TEXT;');
180
+ }
181
+ const first = db.prepare('SELECT MIN(id) AS id FROM events WHERE hash IS NULL').get();
182
+ if (first.id == null)
183
+ return;
184
+ const before = db.prepare('SELECT hash FROM events WHERE id < ? ORDER BY id DESC LIMIT 1').get(first.id);
185
+ let prev = before?.hash ?? GENESIS;
186
+ const rows = db.prepare('SELECT * FROM events WHERE id >= ? ORDER BY id').all(first.id);
187
+ const set = db.prepare('UPDATE events SET prev = ?, hash = ? WHERE id = ?');
188
+ db.exec('BEGIN');
189
+ try {
190
+ for (const row of rows) {
191
+ const hash = eventHash(prev, row);
192
+ set.run(prev, hash, row.id);
193
+ prev = hash;
194
+ }
195
+ db.exec('COMMIT');
196
+ }
197
+ catch (err) {
198
+ db.exec('ROLLBACK');
199
+ throw err;
200
+ }
201
+ writeMeta('events_chained', `${new Date().toISOString()} ${rows.length}`, db);
202
+ }
203
+ /** Checks every event's hash, in order. */
204
+ export function verifyEventChain(database = auditDb()) {
205
+ if (!database)
206
+ return { ok: true, events: 0 };
207
+ let prev = GENESIS;
208
+ let count = 0;
209
+ let last;
210
+ let after = 0;
211
+ for (;;) {
212
+ const rows = database.prepare('SELECT * FROM events WHERE id > ? ORDER BY id LIMIT 5000').all(after);
213
+ if (!rows.length)
214
+ break;
215
+ for (const row of rows) {
216
+ if ((row.prev ?? GENESIS) !== prev)
217
+ return { ok: false, events: count, broken: { id: row.id, at: row.at, problem: 'missing-before' }, ...(last ? { last } : {}) };
218
+ const hash = eventHash(prev, row);
219
+ if (hash !== row.hash)
220
+ return { ok: false, events: count, broken: { id: row.id, at: row.at, problem: 'changed' }, ...(last ? { last } : {}) };
221
+ prev = hash;
222
+ count++;
223
+ last = { id: row.id, at: row.at, hash };
224
+ }
225
+ after = rows.at(-1).id;
226
+ }
227
+ return { ok: true, events: count, ...(last ? { last } : {}) };
228
+ }
229
+ /** The latest event's id and hash: written down anywhere outside the
230
+ * workspace, it lets a later check show the log wasn't rewritten. */
231
+ export function latestEventHash(database = auditDb()) {
232
+ const row = database?.prepare('SELECT id, at, hash FROM events WHERE hash IS NOT NULL ORDER BY id DESC LIMIT 1').get();
233
+ return row ? { id: Number(row.id), at: row.at, hash: row.hash } : undefined;
234
+ }
159
235
  let db;
160
236
  export function schedulerDir() {
161
237
  return process.env.LOOPENGINE_SCHEDULER_DIR || path.join(process.cwd(), '.scheduler');
@@ -192,7 +268,20 @@ export function recordEvent(event, database = auditDb()) {
192
268
  if (!database)
193
269
  return;
194
270
  try {
195
- database.prepare('INSERT INTO events (at, agent, workflow_id, run_id, kind, by, data) VALUES (?, ?, ?, ?, ?, ?, ?)').run(event.at ?? new Date().toISOString(), event.agent, event.workflow_id ?? null, event.run_id ?? null, event.kind, event.by ?? null, JSON.stringify(event.data));
271
+ // Written and chained in one step, so no other event comes between.
272
+ database.exec('BEGIN IMMEDIATE');
273
+ try {
274
+ const prev = database.prepare('SELECT hash FROM events ORDER BY id DESC LIMIT 1').get()?.hash ?? GENESIS;
275
+ const row = { at: event.at ?? new Date().toISOString(), agent: event.agent, workflow_id: event.workflow_id ?? null, run_id: event.run_id ?? null, kind: event.kind, by: event.by ?? null, data: JSON.stringify(event.data) };
276
+ const { lastInsertRowid } = database.prepare('INSERT INTO events (at, agent, workflow_id, run_id, kind, by, data) VALUES (?, ?, ?, ?, ?, ?, ?)').run(row.at, row.agent, row.workflow_id, row.run_id, row.kind, row.by, row.data);
277
+ const id = Number(lastInsertRowid);
278
+ database.prepare('UPDATE events SET prev = ?, hash = ? WHERE id = ?').run(prev, eventHash(prev, { id, ...row }), id);
279
+ database.exec('COMMIT');
280
+ }
281
+ catch (err) {
282
+ database.exec('ROLLBACK');
283
+ throw err;
284
+ }
196
285
  }
197
286
  catch (err) {
198
287
  console.error('[loopengine] could not record an audit event:', err);
@@ -253,6 +342,8 @@ function eventOf(r) {
253
342
  kind: String(r.kind),
254
343
  ...(r.by ? { by: String(r.by) } : {}),
255
344
  data: JSON.parse(String(r.data)),
345
+ ...(r.prev != null ? { prev: String(r.prev) } : {}),
346
+ ...(r.hash ? { hash: String(r.hash) } : {}),
256
347
  };
257
348
  }
258
349
  // ---------- versions ----------
@@ -149,6 +149,9 @@ export interface RunSearch {
149
149
  until?: string;
150
150
  /** Started before this ISO time (the next page). */
151
151
  before?: string;
152
+ /** Runs worth a look: a person denied or changed what it did, its
153
+ * result was marked bad (or heavily edited), or it asked a question. */
154
+ flag?: 'overruled' | 'bad' | 'asked';
152
155
  limit?: number;
153
156
  }
154
157
  /** One JSON file per run under `<dir>/runs/` — one server process. */
@@ -39,7 +39,10 @@ function matchesSearch(run, f) {
39
39
  && (!f.since || run.started_at >= f.since)
40
40
  && (!f.until || run.started_at <= f.until)
41
41
  && (!f.before || run.started_at < f.before)
42
- && (!f.q || JSON.stringify(run).toLowerCase().includes(f.q.toLowerCase()));
42
+ && (!f.q || JSON.stringify(run).toLowerCase().includes(f.q.toLowerCase()))
43
+ && (f.flag !== 'overruled' || (run.decisions ?? []).some((d) => !d.approved || d.edited))
44
+ && (f.flag !== 'bad' || run.feedback?.verdict === 'bad' || run.feedback?.edit === 'heavy')
45
+ && (f.flag !== 'asked' || (run.answers ?? []).length > 0);
43
46
  }
44
47
  const fileMutex = new KeyedMutex();
45
48
  /** One JSON file per run under `<dir>/runs/` — one server process. */
@@ -192,6 +195,12 @@ export class SqliteRunStore {
192
195
  add('started_at < ?', f.before);
193
196
  if (f.by)
194
197
  add("(EXISTS (SELECT 1 FROM json_each(runs.data, '$.decisions') WHERE json_extract(value, '$.by') = ?) OR EXISTS (SELECT 1 FROM json_each(runs.data, '$.answers') WHERE json_extract(value, '$.by') = ?))", f.by, f.by);
198
+ if (f.flag === 'overruled')
199
+ add("EXISTS (SELECT 1 FROM json_each(runs.data, '$.decisions') WHERE json_extract(value, '$.approved') = 0 OR json_extract(value, '$.edited') = 1)");
200
+ if (f.flag === 'bad')
201
+ add("(json_extract(data, '$.feedback.verdict') = 'bad' OR json_extract(data, '$.feedback.edit') = 'heavy')");
202
+ if (f.flag === 'asked')
203
+ add("json_array_length(data, '$.answers') > 0");
195
204
  if (f.q)
196
205
  add("data LIKE ? ESCAPE '\\'", `%${f.q.replace(/[\\%_]/g, (c) => '\\' + c)}%`);
197
206
  const limit = Math.min(Math.max(f.limit ?? 50, 1), 200);
@@ -43,6 +43,8 @@ export function roleLabel(role) {
43
43
  export function inboxOnlyAllows(method, pathname) {
44
44
  if (pathname === '/inbox' || pathname.startsWith('/inbox/'))
45
45
  return true;
46
+ if (method === 'GET' && /^\/cases\/[^/]+$/.test(pathname))
47
+ return true;
46
48
  if (method === 'POST' && /^\/pending-(approvals\/[^/]+\/resolve|questions\/[^/]+\/answer)$/.test(pathname))
47
49
  return true;
48
50
  if (method === 'GET' && (pathname === '/config/settings' || pathname === '/healthz'))
package/dist/index.d.ts CHANGED
@@ -9,7 +9,9 @@ export { signProxyIdentity, verifyProxyIdentity, TRUSTED_PROXY_IDENTITY_HEADER,
9
9
  export { setUsageSink, recordUsage, sessionUsage, usageBySession, type UsageEvent, type UsageSink, type UsageRow } from '#core/usage.js';
10
10
  export { changeOf, keptBody, type Change } from '#web/change-log.js';
11
11
  export { eventText, eventsCsv, caseRow, type AuditCaseRow } from '#web/audit-admin.js';
12
- export { auditPageHtml } from '#web/audit-page.js';
12
+ export { auditPageHtml, auditPageFor } from '#web/audit-page.js';
13
+ export { buildWorkflowAudit, lineDiff, type WorkflowAudit, type WorkflowAuditInput, type AuditCounts, type AuditPerson, type AuditDecision, type AuditVersion, type AuditCase } from '#web/workflow-audit.js';
14
+ export { workflowAuditReportHtml } from '#web/workflow-audit-report.js';
13
15
  export { workflowHealth, healthAlerts, type WorkflowHealth, type HealthNumbers, type HealthVersion, type HealthDay, type HealthAlert, type HealthMeasure } from '#web/workflow-health.js';
14
16
  export { setRunObserver, reportRun, usedTool, type RunEvent, type RunEventSource, type RunObserver } from '#core/run-events.js';
15
17
  export { readNotifierFile, writeNotifierFile, removeNotifierFile, validateNotifierFile, notifierConfigFromFile, NotifierFileError, NOTIFIER_SECRET_VARS, type NotifierFile, type MessagingApprover } from '#core/notifier-file.js';
@@ -96,10 +98,10 @@ export { WORKFLOW_EXAMPLES, workflowExample, type WorkflowExample } from './core
96
98
  export { WORKFLOW_EXAMPLE_MESSAGES, type WorkflowExampleMessage } from './core/system-agents/workflow-example-messages.js';
97
99
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError, type WorkflowTrigger, type PublicTrigger, type TriggerSettings, type TriggerVerify, type TriggerFilter, type TriggerSender, type SignatureAlgorithm, type TriggerDelivery, type TriggerOutcome, type TriggerStore } from './core/workflow-triggers.js';
98
100
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError, type CallbackDelivery, type CallbackPending, type RunCallbackEvent } from './core/run-callbacks.js';
99
- export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, readMeta, writeMeta, type EventFilter, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays, type Version, type VersionKind, type AuditEvent, type AuditEventKind } from './core/audit-store.js';
101
+ export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, type ChainCheck, readMeta, writeMeta, type EventFilter, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays, type Version, type VersionKind, type AuditEvent, type AuditEventKind } from './core/audit-store.js';
100
102
  export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, type RunSearch, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunVersions, type RunDecision, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
101
103
  export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies, type Workflow, type WorkflowFields, type WorkflowParameter, type WorkflowModel, type WorkflowDelivery, type RunMessageExtras } from './core/workflows.js';
102
- export { EvidenceError, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalCheck, type EvalCriterion, type CriterionKind, type EvalRound, type WorkflowEvals, type EvalRunDeps, type StandIn } from './web/workflow-evidence.js';
104
+ export { EvidenceError, evalCandidates, suggestedCriteria, type EvalCandidate, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalCheck, type EvalCriterion, type CriterionKind, type EvalRound, type WorkflowEvals, type EvalRunDeps, type StandIn } from './web/workflow-evidence.js';
103
105
  export { globalConfigPageHtml } from './web/global-config-page.js';
104
106
  export { playgroundHtml } from './web/playground.js';
105
107
  export { readSkill, writeSkill, deleteSkill, SkillInvalidIdError, SkillNotFoundError } from './web/skills-admin.js';
@@ -145,4 +147,4 @@ export { compressResponses, serveConsoleAsset } from './web/response-compression
145
147
  export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
146
148
  export { homeOverview, workflowsOverview, startsOf, type HomeOverview, type WorkflowsOverview, type WorkflowOverviewRow } from './web/workflows-overview.js';
147
149
  export { homePageHtml } from './web/home-page.js';
148
- export { listInbox, getInboxCase, timelineOf, type InboxDeps, type InboxItem, type InboxCase, type InboxPending, type InboxStep } from './web/inbox-admin.js';
150
+ export { listInbox, getInboxCase, timelineOf, RECENT_DAYS, type InboxView, type InboxDeps, type InboxItem, type InboxCase, type InboxPending, type InboxStep } from './web/inbox-admin.js';
package/dist/index.js CHANGED
@@ -11,7 +11,9 @@ export { signProxyIdentity, verifyProxyIdentity, TRUSTED_PROXY_IDENTITY_HEADER }
11
11
  export { setUsageSink, recordUsage, sessionUsage, usageBySession } from '#core/usage.js';
12
12
  export { changeOf, keptBody } from '#web/change-log.js';
13
13
  export { eventText, eventsCsv, caseRow } from '#web/audit-admin.js';
14
- export { auditPageHtml } from '#web/audit-page.js';
14
+ export { auditPageHtml, auditPageFor } from '#web/audit-page.js';
15
+ export { buildWorkflowAudit, lineDiff } from '#web/workflow-audit.js';
16
+ export { workflowAuditReportHtml } from '#web/workflow-audit-report.js';
15
17
  export { workflowHealth, healthAlerts } from '#web/workflow-health.js';
16
18
  export { setRunObserver, reportRun, usedTool } from '#core/run-events.js';
17
19
  export { readNotifierFile, writeNotifierFile, removeNotifierFile, validateNotifierFile, notifierConfigFromFile, NotifierFileError, NOTIFIER_SECRET_VARS } from '#core/notifier-file.js';
@@ -89,10 +91,10 @@ export { WORKFLOW_EXAMPLES, workflowExample } from './core/system-agents/workflo
89
91
  export { WORKFLOW_EXAMPLE_MESSAGES } from './core/system-agents/workflow-example-messages.js';
90
92
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError } from './core/workflow-triggers.js';
91
93
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError } from './core/run-callbacks.js';
92
- export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, readMeta, writeMeta, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays } from './core/audit-store.js';
94
+ export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, readMeta, writeMeta, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays } from './core/audit-store.js';
93
95
  export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, getRun, isUnderWay, RunError } from './core/workflow-runs.js';
94
96
  export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
95
- export { EvidenceError, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION } from './web/workflow-evidence.js';
97
+ export { EvidenceError, evalCandidates, suggestedCriteria, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, setEvalCriteria, effectiveCriteria, codeCheck, judgeCriteria, checkCase, roundSummary, draftCriteria, startEvalRound, EVAL_CRITERIA_PROMPT, DRAFT_CRITERIA_PROMPT, REFERENCE_CRITERION } from './web/workflow-evidence.js';
96
98
  export { globalConfigPageHtml } from './web/global-config-page.js';
97
99
  export { playgroundHtml } from './web/playground.js';
98
100
  export { readSkill, writeSkill, deleteSkill, SkillInvalidIdError, SkillNotFoundError } from './web/skills-admin.js';
@@ -136,4 +138,4 @@ export { compressResponses, serveConsoleAsset } from './web/response-compression
136
138
  export { workflowsOverviewPageHtml } from './web/workflows-overview-page.js';
137
139
  export { homeOverview, workflowsOverview, startsOf } from './web/workflows-overview.js';
138
140
  export { homePageHtml } from './web/home-page.js';
139
- export { listInbox, getInboxCase, timelineOf } from './web/inbox-admin.js';
141
+ export { listInbox, getInboxCase, timelineOf, RECENT_DAYS } from './web/inbox-admin.js';
@@ -209,6 +209,16 @@ export const agentsConfigPageHtml = `<!doctype html>
209
209
  .wf-crit-kind { font-size: 12px; color: var(--ink-muted); }
210
210
  .wf-crit-rate { font-variant-numeric: tabular-nums; }
211
211
  .wf-case-standins { margin: 0; font-size: 12.5px; color: var(--ink-muted); }
212
+ .wf-run-lines, .wf-cand-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 0; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
213
+ .wf-run-line, .wf-cand-list li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding: 8px 12px; border-top: 1px solid var(--line); font-size: 13px; }
214
+ .wf-run-line:first-child, .wf-cand-list li:first-child { border-top: 0; }
215
+ .wf-run-link { display: flex; gap: 10px; flex: 1 1 320px; min-width: 0; color: var(--ink); text-decoration: none; }
216
+ .wf-run-link:hover .wf-run-text { text-decoration: underline; }
217
+ .wf-run-when { color: var(--ink-muted); white-space: nowrap; }
218
+ .wf-run-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
219
+ .wf-run-line .wf-run-evidence { flex-basis: 100%; padding-left: 2px; }
220
+ .wf-cand-text { display: grid; gap: 2px; flex: 1 1 320px; min-width: 0; }
221
+ .wf-cand-text strong { font-weight: 600; overflow-wrap: anywhere; }
212
222
  .wf-health { display: grid; gap: 12px; margin-bottom: 8px; }
213
223
  .wf-health-alert { padding: 10px 12px; border-radius: 8px; background: var(--bad-soft); color: var(--bad); font-size: 13px; font-weight: 600; }
214
224
  .wf-health-chart { margin: 0; display: grid; gap: 4px; }
@@ -218,6 +228,8 @@ export const agentsConfigPageHtml = `<!doctype html>
218
228
  .wf-health-table table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
219
229
  .wf-health-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 6px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
220
230
  .wf-health-table td { padding: 6px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
231
+ .wf-audit-link { font-size: 13px; font-weight: 600; color: var(--accent-ink); text-decoration: none; padding: 6px 12px; border: 1px solid var(--line); border-radius: 8px; margin-right: 8px; }
232
+ .wf-audit-link:hover { background: var(--surface); }
221
233
  .wf-change-list { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; font-size: 13px; }
222
234
  .wf-change-list li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; padding-bottom: 8px; border-bottom: 1px solid var(--line); }
223
235
  .wf-change-kind { font-size: 11px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-faint); min-width: 64px; }
@@ -952,6 +964,11 @@ ${renderMarkdownScript}
952
964
  var pageParams = new URLSearchParams(location.search);
953
965
  var workflowPageId = pageParams.get('tab') === 'workflows' && pageParams.get('workflow') || null;
954
966
  if (workflowPageId && pageParams.get('wtab')) workflowTabs[workflowPageId] = pageParams.get('wtab');
967
+ // A case's page, with a back link to here.
968
+ function caseHref(runId) {
969
+ return '/cases/' + encodeURIComponent(runId) + '?back=' + encodeURIComponent(location.pathname + location.search);
970
+ }
971
+
955
972
  function workflowPageHref(agent, id, tab) {
956
973
  return '/agents/config?agent=' + encodeURIComponent(agent) + '&tab=workflows&workflow=' + encodeURIComponent(id) + (tab ? '&wtab=' + encodeURIComponent(tab) : '');
957
974
  }
@@ -1132,7 +1149,7 @@ ${renderMarkdownScript}
1132
1149
  var kind = e.kind === 'change' ? 'Setting' : e.kind === 'decision' ? 'Decision' : e.kind === 'answer' ? 'Answer' : 'Feedback';
1133
1150
  return '<li><span class="wf-change-kind ' + escapeHtml(e.kind) + '">' + kind + '</span><span class="wf-change-text">' + changeText(e) + '</span>' +
1134
1151
  '<span class="hint">' + (e.by ? escapeHtml(e.by) + DOT : '') + escapeHtml(when) +
1135
- (e.run_id ? DOT + '<a href="/inbox?case=' + encodeURIComponent(e.run_id) + '">case</a>' : '') + '</span></li>';
1152
+ (e.run_id ? DOT + '<a href="' + caseHref(e.run_id) + '">case</a>' : '') + '</span></li>';
1136
1153
  }).join('') + '</ol>';
1137
1154
  }
1138
1155
 
@@ -1404,9 +1421,34 @@ ${renderMarkdownScript}
1404
1421
  '<h4 class="wf-sub">Eval cases</h4>' +
1405
1422
  '<div class="wf-evals-bar"><button type="button" class="wf-evals-run"' + (!evals.cases.length || running ? ' disabled' : '') + '>' + (running ? 'Running ' + running.done + ' of ' + running.total + String.fromCharCode(8230) : 'Run evals') + '</button>' +
1406
1423
  '<span class="hint">' + (round ? 'Last run ' + escapeHtml(new Date(round.at).toLocaleString()) + (round.briefVersion ? DOT + 'brief v' + round.briefVersion : '') + DOT + 'model ' + escapeHtml(round.model) + DOT + 'judged by ' + escapeHtml(round.judge) : 'A test run: only tools that just read data run. Anything that would send, write or change something, or need approval, isn' + RSQ + 't done, and nobody is asked anything.') + '</span></div>' +
1407
- (cases ? '<ul class="wf-cases">' + cases + '</ul>' : '<p class="hint" style="margin:0">No cases yet. Save a run from History below as a case, then run the cases after each change to the instructions or model.</p>') +
1408
- '<h4 class="wf-sub">History</h4>' +
1409
- (runsHtml ? '<ul class="schedule-history">' + runsHtml + '</ul>' : '<p class="hint" style="margin:0">No runs yet.</p>');
1424
+ (cases ? '<ul class="wf-cases">' + cases + '</ul>' : '<p class="hint" style="margin:0">No cases yet. Save runs worth testing (below) as cases, then run them after each change to the brief or model.</p>') +
1425
+ (workflowPageId ? '<h4 class="wf-sub">Worth testing</h4><div class="wf-candidates"><p class="hint" style="margin:0">Looking through its runs' + String.fromCharCode(8230) + '</p></div>' : '') +
1426
+ '<h4 class="wf-sub">Recent runs</h4>' +
1427
+ (runsHtml ? '<ul class="wf-run-lines">' + runsHtml + '</ul>' : '<p class="hint" style="margin:0">No runs yet.</p>') +
1428
+ (workflowPageId ? '<p class="hint" style="margin:0"><a href="/audit?tab=cases&agent=' + encodeURIComponent(pageParams.get('agent') || '') + '&workflow=' + encodeURIComponent(w.id) + '">See all its runs in Audit ' + String.fromCharCode(8594) + '</a></p>' : '');
1429
+ }
1430
+
1431
+ // Worth testing: runs from the last 30 days that would make good eval
1432
+ // cases, each with why (a person denied or changed what it did, a bad
1433
+ // result, a question it asked, a failure, or a typical good run).
1434
+ var WHY = { denied: ['bad', 'Denied'], changed: ['ask', 'Changed'], bad: ['bad', 'Bad result'], asked: ['ask', 'Asked'], failed: ['bad', 'Failed'], typical: ['good', 'Typical'] };
1435
+ function loadCandidates(card, base) {
1436
+ var box = card.querySelector('.wf-candidates');
1437
+ if (!box) return;
1438
+ fetch(base + '/evals/candidates', { headers: { accept: 'application/json' } })
1439
+ .then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
1440
+ .then(function (data) {
1441
+ var list = data.candidates || [];
1442
+ if (!list.length) { box.innerHTML = '<p class="hint" style="margin:0">Nothing new to suggest from the last 30 days.</p>'; return; }
1443
+ box.innerHTML = '<p class="hint" style="margin:0 0 6px">From the last 30 days, best first. Open one to read it in full before saving.</p><ul class="wf-cand-list">' + list.map(function (c) {
1444
+ var why = WHY[c.why] || ['', c.why];
1445
+ return '<li><span class="le-pill ' + why[0] + '">' + why[1] + '</span>' +
1446
+ '<span class="wf-cand-text"><strong>' + escapeHtml(c.detail) + '</strong><span class="hint">' + escapeHtml(new Date(c.at).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })) + (c.inputs ? DOT + escapeHtml(c.inputs) : '') + '</span></span>' +
1447
+ '<a class="wf-link" href="' + caseHref(c.runId) + '">Open</a>' +
1448
+ '<button type="button" class="wf-link wf-save-case" data-run="' + escapeHtml(c.runId) + '">Save as eval case</button></li>';
1449
+ }).join('') + '</ul>';
1450
+ })
1451
+ .catch(function (err) { box.innerHTML = '<p class="error">Could not look through its runs: ' + escapeHtml(err.message) + '</p>'; });
1410
1452
  }
1411
1453
 
1412
1454
  // A run's evidence line: its feedback, and saving it as an eval case.
@@ -1443,20 +1485,20 @@ ${renderMarkdownScript}
1443
1485
  return '<label class="workflow-param">' + escapeHtml(p) + (spec.required ? '' : ' <span class="hint">(optional)</span>') +
1444
1486
  '<textarea rows="1" name="' + escapeHtml(p) + '"' + (spec.required ? ' required' : '') + ' placeholder="' + escapeHtml(spec.description || '') + '"></textarea></label>';
1445
1487
  }).join('');
1488
+ // Recent runs, one line each, opening the case (where everything
1489
+ // about it is).
1446
1490
  var runs = (w.recentRuns || []).map(function (r) {
1447
1491
  var pill = r.status === 'done' ? '<span class="le-pill good">Done</span>'
1448
1492
  : r.status === 'error' ? '<span class="le-pill bad">Failed</span>'
1449
- : r.status === 'awaiting_approval' ? '<span class="le-pill ask">Waiting for a decision</span>'
1493
+ : r.status === 'awaiting_approval' ? '<span class="le-pill ask">Waiting</span>'
1450
1494
  : '<span class="le-pill accent">Running</span>';
1451
- var values = r.params ? Object.keys(r.params).map(function (k) { return '<span><strong>' + escapeHtml(k) + '</strong>: ' + escapeHtml(r.params[k]) + '</span>'; }).join('') : '';
1452
- var source = r.source === 'console' ? 'Manual run' : r.source === 'api' ? 'App / API' : r.source === 'schedule' ? 'Scheduled' + (r.task_name ? ' · ' + r.task_name : '') : r.source === 'chain' ? 'After another workflow, in a goal' + String.fromCharCode(8217) + 's job' : 'Webhook';
1495
+ var values = r.params ? Object.keys(r.params).map(function (k) { return k + ': ' + r.params[k]; }).join(DOT) : '';
1453
1496
  var outcome = r.status === 'error' ? (r.error || '') : (r.result || '');
1454
- var formattedOutcome = outcome ? renderMarkdownPreview(outcome) : '';
1455
- return '<li class="workflow-run-entry"><div class="workflow-run-entry-head">' + pill +
1456
- '<span class="workflow-run-time">' + escapeHtml(new Date(r.started_at).toLocaleString()) + '</span>' +
1457
- '<span class="workflow-run-source hint">' + escapeHtml(source) + (r.versions && r.versions.brief ? DOT + 'brief v' + r.versions.brief : '') + '</span></div>' +
1458
- (values ? '<div><div class="workflow-run-entry-label">Parameters</div><div class="workflow-run-params">' + values + '</div></div>' : '') +
1459
- (outcome ? '<div><div class="workflow-run-entry-label">' + (r.status === 'error' ? 'Error' : 'Final response') + '</div><div class="schedule-result workflow-markdown">' + formattedOutcome + '</div><details class="schedule-result-details"><summary>View full ' + (r.status === 'error' ? 'error' : 'response') + '</summary><div class="schedule-result-full workflow-markdown workflow-markdown-full">' + formattedOutcome + '</div></details></div>' : '') +
1497
+ var line = (values ? values + DOT : '') + outcome;
1498
+ return '<li class="wf-run-line">' + pill +
1499
+ '<a class="wf-run-link" href="' + caseHref(r.run_id) + '"><span class="wf-run-when">' + escapeHtml(new Date(r.started_at).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })) + '</span>' +
1500
+ '<span class="wf-run-text">' + escapeHtml(line.length > 160 ? line.slice(0, 160) + String.fromCharCode(8230) : line) + '</span></a>' +
1501
+ (r.versions && r.versions.brief ? '<span class="hint">brief v' + r.versions.brief + '</span>' : '') +
1460
1502
  runEvidenceHtml(w, r) + '</li>';
1461
1503
  }).join('');
1462
1504
  var last = workflowLastRun(w);
@@ -1472,7 +1514,7 @@ ${renderMarkdownScript}
1472
1514
  '<div class="wf-page-crumb-row"><button type="button" class="le-menu-btn" data-le-menu aria-label="Open navigation">&#9776;</button>' +
1473
1515
  '<a class="wf-page-crumb" href="/agents/config?agent=' + encodeURIComponent(name) + '&tab=workflows">' + String.fromCharCode(8592) + ' ' + escapeHtml(agentLabel) + ' ' + String.fromCharCode(183) + ' Workflows</a></div>' +
1474
1516
  '<div class="wf-page-title-row"><h1>' + escapeHtml(w.title) + '</h1>' +
1475
- '<span class="wf-row-actions"><button type="button" class="workflow-edit">Edit</button></span></div>' +
1517
+ '<span class="wf-row-actions"><a class="wf-audit-link" href="/audit?agent=' + encodeURIComponent(name) + '&workflow=' + encodeURIComponent(w.id) + '">Audit</a><button type="button" class="workflow-edit">Edit</button></span></div>' +
1476
1518
  (w.description && w.description !== w.title ? '<p class="wf-page-desc">' + escapeHtml(w.description) + '</p>' : '') +
1477
1519
  '<div class="wf-page-meta">' +
1478
1520
  '<span class="wf-page-meta-item"><span class="wf-page-meta-k">Agent</span><a href="/agents/config?agent=' + encodeURIComponent(name) + '">' + escapeHtml(agentLabel) + '</a></span>' +
@@ -2142,6 +2184,7 @@ ${renderMarkdownScript}
2142
2184
  for (var t = 0; t < tabs.length; t++) tabs[t].addEventListener('click', function (ev) { showWorkflowTab(card, ev.currentTarget.dataset.tab); });
2143
2185
  loadBriefVersions(card, base);
2144
2186
  loadWorkflowHealth(card, base);
2187
+ loadCandidates(card, base);
2145
2188
  if (workflowTabs[id] === 'changes') loadWorkflowChanges(card);
2146
2189
  card.querySelector('.workflow-edit').addEventListener('click', function () { openWorkflowEditor(name, card); });
2147
2190
  // Opens the workflow's page on its Triggers tab.
@@ -24,5 +24,7 @@ export interface AuditCaseRow {
24
24
  people: string[];
25
25
  /** The start of its result, or its error. */
26
26
  outcome: string;
27
+ /** Saved as one of its workflow's eval cases. */
28
+ evalCase?: boolean;
27
29
  }
28
- export declare function caseRow(run: WorkflowRun, workflowTitle: string | undefined): AuditCaseRow;
30
+ export declare function caseRow(run: WorkflowRun, workflowTitle: string | undefined, evalCase?: boolean): AuditCaseRow;
@@ -19,7 +19,7 @@ export function eventText(e) {
19
19
  const edit = d.edit === 'none' ? 'used unedited' : d.edit ? `${str(d.edit)} edits` : '';
20
20
  return { what: `Feedback${verdict || edit ? `: ${[verdict, edit].filter(Boolean).join(', ')}` : ''}`, detail: str(d.note) };
21
21
  }
22
- const CSV_COLUMNS = ['When (UTC)', 'Kind', 'Person', 'Agent', 'Workflow', 'What', 'Detail', 'Case'];
22
+ const CSV_COLUMNS = ['When (UTC)', 'Kind', 'Person', 'Agent', 'Workflow', 'What', 'Detail', 'Case', 'Event', 'Hash'];
23
23
  function csvCell(value) {
24
24
  // A leading = + - @ would run as a formula in a spreadsheet.
25
25
  const safe = /^[=+\-@]/.test(value) ? `'${value}` : value;
@@ -29,11 +29,11 @@ function csvCell(value) {
29
29
  export function eventsCsv(events) {
30
30
  const rows = events.map((e) => {
31
31
  const { what, detail } = eventText(e);
32
- return [e.at, e.kind, e.by ?? '', e.agent, e.workflow_id ?? '', what, detail, e.run_id ?? ''].map(csvCell).join(',');
32
+ return [e.at, e.kind, e.by ?? '', e.agent, e.workflow_id ?? '', what, detail, e.run_id ?? '', String(e.id), e.hash ?? ''].map(csvCell).join(',');
33
33
  });
34
34
  return [CSV_COLUMNS.join(','), ...rows].join('\r\n') + '\r\n';
35
35
  }
36
- export function caseRow(run, workflowTitle) {
36
+ export function caseRow(run, workflowTitle, evalCase = false) {
37
37
  const inputs = Object.entries(run.params ?? {}).map(([k, v]) => `${k}: ${v}`).join(' · ');
38
38
  const people = [...new Set([...(run.decisions ?? []), ...(run.answers ?? [])].map((d) => d.by).filter((b) => Boolean(b)))];
39
39
  return {
@@ -48,5 +48,6 @@ export function caseRow(run, workflowTitle) {
48
48
  ...(run.versions?.brief ? { briefVersion: run.versions.brief } : {}),
49
49
  people,
50
50
  outcome: short(run.status === 'error' ? run.error ?? '' : run.result ?? '', 200),
51
+ ...(evalCase ? { evalCase: true } : {}),
51
52
  };
52
53
  }
@@ -1 +1,15 @@
1
+ /** The page with its filters' choices in it (agents, workflows, people),
2
+ * so they show at once instead of after another request. */
3
+ export declare function auditPageFor(filters: {
4
+ agents: {
5
+ name: string;
6
+ label: string;
7
+ }[];
8
+ workflows: {
9
+ agent: string;
10
+ id: string;
11
+ title: string;
12
+ }[];
13
+ people: string[];
14
+ }): string;
1
15
  export declare const auditPageHtml: string;