@qlairoslabs/acp-client 0.7.4 → 0.8.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.
Files changed (53) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +452 -19
  3. package/package.json +6 -1
  4. package/src/agent-adapter-registry.ts +66 -0
  5. package/src/agent-conversation-continuation.ts +121 -0
  6. package/src/agent-conversation-contracts.ts +279 -0
  7. package/src/agent-conversation-errors.ts +31 -0
  8. package/src/agent-conversation-owner.ts +55 -0
  9. package/src/agent-conversation-presentation.ts +217 -0
  10. package/src/agent-conversation-queue.ts +44 -0
  11. package/src/agent-conversation.ts +41 -0
  12. package/src/agent-ids.ts +50 -0
  13. package/src/agent-session.ts +973 -673
  14. package/src/agent.ts +1175 -0
  15. package/src/audit/config.ts +186 -0
  16. package/src/audit/contracts.ts +59 -0
  17. package/src/audit/index.ts +50 -0
  18. package/src/audit/projection.ts +125 -0
  19. package/src/audit/reader.ts +371 -0
  20. package/src/audit/runtime.ts +1060 -0
  21. package/src/checkpointing/config.ts +91 -0
  22. package/src/checkpointing/contracts.ts +45 -0
  23. package/src/checkpointing/coordinator.ts +100 -0
  24. package/src/checkpointing/ids.ts +5 -0
  25. package/src/checkpointing/index.ts +6 -0
  26. package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
  27. package/src/checkpointing/recovery.ts +114 -0
  28. package/src/checkpointing/strategy.ts +139 -0
  29. package/src/identity.ts +62 -0
  30. package/src/index.ts +117 -0
  31. package/src/internal-inference/config.ts +68 -0
  32. package/src/internal-inference/contracts.ts +218 -0
  33. package/src/internal-inference/coordination/handles.ts +133 -0
  34. package/src/internal-inference/coordination/manager.ts +487 -0
  35. package/src/internal-inference/ids.ts +10 -0
  36. package/src/internal-inference/index.ts +10 -0
  37. package/src/internal-inference/persistence/records.ts +132 -0
  38. package/src/internal-inference/persistence/repository.ts +35 -0
  39. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  40. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  41. package/src/internal-inference/strategy/registry.ts +42 -0
  42. package/src/metering/engine.ts +47 -0
  43. package/src/metering/record.ts +4 -1
  44. package/src/observation/contracts.ts +10 -0
  45. package/src/observation/index.ts +8 -0
  46. package/src/observation/subscription-hub.ts +43 -0
  47. package/src/persistence/activity-projection.ts +26 -12
  48. package/src/persistence/backend.ts +774 -0
  49. package/src/persistence/index.ts +99 -0
  50. package/src/persistence/sqlite-backend.ts +1927 -0
  51. package/src/persistence/sqlite-conversation-records.ts +425 -0
  52. package/src/persistence/sqlite-owner-lock.ts +106 -0
  53. package/src/persistence/sqlite-schema.ts +561 -0
@@ -0,0 +1,1060 @@
1
+ import { open, mkdir, readdir, realpath, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { Buffer } from "node:buffer";
4
+ import type { FileHandle } from "node:fs/promises";
5
+ import type { AgentSessionId } from "../agent-ids.ts";
6
+ import type {
7
+ AgentAuditState,
8
+ AuditOutboxBacklog,
9
+ AuditOutboxItem,
10
+ PersistenceBackend,
11
+ } from "../persistence/backend.ts";
12
+ import { canonicalizeJson, sha256CanonicalJson } from "../persistence/integrity.ts";
13
+ import { SqliteOwnerLock, SqliteOwnerLockConflictError } from "../persistence/sqlite-owner-lock.ts";
14
+ import { SubscriptionHub } from "../observation/subscription-hub.ts";
15
+ import type { StatefulSubscribable, Unsubscribe } from "../observation/contracts.ts";
16
+ import type { ResolvedAgentAuditLogConfig } from "./config.ts";
17
+
18
+ export interface AgentAuditSegmentHeaderV2 {
19
+ readonly v: 2;
20
+ readonly t: "header";
21
+ readonly auditLogId: string;
22
+ readonly agentSessionId: AgentSessionId;
23
+ readonly generation: number;
24
+ readonly createdAt: string;
25
+ readonly firstAuditSequence: number;
26
+ }
27
+
28
+ export interface AgentAuditEntryV2 {
29
+ readonly v: 2;
30
+ readonly t: "audit";
31
+ readonly auditLogId: string;
32
+ readonly outboxId: string;
33
+ readonly auditSequence: number;
34
+ readonly agentSessionId: AgentSessionId;
35
+ readonly agentConversationId?: string;
36
+ readonly sourceRecordId?: string;
37
+ readonly operationId?: string;
38
+ readonly occurredAt: string;
39
+ readonly kind: string;
40
+ readonly captureLevel: string;
41
+ readonly captureFingerprint: string;
42
+ readonly payloadSha256: string;
43
+ readonly payload: AuditOutboxItem["payload"];
44
+ }
45
+
46
+ export const AGENT_AUDIT_BATCH_SIZE = 16;
47
+ const AUDIT_RECOVERY_TAIL_ENTRIES = AGENT_AUDIT_BATCH_SIZE * 2 + 1;
48
+ const MAX_AUDIT_LINE_BYTES = 1_048_576;
49
+
50
+ export type AgentAuditRuntimeState = "idle" | "delivering" | "backoff" | "blocked" | "stopped";
51
+
52
+ export interface AgentAuditSnapshot {
53
+ readonly state: AgentAuditRuntimeState;
54
+ readonly pendingCount: number;
55
+ readonly pendingPayloadBytes: number;
56
+ readonly oldestPendingAt?: string;
57
+ readonly lastAllocatedSequence: number;
58
+ readonly lastDeliveredSequence: number;
59
+ readonly headAttemptCount?: number;
60
+ readonly headLastError?: string;
61
+ readonly activeSegmentGeneration: number;
62
+ readonly activeSegmentBytes: number;
63
+ readonly directory: string;
64
+ readonly filePrefix: string;
65
+ readonly rotation: ResolvedAgentAuditLogConfig["rotation"];
66
+ readonly retry: ResolvedAgentAuditLogConfig["retry"];
67
+ readonly captureFingerprint: string;
68
+ }
69
+
70
+ export type AgentAuditNotificationKind =
71
+ | "pending"
72
+ | "batch_started"
73
+ | "batch_completed"
74
+ | "batch_failed"
75
+ | "backoff_started"
76
+ | "backoff_ended"
77
+ | "rotation"
78
+ | "recovery"
79
+ | "blocked"
80
+ | "flush_completed"
81
+ | "flush_timed_out"
82
+ | "stopped";
83
+
84
+ export interface AgentAuditNotification {
85
+ readonly kind: AgentAuditNotificationKind;
86
+ readonly at: string;
87
+ readonly snapshot: AgentAuditSnapshot;
88
+ }
89
+
90
+ export interface AgentAuditFlushOptions {
91
+ readonly timeoutMs?: number;
92
+ }
93
+
94
+ export type AgentAuditFlushResult = Readonly<{
95
+ status: "delivered" | "pending" | "blocked" | "timed_out";
96
+ throughSequence: number;
97
+ deliveredThroughSequence: number;
98
+ }>;
99
+
100
+ export class AuditLogDestinationInUseError extends Error {
101
+ constructor(readonly directory: string, readonly filePrefix: string, options?: ErrorOptions) {
102
+ super(`audit log destination is already owned: ${join(directory, filePrefix)}`, options);
103
+ this.name = "AuditLogDestinationInUseError";
104
+ }
105
+ }
106
+
107
+ export class AuditLogIdentityConflictError extends Error {
108
+ constructor(readonly path: string, message: string, options?: ErrorOptions) {
109
+ super(`audit log identity conflict at ${path}: ${message}`, options);
110
+ this.name = "AuditLogIdentityConflictError";
111
+ }
112
+ }
113
+
114
+ export class AuditLogHistoryMissingError extends Error {
115
+ constructor(readonly path: string) {
116
+ super(`delivered audit history is missing: ${path}`);
117
+ this.name = "AuditLogHistoryMissingError";
118
+ }
119
+ }
120
+
121
+ export class AuditLogDestinationBlockedError extends Error {
122
+ constructor(message: string) {
123
+ super(message);
124
+ this.name = "AuditLogDestinationBlockedError";
125
+ }
126
+ }
127
+
128
+ /** One agent-owned background writer. Rotation and tail recovery are layered onto this core. */
129
+ export class AgentAuditRuntime
130
+ implements StatefulSubscribable<AgentAuditSnapshot, AgentAuditNotification> {
131
+ readonly directory: string;
132
+ readonly filePrefix: string;
133
+
134
+ private running = true;
135
+ private runtimeState: AgentAuditRuntimeState = "idle";
136
+ private syncedBatch?: readonly string[];
137
+ private readonly writtenBatchPrefix: string[] = [];
138
+ private wake?: () => void;
139
+ private readonly loop: Promise<void>;
140
+ private readonly subscriptions = new SubscriptionHub<AgentAuditNotification>();
141
+ private currentSnapshot: AgentAuditSnapshot;
142
+ private generation: number;
143
+ private segmentPath: string;
144
+ private file: FileHandle;
145
+ private segmentCreatedAtMs: number;
146
+ private segmentEntryCount: number;
147
+ private segmentBytes: number;
148
+ private constructor(
149
+ private readonly persistence: PersistenceBackend,
150
+ private readonly agentSessionId: AgentSessionId,
151
+ private readonly config: ResolvedAgentAuditLogConfig,
152
+ private readonly auditLogId: string,
153
+ private readonly ownerLock: SqliteOwnerLock,
154
+ active: RecoveredActiveSegment,
155
+ initialSnapshot: AgentAuditSnapshot,
156
+ ) {
157
+ this.directory = config.directory;
158
+ this.filePrefix = config.filePrefix;
159
+ this.generation = active.generation;
160
+ this.segmentPath = active.path;
161
+ this.file = active.file;
162
+ this.segmentCreatedAtMs = Date.parse(active.createdAt);
163
+ this.segmentEntryCount = active.entryCount;
164
+ this.segmentBytes = active.bytes;
165
+ this.currentSnapshot = initialSnapshot;
166
+ this.loop = this.run();
167
+ }
168
+
169
+ static async open(input: {
170
+ readonly persistence: PersistenceBackend;
171
+ readonly agentSessionId: AgentSessionId;
172
+ readonly config: ResolvedAgentAuditLogConfig;
173
+ readonly auditState: AgentAuditState;
174
+ }): Promise<AgentAuditRuntime> {
175
+ await mkdir(input.config.directory, { recursive: true });
176
+ const directory = await realpath(input.config.directory);
177
+ const config = Object.freeze({ ...input.config, directory });
178
+ const lockPath = join(directory, `${config.filePrefix}.writer-owner.sqlite`);
179
+ let ownerLock: SqliteOwnerLock;
180
+ try {
181
+ ownerLock = await SqliteOwnerLock.acquire(`audit:${directory}/${config.filePrefix}`, lockPath);
182
+ } catch (error) {
183
+ if (error instanceof SqliteOwnerLockConflictError) {
184
+ throw new AuditLogDestinationInUseError(directory, config.filePrefix, { cause: error });
185
+ }
186
+ throw error;
187
+ }
188
+
189
+ try {
190
+ const authoritativeState = await input.persistence.auditOutbox!.state();
191
+ if (!authoritativeState || authoritativeState.auditLogId !== input.auditState.auditLogId) {
192
+ throw new AuditLogIdentityConflictError(
193
+ join(directory, segmentName(config.filePrefix, 1)),
194
+ "SQLite audit identity changed during destination open",
195
+ );
196
+ }
197
+ const recovered = await recoverAuditStream(
198
+ directory,
199
+ config.filePrefix,
200
+ input.agentSessionId,
201
+ authoritativeState,
202
+ input.persistence,
203
+ );
204
+ const refreshedState = await input.persistence.auditOutbox!.state();
205
+ if (!refreshedState) throw new Error("agent audit state is unavailable after recovery");
206
+ const [backlog, segment] = await Promise.all([
207
+ input.persistence.auditOutbox!.backlog(),
208
+ recovered.file.stat(),
209
+ ]);
210
+ const head = await input.persistence.auditOutbox!.head();
211
+ const initialSnapshot = makeSnapshot(
212
+ "idle",
213
+ config,
214
+ refreshedState,
215
+ backlog,
216
+ head,
217
+ recovered.generation,
218
+ segment.size,
219
+ );
220
+ return new AgentAuditRuntime(
221
+ input.persistence,
222
+ input.agentSessionId,
223
+ config,
224
+ refreshedState.auditLogId,
225
+ ownerLock,
226
+ recovered,
227
+ initialSnapshot,
228
+ );
229
+ } catch (error) {
230
+ ownerLock.close();
231
+ throw error;
232
+ }
233
+ }
234
+
235
+ notifyPending(): void {
236
+ this.wake?.();
237
+ this.emitCached("pending");
238
+ }
239
+
240
+ get snapshot(): AgentAuditSnapshot {
241
+ return this.currentSnapshot;
242
+ }
243
+
244
+ subscribe(listener: (event: AgentAuditNotification) => void): Unsubscribe {
245
+ return this.subscriptions.subscribe(listener);
246
+ }
247
+
248
+ async status(): Promise<AgentAuditSnapshot> {
249
+ if (this.runtimeState === "stopped") {
250
+ if (this.currentSnapshot.state !== "stopped") {
251
+ this.currentSnapshot = Object.freeze({ ...this.currentSnapshot, state: "stopped" });
252
+ }
253
+ return this.currentSnapshot;
254
+ }
255
+ const [state, backlog, head, segment] = await Promise.all([
256
+ this.persistence.auditOutbox!.state(),
257
+ this.persistence.auditOutbox!.backlog(),
258
+ this.persistence.auditOutbox!.head(),
259
+ this.file.stat(),
260
+ ]);
261
+ if (!state) throw new Error("agent audit state is unavailable");
262
+ this.currentSnapshot = makeSnapshot(
263
+ this.runtimeState,
264
+ this.config,
265
+ state,
266
+ backlog,
267
+ head,
268
+ this.generation,
269
+ segment.size,
270
+ );
271
+ return this.currentSnapshot;
272
+ }
273
+
274
+ async flush(options: AgentAuditFlushOptions = {}): Promise<AgentAuditFlushResult> {
275
+ const timeoutMs = boundedNonNegative(options.timeoutMs ?? 30_000, "audit flush timeoutMs");
276
+ const state = await this.persistence.auditOutbox!.state();
277
+ if (!state) throw new Error("agent audit state is unavailable");
278
+ const throughSequence = state.lastAllocatedSequence;
279
+ const deadline = Date.now() + timeoutMs;
280
+ this.notifyPending();
281
+ while (true) {
282
+ const snapshot = await this.status();
283
+ if (snapshot.lastDeliveredSequence >= throughSequence) {
284
+ const result = flushResult("delivered", throughSequence, snapshot.lastDeliveredSequence);
285
+ await this.publish("flush_completed");
286
+ return result;
287
+ }
288
+ if (snapshot.state === "blocked") {
289
+ return flushResult("blocked", throughSequence, snapshot.lastDeliveredSequence);
290
+ }
291
+ if (snapshot.state === "stopped") {
292
+ return flushResult("pending", throughSequence, snapshot.lastDeliveredSequence);
293
+ }
294
+ if (Date.now() >= deadline) {
295
+ const result = flushResult("timed_out", throughSequence, snapshot.lastDeliveredSequence);
296
+ await this.publish("flush_timed_out");
297
+ return result;
298
+ }
299
+ await Bun.sleep(Math.min(20, Math.max(1, deadline - Date.now())));
300
+ }
301
+ }
302
+
303
+ async retry(): Promise<void> {
304
+ if (this.runtimeState === "blocked") throw new AuditLogDestinationBlockedError("audit destination is blocked");
305
+ if (!this.running) throw new Error("audit runtime is stopped");
306
+ await this.persistence.auditOutbox!.retryHead();
307
+ if (this.runtimeState === "backoff") {
308
+ this.runtimeState = "idle";
309
+ await this.publish("backoff_ended");
310
+ }
311
+ this.notifyPending();
312
+ }
313
+
314
+ async close(): Promise<void> {
315
+ if (!this.running) return;
316
+ await this.flush({ timeoutMs: this.config.shutdownGraceMs });
317
+ this.running = false;
318
+ this.wake?.();
319
+ try {
320
+ await this.loop;
321
+ } finally {
322
+ try {
323
+ await this.file.close();
324
+ } finally {
325
+ this.ownerLock.close();
326
+ }
327
+ }
328
+ this.runtimeState = "stopped";
329
+ await this.publish("stopped");
330
+ this.subscriptions.clear();
331
+ }
332
+
333
+ private async run(): Promise<void> {
334
+ while (this.running) {
335
+ if (this.runtimeState === "blocked") {
336
+ await this.waitForWork();
337
+ continue;
338
+ }
339
+ let pending: readonly AuditOutboxItem[];
340
+ try {
341
+ pending = await this.persistence.auditOutbox!.pending(AGENT_AUDIT_BATCH_SIZE);
342
+ } catch (error) {
343
+ this.runtimeState = "blocked";
344
+ await this.publish("blocked");
345
+ await this.waitForWork();
346
+ continue;
347
+ }
348
+ if (pending.length === 0) {
349
+ if (this.runtimeState === "backoff") {
350
+ this.runtimeState = "idle";
351
+ await this.publish("backoff_ended");
352
+ }
353
+ await this.waitForWork();
354
+ continue;
355
+ }
356
+ try {
357
+ this.runtimeState = "delivering";
358
+ await this.publish("batch_started");
359
+ await this.deliver(pending);
360
+ this.runtimeState = "idle";
361
+ await this.publish("batch_completed");
362
+ } catch (error) {
363
+ if (error instanceof AuditLogDestinationBlockedError) {
364
+ this.runtimeState = "blocked";
365
+ await this.publish("blocked");
366
+ await this.waitForWork();
367
+ continue;
368
+ }
369
+ const head = pending[0]!;
370
+ const delay = retryDelay(this.config, head.attemptCount + 1, Math.random());
371
+ const nextAttemptAt = new Date(Date.now() + delay).toISOString();
372
+ await this.persistence.auditOutbox!.markFailed(head.outboxId, safeError(error), nextAttemptAt);
373
+ this.runtimeState = "backoff";
374
+ await this.publish("batch_failed");
375
+ await this.publish("backoff_started");
376
+ await this.waitForWork(delay);
377
+ if (this.runtimeState === "backoff") {
378
+ this.runtimeState = "idle";
379
+ await this.publish("backoff_ended");
380
+ }
381
+ }
382
+ }
383
+ }
384
+
385
+ private async deliver(items: readonly AuditOutboxItem[]): Promise<void> {
386
+ const outboxIds = items.map((item) => item.outboxId);
387
+ if (this.syncedBatch) {
388
+ if (
389
+ this.syncedBatch.length !== outboxIds.length
390
+ || this.syncedBatch.some((id, index) => id !== outboxIds[index])
391
+ ) throw new AuditLogDestinationBlockedError("synced audit batch no longer matches the pending head");
392
+ await this.persistence.auditOutbox!.acknowledge(this.syncedBatch);
393
+ this.syncedBatch = undefined;
394
+ this.writtenBatchPrefix.length = 0;
395
+ return;
396
+ }
397
+ const lines = items.map((item) => canonicalizeJson(toAuditEntry(
398
+ this.auditLogId,
399
+ this.agentSessionId,
400
+ item,
401
+ )) + "\n");
402
+ if (this.writtenBatchPrefix.some((id, index) => id !== outboxIds[index])) {
403
+ throw new AuditLogDestinationBlockedError("written audit prefix no longer matches the pending head");
404
+ }
405
+ for (let index = this.writtenBatchPrefix.length; index < items.length; index++) {
406
+ const item = items[index]!;
407
+ const line = lines[index]!;
408
+ if (this.shouldRotate(Buffer.byteLength(line, "utf8"))) await this.rotate(item.auditSequence);
409
+ const beforeBytes = this.segmentBytes;
410
+ const beforeEntries = this.segmentEntryCount;
411
+ try {
412
+ await this.file.writeFile(line, "utf8");
413
+ this.segmentBytes += Buffer.byteLength(line, "utf8");
414
+ this.segmentEntryCount++;
415
+ await this.file.sync();
416
+ await assertSameOpenFile(this.file, this.segmentPath);
417
+ } catch (error) {
418
+ if (error instanceof AuditLogDestinationBlockedError) throw error;
419
+ try {
420
+ await this.file.truncate(beforeBytes);
421
+ await this.file.sync();
422
+ this.segmentBytes = beforeBytes;
423
+ this.segmentEntryCount = beforeEntries;
424
+ } catch (rollbackError) {
425
+ throw new AuditLogDestinationBlockedError(
426
+ `audit entry write failed and its tail could not be restored: ${safeError(rollbackError)}`,
427
+ );
428
+ }
429
+ throw error;
430
+ }
431
+ this.writtenBatchPrefix.push(item.outboxId);
432
+ }
433
+ this.syncedBatch = Object.freeze(outboxIds);
434
+ await this.persistence.auditOutbox!.acknowledge(outboxIds);
435
+ this.syncedBatch = undefined;
436
+ this.writtenBatchPrefix.length = 0;
437
+ }
438
+
439
+ private shouldRotate(nextLineBytes: number): boolean {
440
+ if (this.segmentEntryCount === 0) return false;
441
+ const sizeReached = this.config.rotation.maxBytes !== false
442
+ && this.segmentBytes + nextLineBytes > this.config.rotation.maxBytes;
443
+ const ageReached = this.config.rotation.maxAgeMs !== false
444
+ && Date.now() - this.segmentCreatedAtMs >= this.config.rotation.maxAgeMs;
445
+ return sizeReached || ageReached;
446
+ }
447
+
448
+ private async rotate(firstAuditSequence: number): Promise<void> {
449
+ await this.file.sync();
450
+ await assertSameOpenFile(this.file, this.segmentPath);
451
+ const generation = this.generation + 1;
452
+ const active = await createSegment(
453
+ this.config.directory,
454
+ this.config.filePrefix,
455
+ generation,
456
+ this.auditLogId,
457
+ this.agentSessionId,
458
+ firstAuditSequence,
459
+ );
460
+ const previous = this.file;
461
+ this.generation = active.generation;
462
+ this.segmentPath = active.path;
463
+ this.file = active.file;
464
+ this.segmentCreatedAtMs = Date.parse(active.createdAt);
465
+ this.segmentEntryCount = 0;
466
+ this.segmentBytes = active.bytes;
467
+ await previous.close();
468
+ await this.publish("rotation");
469
+ }
470
+
471
+ private async waitForWork(maxDelayMs = 1_000): Promise<void> {
472
+ if (!this.running) return;
473
+ await new Promise<void>((resolve) => {
474
+ const timer = setTimeout(done, maxDelayMs);
475
+ const self = this;
476
+ function done() {
477
+ clearTimeout(timer);
478
+ if (self.wake === done) self.wake = undefined;
479
+ resolve();
480
+ }
481
+ this.wake = done;
482
+ });
483
+ }
484
+
485
+ private async publish(kind: AgentAuditNotificationKind): Promise<void> {
486
+ try {
487
+ await this.status();
488
+ } catch {
489
+ // The state transition remains observable through the cached snapshot.
490
+ this.currentSnapshot = Object.freeze({ ...this.currentSnapshot, state: this.runtimeState });
491
+ }
492
+ this.subscriptions.emit(Object.freeze({
493
+ kind,
494
+ at: new Date().toISOString(),
495
+ snapshot: this.currentSnapshot,
496
+ }));
497
+ }
498
+
499
+ private emitCached(kind: AgentAuditNotificationKind): void {
500
+ this.subscriptions.emit(Object.freeze({
501
+ kind,
502
+ at: new Date().toISOString(),
503
+ snapshot: this.currentSnapshot,
504
+ }));
505
+ }
506
+ }
507
+
508
+ interface RecoveredActiveSegment {
509
+ readonly generation: number;
510
+ readonly path: string;
511
+ readonly file: FileHandle;
512
+ readonly createdAt: string;
513
+ readonly entryCount: number;
514
+ readonly bytes: number;
515
+ }
516
+
517
+ interface ScannedAuditTuple {
518
+ readonly outboxId: string;
519
+ readonly payloadSha256: string;
520
+ }
521
+
522
+ interface InspectedSegment {
523
+ readonly header: AgentAuditSegmentHeaderV2;
524
+ readonly bytes: number;
525
+ readonly entryCount: number;
526
+ readonly entriesOffset: number;
527
+ }
528
+
529
+ async function recoverAuditStream(
530
+ directory: string,
531
+ prefix: string,
532
+ agentSessionId: AgentSessionId,
533
+ state: AgentAuditState,
534
+ persistence: PersistenceBackend,
535
+ ): Promise<RecoveredActiveSegment> {
536
+ const matcher = new RegExp(`^${escapeRegExp(prefix)}\\.([0-9]{6,})\\.jsonl$`);
537
+ const generations = (await readdir(directory))
538
+ .map((name) => ({ name, match: matcher.exec(name) }))
539
+ .filter((item): item is { name: string; match: RegExpExecArray } => item.match !== null)
540
+ .map(({ name, match }) => ({ name, generation: Number(match[1]) }))
541
+ .sort((left, right) => left.generation - right.generation);
542
+ for (let index = 0; index < generations.length; index++) {
543
+ if (generations[index]!.generation !== index + 1) {
544
+ throw new AuditLogIdentityConflictError(
545
+ join(directory, generations[index]!.name),
546
+ "segment generations are not contiguous from one",
547
+ );
548
+ }
549
+ }
550
+
551
+ if (generations.length === 0) {
552
+ const firstPath = join(directory, segmentName(prefix, 1));
553
+ if (state.lastDeliveredSequence > 0) throw new AuditLogHistoryMissingError(firstPath);
554
+ return await createSegment(directory, prefix, 1, state.auditLogId, agentSessionId, 1);
555
+ }
556
+
557
+ const inspectedSegments: Array<InspectedSegment & { readonly path: string }> = [];
558
+ let active: Omit<RecoveredActiveSegment, "file"> | undefined;
559
+ for (let index = 0; index < generations.length; index++) {
560
+ const descriptor = generations[index]!;
561
+ const path = join(directory, descriptor.name);
562
+ const highest = index === generations.length - 1;
563
+ const inspected = await inspectSegment(
564
+ path,
565
+ highest,
566
+ state.auditLogId,
567
+ agentSessionId,
568
+ descriptor.generation,
569
+ );
570
+ if (!inspected) {
571
+ await unlink(path);
572
+ await syncDirectory(directory);
573
+ if (index === 0) {
574
+ if (state.lastDeliveredSequence > 0) throw new AuditLogHistoryMissingError(path);
575
+ return await createSegment(directory, prefix, 1, state.auditLogId, agentSessionId, 1);
576
+ }
577
+ break;
578
+ }
579
+ inspectedSegments.push({ ...inspected, path });
580
+ active = {
581
+ generation: descriptor.generation,
582
+ path,
583
+ createdAt: inspected.header.createdAt,
584
+ entryCount: inspected.entryCount,
585
+ bytes: inspected.bytes,
586
+ };
587
+ }
588
+
589
+ const physicalTail: AgentAuditEntryV2[] = [];
590
+ for (let index = inspectedSegments.length - 1; index >= 0 && physicalTail.length < AUDIT_RECOVERY_TAIL_ENTRIES; index--) {
591
+ const segment = inspectedSegments[index]!;
592
+ const remaining = AUDIT_RECOVERY_TAIL_ENTRIES - physicalTail.length;
593
+ const tail = await readSegmentTail(
594
+ segment.path,
595
+ segment.entriesOffset,
596
+ segment.bytes,
597
+ remaining,
598
+ state.auditLogId,
599
+ agentSessionId,
600
+ );
601
+ physicalTail.unshift(...tail);
602
+ }
603
+ const { maximumSequence, tuples } = validateRecoveryTail(physicalTail, active?.path);
604
+
605
+ if (maximumSequence < state.lastDeliveredSequence) {
606
+ throw new AuditLogHistoryMissingError(active?.path ?? join(directory, segmentName(prefix, 1)));
607
+ }
608
+ if (maximumSequence > state.lastAllocatedSequence) {
609
+ throw new AuditLogIdentityConflictError(active!.path, "physical stream extends beyond SQLite allocation state");
610
+ }
611
+ const unacknowledged = maximumSequence - state.lastDeliveredSequence;
612
+ if (unacknowledged > AGENT_AUDIT_BATCH_SIZE) {
613
+ throw new AuditLogIdentityConflictError(active!.path, "unacknowledged physical suffix exceeds batch bound");
614
+ }
615
+ if (unacknowledged > 0) {
616
+ const pending = await persistence.auditOutbox!.pending(unacknowledged, "9999-12-31T23:59:59.999Z");
617
+ if (pending.length !== unacknowledged || pending.some((item) => {
618
+ const physical = tuples.get(item.auditSequence);
619
+ return !physical || physical.outboxId !== item.outboxId || physical.payloadSha256 !== item.payloadSha256;
620
+ })) throw new AuditLogIdentityConflictError(active!.path, "physical suffix does not match the pending head");
621
+ await persistence.auditOutbox!.acknowledge(pending.map((item) => item.outboxId));
622
+ }
623
+
624
+ if (!active) {
625
+ const previous = generations.at(-2);
626
+ if (!previous) return await createSegment(directory, prefix, 1, state.auditLogId, agentSessionId, 1);
627
+ const path = join(directory, previous.name);
628
+ const inspected = await inspectSegment(
629
+ path,
630
+ false,
631
+ state.auditLogId,
632
+ agentSessionId,
633
+ previous.generation,
634
+ );
635
+ if (!inspected) throw new AuditLogIdentityConflictError(path, "sealed segment header is incomplete");
636
+ active = {
637
+ generation: previous.generation,
638
+ path,
639
+ createdAt: inspected.header.createdAt,
640
+ entryCount: inspected.entryCount,
641
+ bytes: inspected.bytes,
642
+ };
643
+ }
644
+ return Object.freeze({ ...active, file: await open(active.path, "a+", 0o600) });
645
+ }
646
+
647
+ async function inspectSegment(
648
+ path: string,
649
+ highest: boolean,
650
+ auditLogId: string,
651
+ agentSessionId: AgentSessionId,
652
+ generation: number,
653
+ ): Promise<InspectedSegment | null> {
654
+ const handle = await open(path, highest ? "r+" : "r");
655
+ try {
656
+ let bytes = (await handle.stat()).size;
657
+ let headerLine: { line: string; nextOffset: number };
658
+ try {
659
+ headerLine = await readAuditLine(handle, 0, bytes, path);
660
+ } catch (error) {
661
+ if (highest && error instanceof IncompleteAuditLineError) return null;
662
+ throw new AuditLogIdentityConflictError(path, "sealed segment header is incomplete", { cause: error });
663
+ }
664
+ const header = parseHeader(headerLine.line, path, auditLogId, agentSessionId, generation);
665
+ if (bytes > headerLine.nextOffset && !await endsWithNewline(handle, bytes)) {
666
+ if (!highest) throw new AuditLogIdentityConflictError(path, "sealed segment tail is incomplete");
667
+ const completeBytes = await findLastNewlineEnd(handle, bytes, headerLine.nextOffset, path);
668
+ await handle.truncate(completeBytes);
669
+ await handle.sync();
670
+ bytes = completeBytes;
671
+ }
672
+
673
+ let firstEntry: AgentAuditEntryV2 | undefined;
674
+ if (bytes > headerLine.nextOffset) {
675
+ const first = await readAuditLine(handle, headerLine.nextOffset, bytes, path);
676
+ firstEntry = parseEntry(first.line, path, 2, auditLogId, agentSessionId);
677
+ if (header.firstAuditSequence !== firstEntry.auditSequence) {
678
+ throw new AuditLogIdentityConflictError(path, "header firstAuditSequence does not match its first entry");
679
+ }
680
+ }
681
+ return Object.freeze({
682
+ header,
683
+ bytes,
684
+ entryCount: firstEntry ? 1 : 0,
685
+ entriesOffset: headerLine.nextOffset,
686
+ });
687
+ } finally {
688
+ await handle.close();
689
+ }
690
+ }
691
+
692
+ async function readSegmentTail(
693
+ path: string,
694
+ entriesOffset: number,
695
+ bytes: number,
696
+ limit: number,
697
+ auditLogId: string,
698
+ agentSessionId: AgentSessionId,
699
+ ): Promise<readonly AgentAuditEntryV2[]> {
700
+ const handle = await open(path, "r");
701
+ try {
702
+ const lines = await readAuditTailLines(handle, entriesOffset, bytes, limit, path);
703
+ return Object.freeze(lines.map((line, index) => parseEntry(
704
+ line,
705
+ path,
706
+ `tail-${index + 1}`,
707
+ auditLogId,
708
+ agentSessionId,
709
+ )));
710
+ } finally {
711
+ await handle.close();
712
+ }
713
+ }
714
+
715
+ function validateRecoveryTail(
716
+ entries: readonly AgentAuditEntryV2[],
717
+ path = "audit stream",
718
+ ): { maximumSequence: number; tuples: Map<number, ScannedAuditTuple> } {
719
+ if (entries.length === 0) return { maximumSequence: 0, tuples: new Map() };
720
+ const tuples = new Map<number, ScannedAuditTuple>();
721
+ let maximumSequence = entries[0]!.auditSequence - 1;
722
+ let replayLength = 0;
723
+ let previousReplaySequence = 0;
724
+ for (const entry of entries) {
725
+ const tuple = { outboxId: entry.outboxId, payloadSha256: entry.payloadSha256 };
726
+ if (entry.auditSequence === maximumSequence + 1) {
727
+ tuples.set(entry.auditSequence, tuple);
728
+ maximumSequence = entry.auditSequence;
729
+ replayLength = 0;
730
+ previousReplaySequence = 0;
731
+ continue;
732
+ }
733
+ const original = tuples.get(entry.auditSequence);
734
+ if (
735
+ !original
736
+ || original.outboxId !== tuple.outboxId
737
+ || original.payloadSha256 !== tuple.payloadSha256
738
+ || (replayLength > 0 && entry.auditSequence !== previousReplaySequence + 1)
739
+ ) throw new AuditLogIdentityConflictError(path, `conflicting audit sequence ${entry.auditSequence}`);
740
+ replayLength++;
741
+ previousReplaySequence = entry.auditSequence;
742
+ if (replayLength > AGENT_AUDIT_BATCH_SIZE) {
743
+ throw new AuditLogIdentityConflictError(path, "physical replay exceeds the delivery batch bound");
744
+ }
745
+ }
746
+ return { maximumSequence, tuples };
747
+ }
748
+
749
+ class IncompleteAuditLineError extends Error {}
750
+
751
+ async function readAuditLine(
752
+ handle: FileHandle,
753
+ offset: number,
754
+ boundary: number,
755
+ path: string,
756
+ ): Promise<{ line: string; nextOffset: number }> {
757
+ const chunks: Buffer[] = [];
758
+ let cursor = offset;
759
+ let total = 0;
760
+ while (cursor < boundary) {
761
+ const size = Math.min(64 * 1024, boundary - cursor, MAX_AUDIT_LINE_BYTES + 1 - total);
762
+ if (size <= 0) throw new AuditLogIdentityConflictError(path, `audit line exceeds ${MAX_AUDIT_LINE_BYTES} bytes`);
763
+ const buffer = Buffer.allocUnsafe(size);
764
+ const { bytesRead } = await handle.read(buffer, 0, size, cursor);
765
+ if (bytesRead === 0) break;
766
+ const slice = buffer.subarray(0, bytesRead);
767
+ const newline = slice.indexOf(0x0a);
768
+ if (newline >= 0) {
769
+ chunks.push(slice.subarray(0, newline));
770
+ return { line: Buffer.concat(chunks).toString("utf8"), nextOffset: cursor + newline + 1 };
771
+ }
772
+ chunks.push(slice);
773
+ cursor += bytesRead;
774
+ total += bytesRead;
775
+ }
776
+ throw new IncompleteAuditLineError(`incomplete audit line at byte ${offset}: ${path}`);
777
+ }
778
+
779
+ async function endsWithNewline(handle: FileHandle, bytes: number): Promise<boolean> {
780
+ if (bytes === 0) return false;
781
+ const final = Buffer.allocUnsafe(1);
782
+ const { bytesRead } = await handle.read(final, 0, 1, bytes - 1);
783
+ return bytesRead === 1 && final[0] === 0x0a;
784
+ }
785
+
786
+ async function findLastNewlineEnd(
787
+ handle: FileHandle,
788
+ bytes: number,
789
+ minimum: number,
790
+ path: string,
791
+ ): Promise<number> {
792
+ let cursor = bytes;
793
+ let scanned = 0;
794
+ while (cursor > minimum && scanned <= MAX_AUDIT_LINE_BYTES) {
795
+ const size = Math.min(64 * 1024, cursor - minimum, MAX_AUDIT_LINE_BYTES + 1 - scanned);
796
+ if (size <= 0) break;
797
+ const start = cursor - size;
798
+ const buffer = Buffer.allocUnsafe(size);
799
+ const { bytesRead } = await handle.read(buffer, 0, size, start);
800
+ if (bytesRead !== size) throw new IncompleteAuditLineError(`could not inspect audit tail: ${path}`);
801
+ const newline = buffer.lastIndexOf(0x0a);
802
+ if (newline >= 0) return start + newline + 1;
803
+ cursor = start;
804
+ scanned += size;
805
+ }
806
+ if (cursor === minimum) return minimum;
807
+ throw new AuditLogIdentityConflictError(path, `audit line exceeds ${MAX_AUDIT_LINE_BYTES} bytes`);
808
+ }
809
+
810
+ async function readAuditTailLines(
811
+ handle: FileHandle,
812
+ entriesOffset: number,
813
+ bytes: number,
814
+ limit: number,
815
+ path: string,
816
+ ): Promise<readonly string[]> {
817
+ if (bytes <= entriesOffset) return Object.freeze([]);
818
+ const maximumWindow = limit * (MAX_AUDIT_LINE_BYTES + 1);
819
+ const start = Math.max(entriesOffset, bytes - maximumWindow);
820
+ const buffer = Buffer.allocUnsafe(bytes - start);
821
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, start);
822
+ if (bytesRead !== buffer.length) throw new IncompleteAuditLineError(`could not inspect audit tail: ${path}`);
823
+ let complete = buffer;
824
+ if (start > entriesOffset) {
825
+ const firstNewline = complete.indexOf(0x0a);
826
+ if (firstNewline < 0) {
827
+ throw new AuditLogIdentityConflictError(path, `audit line exceeds ${MAX_AUDIT_LINE_BYTES} bytes`);
828
+ }
829
+ complete = complete.subarray(firstNewline + 1);
830
+ }
831
+ const text = complete.toString("utf8");
832
+ const lines = text.endsWith("\n") ? text.slice(0, -1).split("\n") : [];
833
+ for (const line of lines) {
834
+ if (Buffer.byteLength(line, "utf8") > MAX_AUDIT_LINE_BYTES) {
835
+ throw new AuditLogIdentityConflictError(path, `audit line exceeds ${MAX_AUDIT_LINE_BYTES} bytes`);
836
+ }
837
+ }
838
+ return Object.freeze(lines.slice(-limit));
839
+ }
840
+
841
+ async function createSegment(
842
+ directory: string,
843
+ prefix: string,
844
+ generation: number,
845
+ auditLogId: string,
846
+ agentSessionId: AgentSessionId,
847
+ firstAuditSequence: number,
848
+ ): Promise<RecoveredActiveSegment> {
849
+ const path = join(directory, segmentName(prefix, generation));
850
+ const createdAt = new Date().toISOString();
851
+ const header: AgentAuditSegmentHeaderV2 = {
852
+ v: 2,
853
+ t: "header",
854
+ auditLogId,
855
+ agentSessionId,
856
+ generation,
857
+ createdAt,
858
+ firstAuditSequence,
859
+ };
860
+ const line = canonicalizeJson(header) + "\n";
861
+ const file = await open(path, "ax", 0o600);
862
+ try {
863
+ await file.writeFile(line, "utf8");
864
+ await file.sync();
865
+ await syncDirectory(directory);
866
+ await file.close();
867
+ return Object.freeze({
868
+ generation,
869
+ path,
870
+ file: await open(path, "a+", 0o600),
871
+ createdAt,
872
+ entryCount: 0,
873
+ bytes: Buffer.byteLength(line, "utf8"),
874
+ });
875
+ } catch (error) {
876
+ await file.close().catch(() => undefined);
877
+ await unlink(path).catch(() => undefined);
878
+ await syncDirectory(directory).catch(() => undefined);
879
+ throw error;
880
+ }
881
+ }
882
+
883
+ function parseHeader(
884
+ line: string,
885
+ path: string,
886
+ auditLogId: string,
887
+ agentSessionId: AgentSessionId,
888
+ generation: number,
889
+ ): AgentAuditSegmentHeaderV2 {
890
+ let value: unknown;
891
+ try {
892
+ value = JSON.parse(line);
893
+ } catch (error) {
894
+ throw new AuditLogIdentityConflictError(path, "segment header is malformed", { cause: error });
895
+ }
896
+ if (!isMatchingHeader(value, auditLogId, agentSessionId, generation)) {
897
+ throw new AuditLogIdentityConflictError(path, "segment header belongs to another stream");
898
+ }
899
+ const header = value as unknown as AgentAuditSegmentHeaderV2;
900
+ if (!Number.isFinite(Date.parse(header.createdAt)) || !Number.isSafeInteger(header.firstAuditSequence)
901
+ || header.firstAuditSequence < 1) {
902
+ throw new AuditLogIdentityConflictError(path, "segment header fields are invalid");
903
+ }
904
+ return header;
905
+ }
906
+
907
+ function parseEntry(
908
+ line: string,
909
+ path: string,
910
+ lineNumber: number | string,
911
+ auditLogId: string,
912
+ agentSessionId: AgentSessionId,
913
+ ): AgentAuditEntryV2 {
914
+ let value: unknown;
915
+ try {
916
+ value = JSON.parse(line);
917
+ } catch (error) {
918
+ throw new AuditLogIdentityConflictError(path, `audit entry at line ${lineNumber} is malformed`, { cause: error });
919
+ }
920
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
921
+ throw new AuditLogIdentityConflictError(path, `audit entry at line ${lineNumber} is invalid`);
922
+ }
923
+ const entry = value as unknown as AgentAuditEntryV2;
924
+ if (
925
+ entry.v !== 2 || entry.t !== "audit" || entry.auditLogId !== auditLogId
926
+ || entry.agentSessionId !== agentSessionId || !entry.outboxId
927
+ || !Number.isSafeInteger(entry.auditSequence) || entry.auditSequence < 1
928
+ || !/^[0-9a-f]{64}$/.test(entry.payloadSha256)
929
+ || sha256CanonicalJson(entry.payload) !== entry.payloadSha256
930
+ ) throw new AuditLogIdentityConflictError(path, `audit entry at line ${lineNumber} failed validation`);
931
+ return entry;
932
+ }
933
+
934
+ function toAuditEntry(
935
+ auditLogId: string,
936
+ agentSessionId: AgentSessionId,
937
+ item: AuditOutboxItem,
938
+ ): AgentAuditEntryV2 {
939
+ return {
940
+ v: 2,
941
+ t: "audit",
942
+ auditLogId,
943
+ outboxId: item.outboxId,
944
+ auditSequence: item.auditSequence,
945
+ agentSessionId,
946
+ ...(item.agentConversationId ? { agentConversationId: item.agentConversationId } : {}),
947
+ ...(item.sourceRecordId ? { sourceRecordId: item.sourceRecordId } : {}),
948
+ ...(item.operationId ? { operationId: item.operationId } : {}),
949
+ occurredAt: item.occurredAt,
950
+ kind: item.kind,
951
+ captureLevel: item.captureLevel,
952
+ captureFingerprint: item.captureFingerprint,
953
+ payloadSha256: item.payloadSha256,
954
+ payload: item.payload,
955
+ };
956
+ }
957
+
958
+ function isMatchingHeader(
959
+ value: unknown,
960
+ auditLogId: string,
961
+ agentSessionId: AgentSessionId,
962
+ generation: number,
963
+ ): boolean {
964
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
965
+ const header = value as Record<string, unknown>;
966
+ return header.v === 2 && header.t === "header" && header.auditLogId === auditLogId
967
+ && header.agentSessionId === agentSessionId && header.generation === generation;
968
+ }
969
+
970
+ function segmentName(prefix: string, generation: number): string {
971
+ return `${prefix}.${String(generation).padStart(6, "0")}.jsonl`;
972
+ }
973
+
974
+ async function syncDirectory(directory: string): Promise<void> {
975
+ const handle = await open(directory, "r");
976
+ try {
977
+ await handle.sync();
978
+ } catch (error) {
979
+ if (!isNodeErrorCode(error, "EINVAL") && !isNodeErrorCode(error, "ENOTSUP")) throw error;
980
+ } finally {
981
+ await handle.close();
982
+ }
983
+ }
984
+
985
+ async function assertSameOpenFile(file: FileHandle, path: string): Promise<void> {
986
+ let named: FileHandle;
987
+ try {
988
+ named = await open(path, "r");
989
+ } catch (error) {
990
+ throw new AuditLogDestinationBlockedError(`active audit segment is unavailable: ${path}`);
991
+ }
992
+ try {
993
+ const opened = await file.stat();
994
+ const current = await named.stat();
995
+ if (opened.dev !== current.dev || opened.ino !== current.ino) {
996
+ throw new AuditLogDestinationBlockedError(`active audit segment was replaced: ${path}`);
997
+ }
998
+ } finally {
999
+ await named.close();
1000
+ }
1001
+ }
1002
+
1003
+ function retryDelay(config: ResolvedAgentAuditLogConfig, attempt: number, random: number): number {
1004
+ const exponent = Math.max(0, Math.min(30, attempt - 1));
1005
+ const base = Math.min(config.retry.maxDelayMs, config.retry.initialDelayMs * 2 ** exponent);
1006
+ return Math.max(1, Math.round(base * (0.9 + Math.min(1, Math.max(0, random)) * 0.2)));
1007
+ }
1008
+
1009
+ function safeError(error: unknown): string {
1010
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
1011
+ }
1012
+
1013
+ function isNodeErrorCode(error: unknown, code: string): boolean {
1014
+ return !!error && typeof error === "object" && "code" in error && error.code === code;
1015
+ }
1016
+
1017
+ function makeSnapshot(
1018
+ state: AgentAuditRuntimeState,
1019
+ config: ResolvedAgentAuditLogConfig,
1020
+ audit: AgentAuditState,
1021
+ backlog: AuditOutboxBacklog,
1022
+ head: AuditOutboxItem | null,
1023
+ activeSegmentGeneration: number,
1024
+ activeSegmentBytes: number,
1025
+ ): AgentAuditSnapshot {
1026
+ return Object.freeze({
1027
+ state,
1028
+ pendingCount: backlog.pendingCount,
1029
+ pendingPayloadBytes: backlog.pendingPayloadBytes,
1030
+ ...(backlog.oldestPendingAt ? { oldestPendingAt: backlog.oldestPendingAt } : {}),
1031
+ lastAllocatedSequence: audit.lastAllocatedSequence,
1032
+ lastDeliveredSequence: audit.lastDeliveredSequence,
1033
+ ...(head ? { headAttemptCount: head.attemptCount } : {}),
1034
+ ...(head?.lastError ? { headLastError: head.lastError } : {}),
1035
+ activeSegmentGeneration,
1036
+ activeSegmentBytes,
1037
+ directory: config.directory,
1038
+ filePrefix: config.filePrefix,
1039
+ rotation: config.rotation,
1040
+ retry: config.retry,
1041
+ captureFingerprint: audit.captureFingerprint,
1042
+ });
1043
+ }
1044
+
1045
+ function flushResult(
1046
+ status: AgentAuditFlushResult["status"],
1047
+ throughSequence: number,
1048
+ deliveredThroughSequence: number,
1049
+ ): AgentAuditFlushResult {
1050
+ return Object.freeze({ status, throughSequence, deliveredThroughSequence });
1051
+ }
1052
+
1053
+ function boundedNonNegative(value: number, label: string): number {
1054
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label} must be a non-negative safe integer`);
1055
+ return value;
1056
+ }
1057
+
1058
+ function escapeRegExp(value: string): string {
1059
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1060
+ }