@qlairoslabs/acp-client 0.5.0 → 0.7.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 (62) hide show
  1. package/CHANGELOG-metering.md +288 -0
  2. package/CONSUMER_GUIDE.md +579 -292
  3. package/README.md +25 -0
  4. package/package.json +6 -3
  5. package/src/agent-session.ts +2589 -96
  6. package/src/cli/index.ts +33 -5
  7. package/src/cli/managed.ts +220 -0
  8. package/src/client.ts +57 -1
  9. package/src/controller.ts +43 -0
  10. package/src/index.ts +379 -3
  11. package/src/metering/catalog/build.ts +285 -0
  12. package/src/metering/catalog/index.ts +243 -0
  13. package/src/metering/catalog/live.ts +171 -0
  14. package/src/metering/catalog/models-dev.catalog.json +8797 -0
  15. package/src/metering/catalog/models-dev.meta.json +6 -0
  16. package/src/metering/categories.ts +129 -0
  17. package/src/metering/certification.ts +86 -0
  18. package/src/metering/context.ts +134 -0
  19. package/src/metering/delta.ts +108 -0
  20. package/src/metering/engine.ts +999 -0
  21. package/src/metering/money.ts +356 -0
  22. package/src/metering/opencode/channel.ts +389 -0
  23. package/src/metering/opencode/index.ts +159 -0
  24. package/src/metering/opencode/plugin.js +90 -0
  25. package/src/metering/opencode/profile.ts +159 -0
  26. package/src/metering/pricing.ts +285 -0
  27. package/src/metering/provider.ts +121 -0
  28. package/src/metering/rating.ts +349 -0
  29. package/src/metering/record.ts +275 -0
  30. package/src/metering/state.ts +421 -0
  31. package/src/metering/usage.ts +72 -0
  32. package/src/persistence/activity-projection.ts +71 -0
  33. package/src/persistence/audit-log-reader.ts +506 -0
  34. package/src/persistence/audit-runtime.ts +162 -0
  35. package/src/persistence/checkpoint.ts +304 -0
  36. package/src/persistence/config.ts +538 -0
  37. package/src/persistence/configuration-state.ts +191 -0
  38. package/src/persistence/deletion.ts +227 -0
  39. package/src/persistence/file-registry-store.ts +740 -0
  40. package/src/persistence/integrity.ts +147 -0
  41. package/src/persistence/legacy-registry-import.ts +240 -0
  42. package/src/persistence/managed-checkpoint.ts +81 -0
  43. package/src/persistence/managed-creation.ts +456 -0
  44. package/src/persistence/managed-load.ts +172 -0
  45. package/src/persistence/managed-registry.ts +57 -0
  46. package/src/persistence/migration.ts +298 -0
  47. package/src/persistence/paths.ts +172 -0
  48. package/src/persistence/projection.ts +373 -0
  49. package/src/persistence/reconfiguration.ts +453 -0
  50. package/src/persistence/records.ts +873 -0
  51. package/src/persistence/reducer.ts +498 -0
  52. package/src/persistence/registry.ts +446 -0
  53. package/src/persistence/restoration.ts +689 -0
  54. package/src/persistence/session-log-writer.ts +480 -0
  55. package/src/persistence/state-runtime.ts +176 -0
  56. package/src/persistence/transcript-reader.ts +980 -0
  57. package/src/persistence/transcript-runtime.ts +667 -0
  58. package/src/persistence/transcript-scanner.ts +385 -0
  59. package/src/persistence/truncation.ts +276 -0
  60. package/src/session-manager.ts +257 -7
  61. package/src/transcript.ts +3 -3
  62. package/src/types.ts +28 -5
@@ -0,0 +1,498 @@
1
+ import {
2
+ createAgentSessionCheckpoint,
3
+ type AgentSessionCheckpoint,
4
+ type AgentSessionCheckpointInput,
5
+ } from "./checkpoint.ts";
6
+ import { canonicalizeJson, sha256CanonicalJson } from "./integrity.ts";
7
+ import {
8
+ validateTranscriptRecord,
9
+ type InternalSessionDescriptor,
10
+ type InternalSessionHistoryEntry,
11
+ type TranscriptCheckpointRecord,
12
+ type TranscriptOperationRecord,
13
+ type TranscriptTransitionRecord,
14
+ } from "./records.ts";
15
+
16
+ export type TranscriptStructuralRecord =
17
+ | TranscriptCheckpointRecord
18
+ | TranscriptOperationRecord
19
+ | TranscriptTransitionRecord;
20
+
21
+ export interface TranscriptHistoryReduction {
22
+ readonly entries: readonly InternalSessionHistoryEntry[];
23
+ readonly revision: number;
24
+ readonly digest: string;
25
+ }
26
+
27
+ export type SessionRecoveryStatus =
28
+ | { readonly kind: "clean" }
29
+ | {
30
+ readonly kind: "uncertain";
31
+ readonly operationId: string;
32
+ readonly boundary:
33
+ | "started_without_terminal"
34
+ | "terminal_without_checkpoint"
35
+ | "in_flight_checkpoint";
36
+ };
37
+
38
+ export type PersistenceRepair =
39
+ | {
40
+ readonly kind: "aborted_checkpoint_rebuilt";
41
+ readonly operationId: string;
42
+ readonly stateRevision: number;
43
+ }
44
+ | {
45
+ readonly kind: "activation_checkpoint_rebuilt";
46
+ readonly transitionId: string;
47
+ readonly stateRevision: number;
48
+ }
49
+ | {
50
+ readonly kind: "registry_projection_repaired";
51
+ readonly fromRevision: number;
52
+ readonly toRevision: number;
53
+ };
54
+
55
+ export interface TranscriptReductionResult {
56
+ readonly checkpoint: AgentSessionCheckpoint;
57
+ readonly internalSessionHistory: readonly InternalSessionHistoryEntry[];
58
+ readonly recovery: SessionRecoveryStatus;
59
+ readonly repairs: readonly PersistenceRepair[];
60
+ }
61
+
62
+ export class TranscriptReductionError extends Error {
63
+ constructor(message: string, options?: ErrorOptions) {
64
+ super(message, options);
65
+ this.name = "TranscriptReductionError";
66
+ }
67
+ }
68
+
69
+ const EMPTY_HISTORY_DIGEST = sha256CanonicalJson([]);
70
+
71
+ export function reduceTranscriptHistory(
72
+ activationsThroughCheckpoint: Iterable<TranscriptTransitionRecord>,
73
+ ): TranscriptHistoryReduction {
74
+ const entries: InternalSessionHistoryEntry[] = [];
75
+ let previousSequence = 0;
76
+ let identity: { agentSessionId: string; transcriptId: string; generation: number } | null = null;
77
+ let previousTarget: InternalSessionDescriptor | null = null;
78
+ const transitionIds = new Set<string>();
79
+ for (const record of activationsThroughCheckpoint) {
80
+ validateStructuralRecord(record);
81
+ if (record.event !== "target_activated") {
82
+ throw new TranscriptReductionError("history fold accepts only target_activated records");
83
+ }
84
+ if (record.seq <= previousSequence) {
85
+ throw new TranscriptReductionError("history activation records must be strictly sequence ordered");
86
+ }
87
+ if (!identity) {
88
+ identity = {
89
+ agentSessionId: record.agentSessionId,
90
+ transcriptId: record.transcriptId,
91
+ generation: record.generation,
92
+ };
93
+ } else if (record.agentSessionId !== identity.agentSessionId
94
+ || record.transcriptId !== identity.transcriptId
95
+ || record.generation !== identity.generation) {
96
+ throw new TranscriptReductionError("history activation identity changed within one fold");
97
+ }
98
+ if (previousTarget && canonicalizeJson(record.from) !== canonicalizeJson(previousTarget)) {
99
+ throw new TranscriptReductionError("history activation chain has a routing gap");
100
+ }
101
+ if (transitionIds.has(record.transitionId)) {
102
+ throw new TranscriptReductionError(`transition ${record.transitionId} was activated more than once`);
103
+ }
104
+ transitionIds.add(record.transitionId);
105
+ previousSequence = record.seq;
106
+ if (record.historyEntry) entries.push(structuredClone(record.historyEntry));
107
+ previousTarget = structuredClone(record.to!);
108
+ }
109
+ return historyResult(entries);
110
+ }
111
+
112
+ /** Apply the same canonical revision/digest algorithm to a registry or runtime history. */
113
+ export function reduceInternalSessionHistory(
114
+ entries: readonly InternalSessionHistoryEntry[],
115
+ ): TranscriptHistoryReduction {
116
+ return historyResult(entries);
117
+ }
118
+
119
+ export function reduceTranscriptState(
120
+ selectedCheckpointRecord: TranscriptCheckpointRecord,
121
+ historyThroughCheckpoint: TranscriptHistoryReduction,
122
+ structuralTailAfterCheckpointRecord: readonly TranscriptStructuralRecord[],
123
+ ): TranscriptReductionResult {
124
+ validateStructuralRecord(selectedCheckpointRecord);
125
+ const selectedTranscript = selectedCheckpointRecord.checkpoint.transcript;
126
+ if (!selectedTranscript) throw new TranscriptReductionError("selected transcript checkpoint has no transcript identity");
127
+ const validatedHistory = historyResult(historyThroughCheckpoint.entries);
128
+ if (historyThroughCheckpoint.revision !== validatedHistory.revision
129
+ || historyThroughCheckpoint.digest !== validatedHistory.digest) {
130
+ throw new TranscriptReductionError("supplied history reduction is internally inconsistent");
131
+ }
132
+ assertHistoryMatches(selectedCheckpointRecord.checkpoint, validatedHistory);
133
+
134
+ let checkpoint = structuredClone(selectedCheckpointRecord.checkpoint);
135
+ let history = validatedHistory.entries.map((entry) => structuredClone(entry));
136
+ let previousSequence = selectedCheckpointRecord.seq;
137
+ let active: ActiveOperation | null = checkpoint.boundary.status === "in_flight"
138
+ ? {
139
+ operationId: checkpoint.boundary.interruptedOperationId,
140
+ checkpointed: true,
141
+ terminal: null,
142
+ terminalSequence: null,
143
+ }
144
+ : null;
145
+ let pendingRepair: PendingRepair | null = null;
146
+ const activatedTransitions = new Set(history.map((entry) => entry.transition.transitionId));
147
+
148
+ for (const record of structuralTailAfterCheckpointRecord) {
149
+ validateStructuralRecord(record);
150
+ assertTailIdentity(record, selectedCheckpointRecord);
151
+ if (record.seq <= previousSequence) {
152
+ throw new TranscriptReductionError("structural tail must be strictly sequence ordered after the selected checkpoint record");
153
+ }
154
+ previousSequence = record.seq;
155
+
156
+ if (record.t === "operation") {
157
+ if (pendingRepair) {
158
+ throw new TranscriptReductionError("a deterministic repair must be materialized before another operation boundary");
159
+ }
160
+ if (record.event === "started") {
161
+ if (active) throw new TranscriptReductionError("a second operation started before the prior operation was checkpointed");
162
+ checkpoint = deriveStartedCheckpoint(checkpoint, record);
163
+ active = { operationId: record.operationId, checkpointed: false, terminal: null, terminalSequence: null };
164
+ continue;
165
+ }
166
+ if (!active || active.operationId !== record.operationId) {
167
+ throw new TranscriptReductionError(`terminal operation ${record.operationId} has no matching active operation`);
168
+ }
169
+ if (active.terminal) throw new TranscriptReductionError(`operation ${record.operationId} has more than one terminal record`);
170
+ if (record.event === "aborted") {
171
+ checkpoint = deriveAbortedCheckpoint(checkpoint, record);
172
+ pendingRepair = {
173
+ checkpoint,
174
+ repair: {
175
+ kind: "aborted_checkpoint_rebuilt",
176
+ operationId: record.operationId,
177
+ stateRevision: checkpoint.stateRevision,
178
+ },
179
+ };
180
+ active = null;
181
+ } else {
182
+ active.terminal = record.event;
183
+ active.terminalSequence = record.seq;
184
+ }
185
+ continue;
186
+ }
187
+
188
+ if (record.t === "transition") {
189
+ if (record.event !== "target_activated") continue;
190
+ if (active) throw new TranscriptReductionError("a transition target cannot activate during an uncheckpointed operation boundary");
191
+ if (pendingRepair) throw new TranscriptReductionError("a transition target cannot activate before a prior repair is materialized");
192
+ if (activatedTransitions.has(record.transitionId)) {
193
+ throw new TranscriptReductionError(`transition ${record.transitionId} was activated more than once in the structural tail`);
194
+ }
195
+ activatedTransitions.add(record.transitionId);
196
+ assertDescriptorMatchesCheckpoint(record.from, checkpoint);
197
+ if (record.historyEntry) history.push(structuredClone(record.historyEntry));
198
+ checkpoint = deriveActivationCheckpoint(checkpoint, record, historyResult(history));
199
+ pendingRepair = {
200
+ checkpoint,
201
+ repair: {
202
+ kind: "activation_checkpoint_rebuilt",
203
+ transitionId: record.transitionId,
204
+ stateRevision: checkpoint.stateRevision,
205
+ },
206
+ };
207
+ continue;
208
+ }
209
+
210
+ const candidate = record.checkpoint;
211
+ assertCheckpointIdentityStable(candidate, selectedCheckpointRecord.checkpoint);
212
+ const candidateHistory = historyResult(history);
213
+ assertHistoryMatches(candidate, candidateHistory);
214
+ if (candidate.stateRevision < checkpoint.stateRevision) {
215
+ throw new TranscriptReductionError("checkpoint stateRevision regressed");
216
+ }
217
+ const expectedRepair = pendingRepair;
218
+ if (pendingRepair) {
219
+ if (canonicalizeJson(candidate) !== canonicalizeJson(pendingRepair.checkpoint)) {
220
+ throw new TranscriptReductionError("materialized checkpoint disagrees with deterministic reduction");
221
+ }
222
+ pendingRepair = null;
223
+ }
224
+ if (!expectedRepair) assertRoutingStable(candidate, checkpoint);
225
+ if (active) {
226
+ if (active.terminal) {
227
+ if (candidate.stateRevision <= checkpoint.stateRevision) {
228
+ throw new TranscriptReductionError("terminal operation checkpoint must advance stateRevision");
229
+ }
230
+ assertTerminalCheckpoint(candidate, active);
231
+ active = null;
232
+ } else {
233
+ assertInFlightCheckpoint(candidate, active.operationId);
234
+ if (!active.checkpointed && canonicalizeJson(candidate) !== canonicalizeJson(checkpoint)) {
235
+ throw new TranscriptReductionError("materialized in-flight checkpoint disagrees with started-operation reduction");
236
+ }
237
+ active.checkpointed = true;
238
+ }
239
+ } else if (!pendingRepair && candidate.stateRevision === checkpoint.stateRevision
240
+ && canonicalizeJson(candidate) !== canonicalizeJson(checkpoint)) {
241
+ throw new TranscriptReductionError("same-revision checkpoints disagree");
242
+ }
243
+ checkpoint = structuredClone(candidate);
244
+ }
245
+
246
+ const repairs = pendingRepair ? [pendingRepair.repair] : [];
247
+ return {
248
+ checkpoint,
249
+ internalSessionHistory: history,
250
+ recovery: recoveryStatus(checkpoint, active),
251
+ repairs,
252
+ };
253
+ }
254
+
255
+ interface ActiveOperation {
256
+ operationId: string;
257
+ checkpointed: boolean;
258
+ terminal: Exclude<TranscriptOperationRecord["event"], "started" | "aborted"> | null;
259
+ terminalSequence: number | null;
260
+ }
261
+
262
+ interface PendingRepair {
263
+ checkpoint: AgentSessionCheckpoint;
264
+ repair: Extract<PersistenceRepair, { kind: "aborted_checkpoint_rebuilt" | "activation_checkpoint_rebuilt" }>;
265
+ }
266
+
267
+ function deriveStartedCheckpoint(
268
+ previous: AgentSessionCheckpoint,
269
+ record: TranscriptOperationRecord,
270
+ ): AgentSessionCheckpoint {
271
+ if (record.stateRevision !== previous.stateRevision + 1) {
272
+ throw new TranscriptReductionError("started operation stateRevision must follow the preceding checkpoint");
273
+ }
274
+ return rebuildCheckpoint(previous, {
275
+ stateRevision: record.stateRevision,
276
+ updatedAt: timestampToIso(record.ts),
277
+ transcript: withCoveredSequence(previous, record.seq),
278
+ boundary: {
279
+ status: "in_flight",
280
+ lastSettledOperationId: previous.boundary.lastSettledOperationId,
281
+ interruptedOperationId: record.operationId,
282
+ cause: "operation_started",
283
+ },
284
+ });
285
+ }
286
+
287
+ function deriveAbortedCheckpoint(
288
+ previous: AgentSessionCheckpoint,
289
+ record: TranscriptOperationRecord,
290
+ ): AgentSessionCheckpoint {
291
+ if (record.stateRevision !== previous.stateRevision + 1) {
292
+ throw new TranscriptReductionError("aborted operation stateRevision must follow the preceding reduced checkpoint");
293
+ }
294
+ return rebuildCheckpoint(previous, {
295
+ stateRevision: record.stateRevision,
296
+ updatedAt: timestampToIso(record.ts),
297
+ transcript: withCoveredSequence(previous, record.seq),
298
+ boundary: { status: "settled", lastSettledOperationId: record.operationId },
299
+ });
300
+ }
301
+
302
+ function deriveActivationCheckpoint(
303
+ previous: AgentSessionCheckpoint,
304
+ record: TranscriptTransitionRecord,
305
+ reducedHistory: TranscriptHistoryReduction,
306
+ ): AgentSessionCheckpoint {
307
+ if (!record.to || !record.activationState) {
308
+ throw new TranscriptReductionError("target activation lacks its deterministic state");
309
+ }
310
+ if (record.activationState.resultingStateRevision !== previous.stateRevision + 1) {
311
+ throw new TranscriptReductionError("target activation stateRevision must follow the preceding checkpoint");
312
+ }
313
+ return rebuildCheckpoint(previous, {
314
+ stateRevision: record.activationState.resultingStateRevision,
315
+ adapterId: record.to.adapterId,
316
+ mode: record.to.mode,
317
+ internalSessionId: record.to.internalSessionId,
318
+ internalSessionActivatedAt: record.to.activatedAt,
319
+ internalSessionHistoryRevision: reducedHistory.revision,
320
+ internalSessionHistoryDigest: reducedHistory.digest,
321
+ lastTransition: {
322
+ transitionId: record.transitionId,
323
+ kind: record.kind,
324
+ at: record.activationState.transitionAt,
325
+ },
326
+ model: record.to.model,
327
+ sessionConfiguration: record.to.sessionConfiguration,
328
+ protocol: record.to.protocol,
329
+ transcript: withCoveredSequence(previous, record.seq),
330
+ boundary: record.activationState.boundary,
331
+ updatedAt: record.activationState.updatedAt,
332
+ });
333
+ }
334
+
335
+ function rebuildCheckpoint(
336
+ previous: AgentSessionCheckpoint,
337
+ changes: Partial<AgentSessionCheckpointInput>,
338
+ ): AgentSessionCheckpoint {
339
+ const { version: _version, digest: _digest, ...body } = previous;
340
+ return createAgentSessionCheckpoint({ ...body, ...structuredClone(changes) });
341
+ }
342
+
343
+ function withCoveredSequence(previous: AgentSessionCheckpoint, coveredSequence: number) {
344
+ if (!previous.transcript) throw new TranscriptReductionError("cannot reduce transcript state without transcript identity");
345
+ return { ...previous.transcript, coveredSequence };
346
+ }
347
+
348
+ function assertHistoryMatches(
349
+ checkpoint: AgentSessionCheckpoint,
350
+ history: TranscriptHistoryReduction,
351
+ ): void {
352
+ if (checkpoint.internalSessionHistoryRevision !== history.revision
353
+ || checkpoint.internalSessionHistoryDigest !== history.digest) {
354
+ throw new TranscriptReductionError("checkpoint history revision or digest disagrees with canonical transition history");
355
+ }
356
+ }
357
+
358
+ function historyResult(entries: readonly InternalSessionHistoryEntry[]): TranscriptHistoryReduction {
359
+ const detached = entries.map((entry) => structuredClone(entry));
360
+ return {
361
+ entries: detached,
362
+ revision: detached.length,
363
+ digest: detached.length === 0 ? EMPTY_HISTORY_DIGEST : sha256CanonicalJson(detached),
364
+ };
365
+ }
366
+
367
+ function assertDescriptorMatchesCheckpoint(
368
+ descriptor: InternalSessionDescriptor | null,
369
+ checkpoint: AgentSessionCheckpoint,
370
+ ): void {
371
+ const current: InternalSessionDescriptor = {
372
+ internalSessionId: checkpoint.internalSessionId,
373
+ adapterId: checkpoint.adapterId,
374
+ mode: checkpoint.mode,
375
+ model: checkpoint.model,
376
+ sessionConfiguration: checkpoint.sessionConfiguration,
377
+ activatedAt: checkpoint.internalSessionActivatedAt,
378
+ protocol: checkpoint.protocol,
379
+ };
380
+ if (descriptor === null) {
381
+ if (checkpoint.internalSessionId === null) return;
382
+ throw new TranscriptReductionError("transition from descriptor is absent for a current internal session");
383
+ }
384
+ if (canonicalizeJson(descriptor) !== canonicalizeJson(current)) {
385
+ throw new TranscriptReductionError("transition from descriptor disagrees with current reduced state");
386
+ }
387
+ }
388
+
389
+ function assertTerminalCheckpoint(checkpoint: AgentSessionCheckpoint, active: ActiveOperation): void {
390
+ if (active.terminalSequence === null || checkpoint.transcript?.coveredSequence !== active.terminalSequence) {
391
+ throw new TranscriptReductionError("terminal operation checkpoint must cover its terminal record");
392
+ }
393
+ if (checkpoint.boundary.status === "settled") {
394
+ if (checkpoint.boundary.lastSettledOperationId !== active.operationId) {
395
+ throw new TranscriptReductionError("settled terminal checkpoint does not name the operation");
396
+ }
397
+ } else if (checkpoint.boundary.interruptedOperationId !== active.operationId) {
398
+ throw new TranscriptReductionError("terminal in-flight checkpoint names another operation");
399
+ }
400
+ }
401
+
402
+ function assertInFlightCheckpoint(checkpoint: AgentSessionCheckpoint, operationId: string): void {
403
+ if (checkpoint.boundary.status !== "in_flight"
404
+ || checkpoint.boundary.interruptedOperationId !== operationId) {
405
+ throw new TranscriptReductionError("checkpoint after a started operation must preserve its in-flight boundary");
406
+ }
407
+ }
408
+
409
+ function assertCheckpointIdentityStable(
410
+ candidate: AgentSessionCheckpoint,
411
+ selected: AgentSessionCheckpoint,
412
+ ): void {
413
+ if (candidate.agentSessionId !== selected.agentSessionId
414
+ || candidate.incarnationId !== selected.incarnationId
415
+ || candidate.transcript?.transcriptId !== selected.transcript?.transcriptId
416
+ || candidate.transcript?.generation !== selected.transcript?.generation
417
+ || candidate.transcript?.path !== selected.transcript?.path) {
418
+ throw new TranscriptReductionError("checkpoint identity changed within one transcript generation");
419
+ }
420
+ }
421
+
422
+ function assertRoutingStable(
423
+ candidate: AgentSessionCheckpoint,
424
+ previous: AgentSessionCheckpoint,
425
+ ): void {
426
+ const candidateRouting = {
427
+ adapterId: candidate.adapterId,
428
+ mode: candidate.mode,
429
+ internalSessionId: candidate.internalSessionId,
430
+ internalSessionActivatedAt: candidate.internalSessionActivatedAt,
431
+ protocol: candidate.protocol,
432
+ lastTransition: candidate.lastTransition ?? null,
433
+ };
434
+ const previousRouting = {
435
+ adapterId: previous.adapterId,
436
+ mode: previous.mode,
437
+ internalSessionId: previous.internalSessionId,
438
+ internalSessionActivatedAt: previous.internalSessionActivatedAt,
439
+ protocol: previous.protocol,
440
+ lastTransition: previous.lastTransition ?? null,
441
+ };
442
+ if (canonicalizeJson(candidateRouting) !== canonicalizeJson(previousRouting)) {
443
+ throw new TranscriptReductionError("checkpoint changed routing without a target activation record");
444
+ }
445
+ }
446
+
447
+ function recoveryStatus(
448
+ checkpoint: AgentSessionCheckpoint,
449
+ active: ActiveOperation | null,
450
+ ): SessionRecoveryStatus {
451
+ if (active?.terminal) {
452
+ return { kind: "uncertain", operationId: active.operationId, boundary: "terminal_without_checkpoint" };
453
+ }
454
+ if (active) {
455
+ return {
456
+ kind: "uncertain",
457
+ operationId: active.operationId,
458
+ boundary: active.checkpointed ? "in_flight_checkpoint" : "started_without_terminal",
459
+ };
460
+ }
461
+ if (checkpoint.boundary.status === "in_flight") {
462
+ return {
463
+ kind: "uncertain",
464
+ operationId: checkpoint.boundary.interruptedOperationId,
465
+ boundary: "in_flight_checkpoint",
466
+ };
467
+ }
468
+ return { kind: "clean" };
469
+ }
470
+
471
+ function assertTailIdentity(
472
+ record: TranscriptStructuralRecord,
473
+ selected: TranscriptCheckpointRecord,
474
+ ): void {
475
+ if (record.agentSessionId !== selected.agentSessionId
476
+ || record.transcriptId !== selected.transcriptId
477
+ || record.generation !== selected.generation) {
478
+ throw new TranscriptReductionError("structural tail identity disagrees with the selected checkpoint record");
479
+ }
480
+ }
481
+
482
+ function validateStructuralRecord(record: TranscriptStructuralRecord): void {
483
+ try {
484
+ validateTranscriptRecord(record);
485
+ } catch (error) {
486
+ throw new TranscriptReductionError("invalid structural transcript record", { cause: error });
487
+ }
488
+ }
489
+
490
+ function timestampToIso(value: number): string {
491
+ try {
492
+ return new Date(value).toISOString();
493
+ } catch (error) {
494
+ throw new TranscriptReductionError("operation timestamp is outside the ECMAScript ISO range", { cause: error });
495
+ }
496
+ }
497
+
498
+ export { EMPTY_HISTORY_DIGEST };