loopengine 0.4.4 → 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.
- package/dist/core/audit-anchor.d.ts +39 -0
- package/dist/core/audit-anchor.js +90 -0
- package/dist/core/audit-store.d.ts +61 -1
- package/dist/core/audit-store.js +113 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.js +5 -2
- package/dist/web/agents-config-page.js +3 -1
- package/dist/web/audit-admin.js +2 -2
- package/dist/web/audit-page.d.ts +14 -0
- package/dist/web/audit-page.js +105 -15
- package/dist/web/dev-ui-styles.js +2 -0
- package/dist/web/workflow-audit-report.d.ts +8 -0
- package/dist/web/workflow-audit-report.js +129 -0
- package/dist/web/workflow-audit.d.ts +120 -0
- package/dist/web/workflow-audit.js +208 -0
- package/package.json +3 -1
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export declare const AUDIT_ANCHORS_PATH = "/api/workspace/audit-anchors";
|
|
2
|
+
export interface AnchorConfig {
|
|
3
|
+
url: string;
|
|
4
|
+
slug: string;
|
|
5
|
+
secret: string;
|
|
6
|
+
}
|
|
7
|
+
/** Where anchors go and how to sign, or why they stay local. */
|
|
8
|
+
export declare function anchorConfig(env?: NodeJS.ProcessEnv): AnchorConfig | {
|
|
9
|
+
off: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function signAnchorRequest(body: string, timestamp: number, secret: string): string;
|
|
12
|
+
export type AnchorResult = {
|
|
13
|
+
status: 'sent' | 'kept-here';
|
|
14
|
+
eventId: number;
|
|
15
|
+
} | {
|
|
16
|
+
status: 'nothing-new';
|
|
17
|
+
} | {
|
|
18
|
+
status: 'failed';
|
|
19
|
+
reason: string;
|
|
20
|
+
};
|
|
21
|
+
/** Anchors the latest event, unless it already is. Never throws. Off
|
|
22
|
+
* Cloud, the anchor is noted only here. */
|
|
23
|
+
export declare function anchorLatest(config?: AnchorConfig | {
|
|
24
|
+
off: string;
|
|
25
|
+
}, fetchImpl?: typeof fetch): Promise<AnchorResult>;
|
|
26
|
+
/** The anchors kept at loopengine.co, or undefined off Cloud or when
|
|
27
|
+
* they can't be fetched (with why). */
|
|
28
|
+
export declare function fetchAnchors(config?: AnchorConfig | {
|
|
29
|
+
off: string;
|
|
30
|
+
}, fetchImpl?: typeof fetch): Promise<{
|
|
31
|
+
anchors: {
|
|
32
|
+
eventId: number;
|
|
33
|
+
hash: string;
|
|
34
|
+
}[];
|
|
35
|
+
} | {
|
|
36
|
+
unavailable: string;
|
|
37
|
+
}>;
|
|
38
|
+
/** Anchors now (a minute after start) and then daily. */
|
|
39
|
+
export declare function startAuditAnchoring(log?: (message: string) => void): void;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Anchors the audit log's hash chain (core/audit-store.ts) outside the
|
|
2
|
+
// workspace: once a day, the latest event's id and hash go to
|
|
3
|
+
// loopengine.co (POST /api/workspace/audit-anchors), which keeps them
|
|
4
|
+
// where the workspace can't rewrite them. Checking the log
|
|
5
|
+
// (GET /audit/verify) fetches them back (GET on the same path) and
|
|
6
|
+
// matches each against the chain, so rewriting the whole chain to hide a
|
|
7
|
+
// change still shows.
|
|
8
|
+
//
|
|
9
|
+
// Signed like the workspace's other reports (web/lever-events-sync.ts):
|
|
10
|
+
// X-LoopEngine-Workspace names the workspace (from LOOPENGINE_PUBLIC_URL),
|
|
11
|
+
// X-LoopEngine-Signature is t=<unix seconds>,v1=<HMAC-SHA256 of
|
|
12
|
+
// "<t>.<body>"> with LOOPENGINE_TRUSTED_PROXY_SECRET (an empty body for
|
|
13
|
+
// the GET). Off outside LoopEngine Cloud: the anchors are then only kept
|
|
14
|
+
// in the workspace's own database, which shows a changed event but not a
|
|
15
|
+
// rewritten chain.
|
|
16
|
+
import { createHmac } from 'node:crypto';
|
|
17
|
+
import { lastAnchor, latestEventHash, noteAnchor } from './audit-store.js';
|
|
18
|
+
export const AUDIT_ANCHORS_PATH = '/api/workspace/audit-anchors';
|
|
19
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
20
|
+
/** Where anchors go and how to sign, or why they stay local. */
|
|
21
|
+
export function anchorConfig(env = process.env) {
|
|
22
|
+
const secret = env.LOOPENGINE_TRUSTED_PROXY_SECRET;
|
|
23
|
+
if (!secret)
|
|
24
|
+
return { off: 'not a LoopEngine Cloud workspace' };
|
|
25
|
+
let slug;
|
|
26
|
+
try {
|
|
27
|
+
slug = env.LOOPENGINE_PUBLIC_URL ? new URL(env.LOOPENGINE_PUBLIC_URL).hostname.split('.')[0] : undefined;
|
|
28
|
+
}
|
|
29
|
+
catch { }
|
|
30
|
+
if (!slug)
|
|
31
|
+
return { off: 'LOOPENGINE_PUBLIC_URL is needed to name the workspace' };
|
|
32
|
+
return { url: `${(env.LOOPENGINE_CONTROL_PLANE_URL || 'https://loopengine.co').replace(/\/+$/, '')}${AUDIT_ANCHORS_PATH}`, slug, secret };
|
|
33
|
+
}
|
|
34
|
+
export function signAnchorRequest(body, timestamp, secret) {
|
|
35
|
+
return `t=${timestamp},v1=${createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')}`;
|
|
36
|
+
}
|
|
37
|
+
function headers(config, body) {
|
|
38
|
+
return { 'content-type': 'application/json', 'x-loopengine-workspace': config.slug, 'x-loopengine-signature': signAnchorRequest(body, Math.floor(Date.now() / 1000), config.secret) };
|
|
39
|
+
}
|
|
40
|
+
/** Anchors the latest event, unless it already is. Never throws. Off
|
|
41
|
+
* Cloud, the anchor is noted only here. */
|
|
42
|
+
export async function anchorLatest(config = anchorConfig(), fetchImpl = fetch) {
|
|
43
|
+
const latest = latestEventHash();
|
|
44
|
+
if (!latest)
|
|
45
|
+
return { status: 'nothing-new' };
|
|
46
|
+
const last = lastAnchor();
|
|
47
|
+
if (last && last.eventId === latest.id && (last.sentAt || 'off' in config))
|
|
48
|
+
return { status: 'nothing-new' };
|
|
49
|
+
if ('off' in config) {
|
|
50
|
+
noteAnchor({ eventId: latest.id, hash: latest.hash, at: latest.at });
|
|
51
|
+
return { status: 'kept-here', eventId: latest.id };
|
|
52
|
+
}
|
|
53
|
+
const body = JSON.stringify({ eventId: latest.id, hash: latest.hash, eventAt: latest.at });
|
|
54
|
+
try {
|
|
55
|
+
const res = await fetchImpl(config.url, { method: 'POST', headers: headers(config, body), body, signal: AbortSignal.timeout(15_000) });
|
|
56
|
+
if (!res.ok)
|
|
57
|
+
return { status: 'failed', reason: `loopengine.co answered ${res.status}` };
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
return { status: 'failed', reason: `couldn't reach ${config.url}: ${err instanceof Error ? err.message : String(err)}` };
|
|
61
|
+
}
|
|
62
|
+
noteAnchor({ eventId: latest.id, hash: latest.hash, at: latest.at, sentAt: new Date().toISOString() });
|
|
63
|
+
return { status: 'sent', eventId: latest.id };
|
|
64
|
+
}
|
|
65
|
+
/** The anchors kept at loopengine.co, or undefined off Cloud or when
|
|
66
|
+
* they can't be fetched (with why). */
|
|
67
|
+
export async function fetchAnchors(config = anchorConfig(), fetchImpl = fetch) {
|
|
68
|
+
if ('off' in config)
|
|
69
|
+
return { unavailable: config.off };
|
|
70
|
+
try {
|
|
71
|
+
const res = await fetchImpl(config.url, { headers: headers(config, ''), signal: AbortSignal.timeout(15_000) });
|
|
72
|
+
if (!res.ok)
|
|
73
|
+
return { unavailable: `loopengine.co answered ${res.status}` };
|
|
74
|
+
const body = (await res.json());
|
|
75
|
+
const anchors = (body.anchors ?? []).flatMap((a) => (typeof a.eventId === 'number' && typeof a.hash === 'string' ? [{ eventId: a.eventId, hash: a.hash }] : []));
|
|
76
|
+
return { anchors };
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
return { unavailable: `couldn't reach loopengine.co: ${err instanceof Error ? err.message : String(err)}` };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Anchors now (a minute after start) and then daily. */
|
|
83
|
+
export function startAuditAnchoring(log = () => { }) {
|
|
84
|
+
const run = () => void anchorLatest().then((r) => {
|
|
85
|
+
if (r.status === 'failed')
|
|
86
|
+
log(`[loopengine] couldn't anchor the audit log: ${r.reason}`);
|
|
87
|
+
});
|
|
88
|
+
setTimeout(run, 60_000).unref();
|
|
89
|
+
setInterval(run, DAY_MS).unref();
|
|
90
|
+
}
|
|
@@ -17,9 +17,69 @@ 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' | 'missing-after-anchor' | 'anchor-differs';
|
|
53
|
+
};
|
|
54
|
+
/** Anchors checked against the chain. */
|
|
55
|
+
anchors: number;
|
|
56
|
+
}
|
|
57
|
+
/** Checks every event's hash, in order, and that each anchor (a hash
|
|
58
|
+
* sent away earlier: the workspace's own record, or `anchors` fetched
|
|
59
|
+
* back from where they were sent) still matches its event. */
|
|
60
|
+
export declare function verifyEventChain(anchors?: {
|
|
61
|
+
eventId: number;
|
|
62
|
+
hash: string;
|
|
63
|
+
}[], database?: DatabaseSync | undefined): ChainCheck;
|
|
64
|
+
/** The latest event's id and hash, to anchor. */
|
|
65
|
+
export declare function latestEventHash(database?: DatabaseSync | undefined): {
|
|
66
|
+
id: number;
|
|
67
|
+
at: string;
|
|
68
|
+
hash: string;
|
|
69
|
+
} | undefined;
|
|
70
|
+
/** Notes an anchor sent away (or kept only here, `sentAt` absent). */
|
|
71
|
+
export declare function noteAnchor(anchor: {
|
|
72
|
+
eventId: number;
|
|
73
|
+
hash: string;
|
|
74
|
+
at: string;
|
|
75
|
+
sentAt?: string;
|
|
76
|
+
}, database?: DatabaseSync | undefined): void;
|
|
77
|
+
export declare function lastAnchor(database?: DatabaseSync | undefined): {
|
|
78
|
+
eventId: number;
|
|
79
|
+
hash: string;
|
|
80
|
+
at: string;
|
|
81
|
+
sentAt?: string;
|
|
82
|
+
} | undefined;
|
|
23
83
|
export declare function schedulerDir(): string;
|
|
24
84
|
/** The process-wide database; undefined where node:sqlite isn't there,
|
|
25
85
|
* or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
|
|
@@ -34,7 +94,7 @@ export declare function setAuditDb(next: DatabaseSync | undefined): void;
|
|
|
34
94
|
export declare function retentionDays(): number;
|
|
35
95
|
/** Appends what someone did in or about a run. Never throws: the record
|
|
36
96
|
* must not stop the work it records. */
|
|
37
|
-
export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at'> & {
|
|
97
|
+
export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at' | 'prev' | 'hash'> & {
|
|
38
98
|
at?: string;
|
|
39
99
|
}, database?: DatabaseSync | undefined): void;
|
|
40
100
|
/** A run's events, oldest first. */
|
package/dist/core/audit-store.js
CHANGED
|
@@ -154,8 +154,105 @@ 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). The latest hash is also sent away each
|
|
165
|
+
// day (core/audit-anchor.ts), so rewriting the whole chain doesn't pass
|
|
166
|
+
// either. It shows tampering; it can't prevent it.
|
|
167
|
+
const GENESIS = '';
|
|
168
|
+
/** An event's hash: SHA-256 of the hash before it and its content. */
|
|
169
|
+
export function eventHash(prev, e) {
|
|
170
|
+
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]);
|
|
171
|
+
return createHash('sha256').update(prev).update('\n').update(content).digest('hex');
|
|
172
|
+
}
|
|
173
|
+
// Adds the chain's columns to a database from before them, and chains any
|
|
174
|
+
// event without a hash (those recorded before), in order.
|
|
175
|
+
function chainEvents(db) {
|
|
176
|
+
const columns = db.prepare('PRAGMA table_info(events)').all().map((c) => c.name);
|
|
177
|
+
if (!columns.includes('hash')) {
|
|
178
|
+
db.exec('ALTER TABLE events ADD COLUMN prev TEXT; ALTER TABLE events ADD COLUMN hash TEXT;');
|
|
179
|
+
}
|
|
180
|
+
db.exec("CREATE TABLE IF NOT EXISTS audit_anchors (event_id INTEGER PRIMARY KEY, hash TEXT NOT NULL, at TEXT NOT NULL, sent_at TEXT)");
|
|
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, and that each anchor (a hash
|
|
204
|
+
* sent away earlier: the workspace's own record, or `anchors` fetched
|
|
205
|
+
* back from where they were sent) still matches its event. */
|
|
206
|
+
export function verifyEventChain(anchors, database = auditDb()) {
|
|
207
|
+
if (!database)
|
|
208
|
+
return { ok: true, events: 0, anchors: 0 };
|
|
209
|
+
let prev = GENESIS;
|
|
210
|
+
let count = 0;
|
|
211
|
+
let last;
|
|
212
|
+
let after = 0;
|
|
213
|
+
const byId = new Map();
|
|
214
|
+
const kept = anchors ?? database.prepare('SELECT event_id AS eventId, hash FROM audit_anchors').all();
|
|
215
|
+
const wanted = new Set(kept.map((a) => a.eventId));
|
|
216
|
+
for (;;) {
|
|
217
|
+
const rows = database.prepare('SELECT * FROM events WHERE id > ? ORDER BY id LIMIT 5000').all(after);
|
|
218
|
+
if (!rows.length)
|
|
219
|
+
break;
|
|
220
|
+
for (const row of rows) {
|
|
221
|
+
if ((row.prev ?? GENESIS) !== prev)
|
|
222
|
+
return { ok: false, events: count, broken: { id: row.id, at: row.at, problem: 'missing-before' }, anchors: 0, ...(last ? { last } : {}) };
|
|
223
|
+
const hash = eventHash(prev, row);
|
|
224
|
+
if (hash !== row.hash)
|
|
225
|
+
return { ok: false, events: count, broken: { id: row.id, at: row.at, problem: 'changed' }, anchors: 0, ...(last ? { last } : {}) };
|
|
226
|
+
if (wanted.has(row.id))
|
|
227
|
+
byId.set(row.id, hash);
|
|
228
|
+
prev = hash;
|
|
229
|
+
count++;
|
|
230
|
+
last = { id: row.id, at: row.at, hash };
|
|
231
|
+
}
|
|
232
|
+
after = rows.at(-1).id;
|
|
233
|
+
}
|
|
234
|
+
for (const anchor of [...kept].sort((a, b) => a.eventId - b.eventId)) {
|
|
235
|
+
const hash = byId.get(anchor.eventId);
|
|
236
|
+
if (hash === undefined)
|
|
237
|
+
return { ok: false, events: count, broken: { id: anchor.eventId, problem: 'missing-after-anchor' }, anchors: kept.length, ...(last ? { last } : {}) };
|
|
238
|
+
if (hash !== anchor.hash)
|
|
239
|
+
return { ok: false, events: count, broken: { id: anchor.eventId, problem: 'anchor-differs' }, anchors: kept.length, ...(last ? { last } : {}) };
|
|
240
|
+
}
|
|
241
|
+
return { ok: true, events: count, anchors: kept.length, ...(last ? { last } : {}) };
|
|
242
|
+
}
|
|
243
|
+
/** The latest event's id and hash, to anchor. */
|
|
244
|
+
export function latestEventHash(database = auditDb()) {
|
|
245
|
+
const row = database?.prepare('SELECT id, at, hash FROM events WHERE hash IS NOT NULL ORDER BY id DESC LIMIT 1').get();
|
|
246
|
+
return row ? { id: Number(row.id), at: row.at, hash: row.hash } : undefined;
|
|
247
|
+
}
|
|
248
|
+
/** Notes an anchor sent away (or kept only here, `sentAt` absent). */
|
|
249
|
+
export function noteAnchor(anchor, database = auditDb()) {
|
|
250
|
+
database?.prepare('INSERT OR REPLACE INTO audit_anchors (event_id, hash, at, sent_at) VALUES (?, ?, ?, ?)').run(anchor.eventId, anchor.hash, anchor.at, anchor.sentAt ?? null);
|
|
251
|
+
}
|
|
252
|
+
export function lastAnchor(database = auditDb()) {
|
|
253
|
+
const row = database?.prepare('SELECT event_id, hash, at, sent_at FROM audit_anchors ORDER BY event_id DESC LIMIT 1').get();
|
|
254
|
+
return row ? { eventId: Number(row.event_id), hash: row.hash, at: row.at, ...(row.sent_at ? { sentAt: row.sent_at } : {}) } : undefined;
|
|
255
|
+
}
|
|
159
256
|
let db;
|
|
160
257
|
export function schedulerDir() {
|
|
161
258
|
return process.env.LOOPENGINE_SCHEDULER_DIR || path.join(process.cwd(), '.scheduler');
|
|
@@ -192,7 +289,20 @@ export function recordEvent(event, database = auditDb()) {
|
|
|
192
289
|
if (!database)
|
|
193
290
|
return;
|
|
194
291
|
try {
|
|
195
|
-
|
|
292
|
+
// Written and chained in one step, so no other event comes between.
|
|
293
|
+
database.exec('BEGIN IMMEDIATE');
|
|
294
|
+
try {
|
|
295
|
+
const prev = database.prepare('SELECT hash FROM events ORDER BY id DESC LIMIT 1').get()?.hash ?? GENESIS;
|
|
296
|
+
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) };
|
|
297
|
+
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);
|
|
298
|
+
const id = Number(lastInsertRowid);
|
|
299
|
+
database.prepare('UPDATE events SET prev = ?, hash = ? WHERE id = ?').run(prev, eventHash(prev, { id, ...row }), id);
|
|
300
|
+
database.exec('COMMIT');
|
|
301
|
+
}
|
|
302
|
+
catch (err) {
|
|
303
|
+
database.exec('ROLLBACK');
|
|
304
|
+
throw err;
|
|
305
|
+
}
|
|
196
306
|
}
|
|
197
307
|
catch (err) {
|
|
198
308
|
console.error('[loopengine] could not record an audit event:', err);
|
|
@@ -253,6 +363,8 @@ function eventOf(r) {
|
|
|
253
363
|
kind: String(r.kind),
|
|
254
364
|
...(r.by ? { by: String(r.by) } : {}),
|
|
255
365
|
data: JSON.parse(String(r.data)),
|
|
366
|
+
...(r.prev != null ? { prev: String(r.prev) } : {}),
|
|
367
|
+
...(r.hash ? { hash: String(r.hash) } : {}),
|
|
256
368
|
};
|
|
257
369
|
}
|
|
258
370
|
// ---------- versions ----------
|
package/dist/index.d.ts
CHANGED
|
@@ -9,7 +9,10 @@ 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';
|
|
15
|
+
export { anchorConfig, anchorLatest, fetchAnchors, signAnchorRequest, startAuditAnchoring, AUDIT_ANCHORS_PATH, type AnchorConfig, type AnchorResult } from '#core/audit-anchor.js';
|
|
13
16
|
export { workflowHealth, healthAlerts, type WorkflowHealth, type HealthNumbers, type HealthVersion, type HealthDay, type HealthAlert, type HealthMeasure } from '#web/workflow-health.js';
|
|
14
17
|
export { setRunObserver, reportRun, usedTool, type RunEvent, type RunEventSource, type RunObserver } from '#core/run-events.js';
|
|
15
18
|
export { readNotifierFile, writeNotifierFile, removeNotifierFile, validateNotifierFile, notifierConfigFromFile, NotifierFileError, NOTIFIER_SECRET_VARS, type NotifierFile, type MessagingApprover } from '#core/notifier-file.js';
|
|
@@ -96,7 +99,7 @@ export { WORKFLOW_EXAMPLES, workflowExample, type WorkflowExample } from './core
|
|
|
96
99
|
export { WORKFLOW_EXAMPLE_MESSAGES, type WorkflowExampleMessage } from './core/system-agents/workflow-example-messages.js';
|
|
97
100
|
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
101
|
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';
|
|
102
|
+
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, noteAnchor, lastAnchor, 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
103
|
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
104
|
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
105
|
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';
|
package/dist/index.js
CHANGED
|
@@ -11,7 +11,10 @@ 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';
|
|
17
|
+
export { anchorConfig, anchorLatest, fetchAnchors, signAnchorRequest, startAuditAnchoring, AUDIT_ANCHORS_PATH } from '#core/audit-anchor.js';
|
|
15
18
|
export { workflowHealth, healthAlerts } from '#web/workflow-health.js';
|
|
16
19
|
export { setRunObserver, reportRun, usedTool } from '#core/run-events.js';
|
|
17
20
|
export { readNotifierFile, writeNotifierFile, removeNotifierFile, validateNotifierFile, notifierConfigFromFile, NotifierFileError, NOTIFIER_SECRET_VARS } from '#core/notifier-file.js';
|
|
@@ -89,7 +92,7 @@ export { WORKFLOW_EXAMPLES, workflowExample } from './core/system-agents/workflo
|
|
|
89
92
|
export { WORKFLOW_EXAMPLE_MESSAGES } from './core/system-agents/workflow-example-messages.js';
|
|
90
93
|
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
94
|
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';
|
|
95
|
+
export { auditDb, openAuditDb, setAuditDb, recordEvent, runEvents, listEvents, eventPeople, eventHash, verifyEventChain, latestEventHash, noteAnchor, lastAnchor, readMeta, writeMeta, noteVersion, listVersions, getVersion, briefContent, briefFromContent, retentionDays } from './core/audit-store.js';
|
|
93
96
|
export { WorkflowRunner, FileRunStore, SqliteRunStore, getRunStore, setRunStore, listRuns, runsSince, searchRuns, getRun, isUnderWay, RunError } from './core/workflow-runs.js';
|
|
94
97
|
export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
|
|
95
98
|
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';
|
|
@@ -218,6 +218,8 @@ export const agentsConfigPageHtml = `<!doctype html>
|
|
|
218
218
|
.wf-health-table table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
|
219
219
|
.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
220
|
.wf-health-table td { padding: 6px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
|
|
221
|
+
.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; }
|
|
222
|
+
.wf-audit-link:hover { background: var(--surface); }
|
|
221
223
|
.wf-change-list { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; font-size: 13px; }
|
|
222
224
|
.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
225
|
.wf-change-kind { font-size: 11px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-faint); min-width: 64px; }
|
|
@@ -1472,7 +1474,7 @@ ${renderMarkdownScript}
|
|
|
1472
1474
|
'<div class="wf-page-crumb-row"><button type="button" class="le-menu-btn" data-le-menu aria-label="Open navigation">☰</button>' +
|
|
1473
1475
|
'<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
1476
|
'<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>' +
|
|
1477
|
+
'<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
1478
|
(w.description && w.description !== w.title ? '<p class="wf-page-desc">' + escapeHtml(w.description) + '</p>' : '') +
|
|
1477
1479
|
'<div class="wf-page-meta">' +
|
|
1478
1480
|
'<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>' +
|
package/dist/web/audit-admin.js
CHANGED
|
@@ -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,7 +29,7 @@ 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
|
}
|
package/dist/web/audit-page.d.ts
CHANGED
|
@@ -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;
|
package/dist/web/audit-page.js
CHANGED
|
@@ -7,6 +7,12 @@
|
|
|
7
7
|
// placeholders, since it lives inside a template literal.
|
|
8
8
|
import { devUiCss } from './dev-ui-styles.js';
|
|
9
9
|
import { consoleShellScript, consoleSidebarHtml } from './console-shell.js';
|
|
10
|
+
/** The page with its filters' choices in it (agents, workflows, people),
|
|
11
|
+
* so they show at once instead of after another request. */
|
|
12
|
+
export function auditPageFor(filters) {
|
|
13
|
+
// In a script element: no "</" may end it early.
|
|
14
|
+
return auditPageHtml.replace('null/*AUDIT_FILTERS*/', JSON.stringify(filters).replace(/</g, '\\u003c'));
|
|
15
|
+
}
|
|
10
16
|
export const auditPageHtml = `<!doctype html>
|
|
11
17
|
<html lang="en">
|
|
12
18
|
<head>
|
|
@@ -19,10 +25,21 @@ export const auditPageHtml = `<!doctype html>
|
|
|
19
25
|
.au-tabs button { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 8px 12px; font-size: 14px; font-weight: 600; color: var(--ink-muted); margin-bottom: -1px; }
|
|
20
26
|
.au-tabs button[aria-selected="true"] { color: var(--accent-ink); border-bottom-color: var(--accent); }
|
|
21
27
|
.au-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
|
22
|
-
.au-bar select, .au-bar input { font: inherit; font-size: 13px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); max-width:
|
|
28
|
+
.au-bar select, .au-bar input { font: inherit; font-size: 13px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--ink); max-width: 180px; }
|
|
23
29
|
.au-bar input[type="search"] { flex: 1; min-width: 160px; max-width: none; }
|
|
24
30
|
.au-bar [hidden] { display: none; }
|
|
25
|
-
.au-
|
|
31
|
+
.au-actions { display: inline-flex; gap: 8px; margin-left: auto; }
|
|
32
|
+
.au-verify { font-size: 13px; }
|
|
33
|
+
.au-check { padding: 10px 14px; border-radius: 10px; font-size: 13px; background: var(--good-soft); color: var(--good); }
|
|
34
|
+
.au-check.bad { background: var(--bad-soft); color: var(--bad); font-weight: 600; }
|
|
35
|
+
.au-check .hint { display: block; margin-top: 2px; font-weight: 400; }
|
|
36
|
+
.au-summary { border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; display: grid; gap: 10px; background: var(--bg); }
|
|
37
|
+
.au-summary h2 { margin: 0; font-size: 15px; }
|
|
38
|
+
.au-summary ul { margin: 0; padding-left: 20px; display: grid; gap: 4px; font-size: 13.5px; line-height: 1.5; }
|
|
39
|
+
.au-summary-tools { display: flex; gap: 8px; flex-wrap: wrap; }
|
|
40
|
+
.au-summary-tools a { font-size: 13px; font-weight: 600; color: var(--accent-ink); text-decoration: none; padding: 6px 12px; border: 1px solid var(--line); border-radius: 8px; }
|
|
41
|
+
.au-summary-tools a.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
|
|
42
|
+
.au-export { font-size: 13px; font-weight: 600; color: var(--accent-ink); text-decoration: none; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; }
|
|
26
43
|
.au-list { border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--bg); }
|
|
27
44
|
.au-row { display: grid; grid-template-columns: 136px 80px minmax(0, 1fr) auto; gap: 12px; align-items: baseline; padding: 10px 16px; border-top: 1px solid var(--line); font-size: 13px; }
|
|
28
45
|
.au-row:first-child { border-top: 0; }
|
|
@@ -81,14 +98,18 @@ ${consoleSidebarHtml}
|
|
|
81
98
|
<option value="7">Last 7 days</option><option value="30" selected>Last 30 days</option><option value="90">Last 90 days</option><option value="365">Last year</option><option value="">All time</option>
|
|
82
99
|
</select>
|
|
83
100
|
<input type="search" id="auQ" placeholder="Search" aria-label="Search">
|
|
84
|
-
<
|
|
101
|
+
<span class="au-actions"><button type="button" class="au-verify" id="auVerify">Verify log</button>
|
|
102
|
+
<a class="au-export" id="auExport" href="/audit/events.csv" download>Export CSV</a></span>
|
|
85
103
|
</div>
|
|
104
|
+
<div class="au-check" id="auCheck" role="status" hidden></div>
|
|
105
|
+
<section class="au-summary" id="auSummary" hidden></section>
|
|
86
106
|
<div id="auList"><p class="hint">Loading…</p></div>
|
|
87
107
|
<button type="button" class="au-more" id="auMore" hidden>Load older</button>
|
|
88
108
|
</div></div></div>
|
|
89
109
|
</main>
|
|
90
110
|
</div>
|
|
91
111
|
${consoleShellScript}
|
|
112
|
+
<script>window.AUDIT_FILTERS = null/*AUDIT_FILTERS*/;</script>
|
|
92
113
|
<script>
|
|
93
114
|
(function () {
|
|
94
115
|
var DOT = ' ' + String.fromCharCode(183) + ' ';
|
|
@@ -99,7 +120,10 @@ ${consoleShellScript}
|
|
|
99
120
|
kind: params.get('kind') || '', status: params.get('status') || '',
|
|
100
121
|
period: params.has('period') ? params.get('period') : '30', q: params.get('q') || '',
|
|
101
122
|
};
|
|
102
|
-
|
|
123
|
+
// The filters' choices come with the page (auditPageFor), so they show
|
|
124
|
+
// at once; a page served without them fetches them.
|
|
125
|
+
var embedded = window.AUDIT_FILTERS || null;
|
|
126
|
+
var filters = embedded || { agents: [], workflows: [], people: [] };
|
|
103
127
|
var next = null;
|
|
104
128
|
var list = document.getElementById('auList');
|
|
105
129
|
var more = document.getElementById('auMore');
|
|
@@ -238,11 +262,37 @@ ${consoleShellScript}
|
|
|
238
262
|
el.kind.hidden = state.tab !== 'activity';
|
|
239
263
|
el.status.hidden = state.tab !== 'cases';
|
|
240
264
|
el.exportLink.hidden = state.tab !== 'activity';
|
|
265
|
+
verifyBtn.hidden = state.tab !== 'activity';
|
|
241
266
|
el.exportLink.href = '/audit/events.csv?' + query();
|
|
242
267
|
remember();
|
|
243
268
|
}
|
|
244
269
|
|
|
245
|
-
|
|
270
|
+
// With a workflow chosen: its audit for the period, in sentences, and
|
|
271
|
+
// its report.
|
|
272
|
+
var summaryBox = document.getElementById('auSummary');
|
|
273
|
+
function loadSummary() {
|
|
274
|
+
var wf = state.workflow && filters.workflows.filter(function (w) { return w.id === state.workflow && (!state.agent || w.agent === state.agent); })[0];
|
|
275
|
+
if (!wf) { summaryBox.hidden = true; return; }
|
|
276
|
+
var q = new URLSearchParams();
|
|
277
|
+
q.set('since', state.period ? new Date(Date.now() - Number(state.period) * 86400000).toISOString() : '2000-01-01T00:00:00.000Z');
|
|
278
|
+
var base = '/agents/' + encodeURIComponent(wf.agent) + '/workflows/' + encodeURIComponent(wf.id) + '/audit';
|
|
279
|
+
summaryBox.hidden = false;
|
|
280
|
+
summaryBox.innerHTML = '<h2>' + esc(wf.title) + '</h2><p class="hint">Loading its audit' + String.fromCharCode(8230) + '</p>';
|
|
281
|
+
fetch(base + '?' + q.toString(), { headers: { accept: 'application/json' } })
|
|
282
|
+
.then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
|
|
283
|
+
.then(function (a) {
|
|
284
|
+
if (state.workflow !== wf.id) return;
|
|
285
|
+
var period = el.period.options[el.period.selectedIndex].text.toLowerCase();
|
|
286
|
+
summaryBox.innerHTML = '<h2>' + esc(wf.title) + ' <span class="hint">' + esc(period) + '</span></h2>' +
|
|
287
|
+
'<ul>' + a.summary.map(function (line) { return '<li>' + esc(line) + '</li>'; }).join('') + '</ul>' +
|
|
288
|
+
'<div class="au-summary-tools"><a class="primary" href="' + base + '/report?' + q.toString() + '">Open the report</a>' +
|
|
289
|
+
'<a href="' + base + '/report?' + q.toString() + '&format=json" download>Download JSON</a>' +
|
|
290
|
+
'<a href="' + workflowHref(wf.agent, wf.id, '') + '">Open the workflow</a></div>';
|
|
291
|
+
})
|
|
292
|
+
.catch(function (err) { summaryBox.innerHTML = '<p class="error">Could not load its audit: ' + esc(err.message) + '</p>'; });
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function changed() { sync(); load(false); loadSummary(); }
|
|
246
296
|
|
|
247
297
|
document.querySelector('.au-tabs').addEventListener('click', function (ev) {
|
|
248
298
|
var b = ev.target.closest('button[data-tab]');
|
|
@@ -261,20 +311,60 @@ ${consoleShellScript}
|
|
|
261
311
|
});
|
|
262
312
|
more.addEventListener('click', function () { load(true); });
|
|
263
313
|
|
|
314
|
+
// Checks every event's hash, in order, and the anchors sent away.
|
|
315
|
+
var verifyBtn = document.getElementById('auVerify');
|
|
316
|
+
var check = document.getElementById('auCheck');
|
|
317
|
+
var PROBLEMS = {
|
|
318
|
+
'changed': 'it was changed after it was recorded',
|
|
319
|
+
'missing-before': 'an event before it was removed, or the order changed',
|
|
320
|
+
'missing-after-anchor': 'events up to an anchored point are missing',
|
|
321
|
+
'anchor-differs': 'it no longer matches the hash anchored for it',
|
|
322
|
+
};
|
|
323
|
+
verifyBtn.addEventListener('click', function () {
|
|
324
|
+
verifyBtn.disabled = true;
|
|
325
|
+
check.hidden = false;
|
|
326
|
+
check.className = 'au-check';
|
|
327
|
+
check.textContent = 'Checking every event' + String.fromCharCode(8230);
|
|
328
|
+
fetch('/audit/verify', { headers: { accept: 'application/json' } })
|
|
329
|
+
.then(function (r) { return r.ok ? r.json() : r.json().then(function (b) { throw new Error(b.error || 'HTTP ' + r.status); }); })
|
|
330
|
+
.then(function (v) {
|
|
331
|
+
var anchors = v.anchors ? v.anchors + ' anchor' + (v.anchors === 1 ? '' : 's') + ' kept at ' + v.anchoredAt + ' match' + (v.anchors === 1 ? 'es' : '') : 'no anchors yet (one is sent each day)';
|
|
332
|
+
var note = v.anchorsNote ? '<span class="hint">Anchors checked are this workspace' + String.fromCharCode(8217) + 's own: ' + esc(v.anchorsNote) + '.</span>' : '';
|
|
333
|
+
if (v.ok) {
|
|
334
|
+
check.innerHTML = 'Intact: all ' + v.events.toLocaleString() + ' events check out, and ' + anchors + '.' +
|
|
335
|
+
(v.last ? '<span class="hint">Latest event #' + v.last.id + ', ' + esc(when(v.last.at)) + DOT + 'hash ' + esc(v.last.hash.slice(0, 16)) + String.fromCharCode(8230) + '</span>' : '') + note;
|
|
336
|
+
} else {
|
|
337
|
+
check.className = 'au-check bad';
|
|
338
|
+
check.innerHTML = 'Broken at event #' + v.broken.id + (v.broken.at ? ' (' + esc(when(v.broken.at)) + ')' : '') + ': ' + esc(PROBLEMS[v.broken.problem] || v.broken.problem) + '.' +
|
|
339
|
+
'<span class="hint">' + v.events.toLocaleString() + ' events before it check out.</span>' + note;
|
|
340
|
+
}
|
|
341
|
+
})
|
|
342
|
+
.catch(function (err) { check.className = 'au-check bad'; check.textContent = 'Could not check: ' + err.message; })
|
|
343
|
+
.then(function () { verifyBtn.disabled = false; });
|
|
344
|
+
});
|
|
345
|
+
|
|
264
346
|
el.q.value = state.q;
|
|
265
347
|
el.kind.value = state.kind;
|
|
266
348
|
el.status.value = state.status;
|
|
267
349
|
el.period.value = state.period;
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
.
|
|
271
|
-
.
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
350
|
+
function fillFilters(f) {
|
|
351
|
+
filters = f;
|
|
352
|
+
el.agent.innerHTML = '<option value="">All agents</option>' + f.agents.map(function (a) { return '<option value="' + esc(a.name) + '"' + (a.name === state.agent ? ' selected' : '') + '>' + esc(a.label) + '</option>'; }).join('');
|
|
353
|
+
el.by.innerHTML = '<option value="">Anyone</option>' + f.people.map(function (p) { return '<option value="' + esc(p) + '"' + (p === state.by ? ' selected' : '') + '>' + esc(p) + '</option>'; }).join('');
|
|
354
|
+
fillWorkflows();
|
|
355
|
+
}
|
|
356
|
+
if (embedded) {
|
|
357
|
+
fillFilters(embedded);
|
|
358
|
+
changed();
|
|
359
|
+
} else {
|
|
360
|
+
// The list doesn't wait for the choices; its rows are named again once
|
|
361
|
+
// they come.
|
|
362
|
+
changed();
|
|
363
|
+
fetch('/audit/filters', { headers: { accept: 'application/json' } })
|
|
364
|
+
.then(function (r) { return r.ok ? r.json() : null; })
|
|
365
|
+
.catch(function () { return null; })
|
|
366
|
+
.then(function (f) { if (f) { fillFilters(f); load(false); } });
|
|
367
|
+
}
|
|
278
368
|
})();
|
|
279
369
|
</script>
|
|
280
370
|
</body>
|
|
@@ -70,6 +70,8 @@ export const devUiCss = `
|
|
|
70
70
|
cursor: pointer;
|
|
71
71
|
font-weight: 500;
|
|
72
72
|
}
|
|
73
|
+
select { cursor: pointer; }
|
|
74
|
+
select:disabled { cursor: default; }
|
|
73
75
|
button:hover:not(:disabled) { background: var(--surface); }
|
|
74
76
|
button[type="submit"], button.primary {
|
|
75
77
|
background: var(--accent);
|
|
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "loopengine",
|
|
3
|
-
"version": "0.4.
|
|
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",
|