open-multi-agent-kit 0.90.7 → 0.90.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +17 -10
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +5 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/commands/doctor-provider-cli.d.ts +33 -0
- package/dist/commands/doctor-provider-cli.d.ts.map +1 -0
- package/dist/commands/doctor-provider-cli.js +215 -0
- package/dist/commands/doctor-provider-cli.js.map +1 -0
- package/dist/commands/doctor-provider-transport.d.ts +35 -0
- package/dist/commands/doctor-provider-transport.d.ts.map +1 -0
- package/dist/commands/doctor-provider-transport.js +185 -0
- package/dist/commands/doctor-provider-transport.js.map +1 -0
- package/dist/commands/doctor-provider.d.ts +121 -7
- package/dist/commands/doctor-provider.d.ts.map +1 -1
- package/dist/commands/doctor-provider.js +1295 -102
- package/dist/commands/doctor-provider.js.map +1 -1
- package/dist/commands/session-doctor-cli.d.ts +43 -0
- package/dist/commands/session-doctor-cli.d.ts.map +1 -0
- package/dist/commands/session-doctor-cli.js +494 -0
- package/dist/commands/session-doctor-cli.js.map +1 -0
- package/dist/commands/verify-ci.d.ts +21 -0
- package/dist/commands/verify-ci.d.ts.map +1 -0
- package/dist/commands/verify-ci.js +66 -0
- package/dist/commands/verify-ci.js.map +1 -0
- package/dist/core/agent-session-services.d.ts +3 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +3 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +116 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1015 -71
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/agent-tool-settings.d.ts +35 -0
- package/dist/core/agent-tool-settings.d.ts.map +1 -0
- package/dist/core/agent-tool-settings.js +155 -0
- package/dist/core/agent-tool-settings.js.map +1 -0
- package/dist/core/atomic-session-file.d.ts +14 -0
- package/dist/core/atomic-session-file.d.ts.map +1 -0
- package/dist/core/atomic-session-file.js +104 -0
- package/dist/core/atomic-session-file.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +6 -0
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +12 -1
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/hysteresis.d.ts +27 -0
- package/dist/core/compaction/hysteresis.d.ts.map +1 -0
- package/dist/core/compaction/hysteresis.js +84 -0
- package/dist/core/compaction/hysteresis.js.map +1 -0
- package/dist/core/compaction/index.d.ts +2 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +2 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/transaction.d.ts +172 -0
- package/dist/core/compaction/transaction.d.ts.map +1 -0
- package/dist/core/compaction/transaction.js +824 -0
- package/dist/core/compaction/transaction.js.map +1 -0
- package/dist/core/context-budget-governor-v2.d.ts +2 -1
- package/dist/core/context-budget-governor-v2.d.ts.map +1 -1
- package/dist/core/context-budget-governor-v2.js +2 -1
- package/dist/core/context-budget-governor-v2.js.map +1 -1
- package/dist/core/context-budget-headroom.d.ts.map +1 -1
- package/dist/core/context-budget-headroom.js +5 -1
- package/dist/core/context-budget-headroom.js.map +1 -1
- package/dist/core/context-budget-reserved-tokens.d.ts +110 -0
- package/dist/core/context-budget-reserved-tokens.d.ts.map +1 -0
- package/dist/core/context-budget-reserved-tokens.js +188 -0
- package/dist/core/context-budget-reserved-tokens.js.map +1 -0
- package/dist/core/context-budget-v2-cache-invalidation.d.ts +133 -0
- package/dist/core/context-budget-v2-cache-invalidation.d.ts.map +1 -0
- package/dist/core/context-budget-v2-cache-invalidation.js +452 -0
- package/dist/core/context-budget-v2-cache-invalidation.js.map +1 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts +3 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-keys.js +6 -0
- package/dist/core/context-budget-v2-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.d.ts +8 -2
- package/dist/core/context-budget-v2-cache-provider.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-provider.js +28 -5
- package/dist/core/context-budget-v2-cache-provider.js.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.js +1 -0
- package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +1 -0
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
- package/dist/core/context-budget-v2-selection.js +9 -0
- package/dist/core/context-budget-v2-selection.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +4 -0
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/durable-file-directory.d.ts +4 -0
- package/dist/core/durable-file-directory.d.ts.map +1 -0
- package/dist/core/durable-file-directory.js +76 -0
- package/dist/core/durable-file-directory.js.map +1 -0
- package/dist/core/durable-file-identity.d.ts +26 -0
- package/dist/core/durable-file-identity.d.ts.map +1 -0
- package/dist/core/durable-file-identity.js +118 -0
- package/dist/core/durable-file-identity.js.map +1 -0
- package/dist/core/durable-file-io.d.ts +29 -0
- package/dist/core/durable-file-io.d.ts.map +1 -0
- package/dist/core/durable-file-io.js +179 -0
- package/dist/core/durable-file-io.js.map +1 -0
- package/dist/core/durable-file-lock-cleanup.d.ts +12 -0
- package/dist/core/durable-file-lock-cleanup.d.ts.map +1 -0
- package/dist/core/durable-file-lock-cleanup.js +39 -0
- package/dist/core/durable-file-lock-cleanup.js.map +1 -0
- package/dist/core/durable-file-lock-owner.d.ts +18 -0
- package/dist/core/durable-file-lock-owner.d.ts.map +1 -0
- package/dist/core/durable-file-lock-owner.js +78 -0
- package/dist/core/durable-file-lock-owner.js.map +1 -0
- package/dist/core/durable-file-lock-storage.d.ts +35 -0
- package/dist/core/durable-file-lock-storage.d.ts.map +1 -0
- package/dist/core/durable-file-lock-storage.js +263 -0
- package/dist/core/durable-file-lock-storage.js.map +1 -0
- package/dist/core/durable-file-mode.d.ts +8 -0
- package/dist/core/durable-file-mode.d.ts.map +1 -0
- package/dist/core/durable-file-mode.js +41 -0
- package/dist/core/durable-file-mode.js.map +1 -0
- package/dist/core/extensions/loader.d.ts +12 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +50 -37
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/index.d.ts +6 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +5 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/loop-gates.d.ts.map +1 -1
- package/dist/core/loop-gates.js +25 -1
- package/dist/core/loop-gates.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/pi-package-intake.d.ts +1 -0
- package/dist/core/pi-package-intake.d.ts.map +1 -1
- package/dist/core/pi-package-intake.js +7 -0
- package/dist/core/pi-package-intake.js.map +1 -1
- package/dist/core/redaction.d.ts +8 -0
- package/dist/core/redaction.d.ts.map +1 -0
- package/dist/core/redaction.js +31 -0
- package/dist/core/redaction.js.map +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +36 -0
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-journal-store.d.ts +53 -0
- package/dist/core/run-journal-store.d.ts.map +1 -0
- package/dist/core/run-journal-store.js +278 -0
- package/dist/core/run-journal-store.js.map +1 -0
- package/dist/core/run-journal.d.ts +172 -0
- package/dist/core/run-journal.d.ts.map +1 -0
- package/dist/core/run-journal.js +1053 -0
- package/dist/core/run-journal.js.map +1 -0
- package/dist/core/sdk.d.ts +7 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +94 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-doctor-plan.d.ts +128 -0
- package/dist/core/session-doctor-plan.d.ts.map +1 -0
- package/dist/core/session-doctor-plan.js +833 -0
- package/dist/core/session-doctor-plan.js.map +1 -0
- package/dist/core/session-file-compaction.d.ts +6 -0
- package/dist/core/session-file-compaction.d.ts.map +1 -0
- package/dist/core/session-file-compaction.js +169 -0
- package/dist/core/session-file-compaction.js.map +1 -0
- package/dist/core/session-file-head.d.ts +10 -0
- package/dist/core/session-file-head.d.ts.map +1 -0
- package/dist/core/session-file-head.js +78 -0
- package/dist/core/session-file-head.js.map +1 -0
- package/dist/core/session-file-persistence.d.ts +30 -0
- package/dist/core/session-file-persistence.d.ts.map +1 -0
- package/dist/core/session-file-persistence.js +106 -0
- package/dist/core/session-file-persistence.js.map +1 -0
- package/dist/core/session-integrity.d.ts +43 -0
- package/dist/core/session-integrity.d.ts.map +1 -0
- package/dist/core/session-integrity.js +420 -0
- package/dist/core/session-integrity.js.map +1 -0
- package/dist/core/session-manager.d.ts +24 -4
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +242 -125
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-owner-lease.d.ts +22 -0
- package/dist/core/session-owner-lease.d.ts.map +1 -0
- package/dist/core/session-owner-lease.js +176 -0
- package/dist/core/session-owner-lease.js.map +1 -0
- package/dist/core/session-path-policy.d.ts +132 -0
- package/dist/core/session-path-policy.d.ts.map +1 -0
- package/dist/core/session-path-policy.js +780 -0
- package/dist/core/session-path-policy.js.map +1 -0
- package/dist/core/session-repair-plan.d.ts +49 -0
- package/dist/core/session-repair-plan.d.ts.map +1 -0
- package/dist/core/session-repair-plan.js +202 -0
- package/dist/core/session-repair-plan.js.map +1 -0
- package/dist/core/session-termination.d.ts +100 -0
- package/dist/core/session-termination.d.ts.map +1 -0
- package/dist/core/session-termination.js +403 -0
- package/dist/core/session-termination.js.map +1 -0
- package/dist/core/settings-manager.d.ts +32 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +52 -5
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/verified-bash-adapter.d.ts +36 -0
- package/dist/core/verified-bash-adapter.d.ts.map +1 -0
- package/dist/core/verified-bash-adapter.js +90 -0
- package/dist/core/verified-bash-adapter.js.map +1 -0
- package/dist/guardrails/command-redaction.d.ts +32 -0
- package/dist/guardrails/command-redaction.d.ts.map +1 -0
- package/dist/guardrails/command-redaction.js +776 -0
- package/dist/guardrails/command-redaction.js.map +1 -0
- package/dist/guardrails/evidence-attestation.d.ts +31 -0
- package/dist/guardrails/evidence-attestation.d.ts.map +1 -0
- package/dist/guardrails/evidence-attestation.js +178 -0
- package/dist/guardrails/evidence-attestation.js.map +1 -0
- package/dist/guardrails/evidence-receipt-store.d.ts +33 -0
- package/dist/guardrails/evidence-receipt-store.d.ts.map +1 -0
- package/dist/guardrails/evidence-receipt-store.js +446 -0
- package/dist/guardrails/evidence-receipt-store.js.map +1 -0
- package/dist/guardrails/evidence-receipt.d.ts +58 -0
- package/dist/guardrails/evidence-receipt.d.ts.map +1 -0
- package/dist/guardrails/evidence-receipt.js +389 -0
- package/dist/guardrails/evidence-receipt.js.map +1 -0
- package/dist/guardrails/evidence-system.d.ts +40 -9
- package/dist/guardrails/evidence-system.d.ts.map +1 -1
- package/dist/guardrails/evidence-system.js +379 -83
- package/dist/guardrails/evidence-system.js.map +1 -1
- package/dist/guardrails/replay-ledger-io.d.ts +6 -0
- package/dist/guardrails/replay-ledger-io.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-io.js +42 -0
- package/dist/guardrails/replay-ledger-io.js.map +1 -0
- package/dist/guardrails/replay-ledger-lock-owner.d.ts +32 -0
- package/dist/guardrails/replay-ledger-lock-owner.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-lock-owner.js +138 -0
- package/dist/guardrails/replay-ledger-lock-owner.js.map +1 -0
- package/dist/guardrails/replay-ledger-lock.d.ts +24 -0
- package/dist/guardrails/replay-ledger-lock.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-lock.js +135 -0
- package/dist/guardrails/replay-ledger-lock.js.map +1 -0
- package/dist/guardrails/replay-ledger-mutation-gate.d.ts +24 -0
- package/dist/guardrails/replay-ledger-mutation-gate.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-mutation-gate.js +205 -0
- package/dist/guardrails/replay-ledger-mutation-gate.js.map +1 -0
- package/dist/guardrails/replay-ledger-quarantine.d.ts +2 -0
- package/dist/guardrails/replay-ledger-quarantine.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-quarantine.js +19 -0
- package/dist/guardrails/replay-ledger-quarantine.js.map +1 -0
- package/dist/guardrails/replay-ledger-store.d.ts +32 -0
- package/dist/guardrails/replay-ledger-store.d.ts.map +1 -0
- package/dist/guardrails/replay-ledger-store.js +211 -0
- package/dist/guardrails/replay-ledger-store.js.map +1 -0
- package/dist/guardrails/shell-command-name-glob.d.ts +3 -0
- package/dist/guardrails/shell-command-name-glob.d.ts.map +1 -0
- package/dist/guardrails/shell-command-name-glob.js +233 -0
- package/dist/guardrails/shell-command-name-glob.js.map +1 -0
- package/dist/guardrails/shell-command-option.d.ts +7 -0
- package/dist/guardrails/shell-command-option.d.ts.map +1 -0
- package/dist/guardrails/shell-command-option.js +24 -0
- package/dist/guardrails/shell-command-option.js.map +1 -0
- package/dist/guardrails/shell-command-tokenizer.d.ts +29 -0
- package/dist/guardrails/shell-command-tokenizer.d.ts.map +1 -0
- package/dist/guardrails/shell-command-tokenizer.js +145 -0
- package/dist/guardrails/shell-command-tokenizer.js.map +1 -0
- package/dist/guardrails/shell-command-wrapper.d.ts +18 -0
- package/dist/guardrails/shell-command-wrapper.d.ts.map +1 -0
- package/dist/guardrails/shell-command-wrapper.js +42 -0
- package/dist/guardrails/shell-command-wrapper.js.map +1 -0
- package/dist/guardrails/verified-executor.d.ts +65 -0
- package/dist/guardrails/verified-executor.d.ts.map +1 -0
- package/dist/guardrails/verified-executor.js +171 -0
- package/dist/guardrails/verified-executor.js.map +1 -0
- package/dist/guardrails/workspace-fingerprint.d.ts +23 -0
- package/dist/guardrails/workspace-fingerprint.d.ts.map +1 -0
- package/dist/guardrails/workspace-fingerprint.js +634 -0
- package/dist/guardrails/workspace-fingerprint.js.map +1 -0
- package/dist/index.d.ts +15 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +12 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.d.ts.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.js +1 -1
- package/dist/modes/interactive/components/control-panel-layout.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +1 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +59 -9
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +43 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +23 -5
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +3 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/types/evidence.d.ts +215 -1
- package/dist/types/evidence.d.ts.map +1 -1
- package/dist/types/evidence.js.map +1 -1
- package/dist/verify-ci.d.ts +3 -0
- package/dist/verify-ci.d.ts.map +1 -0
- package/dist/verify-ci.js +30 -0
- package/dist/verify-ci.js.map +1 -0
- package/docs/compaction.md +44 -4
- package/docs/extensions.md +2 -0
- package/docs/providers.md +6 -0
- package/docs/sdk.md +238 -1
- package/docs/settings.md +67 -4
- package/docs/usage.md +38 -0
- package/examples/extensions/correctness-wall/README.md +6 -6
- package/examples/extensions/correctness-wall/index.ts +37 -11
- package/examples/extensions/custom-provider-anthropic/package-lock.json +5 -5
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +4 -4
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { atomicRewriteFileSync } from "./atomic-session-file.js";
|
|
3
|
+
import { acquireDurableFileMutationLockSync } from "./durable-file-identity.js";
|
|
4
|
+
import { appendFileDurablySync, readDurableFileSnapshot, sameDurableFileGeneration, writeExclusiveFileDurablySync, } from "./durable-file-io.js";
|
|
5
|
+
import { inspectRunJournal, RunJournal, serializeRunJournalLine, } from "./run-journal.js";
|
|
6
|
+
import { assertSessionOwnerRecoveryAllowedUnlockedSync, sessionPathFromPersistenceArtifact, } from "./session-owner-lease.js";
|
|
7
|
+
import { classifySessionTermination } from "./session-termination.js";
|
|
8
|
+
export class RunJournalStoreCorruptionError extends Error {
|
|
9
|
+
name = "RunJournalStoreCorruptionError";
|
|
10
|
+
}
|
|
11
|
+
export class RunJournalStoreStaleWriteError extends Error {
|
|
12
|
+
constructor() {
|
|
13
|
+
super("Run journal changed since this store accepted its durable head");
|
|
14
|
+
this.name = "RunJournalStoreStaleWriteError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Append one complete JSONL record and fsync it without truncation rollback. */
|
|
18
|
+
export const appendRunJournalRecordDurably = (path, line) => appendFileDurablySync(path, Buffer.from(line, "utf8"));
|
|
19
|
+
export const writeQuarantineBytesDurably = writeExclusiveFileDurablySync;
|
|
20
|
+
function readDurableHead(path, hashFn) {
|
|
21
|
+
const snapshot = readDurableFileSnapshot(path);
|
|
22
|
+
if (!snapshot)
|
|
23
|
+
return { size: 0, lastSeq: 0, lastHash: null, generation: null };
|
|
24
|
+
const report = inspectRunJournal(snapshot.bytes, hashFn);
|
|
25
|
+
const hardFindings = report.findings.filter((finding) => finding.code !== "run_unclosed");
|
|
26
|
+
if (hardFindings.length > 0) {
|
|
27
|
+
throw new RunJournalStoreCorruptionError(`run journal is corrupt: ${hardFindings.map((finding) => finding.code).join(", ")}`);
|
|
28
|
+
}
|
|
29
|
+
const last = report.records.at(-1);
|
|
30
|
+
return {
|
|
31
|
+
size: snapshot.bytes.byteLength,
|
|
32
|
+
lastSeq: last?.seq ?? 0,
|
|
33
|
+
lastHash: last?.hash ?? null,
|
|
34
|
+
generation: snapshot.generation,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function sameDurableHead(left, right) {
|
|
38
|
+
return (left.size === right.size &&
|
|
39
|
+
left.lastSeq === right.lastSeq &&
|
|
40
|
+
left.lastHash === right.lastHash &&
|
|
41
|
+
sameDurableFileGeneration(left.generation, right.generation));
|
|
42
|
+
}
|
|
43
|
+
function sameSourceSnapshot(left, right) {
|
|
44
|
+
return (right !== null &&
|
|
45
|
+
sameDurableFileGeneration(left.generation, right.generation) &&
|
|
46
|
+
Buffer.compare(left.bytes, right.bytes) === 0);
|
|
47
|
+
}
|
|
48
|
+
function replayRecords(records, sessionId, hashFn) {
|
|
49
|
+
const journal = new RunJournal({
|
|
50
|
+
hashFn,
|
|
51
|
+
sessionId,
|
|
52
|
+
runId: "replay",
|
|
53
|
+
sessionRevision: 0,
|
|
54
|
+
timestamp: "1970-01-01T00:00:00.000Z",
|
|
55
|
+
openInitialRun: false,
|
|
56
|
+
});
|
|
57
|
+
for (const record of records) {
|
|
58
|
+
let replayed;
|
|
59
|
+
if (record.event === "run_started") {
|
|
60
|
+
replayed = journal.start({
|
|
61
|
+
runId: record.runId,
|
|
62
|
+
sessionRevision: record.sessionRevision,
|
|
63
|
+
timestamp: record.timestamp,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
else if (record.event === "tool_timeout" ||
|
|
67
|
+
record.event === "tool_late_settlement" ||
|
|
68
|
+
record.event === "transcript_repaired") {
|
|
69
|
+
replayed = journal.audit({
|
|
70
|
+
event: record.event,
|
|
71
|
+
details: record.details,
|
|
72
|
+
sessionRevision: record.sessionRevision,
|
|
73
|
+
timestamp: record.timestamp,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
else if ("termination" in record) {
|
|
77
|
+
const input = {
|
|
78
|
+
termination: record.termination,
|
|
79
|
+
sessionRevision: record.sessionRevision,
|
|
80
|
+
timestamp: record.timestamp,
|
|
81
|
+
};
|
|
82
|
+
replayed =
|
|
83
|
+
record.event === "run_finished"
|
|
84
|
+
? journal.finish(input)
|
|
85
|
+
: record.event === "run_abandoned"
|
|
86
|
+
? journal.abandon(input)
|
|
87
|
+
: journal.recover(input);
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
throw new RunJournalStoreCorruptionError("run journal contains an unsupported record event");
|
|
91
|
+
}
|
|
92
|
+
if (serializeRunJournalLine(replayed) !== serializeRunJournalLine(record)) {
|
|
93
|
+
throw new RunJournalStoreCorruptionError("run journal replay did not reproduce the accepted chain");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return journal;
|
|
97
|
+
}
|
|
98
|
+
export class RunJournalStore {
|
|
99
|
+
static sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
100
|
+
journalPath;
|
|
101
|
+
sessionId;
|
|
102
|
+
hashFn;
|
|
103
|
+
now;
|
|
104
|
+
persistRecord;
|
|
105
|
+
ownerLease;
|
|
106
|
+
acceptedRecords;
|
|
107
|
+
acceptedOpenRunId;
|
|
108
|
+
acceptedDurableHead;
|
|
109
|
+
journalLockDepth = 0;
|
|
110
|
+
quarantineReport;
|
|
111
|
+
constructor(options, records, openRunId, quarantineReport, durableHead) {
|
|
112
|
+
this.journalPath = options.journalPath;
|
|
113
|
+
this.sessionId = options.sessionId;
|
|
114
|
+
this.hashFn = options.hashFn ?? RunJournalStore.sha256;
|
|
115
|
+
this.now = options.now ?? (() => new Date().toISOString());
|
|
116
|
+
this.persistRecord = options.persistRecord ?? appendRunJournalRecordDurably;
|
|
117
|
+
this.ownerLease = options.ownerLease;
|
|
118
|
+
this.acceptedRecords = Object.freeze([...records]);
|
|
119
|
+
this.acceptedOpenRunId = openRunId;
|
|
120
|
+
this.acceptedDurableHead = durableHead;
|
|
121
|
+
this.quarantineReport = quarantineReport;
|
|
122
|
+
}
|
|
123
|
+
static open(options) {
|
|
124
|
+
const hashFn = options.hashFn ?? RunJournalStore.sha256;
|
|
125
|
+
if (!options.journalPath) {
|
|
126
|
+
return new RunJournalStore(options, [], null, null, {
|
|
127
|
+
size: 0,
|
|
128
|
+
lastSeq: 0,
|
|
129
|
+
lastHash: null,
|
|
130
|
+
generation: null,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
const journalPath = options.journalPath;
|
|
134
|
+
const ownerLock = acquireDurableFileMutationLockSync(sessionPathFromPersistenceArtifact(journalPath));
|
|
135
|
+
let journalLock;
|
|
136
|
+
try {
|
|
137
|
+
journalLock = acquireDurableFileMutationLockSync(journalPath);
|
|
138
|
+
assertSessionOwnerRecoveryAllowedUnlockedSync(journalPath, options.ownerLease);
|
|
139
|
+
let records = [];
|
|
140
|
+
let openRunId = null;
|
|
141
|
+
let quarantineReport = null;
|
|
142
|
+
const snapshot = readDurableFileSnapshot(journalPath);
|
|
143
|
+
if (snapshot) {
|
|
144
|
+
const report = inspectRunJournal(snapshot.bytes, hashFn);
|
|
145
|
+
const hardFindings = report.findings.filter((finding) => finding.code !== "trailing_fragment" && finding.code !== "run_unclosed");
|
|
146
|
+
if (hardFindings.length > 0) {
|
|
147
|
+
throw new RunJournalStoreCorruptionError(`run journal is corrupt: ${hardFindings.map((finding) => finding.code).join(", ")}`);
|
|
148
|
+
}
|
|
149
|
+
if (report.records.some((record) => record.sessionId !== options.sessionId)) {
|
|
150
|
+
throw new RunJournalStoreCorruptionError("run journal session identity does not match");
|
|
151
|
+
}
|
|
152
|
+
records = report.records;
|
|
153
|
+
openRunId = report.openRunId;
|
|
154
|
+
if (report.trailingByteCount > 0) {
|
|
155
|
+
const fragment = snapshot.bytes.subarray(report.completePrefix.byteCount);
|
|
156
|
+
const quarantinePath = `${journalPath}.quarantine-${randomUUID()}`;
|
|
157
|
+
(options.persistQuarantine ?? writeQuarantineBytesDurably)(quarantinePath, fragment);
|
|
158
|
+
if (!sameSourceSnapshot(snapshot, readDurableFileSnapshot(journalPath))) {
|
|
159
|
+
throw new RunJournalStoreStaleWriteError();
|
|
160
|
+
}
|
|
161
|
+
atomicRewriteFileSync(journalPath, snapshot.bytes.subarray(0, report.completePrefix.byteCount));
|
|
162
|
+
quarantineReport = Object.freeze({
|
|
163
|
+
path: quarantinePath,
|
|
164
|
+
byteCount: fragment.byteLength,
|
|
165
|
+
completePrefixByteCount: report.completePrefix.byteCount,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const store = new RunJournalStore(options, records, openRunId, quarantineReport, readDurableHead(journalPath, hashFn));
|
|
170
|
+
store.journalLockDepth = 1;
|
|
171
|
+
try {
|
|
172
|
+
if (openRunId !== null) {
|
|
173
|
+
const timestamp = store.now();
|
|
174
|
+
const sessionRevision = records.at(-1)?.sessionRevision ?? 0;
|
|
175
|
+
store.recover({
|
|
176
|
+
termination: classifySessionTermination({
|
|
177
|
+
sessionId: options.sessionId,
|
|
178
|
+
runId: openRunId,
|
|
179
|
+
timestamp,
|
|
180
|
+
source: "inferred_on_resume",
|
|
181
|
+
message: "Previous process exited without closing the run; recovered on startup.",
|
|
182
|
+
cause: { area: "process", code: "crash" },
|
|
183
|
+
sideEffects: "possible",
|
|
184
|
+
}),
|
|
185
|
+
sessionRevision,
|
|
186
|
+
timestamp,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
store.journalLockDepth = 0;
|
|
192
|
+
}
|
|
193
|
+
return store;
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
journalLock?.release();
|
|
197
|
+
ownerLock.release();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
get records() {
|
|
201
|
+
return this.acceptedRecords;
|
|
202
|
+
}
|
|
203
|
+
get openRunId() {
|
|
204
|
+
return this.acceptedOpenRunId;
|
|
205
|
+
}
|
|
206
|
+
start(input) {
|
|
207
|
+
return this.commit((journal) => journal.start(input));
|
|
208
|
+
}
|
|
209
|
+
finish(input) {
|
|
210
|
+
return this.commit((journal) => journal.finish(input));
|
|
211
|
+
}
|
|
212
|
+
abandon(input) {
|
|
213
|
+
return this.commit((journal) => journal.abandon(input));
|
|
214
|
+
}
|
|
215
|
+
recover(input) {
|
|
216
|
+
return this.commit((journal) => journal.recover(input));
|
|
217
|
+
}
|
|
218
|
+
audit(input) {
|
|
219
|
+
return this.commit((journal) => journal.audit(input));
|
|
220
|
+
}
|
|
221
|
+
withJournalLock(fn) {
|
|
222
|
+
if (!this.journalPath || this.journalLockDepth > 0)
|
|
223
|
+
return fn();
|
|
224
|
+
const ownerLock = acquireDurableFileMutationLockSync(sessionPathFromPersistenceArtifact(this.journalPath));
|
|
225
|
+
let journalLock;
|
|
226
|
+
try {
|
|
227
|
+
journalLock = acquireDurableFileMutationLockSync(this.journalPath);
|
|
228
|
+
this.journalLockDepth += 1;
|
|
229
|
+
try {
|
|
230
|
+
return fn();
|
|
231
|
+
}
|
|
232
|
+
finally {
|
|
233
|
+
this.journalLockDepth -= 1;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
journalLock?.release();
|
|
238
|
+
ownerLock.release();
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
commit(append) {
|
|
242
|
+
return this.withJournalLock(() => {
|
|
243
|
+
if (this.journalPath) {
|
|
244
|
+
assertSessionOwnerRecoveryAllowedUnlockedSync(this.journalPath, this.ownerLease);
|
|
245
|
+
const current = readDurableHead(this.journalPath, this.hashFn);
|
|
246
|
+
if (!sameDurableHead(current, this.acceptedDurableHead))
|
|
247
|
+
throw new RunJournalStoreStaleWriteError();
|
|
248
|
+
}
|
|
249
|
+
const candidate = replayRecords(this.acceptedRecords, this.sessionId, this.hashFn);
|
|
250
|
+
const record = append(candidate);
|
|
251
|
+
let nextDurableHead = this.acceptedDurableHead;
|
|
252
|
+
if (this.journalPath) {
|
|
253
|
+
const line = `${serializeRunJournalLine(record)}\n`;
|
|
254
|
+
this.persistRecord(this.journalPath, line);
|
|
255
|
+
nextDurableHead = readDurableHead(this.journalPath, this.hashFn);
|
|
256
|
+
const expected = {
|
|
257
|
+
size: this.acceptedDurableHead.size + Buffer.byteLength(line, "utf8"),
|
|
258
|
+
lastSeq: record.seq,
|
|
259
|
+
lastHash: record.hash,
|
|
260
|
+
generation: nextDurableHead.generation
|
|
261
|
+
? {
|
|
262
|
+
...(this.acceptedDurableHead.generation ?? nextDurableHead.generation),
|
|
263
|
+
ctimeNs: nextDurableHead.generation.ctimeNs,
|
|
264
|
+
}
|
|
265
|
+
: null,
|
|
266
|
+
};
|
|
267
|
+
if (!sameDurableHead(nextDurableHead, expected)) {
|
|
268
|
+
throw new RunJournalStoreCorruptionError("persisted run journal head does not match appended record");
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
this.acceptedRecords = Object.freeze([...candidate.records]);
|
|
272
|
+
this.acceptedOpenRunId = candidate.openRunId;
|
|
273
|
+
this.acceptedDurableHead = nextDurableHead;
|
|
274
|
+
return record;
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
//# sourceMappingURL=run-journal-store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-journal-store.js","sourceRoot":"","sources":["../../src/core/run-journal-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,kCAAkC,EAA8B,MAAM,4BAA4B,CAAC;AAC5G,OAAO,EACN,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,6BAA6B,GAC7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,iBAAiB,EACjB,UAAU,EASV,uBAAuB,GACvB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACN,6CAA6C,EAE7C,kCAAkC,GAClC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AAmBtE,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IACtC,IAAI,GAAG,gCAAgC,CAAC;CAC1D;AAED,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IACxD,cAAc;QACb,KAAK,CAAC,gEAAgE,CAAC,CAAC;QACxE,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;IAAA,CAC7C;CACD;AASD,iFAAiF;AACjF,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAAC,IAAY,EAAE,IAAY,EAAQ,EAAE,CACjF,qBAAqB,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,C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C,iBAAiB,GAAG,SAAS,CAAC,SAAS,CAAC;YAC7C,IAAI,CAAC,mBAAmB,GAAG,eAAe,CAAC;YAC3C,OAAO,MAAM,CAAC;QAAA,CACd,CAAC,CAAC;IAAA,CACH;CACD","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { atomicRewriteFileSync } from \"./atomic-session-file.ts\";\nimport { acquireDurableFileMutationLockSync, type DurableFileGeneration } from \"./durable-file-identity.ts\";\nimport {\n\tappendFileDurablySync,\n\treadDurableFileSnapshot,\n\tsameDurableFileGeneration,\n\twriteExclusiveFileDurablySync,\n} from \"./durable-file-io.ts\";\nimport {\n\tinspectRunJournal,\n\tRunJournal,\n\ttype RunJournalAuditInput,\n\ttype RunJournalAuditRecord,\n\ttype RunJournalHashFn,\n\ttype RunJournalRecord,\n\ttype RunJournalStartedRecord,\n\ttype RunJournalStartInput,\n\ttype RunJournalTerminalInput,\n\ttype RunJournalTerminalRecord,\n\tserializeRunJournalLine,\n} from \"./run-journal.ts\";\nimport {\n\tassertSessionOwnerRecoveryAllowedUnlockedSync,\n\ttype SessionOwnerLease,\n\tsessionPathFromPersistenceArtifact,\n} from \"./session-owner-lease.ts\";\nimport { classifySessionTermination } from \"./session-termination.ts\";\n\nexport interface RunJournalQuarantineReport {\n\treadonly path: string;\n\treadonly byteCount: number;\n\treadonly completePrefixByteCount: number;\n}\n\nexport interface OpenRunJournalStoreOptions {\n\treadonly journalPath?: string;\n\treadonly sessionId: string;\n\treadonly now?: () => string;\n\treadonly hashFn?: RunJournalHashFn;\n\treadonly ownerLease?: SessionOwnerLease;\n\t/** Test seams for deterministic persistence failures and quarantine races. */\n\treadonly persistRecord?: (path: string, line: string) => void;\n\treadonly persistQuarantine?: (path: string, bytes: Uint8Array) => void;\n}\n\nexport class RunJournalStoreCorruptionError extends Error {\n\toverride readonly name = \"RunJournalStoreCorruptionError\";\n}\n\nexport class RunJournalStoreStaleWriteError extends Error {\n\tconstructor() {\n\t\tsuper(\"Run journal changed since this store accepted its durable head\");\n\t\tthis.name = \"RunJournalStoreStaleWriteError\";\n\t}\n}\n\ntype RunJournalDurableHead = {\n\treadonly size: number;\n\treadonly lastSeq: number;\n\treadonly lastHash: string | null;\n\treadonly generation: DurableFileGeneration | null;\n};\n\n/** Append one complete JSONL record and fsync it without truncation rollback. */\nexport const appendRunJournalRecordDurably = (path: string, line: string): void =>\n\tappendFileDurablySync(path, Buffer.from(line, \"utf8\"));\n\nexport const writeQuarantineBytesDurably = writeExclusiveFileDurablySync;\n\nfunction readDurableHead(path: string, hashFn: RunJournalHashFn): RunJournalDurableHead {\n\tconst snapshot = readDurableFileSnapshot(path);\n\tif (!snapshot) return { size: 0, lastSeq: 0, lastHash: null, generation: null };\n\tconst report = inspectRunJournal(snapshot.bytes, hashFn);\n\tconst hardFindings = report.findings.filter((finding) => finding.code !== \"run_unclosed\");\n\tif (hardFindings.length > 0) {\n\t\tthrow new RunJournalStoreCorruptionError(\n\t\t\t`run journal is corrupt: ${hardFindings.map((finding) => finding.code).join(\", \")}`,\n\t\t);\n\t}\n\tconst last = report.records.at(-1);\n\treturn {\n\t\tsize: snapshot.bytes.byteLength,\n\t\tlastSeq: last?.seq ?? 0,\n\t\tlastHash: last?.hash ?? null,\n\t\tgeneration: snapshot.generation,\n\t};\n}\n\nfunction sameDurableHead(left: RunJournalDurableHead, right: RunJournalDurableHead): boolean {\n\treturn (\n\t\tleft.size === right.size &&\n\t\tleft.lastSeq === right.lastSeq &&\n\t\tleft.lastHash === right.lastHash &&\n\t\tsameDurableFileGeneration(left.generation, right.generation)\n\t);\n}\n\nfunction sameSourceSnapshot(\n\tleft: NonNullable<ReturnType<typeof readDurableFileSnapshot>>,\n\tright: ReturnType<typeof readDurableFileSnapshot>,\n): boolean {\n\treturn (\n\t\tright !== null &&\n\t\tsameDurableFileGeneration(left.generation, right.generation) &&\n\t\tBuffer.compare(left.bytes, right.bytes) === 0\n\t);\n}\n\nfunction replayRecords(records: readonly RunJournalRecord[], sessionId: string, hashFn: RunJournalHashFn): RunJournal {\n\tconst journal = new RunJournal({\n\t\thashFn,\n\t\tsessionId,\n\t\trunId: \"replay\",\n\t\tsessionRevision: 0,\n\t\ttimestamp: \"1970-01-01T00:00:00.000Z\",\n\t\topenInitialRun: false,\n\t});\n\tfor (const record of records) {\n\t\tlet replayed: RunJournalRecord;\n\t\tif (record.event === \"run_started\") {\n\t\t\treplayed = journal.start({\n\t\t\t\trunId: record.runId,\n\t\t\t\tsessionRevision: record.sessionRevision,\n\t\t\t\ttimestamp: record.timestamp,\n\t\t\t});\n\t\t} else if (\n\t\t\trecord.event === \"tool_timeout\" ||\n\t\t\trecord.event === \"tool_late_settlement\" ||\n\t\t\trecord.event === \"transcript_repaired\"\n\t\t) {\n\t\t\treplayed = journal.audit({\n\t\t\t\tevent: record.event,\n\t\t\t\tdetails: record.details,\n\t\t\t\tsessionRevision: record.sessionRevision,\n\t\t\t\ttimestamp: record.timestamp,\n\t\t\t});\n\t\t} else if (\"termination\" in record) {\n\t\t\tconst input = {\n\t\t\t\ttermination: record.termination,\n\t\t\t\tsessionRevision: record.sessionRevision,\n\t\t\t\ttimestamp: record.timestamp,\n\t\t\t};\n\t\t\treplayed =\n\t\t\t\trecord.event === \"run_finished\"\n\t\t\t\t\t? journal.finish(input)\n\t\t\t\t\t: record.event === \"run_abandoned\"\n\t\t\t\t\t\t? journal.abandon(input)\n\t\t\t\t\t\t: journal.recover(input);\n\t\t} else {\n\t\t\tthrow new RunJournalStoreCorruptionError(\"run journal contains an unsupported record event\");\n\t\t}\n\t\tif (serializeRunJournalLine(replayed) !== serializeRunJournalLine(record)) {\n\t\t\tthrow new RunJournalStoreCorruptionError(\"run journal replay did not reproduce the accepted chain\");\n\t\t}\n\t}\n\treturn journal;\n}\n\nexport class RunJournalStore {\n\tstatic readonly sha256: RunJournalHashFn = (bytes) => createHash(\"sha256\").update(bytes).digest(\"hex\");\n\n\tprivate readonly journalPath: string | undefined;\n\tprivate readonly sessionId: string;\n\tprivate readonly hashFn: RunJournalHashFn;\n\tprivate readonly now: () => string;\n\tprivate readonly persistRecord: (path: string, line: string) => void;\n\tprivate readonly ownerLease: SessionOwnerLease | undefined;\n\tprivate acceptedRecords: readonly RunJournalRecord[];\n\tprivate acceptedOpenRunId: string | null;\n\tprivate acceptedDurableHead: RunJournalDurableHead;\n\tprivate journalLockDepth = 0;\n\treadonly quarantineReport: RunJournalQuarantineReport | null;\n\n\tprivate constructor(\n\t\toptions: OpenRunJournalStoreOptions,\n\t\trecords: readonly RunJournalRecord[],\n\t\topenRunId: string | null,\n\t\tquarantineReport: RunJournalQuarantineReport | null,\n\t\tdurableHead: RunJournalDurableHead,\n\t) {\n\t\tthis.journalPath = options.journalPath;\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.hashFn = options.hashFn ?? RunJournalStore.sha256;\n\t\tthis.now = options.now ?? (() => new Date().toISOString());\n\t\tthis.persistRecord = options.persistRecord ?? appendRunJournalRecordDurably;\n\t\tthis.ownerLease = options.ownerLease;\n\t\tthis.acceptedRecords = Object.freeze([...records]);\n\t\tthis.acceptedOpenRunId = openRunId;\n\t\tthis.acceptedDurableHead = durableHead;\n\t\tthis.quarantineReport = quarantineReport;\n\t}\n\n\tstatic open(options: OpenRunJournalStoreOptions): RunJournalStore {\n\t\tconst hashFn = options.hashFn ?? RunJournalStore.sha256;\n\t\tif (!options.journalPath) {\n\t\t\treturn new RunJournalStore(options, [], null, null, {\n\t\t\t\tsize: 0,\n\t\t\t\tlastSeq: 0,\n\t\t\t\tlastHash: null,\n\t\t\t\tgeneration: null,\n\t\t\t});\n\t\t}\n\n\t\tconst journalPath = options.journalPath;\n\t\tconst ownerLock = acquireDurableFileMutationLockSync(sessionPathFromPersistenceArtifact(journalPath));\n\t\tlet journalLock: ReturnType<typeof acquireDurableFileMutationLockSync> | undefined;\n\t\ttry {\n\t\t\tjournalLock = acquireDurableFileMutationLockSync(journalPath);\n\t\t\tassertSessionOwnerRecoveryAllowedUnlockedSync(journalPath, options.ownerLease);\n\t\t\tlet records: readonly RunJournalRecord[] = [];\n\t\t\tlet openRunId: string | null = null;\n\t\t\tlet quarantineReport: RunJournalQuarantineReport | null = null;\n\t\t\tconst snapshot = readDurableFileSnapshot(journalPath);\n\t\t\tif (snapshot) {\n\t\t\t\tconst report = inspectRunJournal(snapshot.bytes, hashFn);\n\t\t\t\tconst hardFindings = report.findings.filter(\n\t\t\t\t\t(finding) => finding.code !== \"trailing_fragment\" && finding.code !== \"run_unclosed\",\n\t\t\t\t);\n\t\t\t\tif (hardFindings.length > 0) {\n\t\t\t\t\tthrow new RunJournalStoreCorruptionError(\n\t\t\t\t\t\t`run journal is corrupt: ${hardFindings.map((finding) => finding.code).join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (report.records.some((record) => record.sessionId !== options.sessionId)) {\n\t\t\t\t\tthrow new RunJournalStoreCorruptionError(\"run journal session identity does not match\");\n\t\t\t\t}\n\t\t\t\trecords = report.records;\n\t\t\t\topenRunId = report.openRunId;\n\n\t\t\t\tif (report.trailingByteCount > 0) {\n\t\t\t\t\tconst fragment = snapshot.bytes.subarray(report.completePrefix.byteCount);\n\t\t\t\t\tconst quarantinePath = `${journalPath}.quarantine-${randomUUID()}`;\n\t\t\t\t\t(options.persistQuarantine ?? writeQuarantineBytesDurably)(quarantinePath, fragment);\n\t\t\t\t\tif (!sameSourceSnapshot(snapshot, readDurableFileSnapshot(journalPath))) {\n\t\t\t\t\t\tthrow new RunJournalStoreStaleWriteError();\n\t\t\t\t\t}\n\t\t\t\t\tatomicRewriteFileSync(journalPath, snapshot.bytes.subarray(0, report.completePrefix.byteCount));\n\t\t\t\t\tquarantineReport = Object.freeze({\n\t\t\t\t\t\tpath: quarantinePath,\n\t\t\t\t\t\tbyteCount: fragment.byteLength,\n\t\t\t\t\t\tcompletePrefixByteCount: report.completePrefix.byteCount,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst store = new RunJournalStore(\n\t\t\t\toptions,\n\t\t\t\trecords,\n\t\t\t\topenRunId,\n\t\t\t\tquarantineReport,\n\t\t\t\treadDurableHead(journalPath, hashFn),\n\t\t\t);\n\t\t\tstore.journalLockDepth = 1;\n\t\t\ttry {\n\t\t\t\tif (openRunId !== null) {\n\t\t\t\t\tconst timestamp = store.now();\n\t\t\t\t\tconst sessionRevision = records.at(-1)?.sessionRevision ?? 0;\n\t\t\t\t\tstore.recover({\n\t\t\t\t\t\ttermination: classifySessionTermination({\n\t\t\t\t\t\t\tsessionId: options.sessionId,\n\t\t\t\t\t\t\trunId: openRunId,\n\t\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\t\tsource: \"inferred_on_resume\",\n\t\t\t\t\t\t\tmessage: \"Previous process exited without closing the run; recovered on startup.\",\n\t\t\t\t\t\t\tcause: { area: \"process\", code: \"crash\" },\n\t\t\t\t\t\t\tsideEffects: \"possible\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tsessionRevision,\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tstore.journalLockDepth = 0;\n\t\t\t}\n\t\t\treturn store;\n\t\t} finally {\n\t\t\tjournalLock?.release();\n\t\t\townerLock.release();\n\t\t}\n\t}\n\n\tget records(): readonly RunJournalRecord[] {\n\t\treturn this.acceptedRecords;\n\t}\n\n\tget openRunId(): string | null {\n\t\treturn this.acceptedOpenRunId;\n\t}\n\n\tstart(input: RunJournalStartInput): RunJournalStartedRecord {\n\t\treturn this.commit((journal) => journal.start(input));\n\t}\n\n\tfinish(input: RunJournalTerminalInput): RunJournalTerminalRecord {\n\t\treturn this.commit((journal) => journal.finish(input));\n\t}\n\n\tabandon(input: RunJournalTerminalInput): RunJournalTerminalRecord {\n\t\treturn this.commit((journal) => journal.abandon(input));\n\t}\n\n\trecover(input: RunJournalTerminalInput): RunJournalTerminalRecord {\n\t\treturn this.commit((journal) => journal.recover(input));\n\t}\n\n\taudit(input: RunJournalAuditInput): RunJournalAuditRecord {\n\t\treturn this.commit((journal) => journal.audit(input));\n\t}\n\n\tprivate withJournalLock<T>(fn: () => T): T {\n\t\tif (!this.journalPath || this.journalLockDepth > 0) return fn();\n\t\tconst ownerLock = acquireDurableFileMutationLockSync(sessionPathFromPersistenceArtifact(this.journalPath));\n\t\tlet journalLock: ReturnType<typeof acquireDurableFileMutationLockSync> | undefined;\n\t\ttry {\n\t\t\tjournalLock = acquireDurableFileMutationLockSync(this.journalPath);\n\t\t\tthis.journalLockDepth += 1;\n\t\t\ttry {\n\t\t\t\treturn fn();\n\t\t\t} finally {\n\t\t\t\tthis.journalLockDepth -= 1;\n\t\t\t}\n\t\t} finally {\n\t\t\tjournalLock?.release();\n\t\t\townerLock.release();\n\t\t}\n\t}\n\n\tprivate commit<T extends RunJournalRecord>(append: (journal: RunJournal) => T): T {\n\t\treturn this.withJournalLock(() => {\n\t\t\tif (this.journalPath) {\n\t\t\t\tassertSessionOwnerRecoveryAllowedUnlockedSync(this.journalPath, this.ownerLease);\n\t\t\t\tconst current = readDurableHead(this.journalPath, this.hashFn);\n\t\t\t\tif (!sameDurableHead(current, this.acceptedDurableHead)) throw new RunJournalStoreStaleWriteError();\n\t\t\t}\n\n\t\t\tconst candidate = replayRecords(this.acceptedRecords, this.sessionId, this.hashFn);\n\t\t\tconst record = append(candidate);\n\t\t\tlet nextDurableHead = this.acceptedDurableHead;\n\t\t\tif (this.journalPath) {\n\t\t\t\tconst line = `${serializeRunJournalLine(record)}\\n`;\n\t\t\t\tthis.persistRecord(this.journalPath, line);\n\t\t\t\tnextDurableHead = readDurableHead(this.journalPath, this.hashFn);\n\t\t\t\tconst expected = {\n\t\t\t\t\tsize: this.acceptedDurableHead.size + Buffer.byteLength(line, \"utf8\"),\n\t\t\t\t\tlastSeq: record.seq,\n\t\t\t\t\tlastHash: record.hash,\n\t\t\t\t\tgeneration: nextDurableHead.generation\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...(this.acceptedDurableHead.generation ?? nextDurableHead.generation),\n\t\t\t\t\t\t\t\tctimeNs: nextDurableHead.generation.ctimeNs,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null,\n\t\t\t\t};\n\t\t\t\tif (!sameDurableHead(nextDurableHead, expected)) {\n\t\t\t\t\tthrow new RunJournalStoreCorruptionError(\"persisted run journal head does not match appended record\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.acceptedRecords = Object.freeze([...candidate.records]);\n\t\t\tthis.acceptedOpenRunId = candidate.openRunId;\n\t\t\tthis.acceptedDurableHead = nextDurableHead;\n\t\t\treturn record;\n\t\t});\n\t}\n}\n"]}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure, browser-safe run-journal format and complete-prefix integrity inspector.
|
|
3
|
+
*
|
|
4
|
+
* Runtime purity: this module performs no I/O and uses no Node-specific
|
|
5
|
+
* primitives. It relies only on `TextEncoder`/`TextDecoder`, `JSON`, the pure
|
|
6
|
+
* `Date` string parser, and ordinary language built-ins. It consults no wall
|
|
7
|
+
* clock, draws no entropy, invokes no cryptographic primitives, and mutates no
|
|
8
|
+
* global state. Every record hash is recomputed from a caller-injected
|
|
9
|
+
* synchronous `RunJournalHashFn`, both when records are constructed by
|
|
10
|
+
* {@link RunJournal} and when raw bytes are inspected by
|
|
11
|
+
* {@link inspectRunJournal}. There is no opaque mode that skips hashing.
|
|
12
|
+
*/
|
|
13
|
+
import { type SessionTermination } from "./session-termination.ts";
|
|
14
|
+
export declare const RUN_JOURNAL_SCHEMA_VERSION: 1;
|
|
15
|
+
/** Sixty-four zero bits; the `prevHash` of the first record in every chain. */
|
|
16
|
+
export declare const GENESIS_HASH: string;
|
|
17
|
+
export declare const MAX_RUN_JOURNAL_ID_LENGTH = 128;
|
|
18
|
+
/** Synchronous, pure hash function injected by the caller. Must return 64 lowercase hex chars. */
|
|
19
|
+
export type RunJournalHashFn = (bytes: Uint8Array) => string;
|
|
20
|
+
/** Audit-only journal events; they never open, close, or otherwise affect a run. */
|
|
21
|
+
export type RunJournalAuditEvent = "tool_timeout" | "tool_late_settlement" | "transcript_repaired";
|
|
22
|
+
export type RunJournalEvent = "run_started" | "run_finished" | "run_recovered" | "run_abandoned" | RunJournalAuditEvent;
|
|
23
|
+
export type RunJournalFindingCode = "trailing_fragment" | "invalid_utf8" | "malformed_json" | "schema" | "seq_gap" | "seq_regression" | "hash_shape" | "hash_mismatch" | "hash_chain_break" | "orphan_terminal" | "duplicate_terminal" | "duplicate_start" | "interleaved_run" | "run_unclosed" | "recovered_source_invalid" | "termination_mismatch" | "session_mismatch" | "session_revision_regression";
|
|
24
|
+
export interface RunJournalRecordBase {
|
|
25
|
+
readonly schemaVersion: typeof RUN_JOURNAL_SCHEMA_VERSION;
|
|
26
|
+
readonly seq: number;
|
|
27
|
+
readonly event: RunJournalEvent;
|
|
28
|
+
readonly runId: string;
|
|
29
|
+
readonly sessionId: string;
|
|
30
|
+
readonly sessionRevision: number;
|
|
31
|
+
/** Canonical caller-supplied ISO-8601 UTC instant. */
|
|
32
|
+
readonly timestamp: string;
|
|
33
|
+
/** Hash of the previous record (`GENESIS_HASH` for the first record). */
|
|
34
|
+
readonly prevHash: string;
|
|
35
|
+
/** Recomputed hash of this record's canonical material (without `hash`). */
|
|
36
|
+
readonly hash: string;
|
|
37
|
+
}
|
|
38
|
+
export interface RunJournalStartedRecord extends RunJournalRecordBase {
|
|
39
|
+
readonly event: "run_started";
|
|
40
|
+
}
|
|
41
|
+
export interface RunJournalTerminalRecord extends RunJournalRecordBase {
|
|
42
|
+
readonly event: "run_finished" | "run_recovered" | "run_abandoned";
|
|
43
|
+
readonly termination: SessionTermination;
|
|
44
|
+
}
|
|
45
|
+
/** Bounded structured payload persisted with an audit record. */
|
|
46
|
+
export interface RunJournalAuditDetails {
|
|
47
|
+
readonly toolCallId?: string;
|
|
48
|
+
readonly toolName?: string;
|
|
49
|
+
readonly disposition?: "completed" | "failed" | "blocked" | "aborted" | "timeout" | "skipped";
|
|
50
|
+
readonly outcome?: "resolved" | "rejected";
|
|
51
|
+
readonly timeoutMs?: number;
|
|
52
|
+
readonly executionStarted?: boolean;
|
|
53
|
+
readonly insertedToolCallIds?: readonly string[];
|
|
54
|
+
readonly reason?: string;
|
|
55
|
+
readonly sessionRisk?: "elevated";
|
|
56
|
+
}
|
|
57
|
+
export interface RunJournalAuditRecord extends RunJournalRecordBase {
|
|
58
|
+
readonly event: RunJournalAuditEvent;
|
|
59
|
+
readonly details: RunJournalAuditDetails;
|
|
60
|
+
}
|
|
61
|
+
export type RunJournalRecord = RunJournalStartedRecord | RunJournalTerminalRecord | RunJournalAuditRecord;
|
|
62
|
+
export interface RunJournalFinding {
|
|
63
|
+
readonly code: RunJournalFindingCode;
|
|
64
|
+
readonly line?: number;
|
|
65
|
+
readonly runId?: string;
|
|
66
|
+
}
|
|
67
|
+
export interface RunJournalCompletePrefix {
|
|
68
|
+
readonly byteCount: number;
|
|
69
|
+
readonly lineCount: number;
|
|
70
|
+
}
|
|
71
|
+
export interface RunJournalReport {
|
|
72
|
+
readonly ok: boolean;
|
|
73
|
+
readonly completePrefix: RunJournalCompletePrefix;
|
|
74
|
+
readonly trailingByteCount: number;
|
|
75
|
+
readonly records: readonly RunJournalRecord[];
|
|
76
|
+
readonly openRunId: string | null;
|
|
77
|
+
readonly findings: readonly RunJournalFinding[];
|
|
78
|
+
}
|
|
79
|
+
export interface RunJournalConstructorInit {
|
|
80
|
+
readonly hashFn: RunJournalHashFn;
|
|
81
|
+
readonly sessionId: string;
|
|
82
|
+
readonly runId: string;
|
|
83
|
+
readonly sessionRevision: number;
|
|
84
|
+
readonly timestamp: string;
|
|
85
|
+
/**
|
|
86
|
+
* When `false`, the constructor does not append the initial `run_started`
|
|
87
|
+
* record: the journal starts closed and accepts audit records (and later
|
|
88
|
+
* explicit `start()` calls). Default `true` preserves existing behavior.
|
|
89
|
+
*/
|
|
90
|
+
readonly openInitialRun?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Trusted caller-supplied continuation chain-head `prevHash`. Defaults to
|
|
93
|
+
* `GENESIS_HASH` for a new journal. The writer treats this as a trusted
|
|
94
|
+
* baseline that pins the first record to an external chain; it is never
|
|
95
|
+
* re-derived.
|
|
96
|
+
*/
|
|
97
|
+
readonly prevHash?: string;
|
|
98
|
+
/**
|
|
99
|
+
* Trusted caller-supplied continuation chain-head `seq`. Defaults to `0` for
|
|
100
|
+
* a new journal. Treated as a trusted baseline; the writer advances from it
|
|
101
|
+
* but never re-derives it.
|
|
102
|
+
*/
|
|
103
|
+
readonly seq?: number;
|
|
104
|
+
}
|
|
105
|
+
export interface RunJournalStartInput {
|
|
106
|
+
readonly runId: string;
|
|
107
|
+
readonly sessionRevision: number;
|
|
108
|
+
readonly timestamp: string;
|
|
109
|
+
}
|
|
110
|
+
export interface RunJournalTerminalInput {
|
|
111
|
+
readonly termination: SessionTermination;
|
|
112
|
+
readonly sessionRevision: number;
|
|
113
|
+
readonly timestamp: string;
|
|
114
|
+
}
|
|
115
|
+
export interface RunJournalAuditInput {
|
|
116
|
+
readonly event: RunJournalAuditEvent;
|
|
117
|
+
readonly details: RunJournalAuditDetails;
|
|
118
|
+
readonly sessionRevision: number;
|
|
119
|
+
readonly timestamp: string;
|
|
120
|
+
}
|
|
121
|
+
/** Recursively key-sorted JSON serialization. Deterministic across runtimes and key insertion order. */
|
|
122
|
+
export declare function canonicalJson(value: unknown): string;
|
|
123
|
+
/** Canonical material of a record (everything except `hash`) over which the hash is computed. */
|
|
124
|
+
export declare function serializeRunJournalMaterial(record: Readonly<Omit<RunJournalRecord, "hash">>): string;
|
|
125
|
+
/** Canonical, key-sorted serialization of a full record (including `hash`). */
|
|
126
|
+
export declare function serializeRunJournalLine(record: Readonly<RunJournalRecord>): string;
|
|
127
|
+
/**
|
|
128
|
+
* Append-only run-journal writer. The constructor records the first
|
|
129
|
+
* `run_started` event (and recomputes its hash); {@link RunJournal.start} opens
|
|
130
|
+
* subsequent runs after a terminal event, while {@link RunJournal.finish},
|
|
131
|
+
* {@link RunJournal.abandon}, and {@link RunJournal.recover} close the currently
|
|
132
|
+
* open run. Exactly one run is open at a time.
|
|
133
|
+
*/
|
|
134
|
+
export declare class RunJournal {
|
|
135
|
+
private readonly hashFn;
|
|
136
|
+
private readonly sessionId;
|
|
137
|
+
private readonly startedRunIds;
|
|
138
|
+
private readonly terminatedRunIds;
|
|
139
|
+
private readonly mutableRecords;
|
|
140
|
+
private recordsSnapshot;
|
|
141
|
+
private lastSessionRevision;
|
|
142
|
+
private prevHash;
|
|
143
|
+
private nextSeq;
|
|
144
|
+
private openRun;
|
|
145
|
+
constructor(init: RunJournalConstructorInit);
|
|
146
|
+
start(input: RunJournalStartInput): RunJournalStartedRecord;
|
|
147
|
+
finish(input: RunJournalTerminalInput): RunJournalTerminalRecord;
|
|
148
|
+
abandon(input: RunJournalTerminalInput): RunJournalTerminalRecord;
|
|
149
|
+
recover(input: RunJournalTerminalInput): RunJournalTerminalRecord;
|
|
150
|
+
/**
|
|
151
|
+
* Append an audit-only record. Allowed with or without an open run; never
|
|
152
|
+
* opens, closes, or otherwise mutates run state. The record joins the same
|
|
153
|
+
* seq/hash chain as lifecycle records.
|
|
154
|
+
*/
|
|
155
|
+
audit(input: RunJournalAuditInput): RunJournalAuditRecord;
|
|
156
|
+
get records(): readonly RunJournalRecord[];
|
|
157
|
+
get openRunId(): string | null;
|
|
158
|
+
serialize(): string;
|
|
159
|
+
toBytes(): Uint8Array;
|
|
160
|
+
private refreshRecordsSnapshot;
|
|
161
|
+
private appendStarted;
|
|
162
|
+
private appendTerminal;
|
|
163
|
+
private seal;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Inspect the complete-line prefix of a run-journal byte sequence without
|
|
167
|
+
* mutating or repairing it. Only bytes through the final newline are parsed;
|
|
168
|
+
* trailing bytes are reported as a fragment and never parsed. Every hash is
|
|
169
|
+
* recomputed with the injected `hashFn`. The returned report is deeply frozen.
|
|
170
|
+
*/
|
|
171
|
+
export declare function inspectRunJournal(bytes: Uint8Array, hashFn: RunJournalHashFn): RunJournalReport;
|
|
172
|
+
//# sourceMappingURL=run-journal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-journal.d.ts","sourceRoot":"","sources":["../../src/core/run-journal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAGN,KAAK,kBAAkB,EACvB,MAAM,0BAA0B,CAAC;AAElC,eAAO,MAAM,0BAA0B,GAAa,CAAC;AACrD,+EAA+E;AAC/E,eAAO,MAAM,YAAY,QAAiB,CAAC;AAC3C,eAAO,MAAM,yBAAyB,MAAM,CAAC;AAE7C,kGAAkG;AAClG,MAAM,MAAM,gBAAgB,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,MAAM,CAAC;AAE7D,oFAAoF;AACpF,MAAM,MAAM,oBAAoB,GAAG,cAAc,GAAG,sBAAsB,GAAG,qBAAqB,CAAC;AAEnG,MAAM,MAAM,eAAe,GAAG,aAAa,GAAG,cAAc,GAAG,eAAe,GAAG,eAAe,GAAG,oBAAoB,CAAC;AAExH,MAAM,MAAM,qBAAqB,GAC9B,mBAAmB,GACnB,cAAc,GACd,gBAAgB,GAChB,QAAQ,GACR,SAAS,GACT,gBAAgB,GAChB,YAAY,GACZ,eAAe,GACf,kBAAkB,GAClB,iBAAiB,GACjB,oBAAoB,GACpB,iBAAiB,GACjB,iBAAiB,GACjB,cAAc,GACd,0BAA0B,GAC1B,sBAAsB,GACtB,kBAAkB,GAClB,6BAA6B,CAAC;AAEjC,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,aAAa,EAAE,OAAO,0BAA0B,CAAC;IAC1D,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IA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K,EAAE,oBAAoB,GAAG,uBAAuB,CAE1D;IAED,MAAM,CAAC,KAAK,EAAE,uBAAuB,GAAG,wBAAwB,CAE/D;IAED,OAAO,CAAC,KAAK,EAAE,uBAAuB,GAAG,wBAAwB,CAEhE;IAED,OAAO,CAAC,KAAK,EAAE,uBAAuB,GAAG,wBAAwB,CAEhE;IAED;;;;OAIG;IACH,KAAK,CAAC,KAAK,EAAE,oBAAoB,GAAG,qBAAqB,CA6BxD;IAED,IAAI,OAAO,IAAI,SAAS,gBAAgB,EAAE,CAEzC;IAED,IAAI,SAAS,IAAI,MAAM,GAAG,IAAI,CAE7B;IAED,SAAS,IAAI,MAAM,CAGlB;IAED,OAAO,IAAI,UAAU,CAEpB;IAED,OAAO,CAAC,sBAAsB;IAI9B,OAAO,CAAC,aAAa;IAoCrB,OAAO,CAAC,cAAc;IA2CtB,OAAO,CAAC,IAAI;CAaZ;AAuFD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAiL/F","sourcesContent":["/**\n * Pure, browser-safe run-journal format and complete-prefix integrity inspector.\n *\n * Runtime purity: this module performs no I/O and uses no Node-specific\n * primitives. It relies only on `TextEncoder`/`TextDecoder`, `JSON`, the pure\n * `Date` string parser, and ordinary language built-ins. It consults no wall\n * clock, draws no entropy, invokes no cryptographic primitives, and mutates no\n * global state. Every record hash is recomputed from a caller-injected\n * synchronous `RunJournalHashFn`, both when records are constructed by\n * {@link RunJournal} and when raw bytes are inspected by\n * {@link inspectRunJournal}. There is no opaque mode that skips hashing.\n */\nimport {\n\tassertPreRedactedTerminationMessage,\n\tSESSION_TERMINATION_SCHEMA_VERSION,\n\ttype SessionTermination,\n} from \"./session-termination.ts\";\n\nexport const RUN_JOURNAL_SCHEMA_VERSION = 1 as const;\n/** Sixty-four zero bits; the `prevHash` of the first record in every chain. */\nexport const GENESIS_HASH = \"0\".repeat(64);\nexport const MAX_RUN_JOURNAL_ID_LENGTH = 128;\n\n/** Synchronous, pure hash function injected by the caller. Must return 64 lowercase hex chars. */\nexport type RunJournalHashFn = (bytes: Uint8Array) => string;\n\n/** Audit-only journal events; they never open, close, or otherwise affect a run. */\nexport type RunJournalAuditEvent = \"tool_timeout\" | \"tool_late_settlement\" | \"transcript_repaired\";\n\nexport type RunJournalEvent = \"run_started\" | \"run_finished\" | \"run_recovered\" | \"run_abandoned\" | RunJournalAuditEvent;\n\nexport type RunJournalFindingCode =\n\t| \"trailing_fragment\"\n\t| \"invalid_utf8\"\n\t| \"malformed_json\"\n\t| \"schema\"\n\t| \"seq_gap\"\n\t| \"seq_regression\"\n\t| \"hash_shape\"\n\t| \"hash_mismatch\"\n\t| \"hash_chain_break\"\n\t| \"orphan_terminal\"\n\t| \"duplicate_terminal\"\n\t| \"duplicate_start\"\n\t| \"interleaved_run\"\n\t| \"run_unclosed\"\n\t| \"recovered_source_invalid\"\n\t| \"termination_mismatch\"\n\t| \"session_mismatch\"\n\t| \"session_revision_regression\";\n\nexport interface RunJournalRecordBase {\n\treadonly schemaVersion: typeof RUN_JOURNAL_SCHEMA_VERSION;\n\treadonly seq: number;\n\treadonly event: RunJournalEvent;\n\treadonly runId: string;\n\treadonly sessionId: string;\n\treadonly sessionRevision: number;\n\t/** Canonical caller-supplied ISO-8601 UTC instant. */\n\treadonly timestamp: string;\n\t/** Hash of the previous record (`GENESIS_HASH` for the first record). */\n\treadonly prevHash: string;\n\t/** Recomputed hash of this record's canonical material (without `hash`). */\n\treadonly hash: string;\n}\n\nexport interface RunJournalStartedRecord extends RunJournalRecordBase {\n\treadonly event: \"run_started\";\n}\n\nexport interface RunJournalTerminalRecord extends RunJournalRecordBase {\n\treadonly event: \"run_finished\" | \"run_recovered\" | \"run_abandoned\";\n\treadonly termination: SessionTermination;\n}\n\n/** Bounded structured payload persisted with an audit record. */\nexport interface RunJournalAuditDetails {\n\treadonly toolCallId?: string;\n\treadonly toolName?: string;\n\treadonly disposition?: \"completed\" | \"failed\" | \"blocked\" | \"aborted\" | \"timeout\" | \"skipped\";\n\treadonly outcome?: \"resolved\" | \"rejected\";\n\treadonly timeoutMs?: number;\n\treadonly executionStarted?: boolean;\n\treadonly insertedToolCallIds?: readonly string[];\n\treadonly reason?: string;\n\treadonly sessionRisk?: \"elevated\";\n}\n\nexport interface RunJournalAuditRecord extends RunJournalRecordBase {\n\treadonly event: RunJournalAuditEvent;\n\treadonly details: RunJournalAuditDetails;\n}\n\nexport type RunJournalRecord = RunJournalStartedRecord | RunJournalTerminalRecord | RunJournalAuditRecord;\n\nexport interface RunJournalFinding {\n\treadonly code: RunJournalFindingCode;\n\treadonly line?: number;\n\treadonly runId?: string;\n}\n\nexport interface RunJournalCompletePrefix {\n\treadonly byteCount: number;\n\treadonly lineCount: number;\n}\n\nexport interface RunJournalReport {\n\treadonly ok: boolean;\n\treadonly completePrefix: RunJournalCompletePrefix;\n\treadonly trailingByteCount: number;\n\treadonly records: readonly RunJournalRecord[];\n\treadonly openRunId: string | null;\n\treadonly findings: readonly RunJournalFinding[];\n}\n\nexport interface RunJournalConstructorInit {\n\treadonly hashFn: RunJournalHashFn;\n\treadonly sessionId: string;\n\treadonly runId: string;\n\treadonly sessionRevision: number;\n\treadonly timestamp: string;\n\t/**\n\t * When `false`, the constructor does not append the initial `run_started`\n\t * record: the journal starts closed and accepts audit records (and later\n\t * explicit `start()` calls). Default `true` preserves existing behavior.\n\t */\n\treadonly openInitialRun?: boolean;\n\t/**\n\t * Trusted caller-supplied continuation chain-head `prevHash`. Defaults to\n\t * `GENESIS_HASH` for a new journal. The writer treats this as a trusted\n\t * baseline that pins the first record to an external chain; it is never\n\t * re-derived.\n\t */\n\treadonly prevHash?: string;\n\t/**\n\t * Trusted caller-supplied continuation chain-head `seq`. Defaults to `0` for\n\t * a new journal. Treated as a trusted baseline; the writer advances from it\n\t * but never re-derives it.\n\t */\n\treadonly seq?: number;\n}\n\nexport interface RunJournalStartInput {\n\treadonly runId: string;\n\treadonly sessionRevision: number;\n\treadonly timestamp: string;\n}\n\nexport interface RunJournalTerminalInput {\n\treadonly termination: SessionTermination;\n\treadonly sessionRevision: number;\n\treadonly timestamp: string;\n}\n\nexport interface RunJournalAuditInput {\n\treadonly event: RunJournalAuditEvent;\n\treadonly details: RunJournalAuditDetails;\n\treadonly sessionRevision: number;\n\treadonly timestamp: string;\n}\n\nconst HASH64 = /^[0-9a-f]{64}$/;\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder(\"utf-8\", { fatal: true });\n\nconst RUN_JOURNAL_EVENTS: ReadonlySet<RunJournalEvent> = new Set<RunJournalEvent>([\n\t\"run_started\",\n\t\"run_finished\",\n\t\"run_recovered\",\n\t\"run_abandoned\",\n\t\"tool_timeout\",\n\t\"tool_late_settlement\",\n\t\"transcript_repaired\",\n]);\nconst TERMINAL_EVENTS: ReadonlySet<RunJournalEvent> = new Set<RunJournalEvent>([\n\t\"run_finished\",\n\t\"run_recovered\",\n\t\"run_abandoned\",\n]);\nconst AUDIT_EVENTS: ReadonlySet<RunJournalEvent> = new Set<RunJournalEvent>([\n\t\"tool_timeout\",\n\t\"tool_late_settlement\",\n\t\"transcript_repaired\",\n]);\nconst AUDIT_DETAIL_KEYS = [\n\t\"toolCallId\",\n\t\"toolName\",\n\t\"disposition\",\n\t\"outcome\",\n\t\"timeoutMs\",\n\t\"executionStarted\",\n\t\"insertedToolCallIds\",\n\t\"reason\",\n\t\"sessionRisk\",\n] as const;\nconst AUDIT_DISPOSITIONS: ReadonlySet<string> = new Set([\n\t\"completed\",\n\t\"failed\",\n\t\"blocked\",\n\t\"aborted\",\n\t\"timeout\",\n\t\"skipped\",\n]);\nconst AUDIT_OUTCOMES: ReadonlySet<string> = new Set([\"resolved\", \"rejected\"]);\nconst MAX_AUDIT_INSERTED_IDS = 64;\nconst MAX_AUDIT_REASON_LENGTH = 512;\nconst COMMON_RECORD_KEYS = [\n\t\"schemaVersion\",\n\t\"seq\",\n\t\"event\",\n\t\"runId\",\n\t\"sessionId\",\n\t\"sessionRevision\",\n\t\"timestamp\",\n\t\"prevHash\",\n\t\"hash\",\n] as const;\n\nconst SESSION_TERMINATION_KINDS: ReadonlySet<string> = new Set([\n\t\"completed\",\n\t\"user_abort\",\n\t\"provider_abort\",\n\t\"provider_auth\",\n\t\"provider_rate_limit\",\n\t\"provider_network\",\n\t\"provider_protocol\",\n\t\"context_overflow\",\n\t\"tool_timeout\",\n\t\"tool_fatal\",\n\t\"compaction\",\n\t\"persistence\",\n\t\"process_signal\",\n\t\"process_crash\",\n\t\"transcript_invalid\",\n\t\"configuration\",\n\t\"internal_error\",\n]);\nconst SESSION_TERMINATION_PHASES: ReadonlySet<string> = new Set([\n\t\"completed\",\n\t\"control\",\n\t\"preflight\",\n\t\"provider\",\n\t\"tool\",\n\t\"compaction\",\n\t\"persistence\",\n\t\"process\",\n\t\"resume\",\n]);\nconst SESSION_TERMINATION_SOURCES: ReadonlySet<string> = new Set([\"observed\", \"inferred_on_resume\"]);\nconst SESSION_SIDE_EFFECTS: ReadonlySet<string> = new Set([\"none\", \"possible\", \"confirmed\"]);\nconst SESSION_PROCESS_SIGNALS: ReadonlySet<string> = new Set([\"SIGINT\", \"SIGTERM\", \"SIGHUP\", \"SIGQUIT\"]);\nconst SESSION_TRANSCRIPT_ISSUES: ReadonlySet<string> = new Set([\n\t\"missing_result\",\n\t\"duplicate_result\",\n\t\"orphan_result\",\n\t\"duplicate_call_id\",\n\t\"interleaved_non_result\",\n\t\"invalid_jsonl\",\n\t\"invalid_tree\",\n\t\"unsupported_version\",\n\t\"trailing_fragment\",\n]);\nconst TERMINATION_ALLOWED_KEYS = [\n\t\"schemaVersion\",\n\t\"sessionId\",\n\t\"runId\",\n\t\"kind\",\n\t\"phase\",\n\t\"source\",\n\t\"message\",\n\t\"causeCode\",\n\t\"nextAction\",\n\t\"retryable\",\n\t\"safeToAutoRetry\",\n\t\"sideEffects\",\n\t\"timestamp\",\n\t\"retryAfterMs\",\n\t\"provider\",\n\t\"model\",\n\t\"toolCallId\",\n\t\"toolName\",\n\t\"processSignal\",\n\t\"transcriptIssue\",\n] as const;\n\n/** High-confidence credential shapes; rejected at every trust boundary. */\nconst CREDENTIAL_SHAPES = [\n\t/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,\n\t/\\bsk-[A-Za-z0-9_-]{16,}\\b/,\n\t/\\bgh[pousr]_[A-Za-z0-9]{16,}\\b/,\n\t/\\bgithub_pat_[A-Za-z0-9_]{16,}\\b/,\n\t/\\bxox[baprs]-[A-Za-z0-9-]{16,}\\b/,\n\t/\\bAKIA[A-Z0-9]{16}\\b/,\n\t/\\beyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\b/,\n\t/\\bBearer\\s+[A-Za-z0-9._~+/-]{8,}={0,2}\\b/i,\n\t/(?:^|[^A-Za-z0-9])(?:[A-Za-z0-9]+[_-])*(?:authorization|api[-_ ]?key|access[-_ ]?token|token|password|secret(?:[-_ ]?key)?|private[-_ ]?key|cookie)[\"']?\\s*[:=]/i,\n] as const;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Asserts `value` is a plain data record: an object (never an array) with a\n * plain prototype, only data (non-accessor) own properties, and no keys outside\n * `allowedKeys`. Descriptors are inspected without ever executing a getter, so\n * raw accessor execution is never exposed at the trust boundary. Returns void;\n * it narrows nothing so typed callers keep their static field types.\n */\nfunction assertPlainDataRecord(value: unknown, name: string, allowedKeys: readonly string[]): void {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new TypeError(`${name} must be a plain object`);\n\t}\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (prototype !== null && prototype !== Object.prototype) {\n\t\tthrow new TypeError(`${name} must be a plain object`);\n\t}\n\tconst descriptors = Object.getOwnPropertyDescriptors(value);\n\tfor (const key of Object.keys(descriptors)) {\n\t\tconst descriptor = descriptors[key];\n\t\tif (descriptor !== undefined && !(\"value\" in descriptor)) {\n\t\t\tthrow new TypeError(`${name} must not define accessor properties`);\n\t\t}\n\t\tif (!allowedKeys.includes(key)) {\n\t\t\tthrow new TypeError(`${name} must contain only bounded fields`);\n\t\t}\n\t}\n}\n\nfunction looksLikeCredential(value: string): boolean {\n\treturn CREDENTIAL_SHAPES.some((pattern) => pattern.test(value));\n}\n\nfunction isBoundedIdentifier(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.length > 0 &&\n\t\tvalue.length <= MAX_RUN_JOURNAL_ID_LENGTH &&\n\t\t!/[\\u0000-\\u001f\\u007f]/.test(value)\n\t);\n}\n\nfunction assertIdentifier(value: unknown, name: string, maxLength: number): asserts value is string {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > maxLength) {\n\t\tthrow new TypeError(`${name} must be 1-${maxLength} characters of bounded text`);\n\t}\n\tif (/[\\u0000-\\u001f\\u007f]/.test(value)) {\n\t\tthrow new TypeError(`${name} must not contain C0 or DEL control characters`);\n\t}\n}\n\nfunction rejectCredential(value: string, name: string): void {\n\tif (looksLikeCredential(value)) {\n\t\tthrow new TypeError(`${name} contains a credential-shaped literal`);\n\t}\n}\n\nfunction isCanonicalTimestamp(value: unknown): value is string {\n\tif (typeof value !== \"string\") return false;\n\tconst parsed = new Date(value);\n\treturn Number.isFinite(parsed.getTime()) && parsed.toISOString() === value;\n}\n\nfunction assertCanonicalTimestamp(value: unknown, name: string): asserts value is string {\n\tif (!isCanonicalTimestamp(value)) {\n\t\tthrow new TypeError(`${name} must be a canonical ISO-8601 UTC instant`);\n\t}\n}\n\nfunction assertSafeNonNegativeInt(value: unknown, name: string): asserts value is number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n\t\tthrow new TypeError(`${name} must be a non-negative safe integer`);\n\t}\n}\n\nfunction isValidHashShape(value: unknown): value is string {\n\treturn typeof value === \"string\" && HASH64.test(value);\n}\n\nfunction assertHashShape(value: unknown, name: string): asserts value is string {\n\tif (!isValidHashShape(value)) {\n\t\tthrow new TypeError(`${name} must be 64 lowercase hex characters`);\n\t}\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n\tfor (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child);\n\treturn Object.freeze(value);\n}\n\n/** Recursively key-sorted JSON serialization. Deterministic across runtimes and key insertion order. */\nexport function canonicalJson(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n\tif (typeof value === \"object\") {\n\t\tconst object = value as Record<string, unknown>;\n\t\tconst parts: string[] = [];\n\t\tfor (const key of Object.keys(object).sort()) {\n\t\t\tconst child = object[key];\n\t\t\tif (child === undefined) continue;\n\t\t\tparts.push(`${JSON.stringify(key)}:${canonicalJson(child)}`);\n\t\t}\n\t\treturn `{${parts.join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value);\n}\n\n/** Defensively drop a stray `hash` key so the material never includes it, regardless of caller. */\nfunction stripHashKey(record: unknown): Record<string, unknown> {\n\tif (typeof record !== \"object\" || record === null) return {};\n\tconst clone: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(record)) {\n\t\tif (key !== \"hash\") clone[key] = value;\n\t}\n\treturn clone;\n}\n\n/** Canonical material of a record (everything except `hash`) over which the hash is computed. */\nexport function serializeRunJournalMaterial(record: Readonly<Omit<RunJournalRecord, \"hash\">>): string {\n\treturn canonicalJson(stripHashKey(record));\n}\n\n/** Canonical, key-sorted serialization of a full record (including `hash`). */\nexport function serializeRunJournalLine(record: Readonly<RunJournalRecord>): string {\n\treturn canonicalJson(record);\n}\n\nfunction assertBoundedSessionTermination(\n\tvalue: unknown,\n\texpectedRunId: string,\n\texpectedSessionId: string,\n): asserts value is SessionTermination {\n\tassertPlainDataRecord(value, \"termination\", TERMINATION_ALLOWED_KEYS);\n\tconst v = value as Record<string, unknown>;\n\tif (v.schemaVersion !== SESSION_TERMINATION_SCHEMA_VERSION) {\n\t\tthrow new TypeError(\"termination schemaVersion must match the supported version\");\n\t}\n\tif (typeof v.runId !== \"string\" || v.runId !== expectedRunId) {\n\t\tthrow new TypeError(\"termination runId must match the record runId\");\n\t}\n\tif (typeof v.sessionId !== \"string\" || v.sessionId !== expectedSessionId) {\n\t\tthrow new TypeError(\"termination sessionId must match the record sessionId\");\n\t}\n\tif (typeof v.kind !== \"string\" || !SESSION_TERMINATION_KINDS.has(v.kind)) {\n\t\tthrow new TypeError(\"termination kind is out of bounds\");\n\t}\n\tif (typeof v.phase !== \"string\" || !SESSION_TERMINATION_PHASES.has(v.phase)) {\n\t\tthrow new TypeError(\"termination phase is out of bounds\");\n\t}\n\tif (typeof v.source !== \"string\" || !SESSION_TERMINATION_SOURCES.has(v.source)) {\n\t\tthrow new TypeError(\"termination source is out of bounds\");\n\t}\n\tif (typeof v.message !== \"string\") {\n\t\tthrow new TypeError(\"termination message must be a string\");\n\t}\n\tassertPreRedactedTerminationMessage(v.message);\n\tif (typeof v.causeCode !== \"string\" || !/^[a-z_]+\\.[a-z_]+$/.test(v.causeCode)) {\n\t\tthrow new TypeError(\"termination causeCode is out of bounds\");\n\t}\n\tif (typeof v.nextAction !== \"string\") {\n\t\tthrow new TypeError(\"termination nextAction must be a string\");\n\t}\n\tassertPreRedactedTerminationMessage(v.nextAction);\n\tif (typeof v.retryable !== \"boolean\" || typeof v.safeToAutoRetry !== \"boolean\") {\n\t\tthrow new TypeError(\"termination retry flags must be booleans\");\n\t}\n\tif (typeof v.sideEffects !== \"string\" || !SESSION_SIDE_EFFECTS.has(v.sideEffects)) {\n\t\tthrow new TypeError(\"termination sideEffects is out of bounds\");\n\t}\n\tassertCanonicalTimestamp(v.timestamp, \"termination.timestamp\");\n\tif (v.retryAfterMs !== undefined) assertSafeNonNegativeInt(v.retryAfterMs, \"termination.retryAfterMs\");\n\tif (v.provider !== undefined) {\n\t\tassertIdentifier(v.provider, \"termination.provider\", 128);\n\t\trejectCredential(v.provider, \"termination.provider\");\n\t}\n\tif (v.model !== undefined) {\n\t\tassertIdentifier(v.model, \"termination.model\", 256);\n\t\trejectCredential(v.model, \"termination.model\");\n\t}\n\tif (v.toolCallId !== undefined) {\n\t\tassertIdentifier(v.toolCallId, \"termination.toolCallId\", 512);\n\t\trejectCredential(v.toolCallId, \"termination.toolCallId\");\n\t}\n\tif (v.toolName !== undefined) {\n\t\tassertIdentifier(v.toolName, \"termination.toolName\", 128);\n\t\trejectCredential(v.toolName, \"termination.toolName\");\n\t}\n\tif (v.processSignal !== undefined) {\n\t\tif (typeof v.processSignal !== \"string\" || !SESSION_PROCESS_SIGNALS.has(v.processSignal)) {\n\t\t\tthrow new TypeError(\"termination processSignal is out of bounds\");\n\t\t}\n\t}\n\tif (v.transcriptIssue !== undefined) {\n\t\tif (typeof v.transcriptIssue !== \"string\" || !SESSION_TRANSCRIPT_ISSUES.has(v.transcriptIssue)) {\n\t\t\tthrow new TypeError(\"termination transcriptIssue is out of bounds\");\n\t\t}\n\t}\n\tassertTerminationCoherence(v as unknown as SessionTermination);\n}\n\nfunction assertTerminationCoherence(termination: SessionTermination): void {\n\tconst dot = termination.causeCode.indexOf(\".\");\n\tconst area = dot >= 0 ? termination.causeCode.slice(0, dot) : \"\";\n\tconst suffix = dot >= 0 ? termination.causeCode.slice(dot + 1) : \"\";\n\n\tlet expectedKind: string;\n\tlet expectedPhase: string;\n\tlet expectedRetryable: boolean;\n\tlet processSignalRequired = false;\n\tlet transcriptRequired = false;\n\tlet transcriptSuffix: string | null = null;\n\n\tswitch (area) {\n\t\tcase \"session\":\n\t\t\tif (suffix === \"completed\") {\n\t\t\t\texpectedKind = \"completed\";\n\t\t\t\texpectedPhase = \"completed\";\n\t\t\t\texpectedRetryable = false;\n\t\t\t} else if (suffix === \"user_abort\") {\n\t\t\t\texpectedKind = \"user_abort\";\n\t\t\t\texpectedPhase = \"control\";\n\t\t\t\texpectedRetryable = false;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"provider\":\n\t\t\tswitch (suffix) {\n\t\t\t\tcase \"abort\":\n\t\t\t\t\texpectedKind = \"provider_abort\";\n\t\t\t\t\texpectedPhase = \"provider\";\n\t\t\t\t\texpectedRetryable = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"auth\":\n\t\t\t\t\texpectedKind = \"provider_auth\";\n\t\t\t\t\texpectedPhase = \"provider\";\n\t\t\t\t\texpectedRetryable = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"rate_limit\":\n\t\t\t\t\texpectedKind = \"provider_rate_limit\";\n\t\t\t\t\texpectedPhase = \"provider\";\n\t\t\t\t\texpectedRetryable = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"network\":\n\t\t\t\t\texpectedKind = \"provider_network\";\n\t\t\t\t\texpectedPhase = \"provider\";\n\t\t\t\t\texpectedRetryable = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"protocol\":\n\t\t\t\t\texpectedKind = \"provider_protocol\";\n\t\t\t\t\texpectedPhase = \"provider\";\n\t\t\t\t\texpectedRetryable = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"context_overflow\":\n\t\t\t\t\texpectedKind = \"context_overflow\";\n\t\t\t\t\texpectedPhase = \"provider\";\n\t\t\t\t\texpectedRetryable = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\tif (suffix === \"timeout\") {\n\t\t\t\texpectedKind = \"tool_timeout\";\n\t\t\t\texpectedPhase = \"tool\";\n\t\t\t\texpectedRetryable = true;\n\t\t\t} else if (suffix === \"fatal\") {\n\t\t\t\texpectedKind = \"tool_fatal\";\n\t\t\t\texpectedPhase = \"tool\";\n\t\t\t\texpectedRetryable = false;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"compaction\":\n\t\t\tif (suffix === \"aborted\" || suffix === \"failed\" || suffix === \"stale\") {\n\t\t\t\texpectedKind = \"compaction\";\n\t\t\t\texpectedPhase = \"compaction\";\n\t\t\t\texpectedRetryable = true;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"persistence\":\n\t\t\tif (\n\t\t\t\tsuffix === \"read_failed\" ||\n\t\t\t\tsuffix === \"append_failed\" ||\n\t\t\t\tsuffix === \"replace_failed\" ||\n\t\t\t\tsuffix === \"fsync_failed\" ||\n\t\t\t\tsuffix === \"lock_failed\"\n\t\t\t) {\n\t\t\t\texpectedKind = \"persistence\";\n\t\t\t\texpectedPhase = \"persistence\";\n\t\t\t\texpectedRetryable = true;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"process\":\n\t\t\tif (suffix === \"signal\") {\n\t\t\t\texpectedKind = \"process_signal\";\n\t\t\t\texpectedPhase = \"process\";\n\t\t\t\texpectedRetryable = false;\n\t\t\t\tprocessSignalRequired = true;\n\t\t\t} else if (suffix === \"crash\") {\n\t\t\t\texpectedKind = \"process_crash\";\n\t\t\t\texpectedPhase = \"resume\";\n\t\t\t\texpectedRetryable = true;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"transcript\":\n\t\t\tif (SESSION_TRANSCRIPT_ISSUES.has(suffix)) {\n\t\t\t\texpectedKind = \"transcript_invalid\";\n\t\t\t\texpectedPhase = termination.source === \"inferred_on_resume\" ? \"resume\" : \"preflight\";\n\t\t\t\texpectedRetryable = false;\n\t\t\t\ttranscriptRequired = true;\n\t\t\t\ttranscriptSuffix = suffix;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"configuration\":\n\t\t\tif (suffix === \"invalid\") {\n\t\t\t\texpectedKind = \"configuration\";\n\t\t\t\texpectedPhase = \"preflight\";\n\t\t\t\texpectedRetryable = false;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"internal\":\n\t\t\tif (suffix === \"unclassified\") {\n\t\t\t\texpectedKind = \"internal_error\";\n\t\t\t\texpectedPhase = \"preflight\";\n\t\t\t\texpectedRetryable = false;\n\t\t\t} else {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t}\n\n\tif (termination.kind !== expectedKind) {\n\t\tthrow new TypeError(\"termination kind is incoherent with causeCode\");\n\t}\n\tif (termination.phase !== expectedPhase) {\n\t\tthrow new TypeError(\"termination phase is incoherent with causeCode\");\n\t}\n\tif (termination.retryable !== expectedRetryable) {\n\t\tthrow new TypeError(\"termination retryable flag is incoherent with causeCode\");\n\t}\n\tif (processSignalRequired) {\n\t\tif (termination.processSignal === undefined) {\n\t\t\tthrow new TypeError(\"termination processSignal is required for signal causes\");\n\t\t}\n\t} else if (termination.processSignal !== undefined) {\n\t\tthrow new TypeError(\"termination processSignal is only valid for signal causes\");\n\t}\n\tif (transcriptRequired) {\n\t\tif (termination.transcriptIssue === undefined) {\n\t\t\tthrow new TypeError(\"termination transcriptIssue is required for transcript causes\");\n\t\t} else if (termination.transcriptIssue !== transcriptSuffix) {\n\t\t\tthrow new TypeError(\"termination transcriptIssue must match the transcript cause\");\n\t\t}\n\t} else if (termination.transcriptIssue !== undefined) {\n\t\tthrow new TypeError(\"termination transcriptIssue is only valid for transcript causes\");\n\t}\n\n\tconst expectedSafeToAutoRetry =\n\t\ttermination.retryable &&\n\t\ttermination.source === \"observed\" &&\n\t\ttermination.sideEffects === \"none\" &&\n\t\t(termination.kind === \"provider_rate_limit\" || termination.kind === \"provider_network\");\n\tif (termination.safeToAutoRetry !== expectedSafeToAutoRetry) {\n\t\tthrow new TypeError(\"termination safeToAutoRetry flag is incoherent\");\n\t}\n}\n\nfunction assertBoundedAuditDetails(value: unknown): asserts value is RunJournalAuditDetails {\n\tassertPlainDataRecord(value, \"audit details\", AUDIT_DETAIL_KEYS);\n\tconst v = value as Record<string, unknown>;\n\tif (v.toolCallId !== undefined) {\n\t\tassertIdentifier(v.toolCallId, \"details.toolCallId\", 512);\n\t\trejectCredential(v.toolCallId, \"details.toolCallId\");\n\t}\n\tif (v.toolName !== undefined) {\n\t\tassertIdentifier(v.toolName, \"details.toolName\", 128);\n\t\trejectCredential(v.toolName, \"details.toolName\");\n\t}\n\tif (v.disposition !== undefined && (typeof v.disposition !== \"string\" || !AUDIT_DISPOSITIONS.has(v.disposition))) {\n\t\tthrow new TypeError(\"details.disposition is out of bounds\");\n\t}\n\tif (v.outcome !== undefined && (typeof v.outcome !== \"string\" || !AUDIT_OUTCOMES.has(v.outcome))) {\n\t\tthrow new TypeError(\"details.outcome is out of bounds\");\n\t}\n\tif (v.timeoutMs !== undefined) {\n\t\tassertSafeNonNegativeInt(v.timeoutMs, \"details.timeoutMs\");\n\t}\n\tif (v.executionStarted !== undefined && typeof v.executionStarted !== \"boolean\") {\n\t\tthrow new TypeError(\"details.executionStarted must be a boolean\");\n\t}\n\tif (v.insertedToolCallIds !== undefined) {\n\t\tif (!Array.isArray(v.insertedToolCallIds) || v.insertedToolCallIds.length > MAX_AUDIT_INSERTED_IDS) {\n\t\t\tthrow new TypeError(\"details.insertedToolCallIds must be a bounded array\");\n\t\t}\n\t\tfor (const id of v.insertedToolCallIds) {\n\t\t\tassertIdentifier(id, \"details.insertedToolCallIds[]\", 512);\n\t\t\trejectCredential(id, \"details.insertedToolCallIds[]\");\n\t\t}\n\t}\n\tif (v.reason !== undefined) {\n\t\tassertIdentifier(v.reason, \"details.reason\", MAX_AUDIT_REASON_LENGTH);\n\t\trejectCredential(v.reason, \"details.reason\");\n\t}\n\tif (v.sessionRisk !== undefined && v.sessionRisk !== \"elevated\") {\n\t\tthrow new TypeError(\"details.sessionRisk is out of bounds\");\n\t}\n}\n\nfunction isTerminalCoherentWithEvent(\n\tevent: \"run_finished\" | \"run_recovered\" | \"run_abandoned\",\n\ttermination: SessionTermination,\n): boolean {\n\tif (event === \"run_recovered\") {\n\t\treturn (\n\t\t\ttermination.source === \"inferred_on_resume\" &&\n\t\t\ttermination.kind === \"process_crash\" &&\n\t\t\ttermination.phase === \"resume\"\n\t\t);\n\t}\n\tif (termination.source !== \"observed\") return false;\n\t// process_crash is only coherent with an inferred_on_resume (run_recovered) source.\n\tif (termination.kind === \"process_crash\") return false;\n\treturn true;\n}\n\nfunction assertTerminalCoherentWithEvent(\n\tevent: \"run_finished\" | \"run_recovered\" | \"run_abandoned\",\n\ttermination: SessionTermination,\n): void {\n\tif (isTerminalCoherentWithEvent(event, termination)) return;\n\tif (event === \"run_recovered\") {\n\t\tthrow new TypeError(\n\t\t\t\"run_recovered requires a coherent process_crash termination (source inferred_on_resume, phase resume)\",\n\t\t);\n\t}\n\tif (termination.kind === \"process_crash\") {\n\t\tthrow new TypeError(\"process_crash terminations may only appear on run_recovered events\");\n\t}\n\tthrow new TypeError(\"run_finished and run_abandoned require a termination source of observed\");\n}\n\n/**\n * Append-only run-journal writer. The constructor records the first\n * `run_started` event (and recomputes its hash); {@link RunJournal.start} opens\n * subsequent runs after a terminal event, while {@link RunJournal.finish},\n * {@link RunJournal.abandon}, and {@link RunJournal.recover} close the currently\n * open run. Exactly one run is open at a time.\n */\nexport class RunJournal {\n\tprivate readonly hashFn: RunJournalHashFn;\n\tprivate readonly sessionId: string;\n\tprivate readonly startedRunIds: Set<string> = new Set();\n\tprivate readonly terminatedRunIds: Set<string> = new Set();\n\tprivate readonly mutableRecords: RunJournalRecord[] = [];\n\tprivate recordsSnapshot: readonly RunJournalRecord[] = Object.freeze([]) as readonly RunJournalRecord[];\n\tprivate lastSessionRevision = 0;\n\tprivate prevHash: string;\n\tprivate nextSeq: number;\n\tprivate openRun: { readonly runId: string; readonly sessionId: string } | null = null;\n\n\tconstructor(init: RunJournalConstructorInit) {\n\t\tassertPlainDataRecord(init, \"RunJournalConstructorInit\", [\n\t\t\t\"hashFn\",\n\t\t\t\"sessionId\",\n\t\t\t\"runId\",\n\t\t\t\"sessionRevision\",\n\t\t\t\"timestamp\",\n\t\t\t\"prevHash\",\n\t\t\t\"seq\",\n\t\t\t\"openInitialRun\",\n\t\t]);\n\t\tif (init.openInitialRun !== undefined && typeof init.openInitialRun !== \"boolean\") {\n\t\t\tthrow new TypeError(\"openInitialRun must be a boolean\");\n\t\t}\n\t\tif (typeof init.hashFn !== \"function\") {\n\t\t\tthrow new TypeError(\"hashFn must be a function\");\n\t\t}\n\t\tthis.hashFn = init.hashFn;\n\t\tassertIdentifier(init.sessionId, \"sessionId\", MAX_RUN_JOURNAL_ID_LENGTH);\n\t\trejectCredential(init.sessionId, \"sessionId\");\n\t\tthis.sessionId = init.sessionId;\n\t\tconst startSeq = init.seq ?? 0;\n\t\tassertSafeNonNegativeInt(startSeq, \"seq\");\n\t\tconst startPrevHash = init.prevHash ?? GENESIS_HASH;\n\t\tassertHashShape(startPrevHash, \"prevHash\");\n\t\tthis.prevHash = startPrevHash;\n\t\tthis.nextSeq = startSeq;\n\t\tif (init.openInitialRun !== false) {\n\t\t\tthis.appendStarted({\n\t\t\t\trunId: init.runId,\n\t\t\t\tsessionRevision: init.sessionRevision,\n\t\t\t\ttimestamp: init.timestamp,\n\t\t\t});\n\t\t} else {\n\t\t\t// Audit-first journal: validate the seed runId shape, append nothing.\n\t\t\tassertIdentifier(init.runId, \"runId\", MAX_RUN_JOURNAL_ID_LENGTH);\n\t\t\trejectCredential(init.runId, \"runId\");\n\t\t}\n\t}\n\n\tstart(input: RunJournalStartInput): RunJournalStartedRecord {\n\t\treturn this.appendStarted(input);\n\t}\n\n\tfinish(input: RunJournalTerminalInput): RunJournalTerminalRecord {\n\t\treturn this.appendTerminal(\"run_finished\", input);\n\t}\n\n\tabandon(input: RunJournalTerminalInput): RunJournalTerminalRecord {\n\t\treturn this.appendTerminal(\"run_abandoned\", input);\n\t}\n\n\trecover(input: RunJournalTerminalInput): RunJournalTerminalRecord {\n\t\treturn this.appendTerminal(\"run_recovered\", input);\n\t}\n\n\t/**\n\t * Append an audit-only record. Allowed with or without an open run; never\n\t * opens, closes, or otherwise mutates run state. The record joins the same\n\t * seq/hash chain as lifecycle records.\n\t */\n\taudit(input: RunJournalAuditInput): RunJournalAuditRecord {\n\t\tassertPlainDataRecord(input, \"RunJournalAuditInput\", [\"event\", \"details\", \"sessionRevision\", \"timestamp\"]);\n\t\tif (typeof input.event !== \"string\" || !AUDIT_EVENTS.has(input.event as RunJournalEvent)) {\n\t\t\tthrow new TypeError(\"audit event is out of bounds\");\n\t\t}\n\t\tassertSafeNonNegativeInt(input.sessionRevision, \"sessionRevision\");\n\t\tif (input.sessionRevision < this.lastSessionRevision) {\n\t\t\tthrow new Error(\"sessionRevision must not regress across the journal\");\n\t\t}\n\t\tassertCanonicalTimestamp(input.timestamp, \"timestamp\");\n\t\tassertBoundedAuditDetails(input.details);\n\t\tconst base: Omit<RunJournalAuditRecord, \"hash\"> = {\n\t\t\tschemaVersion: RUN_JOURNAL_SCHEMA_VERSION,\n\t\t\tseq: this.nextSeq,\n\t\t\tevent: input.event as RunJournalAuditEvent,\n\t\t\trunId: this.openRun === null ? \"none\" : this.openRun.runId,\n\t\t\tsessionId: this.sessionId,\n\t\t\tsessionRevision: input.sessionRevision,\n\t\t\ttimestamp: input.timestamp,\n\t\t\tprevHash: this.prevHash,\n\t\t\tdetails: input.details,\n\t\t};\n\t\tconst record = this.seal(base);\n\t\tthis.mutableRecords.push(record);\n\t\tthis.prevHash = record.hash;\n\t\tthis.nextSeq += 1;\n\t\tthis.lastSessionRevision = input.sessionRevision;\n\t\tthis.refreshRecordsSnapshot();\n\t\treturn record;\n\t}\n\n\tget records(): readonly RunJournalRecord[] {\n\t\treturn this.recordsSnapshot;\n\t}\n\n\tget openRunId(): string | null {\n\t\treturn this.openRun === null ? null : this.openRun.runId;\n\t}\n\n\tserialize(): string {\n\t\tif (this.mutableRecords.length === 0) return \"\";\n\t\treturn `${this.mutableRecords.map((record) => serializeRunJournalLine(record)).join(\"\\n\")}\\n`;\n\t}\n\n\ttoBytes(): Uint8Array {\n\t\treturn TEXT_ENCODER.encode(this.serialize());\n\t}\n\n\tprivate refreshRecordsSnapshot(): void {\n\t\tthis.recordsSnapshot = Object.freeze([...this.mutableRecords]) as readonly RunJournalRecord[];\n\t}\n\n\tprivate appendStarted(input: RunJournalStartInput): RunJournalStartedRecord {\n\t\tassertPlainDataRecord(input, \"RunJournalStartInput\", [\"runId\", \"sessionRevision\", \"timestamp\"]);\n\t\tassertIdentifier(input.runId, \"runId\", MAX_RUN_JOURNAL_ID_LENGTH);\n\t\trejectCredential(input.runId, \"runId\");\n\t\tassertSafeNonNegativeInt(input.sessionRevision, \"sessionRevision\");\n\t\tif (input.sessionRevision < this.lastSessionRevision) {\n\t\t\tthrow new Error(\"sessionRevision must not regress across the journal\");\n\t\t}\n\t\tassertCanonicalTimestamp(input.timestamp, \"timestamp\");\n\t\tif (this.openRun !== null) {\n\t\t\tthrow new Error(\"a run is already open; terminate it before starting another\");\n\t\t}\n\t\tif (this.startedRunIds.has(input.runId)) {\n\t\t\tthrow new Error(\"runId was already started earlier in this journal\");\n\t\t}\n\t\tconst base: Omit<RunJournalStartedRecord, \"hash\"> = {\n\t\t\tschemaVersion: RUN_JOURNAL_SCHEMA_VERSION,\n\t\t\tseq: this.nextSeq,\n\t\t\tevent: \"run_started\",\n\t\t\trunId: input.runId,\n\t\t\tsessionId: this.sessionId,\n\t\t\tsessionRevision: input.sessionRevision,\n\t\t\ttimestamp: input.timestamp,\n\t\t\tprevHash: this.prevHash,\n\t\t};\n\t\tconst record = this.seal(base);\n\t\tthis.mutableRecords.push(record);\n\t\tthis.startedRunIds.add(input.runId);\n\t\tthis.openRun = Object.freeze({ runId: input.runId, sessionId: this.sessionId });\n\t\tthis.prevHash = record.hash;\n\t\tthis.nextSeq += 1;\n\t\tthis.lastSessionRevision = input.sessionRevision;\n\t\tthis.refreshRecordsSnapshot();\n\t\treturn record;\n\t}\n\n\tprivate appendTerminal(\n\t\tevent: \"run_finished\" | \"run_recovered\" | \"run_abandoned\",\n\t\tinput: RunJournalTerminalInput,\n\t): RunJournalTerminalRecord {\n\t\tassertPlainDataRecord(input, \"RunJournalTerminalInput\", [\"termination\", \"sessionRevision\", \"timestamp\"]);\n\t\tif (this.openRun === null) {\n\t\t\tthrow new Error(\"no run is open; start a run before terminating it\");\n\t\t}\n\t\tassertSafeNonNegativeInt(input.sessionRevision, \"sessionRevision\");\n\t\tif (input.sessionRevision < this.lastSessionRevision) {\n\t\t\tthrow new Error(\"sessionRevision must not regress across the journal\");\n\t\t}\n\t\tassertCanonicalTimestamp(input.timestamp, \"timestamp\");\n\t\tassertBoundedSessionTermination(input.termination, this.openRun.runId, this.sessionId);\n\t\tassertTerminalCoherentWithEvent(event, input.termination);\n\t\tif (input.timestamp !== input.termination.timestamp) {\n\t\t\tthrow new TypeError(\"terminal event timestamp must equal termination timestamp\");\n\t\t}\n\t\tif (this.terminatedRunIds.has(this.openRun.runId)) {\n\t\t\tthrow new Error(\"the open run was already terminated\");\n\t\t}\n\t\tconst base: Omit<RunJournalTerminalRecord, \"hash\"> = {\n\t\t\tschemaVersion: RUN_JOURNAL_SCHEMA_VERSION,\n\t\t\tseq: this.nextSeq,\n\t\t\tevent,\n\t\t\trunId: this.openRun.runId,\n\t\t\tsessionId: this.sessionId,\n\t\t\tsessionRevision: input.sessionRevision,\n\t\t\ttimestamp: input.timestamp,\n\t\t\tprevHash: this.prevHash,\n\t\t\ttermination: input.termination,\n\t\t};\n\t\tconst record = this.seal(base);\n\t\tthis.mutableRecords.push(record);\n\t\tthis.terminatedRunIds.add(this.openRun.runId);\n\t\tthis.openRun = null;\n\t\tthis.prevHash = record.hash;\n\t\tthis.nextSeq += 1;\n\t\tthis.lastSessionRevision = input.sessionRevision;\n\t\tthis.refreshRecordsSnapshot();\n\t\treturn record;\n\t}\n\n\tprivate seal<T extends Omit<RunJournalRecord, \"hash\">>(base: T): T & { readonly hash: string } {\n\t\tconst material = serializeRunJournalMaterial(base);\n\t\tlet hash: string;\n\t\ttry {\n\t\t\thash = this.hashFn(TEXT_ENCODER.encode(material));\n\t\t} catch (error) {\n\t\t\tthrow new TypeError(\"hashFn threw while sealing a record; failing closed\", { cause: error });\n\t\t}\n\t\tif (!isValidHashShape(hash)) {\n\t\t\tthrow new TypeError(\"hashFn must return 64 lowercase hex characters\");\n\t\t}\n\t\treturn deepFreeze({ ...base, hash }) as T & { readonly hash: string };\n\t}\n}\n\ninterface CommonShape {\n\treadonly schemaVersion: 1;\n\treadonly seq: number;\n\treadonly event: RunJournalEvent;\n\treadonly runId: string;\n\treadonly sessionId: string;\n\treadonly sessionRevision: number;\n\treadonly timestamp: string;\n\treadonly prevHash: string;\n\treadonly hash: string;\n}\n\nfunction validateCommonShape(value: unknown): CommonShape | null {\n\tif (!isPlainObject(value)) return null;\n\tconst rawEvent = (value as { event?: unknown }).event;\n\tconst isTerminal = typeof rawEvent === \"string\" && TERMINAL_EVENTS.has(rawEvent as RunJournalEvent);\n\tconst isAudit = typeof rawEvent === \"string\" && AUDIT_EVENTS.has(rawEvent as RunJournalEvent);\n\tconst allowed: readonly string[] = isTerminal\n\t\t? [...COMMON_RECORD_KEYS, \"termination\"]\n\t\t: isAudit\n\t\t\t? [...COMMON_RECORD_KEYS, \"details\"]\n\t\t\t: COMMON_RECORD_KEYS;\n\tif (Object.keys(value).some((key) => !allowed.includes(key))) {\n\t\treturn null;\n\t}\n\tconst hasTermination = \"termination\" in value;\n\tif (isTerminal !== hasTermination) return null;\n\tif (isAudit !== \"details\" in value) return null;\n\tif (value.schemaVersion !== RUN_JOURNAL_SCHEMA_VERSION) return null;\n\tif (typeof value.event !== \"string\" || !RUN_JOURNAL_EVENTS.has(value.event as RunJournalEvent)) return null;\n\tif (typeof value.seq !== \"number\" || !Number.isSafeInteger(value.seq) || value.seq < 0) return null;\n\tif (!isBoundedIdentifier(value.runId) || looksLikeCredential(value.runId)) return null;\n\tif (!isBoundedIdentifier(value.sessionId) || looksLikeCredential(value.sessionId)) return null;\n\tif (\n\t\ttypeof value.sessionRevision !== \"number\" ||\n\t\t!Number.isSafeInteger(value.sessionRevision) ||\n\t\tvalue.sessionRevision < 0\n\t) {\n\t\treturn null;\n\t}\n\tif (!isCanonicalTimestamp(value.timestamp)) return null;\n\tif (typeof value.prevHash !== \"string\" || typeof value.hash !== \"string\") return null;\n\treturn {\n\t\tschemaVersion: RUN_JOURNAL_SCHEMA_VERSION,\n\t\tseq: value.seq,\n\t\tevent: value.event as RunJournalEvent,\n\t\trunId: value.runId,\n\t\tsessionId: value.sessionId,\n\t\tsessionRevision: value.sessionRevision,\n\t\ttimestamp: value.timestamp,\n\t\tprevHash: value.prevHash,\n\t\thash: value.hash,\n\t};\n}\n\ntype TerminationProbe =\n\t| { readonly kind: \"ok\"; readonly termination: SessionTermination }\n\t| { readonly kind: \"mismatch\" }\n\t| {\n\t\t\treadonly kind: \"source\";\n\t };\n\nfunction probeTermination(\n\trawTermination: unknown,\n\trunId: string,\n\tsessionId: string,\n\tevent: RunJournalEvent,\n): TerminationProbe {\n\tlet termination: SessionTermination;\n\ttry {\n\t\tassertBoundedSessionTermination(rawTermination, runId, sessionId);\n\t\ttermination = rawTermination as SessionTermination;\n\t} catch {\n\t\treturn { kind: \"mismatch\" };\n\t}\n\tif (!isTerminalCoherentWithEvent(event as RunJournalTerminalRecord[\"event\"], termination)) {\n\t\treturn { kind: \"source\" };\n\t}\n\treturn { kind: \"ok\", termination };\n}\n\nfunction addFinding(findings: RunJournalFinding[], finding: RunJournalFinding): void {\n\tfindings.push(Object.freeze({ ...finding }));\n}\n\n/**\n * Inspect the complete-line prefix of a run-journal byte sequence without\n * mutating or repairing it. Only bytes through the final newline are parsed;\n * trailing bytes are reported as a fragment and never parsed. Every hash is\n * recomputed with the injected `hashFn`. The returned report is deeply frozen.\n */\nexport function inspectRunJournal(bytes: Uint8Array, hashFn: RunJournalHashFn): RunJournalReport {\n\tconst findings: RunJournalFinding[] = [];\n\n\tlet lastNewline = -1;\n\tfor (let index = bytes.byteLength - 1; index >= 0; index -= 1) {\n\t\tif (bytes[index] === 0x0a) {\n\t\t\tlastNewline = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst completeByteCount = lastNewline + 1;\n\tconst trailingByteCount = bytes.byteLength - completeByteCount;\n\tif (trailingByteCount > 0) addFinding(findings, { code: \"trailing_fragment\" });\n\n\tconst completeBytes = bytes.subarray(0, completeByteCount);\n\tlet lineCount = 0;\n\tconst parsedLines: { readonly line: number; readonly value: unknown }[] = [];\n\tif (completeByteCount > 0) {\n\t\tlet text: string | undefined;\n\t\ttry {\n\t\t\ttext = TEXT_DECODER.decode(completeBytes);\n\t\t} catch {\n\t\t\taddFinding(findings, { code: \"invalid_utf8\" });\n\t\t}\n\t\tif (text !== undefined) {\n\t\t\tconst body = text.slice(0, -1);\n\t\t\tconst lines = body.length === 0 ? [] : body.split(\"\\n\");\n\t\t\tlineCount = lines.length;\n\t\t\tfor (let index = 0; index < lines.length; index += 1) {\n\t\t\t\tconst lineNumber = index + 1;\n\t\t\t\tconst line = lines[index];\n\t\t\t\tif (line.trim().length === 0) {\n\t\t\t\t\taddFinding(findings, { code: \"malformed_json\", line: lineNumber });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tparsedLines.push({ line: lineNumber, value: JSON.parse(line) });\n\t\t\t\t} catch {\n\t\t\t\t\taddFinding(findings, { code: \"malformed_json\", line: lineNumber });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlet openRun: { runId: string; sessionId: string } | null = null;\n\tconst seenStarts = new Set<string>();\n\tconst terminatedRuns = new Set<string>();\n\tlet expectedSeq = 0;\n\tlet lastHash = GENESIS_HASH;\n\tlet journalSessionId: string | null = null;\n\tlet lastRevision = 0;\n\tconst validRecords: RunJournalRecord[] = [];\n\n\tfor (const { line, value } of parsedLines) {\n\t\tconst common = validateCommonShape(value);\n\t\tif (common === null) {\n\t\t\taddFinding(findings, { code: \"schema\", line });\n\t\t\tcontinue;\n\t\t}\n\t\tlet auditDetails: RunJournalAuditDetails | null = null;\n\t\tif (AUDIT_EVENTS.has(common.event)) {\n\t\t\ttry {\n\t\t\t\tassertBoundedAuditDetails((value as Record<string, unknown>).details);\n\t\t\t\tauditDetails = (value as { details: RunJournalAuditDetails }).details;\n\t\t\t} catch {\n\t\t\t\taddFinding(findings, { code: \"schema\", line });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tlet termination: SessionTermination | null = null;\n\t\tif (TERMINAL_EVENTS.has(common.event)) {\n\t\t\tconst probe = probeTermination(\n\t\t\t\t(value as Record<string, unknown>).termination,\n\t\t\t\tcommon.runId,\n\t\t\t\tcommon.sessionId,\n\t\t\t\tcommon.event,\n\t\t\t);\n\t\t\tif (probe.kind === \"mismatch\") {\n\t\t\t\taddFinding(findings, { code: \"termination_mismatch\", line, runId: common.runId });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (probe.kind === \"source\") {\n\t\t\t\taddFinding(findings, { code: \"recovered_source_invalid\", line, runId: common.runId });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttermination = probe.termination;\n\t\t\tif (common.timestamp !== termination.timestamp) {\n\t\t\t\taddFinding(findings, { code: \"termination_mismatch\", line, runId: common.runId });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (journalSessionId === null) {\n\t\t\tjournalSessionId = common.sessionId;\n\t\t} else if (common.sessionId !== journalSessionId) {\n\t\t\taddFinding(findings, { code: \"session_mismatch\", line, runId: common.runId });\n\t\t\tcontinue;\n\t\t}\n\t\tif (common.sessionRevision < lastRevision) {\n\t\t\taddFinding(findings, { code: \"session_revision_regression\", line, runId: common.runId });\n\t\t\tcontinue;\n\t\t}\n\t\tlastRevision = common.sessionRevision;\n\n\t\tconst baseRecord = {\n\t\t\tschemaVersion: RUN_JOURNAL_SCHEMA_VERSION,\n\t\t\tseq: common.seq,\n\t\t\tevent: common.event,\n\t\t\trunId: common.runId,\n\t\t\tsessionId: common.sessionId,\n\t\t\tsessionRevision: common.sessionRevision,\n\t\t\ttimestamp: common.timestamp,\n\t\t\tprevHash: common.prevHash,\n\t\t};\n\t\tconst recordWithoutHash = (\n\t\t\ttermination !== null\n\t\t\t\t? { ...baseRecord, termination }\n\t\t\t\t: auditDetails !== null\n\t\t\t\t\t? { ...baseRecord, details: auditDetails }\n\t\t\t\t\t: baseRecord\n\t\t) as Omit<RunJournalRecord, \"hash\">;\n\n\t\tif (common.seq > expectedSeq) addFinding(findings, { code: \"seq_gap\", line });\n\t\telse if (common.seq < expectedSeq) addFinding(findings, { code: \"seq_regression\", line });\n\t\texpectedSeq = common.seq + 1;\n\n\t\tconst hashShapeOk = isValidHashShape(common.hash);\n\t\tconst prevHashShapeOk = isValidHashShape(common.prevHash);\n\t\tif (!hashShapeOk || !prevHashShapeOk) addFinding(findings, { code: \"hash_shape\", line });\n\n\t\tconst material = serializeRunJournalMaterial(recordWithoutHash);\n\t\tlet recomputeOk = false;\n\t\ttry {\n\t\t\tconst recomputed = hashFn(TEXT_ENCODER.encode(material));\n\t\t\trecomputeOk = isValidHashShape(recomputed) && recomputed === common.hash;\n\t\t} catch {\n\t\t\trecomputeOk = false;\n\t\t}\n\t\tif (!recomputeOk) addFinding(findings, { code: \"hash_mismatch\", line });\n\n\t\tif (common.prevHash !== lastHash) addFinding(findings, { code: \"hash_chain_break\", line });\n\t\tif (hashShapeOk) lastHash = common.hash;\n\n\t\tif (AUDIT_EVENTS.has(common.event)) {\n\t\t\t// Audit records never affect the run-state machine.\n\t\t} else if (common.event === \"run_started\") {\n\t\t\tif (seenStarts.has(common.runId)) addFinding(findings, { code: \"duplicate_start\", line, runId: common.runId });\n\t\t\tif (openRun !== null && openRun.runId !== common.runId) {\n\t\t\t\taddFinding(findings, { code: \"interleaved_run\", line, runId: common.runId });\n\t\t\t} else if (openRun === null) {\n\t\t\t\topenRun = { runId: common.runId, sessionId: common.sessionId };\n\t\t\t}\n\t\t\tseenStarts.add(common.runId);\n\t\t} else {\n\t\t\tif (terminatedRuns.has(common.runId)) {\n\t\t\t\taddFinding(findings, { code: \"duplicate_terminal\", line, runId: common.runId });\n\t\t\t} else if (openRun === null || openRun.runId !== common.runId) {\n\t\t\t\taddFinding(findings, { code: \"orphan_terminal\", line, runId: common.runId });\n\t\t\t} else {\n\t\t\t\tterminatedRuns.add(common.runId);\n\t\t\t\topenRun = null;\n\t\t\t}\n\t\t}\n\n\t\tconst record = { ...recordWithoutHash, hash: common.hash } as RunJournalRecord;\n\t\tvalidRecords.push(deepFreeze(record) as RunJournalRecord);\n\t}\n\n\tif (openRun !== null) addFinding(findings, { code: \"run_unclosed\", runId: openRun.runId });\n\n\treturn deepFreeze({\n\t\tok: findings.length === 0,\n\t\tcompletePrefix: Object.freeze({ byteCount: completeByteCount, lineCount }),\n\t\ttrailingByteCount,\n\t\trecords: Object.freeze(validRecords) as readonly RunJournalRecord[],\n\t\topenRunId: openRun === null ? null : openRun.runId,\n\t\tfindings: Object.freeze(findings) as readonly RunJournalFinding[],\n\t}) as RunJournalReport;\n}\n"]}
|