open-multi-agent-kit 0.96.0 → 0.96.2
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 +81 -0
- package/README.md +34 -6
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +1 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/commands/doctor-provider.d.ts.map +1 -1
- package/dist/commands/doctor-provider.js +15 -20
- package/dist/commands/doctor-provider.js.map +1 -1
- package/dist/commands/resource-doctor-cli.d.ts +22 -0
- package/dist/commands/resource-doctor-cli.d.ts.map +1 -0
- package/dist/commands/resource-doctor-cli.js +98 -0
- package/dist/commands/resource-doctor-cli.js.map +1 -0
- package/dist/commands/sdk-session-cli.d.ts +24 -0
- package/dist/commands/sdk-session-cli.d.ts.map +1 -0
- package/dist/commands/sdk-session-cli.js +225 -0
- package/dist/commands/sdk-session-cli.js.map +1 -0
- package/dist/core/advisory-judge-model.d.ts +18 -0
- package/dist/core/advisory-judge-model.d.ts.map +1 -0
- package/dist/core/advisory-judge-model.js +168 -0
- package/dist/core/advisory-judge-model.js.map +1 -0
- package/dist/core/advisory-judge-response.d.ts +8 -0
- package/dist/core/advisory-judge-response.d.ts.map +1 -0
- package/dist/core/advisory-judge-response.js +61 -0
- package/dist/core/advisory-judge-response.js.map +1 -0
- package/dist/core/advisory-judge-types.d.ts +53 -0
- package/dist/core/advisory-judge-types.d.ts.map +1 -0
- package/dist/core/advisory-judge-types.js +2 -0
- package/dist/core/advisory-judge-types.js.map +1 -0
- package/dist/core/advisory-judge.d.ts +8 -0
- package/dist/core/advisory-judge.d.ts.map +1 -0
- package/dist/core/advisory-judge.js +178 -0
- package/dist/core/advisory-judge.js.map +1 -0
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +41 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +396 -179
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +28 -4
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/compaction-gate.d.ts +28 -0
- package/dist/core/compaction-gate.d.ts.map +1 -0
- package/dist/core/compaction-gate.js +34 -0
- package/dist/core/compaction-gate.js.map +1 -0
- package/dist/core/completion-sound.d.ts +109 -0
- package/dist/core/completion-sound.d.ts.map +1 -0
- package/dist/core/completion-sound.js +165 -0
- package/dist/core/completion-sound.js.map +1 -0
- package/dist/core/context-budget-system-prompt-items.d.ts.map +1 -1
- package/dist/core/context-budget-system-prompt-items.js +5 -3
- package/dist/core/context-budget-system-prompt-items.js.map +1 -1
- package/dist/core/domain-loadouts.d.ts.map +1 -1
- package/dist/core/domain-loadouts.js +2 -2
- package/dist/core/domain-loadouts.js.map +1 -1
- package/dist/core/durable-goal-checkpoint.d.ts +6 -0
- package/dist/core/durable-goal-checkpoint.d.ts.map +1 -0
- package/dist/core/durable-goal-checkpoint.js +195 -0
- package/dist/core/durable-goal-checkpoint.js.map +1 -0
- package/dist/core/durable-goal-parse.d.ts +3 -0
- package/dist/core/durable-goal-parse.d.ts.map +1 -0
- package/dist/core/durable-goal-parse.js +86 -0
- package/dist/core/durable-goal-parse.js.map +1 -0
- package/dist/core/durable-goal-reducer.d.ts +3 -0
- package/dist/core/durable-goal-reducer.d.ts.map +1 -0
- package/dist/core/durable-goal-reducer.js +175 -0
- package/dist/core/durable-goal-reducer.js.map +1 -0
- package/dist/core/durable-goal-store.d.ts +19 -0
- package/dist/core/durable-goal-store.d.ts.map +1 -0
- package/dist/core/durable-goal-store.js +126 -0
- package/dist/core/durable-goal-store.js.map +1 -0
- package/dist/core/durable-goal.d.ts +92 -0
- package/dist/core/durable-goal.d.ts.map +1 -0
- package/dist/core/durable-goal.js +62 -0
- package/dist/core/durable-goal.js.map +1 -0
- package/dist/core/extensions/builtin/goal-controller.d.ts +3 -0
- package/dist/core/extensions/builtin/goal-controller.d.ts.map +1 -0
- package/dist/core/extensions/builtin/goal-controller.js +125 -0
- package/dist/core/extensions/builtin/goal-controller.js.map +1 -0
- package/dist/core/extensions/builtin/identical-loop.d.ts +3 -0
- package/dist/core/extensions/builtin/identical-loop.d.ts.map +1 -0
- package/dist/core/extensions/builtin/identical-loop.js +31 -0
- package/dist/core/extensions/builtin/identical-loop.js.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset.d.ts +3 -0
- package/dist/core/extensions/builtin/prompt-preset.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset.js +13 -0
- package/dist/core/extensions/builtin/prompt-preset.js.map +1 -0
- package/dist/core/extensions/builtin/tool-pair-repair.d.ts +3 -0
- package/dist/core/extensions/builtin/tool-pair-repair.d.ts.map +1 -0
- package/dist/core/extensions/builtin/tool-pair-repair.js +12 -0
- package/dist/core/extensions/builtin/tool-pair-repair.js.map +1 -0
- package/dist/core/extensions/types.d.ts +6 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/goal-continuation.d.ts +13 -0
- package/dist/core/goal-continuation.d.ts.map +1 -0
- package/dist/core/goal-continuation.js +10 -0
- package/dist/core/goal-continuation.js.map +1 -0
- package/dist/core/grok-harness.d.ts +1 -1
- package/dist/core/grok-harness.d.ts.map +1 -1
- package/dist/core/grok-harness.js +1 -1
- package/dist/core/grok-harness.js.map +1 -1
- package/dist/core/grok-playbook.d.ts +1 -1
- package/dist/core/grok-playbook.d.ts.map +1 -1
- package/dist/core/grok-playbook.js +1 -1
- package/dist/core/grok-playbook.js.map +1 -1
- package/dist/core/host-resource-probe.d.ts +63 -0
- package/dist/core/host-resource-probe.d.ts.map +1 -0
- package/dist/core/host-resource-probe.js +126 -0
- package/dist/core/host-resource-probe.js.map +1 -0
- package/dist/core/host-resource-snapshot.d.ts +54 -0
- package/dist/core/host-resource-snapshot.d.ts.map +1 -0
- package/dist/core/host-resource-snapshot.js +139 -0
- package/dist/core/host-resource-snapshot.js.map +1 -0
- package/dist/core/identical-loop.d.ts +15 -0
- package/dist/core/identical-loop.d.ts.map +1 -0
- package/dist/core/identical-loop.js +34 -0
- package/dist/core/identical-loop.js.map +1 -0
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/model-prompt-policy.d.ts +11 -0
- package/dist/core/model-prompt-policy.d.ts.map +1 -0
- package/dist/core/model-prompt-policy.js +17 -0
- package/dist/core/model-prompt-policy.js.map +1 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +16 -4
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +2 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/prompt-budget.d.ts +21 -0
- package/dist/core/prompt-budget.d.ts.map +1 -0
- package/dist/core/prompt-budget.js +51 -0
- package/dist/core/prompt-budget.js.map +1 -0
- package/dist/core/prompt-cache.d.ts +14 -0
- package/dist/core/prompt-cache.d.ts.map +1 -0
- package/dist/core/prompt-cache.js +16 -0
- package/dist/core/prompt-cache.js.map +1 -0
- package/dist/core/prompt-preset.d.ts +8 -0
- package/dist/core/prompt-preset.d.ts.map +1 -0
- package/dist/core/prompt-preset.js +56 -0
- package/dist/core/prompt-preset.js.map +1 -0
- package/dist/core/prompt-settlement.d.ts +81 -0
- package/dist/core/prompt-settlement.d.ts.map +1 -0
- package/dist/core/prompt-settlement.js +84 -0
- package/dist/core/prompt-settlement.js.map +1 -0
- package/dist/core/provider-resilience.d.ts +16 -0
- package/dist/core/provider-resilience.d.ts.map +1 -1
- package/dist/core/provider-resilience.js +24 -2
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/provider-retry.d.ts +36 -0
- package/dist/core/provider-retry.d.ts.map +1 -0
- package/dist/core/provider-retry.js +73 -0
- package/dist/core/provider-retry.js.map +1 -0
- package/dist/core/provider-usage.d.ts +16 -2
- package/dist/core/provider-usage.d.ts.map +1 -1
- package/dist/core/provider-usage.js +150 -8
- package/dist/core/provider-usage.js.map +1 -1
- package/dist/core/reasoning-router-resolver.d.ts.map +1 -1
- package/dist/core/reasoning-router-resolver.js +1 -1
- package/dist/core/reasoning-router-resolver.js.map +1 -1
- package/dist/core/resource-admission-config.d.ts +55 -0
- package/dist/core/resource-admission-config.d.ts.map +1 -0
- package/dist/core/resource-admission-config.js +97 -0
- package/dist/core/resource-admission-config.js.map +1 -0
- package/dist/core/resource-admission.d.ts +81 -0
- package/dist/core/resource-admission.d.ts.map +1 -0
- package/dist/core/resource-admission.js +128 -0
- package/dist/core/resource-admission.js.map +1 -0
- package/dist/core/resource-governor-format.d.ts +50 -0
- package/dist/core/resource-governor-format.d.ts.map +1 -0
- package/dist/core/resource-governor-format.js +113 -0
- package/dist/core/resource-governor-format.js.map +1 -0
- package/dist/core/resource-governor-settings.d.ts +56 -0
- package/dist/core/resource-governor-settings.d.ts.map +1 -0
- package/dist/core/resource-governor-settings.js +89 -0
- package/dist/core/resource-governor-settings.js.map +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +32 -0
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/resource-observation-journal.d.ts +74 -0
- package/dist/core/resource-observation-journal.d.ts.map +1 -0
- package/dist/core/resource-observation-journal.js +198 -0
- package/dist/core/resource-observation-journal.js.map +1 -0
- package/dist/core/resource-safety-gate.d.ts +54 -0
- package/dist/core/resource-safety-gate.d.ts.map +1 -0
- package/dist/core/resource-safety-gate.js +51 -0
- package/dist/core/resource-safety-gate.js.map +1 -0
- package/dist/core/run-journal.d.ts.map +1 -1
- package/dist/core/run-journal.js +13 -1
- package/dist/core/run-journal.js.map +1 -1
- package/dist/core/run-resource-lease.d.ts +73 -0
- package/dist/core/run-resource-lease.d.ts.map +1 -0
- package/dist/core/run-resource-lease.js +78 -0
- package/dist/core/run-resource-lease.js.map +1 -0
- package/dist/core/sandbox/backend.d.ts +12 -0
- package/dist/core/sandbox/backend.d.ts.map +1 -1
- package/dist/core/sandbox/backend.js +52 -42
- package/dist/core/sandbox/backend.js.map +1 -1
- package/dist/core/sandbox/policy.d.ts +2 -0
- package/dist/core/sandbox/policy.d.ts.map +1 -1
- package/dist/core/sandbox/policy.js +2 -1
- package/dist/core/sandbox/policy.js.map +1 -1
- package/dist/core/sdk.d.ts +2 -0
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +1 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-bash-service.d.ts +12 -0
- package/dist/core/session-bash-service.d.ts.map +1 -1
- package/dist/core/session-bash-service.js +14 -0
- package/dist/core/session-bash-service.js.map +1 -1
- package/dist/core/session-system-prompt.d.ts +30 -0
- package/dist/core/session-system-prompt.d.ts.map +1 -0
- package/dist/core/session-system-prompt.js +39 -0
- package/dist/core/session-system-prompt.js.map +1 -0
- package/dist/core/session-termination.d.ts +7 -2
- package/dist/core/session-termination.d.ts.map +1 -1
- package/dist/core/session-termination.js +29 -1
- package/dist/core/session-termination.js.map +1 -1
- package/dist/core/settings-manager.d.ts +12 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +36 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/strict-record.d.ts +2 -0
- package/dist/core/strict-record.d.ts.map +1 -0
- package/dist/core/strict-record.js +9 -0
- package/dist/core/strict-record.js.map +1 -0
- package/dist/core/subagent-lane-launcher.d.ts +64 -0
- package/dist/core/subagent-lane-launcher.d.ts.map +1 -0
- package/dist/core/subagent-lane-launcher.js +107 -0
- package/dist/core/subagent-lane-launcher.js.map +1 -0
- package/dist/core/system-cpu-sampler.d.ts +45 -0
- package/dist/core/system-cpu-sampler.d.ts.map +1 -0
- package/dist/core/system-cpu-sampler.js +95 -0
- package/dist/core/system-cpu-sampler.js.map +1 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -8
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tool-pair-repair.d.ts +11 -0
- package/dist/core/tool-pair-repair.d.ts.map +1 -0
- package/dist/core/tool-pair-repair.js +38 -0
- package/dist/core/tool-pair-repair.js.map +1 -0
- package/dist/core/tools/artifact-spill.d.ts +13 -0
- package/dist/core/tools/artifact-spill.d.ts.map +1 -0
- package/dist/core/tools/artifact-spill.js +26 -0
- package/dist/core/tools/artifact-spill.js.map +1 -0
- package/dist/core/tools/bash.d.ts +7 -4
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +8 -7
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/read.d.ts +1 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +10 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +2 -0
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/workload-classifier.d.ts +32 -0
- package/dist/core/workload-classifier.d.ts.map +1 -0
- package/dist/core/workload-classifier.js +66 -0
- package/dist/core/workload-classifier.js.map +1 -0
- package/dist/core/workload-family-matcher.d.ts +3 -0
- package/dist/core/workload-family-matcher.d.ts.map +1 -0
- package/dist/core/workload-family-matcher.js +126 -0
- package/dist/core/workload-family-matcher.js.map +1 -0
- package/dist/core/workload-permit-pool.d.ts +78 -0
- package/dist/core/workload-permit-pool.d.ts.map +1 -0
- package/dist/core/workload-permit-pool.js +138 -0
- package/dist/core/workload-permit-pool.js.map +1 -0
- package/dist/core/workload-shard-executor.d.ts +68 -0
- package/dist/core/workload-shard-executor.d.ts.map +1 -0
- package/dist/core/workload-shard-executor.js +156 -0
- package/dist/core/workload-shard-executor.js.map +1 -0
- package/dist/core/workload-shard-plan.d.ts +81 -0
- package/dist/core/workload-shard-plan.d.ts.map +1 -0
- package/dist/core/workload-shard-plan.js +183 -0
- package/dist/core/workload-shard-plan.js.map +1 -0
- package/dist/core/workload-shard-runner.d.ts +11 -0
- package/dist/core/workload-shard-runner.d.ts.map +1 -0
- package/dist/core/workload-shard-runner.js +98 -0
- package/dist/core/workload-shard-runner.js.map +1 -0
- package/dist/core/workload-shard-store.d.ts +44 -0
- package/dist/core/workload-shard-store.d.ts.map +1 -0
- package/dist/core/workload-shard-store.js +189 -0
- package/dist/core/workload-shard-store.js.map +1 -0
- package/dist/core/workload-sharders.d.ts +47 -0
- package/dist/core/workload-sharders.d.ts.map +1 -0
- package/dist/core/workload-sharders.js +162 -0
- package/dist/core/workload-sharders.js.map +1 -0
- package/dist/core/workload-shell-scan.d.ts +12 -0
- package/dist/core/workload-shell-scan.d.ts.map +1 -0
- package/dist/core/workload-shell-scan.js +79 -0
- package/dist/core/workload-shell-scan.js.map +1 -0
- package/dist/index.d.ts +18 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +14 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +4 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +81 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +14 -3
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/docs/adaptorch-preview-spec.md +1 -1
- package/docs/adaptorch-preview.md +2 -2
- package/docs/book-to-skill.md +1 -1
- package/docs/containerization.md +9 -0
- package/docs/docs.json +11 -3
- package/docs/environment-variables.md +11 -4
- package/docs/extensions.md +14 -1
- package/docs/grok-harness.md +35 -12
- package/docs/index.md +7 -6
- package/docs/loadout-domains/grok-harness.md +2 -2
- package/docs/models.md +10 -9
- package/docs/provider-resilience.md +9 -3
- package/docs/providers.md +9 -4
- package/docs/run-protocol.md +32 -0
- package/docs/sdk.md +100 -3
- package/docs/security.md +22 -32
- package/docs/sessions.md +14 -0
- package/docs/settings.md +64 -2
- package/docs/skills.md +16 -0
- package/docs/usage.md +37 -15
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +6 -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/subagent/agent-capability-router.test.ts +7 -0
- package/examples/extensions/subagent/domain-profiles.ts +0 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +18 -18
- package/package.json +7 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-journal.d.ts","sourceRoot":"","sources":["../../src/core/run-journal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAIN,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,oF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2CtB,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_KIND_VALUES,\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(SESSION_TERMINATION_KIND_VALUES);\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\t// Orphan tool_call_id / sticky transcript shape — retry after sanitize.\n\t\t\t\t\texpectedRetryable = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"refusal\":\n\t\t\t\t\texpectedKind = \"provider_refusal\";\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 \"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\t// Keep in lockstep with isSafeToAutoRetry() in session-termination.ts.\n\t// provider_refusal: Fable/Claude false-positive safety stops may auto-retry once when sideEffects=none.\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\" ||\n\t\t\ttermination.kind === \"provider_network\" ||\n\t\t\ttermination.kind === \"provider_refusal\");\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"]}
|
|
1
|
+
{"version":3,"file":"run-journal.d.ts","sourceRoot":"","sources":["../../src/core/run-journal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAIN,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,GA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H,qBAAa,UAAU;IACtB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmB;IAC1C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA0B;IACxD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA0B;IAC3D,OAAO,CAAC,QAAQ,CAAC,cAAc,CAA0B;IACzD,OAAO,CAAC,eAAe,CAAiF;IACxG,OAAO,CAAC,mBAAmB,CAAK;IAChC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,OAAO,CAAuE;IAEtF,YAAY,IAAI,EAAE,yBAAyB,EAsC1C;IAED,KAAK,CAAC,KAAK,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_KIND_VALUES,\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(SESSION_TERMINATION_KIND_VALUES);\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\t// Orphan tool_call_id / sticky transcript shape — retry after sanitize.\n\t\t\t\t\texpectedRetryable = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"refusal\":\n\t\t\t\t\texpectedKind = \"provider_refusal\";\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 \"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 \"resource\":\n\t\t\tif (![\"memory\", \"disk\", \"cpu\", \"heap\", \"probe_unavailable\", \"queue_overflow\"].includes(suffix)) {\n\t\t\t\tthrow new TypeError(\"termination causeCode is incoherent\");\n\t\t\t}\n\t\t\t// §15.4: resource causes are always retryable; queue overflow is the\n\t\t\t// only tool-phase cause, the rest stop at preflight admission.\n\t\t\texpectedKind = \"resource_pressure\";\n\t\t\texpectedPhase = suffix === \"queue_overflow\" ? \"tool\" : \"preflight\";\n\t\t\texpectedRetryable = true;\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\t// Keep in lockstep with isSafeToAutoRetry() in session-termination.ts.\n\t// provider_refusal: Fable/Claude false-positive safety stops may auto-retry once when sideEffects=none.\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\" ||\n\t\t\ttermination.kind === \"provider_network\" ||\n\t\t\ttermination.kind === \"provider_refusal\" ||\n\t\t\t// §15.4 mapping: only cpu pressure is safe to auto-retry (with delay).\n\t\t\ttermination.causeCode === \"resource.cpu\");\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"]}
|
package/dist/core/run-journal.js
CHANGED
|
@@ -387,6 +387,16 @@ function assertTerminationCoherence(termination) {
|
|
|
387
387
|
throw new TypeError("termination causeCode is incoherent");
|
|
388
388
|
}
|
|
389
389
|
break;
|
|
390
|
+
case "resource":
|
|
391
|
+
if (!["memory", "disk", "cpu", "heap", "probe_unavailable", "queue_overflow"].includes(suffix)) {
|
|
392
|
+
throw new TypeError("termination causeCode is incoherent");
|
|
393
|
+
}
|
|
394
|
+
// §15.4: resource causes are always retryable; queue overflow is the
|
|
395
|
+
// only tool-phase cause, the rest stop at preflight admission.
|
|
396
|
+
expectedKind = "resource_pressure";
|
|
397
|
+
expectedPhase = suffix === "queue_overflow" ? "tool" : "preflight";
|
|
398
|
+
expectedRetryable = true;
|
|
399
|
+
break;
|
|
390
400
|
case "tool":
|
|
391
401
|
if (suffix === "timeout") {
|
|
392
402
|
expectedKind = "tool_timeout";
|
|
@@ -512,7 +522,9 @@ function assertTerminationCoherence(termination) {
|
|
|
512
522
|
termination.sideEffects === "none" &&
|
|
513
523
|
(termination.kind === "provider_rate_limit" ||
|
|
514
524
|
termination.kind === "provider_network" ||
|
|
515
|
-
termination.kind === "provider_refusal"
|
|
525
|
+
termination.kind === "provider_refusal" ||
|
|
526
|
+
// §15.4 mapping: only cpu pressure is safe to auto-retry (with delay).
|
|
527
|
+
termination.causeCode === "resource.cpu");
|
|
516
528
|
if (termination.safeToAutoRetry !== expectedSafeToAutoRetry) {
|
|
517
529
|
throw new TypeError("termination safeToAutoRetry flag is incoherent");
|
|
518
530
|
}
|