open-multi-agent-kit 0.96.1 → 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 +41 -0
- package/README.md +12 -2
- 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/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/core/agent-session.d.ts +37 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +289 -5
- package/dist/core/agent-session.js.map +1 -1
- 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 +2 -2
- package/dist/core/context-budget-system-prompt-items.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/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.map +1 -1
- package/dist/core/provider-resilience.js +1 -1
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/provider-retry.d.ts +7 -0
- package/dist/core/provider-retry.d.ts.map +1 -1
- package/dist/core/provider-retry.js +24 -0
- package/dist/core/provider-retry.js.map +1 -1
- package/dist/core/provider-usage.d.ts +15 -2
- package/dist/core/provider-usage.d.ts.map +1 -1
- package/dist/core/provider-usage.js +110 -2
- 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-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/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 +2 -0
- package/dist/core/session-system-prompt.d.ts.map +1 -1
- package/dist/core/session-system-prompt.js +2 -0
- package/dist/core/session-system-prompt.js.map +1 -1
- 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/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/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/main.d.ts.map +1 -1
- package/dist/main.js +6 -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/docs/providers.md +1 -1
- package/docs/sdk.md +4 -0
- package/docs/settings.md +64 -2
- package/docs/skills.md +16 -0
- 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/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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-observation-journal.js","sourceRoot":"","sources":["../../src/core/resource-observation-journal.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAMlC;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG,6BAA6B,CAAC;AAE/E,2DAA0D;AAC1D,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,sBAAsB;IACtB,uBAAuB;IACvB,4BAA4B;IAC5B,4BAA4B;IAC5B,4BAA4B;IAC5B,yBAAyB;IACzB,6BAA6B;IAC7B,6BAA6B;IAC7B,mBAAmB;IACnB,4BAA4B;CACnB,CAAC;AA2BX,MAAM,6BAA6B,GAE/B;IACH,oBAAoB,EAAE,sBAAsB;IAC5C,qBAAqB,EAAE,uBAAuB;IAC9C,0BAA0B,EAAE,4BAA4B;IACxD,uBAAuB,EAAE,oBAAoB;IAC7C,2BAA2B,EAAE,oBAAoB;IACjD,2BAA2B,EAAE,oBAAoB;IACjD,iBAAiB,EAAE,mBAAmB;IACtC,0BAA0B,EAAE,wBAAwB;CACpD,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAAiC,EAAsC;IAC5G,MAAM,IAAI,GAAG,6BAA6B,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACxD,OAAO,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CA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AC;IAChD,IAAI,MAAM,CAAC,aAAa,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAC5C,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IACvG,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAC/E,IAAI,OAAO,MAAM,CAAC,EAAE,KAAK,QAAQ,IAAI,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzF,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1G,KAAK,MAAM,SAAS,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,MAAM,IAAI,GAAG,OAAO,SAAS,CAAC;QAC9B,IAAI,SAAS,KAAK,IAAI,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,SAAS;YAAE,OAAO,IAAI,CAAC;IACrG,CAAC;IACD,OAAO,MAA8C,CAAC;AAAA,CACtD","sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { CompletionSoundResult } from \"./completion-sound.ts\";\nimport type { PromptSettledEvent } from \"./prompt-settlement.ts\";\nimport type { ResourceAdmissionDecision } from \"./resource-admission.ts\";\nimport type { WorkloadClassification } from \"./workload-classifier.ts\";\n\n/**\n * Local-only resource observation journal (roadmap §15.1/§15.2/§20.2).\n *\n * A dedicated JSONL artifact under `.omk/runs/<promptRunId>/` — deliberately\n * NOT the hash-chained run journal: §15.2 restricts raw host facts to a\n * separate local-only artifact, and extending the run journal's closed audit\n * union would invalidate old readers. Shard plan/transition entries stay in\n * `workload-shards.jsonl` (they already journal there); this file carries\n * the remaining §20.2 entries.\n *\n * Privacy (§15.2, §20.3, §30): facts are flat primitives only — pressure\n * levels, caps, digests, durations, reason codes. Never raw memory/cpu\n * numbers, hostnames, usernames, or command text. Observability is\n * fail-open: a write/read failure degrades to diagnostics, never breaks the\n * run (probe failure is non-fatal by contract).\n */\n\nexport const RESOURCE_OBSERVATION_JOURNAL_FILE = \"resource-observations.jsonl\";\n\n/** §20.2 journal entry kinds handled by this artifact. */\nexport const RESOURCE_OBSERVATION_KINDS = [\n\t\"resource_snapshot_v1\",\n\t\"resource_admission_v1\",\n\t\"resource_lease_acquired_v1\",\n\t\"resource_lease_released_v1\",\n\t\"workload_classification_v1\",\n\t\"workload_permit_wait_v1\",\n\t\"workload_permit_acquired_v1\",\n\t\"workload_permit_released_v1\",\n\t\"prompt_settled_v1\",\n\t\"completion_sound_result_v1\",\n] as const;\n\nexport type ResourceObservationKind = (typeof RESOURCE_OBSERVATION_KINDS)[number];\n\nexport type ResourceObservationFacts = Readonly<Record<string, string | number | boolean | null>>;\n\nexport interface ResourceObservationRecord {\n\treadonly schemaVersion: 1;\n\treadonly seq: number;\n\treadonly kind: ResourceObservationKind;\n\treadonly at: string;\n\treadonly promptRunId: string;\n\treadonly facts: ResourceObservationFacts;\n}\n\n/** §15.1 protocol observation projection of one journal record. */\nexport interface ResourceProtocolObservation {\n\treadonly kind:\n\t\t| \"resource_snapshot.v1\"\n\t\t| \"resource_admission.v1\"\n\t\t| \"workload_classification.v1\"\n\t\t| \"workload_permit.v1\"\n\t\t| \"prompt_settled.v1\"\n\t\t| \"notification_result.v1\";\n\treadonly facts: ResourceObservationFacts;\n}\n\nconst PROTOCOL_KIND_BY_JOURNAL_KIND: Readonly<\n\tPartial<Record<ResourceObservationKind, ResourceProtocolObservation[\"kind\"]>>\n> = {\n\tresource_snapshot_v1: \"resource_snapshot.v1\",\n\tresource_admission_v1: \"resource_admission.v1\",\n\tworkload_classification_v1: \"workload_classification.v1\",\n\tworkload_permit_wait_v1: \"workload_permit.v1\",\n\tworkload_permit_acquired_v1: \"workload_permit.v1\",\n\tworkload_permit_released_v1: \"workload_permit.v1\",\n\tprompt_settled_v1: \"prompt_settled.v1\",\n\tcompletion_sound_result_v1: \"notification_result.v1\",\n};\n\n/**\n * Project a journal record onto the §15.1 protocol observation surface.\n * Lease entries are local-only operational detail and project to null.\n */\nexport function toProtocolObservation(record: ResourceObservationRecord): ResourceProtocolObservation | null {\n\tconst kind = PROTOCOL_KIND_BY_JOURNAL_KIND[record.kind];\n\treturn kind === undefined ? null : { kind, facts: record.facts };\n}\n\n/** §15.2: probe health and digest only — raw host values never leave the process. */\nexport function snapshotObservationFacts(snapshot: {\n\treadonly systemCpuPercent: number | null;\n\treadonly processAvailableMemoryBytes: number | null;\n\treadonly hostFreeMemoryBytes: number | null;\n\treadonly heapLimitBytes: number;\n}): ResourceObservationFacts {\n\treturn {\n\t\tcpuProbe: snapshot.systemCpuPercent !== null,\n\t\tmemoryProbe: snapshot.processAvailableMemoryBytes !== null || snapshot.hostFreeMemoryBytes !== null,\n\t\theapLimitKnown: snapshot.heapLimitBytes > 0,\n\t};\n}\n\n/** §15.2 example shape: pressure, action, and the three caps. */\nexport function admissionObservationFacts(decision: ResourceAdmissionDecision): ResourceObservationFacts {\n\treturn {\n\t\tdecisionId: decision.decisionId,\n\t\tsnapshotDigest: decision.snapshotDigest,\n\t\tpressure: decision.pressure,\n\t\taction: decision.action,\n\t\tmaxToolConcurrency: decision.maxToolConcurrency,\n\t\tmaxParallelLanes: decision.maxParallelLanes,\n\t\tmaxHeavyProcesses: decision.maxHeavyProcesses,\n\t};\n}\n\nexport function classificationObservationFacts(classification: WorkloadClassification): ResourceObservationFacts {\n\treturn {\n\t\tworkloadClass: classification.workloadClass,\n\t\tcommandFamily: classification.commandFamily,\n\t\tcomplexity: classification.complexity,\n\t\tsafeToAutoShard: classification.safeToAutoShard,\n\t\treasonCodes: classification.reasonCodes.slice(0, 8).join(\",\"),\n\t};\n}\n\nexport function settledObservationFacts(event: PromptSettledEvent): ResourceObservationFacts {\n\treturn {\n\t\toutcome: event.outcome,\n\t\tdurationMs: event.durationMs,\n\t\t...(event.terminationKind !== undefined ? { terminationKind: event.terminationKind } : {}),\n\t};\n}\n\nexport function soundObservationFacts(result: CompletionSoundResult): ResourceObservationFacts {\n\treturn {\n\t\tbackend: result.backend,\n\t\tattempted: result.attempted,\n\t\tsuccess: result.success,\n\t\t...(result.diagnostic !== undefined ? { diagnostic: result.diagnostic.slice(0, 120) } : {}),\n\t};\n}\n\nconst MAX_LINE_BYTES = 8 * 1024;\nconst MAX_RECORDS = 10_000;\n\nexport interface ResourceObservationLoadResult {\n\treadonly records: readonly ResourceObservationRecord[];\n\treadonly diagnostics: readonly string[];\n}\n\nexport class ResourceObservationJournal {\n\tprivate readonly journalPath: string;\n\tprivate readonly promptRunId: string;\n\tprivate readonly now: () => Date;\n\tprivate seq = 0;\n\tprivate disabled = false;\n\n\tconstructor(journalPath: string, promptRunId: string, now: () => Date = () => new Date()) {\n\t\tthis.journalPath = journalPath;\n\t\tthis.promptRunId = promptRunId;\n\t\tthis.now = now;\n\t}\n\n\tstatic open(cwd: string, promptRunId: string, now?: () => Date): ResourceObservationJournal {\n\t\treturn new ResourceObservationJournal(\n\t\t\tpath.join(cwd, \".omk\", \"runs\", promptRunId, RESOURCE_OBSERVATION_JOURNAL_FILE),\n\t\t\tpromptRunId,\n\t\t\tnow,\n\t\t);\n\t}\n\n\tget filePath(): string {\n\t\treturn this.journalPath;\n\t}\n\n\t/** Fail-open append: returns false (and stops trying) instead of throwing. */\n\trecord(kind: ResourceObservationKind, facts: ResourceObservationFacts): boolean {\n\t\tif (this.disabled || this.seq >= MAX_RECORDS) return false;\n\t\tconst entry: ResourceObservationRecord = {\n\t\t\tschemaVersion: 1,\n\t\t\tseq: this.seq + 1,\n\t\t\tkind,\n\t\t\tat: this.now().toISOString(),\n\t\t\tpromptRunId: this.promptRunId,\n\t\t\tfacts,\n\t\t};\n\t\tconst line = `${JSON.stringify(entry)}\\n`;\n\t\tif (line.length > MAX_LINE_BYTES) return false;\n\t\ttry {\n\t\t\tfs.mkdirSync(path.dirname(this.journalPath), { recursive: true });\n\t\t\tfs.appendFileSync(this.journalPath, line, \"utf8\");\n\t\t\tthis.seq = entry.seq;\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// Observability must never break the run; stop retrying this run.\n\t\t\tthis.disabled = true;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Fail-open load: malformed lines become diagnostics, never throws. */\n\tload(): ResourceObservationLoadResult {\n\t\tlet raw: string;\n\t\ttry {\n\t\t\traw = fs.readFileSync(this.journalPath, \"utf8\");\n\t\t} catch {\n\t\t\treturn { records: [], diagnostics: [] };\n\t\t}\n\t\tconst records: ResourceObservationRecord[] = [];\n\t\tconst diagnostics: string[] = [];\n\t\tconst lines = raw.split(\"\\n\");\n\t\tfor (let index = 0; index < lines.length && records.length < MAX_RECORDS; index++) {\n\t\t\tconst line = lines[index].trim();\n\t\t\tif (line === \"\") continue;\n\t\t\tconst parsed = parseObservationLine(line);\n\t\t\tif (parsed === null) {\n\t\t\t\tdiagnostics.push(`line ${index + 1}: invalid observation record`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\trecords.push(parsed);\n\t\t}\n\t\treturn { records, diagnostics };\n\t}\n}\n\nconst KIND_SET: ReadonlySet<string> = new Set(RESOURCE_OBSERVATION_KINDS);\n\nfunction parseObservationLine(line: string): ResourceObservationRecord | null {\n\tif (line.length > MAX_LINE_BYTES) return null;\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(line);\n\t} catch {\n\t\treturn null;\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n\tconst record = value as Record<string, unknown>;\n\tif (record.schemaVersion !== 1) return null;\n\tif (typeof record.seq !== \"number\" || !Number.isSafeInteger(record.seq) || record.seq < 1) return null;\n\tif (typeof record.kind !== \"string\" || !KIND_SET.has(record.kind)) return null;\n\tif (typeof record.at !== \"string\" || typeof record.promptRunId !== \"string\") return null;\n\tif (typeof record.facts !== \"object\" || record.facts === null || Array.isArray(record.facts)) return null;\n\tfor (const factValue of Object.values(record.facts)) {\n\t\tconst kind = typeof factValue;\n\t\tif (factValue !== null && kind !== \"string\" && kind !== \"number\" && kind !== \"boolean\") return null;\n\t}\n\treturn record as unknown as ResourceObservationRecord;\n}\n"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { ResourceAdmissionDecision, ResourcePressure, ResourceReasonCode } from "./resource-admission.ts";
|
|
2
|
+
import type { WorkloadClassification } from "./workload-classifier.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Pure resource safety gate decision (OMK v0.97.x roadmap §11, M3/PR4).
|
|
5
|
+
*
|
|
6
|
+
* Maps (workload classification × admission decision) to a gate verdict.
|
|
7
|
+
* This module holds no permits and spawns nothing — the shared permit pool
|
|
8
|
+
* and the bash/launch integration consume these verdicts in the next slice.
|
|
9
|
+
*
|
|
10
|
+
* Order contract (§9.4, §22.2): command safety runs FIRST and stays
|
|
11
|
+
* authoritative. The input requires the literal `commandSafety: "allowed"`
|
|
12
|
+
* so a call site cannot even type-check unless the command already passed
|
|
13
|
+
* the safety gate; resource pressure can only throttle or defer an
|
|
14
|
+
* already-allowed command, never re-admit a blocked one.
|
|
15
|
+
*
|
|
16
|
+
* Fail-closed only where side effects matter (§4.6): heavy work and opaque
|
|
17
|
+
* complex shell are deferred at critical pressure, while light reads and
|
|
18
|
+
* bounded IO stay allowed so the agent remains usable (§21).
|
|
19
|
+
*/
|
|
20
|
+
export interface ResourceSafetyGateInput {
|
|
21
|
+
/** §9.4: structurally requires the command-safety gate to have allowed the command. */
|
|
22
|
+
readonly commandSafety: "allowed";
|
|
23
|
+
readonly classification: WorkloadClassification;
|
|
24
|
+
readonly decision: ResourceAdmissionDecision;
|
|
25
|
+
}
|
|
26
|
+
/** §11.3 structured block result. Bounded: no raw host values, paths, or identities. */
|
|
27
|
+
export interface ResourcePressureBlock {
|
|
28
|
+
readonly kind: "resource_pressure";
|
|
29
|
+
readonly pressure: ResourcePressure;
|
|
30
|
+
readonly action: "defer-heavy";
|
|
31
|
+
readonly reasonCodes: readonly ResourceReasonCode[];
|
|
32
|
+
readonly requiredAction: string;
|
|
33
|
+
}
|
|
34
|
+
export type ResourceSafetyGateVerdict = {
|
|
35
|
+
readonly kind: "allow";
|
|
36
|
+
} | {
|
|
37
|
+
readonly kind: "require-permit";
|
|
38
|
+
readonly weight: 1 | 2;
|
|
39
|
+
} | {
|
|
40
|
+
readonly kind: "block";
|
|
41
|
+
readonly block: ResourcePressureBlock;
|
|
42
|
+
};
|
|
43
|
+
export declare const RESOURCE_PRESSURE_REQUIRED_ACTION = "Create a bounded shard plan or free resources before retrying.";
|
|
44
|
+
/**
|
|
45
|
+
* Decide the §11.2 gate behavior for one already-safety-allowed command.
|
|
46
|
+
*
|
|
47
|
+
* | pressure | light | io | cpu | heavy / memory | unknown complex shell |
|
|
48
|
+
* | ----------- | ----- | ----- | -------- | -------------- | --------------------- |
|
|
49
|
+
* | normal | allow | allow | permit | permit | permit, no rewrite |
|
|
50
|
+
* | constrained | allow | allow | permit 1 | permit 1 | permit 1, no rewrite |
|
|
51
|
+
* | critical | allow | allow | permit 1 | block/defer | block/defer |
|
|
52
|
+
*/
|
|
53
|
+
export declare function decideResourceSafetyGate(input: ResourceSafetyGateInput): ResourceSafetyGateVerdict;
|
|
54
|
+
//# sourceMappingURL=resource-safety-gate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-safety-gate.d.ts","sourceRoot":"","sources":["../../src/core/resource-safety-gate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC/G,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAEvE;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,WAAW,uBAAuB;IACvC,wFAAuF;IACvF,QAAQ,CAAC,aAAa,EAAE,SAAS,CAAC;IAClC,QAAQ,CAAC,cAAc,EAAE,sBAAsB,CAAC;IAChD,QAAQ,CAAC,QAAQ,EAAE,yBAAyB,CAAC;CAC7C;AAED,yFAAwF;AACxF,MAAM,WAAW,qBAAqB;IACrC,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAC;IACnC,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,WAAW,EAAE,SAAS,kBAAkB,EAAE,CAAC;IACpD,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;CAChC;AAED,MAAM,MAAM,yBAAyB,GAClC;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAC1B;IAAE,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,GAC3D;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,qBAAqB,CAAA;CAAE,CAAC;AAErE,eAAO,MAAM,iCAAiC,mEAAmE,CAAC;AAElH;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,uBAAuB,GAAG,yBAAyB,CA2ClG","sourcesContent":["import type { ResourceAdmissionDecision, ResourcePressure, ResourceReasonCode } from \"./resource-admission.ts\";\nimport type { WorkloadClassification } from \"./workload-classifier.ts\";\n\n/**\n * Pure resource safety gate decision (OMK v0.97.x roadmap §11, M3/PR4).\n *\n * Maps (workload classification × admission decision) to a gate verdict.\n * This module holds no permits and spawns nothing — the shared permit pool\n * and the bash/launch integration consume these verdicts in the next slice.\n *\n * Order contract (§9.4, §22.2): command safety runs FIRST and stays\n * authoritative. The input requires the literal `commandSafety: \"allowed\"`\n * so a call site cannot even type-check unless the command already passed\n * the safety gate; resource pressure can only throttle or defer an\n * already-allowed command, never re-admit a blocked one.\n *\n * Fail-closed only where side effects matter (§4.6): heavy work and opaque\n * complex shell are deferred at critical pressure, while light reads and\n * bounded IO stay allowed so the agent remains usable (§21).\n */\n\nexport interface ResourceSafetyGateInput {\n\t/** §9.4: structurally requires the command-safety gate to have allowed the command. */\n\treadonly commandSafety: \"allowed\";\n\treadonly classification: WorkloadClassification;\n\treadonly decision: ResourceAdmissionDecision;\n}\n\n/** §11.3 structured block result. Bounded: no raw host values, paths, or identities. */\nexport interface ResourcePressureBlock {\n\treadonly kind: \"resource_pressure\";\n\treadonly pressure: ResourcePressure;\n\treadonly action: \"defer-heavy\";\n\treadonly reasonCodes: readonly ResourceReasonCode[];\n\treadonly requiredAction: string;\n}\n\nexport type ResourceSafetyGateVerdict =\n\t| { readonly kind: \"allow\" }\n\t| { readonly kind: \"require-permit\"; readonly weight: 1 | 2 }\n\t| { readonly kind: \"block\"; readonly block: ResourcePressureBlock };\n\nexport const RESOURCE_PRESSURE_REQUIRED_ACTION = \"Create a bounded shard plan or free resources before retrying.\";\n\n/**\n * Decide the §11.2 gate behavior for one already-safety-allowed command.\n *\n * | pressure | light | io | cpu | heavy / memory | unknown complex shell |\n * | ----------- | ----- | ----- | -------- | -------------- | --------------------- |\n * | normal | allow | allow | permit | permit | permit, no rewrite |\n * | constrained | allow | allow | permit 1 | permit 1 | permit 1, no rewrite |\n * | critical | allow | allow | permit 1 | block/defer | block/defer |\n */\nexport function decideResourceSafetyGate(input: ResourceSafetyGateInput): ResourceSafetyGateVerdict {\n\tconst { classification, decision } = input;\n\tconst critical = decision.pressure === \"critical\";\n\n\tif (classification.workloadClass === \"light\") {\n\t\treturn { kind: \"allow\" };\n\t}\n\tif (classification.workloadClass === \"io\") {\n\t\t// Critical still allows bounded IO; the run lease already caps overall\n\t\t// tool concurrency (§11.2 \"allow with cap\").\n\t\treturn { kind: \"allow\" };\n\t}\n\tif (classification.workloadClass === \"cpu\") {\n\t\treturn { kind: \"require-permit\", weight: 1 };\n\t}\n\n\t// heavy, memory (heavy-equivalent — the §11.2 table has no softer column\n\t// for memory-bound work), and unknown workloads.\n\tconst heavyEquivalent = classification.workloadClass === \"heavy\" || classification.workloadClass === \"memory\";\n\tconst opaqueComplexShell =\n\t\tclassification.workloadClass === \"unknown\" && classification.complexity === \"complex-shell\";\n\n\tif (critical && (heavyEquivalent || opaqueComplexShell)) {\n\t\treturn {\n\t\t\tkind: \"block\",\n\t\t\tblock: {\n\t\t\t\tkind: \"resource_pressure\",\n\t\t\t\tpressure: decision.pressure,\n\t\t\t\taction: \"defer-heavy\",\n\t\t\t\treasonCodes: decision.reasons,\n\t\t\t\trequiredAction: RESOURCE_PRESSURE_REQUIRED_ACTION,\n\t\t\t},\n\t\t};\n\t}\n\tif (heavyEquivalent) {\n\t\t// §10.3: container builds may consume double weight in the permit pool.\n\t\treturn { kind: \"require-permit\", weight: classification.commandFamily === \"container-build\" ? 2 : 1 };\n\t}\n\t// unknown (simple argv or, below critical, complex shell): permit-gated so\n\t// fanout stays bounded, but never blocked outright below critical, and a\n\t// simple unknown binary stays runnable even at critical (§21: the agent\n\t// must remain usable).\n\treturn { kind: \"require-permit\", weight: 1 };\n}\n"]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export const RESOURCE_PRESSURE_REQUIRED_ACTION = "Create a bounded shard plan or free resources before retrying.";
|
|
2
|
+
/**
|
|
3
|
+
* Decide the §11.2 gate behavior for one already-safety-allowed command.
|
|
4
|
+
*
|
|
5
|
+
* | pressure | light | io | cpu | heavy / memory | unknown complex shell |
|
|
6
|
+
* | ----------- | ----- | ----- | -------- | -------------- | --------------------- |
|
|
7
|
+
* | normal | allow | allow | permit | permit | permit, no rewrite |
|
|
8
|
+
* | constrained | allow | allow | permit 1 | permit 1 | permit 1, no rewrite |
|
|
9
|
+
* | critical | allow | allow | permit 1 | block/defer | block/defer |
|
|
10
|
+
*/
|
|
11
|
+
export function decideResourceSafetyGate(input) {
|
|
12
|
+
const { classification, decision } = input;
|
|
13
|
+
const critical = decision.pressure === "critical";
|
|
14
|
+
if (classification.workloadClass === "light") {
|
|
15
|
+
return { kind: "allow" };
|
|
16
|
+
}
|
|
17
|
+
if (classification.workloadClass === "io") {
|
|
18
|
+
// Critical still allows bounded IO; the run lease already caps overall
|
|
19
|
+
// tool concurrency (§11.2 "allow with cap").
|
|
20
|
+
return { kind: "allow" };
|
|
21
|
+
}
|
|
22
|
+
if (classification.workloadClass === "cpu") {
|
|
23
|
+
return { kind: "require-permit", weight: 1 };
|
|
24
|
+
}
|
|
25
|
+
// heavy, memory (heavy-equivalent — the §11.2 table has no softer column
|
|
26
|
+
// for memory-bound work), and unknown workloads.
|
|
27
|
+
const heavyEquivalent = classification.workloadClass === "heavy" || classification.workloadClass === "memory";
|
|
28
|
+
const opaqueComplexShell = classification.workloadClass === "unknown" && classification.complexity === "complex-shell";
|
|
29
|
+
if (critical && (heavyEquivalent || opaqueComplexShell)) {
|
|
30
|
+
return {
|
|
31
|
+
kind: "block",
|
|
32
|
+
block: {
|
|
33
|
+
kind: "resource_pressure",
|
|
34
|
+
pressure: decision.pressure,
|
|
35
|
+
action: "defer-heavy",
|
|
36
|
+
reasonCodes: decision.reasons,
|
|
37
|
+
requiredAction: RESOURCE_PRESSURE_REQUIRED_ACTION,
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
if (heavyEquivalent) {
|
|
42
|
+
// §10.3: container builds may consume double weight in the permit pool.
|
|
43
|
+
return { kind: "require-permit", weight: classification.commandFamily === "container-build" ? 2 : 1 };
|
|
44
|
+
}
|
|
45
|
+
// unknown (simple argv or, below critical, complex shell): permit-gated so
|
|
46
|
+
// fanout stays bounded, but never blocked outright below critical, and a
|
|
47
|
+
// simple unknown binary stays runnable even at critical (§21: the agent
|
|
48
|
+
// must remain usable).
|
|
49
|
+
return { kind: "require-permit", weight: 1 };
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=resource-safety-gate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-safety-gate.js","sourceRoot":"","sources":["../../src/core/resource-safety-gate.ts"],"names":[],"mappings":"AA0CA,MAAM,CAAC,MAAM,iCAAiC,GAAG,gEAAgE,CAAC;AAElH;;;;;;;;GAQG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAA8B,EAA6B;IACnG,MAAM,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IAC3C,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAQ,KAAK,UAAU,CAAC;IAElD,IAAI,cAAc,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QAC9C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC1B,CAAC;IACD,IAAI,cAAc,CAAC,aAAa,KAAK,IAAI,EAAE,CAAC;QAC3C,uEAAuE;QACvE,8CAA6C;QAC7C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC1B,CAAC;IACD,IAAI,cAAc,CAAC,aAAa,KAAK,KAAK,EAAE,CAAC;QAC5C,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;IAC9C,CAAC;IAED,4EAAyE;IACzE,iDAAiD;IACjD,MAAM,eAAe,GAAG,cAAc,CAAC,aAAa,KAAK,OAAO,IAAI,cAAc,CAAC,aAAa,KAAK,QAAQ,CAAC;IAC9G,MAAM,kBAAkB,GACvB,cAAc,CAAC,aAAa,KAAK,SAAS,IAAI,cAAc,CAAC,UAAU,KAAK,eAAe,CAAC;IAE7F,IAAI,QAAQ,IAAI,CAAC,eAAe,IAAI,kBAAkB,CAAC,EAAE,CAAC;QACzD,OAAO;YACN,IAAI,EAAE,OAAO;YACb,KAAK,EAAE;gBACN,IAAI,EAAE,mBAAmB;gBACzB,QAAQ,EAAE,QAAQ,CAAC,QAAQ;gBAC3B,MAAM,EAAE,aAAa;gBACrB,WAAW,EAAE,QAAQ,CAAC,OAAO;gBAC7B,cAAc,EAAE,iCAAiC;aACjD;SACD,CAAC;IACH,CAAC;IACD,IAAI,eAAe,EAAE,CAAC;QACrB,yEAAwE;QACxE,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,EAAE,cAAc,CAAC,aAAa,KAAK,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACvG,CAAC;IACD,2EAA2E;IAC3E,yEAAyE;IACzE,yEAAwE;IACxE,uBAAuB;IACvB,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;AAAA,CAC7C","sourcesContent":["import type { ResourceAdmissionDecision, ResourcePressure, ResourceReasonCode } from \"./resource-admission.ts\";\nimport type { WorkloadClassification } from \"./workload-classifier.ts\";\n\n/**\n * Pure resource safety gate decision (OMK v0.97.x roadmap §11, M3/PR4).\n *\n * Maps (workload classification × admission decision) to a gate verdict.\n * This module holds no permits and spawns nothing — the shared permit pool\n * and the bash/launch integration consume these verdicts in the next slice.\n *\n * Order contract (§9.4, §22.2): command safety runs FIRST and stays\n * authoritative. The input requires the literal `commandSafety: \"allowed\"`\n * so a call site cannot even type-check unless the command already passed\n * the safety gate; resource pressure can only throttle or defer an\n * already-allowed command, never re-admit a blocked one.\n *\n * Fail-closed only where side effects matter (§4.6): heavy work and opaque\n * complex shell are deferred at critical pressure, while light reads and\n * bounded IO stay allowed so the agent remains usable (§21).\n */\n\nexport interface ResourceSafetyGateInput {\n\t/** §9.4: structurally requires the command-safety gate to have allowed the command. */\n\treadonly commandSafety: \"allowed\";\n\treadonly classification: WorkloadClassification;\n\treadonly decision: ResourceAdmissionDecision;\n}\n\n/** §11.3 structured block result. Bounded: no raw host values, paths, or identities. */\nexport interface ResourcePressureBlock {\n\treadonly kind: \"resource_pressure\";\n\treadonly pressure: ResourcePressure;\n\treadonly action: \"defer-heavy\";\n\treadonly reasonCodes: readonly ResourceReasonCode[];\n\treadonly requiredAction: string;\n}\n\nexport type ResourceSafetyGateVerdict =\n\t| { readonly kind: \"allow\" }\n\t| { readonly kind: \"require-permit\"; readonly weight: 1 | 2 }\n\t| { readonly kind: \"block\"; readonly block: ResourcePressureBlock };\n\nexport const RESOURCE_PRESSURE_REQUIRED_ACTION = \"Create a bounded shard plan or free resources before retrying.\";\n\n/**\n * Decide the §11.2 gate behavior for one already-safety-allowed command.\n *\n * | pressure | light | io | cpu | heavy / memory | unknown complex shell |\n * | ----------- | ----- | ----- | -------- | -------------- | --------------------- |\n * | normal | allow | allow | permit | permit | permit, no rewrite |\n * | constrained | allow | allow | permit 1 | permit 1 | permit 1, no rewrite |\n * | critical | allow | allow | permit 1 | block/defer | block/defer |\n */\nexport function decideResourceSafetyGate(input: ResourceSafetyGateInput): ResourceSafetyGateVerdict {\n\tconst { classification, decision } = input;\n\tconst critical = decision.pressure === \"critical\";\n\n\tif (classification.workloadClass === \"light\") {\n\t\treturn { kind: \"allow\" };\n\t}\n\tif (classification.workloadClass === \"io\") {\n\t\t// Critical still allows bounded IO; the run lease already caps overall\n\t\t// tool concurrency (§11.2 \"allow with cap\").\n\t\treturn { kind: \"allow\" };\n\t}\n\tif (classification.workloadClass === \"cpu\") {\n\t\treturn { kind: \"require-permit\", weight: 1 };\n\t}\n\n\t// heavy, memory (heavy-equivalent — the §11.2 table has no softer column\n\t// for memory-bound work), and unknown workloads.\n\tconst heavyEquivalent = classification.workloadClass === \"heavy\" || classification.workloadClass === \"memory\";\n\tconst opaqueComplexShell =\n\t\tclassification.workloadClass === \"unknown\" && classification.complexity === \"complex-shell\";\n\n\tif (critical && (heavyEquivalent || opaqueComplexShell)) {\n\t\treturn {\n\t\t\tkind: \"block\",\n\t\t\tblock: {\n\t\t\t\tkind: \"resource_pressure\",\n\t\t\t\tpressure: decision.pressure,\n\t\t\t\taction: \"defer-heavy\",\n\t\t\t\treasonCodes: decision.reasons,\n\t\t\t\trequiredAction: RESOURCE_PRESSURE_REQUIRED_ACTION,\n\t\t\t},\n\t\t};\n\t}\n\tif (heavyEquivalent) {\n\t\t// §10.3: container builds may consume double weight in the permit pool.\n\t\treturn { kind: \"require-permit\", weight: classification.commandFamily === \"container-build\" ? 2 : 1 };\n\t}\n\t// unknown (simple argv or, below critical, complex shell): permit-gated so\n\t// fanout stays bounded, but never blocked outright below critical, and a\n\t// simple unknown binary stays runnable even at critical (§21: the agent\n\t// must remain usable).\n\treturn { kind: \"require-permit\", weight: 1 };\n}\n"]}
|
|
@@ -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,oFAAoF;AACpF,MAAM,MAAM,oBAAoB,GAAG,cAAc,GAAG,sBAAsB,GAAG,qBAAqB,CAAC;AAEnG,MAAM,MAAM,eAAe,GAAG,aAAa,GAAG,cAAc,GAAG,eAAe,GAAG,eAAe,GAAG,oBAAoB,CAAC;AAExH,MAAM,MAAM,qBAAqB,GAC9B,mBAAmB,GACnB,cAAc,GACd,gBAAgB,GAChB,QAAQ,GACR,SAAS,GACT,gBAAgB,GAChB,YAAY,GACZ,eAAe,GACf,kBAAkB,GAClB,iBAAiB,GAC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AC,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 \"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,GAChB,QAAQ,GACR,SAAS,GACT,gBAAgB,GAChB,YAAY,GACZ,eAAe,GACf,kBAAkB,GAClB,iBAAiB,GACjB,oBAAoB,GACpB,iBAAiB,GACjB,iBAAiB,GACjB,cAAc,GACd,0BAA0B,GAC1B,sBAAsB,GACtB,kBAAkB,GAClB,6BAA6B,CAAC;AAEjC,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,aAAa,EAAE,OAAO,0BAA0B,CAAC;IAC1D,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAC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AAS;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
|
}
|