open-multi-agent-kit 0.95.0 → 0.95.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 +33 -0
- package/README.md +1 -1
- package/dist/approvals/approval-receipt-store.d.ts +18 -0
- package/dist/approvals/approval-receipt-store.d.ts.map +1 -0
- package/dist/approvals/approval-receipt-store.js +169 -0
- package/dist/approvals/approval-receipt-store.js.map +1 -0
- package/dist/approvals/approval-receipt.d.ts +43 -0
- package/dist/approvals/approval-receipt.d.ts.map +1 -0
- package/dist/approvals/approval-receipt.js +208 -0
- package/dist/approvals/approval-receipt.js.map +1 -0
- package/dist/approvals/approval-verifier.d.ts +17 -0
- package/dist/approvals/approval-verifier.d.ts.map +1 -0
- package/dist/approvals/approval-verifier.js +23 -0
- package/dist/approvals/approval-verifier.js.map +1 -0
- package/dist/approvals/plannotator-approval-bridge.d.ts +58 -0
- package/dist/approvals/plannotator-approval-bridge.d.ts.map +1 -0
- package/dist/approvals/plannotator-approval-bridge.js +169 -0
- package/dist/approvals/plannotator-approval-bridge.js.map +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +2 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/commands/package-doctor-cli.d.ts +13 -0
- package/dist/commands/package-doctor-cli.d.ts.map +1 -0
- package/dist/commands/package-doctor-cli.js +80 -0
- package/dist/commands/package-doctor-cli.js.map +1 -0
- package/dist/commands/router-feedback-cli.d.ts +11 -0
- package/dist/commands/router-feedback-cli.d.ts.map +1 -0
- package/dist/commands/router-feedback-cli.js +99 -0
- package/dist/commands/router-feedback-cli.js.map +1 -0
- package/dist/commands/stats-cli.d.ts +20 -0
- package/dist/commands/stats-cli.d.ts.map +1 -0
- package/dist/commands/stats-cli.js +99 -0
- package/dist/commands/stats-cli.js.map +1 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +4 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +97 -29
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +583 -199
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +8 -2
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/compaction/transaction.d.ts +9 -0
- package/dist/core/compaction/transaction.d.ts.map +1 -1
- package/dist/core/compaction/transaction.js +17 -2
- package/dist/core/compaction/transaction.js.map +1 -1
- package/dist/core/context-budget-governor-v2.d.ts +1 -1
- package/dist/core/context-budget-governor-v2.d.ts.map +1 -1
- package/dist/core/context-budget-governor-v2.js +1 -1
- package/dist/core/context-budget-governor-v2.js.map +1 -1
- package/dist/core/context-budget-system-prompt.d.ts.map +1 -1
- package/dist/core/context-budget-system-prompt.js +18 -2
- package/dist/core/context-budget-system-prompt.js.map +1 -1
- package/dist/core/context-budget-v2-cache-disk.d.ts +109 -0
- package/dist/core/context-budget-v2-cache-disk.d.ts.map +1 -0
- package/dist/core/context-budget-v2-cache-disk.js +343 -0
- package/dist/core/context-budget-v2-cache-disk.js.map +1 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts +22 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-keys.js +4 -4
- package/dist/core/context-budget-v2-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-cache.d.ts +1 -0
- package/dist/core/context-budget-v2-cache.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache.js +1 -0
- package/dist/core/context-budget-v2-cache.js.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-plan-cache-keys.js +39 -5
- package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +17 -14
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +1 -0
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +45 -22
- package/dist/core/extensions/loader.js.bak-sharedjiti-20260812-111246 +553 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +4 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/headroom.d.ts.map +1 -1
- package/dist/core/headroom.js +7 -2
- package/dist/core/headroom.js.map +1 -1
- package/dist/core/mcp/client.d.ts +105 -0
- package/dist/core/mcp/client.d.ts.map +1 -0
- package/dist/core/mcp/client.js +198 -0
- package/dist/core/mcp/client.js.map +1 -0
- package/dist/core/mcp/config.d.ts +23 -0
- package/dist/core/mcp/config.d.ts.map +1 -0
- package/dist/core/mcp/config.js +89 -0
- package/dist/core/mcp/config.js.map +1 -0
- package/dist/core/mcp/index.d.ts +15 -0
- package/dist/core/mcp/index.d.ts.map +1 -0
- package/dist/core/mcp/index.js +15 -0
- package/dist/core/mcp/index.js.map +1 -0
- package/dist/core/mcp/manager.d.ts +84 -0
- package/dist/core/mcp/manager.d.ts.map +1 -0
- package/dist/core/mcp/manager.js +173 -0
- package/dist/core/mcp/manager.js.map +1 -0
- package/dist/core/mcp/protocol.d.ts +59 -0
- package/dist/core/mcp/protocol.d.ts.map +1 -0
- package/dist/core/mcp/protocol.js +103 -0
- package/dist/core/mcp/protocol.js.map +1 -0
- package/dist/core/mcp/stdio-transport.d.ts +63 -0
- package/dist/core/mcp/stdio-transport.d.ts.map +1 -0
- package/dist/core/mcp/stdio-transport.js +132 -0
- package/dist/core/mcp/stdio-transport.js.map +1 -0
- package/dist/core/mcp/tools.d.ts +47 -0
- package/dist/core/mcp/tools.d.ts.map +1 -0
- package/dist/core/mcp/tools.js +102 -0
- package/dist/core/mcp/tools.js.map +1 -0
- package/dist/core/package-archive.d.ts +3 -0
- package/dist/core/package-archive.d.ts.map +1 -0
- package/dist/core/package-archive.js +161 -0
- package/dist/core/package-archive.js.map +1 -0
- package/dist/core/package-doctor-source-scan.d.ts +13 -0
- package/dist/core/package-doctor-source-scan.d.ts.map +1 -0
- package/dist/core/package-doctor-source-scan.js +124 -0
- package/dist/core/package-doctor-source-scan.js.map +1 -0
- package/dist/core/package-doctor.d.ts +41 -0
- package/dist/core/package-doctor.d.ts.map +1 -0
- package/dist/core/package-doctor.js +145 -0
- package/dist/core/package-doctor.js.map +1 -0
- package/dist/core/package-manager.d.ts +10 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +175 -42
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/package-manifest.d.ts +26 -0
- package/dist/core/package-manifest.d.ts.map +1 -0
- package/dist/core/package-manifest.js +85 -0
- package/dist/core/package-manifest.js.map +1 -0
- package/dist/core/pi-compat.d.ts +5 -0
- package/dist/core/pi-compat.d.ts.map +1 -0
- package/dist/core/pi-compat.js +18 -0
- package/dist/core/pi-compat.js.map +1 -0
- package/dist/core/reasoning-router-bias.d.ts +10 -14
- package/dist/core/reasoning-router-bias.d.ts.map +1 -1
- package/dist/core/reasoning-router-bias.js +22 -15
- package/dist/core/reasoning-router-bias.js.map +1 -1
- package/dist/core/reasoning-router-v4.d.ts +9 -1
- package/dist/core/reasoning-router-v4.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4.js +20 -5
- package/dist/core/reasoning-router-v4.js.map +1 -1
- package/dist/core/redaction.d.ts +2 -5
- package/dist/core/redaction.d.ts.map +1 -1
- package/dist/core/redaction.js +14 -1
- package/dist/core/redaction.js.map +1 -1
- package/dist/core/repository-learning-scope.d.ts +10 -0
- package/dist/core/repository-learning-scope.d.ts.map +1 -0
- package/dist/core/repository-learning-scope.js +42 -0
- package/dist/core/repository-learning-scope.js.map +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +16 -1
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/router-feedback-collector.d.ts +2 -1
- package/dist/core/router-feedback-collector.d.ts.map +1 -1
- package/dist/core/router-feedback-collector.js +2 -2
- package/dist/core/router-feedback-collector.js.map +1 -1
- package/dist/core/runtime-provenance.d.ts +54 -0
- package/dist/core/runtime-provenance.d.ts.map +1 -0
- package/dist/core/runtime-provenance.js +115 -0
- package/dist/core/runtime-provenance.js.map +1 -0
- package/dist/core/sandbox/backend.d.ts.map +1 -1
- package/dist/core/sandbox/backend.js +39 -21
- package/dist/core/sandbox/backend.js.map +1 -1
- package/dist/core/sandbox/default-policy.d.ts +4 -5
- package/dist/core/sandbox/default-policy.d.ts.map +1 -1
- package/dist/core/sandbox/default-policy.js +9 -11
- package/dist/core/sandbox/default-policy.js.map +1 -1
- package/dist/core/session-bash-runtime.d.ts +4 -4
- package/dist/core/session-bash-runtime.d.ts.map +1 -1
- package/dist/core/session-bash-runtime.js +6 -5
- package/dist/core/session-bash-runtime.js.map +1 -1
- package/dist/core/session-compaction-service.d.ts.map +1 -1
- package/dist/core/session-compaction-service.js +7 -7
- package/dist/core/session-compaction-service.js.map +1 -1
- package/dist/core/session-manager.d.ts +4 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +47 -7
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +7 -4
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +11 -3
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts +9 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +10 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +2 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +15 -0
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/turn-metrics.d.ts +135 -0
- package/dist/core/turn-metrics.d.ts.map +1 -0
- package/dist/core/turn-metrics.js +261 -0
- package/dist/core/turn-metrics.js.map +1 -0
- package/dist/core/verified-bash-runtime.d.ts.map +1 -1
- package/dist/core/verified-bash-runtime.js +10 -4
- package/dist/core/verified-bash-runtime.js.map +1 -1
- package/dist/guardrails/replay-ledger-lock-owner.d.ts +7 -0
- package/dist/guardrails/replay-ledger-lock-owner.d.ts.map +1 -1
- package/dist/guardrails/replay-ledger-lock-owner.js +39 -0
- package/dist/guardrails/replay-ledger-lock-owner.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +18 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.d.ts.map +1 -1
- package/dist/modes/interactive/components/control-panel-layout.js +2 -2
- package/dist/modes/interactive/components/control-panel-layout.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +3 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +40 -12
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +10 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-sidebar.d.ts +14 -2
- package/dist/modes/interactive/components/status-sidebar.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-sidebar.js +106 -19
- package/dist/modes/interactive/components/status-sidebar.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +10 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +104 -17
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/docs/compaction.md +25 -3
- package/docs/containerization.md +14 -2
- package/docs/docs.json +8 -0
- package/docs/environment-variables.md +1 -1
- package/docs/extensions.md +75 -16
- package/docs/mcp.md +97 -0
- package/docs/metrics.md +87 -0
- package/docs/packages.md +25 -4
- package/docs/providers.md +1 -1
- package/docs/sdk.md +25 -4
- package/docs/settings.md +8 -7
- package/docs/usage.md +13 -3
- 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/plannotator-approval-bridge.ts +83 -0
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/subagent/README.md +21 -11
- package/examples/extensions/subagent/adaptive-agent-runtime.ts +9 -3
- package/examples/extensions/subagent/agents/planner.md +1 -3
- package/examples/extensions/subagent/agents/reviewer.md +1 -3
- package/examples/extensions/subagent/agents/scout.md +1 -3
- package/examples/extensions/subagent/agents/worker.md +0 -1
- package/examples/extensions/subagent/agents.test.ts +9 -0
- package/examples/extensions/subagent/agents.ts +11 -4
- package/examples/extensions/subagent/deadline-budget.test.ts +32 -0
- package/examples/extensions/subagent/deadline-budget.ts +25 -1
- package/examples/extensions/subagent/fixtures/fake-omk-json.mjs +10 -0
- package/examples/extensions/subagent/index.ts +234 -55
- package/examples/extensions/subagent/subagent-execution-policy.test.ts +27 -0
- package/examples/extensions/subagent/subagent-extension-smoke.test.ts +167 -2
- package/examples/extensions/subagent/workflow-graph.test.ts +80 -0
- package/examples/extensions/subagent/workflow-graph.ts +89 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +253 -439
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,
|
|
1
|
+
{"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAOtD,MAAM,WAAW,mBAAmB;IACnC,+DAA+D;IAC/D,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IAC1B,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,mDAAmD;IACnD,SAAS,EAAE,OAAO,CAAC;IACnB,uCAAuC;IACvC,SAAS,EAAE,OAAO,CAAC;IACnB,yFAAyF;IACzF,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAuIrB","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `omk-bash-${id}.log`);\n\t\t// Owner-only permissions: full output can contain secrets (env vars, tokens, etc.).\n\t\ttempFileStream = createWriteStream(tempFilePath, { mode: 0o600 });\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\t/** Close and delete the temp file when its path is never surfaced to the caller. */\n\tconst discardTempFile = async () => {\n\t\tif (!tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst path = tempFilePath;\n\t\tconst stream = tempFileStream;\n\t\ttempFilePath = undefined;\n\t\ttempFileStream = undefined;\n\t\tif (stream) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tstream.end(() => resolve());\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tawait rm(path, { force: true });\n\t\t} catch {\n\t\t\t// Best effort: a stale temp file must not fail the command.\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\tenv: options?.env,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t} else {\n\t\t\t// fullOutputPath is only surfaced when output is truncated; don't leave the spill file behind.\n\t\t\tawait discardTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// end() is async — wait for flush so fullOutputPath is complete\n\t\t\t// when the caller reads it (flaky empty/partial file under load).\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\ttempFileStream!.end(() => resolve());\n\t\t\t});\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t} else {\n\t\t\t\t// fullOutputPath is only surfaced when output is truncated; don't leave the spill file behind.\n\t\t\t\tawait discardTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\ttempFileStream!.end(() => resolve());\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\t// The path is never reported when the command throws; clean up the spill file.\n\t\tawait discardTempFile();\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
@@ -100,7 +100,11 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
100
100
|
await discardTempFile();
|
|
101
101
|
}
|
|
102
102
|
if (tempFileStream) {
|
|
103
|
-
|
|
103
|
+
// end() is async — wait for flush so fullOutputPath is complete
|
|
104
|
+
// when the caller reads it (flaky empty/partial file under load).
|
|
105
|
+
await new Promise((resolve) => {
|
|
106
|
+
tempFileStream.end(() => resolve());
|
|
107
|
+
});
|
|
104
108
|
}
|
|
105
109
|
const cancelled = options?.signal?.aborted ?? false;
|
|
106
110
|
return {
|
|
@@ -124,7 +128,9 @@ export async function executeBashWithOperations(command, cwd, operations, option
|
|
|
124
128
|
await discardTempFile();
|
|
125
129
|
}
|
|
126
130
|
if (tempFileStream) {
|
|
127
|
-
|
|
131
|
+
await new Promise((resolve) => {
|
|
132
|
+
tempFileStream.end(() => resolve());
|
|
133
|
+
});
|
|
128
134
|
}
|
|
129
135
|
return {
|
|
130
136
|
output: truncationResult.truncated ? truncationResult.content : fullOutput,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAoB,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AA2BtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B,EACP;IACtB,MAAM,YAAY,GAAa,EAAE,CAAC;IAClC,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,cAAc,GAAG,iBAAiB,GAAG,CAAC,CAAC;IAE7C,IAAI,YAAgC,CAAC;IACrC,IAAI,cAAuC,CAAC;IAC5C,IAAI,UAAU,GAAG,CAAC,CAAC;IAEnB,MAAM,cAAc,GAAG,GAAG,EAAE,CAAC;QAC5B,IAAI,YAAY,EAAE,CAAC;YAClB,OAAO;QACR,CAAC;QACD,MAAM,EAAE,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAC1C,YAAY,GAAG,IAAI,CAAC,MAAM,EAAE,EAAE,YAAY,EA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AAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;YAC1E,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,IAAI,SAAS,CAAC;YAChE,SAAS;YACT,SAAS,EAAE,gBAAgB,CAAC,SAAS;YACrC,cAAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;iBAAM,CAAC;gBACP,+FAA+F;gBAC/F,MAAM,eAAe,EAAE,CAAC;YACzB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,cAAc,CAAC,GAAG,EAAE,CAAC;YACtB,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,+EAA+E;QAC/E,MAAM,eAAe,EAAE,CAAC;QAExB,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `omk-bash-${id}.log`);\n\t\t// Owner-only permissions: full output can contain secrets (env vars, tokens, etc.).\n\t\ttempFileStream = createWriteStream(tempFilePath, { mode: 0o600 });\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\t/** Close and delete the temp file when its path is never surfaced to the caller. */\n\tconst discardTempFile = async () => {\n\t\tif (!tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst path = tempFilePath;\n\t\tconst stream = tempFileStream;\n\t\ttempFilePath = undefined;\n\t\ttempFileStream = undefined;\n\t\tif (stream) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tstream.end(() => resolve());\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tawait rm(path, { force: true });\n\t\t} catch {\n\t\t\t// Best effort: a stale temp file must not fail the command.\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\tenv: options?.env,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t} else {\n\t\t\t// fullOutputPath is only surfaced when output is truncated; don't leave the spill file behind.\n\t\t\tawait discardTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.end();\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t} else {\n\t\t\t\t// fullOutputPath is only surfaced when output is truncated; don't leave the spill file behind.\n\t\t\t\tawait discardTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\ttempFileStream.end();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\t// The path is never reported when the command throws; clean up the spill file.\n\t\tawait discardTempFile();\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAoB,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,SA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C,SAAS;YACrC,cAAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;iBAAM,CAAC;gBACP,+FAA+F;gBAC/F,MAAM,eAAe,EAAE,CAAC;YACzB,CAAC;YACD,IAAI,cAAc,EAAE,CAAC;gBACpB,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC;oBACpC,cAAe,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;gBAAA,CACrC,CAAC,CAAC;YACJ,CAAC;YACD,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,+EAA+E;QAC/E,MAAM,eAAe,EAAE,CAAC;QAExB,MAAM,GAAG,CAAC;IACX,CAAC;AAAA,CACD","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stripAnsi } from \"../utils/ansi.ts\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized) */\n\tonChunk?: (chunk: string) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFileStream: WriteStream | undefined;\n\tlet totalBytes = 0;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\ttempFilePath = join(tmpdir(), `omk-bash-${id}.log`);\n\t\t// Owner-only permissions: full output can contain secrets (env vars, tokens, etc.).\n\t\ttempFileStream = createWriteStream(tempFilePath, { mode: 0o600 });\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFileStream.write(chunk);\n\t\t}\n\t};\n\n\t/** Close and delete the temp file when its path is never surfaced to the caller. */\n\tconst discardTempFile = async () => {\n\t\tif (!tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tconst path = tempFilePath;\n\t\tconst stream = tempFileStream;\n\t\ttempFilePath = undefined;\n\t\ttempFileStream = undefined;\n\t\tif (stream) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tstream.end(() => resolve());\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tawait rm(path, { force: true });\n\t\t} catch {\n\t\t\t// Best effort: a stale temp file must not fail the command.\n\t\t}\n\t};\n\n\tconst decoder = new TextDecoder();\n\n\tconst onData = (data: Buffer) => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoder.decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFileStream) {\n\t\t\ttempFileStream.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\tenv: options?.env,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t} else {\n\t\t\t// fullOutputPath is only surfaced when output is truncated; don't leave the spill file behind.\n\t\t\tawait discardTempFile();\n\t\t}\n\t\tif (tempFileStream) {\n\t\t\t// end() is async — wait for flush so fullOutputPath is complete\n\t\t\t// when the caller reads it (flaky empty/partial file under load).\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\ttempFileStream!.end(() => resolve());\n\t\t\t});\n\t\t}\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t} else {\n\t\t\t\t// fullOutputPath is only surfaced when output is truncated; don't leave the spill file behind.\n\t\t\t\tawait discardTempFile();\n\t\t\t}\n\t\t\tif (tempFileStream) {\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\ttempFileStream!.end(() => resolve());\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\t// The path is never reported when the command throws; clean up the spill file.\n\t\tawait discardTempFile();\n\n\t\tthrow err;\n\t}\n}\n"]}
|
|
@@ -2,6 +2,15 @@ import type { SessionIntegrityReport } from "../session-integrity.ts";
|
|
|
2
2
|
export declare const SESSION_REVISION_TOKEN_SCHEMA_VERSION: 1;
|
|
3
3
|
export declare const COMPACTION_TRANSACTION_SCHEMA_VERSION: 1;
|
|
4
4
|
export declare const COMPACTION_ENVELOPE_SCHEMA_VERSION: 2;
|
|
5
|
+
export declare function containsCredentialShape(value: string): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Deterministically mask credential-shaped spans so sanitized text always
|
|
8
|
+
* satisfies this module's fail-closed content validators. Producers (compaction
|
|
9
|
+
* summaries, preserved provenance) must route generated text through this
|
|
10
|
+
* before validation; otherwise a paranoid validator match would abort the
|
|
11
|
+
* entire compaction and strand an overflowed session.
|
|
12
|
+
*/
|
|
13
|
+
export declare function redactCredentialShapedContent(value: string): string;
|
|
5
14
|
export interface SessionFileIdentity {
|
|
6
15
|
readonly dev: string;
|
|
7
16
|
readonly ino: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/transaction.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGX,sBAAsB,EACtB,MAAM,yBAAyB,CAAC;AAEjC,eAAO,MAAM,qCAAqC,GAAa,CAAC;AAChE,eAAO,MAAM,qCAAqC,GAAa,CAAC;AAChE,eAAO,MAAM,kCAAkC,GAAa,CAAC;AA0B7D,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,oBAAoB;IACpC,QAAQ,CAAC,aAAa,EAAE,OAAO,qCAAqC,CAAC;IACrE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC,QAAQ,CAAC,YAAY,CAAC,EAAE,mBAAmB,CAAC;CAC5C;AAED,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CA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AK,EAAE,2BAA2B,GAAG,wBAAwB,CAmFnG;AAcD,uEAAuE;AACvE,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB,CA0B7E;AAED,sFAAsF;AACtF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,6BAA6B,GAAG,kBAAkB,CA8BjG","sourcesContent":["import type { TranscriptIntegrityIssue, TranscriptIntegrityReport } from \"omk-agent-core\";\nimport { inspectTranscriptIntegrity } from \"omk-agent-core\";\nimport type {\n\tSessionIntegrityFinding,\n\tSessionIntegrityReasonCode,\n\tSessionIntegrityReport,\n} from \"../session-integrity.ts\";\n\nexport const SESSION_REVISION_TOKEN_SCHEMA_VERSION = 1 as const;\nexport const COMPACTION_TRANSACTION_SCHEMA_VERSION = 1 as const;\nexport const COMPACTION_ENVELOPE_SCHEMA_VERSION = 2 as const;\n\nconst MAX_METADATA_LENGTH = 256;\nconst MAX_FILE_IDENTITY_LENGTH = 32;\nconst MAX_SOURCE_ENTRIES = 4096;\nconst MAX_PROVENANCE_IDS = 1024;\nconst MAX_LATEST_INTENT_LENGTH = 16_384;\nconst MAX_SUMMARY_LENGTH = 262_144;\nconst MAX_PROVENANCE_TEXT_LENGTH = 4096;\nconst MAX_NEXT_ACTION_LENGTH = 4096;\nconst MAX_MODEL_HISTORY_ENTRIES = 256;\nconst EMPTY_SHA256 = \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\";\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\nconst DECIMAL_STRING_PATTERN = /^[0-9]+$/u;\nconst CANONICAL_TIMESTAMP_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/u;\nconst METADATA_CONTROL_PATTERN = /[\\u0000-\\u001f\\u007f]/u;\nconst CONTENT_CONTROL_PATTERN = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/u;\nconst CREDENTIAL_SHAPE_PATTERN =\n\t/-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:^|[\\s\"'`:])bearer\\s+[A-Za-z0-9._~+/-]{8,}|(?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|passwd|client[-_ ]?secret|secret[-_ ]?(?:key|token))\\s*[:=]\\s*[\"']?[^\\s\"',;]{3,}|(?:sk|ghp|gho|ghu|ghs|github_pat|xox[baprs])[-_][A-Za-z0-9_-]{8,}/iu;\nconst REDACTED_ASSIGNMENT_PATTERN =\n\t/\\s*[:=]\\s*(?:\"\\[REDACTED\\]\"(?![A-Za-z0-9_+/-])|'\\[REDACTED\\]'(?![A-Za-z0-9_+/-])|\\[REDACTED\\](?![A-Za-z0-9._~+/-]))/giu;\n\nfunction containsCredentialShape(value: string): boolean {\n\treturn CREDENTIAL_SHAPE_PATTERN.test(value.replace(REDACTED_ASSIGNMENT_PATTERN, \"\"));\n}\n\nexport interface SessionFileIdentity {\n\treadonly dev: string;\n\treadonly ino: string;\n}\n\nexport interface SessionRevisionToken {\n\treadonly schemaVersion: typeof SESSION_REVISION_TOKEN_SCHEMA_VERSION;\n\treadonly sessionId: string;\n\treadonly completeBytes: number;\n\treadonly recordCount: number;\n\treadonly leafId: string | null;\n\treadonly lastEntryId: string | null;\n\treadonly completePrefixSha256: string;\n\treadonly fileIdentity?: SessionFileIdentity;\n}\n\nexport interface SessionRevisionTokenInput {\n\treadonly schemaVersion?: typeof SESSION_REVISION_TOKEN_SCHEMA_VERSION;\n\treadonly sessionId: string;\n\treadonly completeBytes: number;\n\treadonly recordCount: number;\n\treadonly leafId: string | null;\n\treadonly lastEntryId: string | null;\n\treadonly completePrefixSha256: string;\n\treadonly fileIdentity?: SessionFileIdentity;\n}\n\nexport interface CompactionSourceIdentity {\n\treadonly sessionId: string;\n\treadonly entryIds: readonly string[];\n\treadonly firstEntryId: string;\n\treadonly lastEntryId: string;\n\treadonly sourceSha256: string;\n\treadonly activeLeafId: string;\n\treadonly messageCount: number;\n}\n\nexport interface CompactionSourceIdentityInput {\n\treadonly sessionId: string;\n\treadonly entryIds: readonly string[];\n\treadonly firstEntryId: string;\n\treadonly lastEntryId: string;\n\treadonly sourceSha256: string;\n\treadonly activeLeafId: string;\n\treadonly messageCount: number;\n}\n\nexport interface CompactionModelIdentity {\n\treadonly provider: string;\n\treadonly id: string;\n}\n\nexport interface CompactionModelHistoryEntry {\n\treadonly entryId: string;\n\treadonly provider: string;\n\treadonly modelId: string;\n}\n\nexport interface CompactionPreservedProvenance {\n\treadonly latestIntent: string;\n\treadonly openTasks: readonly string[];\n\treadonly laneIds: readonly string[];\n\treadonly acceptancePredicateIds: readonly string[];\n\treadonly evidenceReceiptIds: readonly string[];\n\treadonly blockerReasons: readonly string[];\n\treadonly repairEventIds: readonly string[];\n\treadonly branch: string | null;\n\treadonly worktree: string | null;\n\treadonly modelHistory: readonly CompactionModelHistoryEntry[];\n\treadonly nextAction: string;\n}\n\nexport interface CompactionPreservedProvenanceInput {\n\treadonly latestIntent: string;\n\treadonly openTasks: readonly string[];\n\treadonly laneIds: readonly string[];\n\treadonly acceptancePredicateIds: readonly string[];\n\treadonly evidenceReceiptIds: readonly string[];\n\treadonly blockerReasons: readonly string[];\n\treadonly repairEventIds: readonly string[];\n\treadonly branch: string | null;\n\treadonly worktree: string | null;\n\treadonly modelHistory: readonly CompactionModelHistoryEntry[];\n\treadonly nextAction: string;\n}\n\nexport interface CompactionTransaction {\n\treadonly schemaVersion: typeof COMPACTION_TRANSACTION_SCHEMA_VERSION;\n\treadonly transactionId: string;\n\treadonly baseRevision: SessionRevisionToken;\n\treadonly source: CompactionSourceIdentity;\n\treadonly createdAt: string;\n\treadonly model: CompactionModelIdentity;\n\treadonly preserved: CompactionPreservedProvenance;\n}\n\nexport interface CompactionTransactionInput {\n\treadonly schemaVersion?: typeof COMPACTION_TRANSACTION_SCHEMA_VERSION;\n\treadonly transactionId: string;\n\treadonly baseRevision: SessionRevisionTokenInput;\n\treadonly source: CompactionSourceIdentityInput;\n\treadonly createdAt: string;\n\treadonly model: CompactionModelIdentity;\n\treadonly preserved: CompactionPreservedProvenanceInput;\n}\n\nexport type CompactionBarrierStatus = \"ready\" | \"defer\" | \"fail_closed\";\nexport type CompactionBarrierReason =\n\t| \"closed_active_branch\"\n\t| \"pending_tool_calls\"\n\t| \"missing_active_tail_results\"\n\t| \"invalid_pending_tool_ids\"\n\t| \"inconsistent_integrity_report\"\n\t| \"structural_integrity_failure\"\n\t| \"unsafe_missing_tool_results\";\n\nexport interface CompactionBarrierResult {\n\treadonly status: CompactionBarrierStatus;\n\treadonly reason: CompactionBarrierReason;\n\treadonly pendingToolCallIds: readonly string[];\n\treadonly missingToolCallIds: readonly string[];\n}\n\nexport type CompactionCommitDecision =\n\t| {\n\t\t\treadonly decision: \"commit\";\n\t\t\treadonly reason: \"exact_match\";\n\t\t\treadonly transactionId: string;\n\t\t\treadonly revision: SessionRevisionToken;\n\t\t\treadonly source: CompactionSourceIdentity;\n\t }\n\t| {\n\t\t\treadonly decision: \"stale\";\n\t\t\treadonly reason: \"revision_mismatch\" | \"source_mismatch\";\n\t\t\treadonly transactionId: string;\n\t }\n\t| {\n\t\t\treadonly decision: \"duplicate\";\n\t\t\treadonly reason: \"source_already_committed\";\n\t\t\treadonly transactionId: string;\n\t }\n\t| {\n\t\t\treadonly decision: \"defer\";\n\t\t\treadonly reason: \"barrier_defer\";\n\t\t\treadonly transactionId: string;\n\t\t\treadonly barrierReason: CompactionBarrierReason;\n\t }\n\t| {\n\t\t\treadonly decision: \"fail_closed\";\n\t\t\treadonly reason: \"barrier_fail_closed\" | \"invalid_transaction\" | \"invalid_commit_input\";\n\t\t\treadonly transactionId?: string;\n\t\t\treadonly barrierReason?: CompactionBarrierReason;\n\t };\n\nexport interface DecideCompactionCommitInput {\n\treadonly transaction: CompactionTransaction;\n\treadonly currentRevision: SessionRevisionToken;\n\treadonly currentSource: CompactionSourceIdentity;\n\treadonly barrier: CompactionBarrierResult;\n\treadonly priorCommittedSourceDigests: readonly string[];\n}\n\nexport interface CompactionEnvelope {\n\treadonly schemaVersion: typeof COMPACTION_ENVELOPE_SCHEMA_VERSION;\n\treadonly transactionId: string;\n\treadonly baseRevision: SessionRevisionToken;\n\treadonly source: CompactionSourceIdentity;\n\treadonly createdAt: string;\n\treadonly model: CompactionModelIdentity;\n\treadonly summary: string;\n\treadonly summarySha256: string;\n\treadonly preserved: CompactionPreservedProvenance;\n}\n\nexport interface CreateCompactionEnvelopeInput {\n\treadonly transaction: CompactionTransaction;\n\treadonly decision: CompactionCommitDecision;\n\treadonly summary: string;\n\t/** Caller-supplied lowercase 64-hex SHA-256 digest of `summary`. OMK does not compute or verify the digest here; the caller is responsible for computing and binding it. */\n\treadonly summarySha256: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction assertOnlyKeys(value: Record<string, unknown>, allowed: readonly string[], field: string): void {\n\tconst allowedKeys = new Set(allowed);\n\tif (Object.keys(value).some((key) => !allowedKeys.has(key))) {\n\t\tthrow new TypeError(`${field} contains unsupported metadata`);\n\t}\n}\n\nfunction assertSafeInteger(value: unknown, field: string): asserts value is number {\n\tif (!Number.isSafeInteger(value) || (value as number) < 0) {\n\t\tthrow new TypeError(`${field} must be a non-negative safe integer`);\n\t}\n}\n\nfunction assertMetadataText(value: unknown, field: string, maxLength = MAX_METADATA_LENGTH): asserts value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tMETADATA_CONTROL_PATTERN.test(value)\n\t) {\n\t\tthrow new TypeError(`${field} must be non-empty bounded metadata without control characters`);\n\t}\n\tif (containsCredentialShape(value)) {\n\t\tthrow new TypeError(`${field} must not contain credential-shaped metadata`);\n\t}\n}\n\nfunction assertContentText(value: unknown, field: string, maxLength: number): asserts value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tCONTENT_CONTROL_PATTERN.test(value)\n\t) {\n\t\tthrow new TypeError(`${field} must be non-empty bounded text without unsafe control characters`);\n\t}\n\tif (containsCredentialShape(value)) {\n\t\tthrow new TypeError(`${field} must not contain credential-shaped content`);\n\t}\n}\n\nfunction assertSha256(value: unknown, field: string): asserts value is string {\n\tif (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n\t\tthrow new TypeError(`${field} must be a lowercase 64-hex SHA-256 digest`);\n\t}\n}\n\nfunction assertCanonicalTimestamp(value: unknown): asserts value is string {\n\tassertMetadataText(value, \"createdAt\");\n\tif (!CANONICAL_TIMESTAMP_PATTERN.test(value)) {\n\t\tthrow new TypeError(\"createdAt must be a canonical UTC ISO-8601 timestamp\");\n\t}\n\tconst parsed = new Date(value);\n\tif (!Number.isFinite(parsed.valueOf()) || parsed.toISOString() !== value) {\n\t\tthrow new TypeError(\"createdAt must be a canonical UTC ISO-8601 timestamp\");\n\t}\n}\n\nfunction copyFileIdentity(value: unknown): SessionFileIdentity | undefined {\n\tif (value === undefined) return undefined;\n\tif (!isRecord(value)) throw new TypeError(\"fileIdentity must be an object\");\n\tassertOnlyKeys(value, [\"dev\", \"ino\"], \"fileIdentity\");\n\tfor (const field of [\"dev\", \"ino\"] as const) {\n\t\tconst part = value[field];\n\t\tif (\n\t\t\ttypeof part !== \"string\" ||\n\t\t\tpart.length === 0 ||\n\t\t\tpart.length > MAX_FILE_IDENTITY_LENGTH ||\n\t\t\t!DECIMAL_STRING_PATTERN.test(part)\n\t\t) {\n\t\t\tthrow new TypeError(`fileIdentity.${field} must be a bounded decimal string`);\n\t\t}\n\t}\n\treturn Object.freeze({ dev: value.dev as string, ino: value.ino as string });\n}\n\nfunction copyIdArray(value: unknown, field: string, maxItems: number): readonly string[] {\n\tif (!Array.isArray(value) || value.length > maxItems) {\n\t\tthrow new TypeError(`${field} must be a bounded array`);\n\t}\n\tconst copy = value.map((item, index) => {\n\t\tassertMetadataText(item, `${field}[${index}]`);\n\t\treturn item;\n\t});\n\tif (new Set(copy).size !== copy.length) throw new TypeError(`${field} must contain unique IDs`);\n\treturn Object.freeze(copy);\n}\n\nfunction assertProvenanceText(value: unknown, field: string, maxLength: number): asserts value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tCONTENT_CONTROL_PATTERN.test(value)\n\t) {\n\t\tthrow new TypeError(`${field} must be non-empty bounded text without unsafe control characters`);\n\t}\n\tif (containsCredentialShape(value)) {\n\t\tthrow new TypeError(`${field} must not contain credential-shaped content`);\n\t}\n}\n\nfunction assertNullableMetadataText(\n\tvalue: unknown,\n\tfield: string,\n\tmaxLength = MAX_METADATA_LENGTH,\n): asserts value is string | null {\n\tif (value === null) return;\n\tassertMetadataText(value, field, maxLength);\n}\n\nfunction copyTextArray(\n\tvalue: unknown,\n\tfield: string,\n\tmaxItems: number,\n\tmaxLength: number,\n\trequireUnique: boolean,\n): readonly string[] {\n\tif (!Array.isArray(value) || value.length > maxItems) {\n\t\tthrow new TypeError(`${field} must be a bounded array`);\n\t}\n\tconst copy = value.map((item, index) => {\n\t\tassertProvenanceText(item, `${field}[${index}]`, maxLength);\n\t\treturn item;\n\t});\n\tif (requireUnique && new Set(copy).size !== copy.length) {\n\t\tthrow new TypeError(`${field} must contain unique entries`);\n\t}\n\treturn Object.freeze(copy);\n}\n\nfunction copyModelHistory(value: unknown): readonly CompactionModelHistoryEntry[] {\n\tif (!Array.isArray(value) || value.length > MAX_MODEL_HISTORY_ENTRIES) {\n\t\tthrow new TypeError(\"preserved.modelHistory must be a bounded array\");\n\t}\n\tconst seenEntryIds = new Set<string>();\n\tconst copy = value.map((item, index) => {\n\t\tif (!isRecord(item)) throw new TypeError(`preserved.modelHistory[${index}] must be an object`);\n\t\tassertOnlyKeys(item, [\"entryId\", \"provider\", \"modelId\"], `preserved.modelHistory[${index}]`);\n\t\tassertMetadataText(item.entryId, `preserved.modelHistory[${index}].entryId`);\n\t\tassertMetadataText(item.provider, `preserved.modelHistory[${index}].provider`);\n\t\tassertMetadataText(item.modelId, `preserved.modelHistory[${index}].modelId`);\n\t\tconst entryId = item.entryId as string;\n\t\tif (seenEntryIds.has(entryId)) throw new TypeError(\"preserved.modelHistory must contain unique entryId values\");\n\t\tseenEntryIds.add(entryId);\n\t\treturn Object.freeze({ entryId, provider: item.provider as string, modelId: item.modelId as string });\n\t});\n\treturn Object.freeze(copy);\n}\n\nfunction copyPreservedProvenance(input: unknown): CompactionPreservedProvenance {\n\tif (!isRecord(input)) throw new TypeError(\"preserved must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\n\t\t\t\"latestIntent\",\n\t\t\t\"openTasks\",\n\t\t\t\"laneIds\",\n\t\t\t\"acceptancePredicateIds\",\n\t\t\t\"evidenceReceiptIds\",\n\t\t\t\"blockerReasons\",\n\t\t\t\"repairEventIds\",\n\t\t\t\"branch\",\n\t\t\t\"worktree\",\n\t\t\t\"modelHistory\",\n\t\t\t\"nextAction\",\n\t\t],\n\t\t\"preserved\",\n\t);\n\tassertProvenanceText(input.latestIntent, \"preserved.latestIntent\", MAX_LATEST_INTENT_LENGTH);\n\tconst openTasks = copyTextArray(\n\t\tinput.openTasks,\n\t\t\"preserved.openTasks\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_PROVENANCE_TEXT_LENGTH,\n\t\tfalse,\n\t);\n\tconst laneIds = copyTextArray(input.laneIds, \"preserved.laneIds\", MAX_PROVENANCE_IDS, MAX_METADATA_LENGTH, true);\n\tconst acceptancePredicateIds = copyTextArray(\n\t\tinput.acceptancePredicateIds,\n\t\t\"preserved.acceptancePredicateIds\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_METADATA_LENGTH,\n\t\ttrue,\n\t);\n\tconst evidenceReceiptIds = copyTextArray(\n\t\tinput.evidenceReceiptIds,\n\t\t\"preserved.evidenceReceiptIds\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_METADATA_LENGTH,\n\t\ttrue,\n\t);\n\tconst blockerReasons = copyTextArray(\n\t\tinput.blockerReasons,\n\t\t\"preserved.blockerReasons\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_PROVENANCE_TEXT_LENGTH,\n\t\tfalse,\n\t);\n\tconst repairEventIds = copyTextArray(\n\t\tinput.repairEventIds,\n\t\t\"preserved.repairEventIds\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_METADATA_LENGTH,\n\t\ttrue,\n\t);\n\tassertNullableMetadataText(input.branch, \"preserved.branch\", MAX_PROVENANCE_TEXT_LENGTH);\n\tassertNullableMetadataText(input.worktree, \"preserved.worktree\", MAX_PROVENANCE_TEXT_LENGTH);\n\tconst modelHistory = copyModelHistory(input.modelHistory);\n\tassertProvenanceText(input.nextAction, \"preserved.nextAction\", MAX_NEXT_ACTION_LENGTH);\n\treturn Object.freeze({\n\t\tlatestIntent: input.latestIntent,\n\t\topenTasks,\n\t\tlaneIds,\n\t\tacceptancePredicateIds,\n\t\tevidenceReceiptIds,\n\t\tblockerReasons,\n\t\trepairEventIds,\n\t\tbranch: input.branch,\n\t\tworktree: input.worktree,\n\t\tmodelHistory,\n\t\tnextAction: input.nextAction,\n\t});\n}\n\nexport function createSessionRevisionToken(input: unknown): SessionRevisionToken {\n\tif (!isRecord(input)) throw new TypeError(\"session revision token must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\n\t\t\t\"schemaVersion\",\n\t\t\t\"sessionId\",\n\t\t\t\"completeBytes\",\n\t\t\t\"recordCount\",\n\t\t\t\"leafId\",\n\t\t\t\"lastEntryId\",\n\t\t\t\"completePrefixSha256\",\n\t\t\t\"fileIdentity\",\n\t\t],\n\t\t\"session revision token\",\n\t);\n\tif (input.schemaVersion !== undefined && input.schemaVersion !== SESSION_REVISION_TOKEN_SCHEMA_VERSION) {\n\t\tthrow new TypeError(\"unsupported session revision token schema version\");\n\t}\n\tassertMetadataText(input.sessionId, \"sessionId\");\n\tassertSafeInteger(input.completeBytes, \"completeBytes\");\n\tassertSafeInteger(input.recordCount, \"recordCount\");\n\tif (input.leafId !== null) assertMetadataText(input.leafId, \"leafId\");\n\tif (input.lastEntryId !== null) assertMetadataText(input.lastEntryId, \"lastEntryId\");\n\tassertSha256(input.completePrefixSha256, \"completePrefixSha256\");\n\n\tif ((input.completeBytes === 0) !== (input.recordCount === 0)) {\n\t\tthrow new TypeError(\"completeBytes and recordCount must both be empty or both be non-empty\");\n\t}\n\tif (input.recordCount === 0 && (input.leafId !== null || input.lastEntryId !== null)) {\n\t\tthrow new TypeError(\"an empty revision cannot identify entries\");\n\t}\n\tif (input.leafId !== null && input.lastEntryId === null) {\n\t\tthrow new TypeError(\"leafId requires a lastEntryId\");\n\t}\n\tif (input.completeBytes === 0 && input.completePrefixSha256 !== EMPTY_SHA256) {\n\t\tthrow new TypeError(\"an empty revision must use the SHA-256 digest of empty bytes\");\n\t}\n\n\tconst fileIdentity = copyFileIdentity(input.fileIdentity);\n\treturn Object.freeze({\n\t\tschemaVersion: SESSION_REVISION_TOKEN_SCHEMA_VERSION,\n\t\tsessionId: input.sessionId,\n\t\tcompleteBytes: input.completeBytes,\n\t\trecordCount: input.recordCount,\n\t\tleafId: input.leafId,\n\t\tlastEntryId: input.lastEntryId,\n\t\tcompletePrefixSha256: input.completePrefixSha256,\n\t\t...(fileIdentity === undefined ? {} : { fileIdentity }),\n\t});\n}\n\nexport function createCompactionSourceIdentity(input: unknown): CompactionSourceIdentity {\n\tif (!isRecord(input)) throw new TypeError(\"compaction source identity must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\"sessionId\", \"entryIds\", \"firstEntryId\", \"lastEntryId\", \"sourceSha256\", \"activeLeafId\", \"messageCount\"],\n\t\t\"compaction source identity\",\n\t);\n\tassertMetadataText(input.sessionId, \"source.sessionId\");\n\tconst entryIds = copyIdArray(input.entryIds, \"source.entryIds\", MAX_SOURCE_ENTRIES);\n\tif (entryIds.length === 0) throw new TypeError(\"source.entryIds must be non-empty\");\n\tassertMetadataText(input.firstEntryId, \"source.firstEntryId\");\n\tassertMetadataText(input.lastEntryId, \"source.lastEntryId\");\n\tassertMetadataText(input.activeLeafId, \"source.activeLeafId\");\n\tassertSha256(input.sourceSha256, \"source.sourceSha256\");\n\tassertSafeInteger(input.messageCount, \"source.messageCount\");\n\tif (input.messageCount > entryIds.length) {\n\t\tthrow new TypeError(\"source.messageCount cannot exceed source.entryIds length\");\n\t}\n\tif (input.firstEntryId !== entryIds[0] || input.lastEntryId !== entryIds.at(-1)) {\n\t\tthrow new TypeError(\"source first/last IDs must match the ordered entry IDs\");\n\t}\n\t// R30 P2: active leaf must be the last entry in the source range\n\tif (input.activeLeafId !== input.lastEntryId) {\n\t\tthrow new TypeError(\"source.activeLeafId must match source.lastEntryId\");\n\t}\n\treturn Object.freeze({\n\t\tsessionId: input.sessionId,\n\t\tentryIds,\n\t\tfirstEntryId: input.firstEntryId,\n\t\tlastEntryId: input.lastEntryId,\n\t\tsourceSha256: input.sourceSha256,\n\t\tactiveLeafId: input.activeLeafId,\n\t\tmessageCount: input.messageCount,\n\t});\n}\n\nfunction copyModelIdentity(value: unknown): CompactionModelIdentity {\n\tif (!isRecord(value)) throw new TypeError(\"model must be an object\");\n\tassertOnlyKeys(value, [\"provider\", \"id\"], \"model\");\n\tassertMetadataText(value.provider, \"model.provider\");\n\tassertMetadataText(value.id, \"model.id\");\n\treturn Object.freeze({ provider: value.provider, id: value.id });\n}\n\nexport function createCompactionTransaction(input: CompactionTransactionInput): CompactionTransaction {\n\tif (!isRecord(input)) throw new TypeError(\"compaction transaction must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\"schemaVersion\", \"transactionId\", \"baseRevision\", \"source\", \"createdAt\", \"model\", \"preserved\"],\n\t\t\"compaction transaction\",\n\t);\n\tif (input.schemaVersion !== undefined && input.schemaVersion !== COMPACTION_TRANSACTION_SCHEMA_VERSION) {\n\t\tthrow new TypeError(\"unsupported compaction transaction schema version\");\n\t}\n\tassertMetadataText(input.transactionId, \"transactionId\");\n\tassertCanonicalTimestamp(input.createdAt);\n\tconst baseRevision = createSessionRevisionToken(input.baseRevision);\n\tconst source = createCompactionSourceIdentity(input.source);\n\tif (baseRevision.sessionId !== source.sessionId || baseRevision.leafId !== source.activeLeafId) {\n\t\tthrow new TypeError(\"transaction revision and source must identify the same session and active leaf\");\n\t}\n\tconst model = copyModelIdentity(input.model);\n\tconst preserved = copyPreservedProvenance(input.preserved);\n\treturn Object.freeze({\n\t\tschemaVersion: COMPACTION_TRANSACTION_SCHEMA_VERSION,\n\t\ttransactionId: input.transactionId,\n\t\tbaseRevision,\n\t\tsource,\n\t\tcreatedAt: input.createdAt,\n\t\tmodel,\n\t\tpreserved,\n\t});\n}\n\nconst KNOWN_FINDING_REASONS = new Set<SessionIntegrityReasonCode>([\n\t\"trailing_fragment\",\n\t\"invalid_utf8\",\n\t\"malformed_json\",\n\t\"missing_header\",\n\t\"invalid_header\",\n\t\"unsupported_header\",\n\t\"multiple_header\",\n\t\"late_header\",\n\t\"invalid_entry\",\n\t\"unsupported_entry\",\n\t\"duplicate_entry_id\",\n\t\"missing_parent\",\n\t\"self_cycle\",\n\t\"parent_cycle\",\n\t\"active_leaf_missing\",\n\t\"compaction_first_kept_not_ancestor\",\n\t\"active_branch_context_invalid\",\n\t\"transcript_missing_result\",\n\t\"transcript_duplicate_result\",\n\t\"transcript_orphan_result\",\n\t\"transcript_duplicate_call_id\",\n\t\"transcript_interleaved_non_result\",\n]);\nconst TRANSCRIPT_FINDING_REASONS = new Set<SessionIntegrityReasonCode>([\n\t\"transcript_missing_result\",\n\t\"transcript_duplicate_result\",\n\t\"transcript_orphan_result\",\n\t\"transcript_duplicate_call_id\",\n\t\"transcript_interleaved_non_result\",\n]);\nconst HEADER_FINDING_REASONS = new Set<SessionIntegrityReasonCode>([\n\t\"missing_header\",\n\t\"invalid_header\",\n\t\"unsupported_header\",\n\t\"multiple_header\",\n\t\"late_header\",\n]);\nconst TRANSCRIPT_ISSUE_KINDS = new Set<string>([\n\t\"missing_result\",\n\t\"duplicate_result\",\n\t\"orphan_result\",\n\t\"duplicate_call_id\",\n\t\"interleaved_non_result\",\n]);\n\nfunction messageToolCalls(message: SessionIntegrityReport[\"activeMessages\"][number]): readonly {\n\treadonly id: string;\n\treadonly name: string;\n}[] {\n\tif (message.role !== \"assistant\") return [];\n\treturn message.content.flatMap((block) => (block.type === \"toolCall\" ? [{ id: block.id, name: block.name }] : []));\n}\n\nfunction transcriptFindingReason(issue: TranscriptIntegrityIssue): SessionIntegrityReasonCode {\n\tswitch (issue.kind) {\n\t\tcase \"missing_result\":\n\t\t\treturn \"transcript_missing_result\";\n\t\tcase \"duplicate_result\":\n\t\t\treturn \"transcript_duplicate_result\";\n\t\tcase \"orphan_result\":\n\t\t\treturn \"transcript_orphan_result\";\n\t\tcase \"duplicate_call_id\":\n\t\t\treturn \"transcript_duplicate_call_id\";\n\t\tcase \"interleaved_non_result\":\n\t\t\treturn \"transcript_interleaved_non_result\";\n\t}\n}\n\nfunction issueIdentity(issue: {\n\treadonly kind: string;\n\treadonly toolCallId: string;\n\treadonly toolName?: string;\n}): string {\n\treturn JSON.stringify([issue.kind, issue.toolCallId, issue.toolName ?? null]);\n}\n\nfunction findingIdentity(finding: SessionIntegrityFinding): string {\n\treturn JSON.stringify([\n\t\tfinding.reason,\n\t\tfinding.line ?? null,\n\t\tfinding.entryId ?? null,\n\t\tfinding.parentId ?? null,\n\t\tfinding.cycleEntryIds ?? null,\n\t\tfinding.toolCallId ?? null,\n\t\tfinding.toolName ?? null,\n\t]);\n}\n\nfunction sameMultiset(left: readonly string[], right: readonly string[]): boolean {\n\tif (left.length !== right.length) return false;\n\tconst counts = new Map<string, number>();\n\tfor (const item of left) counts.set(item, (counts.get(item) ?? 0) + 1);\n\tfor (const item of right) {\n\t\tconst count = counts.get(item);\n\t\tif (count === undefined) return false;\n\t\tif (count === 1) counts.delete(item);\n\t\telse counts.set(item, count - 1);\n\t}\n\treturn counts.size === 0;\n}\n\nfunction validByteDigest(value: unknown, completePrefix: boolean): boolean {\n\tif (!isRecord(value)) return false;\n\tconst keys = completePrefix ? [\"byteCount\", \"sha256\", \"lineCount\"] : [\"byteCount\", \"sha256\"];\n\tif (Object.keys(value).some((key) => !keys.includes(key))) return false;\n\tif (!Number.isSafeInteger(value.byteCount) || (value.byteCount as number) < 0) return false;\n\tif (typeof value.sha256 !== \"string\" || !SHA256_PATTERN.test(value.sha256)) return false;\n\tif (!completePrefix) return true;\n\treturn Number.isSafeInteger(value.lineCount) && (value.lineCount as number) >= 0;\n}\n\nfunction validFinding(value: unknown): value is SessionIntegrityFinding {\n\tif (!isRecord(value) || typeof value.reason !== \"string\") return false;\n\tif (!KNOWN_FINDING_REASONS.has(value.reason as SessionIntegrityReasonCode)) return false;\n\tconst allowed = [\"reason\", \"line\", \"entryId\", \"parentId\", \"cycleEntryIds\", \"toolCallId\", \"toolName\"];\n\tif (Object.keys(value).some((key) => !allowed.includes(key))) return false;\n\tif (value.line !== undefined && (!Number.isSafeInteger(value.line) || (value.line as number) < 1)) return false;\n\tfor (const field of [\"entryId\", \"parentId\", \"toolCallId\", \"toolName\"] as const) {\n\t\tif (value[field] !== undefined && typeof value[field] !== \"string\") return false;\n\t}\n\treturn (\n\t\tvalue.cycleEntryIds === undefined ||\n\t\t(Array.isArray(value.cycleEntryIds) && value.cycleEntryIds.every((item) => typeof item === \"string\"))\n\t);\n}\n\nfunction validTranscriptIssue(value: unknown): value is TranscriptIntegrityIssue {\n\tif (!isRecord(value) || !TRANSCRIPT_ISSUE_KINDS.has(value.kind as string)) return false;\n\tif (typeof value.toolCallId !== \"string\" || value.toolCallId.length === 0) return false;\n\tif (value.toolName !== undefined && typeof value.toolName !== \"string\") return false;\n\treturn Object.keys(value).every((key) => [\"kind\", \"toolCallId\", \"toolName\"].includes(key));\n}\n\nfunction activeBranchIsConsistent(report: SessionIntegrityReport): boolean {\n\tif (!Array.isArray(report.entries) || !Array.isArray(report.activeBranch) || !Array.isArray(report.activeMessages)) {\n\t\treturn false;\n\t}\n\tconst entryIds = new Set<string>();\n\tfor (const entry of report.entries) {\n\t\tif (!isRecord(entry) || typeof entry.id !== \"string\" || entry.id.length === 0) return false;\n\t\tentryIds.add(entry.id);\n\t}\n\tif (report.activeLeafId === null) return report.activeBranch.length === 0;\n\tif (typeof report.activeLeafId !== \"string\" || report.activeBranch.length === 0) return false;\n\tconst branchIds = new Set<string>();\n\tfor (let index = 0; index < report.activeBranch.length; index++) {\n\t\tconst entry = report.activeBranch[index];\n\t\tif (!isRecord(entry) || typeof entry.id !== \"string\" || branchIds.has(entry.id) || !entryIds.has(entry.id)) {\n\t\t\treturn false;\n\t\t}\n\t\tbranchIds.add(entry.id);\n\t\tconst expectedParent = index === 0 ? null : report.activeBranch[index - 1]?.id;\n\t\tif (entry.parentId !== expectedParent) return false;\n\t}\n\treturn report.activeBranch.at(-1)?.id === report.activeLeafId;\n}\n\nfunction reportIsConsistent(report: SessionIntegrityReport): boolean {\n\tif (!isRecord(report)) return false;\n\tif (!validByteDigest(report.source, false) || !validByteDigest(report.completePrefix, true)) return false;\n\tif (report.trailingFragment !== null && !validByteDigest(report.trailingFragment, false)) return false;\n\tconst trailingBytes = report.trailingFragment?.byteCount ?? 0;\n\tif (report.source.byteCount !== report.completePrefix.byteCount + trailingBytes) return false;\n\tif (report.completePrefix.lineCount > report.completePrefix.byteCount) return false;\n\tif (report.completePrefix.byteCount === 0 && report.completePrefix.sha256 !== EMPTY_SHA256) return false;\n\tif (report.trailingFragment === null && report.source.sha256 !== report.completePrefix.sha256) return false;\n\tif (!Array.isArray(report.findings) || !report.findings.every(validFinding)) return false;\n\tif (typeof report.ok !== \"boolean\" || report.ok !== (report.findings.length === 0)) return false;\n\n\tconst trailingFindings = report.findings.filter((finding) => finding.reason === \"trailing_fragment\");\n\tif (\n\t\ttrailingFindings.length !== (report.trailingFragment === null ? 0 : 1) ||\n\t\ttrailingFindings.some((finding) => Object.keys(finding).length !== 1)\n\t) {\n\t\treturn false;\n\t}\n\tif (report.header === null) {\n\t\tif (!report.findings.some((finding) => HEADER_FINDING_REASONS.has(finding.reason))) return false;\n\t} else if (!isRecord(report.header) || typeof report.header.id !== \"string\" || report.header.id.length === 0) {\n\t\treturn false;\n\t}\n\tif (!activeBranchIsConsistent(report)) return false;\n\n\tconst transcriptFindings = report.findings.filter((finding) => TRANSCRIPT_FINDING_REASONS.has(finding.reason));\n\tif (report.transcript === null) {\n\t\t// R30 P1-2: null transcript can never produce ready.\n\t\t// A producer-consistent null transcript requires activeMessages to be empty\n\t\t// and a structural finding to explain why no transcript was produced.\n\t\tif (report.activeMessages.length > 0) return false;\n\t\tif (transcriptFindings.length !== 0) return false;\n\t\tconst hasStructuralFinding = report.findings.some(\n\t\t\t(finding) => finding.reason !== \"trailing_fragment\" && !TRANSCRIPT_FINDING_REASONS.has(finding.reason),\n\t\t);\n\t\treturn hasStructuralFinding;\n\t}\n\tif (!isRecord(report.transcript) || !Array.isArray(report.transcript.issues)) return false;\n\tif (!report.transcript.issues.every(validTranscriptIssue)) return false;\n\tif (report.transcript.ok !== (report.transcript.issues.length === 0)) return false;\n\tif (\n\t\treport.findings.some(\n\t\t\t(finding) => finding.reason !== \"trailing_fragment\" && !TRANSCRIPT_FINDING_REASONS.has(finding.reason),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\n\tlet inspected: TranscriptIntegrityReport;\n\ttry {\n\t\tinspected = inspectTranscriptIntegrity(report.activeMessages);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (\n\t\tinspected.ok !== report.transcript.ok ||\n\t\t!sameMultiset(inspected.issues.map(issueIdentity), report.transcript.issues.map(issueIdentity))\n\t) {\n\t\treturn false;\n\t}\n\treturn sameMultiset(\n\t\ttranscriptFindings.map(findingIdentity),\n\t\tinspected.issues.map((issue) =>\n\t\t\tJSON.stringify([\n\t\t\t\ttranscriptFindingReason(issue),\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tissue.toolCallId,\n\t\t\t\tissue.toolName ?? null,\n\t\t\t]),\n\t\t),\n\t);\n}\n\nfunction missingCallsAreAtActiveTail(report: SessionIntegrityReport, missingIds: ReadonlySet<string>): boolean {\n\tlet lastAssistantIndex = -1;\n\tfor (let index = report.activeMessages.length - 1; index >= 0; index--) {\n\t\tif (report.activeMessages[index]?.role === \"assistant\") {\n\t\t\tlastAssistantIndex = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (lastAssistantIndex === -1) return false;\n\tconst assistant = report.activeMessages[lastAssistantIndex];\n\tif (!assistant || assistant.role !== \"assistant\") return false;\n\tconst tailCallIds = new Set(messageToolCalls(assistant).map((call) => call.id));\n\tif ([...missingIds].some((id) => !tailCallIds.has(id))) return false;\n\tfor (let index = lastAssistantIndex + 1; index < report.activeMessages.length; index++) {\n\t\tconst message = report.activeMessages[index];\n\t\tif (!message || message.role !== \"toolResult\" || !tailCallIds.has(message.toolCallId)) return false;\n\t}\n\treturn true;\n}\n\nfunction barrierResult(\n\tstatus: CompactionBarrierStatus,\n\treason: CompactionBarrierReason,\n\tpendingToolCallIds: readonly string[],\n\tmissingToolCallIds: readonly string[] = [],\n): CompactionBarrierResult {\n\treturn Object.freeze({\n\t\tstatus,\n\t\treason,\n\t\tpendingToolCallIds: Object.freeze([...pendingToolCallIds]),\n\t\tmissingToolCallIds: Object.freeze([...missingToolCallIds]),\n\t});\n}\n\n/** Derive a closed-turn compaction barrier without repairing or mutating the report. */\nexport function evaluateCompactionBarrier(\n\treport: SessionIntegrityReport,\n\tpendingToolCallIds: readonly string[],\n): CompactionBarrierResult {\n\tlet pending: readonly string[];\n\ttry {\n\t\tpending = copyIdArray(pendingToolCallIds, \"pendingToolCallIds\", MAX_PROVENANCE_IDS);\n\t} catch {\n\t\treturn barrierResult(\"fail_closed\", \"invalid_pending_tool_ids\", []);\n\t}\n\tif (!reportIsConsistent(report)) {\n\t\treturn barrierResult(\"fail_closed\", \"inconsistent_integrity_report\", pending);\n\t}\n\tconst blockingFinding = report.findings.find((finding) => finding.reason !== \"transcript_missing_result\");\n\tconst blockingIssue = report.transcript?.issues.find((issue) => issue.kind !== \"missing_result\");\n\tif (blockingFinding || blockingIssue) {\n\t\treturn barrierResult(\"fail_closed\", \"structural_integrity_failure\", pending);\n\t}\n\n\tconst missing = Object.freeze(\n\t\t(report.transcript?.issues ?? [])\n\t\t\t.filter((issue) => issue.kind === \"missing_result\")\n\t\t\t.map((issue) => issue.toolCallId),\n\t);\n\tconst missingSet = new Set(missing);\n\tconst pendingSet = new Set(pending);\n\tif (\n\t\tmissing.length > 0 &&\n\t\t(!missingCallsAreAtActiveTail(report, missingSet) || missing.some((toolCallId) => !pendingSet.has(toolCallId)))\n\t) {\n\t\treturn barrierResult(\"fail_closed\", \"unsafe_missing_tool_results\", pending, missing);\n\t}\n\tif (missing.length > 0) return barrierResult(\"defer\", \"missing_active_tail_results\", pending, missing);\n\tif (pending.length > 0) return barrierResult(\"defer\", \"pending_tool_calls\", pending);\n\treturn barrierResult(\"ready\", \"closed_active_branch\", []);\n}\n\nfunction sameRevision(left: SessionRevisionToken, right: SessionRevisionToken): boolean {\n\treturn (\n\t\tleft.schemaVersion === right.schemaVersion &&\n\t\tleft.sessionId === right.sessionId &&\n\t\tleft.completeBytes === right.completeBytes &&\n\t\tleft.recordCount === right.recordCount &&\n\t\tleft.leafId === right.leafId &&\n\t\tleft.lastEntryId === right.lastEntryId &&\n\t\tleft.completePrefixSha256 === right.completePrefixSha256 &&\n\t\tleft.fileIdentity?.dev === right.fileIdentity?.dev &&\n\t\tleft.fileIdentity?.ino === right.fileIdentity?.ino\n\t);\n}\n\nfunction sameSource(left: CompactionSourceIdentity, right: CompactionSourceIdentity): boolean {\n\treturn (\n\t\tleft.sessionId === right.sessionId &&\n\t\tleft.firstEntryId === right.firstEntryId &&\n\t\tleft.lastEntryId === right.lastEntryId &&\n\t\tleft.sourceSha256 === right.sourceSha256 &&\n\t\tleft.activeLeafId === right.activeLeafId &&\n\t\tleft.messageCount === right.messageCount &&\n\t\tleft.entryIds.length === right.entryIds.length &&\n\t\tleft.entryIds.every((id, index) => id === right.entryIds[index])\n\t);\n}\n\nfunction validBarrierResult(barrier: CompactionBarrierResult): boolean {\n\tif (!isRecord(barrier) || !Array.isArray(barrier.pendingToolCallIds) || !Array.isArray(barrier.missingToolCallIds)) {\n\t\treturn false;\n\t}\n\tconst pending = barrier.pendingToolCallIds;\n\tconst missing = barrier.missingToolCallIds;\n\t// R30 P1-3: validate all IDs are bounded, unique, safe metadata text\n\ttry {\n\t\tfor (const ids of [pending, missing]) {\n\t\t\tif (ids.length > MAX_PROVENANCE_IDS) return false;\n\t\t\tif (new Set(ids).size !== ids.length) return false;\n\t\t\tfor (const id of ids) assertMetadataText(id, \"barrier toolCallId\");\n\t\t}\n\t} catch {\n\t\treturn false;\n\t}\n\tswitch (barrier.status) {\n\t\tcase \"ready\":\n\t\t\treturn barrier.reason === \"closed_active_branch\" && pending.length === 0 && missing.length === 0;\n\t\tcase \"defer\":\n\t\t\tif (barrier.reason === \"pending_tool_calls\") {\n\t\t\t\treturn pending.length > 0 && missing.length === 0;\n\t\t\t}\n\t\t\tif (barrier.reason === \"missing_active_tail_results\") {\n\t\t\t\treturn missing.length > 0 && missing.every((id) => pending.includes(id));\n\t\t\t}\n\t\t\treturn false;\n\t\tcase \"fail_closed\":\n\t\t\treturn (\n\t\t\t\tbarrier.reason === \"invalid_pending_tool_ids\" ||\n\t\t\t\tbarrier.reason === \"inconsistent_integrity_report\" ||\n\t\t\t\tbarrier.reason === \"structural_integrity_failure\" ||\n\t\t\t\tbarrier.reason === \"unsafe_missing_tool_results\"\n\t\t\t);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/**\n * Authorize an in-memory commit attempt. A \"commit\" decision is not evidence of\n * durable persistence; the integration layer must still perform its own atomic CAS write.\n */\nexport function decideCompactionCommit(input: DecideCompactionCommitInput): CompactionCommitDecision {\n\tlet transaction: CompactionTransaction;\n\ttry {\n\t\ttransaction = createCompactionTransaction(input.transaction);\n\t} catch {\n\t\treturn Object.freeze({ decision: \"fail_closed\", reason: \"invalid_transaction\" });\n\t}\n\tif (!validBarrierResult(input.barrier)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"fail_closed\",\n\t\t\treason: \"invalid_commit_input\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\tif (input.barrier.status === \"fail_closed\") {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"fail_closed\",\n\t\t\treason: \"barrier_fail_closed\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t\tbarrierReason: input.barrier.reason,\n\t\t});\n\t}\n\tif (input.barrier.status === \"defer\") {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"defer\",\n\t\t\treason: \"barrier_defer\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t\tbarrierReason: input.barrier.reason,\n\t\t});\n\t}\n\n\tlet currentRevision: SessionRevisionToken;\n\tlet currentSource: CompactionSourceIdentity;\n\tlet priorDigests: readonly string[];\n\ttry {\n\t\tcurrentRevision = createSessionRevisionToken(input.currentRevision);\n\t\tcurrentSource = createCompactionSourceIdentity(input.currentSource);\n\t\tif (\n\t\t\t!Array.isArray(input.priorCommittedSourceDigests) ||\n\t\t\tinput.priorCommittedSourceDigests.length > MAX_SOURCE_ENTRIES\n\t\t) {\n\t\t\tthrow new TypeError(\"priorCommittedSourceDigests must be a bounded array\");\n\t\t}\n\t\tpriorDigests = input.priorCommittedSourceDigests.map((digest, index) => {\n\t\t\tassertSha256(digest, `priorCommittedSourceDigests[${index}]`);\n\t\t\treturn digest;\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"fail_closed\",\n\t\t\treason: \"invalid_commit_input\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\n\tif (priorDigests.includes(transaction.source.sourceSha256)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"duplicate\",\n\t\t\treason: \"source_already_committed\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\tif (!sameRevision(transaction.baseRevision, currentRevision)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"stale\",\n\t\t\treason: \"revision_mismatch\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\tif (!sameSource(transaction.source, currentSource)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"stale\",\n\t\t\treason: \"source_mismatch\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tdecision: \"commit\",\n\t\treason: \"exact_match\",\n\t\ttransactionId: transaction.transactionId,\n\t\trevision: currentRevision,\n\t\tsource: currentSource,\n\t});\n}\n\nconst COMPACTION_ENVELOPE_KEYS = [\n\t\"schemaVersion\",\n\t\"transactionId\",\n\t\"baseRevision\",\n\t\"source\",\n\t\"createdAt\",\n\t\"model\",\n\t\"summary\",\n\t\"summarySha256\",\n\t\"preserved\",\n] as const;\n\n/** Parse and deep-freeze a persisted schema-v2 compaction envelope. */\nexport function validateCompactionEnvelope(input: unknown): CompactionEnvelope {\n\tif (!isRecord(input)) throw new TypeError(\"compaction envelope must be an object\");\n\tassertOnlyKeys(input, COMPACTION_ENVELOPE_KEYS, \"compaction envelope\");\n\tif (input.schemaVersion !== COMPACTION_ENVELOPE_SCHEMA_VERSION) {\n\t\tthrow new TypeError(\"unsupported compaction envelope schema version\");\n\t}\n\tassertMetadataText(input.transactionId, \"transactionId\");\n\tassertCanonicalTimestamp(input.createdAt);\n\tassertContentText(input.summary, \"summary\", MAX_SUMMARY_LENGTH);\n\tassertSha256(input.summarySha256, \"summarySha256\");\n\tconst baseRevision = createSessionRevisionToken(input.baseRevision);\n\tconst source = createCompactionSourceIdentity(input.source);\n\tif (baseRevision.sessionId !== source.sessionId || baseRevision.leafId !== source.activeLeafId) {\n\t\tthrow new TypeError(\"envelope revision and source must identify the same session and active leaf\");\n\t}\n\treturn Object.freeze({\n\t\tschemaVersion: COMPACTION_ENVELOPE_SCHEMA_VERSION,\n\t\ttransactionId: input.transactionId,\n\t\tbaseRevision,\n\t\tsource,\n\t\tcreatedAt: input.createdAt,\n\t\tmodel: copyModelIdentity(input.model),\n\t\tsummary: input.summary,\n\t\tsummarySha256: input.summarySha256,\n\t\tpreserved: copyPreservedProvenance(input.preserved),\n\t});\n}\n\n/** Create provenance-bearing summary data only from an exact commit authorization. */\nexport function createCompactionEnvelope(input: CreateCompactionEnvelopeInput): CompactionEnvelope {\n\tif (!isRecord(input)) throw new TypeError(\"compaction envelope input must be an object\");\n\tassertOnlyKeys(input, [\"transaction\", \"decision\", \"summary\", \"summarySha256\"], \"compaction envelope input\");\n\tassertContentText(input.summary, \"summary\", MAX_SUMMARY_LENGTH);\n\tassertSha256(input.summarySha256, \"summarySha256\");\n\tif (input.decision.decision !== \"commit\" || input.decision.reason !== \"exact_match\") {\n\t\tthrow new TypeError(\"a commit decision is required to create a compaction envelope\");\n\t}\n\tconst transaction = createCompactionTransaction(input.transaction);\n\tconst decisionRevision = createSessionRevisionToken(input.decision.revision);\n\tconst decisionSource = createCompactionSourceIdentity(input.decision.source);\n\tif (\n\t\tinput.decision.transactionId !== transaction.transactionId ||\n\t\t!sameRevision(transaction.baseRevision, decisionRevision) ||\n\t\t!sameSource(transaction.source, decisionSource)\n\t) {\n\t\tthrow new TypeError(\"commit decision does not match the compaction transaction\");\n\t}\n\n\treturn validateCompactionEnvelope({\n\t\tschemaVersion: COMPACTION_ENVELOPE_SCHEMA_VERSION,\n\t\ttransactionId: transaction.transactionId,\n\t\tbaseRevision: transaction.baseRevision,\n\t\tsource: transaction.source,\n\t\tcreatedAt: transaction.createdAt,\n\t\tmodel: transaction.model,\n\t\tsummary: input.summary,\n\t\tsummarySha256: input.summarySha256,\n\t\tpreserved: transaction.preserved,\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transaction.d.ts","sourceRoot":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inspectTranscriptIntegrity } from \"omk-agent-core\";\nimport type {\n\tSessionIntegrityFinding,\n\tSessionIntegrityReasonCode,\n\tSessionIntegrityReport,\n} from \"../session-integrity.ts\";\n\nexport const SESSION_REVISION_TOKEN_SCHEMA_VERSION = 1 as const;\nexport const COMPACTION_TRANSACTION_SCHEMA_VERSION = 1 as const;\nexport const COMPACTION_ENVELOPE_SCHEMA_VERSION = 2 as const;\n\nconst MAX_METADATA_LENGTH = 256;\nconst MAX_FILE_IDENTITY_LENGTH = 32;\nconst MAX_SOURCE_ENTRIES = 4096;\nconst MAX_PROVENANCE_IDS = 1024;\nconst MAX_LATEST_INTENT_LENGTH = 16_384;\nconst MAX_SUMMARY_LENGTH = 262_144;\nconst MAX_PROVENANCE_TEXT_LENGTH = 4096;\nconst MAX_NEXT_ACTION_LENGTH = 4096;\nconst MAX_MODEL_HISTORY_ENTRIES = 256;\nconst EMPTY_SHA256 = \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\";\nconst SHA256_PATTERN = /^[a-f0-9]{64}$/u;\nconst DECIMAL_STRING_PATTERN = /^[0-9]+$/u;\nconst CANONICAL_TIMESTAMP_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/u;\nconst METADATA_CONTROL_PATTERN = /[\\u0000-\\u001f\\u007f]/u;\nconst CONTENT_CONTROL_PATTERN = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/u;\nconst CREDENTIAL_SHAPE_PATTERN =\n\t/-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:^|[\\s\"'`:])bearer\\s+[A-Za-z0-9._~+/-]{8,}|(?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|passwd|client[-_ ]?secret|secret[-_ ]?(?:key|token))\\s*[:=]\\s*[\"']?[^\\s\"',;]{3,}|(?<![A-Za-z0-9])(?:sk|ghp|gho|ghu|ghs|github_pat|xox[baprs])[-_][A-Za-z0-9_-]{8,}|(?<![A-Za-z0-9])AKIA[A-Z0-9]{16}(?![A-Z0-9])|(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}(?![A-Za-z0-9_-])|(?<![A-Za-z0-9_-])gAAAAA[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])|(?<![A-Za-z0-9])v2:[A-Za-z0-9_+/=-]{20,}/iu;\nconst REDACTED_ASSIGNMENT_PATTERN =\n\t/\\s*[:=]\\s*(?:\"\\[REDACTED\\]\"(?![A-Za-z0-9_+/-])|'\\[REDACTED\\]'(?![A-Za-z0-9_+/-])|\\[REDACTED\\](?![A-Za-z0-9._~+/-]))/giu;\nconst CREDENTIAL_SHAPE_MASK_PATTERN = new RegExp(CREDENTIAL_SHAPE_PATTERN.source, \"giu\");\n\nexport function containsCredentialShape(value: string): boolean {\n\treturn CREDENTIAL_SHAPE_PATTERN.test(value.replace(REDACTED_ASSIGNMENT_PATTERN, \"\"));\n}\n\n/**\n * Deterministically mask credential-shaped spans so sanitized text always\n * satisfies this module's fail-closed content validators. Producers (compaction\n * summaries, preserved provenance) must route generated text through this\n * before validation; otherwise a paranoid validator match would abort the\n * entire compaction and strand an overflowed session.\n */\nexport function redactCredentialShapedContent(value: string): string {\n\tlet result = value;\n\tfor (let pass = 0; pass < 8 && containsCredentialShape(result); pass += 1) {\n\t\tresult = result.replace(CREDENTIAL_SHAPE_MASK_PATTERN, \"[REDACTED]\");\n\t}\n\treturn containsCredentialShape(result) ? \"[REDACTED]\" : result;\n}\n\nexport interface SessionFileIdentity {\n\treadonly dev: string;\n\treadonly ino: string;\n}\n\nexport interface SessionRevisionToken {\n\treadonly schemaVersion: typeof SESSION_REVISION_TOKEN_SCHEMA_VERSION;\n\treadonly sessionId: string;\n\treadonly completeBytes: number;\n\treadonly recordCount: number;\n\treadonly leafId: string | null;\n\treadonly lastEntryId: string | null;\n\treadonly completePrefixSha256: string;\n\treadonly fileIdentity?: SessionFileIdentity;\n}\n\nexport interface SessionRevisionTokenInput {\n\treadonly schemaVersion?: typeof SESSION_REVISION_TOKEN_SCHEMA_VERSION;\n\treadonly sessionId: string;\n\treadonly completeBytes: number;\n\treadonly recordCount: number;\n\treadonly leafId: string | null;\n\treadonly lastEntryId: string | null;\n\treadonly completePrefixSha256: string;\n\treadonly fileIdentity?: SessionFileIdentity;\n}\n\nexport interface CompactionSourceIdentity {\n\treadonly sessionId: string;\n\treadonly entryIds: readonly string[];\n\treadonly firstEntryId: string;\n\treadonly lastEntryId: string;\n\treadonly sourceSha256: string;\n\treadonly activeLeafId: string;\n\treadonly messageCount: number;\n}\n\nexport interface CompactionSourceIdentityInput {\n\treadonly sessionId: string;\n\treadonly entryIds: readonly string[];\n\treadonly firstEntryId: string;\n\treadonly lastEntryId: string;\n\treadonly sourceSha256: string;\n\treadonly activeLeafId: string;\n\treadonly messageCount: number;\n}\n\nexport interface CompactionModelIdentity {\n\treadonly provider: string;\n\treadonly id: string;\n}\n\nexport interface CompactionModelHistoryEntry {\n\treadonly entryId: string;\n\treadonly provider: string;\n\treadonly modelId: string;\n}\n\nexport interface CompactionPreservedProvenance {\n\treadonly latestIntent: string;\n\treadonly openTasks: readonly string[];\n\treadonly laneIds: readonly string[];\n\treadonly acceptancePredicateIds: readonly string[];\n\treadonly evidenceReceiptIds: readonly string[];\n\treadonly blockerReasons: readonly string[];\n\treadonly repairEventIds: readonly string[];\n\treadonly branch: string | null;\n\treadonly worktree: string | null;\n\treadonly modelHistory: readonly CompactionModelHistoryEntry[];\n\treadonly nextAction: string;\n}\n\nexport interface CompactionPreservedProvenanceInput {\n\treadonly latestIntent: string;\n\treadonly openTasks: readonly string[];\n\treadonly laneIds: readonly string[];\n\treadonly acceptancePredicateIds: readonly string[];\n\treadonly evidenceReceiptIds: readonly string[];\n\treadonly blockerReasons: readonly string[];\n\treadonly repairEventIds: readonly string[];\n\treadonly branch: string | null;\n\treadonly worktree: string | null;\n\treadonly modelHistory: readonly CompactionModelHistoryEntry[];\n\treadonly nextAction: string;\n}\n\nexport interface CompactionTransaction {\n\treadonly schemaVersion: typeof COMPACTION_TRANSACTION_SCHEMA_VERSION;\n\treadonly transactionId: string;\n\treadonly baseRevision: SessionRevisionToken;\n\treadonly source: CompactionSourceIdentity;\n\treadonly createdAt: string;\n\treadonly model: CompactionModelIdentity;\n\treadonly preserved: CompactionPreservedProvenance;\n}\n\nexport interface CompactionTransactionInput {\n\treadonly schemaVersion?: typeof COMPACTION_TRANSACTION_SCHEMA_VERSION;\n\treadonly transactionId: string;\n\treadonly baseRevision: SessionRevisionTokenInput;\n\treadonly source: CompactionSourceIdentityInput;\n\treadonly createdAt: string;\n\treadonly model: CompactionModelIdentity;\n\treadonly preserved: CompactionPreservedProvenanceInput;\n}\n\nexport type CompactionBarrierStatus = \"ready\" | \"defer\" | \"fail_closed\";\nexport type CompactionBarrierReason =\n\t| \"closed_active_branch\"\n\t| \"pending_tool_calls\"\n\t| \"missing_active_tail_results\"\n\t| \"invalid_pending_tool_ids\"\n\t| \"inconsistent_integrity_report\"\n\t| \"structural_integrity_failure\"\n\t| \"unsafe_missing_tool_results\";\n\nexport interface CompactionBarrierResult {\n\treadonly status: CompactionBarrierStatus;\n\treadonly reason: CompactionBarrierReason;\n\treadonly pendingToolCallIds: readonly string[];\n\treadonly missingToolCallIds: readonly string[];\n}\n\nexport type CompactionCommitDecision =\n\t| {\n\t\t\treadonly decision: \"commit\";\n\t\t\treadonly reason: \"exact_match\";\n\t\t\treadonly transactionId: string;\n\t\t\treadonly revision: SessionRevisionToken;\n\t\t\treadonly source: CompactionSourceIdentity;\n\t }\n\t| {\n\t\t\treadonly decision: \"stale\";\n\t\t\treadonly reason: \"revision_mismatch\" | \"source_mismatch\";\n\t\t\treadonly transactionId: string;\n\t }\n\t| {\n\t\t\treadonly decision: \"duplicate\";\n\t\t\treadonly reason: \"source_already_committed\";\n\t\t\treadonly transactionId: string;\n\t }\n\t| {\n\t\t\treadonly decision: \"defer\";\n\t\t\treadonly reason: \"barrier_defer\";\n\t\t\treadonly transactionId: string;\n\t\t\treadonly barrierReason: CompactionBarrierReason;\n\t }\n\t| {\n\t\t\treadonly decision: \"fail_closed\";\n\t\t\treadonly reason: \"barrier_fail_closed\" | \"invalid_transaction\" | \"invalid_commit_input\";\n\t\t\treadonly transactionId?: string;\n\t\t\treadonly barrierReason?: CompactionBarrierReason;\n\t };\n\nexport interface DecideCompactionCommitInput {\n\treadonly transaction: CompactionTransaction;\n\treadonly currentRevision: SessionRevisionToken;\n\treadonly currentSource: CompactionSourceIdentity;\n\treadonly barrier: CompactionBarrierResult;\n\treadonly priorCommittedSourceDigests: readonly string[];\n}\n\nexport interface CompactionEnvelope {\n\treadonly schemaVersion: typeof COMPACTION_ENVELOPE_SCHEMA_VERSION;\n\treadonly transactionId: string;\n\treadonly baseRevision: SessionRevisionToken;\n\treadonly source: CompactionSourceIdentity;\n\treadonly createdAt: string;\n\treadonly model: CompactionModelIdentity;\n\treadonly summary: string;\n\treadonly summarySha256: string;\n\treadonly preserved: CompactionPreservedProvenance;\n}\n\nexport interface CreateCompactionEnvelopeInput {\n\treadonly transaction: CompactionTransaction;\n\treadonly decision: CompactionCommitDecision;\n\treadonly summary: string;\n\t/** Caller-supplied lowercase 64-hex SHA-256 digest of `summary`. OMK does not compute or verify the digest here; the caller is responsible for computing and binding it. */\n\treadonly summarySha256: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction assertOnlyKeys(value: Record<string, unknown>, allowed: readonly string[], field: string): void {\n\tconst allowedKeys = new Set(allowed);\n\tif (Object.keys(value).some((key) => !allowedKeys.has(key))) {\n\t\tthrow new TypeError(`${field} contains unsupported metadata`);\n\t}\n}\n\nfunction assertSafeInteger(value: unknown, field: string): asserts value is number {\n\tif (!Number.isSafeInteger(value) || (value as number) < 0) {\n\t\tthrow new TypeError(`${field} must be a non-negative safe integer`);\n\t}\n}\n\nfunction assertMetadataText(value: unknown, field: string, maxLength = MAX_METADATA_LENGTH): asserts value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tMETADATA_CONTROL_PATTERN.test(value)\n\t) {\n\t\tthrow new TypeError(`${field} must be non-empty bounded metadata without control characters`);\n\t}\n\tif (containsCredentialShape(value)) {\n\t\tthrow new TypeError(`${field} must not contain credential-shaped metadata`);\n\t}\n}\n\nfunction assertContentText(value: unknown, field: string, maxLength: number): asserts value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tCONTENT_CONTROL_PATTERN.test(value)\n\t) {\n\t\tthrow new TypeError(`${field} must be non-empty bounded text without unsafe control characters`);\n\t}\n\tif (containsCredentialShape(value)) {\n\t\tthrow new TypeError(`${field} must not contain credential-shaped content`);\n\t}\n}\n\nfunction assertSha256(value: unknown, field: string): asserts value is string {\n\tif (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n\t\tthrow new TypeError(`${field} must be a lowercase 64-hex SHA-256 digest`);\n\t}\n}\n\nfunction assertCanonicalTimestamp(value: unknown): asserts value is string {\n\tassertMetadataText(value, \"createdAt\");\n\tif (!CANONICAL_TIMESTAMP_PATTERN.test(value)) {\n\t\tthrow new TypeError(\"createdAt must be a canonical UTC ISO-8601 timestamp\");\n\t}\n\tconst parsed = new Date(value);\n\tif (!Number.isFinite(parsed.valueOf()) || parsed.toISOString() !== value) {\n\t\tthrow new TypeError(\"createdAt must be a canonical UTC ISO-8601 timestamp\");\n\t}\n}\n\nfunction copyFileIdentity(value: unknown): SessionFileIdentity | undefined {\n\tif (value === undefined) return undefined;\n\tif (!isRecord(value)) throw new TypeError(\"fileIdentity must be an object\");\n\tassertOnlyKeys(value, [\"dev\", \"ino\"], \"fileIdentity\");\n\tfor (const field of [\"dev\", \"ino\"] as const) {\n\t\tconst part = value[field];\n\t\tif (\n\t\t\ttypeof part !== \"string\" ||\n\t\t\tpart.length === 0 ||\n\t\t\tpart.length > MAX_FILE_IDENTITY_LENGTH ||\n\t\t\t!DECIMAL_STRING_PATTERN.test(part)\n\t\t) {\n\t\t\tthrow new TypeError(`fileIdentity.${field} must be a bounded decimal string`);\n\t\t}\n\t}\n\treturn Object.freeze({ dev: value.dev as string, ino: value.ino as string });\n}\n\nfunction copyIdArray(value: unknown, field: string, maxItems: number): readonly string[] {\n\tif (!Array.isArray(value) || value.length > maxItems) {\n\t\tthrow new TypeError(`${field} must be a bounded array`);\n\t}\n\tconst copy = value.map((item, index) => {\n\t\tassertMetadataText(item, `${field}[${index}]`);\n\t\treturn item;\n\t});\n\tif (new Set(copy).size !== copy.length) throw new TypeError(`${field} must contain unique IDs`);\n\treturn Object.freeze(copy);\n}\n\nfunction assertProvenanceText(value: unknown, field: string, maxLength: number): asserts value is string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > maxLength ||\n\t\tCONTENT_CONTROL_PATTERN.test(value)\n\t) {\n\t\tthrow new TypeError(`${field} must be non-empty bounded text without unsafe control characters`);\n\t}\n\tif (containsCredentialShape(value)) {\n\t\tthrow new TypeError(`${field} must not contain credential-shaped content`);\n\t}\n}\n\nfunction assertNullableMetadataText(\n\tvalue: unknown,\n\tfield: string,\n\tmaxLength = MAX_METADATA_LENGTH,\n): asserts value is string | null {\n\tif (value === null) return;\n\tassertMetadataText(value, field, maxLength);\n}\n\nfunction copyTextArray(\n\tvalue: unknown,\n\tfield: string,\n\tmaxItems: number,\n\tmaxLength: number,\n\trequireUnique: boolean,\n): readonly string[] {\n\tif (!Array.isArray(value) || value.length > maxItems) {\n\t\tthrow new TypeError(`${field} must be a bounded array`);\n\t}\n\tconst copy = value.map((item, index) => {\n\t\tassertProvenanceText(item, `${field}[${index}]`, maxLength);\n\t\treturn item;\n\t});\n\tif (requireUnique && new Set(copy).size !== copy.length) {\n\t\tthrow new TypeError(`${field} must contain unique entries`);\n\t}\n\treturn Object.freeze(copy);\n}\n\nfunction copyModelHistory(value: unknown): readonly CompactionModelHistoryEntry[] {\n\tif (!Array.isArray(value) || value.length > MAX_MODEL_HISTORY_ENTRIES) {\n\t\tthrow new TypeError(\"preserved.modelHistory must be a bounded array\");\n\t}\n\tconst seenEntryIds = new Set<string>();\n\tconst copy = value.map((item, index) => {\n\t\tif (!isRecord(item)) throw new TypeError(`preserved.modelHistory[${index}] must be an object`);\n\t\tassertOnlyKeys(item, [\"entryId\", \"provider\", \"modelId\"], `preserved.modelHistory[${index}]`);\n\t\tassertMetadataText(item.entryId, `preserved.modelHistory[${index}].entryId`);\n\t\tassertMetadataText(item.provider, `preserved.modelHistory[${index}].provider`);\n\t\tassertMetadataText(item.modelId, `preserved.modelHistory[${index}].modelId`);\n\t\tconst entryId = item.entryId as string;\n\t\tif (seenEntryIds.has(entryId)) throw new TypeError(\"preserved.modelHistory must contain unique entryId values\");\n\t\tseenEntryIds.add(entryId);\n\t\treturn Object.freeze({ entryId, provider: item.provider as string, modelId: item.modelId as string });\n\t});\n\treturn Object.freeze(copy);\n}\n\nfunction copyPreservedProvenance(input: unknown): CompactionPreservedProvenance {\n\tif (!isRecord(input)) throw new TypeError(\"preserved must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\n\t\t\t\"latestIntent\",\n\t\t\t\"openTasks\",\n\t\t\t\"laneIds\",\n\t\t\t\"acceptancePredicateIds\",\n\t\t\t\"evidenceReceiptIds\",\n\t\t\t\"blockerReasons\",\n\t\t\t\"repairEventIds\",\n\t\t\t\"branch\",\n\t\t\t\"worktree\",\n\t\t\t\"modelHistory\",\n\t\t\t\"nextAction\",\n\t\t],\n\t\t\"preserved\",\n\t);\n\tassertProvenanceText(input.latestIntent, \"preserved.latestIntent\", MAX_LATEST_INTENT_LENGTH);\n\tconst openTasks = copyTextArray(\n\t\tinput.openTasks,\n\t\t\"preserved.openTasks\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_PROVENANCE_TEXT_LENGTH,\n\t\tfalse,\n\t);\n\tconst laneIds = copyTextArray(input.laneIds, \"preserved.laneIds\", MAX_PROVENANCE_IDS, MAX_METADATA_LENGTH, true);\n\tconst acceptancePredicateIds = copyTextArray(\n\t\tinput.acceptancePredicateIds,\n\t\t\"preserved.acceptancePredicateIds\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_METADATA_LENGTH,\n\t\ttrue,\n\t);\n\tconst evidenceReceiptIds = copyTextArray(\n\t\tinput.evidenceReceiptIds,\n\t\t\"preserved.evidenceReceiptIds\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_METADATA_LENGTH,\n\t\ttrue,\n\t);\n\tconst blockerReasons = copyTextArray(\n\t\tinput.blockerReasons,\n\t\t\"preserved.blockerReasons\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_PROVENANCE_TEXT_LENGTH,\n\t\tfalse,\n\t);\n\tconst repairEventIds = copyTextArray(\n\t\tinput.repairEventIds,\n\t\t\"preserved.repairEventIds\",\n\t\tMAX_PROVENANCE_IDS,\n\t\tMAX_METADATA_LENGTH,\n\t\ttrue,\n\t);\n\tassertNullableMetadataText(input.branch, \"preserved.branch\", MAX_PROVENANCE_TEXT_LENGTH);\n\tassertNullableMetadataText(input.worktree, \"preserved.worktree\", MAX_PROVENANCE_TEXT_LENGTH);\n\tconst modelHistory = copyModelHistory(input.modelHistory);\n\tassertProvenanceText(input.nextAction, \"preserved.nextAction\", MAX_NEXT_ACTION_LENGTH);\n\treturn Object.freeze({\n\t\tlatestIntent: input.latestIntent,\n\t\topenTasks,\n\t\tlaneIds,\n\t\tacceptancePredicateIds,\n\t\tevidenceReceiptIds,\n\t\tblockerReasons,\n\t\trepairEventIds,\n\t\tbranch: input.branch,\n\t\tworktree: input.worktree,\n\t\tmodelHistory,\n\t\tnextAction: input.nextAction,\n\t});\n}\n\nexport function createSessionRevisionToken(input: unknown): SessionRevisionToken {\n\tif (!isRecord(input)) throw new TypeError(\"session revision token must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\n\t\t\t\"schemaVersion\",\n\t\t\t\"sessionId\",\n\t\t\t\"completeBytes\",\n\t\t\t\"recordCount\",\n\t\t\t\"leafId\",\n\t\t\t\"lastEntryId\",\n\t\t\t\"completePrefixSha256\",\n\t\t\t\"fileIdentity\",\n\t\t],\n\t\t\"session revision token\",\n\t);\n\tif (input.schemaVersion !== undefined && input.schemaVersion !== SESSION_REVISION_TOKEN_SCHEMA_VERSION) {\n\t\tthrow new TypeError(\"unsupported session revision token schema version\");\n\t}\n\tassertMetadataText(input.sessionId, \"sessionId\");\n\tassertSafeInteger(input.completeBytes, \"completeBytes\");\n\tassertSafeInteger(input.recordCount, \"recordCount\");\n\tif (input.leafId !== null) assertMetadataText(input.leafId, \"leafId\");\n\tif (input.lastEntryId !== null) assertMetadataText(input.lastEntryId, \"lastEntryId\");\n\tassertSha256(input.completePrefixSha256, \"completePrefixSha256\");\n\n\tif ((input.completeBytes === 0) !== (input.recordCount === 0)) {\n\t\tthrow new TypeError(\"completeBytes and recordCount must both be empty or both be non-empty\");\n\t}\n\tif (input.recordCount === 0 && (input.leafId !== null || input.lastEntryId !== null)) {\n\t\tthrow new TypeError(\"an empty revision cannot identify entries\");\n\t}\n\tif (input.leafId !== null && input.lastEntryId === null) {\n\t\tthrow new TypeError(\"leafId requires a lastEntryId\");\n\t}\n\tif (input.completeBytes === 0 && input.completePrefixSha256 !== EMPTY_SHA256) {\n\t\tthrow new TypeError(\"an empty revision must use the SHA-256 digest of empty bytes\");\n\t}\n\n\tconst fileIdentity = copyFileIdentity(input.fileIdentity);\n\treturn Object.freeze({\n\t\tschemaVersion: SESSION_REVISION_TOKEN_SCHEMA_VERSION,\n\t\tsessionId: input.sessionId,\n\t\tcompleteBytes: input.completeBytes,\n\t\trecordCount: input.recordCount,\n\t\tleafId: input.leafId,\n\t\tlastEntryId: input.lastEntryId,\n\t\tcompletePrefixSha256: input.completePrefixSha256,\n\t\t...(fileIdentity === undefined ? {} : { fileIdentity }),\n\t});\n}\n\nexport function createCompactionSourceIdentity(input: unknown): CompactionSourceIdentity {\n\tif (!isRecord(input)) throw new TypeError(\"compaction source identity must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\"sessionId\", \"entryIds\", \"firstEntryId\", \"lastEntryId\", \"sourceSha256\", \"activeLeafId\", \"messageCount\"],\n\t\t\"compaction source identity\",\n\t);\n\tassertMetadataText(input.sessionId, \"source.sessionId\");\n\tconst entryIds = copyIdArray(input.entryIds, \"source.entryIds\", MAX_SOURCE_ENTRIES);\n\tif (entryIds.length === 0) throw new TypeError(\"source.entryIds must be non-empty\");\n\tassertMetadataText(input.firstEntryId, \"source.firstEntryId\");\n\tassertMetadataText(input.lastEntryId, \"source.lastEntryId\");\n\tassertMetadataText(input.activeLeafId, \"source.activeLeafId\");\n\tassertSha256(input.sourceSha256, \"source.sourceSha256\");\n\tassertSafeInteger(input.messageCount, \"source.messageCount\");\n\tif (input.messageCount > entryIds.length) {\n\t\tthrow new TypeError(\"source.messageCount cannot exceed source.entryIds length\");\n\t}\n\tif (input.firstEntryId !== entryIds[0] || input.lastEntryId !== entryIds.at(-1)) {\n\t\tthrow new TypeError(\"source first/last IDs must match the ordered entry IDs\");\n\t}\n\t// R30 P2: active leaf must be the last entry in the source range\n\tif (input.activeLeafId !== input.lastEntryId) {\n\t\tthrow new TypeError(\"source.activeLeafId must match source.lastEntryId\");\n\t}\n\treturn Object.freeze({\n\t\tsessionId: input.sessionId,\n\t\tentryIds,\n\t\tfirstEntryId: input.firstEntryId,\n\t\tlastEntryId: input.lastEntryId,\n\t\tsourceSha256: input.sourceSha256,\n\t\tactiveLeafId: input.activeLeafId,\n\t\tmessageCount: input.messageCount,\n\t});\n}\n\nfunction copyModelIdentity(value: unknown): CompactionModelIdentity {\n\tif (!isRecord(value)) throw new TypeError(\"model must be an object\");\n\tassertOnlyKeys(value, [\"provider\", \"id\"], \"model\");\n\tassertMetadataText(value.provider, \"model.provider\");\n\tassertMetadataText(value.id, \"model.id\");\n\treturn Object.freeze({ provider: value.provider, id: value.id });\n}\n\nexport function createCompactionTransaction(input: CompactionTransactionInput): CompactionTransaction {\n\tif (!isRecord(input)) throw new TypeError(\"compaction transaction must be an object\");\n\tassertOnlyKeys(\n\t\tinput,\n\t\t[\"schemaVersion\", \"transactionId\", \"baseRevision\", \"source\", \"createdAt\", \"model\", \"preserved\"],\n\t\t\"compaction transaction\",\n\t);\n\tif (input.schemaVersion !== undefined && input.schemaVersion !== COMPACTION_TRANSACTION_SCHEMA_VERSION) {\n\t\tthrow new TypeError(\"unsupported compaction transaction schema version\");\n\t}\n\tassertMetadataText(input.transactionId, \"transactionId\");\n\tassertCanonicalTimestamp(input.createdAt);\n\tconst baseRevision = createSessionRevisionToken(input.baseRevision);\n\tconst source = createCompactionSourceIdentity(input.source);\n\tif (baseRevision.sessionId !== source.sessionId || baseRevision.leafId !== source.activeLeafId) {\n\t\tthrow new TypeError(\"transaction revision and source must identify the same session and active leaf\");\n\t}\n\tconst model = copyModelIdentity(input.model);\n\tconst preserved = copyPreservedProvenance(input.preserved);\n\treturn Object.freeze({\n\t\tschemaVersion: COMPACTION_TRANSACTION_SCHEMA_VERSION,\n\t\ttransactionId: input.transactionId,\n\t\tbaseRevision,\n\t\tsource,\n\t\tcreatedAt: input.createdAt,\n\t\tmodel,\n\t\tpreserved,\n\t});\n}\n\nconst KNOWN_FINDING_REASONS = new Set<SessionIntegrityReasonCode>([\n\t\"trailing_fragment\",\n\t\"invalid_utf8\",\n\t\"malformed_json\",\n\t\"missing_header\",\n\t\"invalid_header\",\n\t\"unsupported_header\",\n\t\"multiple_header\",\n\t\"late_header\",\n\t\"invalid_entry\",\n\t\"unsupported_entry\",\n\t\"duplicate_entry_id\",\n\t\"missing_parent\",\n\t\"self_cycle\",\n\t\"parent_cycle\",\n\t\"active_leaf_missing\",\n\t\"compaction_first_kept_not_ancestor\",\n\t\"active_branch_context_invalid\",\n\t\"transcript_missing_result\",\n\t\"transcript_duplicate_result\",\n\t\"transcript_orphan_result\",\n\t\"transcript_duplicate_call_id\",\n\t\"transcript_interleaved_non_result\",\n]);\nconst TRANSCRIPT_FINDING_REASONS = new Set<SessionIntegrityReasonCode>([\n\t\"transcript_missing_result\",\n\t\"transcript_duplicate_result\",\n\t\"transcript_orphan_result\",\n\t\"transcript_duplicate_call_id\",\n\t\"transcript_interleaved_non_result\",\n]);\nconst HEADER_FINDING_REASONS = new Set<SessionIntegrityReasonCode>([\n\t\"missing_header\",\n\t\"invalid_header\",\n\t\"unsupported_header\",\n\t\"multiple_header\",\n\t\"late_header\",\n]);\nconst TRANSCRIPT_ISSUE_KINDS = new Set<string>([\n\t\"missing_result\",\n\t\"duplicate_result\",\n\t\"orphan_result\",\n\t\"duplicate_call_id\",\n\t\"interleaved_non_result\",\n]);\n\nfunction messageToolCalls(message: SessionIntegrityReport[\"activeMessages\"][number]): readonly {\n\treadonly id: string;\n\treadonly name: string;\n}[] {\n\tif (message.role !== \"assistant\") return [];\n\treturn message.content.flatMap((block) => (block.type === \"toolCall\" ? [{ id: block.id, name: block.name }] : []));\n}\n\nfunction transcriptFindingReason(issue: TranscriptIntegrityIssue): SessionIntegrityReasonCode {\n\tswitch (issue.kind) {\n\t\tcase \"missing_result\":\n\t\t\treturn \"transcript_missing_result\";\n\t\tcase \"duplicate_result\":\n\t\t\treturn \"transcript_duplicate_result\";\n\t\tcase \"orphan_result\":\n\t\t\treturn \"transcript_orphan_result\";\n\t\tcase \"duplicate_call_id\":\n\t\t\treturn \"transcript_duplicate_call_id\";\n\t\tcase \"interleaved_non_result\":\n\t\t\treturn \"transcript_interleaved_non_result\";\n\t}\n}\n\nfunction issueIdentity(issue: {\n\treadonly kind: string;\n\treadonly toolCallId: string;\n\treadonly toolName?: string;\n}): string {\n\treturn JSON.stringify([issue.kind, issue.toolCallId, issue.toolName ?? null]);\n}\n\nfunction findingIdentity(finding: SessionIntegrityFinding): string {\n\treturn JSON.stringify([\n\t\tfinding.reason,\n\t\tfinding.line ?? null,\n\t\tfinding.entryId ?? null,\n\t\tfinding.parentId ?? null,\n\t\tfinding.cycleEntryIds ?? null,\n\t\tfinding.toolCallId ?? null,\n\t\tfinding.toolName ?? null,\n\t]);\n}\n\nfunction sameMultiset(left: readonly string[], right: readonly string[]): boolean {\n\tif (left.length !== right.length) return false;\n\tconst counts = new Map<string, number>();\n\tfor (const item of left) counts.set(item, (counts.get(item) ?? 0) + 1);\n\tfor (const item of right) {\n\t\tconst count = counts.get(item);\n\t\tif (count === undefined) return false;\n\t\tif (count === 1) counts.delete(item);\n\t\telse counts.set(item, count - 1);\n\t}\n\treturn counts.size === 0;\n}\n\nfunction validByteDigest(value: unknown, completePrefix: boolean): boolean {\n\tif (!isRecord(value)) return false;\n\tconst keys = completePrefix ? [\"byteCount\", \"sha256\", \"lineCount\"] : [\"byteCount\", \"sha256\"];\n\tif (Object.keys(value).some((key) => !keys.includes(key))) return false;\n\tif (!Number.isSafeInteger(value.byteCount) || (value.byteCount as number) < 0) return false;\n\tif (typeof value.sha256 !== \"string\" || !SHA256_PATTERN.test(value.sha256)) return false;\n\tif (!completePrefix) return true;\n\treturn Number.isSafeInteger(value.lineCount) && (value.lineCount as number) >= 0;\n}\n\nfunction validFinding(value: unknown): value is SessionIntegrityFinding {\n\tif (!isRecord(value) || typeof value.reason !== \"string\") return false;\n\tif (!KNOWN_FINDING_REASONS.has(value.reason as SessionIntegrityReasonCode)) return false;\n\tconst allowed = [\"reason\", \"line\", \"entryId\", \"parentId\", \"cycleEntryIds\", \"toolCallId\", \"toolName\"];\n\tif (Object.keys(value).some((key) => !allowed.includes(key))) return false;\n\tif (value.line !== undefined && (!Number.isSafeInteger(value.line) || (value.line as number) < 1)) return false;\n\tfor (const field of [\"entryId\", \"parentId\", \"toolCallId\", \"toolName\"] as const) {\n\t\tif (value[field] !== undefined && typeof value[field] !== \"string\") return false;\n\t}\n\treturn (\n\t\tvalue.cycleEntryIds === undefined ||\n\t\t(Array.isArray(value.cycleEntryIds) && value.cycleEntryIds.every((item) => typeof item === \"string\"))\n\t);\n}\n\nfunction validTranscriptIssue(value: unknown): value is TranscriptIntegrityIssue {\n\tif (!isRecord(value) || !TRANSCRIPT_ISSUE_KINDS.has(value.kind as string)) return false;\n\tif (typeof value.toolCallId !== \"string\" || value.toolCallId.length === 0) return false;\n\tif (value.toolName !== undefined && typeof value.toolName !== \"string\") return false;\n\treturn Object.keys(value).every((key) => [\"kind\", \"toolCallId\", \"toolName\"].includes(key));\n}\n\nfunction activeBranchIsConsistent(report: SessionIntegrityReport): boolean {\n\tif (!Array.isArray(report.entries) || !Array.isArray(report.activeBranch) || !Array.isArray(report.activeMessages)) {\n\t\treturn false;\n\t}\n\tconst entryIds = new Set<string>();\n\tfor (const entry of report.entries) {\n\t\tif (!isRecord(entry) || typeof entry.id !== \"string\" || entry.id.length === 0) return false;\n\t\tentryIds.add(entry.id);\n\t}\n\tif (report.activeLeafId === null) return report.activeBranch.length === 0;\n\tif (typeof report.activeLeafId !== \"string\" || report.activeBranch.length === 0) return false;\n\tconst branchIds = new Set<string>();\n\tfor (let index = 0; index < report.activeBranch.length; index++) {\n\t\tconst entry = report.activeBranch[index];\n\t\tif (!isRecord(entry) || typeof entry.id !== \"string\" || branchIds.has(entry.id) || !entryIds.has(entry.id)) {\n\t\t\treturn false;\n\t\t}\n\t\tbranchIds.add(entry.id);\n\t\tconst expectedParent = index === 0 ? null : report.activeBranch[index - 1]?.id;\n\t\tif (entry.parentId !== expectedParent) return false;\n\t}\n\treturn report.activeBranch.at(-1)?.id === report.activeLeafId;\n}\n\nfunction reportIsConsistent(report: SessionIntegrityReport): boolean {\n\tif (!isRecord(report)) return false;\n\tif (!validByteDigest(report.source, false) || !validByteDigest(report.completePrefix, true)) return false;\n\tif (report.trailingFragment !== null && !validByteDigest(report.trailingFragment, false)) return false;\n\tconst trailingBytes = report.trailingFragment?.byteCount ?? 0;\n\tif (report.source.byteCount !== report.completePrefix.byteCount + trailingBytes) return false;\n\tif (report.completePrefix.lineCount > report.completePrefix.byteCount) return false;\n\tif (report.completePrefix.byteCount === 0 && report.completePrefix.sha256 !== EMPTY_SHA256) return false;\n\tif (report.trailingFragment === null && report.source.sha256 !== report.completePrefix.sha256) return false;\n\tif (!Array.isArray(report.findings) || !report.findings.every(validFinding)) return false;\n\tif (typeof report.ok !== \"boolean\" || report.ok !== (report.findings.length === 0)) return false;\n\n\tconst trailingFindings = report.findings.filter((finding) => finding.reason === \"trailing_fragment\");\n\tif (\n\t\ttrailingFindings.length !== (report.trailingFragment === null ? 0 : 1) ||\n\t\ttrailingFindings.some((finding) => Object.keys(finding).length !== 1)\n\t) {\n\t\treturn false;\n\t}\n\tif (report.header === null) {\n\t\tif (!report.findings.some((finding) => HEADER_FINDING_REASONS.has(finding.reason))) return false;\n\t} else if (!isRecord(report.header) || typeof report.header.id !== \"string\" || report.header.id.length === 0) {\n\t\treturn false;\n\t}\n\tif (!activeBranchIsConsistent(report)) return false;\n\n\tconst transcriptFindings = report.findings.filter((finding) => TRANSCRIPT_FINDING_REASONS.has(finding.reason));\n\tif (report.transcript === null) {\n\t\t// R30 P1-2: null transcript can never produce ready.\n\t\t// A producer-consistent null transcript requires activeMessages to be empty\n\t\t// and a structural finding to explain why no transcript was produced.\n\t\tif (report.activeMessages.length > 0) return false;\n\t\tif (transcriptFindings.length !== 0) return false;\n\t\tconst hasStructuralFinding = report.findings.some(\n\t\t\t(finding) => finding.reason !== \"trailing_fragment\" && !TRANSCRIPT_FINDING_REASONS.has(finding.reason),\n\t\t);\n\t\treturn hasStructuralFinding;\n\t}\n\tif (!isRecord(report.transcript) || !Array.isArray(report.transcript.issues)) return false;\n\tif (!report.transcript.issues.every(validTranscriptIssue)) return false;\n\tif (report.transcript.ok !== (report.transcript.issues.length === 0)) return false;\n\tif (\n\t\treport.findings.some(\n\t\t\t(finding) => finding.reason !== \"trailing_fragment\" && !TRANSCRIPT_FINDING_REASONS.has(finding.reason),\n\t\t)\n\t) {\n\t\treturn false;\n\t}\n\n\tlet inspected: TranscriptIntegrityReport;\n\ttry {\n\t\tinspected = inspectTranscriptIntegrity(report.activeMessages);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (\n\t\tinspected.ok !== report.transcript.ok ||\n\t\t!sameMultiset(inspected.issues.map(issueIdentity), report.transcript.issues.map(issueIdentity))\n\t) {\n\t\treturn false;\n\t}\n\treturn sameMultiset(\n\t\ttranscriptFindings.map(findingIdentity),\n\t\tinspected.issues.map((issue) =>\n\t\t\tJSON.stringify([\n\t\t\t\ttranscriptFindingReason(issue),\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tissue.toolCallId,\n\t\t\t\tissue.toolName ?? null,\n\t\t\t]),\n\t\t),\n\t);\n}\n\nfunction missingCallsAreAtActiveTail(report: SessionIntegrityReport, missingIds: ReadonlySet<string>): boolean {\n\tlet lastAssistantIndex = -1;\n\tfor (let index = report.activeMessages.length - 1; index >= 0; index--) {\n\t\tif (report.activeMessages[index]?.role === \"assistant\") {\n\t\t\tlastAssistantIndex = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (lastAssistantIndex === -1) return false;\n\tconst assistant = report.activeMessages[lastAssistantIndex];\n\tif (!assistant || assistant.role !== \"assistant\") return false;\n\tconst tailCallIds = new Set(messageToolCalls(assistant).map((call) => call.id));\n\tif ([...missingIds].some((id) => !tailCallIds.has(id))) return false;\n\tfor (let index = lastAssistantIndex + 1; index < report.activeMessages.length; index++) {\n\t\tconst message = report.activeMessages[index];\n\t\tif (!message || message.role !== \"toolResult\" || !tailCallIds.has(message.toolCallId)) return false;\n\t}\n\treturn true;\n}\n\nfunction barrierResult(\n\tstatus: CompactionBarrierStatus,\n\treason: CompactionBarrierReason,\n\tpendingToolCallIds: readonly string[],\n\tmissingToolCallIds: readonly string[] = [],\n): CompactionBarrierResult {\n\treturn Object.freeze({\n\t\tstatus,\n\t\treason,\n\t\tpendingToolCallIds: Object.freeze([...pendingToolCallIds]),\n\t\tmissingToolCallIds: Object.freeze([...missingToolCallIds]),\n\t});\n}\n\n/** Derive a closed-turn compaction barrier without repairing or mutating the report. */\nexport function evaluateCompactionBarrier(\n\treport: SessionIntegrityReport,\n\tpendingToolCallIds: readonly string[],\n): CompactionBarrierResult {\n\tlet pending: readonly string[];\n\ttry {\n\t\tpending = copyIdArray(pendingToolCallIds, \"pendingToolCallIds\", MAX_PROVENANCE_IDS);\n\t} catch {\n\t\treturn barrierResult(\"fail_closed\", \"invalid_pending_tool_ids\", []);\n\t}\n\tif (!reportIsConsistent(report)) {\n\t\treturn barrierResult(\"fail_closed\", \"inconsistent_integrity_report\", pending);\n\t}\n\tconst blockingFinding = report.findings.find((finding) => finding.reason !== \"transcript_missing_result\");\n\tconst blockingIssue = report.transcript?.issues.find((issue) => issue.kind !== \"missing_result\");\n\tif (blockingFinding || blockingIssue) {\n\t\treturn barrierResult(\"fail_closed\", \"structural_integrity_failure\", pending);\n\t}\n\n\tconst missing = Object.freeze(\n\t\t(report.transcript?.issues ?? [])\n\t\t\t.filter((issue) => issue.kind === \"missing_result\")\n\t\t\t.map((issue) => issue.toolCallId),\n\t);\n\tconst missingSet = new Set(missing);\n\tconst pendingSet = new Set(pending);\n\tif (\n\t\tmissing.length > 0 &&\n\t\t(!missingCallsAreAtActiveTail(report, missingSet) || missing.some((toolCallId) => !pendingSet.has(toolCallId)))\n\t) {\n\t\treturn barrierResult(\"fail_closed\", \"unsafe_missing_tool_results\", pending, missing);\n\t}\n\tif (missing.length > 0) return barrierResult(\"defer\", \"missing_active_tail_results\", pending, missing);\n\tif (pending.length > 0) return barrierResult(\"defer\", \"pending_tool_calls\", pending);\n\treturn barrierResult(\"ready\", \"closed_active_branch\", []);\n}\n\nfunction sameRevision(left: SessionRevisionToken, right: SessionRevisionToken): boolean {\n\treturn (\n\t\tleft.schemaVersion === right.schemaVersion &&\n\t\tleft.sessionId === right.sessionId &&\n\t\tleft.completeBytes === right.completeBytes &&\n\t\tleft.recordCount === right.recordCount &&\n\t\tleft.leafId === right.leafId &&\n\t\tleft.lastEntryId === right.lastEntryId &&\n\t\tleft.completePrefixSha256 === right.completePrefixSha256 &&\n\t\tleft.fileIdentity?.dev === right.fileIdentity?.dev &&\n\t\tleft.fileIdentity?.ino === right.fileIdentity?.ino\n\t);\n}\n\nfunction sameSource(left: CompactionSourceIdentity, right: CompactionSourceIdentity): boolean {\n\treturn (\n\t\tleft.sessionId === right.sessionId &&\n\t\tleft.firstEntryId === right.firstEntryId &&\n\t\tleft.lastEntryId === right.lastEntryId &&\n\t\tleft.sourceSha256 === right.sourceSha256 &&\n\t\tleft.activeLeafId === right.activeLeafId &&\n\t\tleft.messageCount === right.messageCount &&\n\t\tleft.entryIds.length === right.entryIds.length &&\n\t\tleft.entryIds.every((id, index) => id === right.entryIds[index])\n\t);\n}\n\nfunction validBarrierResult(barrier: CompactionBarrierResult): boolean {\n\tif (!isRecord(barrier) || !Array.isArray(barrier.pendingToolCallIds) || !Array.isArray(barrier.missingToolCallIds)) {\n\t\treturn false;\n\t}\n\tconst pending = barrier.pendingToolCallIds;\n\tconst missing = barrier.missingToolCallIds;\n\t// R30 P1-3: validate all IDs are bounded, unique, safe metadata text\n\ttry {\n\t\tfor (const ids of [pending, missing]) {\n\t\t\tif (ids.length > MAX_PROVENANCE_IDS) return false;\n\t\t\tif (new Set(ids).size !== ids.length) return false;\n\t\t\tfor (const id of ids) assertMetadataText(id, \"barrier toolCallId\");\n\t\t}\n\t} catch {\n\t\treturn false;\n\t}\n\tswitch (barrier.status) {\n\t\tcase \"ready\":\n\t\t\treturn barrier.reason === \"closed_active_branch\" && pending.length === 0 && missing.length === 0;\n\t\tcase \"defer\":\n\t\t\tif (barrier.reason === \"pending_tool_calls\") {\n\t\t\t\treturn pending.length > 0 && missing.length === 0;\n\t\t\t}\n\t\t\tif (barrier.reason === \"missing_active_tail_results\") {\n\t\t\t\treturn missing.length > 0 && missing.every((id) => pending.includes(id));\n\t\t\t}\n\t\t\treturn false;\n\t\tcase \"fail_closed\":\n\t\t\treturn (\n\t\t\t\tbarrier.reason === \"invalid_pending_tool_ids\" ||\n\t\t\t\tbarrier.reason === \"inconsistent_integrity_report\" ||\n\t\t\t\tbarrier.reason === \"structural_integrity_failure\" ||\n\t\t\t\tbarrier.reason === \"unsafe_missing_tool_results\"\n\t\t\t);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/**\n * Authorize an in-memory commit attempt. A \"commit\" decision is not evidence of\n * durable persistence; the integration layer must still perform its own atomic CAS write.\n */\nexport function decideCompactionCommit(input: DecideCompactionCommitInput): CompactionCommitDecision {\n\tlet transaction: CompactionTransaction;\n\ttry {\n\t\ttransaction = createCompactionTransaction(input.transaction);\n\t} catch {\n\t\treturn Object.freeze({ decision: \"fail_closed\", reason: \"invalid_transaction\" });\n\t}\n\tif (!validBarrierResult(input.barrier)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"fail_closed\",\n\t\t\treason: \"invalid_commit_input\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\tif (input.barrier.status === \"fail_closed\") {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"fail_closed\",\n\t\t\treason: \"barrier_fail_closed\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t\tbarrierReason: input.barrier.reason,\n\t\t});\n\t}\n\tif (input.barrier.status === \"defer\") {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"defer\",\n\t\t\treason: \"barrier_defer\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t\tbarrierReason: input.barrier.reason,\n\t\t});\n\t}\n\n\tlet currentRevision: SessionRevisionToken;\n\tlet currentSource: CompactionSourceIdentity;\n\tlet priorDigests: readonly string[];\n\ttry {\n\t\tcurrentRevision = createSessionRevisionToken(input.currentRevision);\n\t\tcurrentSource = createCompactionSourceIdentity(input.currentSource);\n\t\tif (\n\t\t\t!Array.isArray(input.priorCommittedSourceDigests) ||\n\t\t\tinput.priorCommittedSourceDigests.length > MAX_SOURCE_ENTRIES\n\t\t) {\n\t\t\tthrow new TypeError(\"priorCommittedSourceDigests must be a bounded array\");\n\t\t}\n\t\tpriorDigests = input.priorCommittedSourceDigests.map((digest, index) => {\n\t\t\tassertSha256(digest, `priorCommittedSourceDigests[${index}]`);\n\t\t\treturn digest;\n\t\t});\n\t} catch {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"fail_closed\",\n\t\t\treason: \"invalid_commit_input\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\n\tif (priorDigests.includes(transaction.source.sourceSha256)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"duplicate\",\n\t\t\treason: \"source_already_committed\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\tif (!sameRevision(transaction.baseRevision, currentRevision)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"stale\",\n\t\t\treason: \"revision_mismatch\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\tif (!sameSource(transaction.source, currentSource)) {\n\t\treturn Object.freeze({\n\t\t\tdecision: \"stale\",\n\t\t\treason: \"source_mismatch\",\n\t\t\ttransactionId: transaction.transactionId,\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tdecision: \"commit\",\n\t\treason: \"exact_match\",\n\t\ttransactionId: transaction.transactionId,\n\t\trevision: currentRevision,\n\t\tsource: currentSource,\n\t});\n}\n\nconst COMPACTION_ENVELOPE_KEYS = [\n\t\"schemaVersion\",\n\t\"transactionId\",\n\t\"baseRevision\",\n\t\"source\",\n\t\"createdAt\",\n\t\"model\",\n\t\"summary\",\n\t\"summarySha256\",\n\t\"preserved\",\n] as const;\n\n/** Parse and deep-freeze a persisted schema-v2 compaction envelope. */\nexport function validateCompactionEnvelope(input: unknown): CompactionEnvelope {\n\tif (!isRecord(input)) throw new TypeError(\"compaction envelope must be an object\");\n\tassertOnlyKeys(input, COMPACTION_ENVELOPE_KEYS, \"compaction envelope\");\n\tif (input.schemaVersion !== COMPACTION_ENVELOPE_SCHEMA_VERSION) {\n\t\tthrow new TypeError(\"unsupported compaction envelope schema version\");\n\t}\n\tassertMetadataText(input.transactionId, \"transactionId\");\n\tassertCanonicalTimestamp(input.createdAt);\n\tassertContentText(input.summary, \"summary\", MAX_SUMMARY_LENGTH);\n\tassertSha256(input.summarySha256, \"summarySha256\");\n\tconst baseRevision = createSessionRevisionToken(input.baseRevision);\n\tconst source = createCompactionSourceIdentity(input.source);\n\tif (baseRevision.sessionId !== source.sessionId || baseRevision.leafId !== source.activeLeafId) {\n\t\tthrow new TypeError(\"envelope revision and source must identify the same session and active leaf\");\n\t}\n\treturn Object.freeze({\n\t\tschemaVersion: COMPACTION_ENVELOPE_SCHEMA_VERSION,\n\t\ttransactionId: input.transactionId,\n\t\tbaseRevision,\n\t\tsource,\n\t\tcreatedAt: input.createdAt,\n\t\tmodel: copyModelIdentity(input.model),\n\t\tsummary: input.summary,\n\t\tsummarySha256: input.summarySha256,\n\t\tpreserved: copyPreservedProvenance(input.preserved),\n\t});\n}\n\n/** Create provenance-bearing summary data only from an exact commit authorization. */\nexport function createCompactionEnvelope(input: CreateCompactionEnvelopeInput): CompactionEnvelope {\n\tif (!isRecord(input)) throw new TypeError(\"compaction envelope input must be an object\");\n\tassertOnlyKeys(input, [\"transaction\", \"decision\", \"summary\", \"summarySha256\"], \"compaction envelope input\");\n\tassertContentText(input.summary, \"summary\", MAX_SUMMARY_LENGTH);\n\tassertSha256(input.summarySha256, \"summarySha256\");\n\tif (input.decision.decision !== \"commit\" || input.decision.reason !== \"exact_match\") {\n\t\tthrow new TypeError(\"a commit decision is required to create a compaction envelope\");\n\t}\n\tconst transaction = createCompactionTransaction(input.transaction);\n\tconst decisionRevision = createSessionRevisionToken(input.decision.revision);\n\tconst decisionSource = createCompactionSourceIdentity(input.decision.source);\n\tif (\n\t\tinput.decision.transactionId !== transaction.transactionId ||\n\t\t!sameRevision(transaction.baseRevision, decisionRevision) ||\n\t\t!sameSource(transaction.source, decisionSource)\n\t) {\n\t\tthrow new TypeError(\"commit decision does not match the compaction transaction\");\n\t}\n\n\treturn validateCompactionEnvelope({\n\t\tschemaVersion: COMPACTION_ENVELOPE_SCHEMA_VERSION,\n\t\ttransactionId: transaction.transactionId,\n\t\tbaseRevision: transaction.baseRevision,\n\t\tsource: transaction.source,\n\t\tcreatedAt: transaction.createdAt,\n\t\tmodel: transaction.model,\n\t\tsummary: input.summary,\n\t\tsummarySha256: input.summarySha256,\n\t\tpreserved: transaction.preserved,\n\t});\n}\n"]}
|
|
@@ -17,11 +17,26 @@ const DECIMAL_STRING_PATTERN = /^[0-9]+$/u;
|
|
|
17
17
|
const CANONICAL_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;
|
|
18
18
|
const METADATA_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/u;
|
|
19
19
|
const CONTENT_CONTROL_PATTERN = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u;
|
|
20
|
-
const CREDENTIAL_SHAPE_PATTERN = /-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:^|[\s"'`:])bearer\s+[A-Za-z0-9._~+/-]{8,}|(?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|passwd|client[-_ ]?secret|secret[-_ ]?(?:key|token))\s*[:=]\s*["']?[^\s"',;]{3,}|(?:sk|ghp|gho|ghu|ghs|github_pat|xox[baprs])[-_][A-Za-z0-9_-]{8,}/iu;
|
|
20
|
+
const CREDENTIAL_SHAPE_PATTERN = /-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:^|[\s"'`:])bearer\s+[A-Za-z0-9._~+/-]{8,}|(?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|passwd|client[-_ ]?secret|secret[-_ ]?(?:key|token))\s*[:=]\s*["']?[^\s"',;]{3,}|(?<![A-Za-z0-9])(?:sk|ghp|gho|ghu|ghs|github_pat|xox[baprs])[-_][A-Za-z0-9_-]{8,}|(?<![A-Za-z0-9])AKIA[A-Z0-9]{16}(?![A-Z0-9])|(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?![A-Za-z0-9_-])|(?<![A-Za-z0-9_-])gAAAAA[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])|(?<![A-Za-z0-9])v2:[A-Za-z0-9_+/=-]{20,}/iu;
|
|
21
21
|
const REDACTED_ASSIGNMENT_PATTERN = /\s*[:=]\s*(?:"\[REDACTED\]"(?![A-Za-z0-9_+/-])|'\[REDACTED\]'(?![A-Za-z0-9_+/-])|\[REDACTED\](?![A-Za-z0-9._~+/-]))/giu;
|
|
22
|
-
|
|
22
|
+
const CREDENTIAL_SHAPE_MASK_PATTERN = new RegExp(CREDENTIAL_SHAPE_PATTERN.source, "giu");
|
|
23
|
+
export function containsCredentialShape(value) {
|
|
23
24
|
return CREDENTIAL_SHAPE_PATTERN.test(value.replace(REDACTED_ASSIGNMENT_PATTERN, ""));
|
|
24
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Deterministically mask credential-shaped spans so sanitized text always
|
|
28
|
+
* satisfies this module's fail-closed content validators. Producers (compaction
|
|
29
|
+
* summaries, preserved provenance) must route generated text through this
|
|
30
|
+
* before validation; otherwise a paranoid validator match would abort the
|
|
31
|
+
* entire compaction and strand an overflowed session.
|
|
32
|
+
*/
|
|
33
|
+
export function redactCredentialShapedContent(value) {
|
|
34
|
+
let result = value;
|
|
35
|
+
for (let pass = 0; pass < 8 && containsCredentialShape(result); pass += 1) {
|
|
36
|
+
result = result.replace(CREDENTIAL_SHAPE_MASK_PATTERN, "[REDACTED]");
|
|
37
|
+
}
|
|
38
|
+
return containsCredentialShape(result) ? "[REDACTED]" : result;
|
|
39
|
+
}
|
|
25
40
|
function isRecord(value) {
|
|
26
41
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
27
42
|
}
|