@nones/agentflow-core 0.1.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1580 @@
1
+ import { Database, type SQLQueryBindings } from "bun:sqlite";
2
+ import { statSync } from "node:fs";
3
+ import { basename } from "node:path";
4
+ import { AgentFlowError } from "./errors";
5
+ import {
6
+ listArtifactVersions,
7
+ type ArtifactCatalogueEntry,
8
+ } from "./artifact-history";
9
+ import { SCHEMA_VERSION, canonicalProjectId } from "./store";
10
+ import type {
11
+ AgentStatus,
12
+ OperationReceipt,
13
+ PlanPhaseDescriptor,
14
+ PlanStepDescriptor,
15
+ RecoveryItem,
16
+ RunPlanMetadata,
17
+ RunStatus,
18
+ WaveStatus,
19
+ } from "./types";
20
+
21
+ /**
22
+ * Read-only SQLite inspection.
23
+ *
24
+ * The inspector opens the durable state database with `readonly`, so it never
25
+ * creates, migrates or writes anything and works while the daemon is down or
26
+ * running. Every query is parameterized and every list is keyset-paginated with
27
+ * a bounded page size, so an active run cannot exceed an IPC response limit.
28
+ * Nothing here infers a PID, a daemon generation or ownership of a live process:
29
+ * only what AgentFlow actually persisted is reported.
30
+ */
31
+
32
+ export const INSPECTION_SNAPSHOT_VERSION = 1;
33
+ export const INSPECTION_DEFAULT_LIMIT = 100;
34
+ export const INSPECTION_MAX_LIMIT = 500;
35
+ /** Payload bound for one page. Records past it are dropped and the cursor keeps resuming. */
36
+ export const INSPECTION_PAGE_MAX_BYTES = 256 * 1024;
37
+ /** Hard cap on exported document bytes before value-level truncation. */
38
+ export const INSPECTION_VALUE_MAX_BYTES = 2 * 1024;
39
+
40
+ export type StepKind = "agent" | "script" | "gate";
41
+
42
+ /** Every terminal step status, including the older `blocked`/`skipped` names. */
43
+ export const STEP_TERMINAL_STATUSES: readonly string[] = [
44
+ "succeeded",
45
+ "failed",
46
+ "paused",
47
+ "blocked",
48
+ "skipped",
49
+ "cancelled",
50
+ "interrupted",
51
+ ];
52
+
53
+ const ERROR_EVENT_FILTER =
54
+ "(type LIKE '%.error' OR type LIKE '%.failed' OR type LIKE '%.failure' OR type IN ('error', 'failed', 'quota.exhausted'))";
55
+
56
+ const REDACTED = "[redacted]";
57
+ const SECRET_KEY =
58
+ /(authorization|api[-_]?key|access[-_]?token|refresh[-]?token|bearer|cookie|credential|passw(or)?d|private[-_]?key|secret|session[-_]?token|client[-_]?secret)/i;
59
+ /** `token`, `auth` and `key` are secrets only as exact keys, not `tokenCount`. */
60
+ const SECRET_EXACT = /^(token|auth|key|cookie|session)$/i;
61
+
62
+ /** Project identity, mirroring `Store.getRunSnapshot`'s canonical fields. */
63
+ export interface InspectionProject {
64
+ id?: string;
65
+ dir?: string;
66
+ }
67
+
68
+ export interface RunHeader {
69
+ id: string;
70
+ name?: string;
71
+ project: InspectionProject;
72
+ strategy: string;
73
+ /** Digest of the plan the run is executing, when one was persisted. */
74
+ planDigest?: string;
75
+ /** Highest applied plan revision; absent when no amendment was applied. */
76
+ revision?: number;
77
+ predecessorId?: string;
78
+ successorId?: string;
79
+ /** Stable lifecycle reason: the run error or a derived `stopped` marker. */
80
+ lifecycleReason?: string;
81
+ /** Daemon generation persisted with the run's newest event. */
82
+ activeDaemonGeneration?: number;
83
+ adapter: string;
84
+ sealed: boolean;
85
+ stopped: boolean;
86
+ maxConcurrent?: number;
87
+ activeTurns: number;
88
+ turnCounts: Record<string, number>;
89
+ createdAt: number;
90
+ updatedAt: number;
91
+ /** Elapsed time up to `updatedAt`; never measured from a PID. */
92
+ elapsedMs: number;
93
+ status: RunStatus;
94
+ }
95
+
96
+ /** Explicit terminal breakdown: current counts and a completed total. */
97
+ export interface StatusCounts {
98
+ total: number;
99
+ byStatus: Record<string, number>;
100
+ /** Steps in any terminal state (see `STEP_TERMINAL_STATUSES`). */
101
+ completed: number;
102
+ /** Terminal steps that still block progress. */
103
+ current: number;
104
+ breakdown: { succeeded: number; failed: number; blocked: number };
105
+ }
106
+
107
+ export interface PhaseSummary {
108
+ waveId: string;
109
+ index: number;
110
+ status: WaveStatus;
111
+ phaseId?: string;
112
+ startedAt?: number;
113
+ finishedAt?: number;
114
+ counts: StatusCounts;
115
+ }
116
+
117
+ export interface StepSummary {
118
+ /** Stable step key: the agent id, or its persisted `stepKey`. */
119
+ id: string;
120
+ agentId: string;
121
+ waveId: string;
122
+ phaseId: string;
123
+ kind: StepKind;
124
+ status: AgentStatus | string;
125
+ profileId: string;
126
+ adapter: string;
127
+ model?: string;
128
+ quotaGroup: string;
129
+ attempts: number;
130
+ attempt?: string;
131
+ reason?: string;
132
+ blocker?: string;
133
+ session?: string;
134
+ turns: number;
135
+ reusedFrom?: string;
136
+ startedAt?: number;
137
+ finishedAt?: number;
138
+ counts: StatusCounts;
139
+ }
140
+
141
+ export interface InspectionSummary {
142
+ status: RunStatus;
143
+ run: { status: RunStatus; decided: boolean };
144
+ waves: StatusCounts & { byStatus: Record<string, number> };
145
+ agents: StatusCounts & { byStatus: Record<string, number> };
146
+ /** Steps (agent rows) broken down by status. */
147
+ steps: StatusCounts;
148
+ /** Waves broken down by status, kept alongside `waves.byStatus`. */
149
+ byWaveStatus: Record<string, number>;
150
+ byAgentStatus: Record<string, number>;
151
+ events: number;
152
+ lastEventAt?: number;
153
+ recovery: RecoveryItem[];
154
+ operations: OperationReceipt[];
155
+ }
156
+
157
+ export interface InspectionPage {
158
+ snapshotVersion: number;
159
+ readOnly: true;
160
+ mode: "snapshot" | "runs";
161
+ at: number;
162
+ limit: number;
163
+ /** True when the page stopped before its limit because of the byte cap. */
164
+ truncated: boolean;
165
+ /** Resume token for the next page; null when this page is the last. */
166
+ nextCursor: string | null;
167
+ /** Highest sequence/created-at observed, for follow reconnects. */
168
+ highWaterMark: number;
169
+ summary?: InspectionSummary;
170
+ header?: RunHeader;
171
+ phases?: PhaseSummary[];
172
+ steps?: StepSummary[];
173
+ artifacts?: Array<{
174
+ id: string;
175
+ type: string;
176
+ state: string;
177
+ required: boolean;
178
+ }>;
179
+ artifactVersions?: ArtifactCatalogueEntry[];
180
+ history?: {
181
+ provider: string;
182
+ sessionId: string;
183
+ status: string;
184
+ capturedAt: number;
185
+ records: { seq: number; data: unknown }[];
186
+ };
187
+ runs?: RunListItem[];
188
+ }
189
+
190
+ export interface RunListItem {
191
+ id: string;
192
+ name?: string;
193
+ status: RunStatus;
194
+ project: InspectionProject;
195
+ strategy: string;
196
+ createdAt: number;
197
+ updatedAt: number;
198
+ }
199
+
200
+ export interface InspectOptions {
201
+ /** Run id, or a display name (newest run wins when names repeat). */
202
+ selector?: string;
203
+ /** Canonical project directory or id used to resolve a selector. */
204
+ project?: string;
205
+ /** Only runs recorded for this project. */
206
+ projectOnly?: string;
207
+ phase?: string;
208
+ round?: number;
209
+ agent?: string;
210
+ failed?: boolean;
211
+ /** Resume from a previous page's `nextCursor`. */
212
+ after?: string;
213
+ limit?: number;
214
+ }
215
+
216
+ export interface LogRecord {
217
+ seq: number;
218
+ runId: string;
219
+ at: number;
220
+ level: string;
221
+ type: string;
222
+ waveId?: string;
223
+ agentId?: string;
224
+ data?: unknown;
225
+ /** Explicit data states so a missing body never reads as success. */
226
+ state: "included" | "redacted" | "truncated" | "omitted";
227
+ omitted?: string;
228
+ /** Stable failure code for error records. */
229
+ code?: string;
230
+ /** Safe one-line summary for error records. */
231
+ summary?: string;
232
+ }
233
+
234
+ export interface LogsPage {
235
+ snapshotVersion: number;
236
+ readOnly: true;
237
+ runId: string;
238
+ limit: number;
239
+ truncated: boolean;
240
+ nextCursor: string | null;
241
+ highWaterMark: number;
242
+ /** True when the cursor is past everything persisted. */
243
+ atEnd: boolean;
244
+ records: LogRecord[];
245
+ /** Non-fatal projection problems (undecodable payloads, dropped bytes). */
246
+ projectionErrors: string[];
247
+ }
248
+
249
+ export interface ReadLogsOptions {
250
+ after?: string;
251
+ limit?: number;
252
+ agent?: string;
253
+ step?: string;
254
+ level?: string;
255
+ /** Only error/failure events (stable code + summary). */
256
+ errorsOnly?: boolean;
257
+ }
258
+
259
+ const SUPPORTED_SCHEMA_VERSION = SCHEMA_VERSION;
260
+
261
+ interface DbRow {
262
+ [key: string]: unknown;
263
+ }
264
+
265
+ interface CursorShape {
266
+ v: 1;
267
+ k: "runs" | "steps" | "logs";
268
+ id?: string;
269
+ createdAt?: number;
270
+ seq?: number;
271
+ }
272
+
273
+ /**
274
+ * Encode a resumable cursor. Human-readable mode prints it too, so machines can
275
+ * always resume from the last delivered record.
276
+ */
277
+ export function encodeCursor(cursor: Omit<CursorShape, "v">): string {
278
+ return Buffer.from(JSON.stringify({ v: 1, ...cursor })).toString("base64url");
279
+ }
280
+
281
+ export function decodeCursor(
282
+ value: string | undefined,
283
+ kind: CursorShape["k"],
284
+ ): CursorShape | undefined {
285
+ if (value === undefined || value.length === 0) return undefined;
286
+ let parsed: unknown;
287
+ try {
288
+ parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
289
+ } catch {
290
+ throw new AgentFlowError("validation", `invalid ${kind} cursor`, {
291
+ cursor: value,
292
+ });
293
+ }
294
+ if (
295
+ !parsed ||
296
+ typeof parsed !== "object" ||
297
+ (parsed as CursorShape).v !== 1 ||
298
+ (parsed as CursorShape).k !== kind
299
+ ) {
300
+ throw new AgentFlowError("validation", `invalid ${kind} cursor`, {
301
+ cursor: value,
302
+ });
303
+ }
304
+ const cursor = parsed as CursorShape;
305
+ if (kind === "logs") {
306
+ if (typeof cursor.seq !== "number" || !Number.isSafeInteger(cursor.seq)) {
307
+ throw new AgentFlowError("validation", `invalid ${kind} cursor`, {
308
+ cursor: value,
309
+ });
310
+ }
311
+ } else if (
312
+ typeof cursor.id !== "string" ||
313
+ typeof cursor.createdAt !== "number" ||
314
+ !Number.isSafeInteger(cursor.createdAt) ||
315
+ cursor.createdAt < 0
316
+ ) {
317
+ throw new AgentFlowError("validation", `invalid ${kind} cursor`, {
318
+ cursor: value,
319
+ });
320
+ }
321
+ return cursor;
322
+ }
323
+
324
+ function boundedLimit(value: number | undefined): number {
325
+ if (value === undefined) return INSPECTION_DEFAULT_LIMIT;
326
+ if (!Number.isSafeInteger(value) || value < 1) {
327
+ throw new AgentFlowError("validation", "limit must be a positive integer");
328
+ }
329
+ return Math.min(value, INSPECTION_MAX_LIMIT);
330
+ }
331
+
332
+ /**
333
+ * Structural redaction for persisted payloads: obvious credential keys are
334
+ * replaced, strings are capped and deep/oversized values become explicit
335
+ * truncation markers instead of unbounded dumps.
336
+ */
337
+ export function redactValue(
338
+ value: unknown,
339
+ maxBytes = INSPECTION_VALUE_MAX_BYTES,
340
+ ): { value: unknown; state: LogRecord["state"]; omitted?: string } {
341
+ let state: LogRecord["state"] = "included";
342
+ const seen = new WeakSet<object>();
343
+ const walk = (input: unknown, depth: number): unknown => {
344
+ if (input === null || input === undefined) return input;
345
+ const kind = typeof input;
346
+ if (kind === "string") {
347
+ const text = input as string;
348
+ if (Buffer.byteLength(text) > maxBytes) {
349
+ state = state === "redacted" ? state : "truncated";
350
+ const cut = Buffer.from(text).subarray(0, maxBytes).toString("utf8");
351
+ return `${cut}…[truncated ${Buffer.byteLength(text) - maxBytes} bytes]`;
352
+ }
353
+ return text;
354
+ }
355
+ if (kind === "number" || kind === "boolean") return input;
356
+ if (kind !== "object") return String(input);
357
+ if (depth > 6) {
358
+ state = "truncated";
359
+ return "[truncated: depth]";
360
+ }
361
+ const object = input as object;
362
+ if (seen.has(object)) {
363
+ state = "truncated";
364
+ return "[truncated: cycle]";
365
+ }
366
+ seen.add(object);
367
+ try {
368
+ if (Array.isArray(object)) {
369
+ if (object.length > 50) {
370
+ state = "truncated";
371
+ return [
372
+ ...object.slice(0, 50).map((entry) => walk(entry, depth + 1)),
373
+ `[truncated ${object.length - 50} elements]`,
374
+ ];
375
+ }
376
+ return object.map((entry) => walk(entry, depth + 1));
377
+ }
378
+ const result: Record<string, unknown> = {};
379
+ for (const [key, entry] of Object.entries(object)) {
380
+ if (SECRET_KEY.test(key) || SECRET_EXACT.test(key)) {
381
+ state = state === "truncated" ? state : "redacted";
382
+ result[key] = REDACTED;
383
+ continue;
384
+ }
385
+ result[key] = walk(entry, depth + 1);
386
+ }
387
+ return result;
388
+ } finally {
389
+ seen.delete(object);
390
+ }
391
+ };
392
+ const projected = walk(value, 0);
393
+ return { value: projected, state };
394
+ }
395
+
396
+ function byteLength(value: unknown): number {
397
+ return Buffer.byteLength(JSON.stringify(value) ?? "");
398
+ }
399
+
400
+ function parseJson(value: unknown): unknown {
401
+ if (typeof value !== "string" || value.length === 0) return undefined;
402
+ try {
403
+ return JSON.parse(value);
404
+ } catch {
405
+ return undefined;
406
+ }
407
+ }
408
+
409
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
410
+ return value !== null && typeof value === "object" && !Array.isArray(value);
411
+ }
412
+
413
+ function emptyCounts(keys: readonly string[]): Record<string, number> {
414
+ const result: Record<string, number> = {};
415
+ for (const key of keys) result[key] = 0;
416
+ return result;
417
+ }
418
+
419
+ /**
420
+ * Canonical project identity for display. The persisted `project_dir` is
421
+ * normalized the same way `canonicalProjectId` normalizes it, so a legacy row
422
+ * that stored `/work/app/../app` reads back as `/work/app`; when the directory
423
+ * cannot be normalized the persisted value is reported unchanged. Only stored
424
+ * values are used, so nothing is invented for a run that never recorded a
425
+ * project.
426
+ */
427
+ function projectIdentity(
428
+ projectId: string | null,
429
+ projectDir: string | null,
430
+ ): InspectionProject {
431
+ let dir: string | undefined;
432
+ if (projectDir !== null) {
433
+ try {
434
+ dir = canonicalProjectId(projectDir);
435
+ } catch {
436
+ dir = projectDir;
437
+ }
438
+ }
439
+ const id =
440
+ projectId !== null
441
+ ? projectId
442
+ : dir === undefined
443
+ ? undefined
444
+ : canonicalProjectId(dir);
445
+ return {
446
+ ...(id === undefined ? {} : { id }),
447
+ ...(dir === undefined ? {} : { dir }),
448
+ };
449
+ }
450
+
451
+ function statusCounts(
452
+ rows: readonly { status: string }[],
453
+ keys: readonly string[],
454
+ ): StatusCounts & { byStatus: Record<string, number> } {
455
+ const byStatus = emptyCounts(keys);
456
+ for (const row of rows) {
457
+ byStatus[row.status] = (byStatus[row.status] ?? 0) + 1;
458
+ }
459
+ let completed = 0;
460
+ for (const status of STEP_TERMINAL_STATUSES) {
461
+ completed += byStatus[status] ?? 0;
462
+ }
463
+ return {
464
+ total: rows.length,
465
+ byStatus,
466
+ completed,
467
+ current: (byStatus.failed ?? 0) + (byStatus.blocked ?? 0),
468
+ breakdown: {
469
+ succeeded: byStatus.succeeded ?? 0,
470
+ failed: byStatus.failed ?? 0,
471
+ blocked: byStatus.blocked ?? 0,
472
+ },
473
+ };
474
+ }
475
+
476
+ /** One read-only connection; close it when the read is complete. */
477
+ export class InspectionReader {
478
+ private readonly db: Database;
479
+ private readonly path: string;
480
+ readonly readOnly = true;
481
+
482
+ constructor(path: string) {
483
+ this.path = path;
484
+ let info;
485
+ try {
486
+ info = statSync(path);
487
+ } catch {
488
+ throw new AgentFlowError(
489
+ "not_found",
490
+ `no AgentFlow state database at ${path}`,
491
+ { path },
492
+ );
493
+ }
494
+ if (!info.isFile()) {
495
+ throw new AgentFlowError(
496
+ "not_found",
497
+ `AgentFlow state path is not a file: ${path}`,
498
+ { path },
499
+ );
500
+ }
501
+ try {
502
+ this.db = new Database(path, { readonly: true });
503
+ } catch (error) {
504
+ throw new AgentFlowError(
505
+ "internal",
506
+ `cannot open the state database read-only: ${error instanceof Error ? error.message : String(error)}`,
507
+ { path },
508
+ );
509
+ }
510
+ // Owner-only path: a state database readable by anyone else is refused so
511
+ // inspection never becomes a way around the private store.
512
+ const mode = info.mode & 0o777;
513
+ if (typeof process.getuid === "function") {
514
+ if (
515
+ (info.uid !== process.getuid() && info.uid !== 0) ||
516
+ (mode & 0o077) !== 0
517
+ ) {
518
+ this.db.close();
519
+ throw new AgentFlowError(
520
+ "validation",
521
+ `refusing to inspect ${basename(path)}: it is not an owner-only state database`,
522
+ { path, mode: mode.toString(8) },
523
+ );
524
+ }
525
+ }
526
+ try {
527
+ const row = this.db
528
+ .query<{ user_version: number }, SQLQueryBindings[]>(
529
+ "PRAGMA user_version",
530
+ )
531
+ .get();
532
+ const version = row?.user_version ?? 0;
533
+ if (version > SUPPORTED_SCHEMA_VERSION) {
534
+ throw new AgentFlowError(
535
+ "conflict",
536
+ `state database schema version ${version} is newer than the supported version ${SUPPORTED_SCHEMA_VERSION}`,
537
+ {
538
+ stateSchemaVersion: version,
539
+ supportedSchemaVersion: SUPPORTED_SCHEMA_VERSION,
540
+ },
541
+ );
542
+ }
543
+ } catch (error) {
544
+ this.db.close();
545
+ if (error instanceof AgentFlowError) throw error;
546
+ throw new AgentFlowError(
547
+ "internal",
548
+ `cannot read the state database: ${error instanceof Error ? error.message : String(error)}`,
549
+ { path },
550
+ );
551
+ }
552
+ }
553
+
554
+ close(): void {
555
+ this.db.close();
556
+ }
557
+
558
+ get databasePath(): string {
559
+ return this.path;
560
+ }
561
+
562
+ /**
563
+ * True when an optional table exists. Additive schema steps and older
564
+ * projections may omit a table; a read of it then reports nothing instead of
565
+ * failing the whole inspection.
566
+ */
567
+ private hasTable(table: string): boolean {
568
+ return (
569
+ this.one(
570
+ "SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?",
571
+ table,
572
+ ) !== undefined
573
+ );
574
+ }
575
+
576
+ private all<T extends DbRow>(
577
+ sql: string,
578
+ ...params: SQLQueryBindings[]
579
+ ): T[] {
580
+ return this.db.query<T, SQLQueryBindings[]>(sql).all(...params);
581
+ }
582
+
583
+ private one<T extends DbRow>(
584
+ sql: string,
585
+ ...params: SQLQueryBindings[]
586
+ ): T | undefined {
587
+ return (
588
+ (this.db.query<T, SQLQueryBindings[]>(sql).get(...params) as T | null) ??
589
+ undefined
590
+ );
591
+ }
592
+
593
+ /** One consistent snapshot: lists and headers come from the same read txn. */
594
+ private consistent<T>(fn: () => T): T {
595
+ this.db.exec("BEGIN");
596
+ try {
597
+ return fn();
598
+ } finally {
599
+ this.db.exec("COMMIT");
600
+ }
601
+ }
602
+
603
+ // ------------------------------------------------------------- resolution
604
+
605
+ /** Resolve a run id — or, failing that, a name — to its durable id. */
606
+ resolveRun(
607
+ selector: string,
608
+ project?: string,
609
+ ): { id: string; name: string | null } {
610
+ if (typeof selector !== "string" || selector.trim() === "") {
611
+ throw new AgentFlowError("validation", "a run id or name is required");
612
+ }
613
+ const projectId =
614
+ project === undefined ? undefined : canonicalProjectId(project);
615
+ const byId =
616
+ projectId === undefined
617
+ ? this.one<{ id: string; name: string | null }>(
618
+ "SELECT id, name FROM runs WHERE id = ?",
619
+ selector,
620
+ )
621
+ : this.one<{ id: string; name: string | null }>(
622
+ "SELECT id, name FROM runs WHERE id = ? AND (project_id = ? OR project_dir = ?)",
623
+ selector,
624
+ projectId,
625
+ projectId,
626
+ );
627
+ if (byId !== undefined) return byId;
628
+ const byName =
629
+ projectId === undefined
630
+ ? this.one<{ id: string; name: string | null }>(
631
+ "SELECT id, name FROM runs WHERE name = ? ORDER BY created_at DESC, id DESC LIMIT 1",
632
+ selector,
633
+ )
634
+ : this.one<{ id: string; name: string | null }>(
635
+ "SELECT id, name FROM runs WHERE name = ? AND (project_id = ? OR project_dir = ?) ORDER BY created_at DESC, id DESC LIMIT 1",
636
+ selector,
637
+ projectId,
638
+ projectId,
639
+ );
640
+ if (byName !== undefined) return byName;
641
+ throw new AgentFlowError(
642
+ "not_found",
643
+ `no run matches ${JSON.stringify(selector)}`,
644
+ {
645
+ selector,
646
+ ...(projectId === undefined ? {} : { project: projectId }),
647
+ },
648
+ );
649
+ }
650
+
651
+ /** Run summary plus optional step drill-down; never requires a daemon. */
652
+ inspect(options: InspectOptions = {}): InspectionPage {
653
+ const limit = boundedLimit(options.limit);
654
+ const cursor = decodeCursor(
655
+ options.after,
656
+ options.selector ? "steps" : "runs",
657
+ );
658
+ return this.consistent(() =>
659
+ options.selector === undefined || options.selector === ""
660
+ ? this.listRunsPage(options, limit, cursor)
661
+ : this.runPage(options, limit, cursor),
662
+ );
663
+ }
664
+
665
+ private listRunsPage(
666
+ options: InspectOptions,
667
+ limit: number,
668
+ cursor: CursorShape | undefined,
669
+ ): InspectionPage {
670
+ const at = Date.now();
671
+ const params: SQLQueryBindings[] = [];
672
+ let where = "1 = 1";
673
+ if (options.projectOnly !== undefined) {
674
+ const projectId = canonicalProjectId(options.projectOnly);
675
+ where += " AND (project_id = ? OR project_dir = ?)";
676
+ params.push(projectId, projectId);
677
+ }
678
+ if (cursor?.id !== undefined && cursor.createdAt !== undefined) {
679
+ where += " AND (created_at < ? OR (created_at = ? AND id < ?))";
680
+ params.push(cursor.createdAt, cursor.createdAt, cursor.id);
681
+ }
682
+ const rows = this.all<{
683
+ id: string;
684
+ name: string | null;
685
+ status: RunStatus;
686
+ project_id: string | null;
687
+ project_dir: string | null;
688
+ strategy: string;
689
+ created_at: number;
690
+ updated_at: number;
691
+ }>(
692
+ `SELECT id, name, status, project_id, project_dir, strategy, created_at, updated_at
693
+ FROM runs WHERE ${where} ORDER BY created_at DESC, id DESC LIMIT ?`,
694
+ ...params,
695
+ limit + 1,
696
+ );
697
+ const page = this.boundRecords(
698
+ rows.map((row) => ({
699
+ id: row.id,
700
+ ...(row.name === null ? {} : { name: row.name }),
701
+ status: row.status,
702
+ project: projectIdentity(row.project_id, row.project_dir),
703
+ strategy: row.strategy,
704
+ createdAt: row.created_at,
705
+ updatedAt: row.updated_at,
706
+ })),
707
+ limit,
708
+ );
709
+ const last = page.records[page.records.length - 1];
710
+ const hasMore = page.records.length < limit ? false : rows.length > limit;
711
+ return {
712
+ snapshotVersion: INSPECTION_SNAPSHOT_VERSION,
713
+ readOnly: true,
714
+ mode: "runs",
715
+ at,
716
+ limit,
717
+ truncated: page.truncated,
718
+ nextCursor:
719
+ hasMore && last !== undefined
720
+ ? encodeCursor({ k: "runs", id: last.id, createdAt: last.createdAt })
721
+ : null,
722
+ highWaterMark: rows[0]?.created_at ?? cursor?.createdAt ?? 0,
723
+ runs: page.records,
724
+ };
725
+ }
726
+
727
+ private runPage(
728
+ options: InspectOptions,
729
+ limit: number,
730
+ cursor: CursorShape | undefined,
731
+ ): InspectionPage {
732
+ const at = Date.now();
733
+ const run = this.resolveRun(options.selector as string, options.project);
734
+ const runId = run.id;
735
+
736
+ const runRow = this.one<{
737
+ id: string;
738
+ name: string | null;
739
+ project_id: string | null;
740
+ project_dir: string | null;
741
+ strategy: string;
742
+ status: RunStatus;
743
+ error: string | null;
744
+ stopped: number;
745
+ sealed: number;
746
+ adapter: string;
747
+ max_concurrent: number | null;
748
+ predecessor_id: string | null;
749
+ successor_id: string | null;
750
+ plan_digest: string | null;
751
+ created_at: number;
752
+ updated_at: number;
753
+ }>(
754
+ `SELECT id, name, project_id, project_dir, strategy, status, error, stopped, sealed,
755
+ adapter, max_concurrent, predecessor_id, successor_id, plan_digest,
756
+ created_at, updated_at
757
+ FROM runs WHERE id = ?`,
758
+ runId,
759
+ );
760
+ if (runRow === undefined) {
761
+ throw new AgentFlowError("not_found", `no run ${runId}`);
762
+ }
763
+
764
+ const planMeta = this.hasTable("plan_meta")
765
+ ? this.one<{ revision: number; meta_json: string }>(
766
+ "SELECT revision, meta_json FROM plan_meta WHERE run_id = ? ORDER BY revision DESC LIMIT 1",
767
+ runId,
768
+ )
769
+ : undefined;
770
+ const plan = parseJson(planMeta?.meta_json) as RunPlanMetadata | undefined;
771
+ const planSteps = new Map<string, PlanStepDescriptor>(
772
+ (isPlainObject(plan) && Array.isArray(plan.steps) ? plan.steps : []).map(
773
+ (step: PlanStepDescriptor) => [step.id, step] as const,
774
+ ),
775
+ );
776
+ const planPhases = new Map<string, PlanPhaseDescriptor>(
777
+ (isPlainObject(plan) && Array.isArray(plan.phases)
778
+ ? plan.phases
779
+ : []
780
+ ).map((phase: PlanPhaseDescriptor) => [phase.id, phase] as const),
781
+ );
782
+
783
+ const waves = this.all<{
784
+ id: string;
785
+ idx: number;
786
+ status: WaveStatus;
787
+ phase_id: string | null;
788
+ started_at: number | null;
789
+ finished_at: number | null;
790
+ }>(
791
+ "SELECT id, idx, status, phase_id, started_at, finished_at FROM waves WHERE run_id = ? ORDER BY idx ASC",
792
+ runId,
793
+ );
794
+
795
+ const agentRows = this.all<{
796
+ id: string;
797
+ wave_id: string;
798
+ spec_json: string;
799
+ profile_id: string;
800
+ profile_json: string;
801
+ adapter: string;
802
+ status: string;
803
+ session_id: string | null;
804
+ turns: number;
805
+ error: string | null;
806
+ result_json: string | null;
807
+ created_at: number;
808
+ started_at: number | null;
809
+ finished_at: number | null;
810
+ step_key: string | null;
811
+ step_kind: string | null;
812
+ attempts: number | null;
813
+ blocker: string | null;
814
+ reused_from: string | null;
815
+ }>(
816
+ `SELECT id, wave_id, spec_json, profile_id, profile_json, adapter, status, session_id,
817
+ turns, error, result_json, created_at, started_at, finished_at, step_key,
818
+ step_kind, attempts, blocker, reused_from
819
+ FROM agents WHERE run_id = ? ORDER BY wave_id ASC, created_at ASC, id ASC`,
820
+ runId,
821
+ );
822
+
823
+ const turnCounts = emptyCounts([
824
+ "admitted",
825
+ "running",
826
+ "succeeded",
827
+ "failed",
828
+ "interrupted",
829
+ "rate_limited",
830
+ "cancelled",
831
+ ]);
832
+ let turnTotal = 0;
833
+ let activeTurns = 0;
834
+ for (const row of this.all<{ state: string; count: number }>(
835
+ "SELECT state, COUNT(*) AS count FROM turns WHERE run_id = ? GROUP BY state",
836
+ runId,
837
+ )) {
838
+ turnCounts[row.state] = (turnCounts[row.state] ?? 0) + row.count;
839
+ turnTotal += row.count;
840
+ if (row.state === "admitted" || row.state === "running")
841
+ activeTurns += row.count;
842
+ }
843
+
844
+ // Last-resort per-step reason from the step's own durable error/failure
845
+ // events; the newest such event for an agent wins.
846
+ const stepErrorReason = new Map<string, string>();
847
+ for (const row of this.all<{ agent_id: string; data_json: string | null }>(
848
+ `SELECT agent_id, data_json FROM events
849
+ WHERE run_id = ? AND agent_id IS NOT NULL AND ${ERROR_EVENT_FILTER}
850
+ ORDER BY seq ASC`,
851
+ runId,
852
+ )) {
853
+ const data = parseJson(row.data_json);
854
+ if (!isPlainObject(data)) continue;
855
+ const text =
856
+ typeof data.message === "string"
857
+ ? data.message
858
+ : typeof data.error === "string"
859
+ ? data.error
860
+ : typeof data.reason === "string"
861
+ ? data.reason
862
+ : undefined;
863
+ if (text !== undefined) stepErrorReason.set(row.agent_id, text);
864
+ }
865
+
866
+ const steps: StepSummary[] = agentRows.map((row) => {
867
+ const waveIndex = waves.findIndex((wave) => wave.id === row.wave_id);
868
+ const wave = waves[waveIndex];
869
+ const spec = parseJson(row.spec_json);
870
+ const profile = parseJson(row.profile_json);
871
+ const result = parseJson(row.result_json);
872
+ const model =
873
+ isPlainObject(spec) && typeof spec.model === "string"
874
+ ? spec.model
875
+ : isPlainObject(profile) && typeof profile.model === "string"
876
+ ? profile.model
877
+ : planSteps.get(row.step_key ?? row.id)?.model;
878
+ const quotaGroup =
879
+ isPlainObject(profile) && typeof profile.quotaGroup === "string"
880
+ ? profile.quotaGroup
881
+ : "default";
882
+ // The durable `agents` row is authoritative for why a step stopped: a
883
+ // blocker, then the persisted result reason (how the engine records a
884
+ // failure), then the row error. A step's own persisted error/failure
885
+ // event is only consulted when the row itself carries no failure text.
886
+ const reason =
887
+ row.blocker ??
888
+ (isPlainObject(result) && typeof result.reason === "string"
889
+ ? result.reason
890
+ : undefined) ??
891
+ row.error ??
892
+ stepErrorReason.get(row.id);
893
+ const kind: StepKind =
894
+ row.step_kind === "script" || row.step_kind === "gate"
895
+ ? row.step_kind
896
+ : "agent";
897
+ return {
898
+ id: row.step_key ?? row.id,
899
+ agentId: row.id,
900
+ waveId: row.wave_id,
901
+ phaseId:
902
+ wave?.phase_id ?? planSteps.get(row.id)?.phaseId ?? row.wave_id,
903
+ kind,
904
+ status: row.status,
905
+ profileId: row.profile_id,
906
+ adapter: row.adapter,
907
+ ...(model === undefined ? {} : { model }),
908
+ quotaGroup,
909
+ attempts: row.attempts ?? 0,
910
+ reason,
911
+ ...(row.session_id === null ? {} : { session: row.session_id }),
912
+ turns: row.turns,
913
+ ...(row.reused_from === null ? {} : { reusedFrom: row.reused_from }),
914
+ ...(row.started_at === null ? {} : { startedAt: row.started_at }),
915
+ ...(row.finished_at === null ? {} : { finishedAt: row.finished_at }),
916
+ // One agent row is one persisted attempt. `attempts` is the retry count
917
+ // AgentFlow stored, so it is never replaced by an invented id.
918
+ counts: (() => {
919
+ const counts = statusCounts(
920
+ [{ status: row.status }],
921
+ voiceKeys(kind),
922
+ );
923
+ return {
924
+ total: counts.total,
925
+ byStatus: counts.byStatus,
926
+ completed: counts.completed,
927
+ current: counts.current,
928
+ breakdown: counts.breakdown,
929
+ };
930
+ })(),
931
+ };
932
+ });
933
+
934
+ if (this.hasTable("plan_steps")) {
935
+ const handled = this.all<{
936
+ step_id: string;
937
+ wave_id: string;
938
+ kind: "script" | "gate";
939
+ handler: string;
940
+ handler_version: string;
941
+ status: string;
942
+ error: string | null;
943
+ reason: string | null;
944
+ attempt_id: string;
945
+ started_at: number;
946
+ finished_at: number | null;
947
+ }>(
948
+ "SELECT step_id,wave_id,kind,handler,handler_version,status,error,reason,attempt_id,started_at,finished_at FROM plan_steps WHERE run_id = ?",
949
+ runId,
950
+ );
951
+ for (const step of handled) {
952
+ const wave = waves.find((entry) => entry.id === step.wave_id);
953
+ steps.push({
954
+ id: step.step_id,
955
+ agentId: `${step.wave_id}/${step.step_id}`,
956
+ waveId: step.wave_id,
957
+ phaseId:
958
+ wave?.phase_id ?? planPhases.get(step.wave_id)?.id ?? step.wave_id,
959
+ kind: step.kind,
960
+ status: step.status,
961
+ profileId: `${step.handler}@${step.handler_version}`,
962
+ adapter: "local",
963
+ quotaGroup: "",
964
+ turns: 0,
965
+ attempts: 1,
966
+ attempt: step.attempt_id,
967
+ reason: step.error ?? step.reason ?? undefined,
968
+ startedAt: step.started_at,
969
+ finishedAt: step.finished_at ?? undefined,
970
+ counts: statusCounts([{ status: step.status }], voiceKeys(step.kind)),
971
+ });
972
+ }
973
+ }
974
+
975
+ const filteredSteps = steps.filter((step) => {
976
+ if (options.failed === true && !isProblemStatus(step.status))
977
+ return false;
978
+ if (
979
+ options.agent !== undefined &&
980
+ step.agentId !== options.agent &&
981
+ step.id !== options.agent
982
+ ) {
983
+ return false;
984
+ }
985
+ if (
986
+ options.phase !== undefined &&
987
+ step.phaseId !== options.phase &&
988
+ step.waveId !== options.phase
989
+ ) {
990
+ return false;
991
+ }
992
+ if (options.round !== undefined) {
993
+ const phase = planPhases.get(step.waveId);
994
+ if (
995
+ phase === undefined ||
996
+ phase.waveIds.indexOf(step.waveId) !== options.round
997
+ )
998
+ return false;
999
+ }
1000
+ return true;
1001
+ });
1002
+ filteredSteps.sort((a, b) => {
1003
+ const left = waves.find((wave) => wave.id === a.waveId)?.idx ?? 0;
1004
+ const right = waves.find((wave) => wave.id === b.waveId)?.idx ?? 0;
1005
+ if (left !== right) return left - right;
1006
+ return a.agentId.localeCompare(b.agentId);
1007
+ });
1008
+
1009
+ const phases: PhaseSummary[] = waves
1010
+ .filter(
1011
+ (wave) =>
1012
+ options.phase === undefined ||
1013
+ wave.id === options.phase ||
1014
+ wave.phase_id === options.phase,
1015
+ )
1016
+ .map((wave) => {
1017
+ const phaseId = wave.phase_id ?? planPhases.get(wave.id)?.id ?? wave.id;
1018
+ const members = steps.filter((step) => step.waveId === wave.id);
1019
+ const counts = statusCounts(members, [
1020
+ "pending",
1021
+ "running",
1022
+ "succeeded",
1023
+ "failed",
1024
+ "interrupted",
1025
+ "cancelled",
1026
+ "paused",
1027
+ "blocked",
1028
+ "skipped",
1029
+ ]);
1030
+ return {
1031
+ waveId: wave.id,
1032
+ index: wave.idx,
1033
+ status: wave.status,
1034
+ phaseId,
1035
+ ...(wave.started_at === null ? {} : { startedAt: wave.started_at }),
1036
+ ...(wave.finished_at === null
1037
+ ? {}
1038
+ : { finishedAt: wave.finished_at }),
1039
+ counts: {
1040
+ total: counts.total,
1041
+ byStatus: counts.byStatus,
1042
+ completed: counts.completed,
1043
+ current: counts.current,
1044
+ breakdown: counts.breakdown,
1045
+ },
1046
+ };
1047
+ });
1048
+
1049
+ const lastEvent = this.one<{
1050
+ seq: number;
1051
+ daemon: number | null;
1052
+ at: number;
1053
+ }>(
1054
+ "SELECT seq, daemon, at FROM events WHERE run_id = ? ORDER BY seq DESC LIMIT 1",
1055
+ runId,
1056
+ );
1057
+ const eventCount =
1058
+ this.one<{ count: number }>(
1059
+ "SELECT COUNT(*) AS count FROM events WHERE run_id = ?",
1060
+ runId,
1061
+ )?.count ?? 0;
1062
+
1063
+ const lifecycleReason =
1064
+ runRow.error ??
1065
+ (runRow.stopped === 1 ? "stopped by operator" : undefined);
1066
+ const summary: InspectionSummary = {
1067
+ status: runRow.status,
1068
+ run: {
1069
+ status: runRow.status,
1070
+ decided:
1071
+ runRow.status === "completed" ||
1072
+ runRow.status === "failed" ||
1073
+ runRow.status === "cancelled",
1074
+ },
1075
+ waves: (() => {
1076
+ const counts = statusCounts(waves, [
1077
+ "pending",
1078
+ "running",
1079
+ "paused",
1080
+ "completed",
1081
+ "failed",
1082
+ "blocked",
1083
+ "cancelled",
1084
+ ]);
1085
+ return counts;
1086
+ })(),
1087
+ agents: (() => {
1088
+ const counts = statusCounts(agentRows, [
1089
+ "pending",
1090
+ "running",
1091
+ "paused",
1092
+ "succeeded",
1093
+ "failed",
1094
+ "interrupted",
1095
+ "cancelled",
1096
+ ]);
1097
+ return counts;
1098
+ })(),
1099
+ steps: (() => {
1100
+ const counts = statusCounts(steps, [
1101
+ "pending",
1102
+ "running",
1103
+ "paused",
1104
+ "succeeded",
1105
+ "failed",
1106
+ "interrupted",
1107
+ "cancelled",
1108
+ "blocked",
1109
+ "skipped",
1110
+ ]);
1111
+ return {
1112
+ total: counts.total,
1113
+ byStatus: counts.byStatus,
1114
+ completed: counts.completed,
1115
+ current: counts.current,
1116
+ breakdown: counts.breakdown,
1117
+ };
1118
+ })(),
1119
+ byWaveStatus: statusCounts(waves, []).byStatus,
1120
+ byAgentStatus: statusCounts(agentRows, []).byStatus,
1121
+ events: eventCount,
1122
+ ...(lastEvent === undefined ? {} : { lastEventAt: lastEvent.at }),
1123
+ recovery: this.recoveryItems(runId),
1124
+ operations: this.operationReceipts(runId),
1125
+ };
1126
+
1127
+ const startAfter = cursor;
1128
+ const stepsAfter =
1129
+ startAfter?.id === undefined || startAfter.createdAt === undefined
1130
+ ? filteredSteps
1131
+ : filteredSteps.filter((step) => {
1132
+ const waveIndex =
1133
+ waves.find((wave) => wave.id === step.waveId)?.idx ?? 0;
1134
+ const key = startAfter.createdAt as number;
1135
+ if (waveIndex !== key) return waveIndex > key;
1136
+ return step.agentId.localeCompare(startAfter.id as string) > 0;
1137
+ });
1138
+ const stepPage = this.boundRecords(stepsAfter, limit);
1139
+ const lastStep = stepPage.records[stepPage.records.length - 1];
1140
+ const moreSteps = stepPage.records.length < stepsAfter.length;
1141
+
1142
+ const artifacts = this.all<{
1143
+ id: string;
1144
+ declaration_json: string;
1145
+ state: string;
1146
+ }>(
1147
+ "SELECT id, declaration_json, state FROM artifacts WHERE run_id = ? ORDER BY id ASC",
1148
+ runId,
1149
+ ).map((row) => {
1150
+ const declaration = parseJson(row.declaration_json);
1151
+ return {
1152
+ id: row.id,
1153
+ type:
1154
+ isPlainObject(declaration) && typeof declaration.type === "string"
1155
+ ? declaration.type
1156
+ : "text",
1157
+ state: row.state,
1158
+ required: isPlainObject(declaration) && declaration.required === true,
1159
+ };
1160
+ });
1161
+
1162
+ const header: RunHeader = {
1163
+ id: runRow.id,
1164
+ ...(runRow.name === null ? {} : { name: runRow.name }),
1165
+ project: projectIdentity(runRow.project_id, runRow.project_dir),
1166
+ strategy: runRow.strategy,
1167
+ ...(runRow.plan_digest === null
1168
+ ? {}
1169
+ : { planDigest: runRow.plan_digest }),
1170
+ ...(planMeta === undefined ? {} : { revision: planMeta.revision }),
1171
+ ...(runRow.predecessor_id === null
1172
+ ? {}
1173
+ : { predecessorId: runRow.predecessor_id }),
1174
+ ...(runRow.successor_id === null
1175
+ ? {}
1176
+ : { successorId: runRow.successor_id }),
1177
+ ...(lifecycleReason === undefined ? {} : { lifecycleReason }),
1178
+ ...(lastEvent?.daemon === null || lastEvent === undefined
1179
+ ? {}
1180
+ : { activeDaemonGeneration: lastEvent.daemon }),
1181
+ adapter: runRow.adapter,
1182
+ sealed: runRow.sealed === 1,
1183
+ stopped: runRow.stopped === 1,
1184
+ ...(runRow.max_concurrent === null
1185
+ ? {}
1186
+ : { maxConcurrent: runRow.max_concurrent }),
1187
+ activeTurns,
1188
+ turnCounts: { ...turnCounts, total: turnTotal },
1189
+ createdAt: runRow.created_at,
1190
+ updatedAt: runRow.updated_at,
1191
+ elapsedMs: Math.max(0, runRow.updated_at - runRow.created_at),
1192
+ status: runRow.status,
1193
+ };
1194
+
1195
+ const selectedAgent =
1196
+ options.agent === undefined
1197
+ ? undefined
1198
+ : agentRows.find(
1199
+ (agent) =>
1200
+ agent.id === options.agent || agent.step_key === options.agent,
1201
+ );
1202
+ const history = selectedAgent?.session_id
1203
+ ? this.providerHistory(
1204
+ selectedAgent.adapter,
1205
+ selectedAgent.session_id,
1206
+ limit,
1207
+ )
1208
+ : undefined;
1209
+
1210
+ return {
1211
+ snapshotVersion: INSPECTION_SNAPSHOT_VERSION,
1212
+ readOnly: true,
1213
+ mode: "snapshot",
1214
+ at,
1215
+ limit,
1216
+ truncated: stepPage.truncated,
1217
+ nextCursor:
1218
+ moreSteps && lastStep !== undefined
1219
+ ? encodeCursor({
1220
+ k: "steps",
1221
+ id: lastStep.agentId,
1222
+ createdAt:
1223
+ waves.find((wave) => wave.id === lastStep.waveId)?.idx ?? 0,
1224
+ })
1225
+ : null,
1226
+ highWaterMark: lastEvent?.seq ?? 0,
1227
+ summary,
1228
+ header,
1229
+ phases,
1230
+ steps: stepPage.records,
1231
+ artifacts,
1232
+ ...(history === undefined ? {} : { history }),
1233
+ ...(this.hasTable("artifact_versions")
1234
+ ? { artifactVersions: listArtifactVersions(this.db, runId, { limit }) }
1235
+ : {}),
1236
+ };
1237
+ }
1238
+
1239
+ private providerHistory(
1240
+ provider: string,
1241
+ sessionId: string,
1242
+ limit: number,
1243
+ ): InspectionPage["history"] {
1244
+ if (!this.hasTable("provider_history_sessions")) return undefined;
1245
+ const session = this.one<{ status: string; captured_at: number }>(
1246
+ "SELECT status, captured_at FROM provider_history_sessions WHERE provider = ? AND provider_session_id = ?",
1247
+ provider,
1248
+ sessionId,
1249
+ );
1250
+ if (!session) return undefined;
1251
+ const rows = this.all<{ seq: number; record_json: string }>(
1252
+ "SELECT seq, record_json FROM provider_history_records WHERE provider = ? AND provider_session_id = ? ORDER BY seq DESC LIMIT ?",
1253
+ provider,
1254
+ sessionId,
1255
+ Math.min(20, limit),
1256
+ );
1257
+ return {
1258
+ provider,
1259
+ sessionId,
1260
+ status: session.status,
1261
+ capturedAt: session.captured_at,
1262
+ records: rows.reverse().map(({ seq, record_json }) => ({
1263
+ seq,
1264
+ data: redactValue(parseJson(record_json)),
1265
+ })),
1266
+ };
1267
+ }
1268
+
1269
+ private recoveryItems(runId: string): RecoveryItem[] {
1270
+ if (!this.hasTable("run_recovery")) return [];
1271
+ return this.all<{
1272
+ seq: number;
1273
+ wave_id: string | null;
1274
+ agent_id: string | null;
1275
+ attempt_id: string | null;
1276
+ daemon: number;
1277
+ action: RecoveryItem["action"];
1278
+ reason: string;
1279
+ blocker: string | null;
1280
+ at: number;
1281
+ }>(
1282
+ "SELECT seq, wave_id, agent_id, attempt_id, daemon, action, reason, blocker, at FROM run_recovery WHERE run_id = ? ORDER BY seq ASC",
1283
+ runId,
1284
+ ).map((row) => ({
1285
+ runId,
1286
+ seq: row.seq,
1287
+ ...(row.wave_id === null ? {} : { waveId: row.wave_id }),
1288
+ ...(row.agent_id === null ? {} : { agentId: row.agent_id }),
1289
+ ...(row.attempt_id === null ? {} : { attemptId: row.attempt_id }),
1290
+ daemon: row.daemon,
1291
+ action: row.action,
1292
+ reason: row.reason,
1293
+ ...(row.blocker === null ? {} : { blocker: row.blocker }),
1294
+ at: row.at,
1295
+ }));
1296
+ }
1297
+
1298
+ private operationReceipts(runId: string): OperationReceipt[] {
1299
+ if (!this.hasTable("operations")) return [];
1300
+ return this.all<{
1301
+ id: string;
1302
+ kind: string;
1303
+ actor: string;
1304
+ reason: string | null;
1305
+ old_json: string | null;
1306
+ new_json: string | null;
1307
+ at: number;
1308
+ }>(
1309
+ "SELECT id, kind, actor, reason, old_json, new_json, at FROM operations WHERE run_id = ? ORDER BY at ASC, id ASC",
1310
+ runId,
1311
+ ).map((row) => ({
1312
+ id: row.id,
1313
+ runId,
1314
+ kind: row.kind as OperationReceipt["kind"],
1315
+ actor: row.actor,
1316
+ ...(row.reason === null ? {} : { reason: row.reason }),
1317
+ at: row.at,
1318
+ ...(row.old_json === null
1319
+ ? {}
1320
+ : { oldValue: redactValue(parseJson(row.old_json)).value }),
1321
+ ...(row.new_json === null
1322
+ ? {}
1323
+ : { newValue: redactValue(parseJson(row.new_json)).value }),
1324
+ duplicate: false,
1325
+ }));
1326
+ }
1327
+
1328
+ private boundRecords<T>(
1329
+ records: T[],
1330
+ limit: number,
1331
+ ): { records: T[]; truncated: boolean } {
1332
+ const out: T[] = [];
1333
+ let bytes = 0;
1334
+ let truncated = false;
1335
+ for (const record of records) {
1336
+ if (out.length >= limit) break;
1337
+ const size = byteLength(record);
1338
+ if (out.length > 0 && bytes + size > INSPECTION_PAGE_MAX_BYTES) {
1339
+ truncated = true;
1340
+ break;
1341
+ }
1342
+ out.push(record);
1343
+ bytes += size;
1344
+ }
1345
+ return { records: out, truncated };
1346
+ }
1347
+
1348
+ // ------------------------------------------------------------------ logs
1349
+
1350
+ /**
1351
+ * Bounded, redacted diagnostic records for one run. `after` is an opaque
1352
+ * cursor wrapping the stable event `seq`, so a truncated page always resumes
1353
+ * from the last delivered record without duplicates or gaps.
1354
+ */
1355
+ readRunLogs(runRef: string, options: ReadLogsOptions = {}): LogsPage {
1356
+ const limit = boundedLimit(options.limit);
1357
+ const cursor = decodeCursor(options.after, "logs");
1358
+ // The same selector rule as a snapshot: an exact id wins, then a name.
1359
+ const run = this.resolveRun(runRef);
1360
+ const runId = run.id;
1361
+ return this.consistent(() => {
1362
+ const highWater =
1363
+ this.one<{ seq: number | null }>(
1364
+ "SELECT MAX(seq) AS seq FROM events WHERE run_id = ?",
1365
+ runId,
1366
+ )?.seq ?? 0;
1367
+ const params: SQLQueryBindings[] = [runId];
1368
+ let where = "run_id = ? AND seq > ?";
1369
+ params.push(cursor?.seq ?? 0);
1370
+ if (options.agent !== undefined) {
1371
+ where +=
1372
+ " AND (agent_id = ? OR agent_id IN (SELECT id FROM agents WHERE run_id = ? AND step_key = ?))";
1373
+ params.push(options.agent, runId, options.agent);
1374
+ }
1375
+ if (options.step !== undefined) {
1376
+ where +=
1377
+ " AND agent_id IN (SELECT id FROM agents WHERE run_id = ? AND (id = ? OR step_key = ?))";
1378
+ params.push(runId, options.step, options.step);
1379
+ }
1380
+ if (options.errorsOnly === true) where += ` AND ${ERROR_EVENT_FILTER}`;
1381
+ const rows = this.all<{
1382
+ seq: number;
1383
+ type: string;
1384
+ wave_id: string | null;
1385
+ agent_id: string | null;
1386
+ data_json: string | null;
1387
+ at: number;
1388
+ }>(
1389
+ `SELECT seq, type, wave_id, agent_id, data_json, at FROM events
1390
+ WHERE ${where} ORDER BY seq ASC LIMIT ?`,
1391
+ ...params,
1392
+ limit + 1,
1393
+ );
1394
+
1395
+ const projectionErrors: string[] = [];
1396
+ const records: LogRecord[] = [];
1397
+ let bytes = 0;
1398
+ // Rows are read in ascending `seq` and a row is either delivered or ends
1399
+ // the page, so the delivered sequence is stable, gap-free and strictly
1400
+ // increasing. A level-filtered row is skipped and never ends the page.
1401
+ let capped: number | undefined;
1402
+ for (const row of rows) {
1403
+ if (records.length >= limit) break;
1404
+ const record = this.logRecord(row, runId, projectionErrors);
1405
+ if (
1406
+ options.level !== undefined &&
1407
+ !levelMatches(record.level, options.level)
1408
+ ) {
1409
+ continue;
1410
+ }
1411
+ const size = byteLength(record);
1412
+ if (records.length > 0 && bytes + size > INSPECTION_PAGE_MAX_BYTES) {
1413
+ capped = row.seq;
1414
+ break;
1415
+ }
1416
+ records.push(record);
1417
+ bytes += size;
1418
+ }
1419
+ const delivered = records[records.length - 1];
1420
+ const nextSeq = delivered?.seq ?? cursor?.seq ?? 0;
1421
+ // `truncated` means records exist after this page, either because the
1422
+ // limit cut the read or because the byte cap stopped an inspected row.
1423
+ const more = rows.length > records.length || capped !== undefined;
1424
+ return {
1425
+ snapshotVersion: INSPECTION_SNAPSHOT_VERSION,
1426
+ readOnly: true,
1427
+ runId,
1428
+ limit,
1429
+ truncated: delivered !== undefined && capped !== undefined,
1430
+ nextCursor:
1431
+ delivered === undefined
1432
+ ? null
1433
+ : encodeCursor({ k: "logs", seq: nextSeq }),
1434
+ highWaterMark: highWater,
1435
+ atEnd: !more && nextSeq >= highWater,
1436
+ records,
1437
+ projectionErrors,
1438
+ };
1439
+ });
1440
+ }
1441
+
1442
+ private logRecord(
1443
+ row: {
1444
+ seq: number;
1445
+ type: string;
1446
+ wave_id: string | null;
1447
+ agent_id: string | null;
1448
+ data_json: string | null;
1449
+ at: number;
1450
+ },
1451
+ runId: string,
1452
+ projectionErrors: string[],
1453
+ ): LogRecord {
1454
+ const level = levelOf(row.type);
1455
+ const record: LogRecord = {
1456
+ seq: row.seq,
1457
+ runId,
1458
+ at: row.at,
1459
+ level,
1460
+ type: row.type,
1461
+ ...(row.wave_id === null ? {} : { waveId: row.wave_id }),
1462
+ ...(row.agent_id === null ? {} : { agentId: row.agent_id }),
1463
+ state: "omitted",
1464
+ };
1465
+ if (row.data_json === null) {
1466
+ record.state = "omitted";
1467
+ record.omitted = "no payload";
1468
+ return record;
1469
+ }
1470
+ const data = parseJson(row.data_json);
1471
+ if (data === undefined) {
1472
+ projectionErrors.push(`event ${row.seq}: undecodable payload`);
1473
+ record.state = "omitted";
1474
+ record.omitted = "undecodable payload";
1475
+ return record;
1476
+ }
1477
+ const redacted = redactValue(data);
1478
+ record.data = redacted.value;
1479
+ record.state = redacted.state;
1480
+ if (redacted.state === "truncated") record.omitted = "payload truncated";
1481
+ if (redacted.state === "redacted")
1482
+ record.omitted = "secret fields redacted";
1483
+ if (isErrorType(row.type)) {
1484
+ const summary = isPlainObject(data)
1485
+ ? typeof data.message === "string"
1486
+ ? data.message
1487
+ : typeof data.error === "string"
1488
+ ? data.error
1489
+ : typeof data.reason === "string"
1490
+ ? data.reason
1491
+ : undefined
1492
+ : undefined;
1493
+ const code =
1494
+ isPlainObject(data) && typeof data.code === "string"
1495
+ ? data.code
1496
+ : isPlainObject(data) && typeof data.reason === "string"
1497
+ ? data.reason
1498
+ : levelOf(row.type) === "error"
1499
+ ? row.type
1500
+ : undefined;
1501
+ if (code !== undefined) record.code = code;
1502
+ if (summary !== undefined)
1503
+ record.summary = redactValue(summary).value as string;
1504
+ }
1505
+ return record;
1506
+ }
1507
+ }
1508
+
1509
+ // Additive optional members stay declared on LogRecord itself.
1510
+
1511
+ function voiceKeys(kind: StepKind): readonly string[] {
1512
+ // Agent, script and gate steps share the persisted step-status vocabulary.
1513
+ return [
1514
+ "pending",
1515
+ "running",
1516
+ "paused",
1517
+ "succeeded",
1518
+ "failed",
1519
+ "interrupted",
1520
+ "cancelled",
1521
+ "blocked",
1522
+ "skipped",
1523
+ ];
1524
+ }
1525
+
1526
+ function isProblemStatus(status: string): boolean {
1527
+ return (
1528
+ status === "failed" || status === "blocked" || status === "interrupted"
1529
+ );
1530
+ }
1531
+
1532
+ function isErrorType(type: string): boolean {
1533
+ return (
1534
+ type.endsWith(".error") ||
1535
+ type.endsWith(".failed") ||
1536
+ type.endsWith(".failure") ||
1537
+ type === "error" ||
1538
+ type === "failed" ||
1539
+ type === "quota.exhausted"
1540
+ );
1541
+ }
1542
+
1543
+ /** Derive a level from the persisted event type only; no payload guessing. */
1544
+ export function levelOf(type: string): string {
1545
+ if (
1546
+ type === "quota.exhausted" ||
1547
+ type.endsWith(".error") ||
1548
+ type.endsWith(".failed") ||
1549
+ type.endsWith(".failure") ||
1550
+ type === "error" ||
1551
+ type === "failed"
1552
+ ) {
1553
+ return "error";
1554
+ }
1555
+ if (
1556
+ type.endsWith(".warn") ||
1557
+ type.endsWith(".warning") ||
1558
+ type.endsWith(".rate_limit") ||
1559
+ type.endsWith(".rate_limited")
1560
+ ) {
1561
+ return "warn";
1562
+ }
1563
+ if (type.endsWith(".debug") || type.endsWith(".trace")) return "debug";
1564
+ return "info";
1565
+ }
1566
+
1567
+ const LEVEL_RANK: Record<string, number> = {
1568
+ trace: 0,
1569
+ debug: 1,
1570
+ info: 2,
1571
+ warn: 3,
1572
+ error: 4,
1573
+ };
1574
+
1575
+ /** `--level error` shows errors only; `--level debug` shows everything. */
1576
+ function levelMatches(level: string, filter: string): boolean {
1577
+ const wanted = LEVEL_RANK[filter.toLowerCase()];
1578
+ if (wanted === undefined) return level === filter;
1579
+ return (LEVEL_RANK[level] ?? 2) >= wanted;
1580
+ }