open-multi-agent-kit 0.96.2 → 0.98.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.md +43 -9
- package/dist/cli/args.d.ts +2 -3
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +13 -189
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/help.d.ts +3 -0
- package/dist/cli/help.d.ts.map +1 -0
- package/dist/cli/help.js +194 -0
- package/dist/cli/help.js.map +1 -0
- package/dist/cli/initial-message.d.ts.map +1 -1
- package/dist/cli/initial-message.js +2 -1
- package/dist/cli/initial-message.js.map +1 -1
- package/dist/cli/resource-paths.d.ts +4 -0
- package/dist/cli/resource-paths.d.ts.map +1 -0
- package/dist/cli/resource-paths.js +59 -0
- package/dist/cli/resource-paths.js.map +1 -0
- package/dist/commands/adaptorch-doctor-cli.d.ts +13 -0
- package/dist/commands/adaptorch-doctor-cli.d.ts.map +1 -0
- package/dist/commands/adaptorch-doctor-cli.js +115 -0
- package/dist/commands/adaptorch-doctor-cli.js.map +1 -0
- package/dist/commands/resource-doctor-cli.d.ts +4 -0
- package/dist/commands/resource-doctor-cli.d.ts.map +1 -1
- package/dist/commands/resource-doctor-cli.js +35 -5
- package/dist/commands/resource-doctor-cli.js.map +1 -1
- package/dist/core/adaptorch-bridge.d.ts +11 -13
- package/dist/core/adaptorch-bridge.d.ts.map +1 -1
- package/dist/core/adaptorch-bridge.js +11 -13
- package/dist/core/adaptorch-bridge.js.map +1 -1
- package/dist/core/agent-session-snapshot.d.ts +16 -0
- package/dist/core/agent-session-snapshot.d.ts.map +1 -0
- package/dist/core/agent-session-snapshot.js +111 -0
- package/dist/core/agent-session-snapshot.js.map +1 -0
- package/dist/core/agent-session.d.ts +14 -10
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +102 -217
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/agent-tool-settings.d.ts +10 -0
- package/dist/core/agent-tool-settings.d.ts.map +1 -1
- package/dist/core/agent-tool-settings.js +10 -1
- package/dist/core/agent-tool-settings.js.map +1 -1
- package/dist/core/attachment-store.d.ts +39 -0
- package/dist/core/attachment-store.d.ts.map +1 -0
- package/dist/core/attachment-store.js +81 -0
- package/dist/core/attachment-store.js.map +1 -0
- package/dist/core/command-safety.d.ts +8 -0
- package/dist/core/command-safety.d.ts.map +1 -1
- package/dist/core/command-safety.js +140 -14
- package/dist/core/command-safety.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +13 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +60 -62
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/index.d.ts +1 -0
- package/dist/core/compaction/index.d.ts.map +1 -1
- package/dist/core/compaction/index.js +1 -0
- package/dist/core/compaction/index.js.map +1 -1
- package/dist/core/compaction/knowledge-triage-format.d.ts +9 -0
- package/dist/core/compaction/knowledge-triage-format.d.ts.map +1 -0
- package/dist/core/compaction/knowledge-triage-format.js +71 -0
- package/dist/core/compaction/knowledge-triage-format.js.map +1 -0
- package/dist/core/compaction/knowledge-triage-types.d.ts +7 -0
- package/dist/core/compaction/knowledge-triage-types.d.ts.map +1 -0
- package/dist/core/compaction/knowledge-triage-types.js +2 -0
- package/dist/core/compaction/knowledge-triage-types.js.map +1 -0
- package/dist/core/compaction/knowledge-triage.d.ts +29 -0
- package/dist/core/compaction/knowledge-triage.d.ts.map +1 -0
- package/dist/core/compaction/knowledge-triage.js +189 -0
- package/dist/core/compaction/knowledge-triage.js.map +1 -0
- package/dist/core/compaction/transaction.d.ts.map +1 -1
- package/dist/core/compaction/transaction.js +1 -1
- package/dist/core/compaction/transaction.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +4 -0
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +37 -0
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/completion-sound-io.d.ts +14 -0
- package/dist/core/completion-sound-io.d.ts.map +1 -0
- package/dist/core/completion-sound-io.js +64 -0
- package/dist/core/completion-sound-io.js.map +1 -0
- package/dist/core/completion-sound.d.ts +4 -10
- package/dist/core/completion-sound.d.ts.map +1 -1
- package/dist/core/completion-sound.js +28 -58
- package/dist/core/completion-sound.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-relevance.d.ts +15 -2
- package/dist/core/context-budget-relevance.d.ts.map +1 -1
- package/dist/core/context-budget-relevance.js +21 -9
- package/dist/core/context-budget-relevance.js.map +1 -1
- package/dist/core/context-budget-system-prompt-items.d.ts +1 -1
- package/dist/core/context-budget-system-prompt-items.d.ts.map +1 -1
- package/dist/core/context-budget-system-prompt-items.js.map +1 -1
- package/dist/core/context-budget-system-prompt.d.ts +1 -1
- package/dist/core/context-budget-system-prompt.d.ts.map +1 -1
- package/dist/core/context-budget-system-prompt.js.map +1 -1
- package/dist/core/context-budget-v2-cache-keys.d.ts +3 -0
- package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
- package/dist/core/context-budget-v2-cache-keys.js +2 -0
- package/dist/core/context-budget-v2-cache-keys.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 +3 -0
- package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
- package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
- package/dist/core/context-budget-v2-planner.js +2 -1
- package/dist/core/context-budget-v2-planner.js.map +1 -1
- package/dist/core/context-budget-v2-scoring.d.ts +17 -0
- package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
- package/dist/core/context-budget-v2-scoring.js +25 -8
- package/dist/core/context-budget-v2-scoring.js.map +1 -1
- package/dist/core/context-budget-v2-selection.d.ts +2 -2
- package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
- package/dist/core/context-budget-v2-selection.js +18 -1
- package/dist/core/context-budget-v2-selection.js.map +1 -1
- package/dist/core/context-budget-v2-types.d.ts +17 -0
- package/dist/core/context-budget-v2-types.d.ts.map +1 -1
- package/dist/core/context-budget-v2-types.js +15 -0
- package/dist/core/context-budget-v2-types.js.map +1 -1
- package/dist/core/context-file.d.ts +23 -0
- package/dist/core/context-file.d.ts.map +1 -0
- package/dist/core/context-file.js +17 -0
- package/dist/core/context-file.js.map +1 -0
- package/dist/core/extensions/builtin/command-safety-gate.d.ts +3 -1
- package/dist/core/extensions/builtin/command-safety-gate.d.ts.map +1 -1
- package/dist/core/extensions/builtin/command-safety-gate.js +7 -0
- package/dist/core/extensions/builtin/command-safety-gate.js.map +1 -1
- package/dist/core/extensions/types.d.ts +12 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +1 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +6 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-prompt-policy.d.ts +1 -1
- package/dist/core/model-prompt-policy.d.ts.map +1 -1
- package/dist/core/model-prompt-policy.js.map +1 -1
- package/dist/core/model-registry.d.ts +8 -3
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +71 -1
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/package-doctor-source-scan.d.ts +9 -0
- package/dist/core/package-doctor-source-scan.d.ts.map +1 -1
- package/dist/core/package-doctor-source-scan.js +77 -4
- package/dist/core/package-doctor-source-scan.js.map +1 -1
- package/dist/core/prompt-attachment.d.ts +51 -0
- package/dist/core/prompt-attachment.d.ts.map +1 -0
- package/dist/core/prompt-attachment.js +186 -0
- package/dist/core/prompt-attachment.js.map +1 -0
- package/dist/core/prompt-settlement.d.ts +6 -3
- package/dist/core/prompt-settlement.d.ts.map +1 -1
- package/dist/core/prompt-settlement.js +10 -14
- package/dist/core/prompt-settlement.js.map +1 -1
- package/dist/core/provider-resilience.d.ts +28 -0
- package/dist/core/provider-resilience.d.ts.map +1 -1
- package/dist/core/provider-resilience.js +50 -0
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/provider-retry.d.ts +1 -1
- package/dist/core/provider-retry.d.ts.map +1 -1
- package/dist/core/provider-retry.js +1 -1
- package/dist/core/provider-retry.js.map +1 -1
- package/dist/core/provider-usage.d.ts.map +1 -1
- package/dist/core/provider-usage.js +68 -2
- package/dist/core/provider-usage.js.map +1 -1
- package/dist/core/reasoning-router-promotion.d.ts +124 -0
- package/dist/core/reasoning-router-promotion.d.ts.map +1 -0
- package/dist/core/reasoning-router-promotion.js +121 -0
- package/dist/core/reasoning-router-promotion.js.map +1 -0
- package/dist/core/reasoning-router-replay-stability.d.ts +65 -0
- package/dist/core/reasoning-router-replay-stability.d.ts.map +1 -0
- package/dist/core/reasoning-router-replay-stability.js +67 -0
- package/dist/core/reasoning-router-replay-stability.js.map +1 -0
- package/dist/core/reasoning-router-v4-weights.d.ts +6 -6
- package/dist/core/reasoning-router-v4-weights.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4-weights.js +3 -3
- package/dist/core/reasoning-router-v4-weights.js.map +1 -1
- package/dist/core/reasoning-router-v4.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4.js +6 -6
- package/dist/core/reasoning-router-v4.js.map +1 -1
- package/dist/core/redaction.d.ts.map +1 -1
- package/dist/core/redaction.js +1 -1
- package/dist/core/redaction.js.map +1 -1
- package/dist/core/resource-admission.d.ts +2 -1
- package/dist/core/resource-admission.d.ts.map +1 -1
- package/dist/core/resource-admission.js +11 -0
- package/dist/core/resource-admission.js.map +1 -1
- package/dist/core/resource-governor-format.d.ts +1 -1
- package/dist/core/resource-governor-format.d.ts.map +1 -1
- package/dist/core/resource-governor-format.js.map +1 -1
- package/dist/core/resource-governor-settings.d.ts +6 -12
- package/dist/core/resource-governor-settings.d.ts.map +1 -1
- package/dist/core/resource-governor-settings.js.map +1 -1
- package/dist/core/resource-governor-types.d.ts +24 -0
- package/dist/core/resource-governor-types.d.ts.map +1 -0
- package/dist/core/resource-governor-types.js +15 -0
- package/dist/core/resource-governor-types.js.map +1 -0
- package/dist/core/resource-loader.d.ts +1 -7
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/resource-observation-journal.d.ts +2 -1
- package/dist/core/resource-observation-journal.d.ts.map +1 -1
- package/dist/core/resource-observation-journal.js +4 -3
- package/dist/core/resource-observation-journal.js.map +1 -1
- package/dist/core/resource-observation-report-reader.d.ts +7 -0
- package/dist/core/resource-observation-report-reader.d.ts.map +1 -0
- package/dist/core/resource-observation-report-reader.js +157 -0
- package/dist/core/resource-observation-report-reader.js.map +1 -0
- package/dist/core/resource-observation-report.d.ts +24 -0
- package/dist/core/resource-observation-report.d.ts.map +1 -0
- package/dist/core/resource-observation-report.js +101 -0
- package/dist/core/resource-observation-report.js.map +1 -0
- package/dist/core/router-feedback-collector.d.ts +1 -1
- package/dist/core/router-feedback-collector.d.ts.map +1 -1
- package/dist/core/router-feedback-collector.js.map +1 -1
- package/dist/core/session-bash-service.d.ts.map +1 -1
- package/dist/core/session-bash-service.js +4 -3
- package/dist/core/session-bash-service.js.map +1 -1
- package/dist/core/session-failure-cause.d.ts +33 -0
- package/dist/core/session-failure-cause.d.ts.map +1 -0
- package/dist/core/session-failure-cause.js +141 -0
- package/dist/core/session-failure-cause.js.map +1 -0
- package/dist/core/session-system-prompt.d.ts +1 -1
- package/dist/core/session-system-prompt.d.ts.map +1 -1
- package/dist/core/session-system-prompt.js.map +1 -1
- package/dist/core/session-termination.d.ts +1 -1
- package/dist/core/session-termination.d.ts.map +1 -1
- package/dist/core/session-termination.js +11 -2
- package/dist/core/session-termination.js.map +1 -1
- package/dist/core/settings-manager.d.ts +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt.d.ts +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +10 -14
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +13 -48
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +1 -34
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/workload-classifier.d.ts +2 -10
- package/dist/core/workload-classifier.d.ts.map +1 -1
- package/dist/core/workload-classifier.js +17 -0
- package/dist/core/workload-classifier.js.map +1 -1
- package/dist/core/workload-family-matcher.d.ts +1 -1
- package/dist/core/workload-family-matcher.d.ts.map +1 -1
- package/dist/core/workload-family-matcher.js.map +1 -1
- package/dist/core/workload-shard-execution-types.d.ts +40 -0
- package/dist/core/workload-shard-execution-types.d.ts.map +1 -0
- package/dist/core/workload-shard-execution-types.js +14 -0
- package/dist/core/workload-shard-execution-types.js.map +1 -0
- package/dist/core/workload-shard-executor.d.ts +3 -27
- package/dist/core/workload-shard-executor.d.ts.map +1 -1
- package/dist/core/workload-shard-executor.js.map +1 -1
- package/dist/core/workload-shard-runner.d.ts +1 -1
- package/dist/core/workload-shard-runner.d.ts.map +1 -1
- package/dist/core/workload-shard-runner.js.map +1 -1
- package/dist/core/workload-types.d.ts +24 -0
- package/dist/core/workload-types.d.ts.map +1 -0
- package/dist/core/workload-types.js +15 -0
- package/dist/core/workload-types.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +2 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +27 -47
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/attachment-strip.d.ts +21 -0
- package/dist/modes/interactive/components/attachment-strip.d.ts.map +1 -0
- package/dist/modes/interactive/components/attachment-strip.js +136 -0
- package/dist/modes/interactive/components/attachment-strip.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts +6 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +26 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/status-sidebar.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-sidebar.js +12 -1
- package/dist/modes/interactive/components/status-sidebar.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +23 -4
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +174 -53
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/omk-control-panel.json +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +42 -33
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +14 -2
- package/dist/utils/clipboard.js.map +1 -1
- package/docs/adaptorch-preview-spec.md +20 -18
- package/docs/adaptorch-preview.md +9 -9
- package/docs/compaction.md +25 -4
- package/docs/correctness-wall.md +10 -10
- package/docs/docs.json +12 -0
- package/docs/environment-variables.md +9 -2
- package/docs/extensions.md +12 -3
- package/docs/index.md +7 -1
- package/docs/metrics.md +74 -2
- package/docs/provider-resilience.md +11 -0
- package/docs/runtime-algorithms.md +359 -0
- package/docs/sdk.md +2 -2
- package/docs/settings.md +11 -10
- package/docs/usage.md +19 -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/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +18 -18
- package/package.json +7 -7
- package/dist/core/context-budget-governor.d.ts +0 -67
- package/dist/core/context-budget-governor.d.ts.map +0 -1
- package/dist/core/context-budget-governor.js +0 -224
- package/dist/core/context-budget-governor.js.map +0 -1
- package/dist/core/lean-ctx.d.ts +0 -99
- package/dist/core/lean-ctx.d.ts.map +0 -1
- package/dist/core/lean-ctx.js +0 -225
- package/dist/core/lean-ctx.js.map +0 -1
- package/dist/core/read-anchors.d.ts +0 -110
- package/dist/core/read-anchors.d.ts.map +0 -1
- package/dist/core/read-anchors.js +0 -193
- package/dist/core/read-anchors.js.map +0 -1
- package/dist/core/recovery-checkpoint.d.ts +0 -196
- package/dist/core/recovery-checkpoint.d.ts.map +0 -1
- package/dist/core/recovery-checkpoint.js +0 -382
- package/dist/core/recovery-checkpoint.js.map +0 -1
- package/dist/core/sandbox-policy-v2.d.ts +0 -49
- package/dist/core/sandbox-policy-v2.d.ts.map +0 -1
- package/dist/core/sandbox-policy-v2.js +0 -368
- package/dist/core/sandbox-policy-v2.js.map +0 -1
- package/dist/core/tools/omp-pure-seams.d.ts +0 -41
- package/dist/core/tools/omp-pure-seams.d.ts.map +0 -1
- package/dist/core/tools/omp-pure-seams.js +0 -142
- package/dist/core/tools/omp-pure-seams.js.map +0 -1
- package/dist/core/tools/omp-seam-runtime.d.ts +0 -100
- package/dist/core/tools/omp-seam-runtime.d.ts.map +0 -1
- package/dist/core/tools/omp-seam-runtime.js +0 -40
- package/dist/core/tools/omp-seam-runtime.js.map +0 -1
- package/dist/guardrails/audit-logger.d.ts +0 -4
- package/dist/guardrails/audit-logger.d.ts.map +0 -1
- package/dist/guardrails/audit-logger.js +0 -28
- package/dist/guardrails/audit-logger.js.map +0 -1
- package/dist/guardrails/freedomd-adapter.d.ts +0 -16
- package/dist/guardrails/freedomd-adapter.d.ts.map +0 -1
- package/dist/guardrails/freedomd-adapter.js +0 -87
- package/dist/guardrails/freedomd-adapter.js.map +0 -1
- package/dist/orchestration/lane-grant-auditor.d.ts +0 -4
- package/dist/orchestration/lane-grant-auditor.d.ts.map +0 -1
- package/dist/orchestration/lane-grant-auditor.js +0 -87
- package/dist/orchestration/lane-grant-auditor.js.map +0 -1
- package/dist/types/guardrails.d.ts +0 -61
- package/dist/types/guardrails.d.ts.map +0 -1
- package/dist/types/guardrails.js +0 -9
- package/dist/types/guardrails.js.map +0 -1
- package/dist/types/lane-grant.d.ts +0 -58
- package/dist/types/lane-grant.d.ts.map +0 -1
- package/dist/types/lane-grant.js +0 -9
- package/dist/types/lane-grant.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"recovery-checkpoint.d.ts","sourceRoot":"","sources":["../../src/core/recovery-checkpoint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,eAAO,MAAM,kCAAkC,+BAA+B,CAAC;AAE/E,MAAM,MAAM,WAAW,GAAG,KAAK,GAAG,MAAM,CAAC;AACzC,MAAM,MAAM,eAAe,GAAG,SAAS,GAAG,WAAW,GAAG,SAAS,CAAC;AAElE,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;CA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CAgChE","sourcesContent":["/**\n * `omk.recovery.checkpoint` — pure decision algorithms for native worktree/\n * conversation recovery checkpoints.\n *\n * This module is intentionally side-effect free: it never reads the filesystem,\n * never shells out to git, and never mutates a worktree. It validates a\n * file-backed {@link RecoveryCheckpoint}, classifies a restore preflight against\n * an externally-observed worktree snapshot, decides how OMK-created untracked\n * files should be disposed (delete vs quarantine), and produces a\n * conversation/code/both restore plan. The caller is responsible for gathering\n * the observed state (git status, per-file hashes) and for executing the plan.\n *\n * Derived clean-room from the lane C plan\n * (`.omk/runs/omk-package-hardening-plan/recovery-readseek.md`) and the\n * adoption algorithm plan; no legacy package source is imported or copied.\n *\n * Dependency-free apart from `node:path` (pure path math, no I/O).\n */\n\nimport { isAbsolute } from \"node:path\";\n\nexport const RECOVERY_CHECKPOINT_SCHEMA_VERSION = \"omk.recovery.checkpoint.v1\";\n\nexport type RecoveryVcs = \"git\" | \"none\";\nexport type TouchedFileMode = \"tracked\" | \"untracked\" | \"deleted\";\n\nexport interface RecoveryCheckpointSession {\n\treadonly sessionFile?: string;\n\treadonly leafId: string | null;\n\treadonly branchPathIds: readonly string[];\n\treadonly contextHash: string;\n}\n\nexport interface RecoveryTouchedFile {\n\treadonly path: string;\n\treadonly beforeSha256?: string;\n\treadonly afterSha256?: string;\n\treadonly mode: TouchedFileMode;\n}\n\nexport interface RecoveryCheckpointWorkspace {\n\treadonly repoRoot: string;\n\treadonly vcs: RecoveryVcs;\n\treadonly head?: string;\n\treadonly statusPorcelainSha256: string;\n\treadonly touchedFiles: readonly RecoveryTouchedFile[];\n\treadonly reversePatchArtifact?: string;\n}\n\nexport interface RecoveryCheckpointTool {\n\treadonly turnIndex: number;\n\treadonly beforeToolCallId?: string;\n\treadonly afterToolCallId?: string;\n\treadonly mutatingTools: readonly string[];\n}\n\nexport interface RecoveryCheckpointLedger {\n\treadonly eventId: string;\n\treadonly previousEventHash: string;\n\treadonly eventHash: string;\n}\n\nexport interface RecoveryCheckpoint {\n\treadonly schemaVersion: typeof RECOVERY_CHECKPOINT_SCHEMA_VERSION;\n\treadonly checkpointId: string;\n\treadonly createdAt: string;\n\treadonly session: RecoveryCheckpointSession;\n\treadonly workspace: RecoveryCheckpointWorkspace;\n\treadonly tool?: RecoveryCheckpointTool;\n\treadonly ledger: RecoveryCheckpointLedger;\n}\n\nexport interface RecoveryCheckpointValidation {\n\treadonly ok: boolean;\n\treadonly errors: readonly string[];\n\treadonly checkpoint?: RecoveryCheckpoint;\n}\n\nconst HEX64 = /^[0-9a-f]{64}$/i;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction isHex64(value: unknown): value is string {\n\treturn typeof value === \"string\" && HEX64.test(value);\n}\n\nfunction isIsoTimestamp(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !Number.isNaN(Date.parse(value));\n}\n\n/** A touched-file path must be repo-relative and must not escape the repo root. */\nexport function isUnsafeTouchedPath(path: unknown): boolean {\n\tif (typeof path !== \"string\" || path.length === 0) return true;\n\tif (isAbsolute(path)) return true;\n\tconst normalized = path.replace(/\\\\/g, \"/\");\n\treturn normalized.split(\"/\").some((segment) => segment === \"..\");\n}\n\nfunction normalizeRelPath(path: string): string {\n\treturn path.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n\nfunction validateTouchedFile(value: unknown, index: number, errors: string[]): void {\n\tconst label = `workspace.touchedFiles[${index}]`;\n\tif (!isPlainObject(value)) {\n\t\terrors.push(`${label} must be an object`);\n\t\treturn;\n\t}\n\tif (isUnsafeTouchedPath(value.path)) {\n\t\terrors.push(`${label}.path must be a repo-relative path without '..' segments`);\n\t}\n\tconst mode = value.mode;\n\tif (mode !== \"tracked\" && mode !== \"untracked\" && mode !== \"deleted\") {\n\t\terrors.push(`${label}.mode must be one of tracked|untracked|deleted`);\n\t\treturn;\n\t}\n\tif (value.beforeSha256 !== undefined && !isHex64(value.beforeSha256)) {\n\t\terrors.push(`${label}.beforeSha256 must be a 64-char hex digest when present`);\n\t}\n\tif (value.afterSha256 !== undefined && !isHex64(value.afterSha256)) {\n\t\terrors.push(`${label}.afterSha256 must be a 64-char hex digest when present`);\n\t}\n\tif (mode === \"untracked\") {\n\t\tif (!isHex64(value.afterSha256)) errors.push(`${label}.afterSha256 is required for untracked files`);\n\t\tif (value.beforeSha256 !== undefined) errors.push(`${label}.beforeSha256 must be absent for untracked files`);\n\t}\n\tif (mode === \"deleted\") {\n\t\tif (!isHex64(value.beforeSha256)) errors.push(`${label}.beforeSha256 is required for deleted files`);\n\t\tif (value.afterSha256 !== undefined) errors.push(`${label}.afterSha256 must be absent for deleted files`);\n\t}\n\tif (mode === \"tracked\" && !isHex64(value.afterSha256)) {\n\t\terrors.push(`${label}.afterSha256 is required for tracked files`);\n\t}\n}\n\nfunction validateSession(value: unknown, errors: string[]): void {\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"session must be an object\");\n\t\treturn;\n\t}\n\tif (value.leafId !== null && typeof value.leafId !== \"string\") {\n\t\terrors.push(\"session.leafId must be a string or null\");\n\t}\n\tif (!Array.isArray(value.branchPathIds) || value.branchPathIds.some((id) => typeof id !== \"string\")) {\n\t\terrors.push(\"session.branchPathIds must be an array of strings\");\n\t}\n\tif (!isHex64(value.contextHash)) {\n\t\terrors.push(\"session.contextHash must be a 64-char hex digest\");\n\t}\n\tif (value.sessionFile !== undefined && typeof value.sessionFile !== \"string\") {\n\t\terrors.push(\"session.sessionFile must be a string when present\");\n\t}\n}\n\nfunction validateWorkspace(value: unknown, errors: string[]): void {\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"workspace must be an object\");\n\t\treturn;\n\t}\n\tif (!isNonEmptyString(value.repoRoot)) errors.push(\"workspace.repoRoot must be a non-empty string\");\n\tif (value.vcs !== \"git\" && value.vcs !== \"none\") errors.push(\"workspace.vcs must be one of git|none\");\n\tif (value.head !== undefined && typeof value.head !== \"string\") {\n\t\terrors.push(\"workspace.head must be a string when present\");\n\t}\n\tif (!isHex64(value.statusPorcelainSha256)) {\n\t\terrors.push(\"workspace.statusPorcelainSha256 must be a 64-char hex digest\");\n\t}\n\tif (value.reversePatchArtifact !== undefined && typeof value.reversePatchArtifact !== \"string\") {\n\t\terrors.push(\"workspace.reversePatchArtifact must be a string when present\");\n\t}\n\tif (!Array.isArray(value.touchedFiles)) {\n\t\terrors.push(\"workspace.touchedFiles must be an array\");\n\t\treturn;\n\t}\n\tvalue.touchedFiles.forEach((entry, index) => {\n\t\tvalidateTouchedFile(entry, index, errors);\n\t});\n}\n\nfunction validateTool(value: unknown, errors: string[]): void {\n\tif (value === undefined) return;\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"tool must be an object when present\");\n\t\treturn;\n\t}\n\tif (typeof value.turnIndex !== \"number\" || !Number.isInteger(value.turnIndex) || value.turnIndex < 0) {\n\t\terrors.push(\"tool.turnIndex must be a non-negative integer\");\n\t}\n\tif (!Array.isArray(value.mutatingTools) || value.mutatingTools.some((t) => typeof t !== \"string\")) {\n\t\terrors.push(\"tool.mutatingTools must be an array of strings\");\n\t}\n\tif (value.beforeToolCallId !== undefined && typeof value.beforeToolCallId !== \"string\") {\n\t\terrors.push(\"tool.beforeToolCallId must be a string when present\");\n\t}\n\tif (value.afterToolCallId !== undefined && typeof value.afterToolCallId !== \"string\") {\n\t\terrors.push(\"tool.afterToolCallId must be a string when present\");\n\t}\n}\n\nfunction validateLedger(value: unknown, errors: string[]): void {\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"ledger must be an object\");\n\t\treturn;\n\t}\n\tif (!isNonEmptyString(value.eventId)) errors.push(\"ledger.eventId must be a non-empty string\");\n\tif (!isHex64(value.previousEventHash)) errors.push(\"ledger.previousEventHash must be a 64-char hex digest\");\n\tif (!isHex64(value.eventHash)) errors.push(\"ledger.eventHash must be a 64-char hex digest\");\n}\n\n/**\n * Validate an untrusted value as a {@link RecoveryCheckpoint}. Pure and\n * fail-closed: any structural problem yields `ok: false` with explicit errors\n * and no `checkpoint` payload.\n */\nexport function validateRecoveryCheckpoint(value: unknown): RecoveryCheckpointValidation {\n\tconst errors: string[] = [];\n\tif (!isPlainObject(value)) {\n\t\treturn { ok: false, errors: [\"checkpoint must be an object\"] };\n\t}\n\tif (value.schemaVersion !== RECOVERY_CHECKPOINT_SCHEMA_VERSION) {\n\t\terrors.push(`schemaVersion must be ${RECOVERY_CHECKPOINT_SCHEMA_VERSION}`);\n\t}\n\tif (!isNonEmptyString(value.checkpointId)) errors.push(\"checkpointId must be a non-empty string\");\n\tif (!isIsoTimestamp(value.createdAt)) errors.push(\"createdAt must be an ISO-8601 timestamp\");\n\tvalidateSession(value.session, errors);\n\tvalidateWorkspace(value.workspace, errors);\n\tvalidateTool(value.tool, errors);\n\tvalidateLedger(value.ledger, errors);\n\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn { ok: true, errors: [], checkpoint: value as unknown as RecoveryCheckpoint };\n}\n\n/**\n * The ledger anchor as independently re-read from the hash-chained ledger.\n * Compared against the checkpoint's embedded anchor before any mutation.\n */\nexport interface ObservedLedgerAnchor {\n\treadonly eventId: string;\n\treadonly previousEventHash: string;\n\treadonly eventHash: string;\n}\n\nexport interface LedgerAnchorVerification {\n\treadonly ok: boolean;\n\treadonly mismatches: readonly string[];\n}\n\n/**\n * Compare a checkpoint's embedded ledger anchor with the anchor observed in the\n * live ledger. A mismatch means the checkpoint references an event that no\n * longer matches the durable audit trail (tamper or divergence) and the restore\n * must fail closed.\n */\nexport function verifyCheckpointLedgerAnchor(\n\tcheckpoint: RecoveryCheckpoint,\n\tobserved: ObservedLedgerAnchor,\n): LedgerAnchorVerification {\n\tconst mismatches: string[] = [];\n\tif (checkpoint.ledger.eventId !== observed.eventId) {\n\t\tmismatches.push(`eventId mismatch: checkpoint=${checkpoint.ledger.eventId} ledger=${observed.eventId}`);\n\t}\n\tif (checkpoint.ledger.previousEventHash !== observed.previousEventHash) {\n\t\tmismatches.push(\"previousEventHash mismatch between checkpoint and ledger\");\n\t}\n\tif (checkpoint.ledger.eventHash !== observed.eventHash) {\n\t\tmismatches.push(\"eventHash mismatch between checkpoint and ledger\");\n\t}\n\treturn { ok: mismatches.length === 0, mismatches };\n}\n\nexport interface ObservedTouchedFile {\n\treadonly path: string;\n\treadonly exists: boolean;\n\treadonly sha256?: string;\n\treadonly isSymlink?: boolean;\n\t/** True when the path (or its symlink target) resolves outside the repo root. */\n\treadonly escapesRepo?: boolean;\n}\n\nexport interface ObservedWorktree {\n\treadonly head?: string;\n\treadonly statusPorcelainSha256?: string;\n\t/** Current dirty paths (repo-relative) from `git status --porcelain`. */\n\treadonly dirtyPaths: readonly string[];\n\treadonly touchedFiles: readonly ObservedTouchedFile[];\n}\n\nexport interface RestorePreflightOptions {\n\t/** Allow restoring even though HEAD moved since the checkpoint. */\n\treadonly allowNonHeadRestore?: boolean;\n}\n\nexport type RestorePreflightVerdict = \"clean\" | \"blocked\";\n\nexport type RestorePreflightIssueCode =\n\t| \"unrelated-dirty-path\"\n\t| \"touched-hash-mismatch\"\n\t| \"missing-touched-file\"\n\t| \"symlink-escape\"\n\t| \"head-mismatch\";\n\nexport interface RestorePreflightIssue {\n\treadonly code: RestorePreflightIssueCode;\n\treadonly path?: string;\n\treadonly detail: string;\n}\n\nexport interface RestorePreflightResult {\n\treadonly verdict: RestorePreflightVerdict;\n\treadonly issues: readonly RestorePreflightIssue[];\n\treadonly unrelatedDirtyPaths: readonly string[];\n\treadonly hashMismatches: readonly string[];\n\treadonly symlinkEscapes: readonly string[];\n\treadonly headChanged: boolean;\n}\n\n/**\n * Classify whether a code restore can proceed against the live worktree.\n *\n * Fail-closed rules (from the lane C restore algorithm):\n * - any dirty path outside the recorded touched set blocks the restore;\n * - any touched file whose current hash differs from the recorded `afterSha256`\n * blocks the restore;\n * - any symlink escaping the repo root blocks the restore;\n * - a moved HEAD blocks the restore unless `allowNonHeadRestore` is set.\n */\nexport function classifyRestorePreflight(\n\tcheckpoint: RecoveryCheckpoint,\n\tobserved: ObservedWorktree,\n\toptions: RestorePreflightOptions = {},\n): RestorePreflightResult {\n\tconst issues: RestorePreflightIssue[] = [];\n\tconst touchedByPath = new Map<string, RecoveryTouchedFile>();\n\tfor (const file of checkpoint.workspace.touchedFiles) {\n\t\ttouchedByPath.set(normalizeRelPath(file.path), file);\n\t}\n\n\tconst unrelatedDirtyPaths: string[] = [];\n\tfor (const dirty of observed.dirtyPaths) {\n\t\tif (!touchedByPath.has(normalizeRelPath(dirty))) {\n\t\t\tunrelatedDirtyPaths.push(dirty);\n\t\t\tissues.push({\n\t\t\t\tcode: \"unrelated-dirty-path\",\n\t\t\t\tpath: dirty,\n\t\t\t\tdetail: \"dirty path is outside the checkpoint's recorded touched files\",\n\t\t\t});\n\t\t}\n\t}\n\n\tconst observedByPath = new Map<string, ObservedTouchedFile>();\n\tfor (const file of observed.touchedFiles) {\n\t\tobservedByPath.set(normalizeRelPath(file.path), file);\n\t}\n\n\tconst hashMismatches: string[] = [];\n\tconst symlinkEscapes: string[] = [];\n\tfor (const expected of checkpoint.workspace.touchedFiles) {\n\t\tconst key = normalizeRelPath(expected.path);\n\t\tconst current = observedByPath.get(key);\n\t\tif (!current) {\n\t\t\tissues.push({\n\t\t\t\tcode: \"missing-touched-file\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"no observed state was provided for a recorded touched file\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.escapesRepo === true || (current.isSymlink === true && current.escapesRepo !== false)) {\n\t\t\tsymlinkEscapes.push(expected.path);\n\t\t\tissues.push({\n\t\t\t\tcode: \"symlink-escape\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"touched path is a symlink resolving outside the repo root\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (expected.mode === \"deleted\") {\n\t\t\tif (current.exists) {\n\t\t\t\thashMismatches.push(expected.path);\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: \"touched-hash-mismatch\",\n\t\t\t\t\tpath: expected.path,\n\t\t\t\t\tdetail: \"expected a deleted file to be absent but it is present\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!current.exists) {\n\t\t\tissues.push({\n\t\t\t\tcode: \"missing-touched-file\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"recorded touched file is missing from the worktree\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.sha256 !== expected.afterSha256) {\n\t\t\thashMismatches.push(expected.path);\n\t\t\tissues.push({\n\t\t\t\tcode: \"touched-hash-mismatch\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"current file hash differs from the recorded post-edit hash\",\n\t\t\t});\n\t\t}\n\t}\n\n\tconst headChanged =\n\t\tcheckpoint.workspace.vcs === \"git\" &&\n\t\tcheckpoint.workspace.head !== undefined &&\n\t\tobserved.head !== undefined &&\n\t\tcheckpoint.workspace.head !== observed.head;\n\tif (headChanged && options.allowNonHeadRestore !== true) {\n\t\tissues.push({\n\t\t\tcode: \"head-mismatch\",\n\t\t\tdetail: \"HEAD moved since the checkpoint; pass allowNonHeadRestore to override\",\n\t\t});\n\t}\n\n\treturn {\n\t\tverdict: issues.length === 0 ? \"clean\" : \"blocked\",\n\t\tissues,\n\t\tunrelatedDirtyPaths,\n\t\thashMismatches,\n\t\tsymlinkEscapes,\n\t\theadChanged,\n\t};\n}\n\nexport type UntrackedDisposition = \"delete\" | \"quarantine\" | \"skip\";\n\nexport interface UntrackedDispositionDecision {\n\treadonly disposition: UntrackedDisposition;\n\treadonly reason: string;\n}\n\nexport interface ObservedUntrackedFile {\n\treadonly exists: boolean;\n\treadonly sha256?: string;\n}\n\n/**\n * Decide how an OMK-created untracked file should be handled on restore.\n *\n * - `skip`: the file is already gone, nothing to undo.\n * - `delete`: the file still exactly matches what OMK created, safe to remove.\n * - `quarantine`: the file changed since OMK created it; move it under the\n * recovery quarantine directory rather than destroying user edits.\n */\nexport function decideUntrackedDisposition(\n\ttouched: RecoveryTouchedFile,\n\tobserved: ObservedUntrackedFile,\n): UntrackedDispositionDecision {\n\tif (touched.mode !== \"untracked\") {\n\t\treturn { disposition: \"skip\", reason: \"disposition only applies to untracked files\" };\n\t}\n\tif (!observed.exists) {\n\t\treturn { disposition: \"skip\", reason: \"untracked file is already absent\" };\n\t}\n\tif (isHex64(touched.afterSha256) && observed.sha256 === touched.afterSha256) {\n\t\treturn { disposition: \"delete\", reason: \"current hash matches the OMK-created hash\" };\n\t}\n\treturn { disposition: \"quarantine\", reason: \"current hash differs from the OMK-created hash\" };\n}\n\nexport type RestoreMode = \"conversation\" | \"code\" | \"both\";\n\nexport type RestorePhaseKind = \"conversation\" | \"code\";\nexport type RestorePhaseAction = \"navigate-tree\" | \"apply-reverse-patch\";\n\nexport interface RestorePlanPhase {\n\treadonly phase: RestorePhaseKind;\n\treadonly action: RestorePhaseAction;\n\treadonly targetLeafId?: string | null;\n\treadonly recordedPaths?: readonly string[];\n}\n\nexport interface RestorePlan {\n\treadonly mode: RestoreMode;\n\treadonly status: \"ready\" | \"blocked\";\n\treadonly phases: readonly RestorePlanPhase[];\n\treadonly blockers: readonly string[];\n\t/** For `both`: the leaf to keep if the conversation phase fails after code restore. */\n\treadonly preservePreviousLeafId?: string | null;\n\treadonly inDoubtPolicy?: \"preserve-previous-leaf\";\n}\n\nexport interface PlanRestoreInput {\n\treadonly mode: RestoreMode;\n\treadonly checkpoint: RecoveryCheckpoint;\n\t/** Required for `code` and `both` modes. */\n\treadonly preflight?: RestorePreflightResult;\n\t/** The current session leaf, preserved for manual recovery in `both` mode. */\n\treadonly currentLeafId?: string | null;\n}\n\nfunction codePhase(checkpoint: RecoveryCheckpoint): RestorePlanPhase {\n\treturn {\n\t\tphase: \"code\",\n\t\taction: \"apply-reverse-patch\",\n\t\trecordedPaths: checkpoint.workspace.touchedFiles.map((file) => file.path),\n\t};\n}\n\nfunction conversationPhase(checkpoint: RecoveryCheckpoint): RestorePlanPhase {\n\treturn { phase: \"conversation\", action: \"navigate-tree\", targetLeafId: checkpoint.session.leafId };\n}\n\nfunction collectPreflightBlockers(preflight: RestorePreflightResult | undefined): string[] {\n\tif (!preflight) return [\"code restore requires a preflight classification\"];\n\tif (preflight.verdict === \"clean\") return [];\n\treturn preflight.issues.map((issue) => (issue.path ? `${issue.code}: ${issue.path}` : issue.code));\n}\n\n/**\n * Build a restore plan for the requested mode.\n *\n * - `conversation`: navigate the session tree to the checkpoint leaf; no file\n * writes, so no worktree preflight is required.\n * - `code`: apply the recorded reverse patch path-by-path; requires a clean\n * preflight.\n * - `both`: restore code first, then navigate the tree; requires a clean\n * preflight. If the second (conversation) phase fails at execution time the\n * caller marks the operation `in_doubt` and keeps `preservePreviousLeafId`.\n */\nexport function planRestore(input: PlanRestoreInput): RestorePlan {\n\tconst { mode, checkpoint, preflight } = input;\n\tif (mode === \"conversation\") {\n\t\treturn { mode, status: \"ready\", phases: [conversationPhase(checkpoint)], blockers: [] };\n\t}\n\n\tconst blockers = collectPreflightBlockers(preflight);\n\tif (mode === \"code\") {\n\t\tif (blockers.length > 0) return { mode, status: \"blocked\", phases: [], blockers };\n\t\treturn { mode, status: \"ready\", phases: [codePhase(checkpoint)], blockers: [] };\n\t}\n\n\t// mode === \"both\"\n\tconst preservePreviousLeafId = input.currentLeafId ?? null;\n\tif (blockers.length > 0) {\n\t\treturn {\n\t\t\tmode,\n\t\t\tstatus: \"blocked\",\n\t\t\tphases: [],\n\t\t\tblockers,\n\t\t\tpreservePreviousLeafId,\n\t\t\tinDoubtPolicy: \"preserve-previous-leaf\",\n\t\t};\n\t}\n\treturn {\n\t\tmode,\n\t\tstatus: \"ready\",\n\t\tphases: [codePhase(checkpoint), conversationPhase(checkpoint)],\n\t\tblockers: [],\n\t\tpreservePreviousLeafId,\n\t\tinDoubtPolicy: \"preserve-previous-leaf\",\n\t};\n}\n"]}
|
|
@@ -1,382 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `omk.recovery.checkpoint` — pure decision algorithms for native worktree/
|
|
3
|
-
* conversation recovery checkpoints.
|
|
4
|
-
*
|
|
5
|
-
* This module is intentionally side-effect free: it never reads the filesystem,
|
|
6
|
-
* never shells out to git, and never mutates a worktree. It validates a
|
|
7
|
-
* file-backed {@link RecoveryCheckpoint}, classifies a restore preflight against
|
|
8
|
-
* an externally-observed worktree snapshot, decides how OMK-created untracked
|
|
9
|
-
* files should be disposed (delete vs quarantine), and produces a
|
|
10
|
-
* conversation/code/both restore plan. The caller is responsible for gathering
|
|
11
|
-
* the observed state (git status, per-file hashes) and for executing the plan.
|
|
12
|
-
*
|
|
13
|
-
* Derived clean-room from the lane C plan
|
|
14
|
-
* (`.omk/runs/omk-package-hardening-plan/recovery-readseek.md`) and the
|
|
15
|
-
* adoption algorithm plan; no legacy package source is imported or copied.
|
|
16
|
-
*
|
|
17
|
-
* Dependency-free apart from `node:path` (pure path math, no I/O).
|
|
18
|
-
*/
|
|
19
|
-
import { isAbsolute } from "node:path";
|
|
20
|
-
export const RECOVERY_CHECKPOINT_SCHEMA_VERSION = "omk.recovery.checkpoint.v1";
|
|
21
|
-
const HEX64 = /^[0-9a-f]{64}$/i;
|
|
22
|
-
function isPlainObject(value) {
|
|
23
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
-
}
|
|
25
|
-
function isNonEmptyString(value) {
|
|
26
|
-
return typeof value === "string" && value.length > 0;
|
|
27
|
-
}
|
|
28
|
-
function isHex64(value) {
|
|
29
|
-
return typeof value === "string" && HEX64.test(value);
|
|
30
|
-
}
|
|
31
|
-
function isIsoTimestamp(value) {
|
|
32
|
-
return typeof value === "string" && value.length > 0 && !Number.isNaN(Date.parse(value));
|
|
33
|
-
}
|
|
34
|
-
/** A touched-file path must be repo-relative and must not escape the repo root. */
|
|
35
|
-
export function isUnsafeTouchedPath(path) {
|
|
36
|
-
if (typeof path !== "string" || path.length === 0)
|
|
37
|
-
return true;
|
|
38
|
-
if (isAbsolute(path))
|
|
39
|
-
return true;
|
|
40
|
-
const normalized = path.replace(/\\/g, "/");
|
|
41
|
-
return normalized.split("/").some((segment) => segment === "..");
|
|
42
|
-
}
|
|
43
|
-
function normalizeRelPath(path) {
|
|
44
|
-
return path.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
45
|
-
}
|
|
46
|
-
function validateTouchedFile(value, index, errors) {
|
|
47
|
-
const label = `workspace.touchedFiles[${index}]`;
|
|
48
|
-
if (!isPlainObject(value)) {
|
|
49
|
-
errors.push(`${label} must be an object`);
|
|
50
|
-
return;
|
|
51
|
-
}
|
|
52
|
-
if (isUnsafeTouchedPath(value.path)) {
|
|
53
|
-
errors.push(`${label}.path must be a repo-relative path without '..' segments`);
|
|
54
|
-
}
|
|
55
|
-
const mode = value.mode;
|
|
56
|
-
if (mode !== "tracked" && mode !== "untracked" && mode !== "deleted") {
|
|
57
|
-
errors.push(`${label}.mode must be one of tracked|untracked|deleted`);
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
if (value.beforeSha256 !== undefined && !isHex64(value.beforeSha256)) {
|
|
61
|
-
errors.push(`${label}.beforeSha256 must be a 64-char hex digest when present`);
|
|
62
|
-
}
|
|
63
|
-
if (value.afterSha256 !== undefined && !isHex64(value.afterSha256)) {
|
|
64
|
-
errors.push(`${label}.afterSha256 must be a 64-char hex digest when present`);
|
|
65
|
-
}
|
|
66
|
-
if (mode === "untracked") {
|
|
67
|
-
if (!isHex64(value.afterSha256))
|
|
68
|
-
errors.push(`${label}.afterSha256 is required for untracked files`);
|
|
69
|
-
if (value.beforeSha256 !== undefined)
|
|
70
|
-
errors.push(`${label}.beforeSha256 must be absent for untracked files`);
|
|
71
|
-
}
|
|
72
|
-
if (mode === "deleted") {
|
|
73
|
-
if (!isHex64(value.beforeSha256))
|
|
74
|
-
errors.push(`${label}.beforeSha256 is required for deleted files`);
|
|
75
|
-
if (value.afterSha256 !== undefined)
|
|
76
|
-
errors.push(`${label}.afterSha256 must be absent for deleted files`);
|
|
77
|
-
}
|
|
78
|
-
if (mode === "tracked" && !isHex64(value.afterSha256)) {
|
|
79
|
-
errors.push(`${label}.afterSha256 is required for tracked files`);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
function validateSession(value, errors) {
|
|
83
|
-
if (!isPlainObject(value)) {
|
|
84
|
-
errors.push("session must be an object");
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
if (value.leafId !== null && typeof value.leafId !== "string") {
|
|
88
|
-
errors.push("session.leafId must be a string or null");
|
|
89
|
-
}
|
|
90
|
-
if (!Array.isArray(value.branchPathIds) || value.branchPathIds.some((id) => typeof id !== "string")) {
|
|
91
|
-
errors.push("session.branchPathIds must be an array of strings");
|
|
92
|
-
}
|
|
93
|
-
if (!isHex64(value.contextHash)) {
|
|
94
|
-
errors.push("session.contextHash must be a 64-char hex digest");
|
|
95
|
-
}
|
|
96
|
-
if (value.sessionFile !== undefined && typeof value.sessionFile !== "string") {
|
|
97
|
-
errors.push("session.sessionFile must be a string when present");
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
function validateWorkspace(value, errors) {
|
|
101
|
-
if (!isPlainObject(value)) {
|
|
102
|
-
errors.push("workspace must be an object");
|
|
103
|
-
return;
|
|
104
|
-
}
|
|
105
|
-
if (!isNonEmptyString(value.repoRoot))
|
|
106
|
-
errors.push("workspace.repoRoot must be a non-empty string");
|
|
107
|
-
if (value.vcs !== "git" && value.vcs !== "none")
|
|
108
|
-
errors.push("workspace.vcs must be one of git|none");
|
|
109
|
-
if (value.head !== undefined && typeof value.head !== "string") {
|
|
110
|
-
errors.push("workspace.head must be a string when present");
|
|
111
|
-
}
|
|
112
|
-
if (!isHex64(value.statusPorcelainSha256)) {
|
|
113
|
-
errors.push("workspace.statusPorcelainSha256 must be a 64-char hex digest");
|
|
114
|
-
}
|
|
115
|
-
if (value.reversePatchArtifact !== undefined && typeof value.reversePatchArtifact !== "string") {
|
|
116
|
-
errors.push("workspace.reversePatchArtifact must be a string when present");
|
|
117
|
-
}
|
|
118
|
-
if (!Array.isArray(value.touchedFiles)) {
|
|
119
|
-
errors.push("workspace.touchedFiles must be an array");
|
|
120
|
-
return;
|
|
121
|
-
}
|
|
122
|
-
value.touchedFiles.forEach((entry, index) => {
|
|
123
|
-
validateTouchedFile(entry, index, errors);
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
function validateTool(value, errors) {
|
|
127
|
-
if (value === undefined)
|
|
128
|
-
return;
|
|
129
|
-
if (!isPlainObject(value)) {
|
|
130
|
-
errors.push("tool must be an object when present");
|
|
131
|
-
return;
|
|
132
|
-
}
|
|
133
|
-
if (typeof value.turnIndex !== "number" || !Number.isInteger(value.turnIndex) || value.turnIndex < 0) {
|
|
134
|
-
errors.push("tool.turnIndex must be a non-negative integer");
|
|
135
|
-
}
|
|
136
|
-
if (!Array.isArray(value.mutatingTools) || value.mutatingTools.some((t) => typeof t !== "string")) {
|
|
137
|
-
errors.push("tool.mutatingTools must be an array of strings");
|
|
138
|
-
}
|
|
139
|
-
if (value.beforeToolCallId !== undefined && typeof value.beforeToolCallId !== "string") {
|
|
140
|
-
errors.push("tool.beforeToolCallId must be a string when present");
|
|
141
|
-
}
|
|
142
|
-
if (value.afterToolCallId !== undefined && typeof value.afterToolCallId !== "string") {
|
|
143
|
-
errors.push("tool.afterToolCallId must be a string when present");
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
function validateLedger(value, errors) {
|
|
147
|
-
if (!isPlainObject(value)) {
|
|
148
|
-
errors.push("ledger must be an object");
|
|
149
|
-
return;
|
|
150
|
-
}
|
|
151
|
-
if (!isNonEmptyString(value.eventId))
|
|
152
|
-
errors.push("ledger.eventId must be a non-empty string");
|
|
153
|
-
if (!isHex64(value.previousEventHash))
|
|
154
|
-
errors.push("ledger.previousEventHash must be a 64-char hex digest");
|
|
155
|
-
if (!isHex64(value.eventHash))
|
|
156
|
-
errors.push("ledger.eventHash must be a 64-char hex digest");
|
|
157
|
-
}
|
|
158
|
-
/**
|
|
159
|
-
* Validate an untrusted value as a {@link RecoveryCheckpoint}. Pure and
|
|
160
|
-
* fail-closed: any structural problem yields `ok: false` with explicit errors
|
|
161
|
-
* and no `checkpoint` payload.
|
|
162
|
-
*/
|
|
163
|
-
export function validateRecoveryCheckpoint(value) {
|
|
164
|
-
const errors = [];
|
|
165
|
-
if (!isPlainObject(value)) {
|
|
166
|
-
return { ok: false, errors: ["checkpoint must be an object"] };
|
|
167
|
-
}
|
|
168
|
-
if (value.schemaVersion !== RECOVERY_CHECKPOINT_SCHEMA_VERSION) {
|
|
169
|
-
errors.push(`schemaVersion must be ${RECOVERY_CHECKPOINT_SCHEMA_VERSION}`);
|
|
170
|
-
}
|
|
171
|
-
if (!isNonEmptyString(value.checkpointId))
|
|
172
|
-
errors.push("checkpointId must be a non-empty string");
|
|
173
|
-
if (!isIsoTimestamp(value.createdAt))
|
|
174
|
-
errors.push("createdAt must be an ISO-8601 timestamp");
|
|
175
|
-
validateSession(value.session, errors);
|
|
176
|
-
validateWorkspace(value.workspace, errors);
|
|
177
|
-
validateTool(value.tool, errors);
|
|
178
|
-
validateLedger(value.ledger, errors);
|
|
179
|
-
if (errors.length > 0)
|
|
180
|
-
return { ok: false, errors };
|
|
181
|
-
return { ok: true, errors: [], checkpoint: value };
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Compare a checkpoint's embedded ledger anchor with the anchor observed in the
|
|
185
|
-
* live ledger. A mismatch means the checkpoint references an event that no
|
|
186
|
-
* longer matches the durable audit trail (tamper or divergence) and the restore
|
|
187
|
-
* must fail closed.
|
|
188
|
-
*/
|
|
189
|
-
export function verifyCheckpointLedgerAnchor(checkpoint, observed) {
|
|
190
|
-
const mismatches = [];
|
|
191
|
-
if (checkpoint.ledger.eventId !== observed.eventId) {
|
|
192
|
-
mismatches.push(`eventId mismatch: checkpoint=${checkpoint.ledger.eventId} ledger=${observed.eventId}`);
|
|
193
|
-
}
|
|
194
|
-
if (checkpoint.ledger.previousEventHash !== observed.previousEventHash) {
|
|
195
|
-
mismatches.push("previousEventHash mismatch between checkpoint and ledger");
|
|
196
|
-
}
|
|
197
|
-
if (checkpoint.ledger.eventHash !== observed.eventHash) {
|
|
198
|
-
mismatches.push("eventHash mismatch between checkpoint and ledger");
|
|
199
|
-
}
|
|
200
|
-
return { ok: mismatches.length === 0, mismatches };
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Classify whether a code restore can proceed against the live worktree.
|
|
204
|
-
*
|
|
205
|
-
* Fail-closed rules (from the lane C restore algorithm):
|
|
206
|
-
* - any dirty path outside the recorded touched set blocks the restore;
|
|
207
|
-
* - any touched file whose current hash differs from the recorded `afterSha256`
|
|
208
|
-
* blocks the restore;
|
|
209
|
-
* - any symlink escaping the repo root blocks the restore;
|
|
210
|
-
* - a moved HEAD blocks the restore unless `allowNonHeadRestore` is set.
|
|
211
|
-
*/
|
|
212
|
-
export function classifyRestorePreflight(checkpoint, observed, options = {}) {
|
|
213
|
-
const issues = [];
|
|
214
|
-
const touchedByPath = new Map();
|
|
215
|
-
for (const file of checkpoint.workspace.touchedFiles) {
|
|
216
|
-
touchedByPath.set(normalizeRelPath(file.path), file);
|
|
217
|
-
}
|
|
218
|
-
const unrelatedDirtyPaths = [];
|
|
219
|
-
for (const dirty of observed.dirtyPaths) {
|
|
220
|
-
if (!touchedByPath.has(normalizeRelPath(dirty))) {
|
|
221
|
-
unrelatedDirtyPaths.push(dirty);
|
|
222
|
-
issues.push({
|
|
223
|
-
code: "unrelated-dirty-path",
|
|
224
|
-
path: dirty,
|
|
225
|
-
detail: "dirty path is outside the checkpoint's recorded touched files",
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
const observedByPath = new Map();
|
|
230
|
-
for (const file of observed.touchedFiles) {
|
|
231
|
-
observedByPath.set(normalizeRelPath(file.path), file);
|
|
232
|
-
}
|
|
233
|
-
const hashMismatches = [];
|
|
234
|
-
const symlinkEscapes = [];
|
|
235
|
-
for (const expected of checkpoint.workspace.touchedFiles) {
|
|
236
|
-
const key = normalizeRelPath(expected.path);
|
|
237
|
-
const current = observedByPath.get(key);
|
|
238
|
-
if (!current) {
|
|
239
|
-
issues.push({
|
|
240
|
-
code: "missing-touched-file",
|
|
241
|
-
path: expected.path,
|
|
242
|
-
detail: "no observed state was provided for a recorded touched file",
|
|
243
|
-
});
|
|
244
|
-
continue;
|
|
245
|
-
}
|
|
246
|
-
if (current.escapesRepo === true || (current.isSymlink === true && current.escapesRepo !== false)) {
|
|
247
|
-
symlinkEscapes.push(expected.path);
|
|
248
|
-
issues.push({
|
|
249
|
-
code: "symlink-escape",
|
|
250
|
-
path: expected.path,
|
|
251
|
-
detail: "touched path is a symlink resolving outside the repo root",
|
|
252
|
-
});
|
|
253
|
-
continue;
|
|
254
|
-
}
|
|
255
|
-
if (expected.mode === "deleted") {
|
|
256
|
-
if (current.exists) {
|
|
257
|
-
hashMismatches.push(expected.path);
|
|
258
|
-
issues.push({
|
|
259
|
-
code: "touched-hash-mismatch",
|
|
260
|
-
path: expected.path,
|
|
261
|
-
detail: "expected a deleted file to be absent but it is present",
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
continue;
|
|
265
|
-
}
|
|
266
|
-
if (!current.exists) {
|
|
267
|
-
issues.push({
|
|
268
|
-
code: "missing-touched-file",
|
|
269
|
-
path: expected.path,
|
|
270
|
-
detail: "recorded touched file is missing from the worktree",
|
|
271
|
-
});
|
|
272
|
-
continue;
|
|
273
|
-
}
|
|
274
|
-
if (current.sha256 !== expected.afterSha256) {
|
|
275
|
-
hashMismatches.push(expected.path);
|
|
276
|
-
issues.push({
|
|
277
|
-
code: "touched-hash-mismatch",
|
|
278
|
-
path: expected.path,
|
|
279
|
-
detail: "current file hash differs from the recorded post-edit hash",
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
const headChanged = checkpoint.workspace.vcs === "git" &&
|
|
284
|
-
checkpoint.workspace.head !== undefined &&
|
|
285
|
-
observed.head !== undefined &&
|
|
286
|
-
checkpoint.workspace.head !== observed.head;
|
|
287
|
-
if (headChanged && options.allowNonHeadRestore !== true) {
|
|
288
|
-
issues.push({
|
|
289
|
-
code: "head-mismatch",
|
|
290
|
-
detail: "HEAD moved since the checkpoint; pass allowNonHeadRestore to override",
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
return {
|
|
294
|
-
verdict: issues.length === 0 ? "clean" : "blocked",
|
|
295
|
-
issues,
|
|
296
|
-
unrelatedDirtyPaths,
|
|
297
|
-
hashMismatches,
|
|
298
|
-
symlinkEscapes,
|
|
299
|
-
headChanged,
|
|
300
|
-
};
|
|
301
|
-
}
|
|
302
|
-
/**
|
|
303
|
-
* Decide how an OMK-created untracked file should be handled on restore.
|
|
304
|
-
*
|
|
305
|
-
* - `skip`: the file is already gone, nothing to undo.
|
|
306
|
-
* - `delete`: the file still exactly matches what OMK created, safe to remove.
|
|
307
|
-
* - `quarantine`: the file changed since OMK created it; move it under the
|
|
308
|
-
* recovery quarantine directory rather than destroying user edits.
|
|
309
|
-
*/
|
|
310
|
-
export function decideUntrackedDisposition(touched, observed) {
|
|
311
|
-
if (touched.mode !== "untracked") {
|
|
312
|
-
return { disposition: "skip", reason: "disposition only applies to untracked files" };
|
|
313
|
-
}
|
|
314
|
-
if (!observed.exists) {
|
|
315
|
-
return { disposition: "skip", reason: "untracked file is already absent" };
|
|
316
|
-
}
|
|
317
|
-
if (isHex64(touched.afterSha256) && observed.sha256 === touched.afterSha256) {
|
|
318
|
-
return { disposition: "delete", reason: "current hash matches the OMK-created hash" };
|
|
319
|
-
}
|
|
320
|
-
return { disposition: "quarantine", reason: "current hash differs from the OMK-created hash" };
|
|
321
|
-
}
|
|
322
|
-
function codePhase(checkpoint) {
|
|
323
|
-
return {
|
|
324
|
-
phase: "code",
|
|
325
|
-
action: "apply-reverse-patch",
|
|
326
|
-
recordedPaths: checkpoint.workspace.touchedFiles.map((file) => file.path),
|
|
327
|
-
};
|
|
328
|
-
}
|
|
329
|
-
function conversationPhase(checkpoint) {
|
|
330
|
-
return { phase: "conversation", action: "navigate-tree", targetLeafId: checkpoint.session.leafId };
|
|
331
|
-
}
|
|
332
|
-
function collectPreflightBlockers(preflight) {
|
|
333
|
-
if (!preflight)
|
|
334
|
-
return ["code restore requires a preflight classification"];
|
|
335
|
-
if (preflight.verdict === "clean")
|
|
336
|
-
return [];
|
|
337
|
-
return preflight.issues.map((issue) => (issue.path ? `${issue.code}: ${issue.path}` : issue.code));
|
|
338
|
-
}
|
|
339
|
-
/**
|
|
340
|
-
* Build a restore plan for the requested mode.
|
|
341
|
-
*
|
|
342
|
-
* - `conversation`: navigate the session tree to the checkpoint leaf; no file
|
|
343
|
-
* writes, so no worktree preflight is required.
|
|
344
|
-
* - `code`: apply the recorded reverse patch path-by-path; requires a clean
|
|
345
|
-
* preflight.
|
|
346
|
-
* - `both`: restore code first, then navigate the tree; requires a clean
|
|
347
|
-
* preflight. If the second (conversation) phase fails at execution time the
|
|
348
|
-
* caller marks the operation `in_doubt` and keeps `preservePreviousLeafId`.
|
|
349
|
-
*/
|
|
350
|
-
export function planRestore(input) {
|
|
351
|
-
const { mode, checkpoint, preflight } = input;
|
|
352
|
-
if (mode === "conversation") {
|
|
353
|
-
return { mode, status: "ready", phases: [conversationPhase(checkpoint)], blockers: [] };
|
|
354
|
-
}
|
|
355
|
-
const blockers = collectPreflightBlockers(preflight);
|
|
356
|
-
if (mode === "code") {
|
|
357
|
-
if (blockers.length > 0)
|
|
358
|
-
return { mode, status: "blocked", phases: [], blockers };
|
|
359
|
-
return { mode, status: "ready", phases: [codePhase(checkpoint)], blockers: [] };
|
|
360
|
-
}
|
|
361
|
-
// mode === "both"
|
|
362
|
-
const preservePreviousLeafId = input.currentLeafId ?? null;
|
|
363
|
-
if (blockers.length > 0) {
|
|
364
|
-
return {
|
|
365
|
-
mode,
|
|
366
|
-
status: "blocked",
|
|
367
|
-
phases: [],
|
|
368
|
-
blockers,
|
|
369
|
-
preservePreviousLeafId,
|
|
370
|
-
inDoubtPolicy: "preserve-previous-leaf",
|
|
371
|
-
};
|
|
372
|
-
}
|
|
373
|
-
return {
|
|
374
|
-
mode,
|
|
375
|
-
status: "ready",
|
|
376
|
-
phases: [codePhase(checkpoint), conversationPhase(checkpoint)],
|
|
377
|
-
blockers: [],
|
|
378
|
-
preservePreviousLeafId,
|
|
379
|
-
inDoubtPolicy: "preserve-previous-leaf",
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
//# sourceMappingURL=recovery-checkpoint.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"recovery-checkpoint.js","sourceRoot":"","sources":["../../src/core/recovery-checkpoint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,MAAM,CAAC,MAAM,kCAAkC,GAAG,4BAA4B,CAAC;AAyD/E,MAAM,KAAK,GAAG,iBAAiB,CAAC;AAEhC,SAAS,aAAa,CAAC,KAAc,EAAoC;IACxE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E;AAED,SAAS,gBAAgB,CAAC,KAAc,EAAmB;IAC1D,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAAA,CACrD;AAED,SAAS,OAAO,CAAC,KAAc,EAAmB;IACjD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAAA,CACtD;AAED,SAAS,cAAc,CAAC,KAAc,EAAmB;IACxD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAA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AAC,UAAU,CAAC,EAAE,iBAAiB,CAAC,UAAU,CAAC,CAAC;QAC9D,QAAQ,EAAE,EAAE;QACZ,sBAAsB;QACtB,aAAa,EAAE,wBAAwB;KACvC,CAAC;AAAA,CACF","sourcesContent":["/**\n * `omk.recovery.checkpoint` — pure decision algorithms for native worktree/\n * conversation recovery checkpoints.\n *\n * This module is intentionally side-effect free: it never reads the filesystem,\n * never shells out to git, and never mutates a worktree. It validates a\n * file-backed {@link RecoveryCheckpoint}, classifies a restore preflight against\n * an externally-observed worktree snapshot, decides how OMK-created untracked\n * files should be disposed (delete vs quarantine), and produces a\n * conversation/code/both restore plan. The caller is responsible for gathering\n * the observed state (git status, per-file hashes) and for executing the plan.\n *\n * Derived clean-room from the lane C plan\n * (`.omk/runs/omk-package-hardening-plan/recovery-readseek.md`) and the\n * adoption algorithm plan; no legacy package source is imported or copied.\n *\n * Dependency-free apart from `node:path` (pure path math, no I/O).\n */\n\nimport { isAbsolute } from \"node:path\";\n\nexport const RECOVERY_CHECKPOINT_SCHEMA_VERSION = \"omk.recovery.checkpoint.v1\";\n\nexport type RecoveryVcs = \"git\" | \"none\";\nexport type TouchedFileMode = \"tracked\" | \"untracked\" | \"deleted\";\n\nexport interface RecoveryCheckpointSession {\n\treadonly sessionFile?: string;\n\treadonly leafId: string | null;\n\treadonly branchPathIds: readonly string[];\n\treadonly contextHash: string;\n}\n\nexport interface RecoveryTouchedFile {\n\treadonly path: string;\n\treadonly beforeSha256?: string;\n\treadonly afterSha256?: string;\n\treadonly mode: TouchedFileMode;\n}\n\nexport interface RecoveryCheckpointWorkspace {\n\treadonly repoRoot: string;\n\treadonly vcs: RecoveryVcs;\n\treadonly head?: string;\n\treadonly statusPorcelainSha256: string;\n\treadonly touchedFiles: readonly RecoveryTouchedFile[];\n\treadonly reversePatchArtifact?: string;\n}\n\nexport interface RecoveryCheckpointTool {\n\treadonly turnIndex: number;\n\treadonly beforeToolCallId?: string;\n\treadonly afterToolCallId?: string;\n\treadonly mutatingTools: readonly string[];\n}\n\nexport interface RecoveryCheckpointLedger {\n\treadonly eventId: string;\n\treadonly previousEventHash: string;\n\treadonly eventHash: string;\n}\n\nexport interface RecoveryCheckpoint {\n\treadonly schemaVersion: typeof RECOVERY_CHECKPOINT_SCHEMA_VERSION;\n\treadonly checkpointId: string;\n\treadonly createdAt: string;\n\treadonly session: RecoveryCheckpointSession;\n\treadonly workspace: RecoveryCheckpointWorkspace;\n\treadonly tool?: RecoveryCheckpointTool;\n\treadonly ledger: RecoveryCheckpointLedger;\n}\n\nexport interface RecoveryCheckpointValidation {\n\treadonly ok: boolean;\n\treadonly errors: readonly string[];\n\treadonly checkpoint?: RecoveryCheckpoint;\n}\n\nconst HEX64 = /^[0-9a-f]{64}$/i;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0;\n}\n\nfunction isHex64(value: unknown): value is string {\n\treturn typeof value === \"string\" && HEX64.test(value);\n}\n\nfunction isIsoTimestamp(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && !Number.isNaN(Date.parse(value));\n}\n\n/** A touched-file path must be repo-relative and must not escape the repo root. */\nexport function isUnsafeTouchedPath(path: unknown): boolean {\n\tif (typeof path !== \"string\" || path.length === 0) return true;\n\tif (isAbsolute(path)) return true;\n\tconst normalized = path.replace(/\\\\/g, \"/\");\n\treturn normalized.split(\"/\").some((segment) => segment === \"..\");\n}\n\nfunction normalizeRelPath(path: string): string {\n\treturn path.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n}\n\nfunction validateTouchedFile(value: unknown, index: number, errors: string[]): void {\n\tconst label = `workspace.touchedFiles[${index}]`;\n\tif (!isPlainObject(value)) {\n\t\terrors.push(`${label} must be an object`);\n\t\treturn;\n\t}\n\tif (isUnsafeTouchedPath(value.path)) {\n\t\terrors.push(`${label}.path must be a repo-relative path without '..' segments`);\n\t}\n\tconst mode = value.mode;\n\tif (mode !== \"tracked\" && mode !== \"untracked\" && mode !== \"deleted\") {\n\t\terrors.push(`${label}.mode must be one of tracked|untracked|deleted`);\n\t\treturn;\n\t}\n\tif (value.beforeSha256 !== undefined && !isHex64(value.beforeSha256)) {\n\t\terrors.push(`${label}.beforeSha256 must be a 64-char hex digest when present`);\n\t}\n\tif (value.afterSha256 !== undefined && !isHex64(value.afterSha256)) {\n\t\terrors.push(`${label}.afterSha256 must be a 64-char hex digest when present`);\n\t}\n\tif (mode === \"untracked\") {\n\t\tif (!isHex64(value.afterSha256)) errors.push(`${label}.afterSha256 is required for untracked files`);\n\t\tif (value.beforeSha256 !== undefined) errors.push(`${label}.beforeSha256 must be absent for untracked files`);\n\t}\n\tif (mode === \"deleted\") {\n\t\tif (!isHex64(value.beforeSha256)) errors.push(`${label}.beforeSha256 is required for deleted files`);\n\t\tif (value.afterSha256 !== undefined) errors.push(`${label}.afterSha256 must be absent for deleted files`);\n\t}\n\tif (mode === \"tracked\" && !isHex64(value.afterSha256)) {\n\t\terrors.push(`${label}.afterSha256 is required for tracked files`);\n\t}\n}\n\nfunction validateSession(value: unknown, errors: string[]): void {\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"session must be an object\");\n\t\treturn;\n\t}\n\tif (value.leafId !== null && typeof value.leafId !== \"string\") {\n\t\terrors.push(\"session.leafId must be a string or null\");\n\t}\n\tif (!Array.isArray(value.branchPathIds) || value.branchPathIds.some((id) => typeof id !== \"string\")) {\n\t\terrors.push(\"session.branchPathIds must be an array of strings\");\n\t}\n\tif (!isHex64(value.contextHash)) {\n\t\terrors.push(\"session.contextHash must be a 64-char hex digest\");\n\t}\n\tif (value.sessionFile !== undefined && typeof value.sessionFile !== \"string\") {\n\t\terrors.push(\"session.sessionFile must be a string when present\");\n\t}\n}\n\nfunction validateWorkspace(value: unknown, errors: string[]): void {\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"workspace must be an object\");\n\t\treturn;\n\t}\n\tif (!isNonEmptyString(value.repoRoot)) errors.push(\"workspace.repoRoot must be a non-empty string\");\n\tif (value.vcs !== \"git\" && value.vcs !== \"none\") errors.push(\"workspace.vcs must be one of git|none\");\n\tif (value.head !== undefined && typeof value.head !== \"string\") {\n\t\terrors.push(\"workspace.head must be a string when present\");\n\t}\n\tif (!isHex64(value.statusPorcelainSha256)) {\n\t\terrors.push(\"workspace.statusPorcelainSha256 must be a 64-char hex digest\");\n\t}\n\tif (value.reversePatchArtifact !== undefined && typeof value.reversePatchArtifact !== \"string\") {\n\t\terrors.push(\"workspace.reversePatchArtifact must be a string when present\");\n\t}\n\tif (!Array.isArray(value.touchedFiles)) {\n\t\terrors.push(\"workspace.touchedFiles must be an array\");\n\t\treturn;\n\t}\n\tvalue.touchedFiles.forEach((entry, index) => {\n\t\tvalidateTouchedFile(entry, index, errors);\n\t});\n}\n\nfunction validateTool(value: unknown, errors: string[]): void {\n\tif (value === undefined) return;\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"tool must be an object when present\");\n\t\treturn;\n\t}\n\tif (typeof value.turnIndex !== \"number\" || !Number.isInteger(value.turnIndex) || value.turnIndex < 0) {\n\t\terrors.push(\"tool.turnIndex must be a non-negative integer\");\n\t}\n\tif (!Array.isArray(value.mutatingTools) || value.mutatingTools.some((t) => typeof t !== \"string\")) {\n\t\terrors.push(\"tool.mutatingTools must be an array of strings\");\n\t}\n\tif (value.beforeToolCallId !== undefined && typeof value.beforeToolCallId !== \"string\") {\n\t\terrors.push(\"tool.beforeToolCallId must be a string when present\");\n\t}\n\tif (value.afterToolCallId !== undefined && typeof value.afterToolCallId !== \"string\") {\n\t\terrors.push(\"tool.afterToolCallId must be a string when present\");\n\t}\n}\n\nfunction validateLedger(value: unknown, errors: string[]): void {\n\tif (!isPlainObject(value)) {\n\t\terrors.push(\"ledger must be an object\");\n\t\treturn;\n\t}\n\tif (!isNonEmptyString(value.eventId)) errors.push(\"ledger.eventId must be a non-empty string\");\n\tif (!isHex64(value.previousEventHash)) errors.push(\"ledger.previousEventHash must be a 64-char hex digest\");\n\tif (!isHex64(value.eventHash)) errors.push(\"ledger.eventHash must be a 64-char hex digest\");\n}\n\n/**\n * Validate an untrusted value as a {@link RecoveryCheckpoint}. Pure and\n * fail-closed: any structural problem yields `ok: false` with explicit errors\n * and no `checkpoint` payload.\n */\nexport function validateRecoveryCheckpoint(value: unknown): RecoveryCheckpointValidation {\n\tconst errors: string[] = [];\n\tif (!isPlainObject(value)) {\n\t\treturn { ok: false, errors: [\"checkpoint must be an object\"] };\n\t}\n\tif (value.schemaVersion !== RECOVERY_CHECKPOINT_SCHEMA_VERSION) {\n\t\terrors.push(`schemaVersion must be ${RECOVERY_CHECKPOINT_SCHEMA_VERSION}`);\n\t}\n\tif (!isNonEmptyString(value.checkpointId)) errors.push(\"checkpointId must be a non-empty string\");\n\tif (!isIsoTimestamp(value.createdAt)) errors.push(\"createdAt must be an ISO-8601 timestamp\");\n\tvalidateSession(value.session, errors);\n\tvalidateWorkspace(value.workspace, errors);\n\tvalidateTool(value.tool, errors);\n\tvalidateLedger(value.ledger, errors);\n\n\tif (errors.length > 0) return { ok: false, errors };\n\treturn { ok: true, errors: [], checkpoint: value as unknown as RecoveryCheckpoint };\n}\n\n/**\n * The ledger anchor as independently re-read from the hash-chained ledger.\n * Compared against the checkpoint's embedded anchor before any mutation.\n */\nexport interface ObservedLedgerAnchor {\n\treadonly eventId: string;\n\treadonly previousEventHash: string;\n\treadonly eventHash: string;\n}\n\nexport interface LedgerAnchorVerification {\n\treadonly ok: boolean;\n\treadonly mismatches: readonly string[];\n}\n\n/**\n * Compare a checkpoint's embedded ledger anchor with the anchor observed in the\n * live ledger. A mismatch means the checkpoint references an event that no\n * longer matches the durable audit trail (tamper or divergence) and the restore\n * must fail closed.\n */\nexport function verifyCheckpointLedgerAnchor(\n\tcheckpoint: RecoveryCheckpoint,\n\tobserved: ObservedLedgerAnchor,\n): LedgerAnchorVerification {\n\tconst mismatches: string[] = [];\n\tif (checkpoint.ledger.eventId !== observed.eventId) {\n\t\tmismatches.push(`eventId mismatch: checkpoint=${checkpoint.ledger.eventId} ledger=${observed.eventId}`);\n\t}\n\tif (checkpoint.ledger.previousEventHash !== observed.previousEventHash) {\n\t\tmismatches.push(\"previousEventHash mismatch between checkpoint and ledger\");\n\t}\n\tif (checkpoint.ledger.eventHash !== observed.eventHash) {\n\t\tmismatches.push(\"eventHash mismatch between checkpoint and ledger\");\n\t}\n\treturn { ok: mismatches.length === 0, mismatches };\n}\n\nexport interface ObservedTouchedFile {\n\treadonly path: string;\n\treadonly exists: boolean;\n\treadonly sha256?: string;\n\treadonly isSymlink?: boolean;\n\t/** True when the path (or its symlink target) resolves outside the repo root. */\n\treadonly escapesRepo?: boolean;\n}\n\nexport interface ObservedWorktree {\n\treadonly head?: string;\n\treadonly statusPorcelainSha256?: string;\n\t/** Current dirty paths (repo-relative) from `git status --porcelain`. */\n\treadonly dirtyPaths: readonly string[];\n\treadonly touchedFiles: readonly ObservedTouchedFile[];\n}\n\nexport interface RestorePreflightOptions {\n\t/** Allow restoring even though HEAD moved since the checkpoint. */\n\treadonly allowNonHeadRestore?: boolean;\n}\n\nexport type RestorePreflightVerdict = \"clean\" | \"blocked\";\n\nexport type RestorePreflightIssueCode =\n\t| \"unrelated-dirty-path\"\n\t| \"touched-hash-mismatch\"\n\t| \"missing-touched-file\"\n\t| \"symlink-escape\"\n\t| \"head-mismatch\";\n\nexport interface RestorePreflightIssue {\n\treadonly code: RestorePreflightIssueCode;\n\treadonly path?: string;\n\treadonly detail: string;\n}\n\nexport interface RestorePreflightResult {\n\treadonly verdict: RestorePreflightVerdict;\n\treadonly issues: readonly RestorePreflightIssue[];\n\treadonly unrelatedDirtyPaths: readonly string[];\n\treadonly hashMismatches: readonly string[];\n\treadonly symlinkEscapes: readonly string[];\n\treadonly headChanged: boolean;\n}\n\n/**\n * Classify whether a code restore can proceed against the live worktree.\n *\n * Fail-closed rules (from the lane C restore algorithm):\n * - any dirty path outside the recorded touched set blocks the restore;\n * - any touched file whose current hash differs from the recorded `afterSha256`\n * blocks the restore;\n * - any symlink escaping the repo root blocks the restore;\n * - a moved HEAD blocks the restore unless `allowNonHeadRestore` is set.\n */\nexport function classifyRestorePreflight(\n\tcheckpoint: RecoveryCheckpoint,\n\tobserved: ObservedWorktree,\n\toptions: RestorePreflightOptions = {},\n): RestorePreflightResult {\n\tconst issues: RestorePreflightIssue[] = [];\n\tconst touchedByPath = new Map<string, RecoveryTouchedFile>();\n\tfor (const file of checkpoint.workspace.touchedFiles) {\n\t\ttouchedByPath.set(normalizeRelPath(file.path), file);\n\t}\n\n\tconst unrelatedDirtyPaths: string[] = [];\n\tfor (const dirty of observed.dirtyPaths) {\n\t\tif (!touchedByPath.has(normalizeRelPath(dirty))) {\n\t\t\tunrelatedDirtyPaths.push(dirty);\n\t\t\tissues.push({\n\t\t\t\tcode: \"unrelated-dirty-path\",\n\t\t\t\tpath: dirty,\n\t\t\t\tdetail: \"dirty path is outside the checkpoint's recorded touched files\",\n\t\t\t});\n\t\t}\n\t}\n\n\tconst observedByPath = new Map<string, ObservedTouchedFile>();\n\tfor (const file of observed.touchedFiles) {\n\t\tobservedByPath.set(normalizeRelPath(file.path), file);\n\t}\n\n\tconst hashMismatches: string[] = [];\n\tconst symlinkEscapes: string[] = [];\n\tfor (const expected of checkpoint.workspace.touchedFiles) {\n\t\tconst key = normalizeRelPath(expected.path);\n\t\tconst current = observedByPath.get(key);\n\t\tif (!current) {\n\t\t\tissues.push({\n\t\t\t\tcode: \"missing-touched-file\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"no observed state was provided for a recorded touched file\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.escapesRepo === true || (current.isSymlink === true && current.escapesRepo !== false)) {\n\t\t\tsymlinkEscapes.push(expected.path);\n\t\t\tissues.push({\n\t\t\t\tcode: \"symlink-escape\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"touched path is a symlink resolving outside the repo root\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (expected.mode === \"deleted\") {\n\t\t\tif (current.exists) {\n\t\t\t\thashMismatches.push(expected.path);\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: \"touched-hash-mismatch\",\n\t\t\t\t\tpath: expected.path,\n\t\t\t\t\tdetail: \"expected a deleted file to be absent but it is present\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (!current.exists) {\n\t\t\tissues.push({\n\t\t\t\tcode: \"missing-touched-file\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"recorded touched file is missing from the worktree\",\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.sha256 !== expected.afterSha256) {\n\t\t\thashMismatches.push(expected.path);\n\t\t\tissues.push({\n\t\t\t\tcode: \"touched-hash-mismatch\",\n\t\t\t\tpath: expected.path,\n\t\t\t\tdetail: \"current file hash differs from the recorded post-edit hash\",\n\t\t\t});\n\t\t}\n\t}\n\n\tconst headChanged =\n\t\tcheckpoint.workspace.vcs === \"git\" &&\n\t\tcheckpoint.workspace.head !== undefined &&\n\t\tobserved.head !== undefined &&\n\t\tcheckpoint.workspace.head !== observed.head;\n\tif (headChanged && options.allowNonHeadRestore !== true) {\n\t\tissues.push({\n\t\t\tcode: \"head-mismatch\",\n\t\t\tdetail: \"HEAD moved since the checkpoint; pass allowNonHeadRestore to override\",\n\t\t});\n\t}\n\n\treturn {\n\t\tverdict: issues.length === 0 ? \"clean\" : \"blocked\",\n\t\tissues,\n\t\tunrelatedDirtyPaths,\n\t\thashMismatches,\n\t\tsymlinkEscapes,\n\t\theadChanged,\n\t};\n}\n\nexport type UntrackedDisposition = \"delete\" | \"quarantine\" | \"skip\";\n\nexport interface UntrackedDispositionDecision {\n\treadonly disposition: UntrackedDisposition;\n\treadonly reason: string;\n}\n\nexport interface ObservedUntrackedFile {\n\treadonly exists: boolean;\n\treadonly sha256?: string;\n}\n\n/**\n * Decide how an OMK-created untracked file should be handled on restore.\n *\n * - `skip`: the file is already gone, nothing to undo.\n * - `delete`: the file still exactly matches what OMK created, safe to remove.\n * - `quarantine`: the file changed since OMK created it; move it under the\n * recovery quarantine directory rather than destroying user edits.\n */\nexport function decideUntrackedDisposition(\n\ttouched: RecoveryTouchedFile,\n\tobserved: ObservedUntrackedFile,\n): UntrackedDispositionDecision {\n\tif (touched.mode !== \"untracked\") {\n\t\treturn { disposition: \"skip\", reason: \"disposition only applies to untracked files\" };\n\t}\n\tif (!observed.exists) {\n\t\treturn { disposition: \"skip\", reason: \"untracked file is already absent\" };\n\t}\n\tif (isHex64(touched.afterSha256) && observed.sha256 === touched.afterSha256) {\n\t\treturn { disposition: \"delete\", reason: \"current hash matches the OMK-created hash\" };\n\t}\n\treturn { disposition: \"quarantine\", reason: \"current hash differs from the OMK-created hash\" };\n}\n\nexport type RestoreMode = \"conversation\" | \"code\" | \"both\";\n\nexport type RestorePhaseKind = \"conversation\" | \"code\";\nexport type RestorePhaseAction = \"navigate-tree\" | \"apply-reverse-patch\";\n\nexport interface RestorePlanPhase {\n\treadonly phase: RestorePhaseKind;\n\treadonly action: RestorePhaseAction;\n\treadonly targetLeafId?: string | null;\n\treadonly recordedPaths?: readonly string[];\n}\n\nexport interface RestorePlan {\n\treadonly mode: RestoreMode;\n\treadonly status: \"ready\" | \"blocked\";\n\treadonly phases: readonly RestorePlanPhase[];\n\treadonly blockers: readonly string[];\n\t/** For `both`: the leaf to keep if the conversation phase fails after code restore. */\n\treadonly preservePreviousLeafId?: string | null;\n\treadonly inDoubtPolicy?: \"preserve-previous-leaf\";\n}\n\nexport interface PlanRestoreInput {\n\treadonly mode: RestoreMode;\n\treadonly checkpoint: RecoveryCheckpoint;\n\t/** Required for `code` and `both` modes. */\n\treadonly preflight?: RestorePreflightResult;\n\t/** The current session leaf, preserved for manual recovery in `both` mode. */\n\treadonly currentLeafId?: string | null;\n}\n\nfunction codePhase(checkpoint: RecoveryCheckpoint): RestorePlanPhase {\n\treturn {\n\t\tphase: \"code\",\n\t\taction: \"apply-reverse-patch\",\n\t\trecordedPaths: checkpoint.workspace.touchedFiles.map((file) => file.path),\n\t};\n}\n\nfunction conversationPhase(checkpoint: RecoveryCheckpoint): RestorePlanPhase {\n\treturn { phase: \"conversation\", action: \"navigate-tree\", targetLeafId: checkpoint.session.leafId };\n}\n\nfunction collectPreflightBlockers(preflight: RestorePreflightResult | undefined): string[] {\n\tif (!preflight) return [\"code restore requires a preflight classification\"];\n\tif (preflight.verdict === \"clean\") return [];\n\treturn preflight.issues.map((issue) => (issue.path ? `${issue.code}: ${issue.path}` : issue.code));\n}\n\n/**\n * Build a restore plan for the requested mode.\n *\n * - `conversation`: navigate the session tree to the checkpoint leaf; no file\n * writes, so no worktree preflight is required.\n * - `code`: apply the recorded reverse patch path-by-path; requires a clean\n * preflight.\n * - `both`: restore code first, then navigate the tree; requires a clean\n * preflight. If the second (conversation) phase fails at execution time the\n * caller marks the operation `in_doubt` and keeps `preservePreviousLeafId`.\n */\nexport function planRestore(input: PlanRestoreInput): RestorePlan {\n\tconst { mode, checkpoint, preflight } = input;\n\tif (mode === \"conversation\") {\n\t\treturn { mode, status: \"ready\", phases: [conversationPhase(checkpoint)], blockers: [] };\n\t}\n\n\tconst blockers = collectPreflightBlockers(preflight);\n\tif (mode === \"code\") {\n\t\tif (blockers.length > 0) return { mode, status: \"blocked\", phases: [], blockers };\n\t\treturn { mode, status: \"ready\", phases: [codePhase(checkpoint)], blockers: [] };\n\t}\n\n\t// mode === \"both\"\n\tconst preservePreviousLeafId = input.currentLeafId ?? null;\n\tif (blockers.length > 0) {\n\t\treturn {\n\t\t\tmode,\n\t\t\tstatus: \"blocked\",\n\t\t\tphases: [],\n\t\t\tblockers,\n\t\t\tpreservePreviousLeafId,\n\t\t\tinDoubtPolicy: \"preserve-previous-leaf\",\n\t\t};\n\t}\n\treturn {\n\t\tmode,\n\t\tstatus: \"ready\",\n\t\tphases: [codePhase(checkpoint), conversationPhase(checkpoint)],\n\t\tblockers: [],\n\t\tpreservePreviousLeafId,\n\t\tinDoubtPolicy: \"preserve-previous-leaf\",\n\t};\n}\n"]}
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import type { NetworkAccessRequest, PathAccessKind, SandboxDecision, SandboxPathResolver, SandboxPolicy } from "./sandbox/policy.ts";
|
|
2
|
-
export interface PathAccessRequestV2 {
|
|
3
|
-
readonly kind: PathAccessKind;
|
|
4
|
-
readonly path: string;
|
|
5
|
-
}
|
|
6
|
-
export interface PolicyDiagnostic {
|
|
7
|
-
readonly code: string;
|
|
8
|
-
readonly message: string;
|
|
9
|
-
readonly severity: "info" | "warn" | "block";
|
|
10
|
-
}
|
|
11
|
-
export interface PathDecisionV2 {
|
|
12
|
-
readonly requestedPath: string;
|
|
13
|
-
readonly candidate: string;
|
|
14
|
-
readonly kind: PathAccessKind;
|
|
15
|
-
readonly action: "allow" | "block";
|
|
16
|
-
readonly rule: string;
|
|
17
|
-
readonly reason: string;
|
|
18
|
-
readonly matchedPattern?: string;
|
|
19
|
-
}
|
|
20
|
-
export interface EnvDecisionV2 {
|
|
21
|
-
readonly action: "allow" | "block";
|
|
22
|
-
readonly rule: string;
|
|
23
|
-
readonly reason: string;
|
|
24
|
-
/** Denied variable NAMES only. Values are never recorded. */
|
|
25
|
-
readonly deniedNames: readonly string[];
|
|
26
|
-
}
|
|
27
|
-
export interface SandboxPolicyV2Decision {
|
|
28
|
-
readonly action: "allow" | "confirm" | "block";
|
|
29
|
-
readonly rule: string;
|
|
30
|
-
readonly reason: string;
|
|
31
|
-
readonly diagnostics: readonly PolicyDiagnostic[];
|
|
32
|
-
readonly pathDecisions: readonly PathDecisionV2[];
|
|
33
|
-
readonly networkDecision?: SandboxDecision;
|
|
34
|
-
readonly envDecision?: EnvDecisionV2;
|
|
35
|
-
}
|
|
36
|
-
export interface SandboxPolicyV2Input {
|
|
37
|
-
readonly policy: SandboxPolicy;
|
|
38
|
-
readonly pathRequests?: readonly PathAccessRequestV2[];
|
|
39
|
-
readonly networkRequest?: NetworkAccessRequest;
|
|
40
|
-
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
41
|
-
readonly resolver?: SandboxPathResolver;
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Public: evaluate path / env / network requests against a sandbox policy.
|
|
45
|
-
* Path and env checks are fail-closed. Audit mode downgrades a would-block
|
|
46
|
-
* outcome to confirm; enforce mode keeps it block.
|
|
47
|
-
*/
|
|
48
|
-
export declare function evaluateSandboxPolicyV2(input: SandboxPolicyV2Input): SandboxPolicyV2Decision;
|
|
49
|
-
//# sourceMappingURL=sandbox-policy-v2.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-policy-v2.d.ts","sourceRoot":"","sources":["../../src/core/sandbox-policy-v2.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACX,oBAAoB,EACpB,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,aAAa,EACb,MAAM,qBAAqB,CAAC;AA+D7B,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;CAC7C;AAED,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAA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ow: SIZE_OK - legacy evaluator; this change only keeps strip-only TypeScript compatibility.\n *\n * Pure fail-closed evaluator that composes path / env / network checks for a\n * sandbox policy. It layers general glob matching (via `minimatch`), realpath\n * normalization (when a resolver is provided), denied-env fail-closed\n * semantics, and IPv4 / IPv6 loopback detection on top of the existing\n * `SandboxPolicy` types. It does not spawn, resolve through the filesystem on\n * its own, or log env values.\n */\nimport path from \"node:path\";\nimport { minimatch } from \"minimatch\";\nimport type {\n\tNetworkAccessRequest,\n\tPathAccessKind,\n\tSandboxDecision,\n\tSandboxPathResolver,\n\tSandboxPolicy,\n} from \"./sandbox/policy.ts\";\n\n/** Exact sensitive environment variable names (do not end in a standard suffix). */\nconst SENSITIVE_ENV_EXACT = new Set<string>([\n\t\"AWS_ACCESS_KEY_ID\",\n\t\"AWS_SECRET_ACCESS_KEY\",\n\t\"AWS_SESSION_TOKEN\",\n\t\"GITHUB_TOKEN\",\n\t\"GH_TOKEN\",\n\t\"GITLAB_TOKEN\",\n\t\"NPM_TOKEN\",\n\t\"NODE_AUTH_TOKEN\",\n]);\n\n/** Sensitive environment variable name suffixes. */\nconst SENSITIVE_ENV_REGEX =\n\t/(^|_)(API_KEY|API_TOKEN|ACCESS_TOKEN|SECRET|SECRET_KEY|PRIVATE_KEY|PASSWORD|PASSWD|TOKEN)$/i;\n\n/**\n * Environment variable names that are always denied because they inject code\n * or redirect runtime loader behavior. Denial is fail-closed: presence of any\n * of these names blocks the policy evaluation regardless of value.\n */\nconst ENV_DENY_NAMES = new Set<string>([\n\t\"LD_PRELOAD\",\n\t\"LD_LIBRARY_PATH\",\n\t\"LD_AUDIT\",\n\t\"LD_BIND_NOW\",\n\t\"LD_PROFILE\",\n\t\"DYLD_INSERT_LIBRARIES\",\n\t\"DYLD_LIBRARY_PATH\",\n\t\"DYLD_FALLBACK_LIBRARY_PATH\",\n\t\"NODE_OPTIONS\",\n\t\"NODE_PATH\",\n\t\"NODE_REPL_EXTERNAL_MODULE\",\n\t\"NODE_EXTRA_CA_CERTS\",\n\t\"NODE_TLS_REJECT_UNAUTHORIZED\",\n\t\"PYTHONPATH\",\n\t\"PYTHONHOME\",\n\t\"PYTHONSTARTUP\",\n\t\"PYTHONINSPECT\",\n\t\"PERL5LIB\",\n\t\"PERLLIB\",\n\t\"PERL5OPT\",\n\t\"RUBYLIB\",\n\t\"RUBYOPT\",\n\t\"RUBYPATH\",\n\t\"JAVA_TOOL_OPTIONS\",\n\t\"_JAVA_OPTIONS\",\n\t\"JDK_JAVA_OPTIONS\",\n\t\"MAVEN_OPTS\",\n]);\n\n/**\n * Matches a URL / DSN with embedded userinfo (`scheme://user:pass@host`).\n * Used for value-based denial; only the variable NAME is ever recorded.\n */\nconst AUTH_URL_REGEX = /^[a-z][a-z0-9+.-]*:\\/\\/[^\\s/@:]+:[^\\s/@]+@[^\\s/@]/i;\n\n/** Path patterns that look like credential / key material on disk. */\nconst SENSITIVE_PATH_REGEX =\n\t/(?:^|[/\\\\])(?:\\.env(?:\\..*)?|auth\\.json|oauth\\.json|\\.netrc|\\.npmrc|\\.pgpass|credentials|id_rsa|id_dsa|id_ecdsa|id_ed25519|.*(?:token|private[_-]?key|credential).*)$/i;\n\nexport interface PathAccessRequestV2 {\n\treadonly kind: PathAccessKind;\n\treadonly path: string;\n}\n\nexport interface PolicyDiagnostic {\n\treadonly code: string;\n\treadonly message: string;\n\treadonly severity: \"info\" | \"warn\" | \"block\";\n}\n\nexport interface PathDecisionV2 {\n\treadonly requestedPath: string;\n\treadonly candidate: string;\n\treadonly kind: PathAccessKind;\n\treadonly action: \"allow\" | \"block\";\n\treadonly rule: string;\n\treadonly reason: string;\n\treadonly matchedPattern?: string;\n}\n\nexport interface EnvDecisionV2 {\n\treadonly action: \"allow\" | \"block\";\n\treadonly rule: string;\n\treadonly reason: string;\n\t/** Denied variable NAMES only. Values are never recorded. */\n\treadonly deniedNames: readonly string[];\n}\n\nexport interface SandboxPolicyV2Decision {\n\treadonly action: \"allow\" | \"confirm\" | \"block\";\n\treadonly rule: string;\n\treadonly reason: string;\n\treadonly diagnostics: readonly PolicyDiagnostic[];\n\treadonly pathDecisions: readonly PathDecisionV2[];\n\treadonly networkDecision?: SandboxDecision;\n\treadonly envDecision?: EnvDecisionV2;\n}\n\nexport interface SandboxPolicyV2Input {\n\treadonly policy: SandboxPolicy;\n\treadonly pathRequests?: readonly PathAccessRequestV2[];\n\treadonly networkRequest?: NetworkAccessRequest;\n\treadonly env?: Readonly<Record<string, string | undefined>>;\n\treadonly resolver?: SandboxPathResolver;\n}\n\nfunction isSensitiveEnvName(name: string): boolean {\n\tif (SENSITIVE_ENV_EXACT.has(name)) return true;\n\treturn SENSITIVE_ENV_REGEX.test(name);\n}\n\nfunction normalizePathValue(value: string): string {\n\tconst resolved = path.resolve(value);\n\tlet normalized = resolved.replace(/\\\\/g, \"/\");\n\tif (normalized.length > 1) normalized = normalized.replace(/\\/+$/, \"\");\n\treturn normalized;\n}\n\nfunction ruleHasGlob(pattern: string): boolean {\n\treturn /[*?[\\]{}]/.test(pattern);\n}\n\nfunction matchesRule(pattern: string, candidate: string): boolean {\n\tconst normPattern = normalizePathValue(pattern);\n\tconst normCandidate = normalizePathValue(candidate);\n\tif (ruleHasGlob(normPattern)) {\n\t\tif (minimatch(normCandidate, normPattern)) return true;\n\t\t// also accept recursive prefix form even if the writer omitted `/**`\n\t\treturn minimatch(normCandidate, `${normPattern}/**`);\n\t}\n\treturn normCandidate === normPattern || normCandidate.startsWith(`${normPattern}/`);\n}\n\nfunction matchesAny(patterns: readonly string[], candidate: string): { match: boolean; pattern?: string } {\n\tfor (const pattern of patterns) {\n\t\tif (matchesRule(pattern, candidate)) return { match: true, pattern };\n\t}\n\treturn { match: false };\n}\n\nfunction isInsideRoot(root: string, candidate: string): boolean {\n\tconst normRoot = normalizePathValue(root);\n\tconst normCandidate = normalizePathValue(candidate);\n\treturn normCandidate === normRoot || normCandidate.startsWith(`${normRoot}/`);\n}\n\nfunction isSensitivePath(value: string): boolean {\n\treturn SENSITIVE_PATH_REGEX.test(value.replace(/\\\\/g, \"/\"));\n}\n\n/** True for IPv4 / IPv6 loopback and localhost hostnames. */\nfunction isLoopbackHost(host: string): boolean {\n\tconst h = host\n\t\t.toLowerCase()\n\t\t.replace(/^\\[|\\]$/g, \"\")\n\t\t.trim();\n\tif (h === \"localhost\") return true;\n\tif (h === \"127.0.0.1\" || h === \"::1\" || h === \"0:0:0:0:0:0:0:1\") return true;\n\tif (h === \"::ffff:127.0.0.1\" || h === \"::ffff:7f00:1\") return true;\n\tif (/^127\\./.test(h)) return true;\n\treturn false;\n}\n\nfunction normalizeNetworkLoopback(request: NetworkAccessRequest): NetworkAccessRequest {\n\tlet host = request.host;\n\tif (!host && request.url) {\n\t\ttry {\n\t\t\thost = new URL(request.url).hostname;\n\t\t} catch {\n\t\t\thost = undefined;\n\t\t}\n\t}\n\tif (host && isLoopbackHost(host)) {\n\t\treturn { ...request, host, loopback: true };\n\t}\n\treturn request;\n}\n\nfunction hostFromRequest(request: NetworkAccessRequest): string | undefined {\n\tif (request.host) return request.host.toLowerCase();\n\tif (!request.url) return undefined;\n\ttry {\n\t\treturn new URL(request.url).hostname.toLowerCase();\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction hostMatches(patterns: readonly string[], host: string): boolean {\n\tconst h = host.replace(/\\.$/, \"\");\n\tfor (const raw of patterns) {\n\t\tconst p = raw.toLowerCase().replace(/\\.$/, \"\");\n\t\tif (h === p || h.endsWith(`.${p}`)) return true;\n\t}\n\treturn false;\n}\n\nfunction decideNetworkV2(policy: SandboxPolicy, request: NetworkAccessRequest): SandboxDecision {\n\tif (policy.mode === \"off\") return { allowed: true, rule: \"sandbox.off\", reason: \"Sandbox policy is disabled.\" };\n\tif (request.browser || request.unixSocketPath) {\n\t\treturn {\n\t\t\tallowed: false,\n\t\t\trule: \"network.socket_or_browser\",\n\t\t\treason: \"Browser and Unix socket access is denied by default.\",\n\t\t};\n\t}\n\tif (policy.network.mode === \"none\") {\n\t\treturn { allowed: false, rule: \"network.none\", reason: \"Network access is disabled by policy.\" };\n\t}\n\tif (request.loopback) {\n\t\tif (\n\t\t\tpolicy.network.mode === \"loopback\" ||\n\t\t\tpolicy.network.mode === \"domain-allowlist\" ||\n\t\t\tpolicy.network.mode === \"all-explicit\"\n\t\t) {\n\t\t\treturn { allowed: true, rule: \"network.loopback\", reason: \"Loopback access is allowed.\" };\n\t\t}\n\t\treturn { allowed: false, rule: \"network.loopback_denied\", reason: \"Loopback access is denied.\" };\n\t}\n\tconst host = hostFromRequest(request);\n\tif (!host)\n\t\treturn {\n\t\t\tallowed: false,\n\t\t\trule: \"network.unknown_host\",\n\t\t\treason: \"Network host could not be resolved from request.\",\n\t\t};\n\tif (hostMatches(policy.network.deniedDomains, host)) {\n\t\treturn { allowed: false, rule: \"network.domain_deny\", reason: \"Host matches a denied domain.\" };\n\t}\n\tif (policy.network.mode === \"all-explicit\") {\n\t\treturn {\n\t\t\tallowed: true,\n\t\t\trule: \"network.explicit_all\",\n\t\t\treason: \"Explicit network profile allows outbound host access.\",\n\t\t};\n\t}\n\tif (policy.network.mode === \"domain-allowlist\" && hostMatches(policy.network.allowedDomains, host)) {\n\t\treturn { allowed: true, rule: \"network.domain_allow\", reason: \"Host matches an allowed domain.\" };\n\t}\n\treturn { allowed: false, rule: \"network.domain_not_allowed\", reason: \"Host is not allowed by network policy.\" };\n}\n\nfunction decidePathV2(\n\tpolicy: SandboxPolicy,\n\trequest: PathAccessRequestV2,\n\tresolver: SandboxPathResolver | undefined,\n): PathDecisionV2 {\n\tconst requested = request.path;\n\tconst base = (\n\t\trule: string,\n\t\treason: string,\n\t\tcandidate: string,\n\t\taction: \"allow\" | \"block\",\n\t\tmatchedPattern?: string,\n\t): PathDecisionV2 => ({\n\t\trequestedPath: requested,\n\t\tcandidate,\n\t\tkind: request.kind,\n\t\taction,\n\t\trule,\n\t\treason,\n\t\tmatchedPattern,\n\t});\n\tconst block = (rule: string, reason: string, candidate: string, matchedPattern?: string): PathDecisionV2 =>\n\t\tbase(rule, reason, candidate, \"block\", matchedPattern);\n\tconst allow = (rule: string, reason: string, candidate: string): PathDecisionV2 =>\n\t\tbase(rule, reason, candidate, \"allow\");\n\n\tif (requested.includes(\"\\0\")) {\n\t\treturn block(\"path.invalid\", \"Path contains a NUL byte.\", requested);\n\t}\n\n\tlet candidate: string;\n\tlet isSymlink = false;\n\tif (resolver) {\n\t\tconst resolved = resolver(requested);\n\t\tif (resolved.error) {\n\t\t\treturn block(\"path.resolve_error\", resolved.error, requested);\n\t\t}\n\t\tcandidate = resolved.realPath ?? resolved.nearestExistingParentRealPath ?? normalizePathValue(requested);\n\t\tisSymlink = resolved.isSymlink === true;\n\t} else {\n\t\tcandidate = normalizePathValue(requested);\n\t}\n\n\tif (isSensitivePath(requested) || isSensitivePath(candidate)) {\n\t\treturn block(\"path.sensitive\", \"Sensitive credential-like path is denied.\", candidate);\n\t}\n\n\tif (!isInsideRoot(policy.filesystem.root, candidate)) {\n\t\treturn block(\"path.root_escape\", \"Resolved path is outside the sandbox root.\", candidate);\n\t}\n\n\tif (isSymlink && !policy.filesystem.followSymlinks) {\n\t\treturn block(\"path.symlink\", \"Symlink traversal is denied by policy.\", candidate);\n\t}\n\n\tif (request.kind === \"read\") {\n\t\tconst denied = matchesAny(policy.filesystem.readDeny, candidate);\n\t\tif (denied.match) {\n\t\t\treturn block(\"path.read_deny\", \"Read path matches a deny rule.\", candidate, denied.pattern);\n\t\t}\n\t\tconst deniedRequested = matchesAny(policy.filesystem.readDeny, requested);\n\t\tif (deniedRequested.match) {\n\t\t\treturn block(\"path.read_deny\", \"Read path matches a deny rule.\", candidate, deniedRequested.pattern);\n\t\t}\n\t\tif (matchesAny(policy.filesystem.readAllow, candidate).match) {\n\t\t\treturn allow(\"path.read_allow\", \"Read path is allowed.\", candidate);\n\t\t}\n\t\treturn block(\"path.read_not_allowed\", \"Read path is not in an allow rule.\", candidate);\n\t}\n\n\tconst denyWriteCandidate = matchesAny(policy.filesystem.denyWrite, candidate);\n\tif (denyWriteCandidate.match) {\n\t\treturn block(\n\t\t\t\"path.deny_write\",\n\t\t\t\"Write path matches an unoverrideable denyWrite rule.\",\n\t\t\tcandidate,\n\t\t\tdenyWriteCandidate.pattern,\n\t\t);\n\t}\n\tconst denyWriteRequested = matchesAny(policy.filesystem.denyWrite, requested);\n\tif (denyWriteRequested.match) {\n\t\treturn block(\n\t\t\t\"path.deny_write\",\n\t\t\t\"Write path matches an unoverrideable denyWrite rule.\",\n\t\t\tcandidate,\n\t\t\tdenyWriteRequested.pattern,\n\t\t);\n\t}\n\tif (\n\t\tmatchesAny(policy.filesystem.writeAllow, candidate).match ||\n\t\tmatchesAny(policy.filesystem.tempWrite, candidate).match\n\t) {\n\t\treturn allow(\"path.write_allow\", \"Write path is allowed.\", candidate);\n\t}\n\treturn block(\"path.write_not_allowed\", \"Write path is not in an allow rule.\", candidate);\n}\n\nfunction decideEnvV2(env: Readonly<Record<string, string | undefined>>): EnvDecisionV2 {\n\tconst denied: string[] = [];\n\tfor (const [name, value] of Object.entries(env)) {\n\t\tif (value === undefined) continue;\n\t\tif (ENV_DENY_NAMES.has(name)) {\n\t\t\tdenied.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isSensitiveEnvName(name)) {\n\t\t\tdenied.push(name);\n\t\t\tcontinue;\n\t\t}\n\t\tif (AUTH_URL_REGEX.test(value)) {\n\t\t\t// Value-based denial: the value embeds credentials. Record NAME only.\n\t\t\tdenied.push(name);\n\t\t}\n\t}\n\tif (denied.length > 0) {\n\t\treturn {\n\t\t\taction: \"block\",\n\t\t\trule: \"env.denied_pattern\",\n\t\t\treason: `Environment contains denied variable(s): ${denied.join(\", \")}.`,\n\t\t\tdeniedNames: denied,\n\t\t};\n\t}\n\treturn { action: \"allow\", rule: \"env.allow\", reason: \"No denied environment variables.\", deniedNames: [] };\n}\n\n/**\n * Public: evaluate path / env / network requests against a sandbox policy.\n * Path and env checks are fail-closed. Audit mode downgrades a would-block\n * outcome to confirm; enforce mode keeps it block.\n */\nexport function evaluateSandboxPolicyV2(input: SandboxPolicyV2Input): SandboxPolicyV2Decision {\n\tconst { policy } = input;\n\tconst diagnostics: PolicyDiagnostic[] = [];\n\tconst pathDecisions: PathDecisionV2[] = [];\n\tlet envDecision: EnvDecisionV2 | undefined;\n\tlet networkDecision: SandboxDecision | undefined;\n\tlet worst: \"allow\" | \"block\" = \"block\";\n\n\tif (policy.mode === \"off\") {\n\t\treturn {\n\t\t\taction: \"allow\",\n\t\t\trule: \"sandbox.off\",\n\t\t\treason: \"Sandbox policy is disabled.\",\n\t\t\tdiagnostics,\n\t\t\tpathDecisions,\n\t\t};\n\t}\n\n\t// Default to allow and escalate to block on any failed check.\n\tworst = \"allow\";\n\n\tif (input.env) {\n\t\tenvDecision = decideEnvV2(input.env);\n\t\tif (envDecision.action === \"block\") {\n\t\t\tworst = \"block\";\n\t\t\tdiagnostics.push({\n\t\t\t\tcode: envDecision.rule,\n\t\t\t\tmessage: `Denied env name(s): ${envDecision.deniedNames.join(\", \")}`,\n\t\t\t\tseverity: \"block\",\n\t\t\t});\n\t\t}\n\t}\n\n\tfor (const request of input.pathRequests ?? []) {\n\t\tconst decision = decidePathV2(policy, request, input.resolver);\n\t\tpathDecisions.push(decision);\n\t\tif (decision.action === \"block\") {\n\t\t\tworst = \"block\";\n\t\t\tdiagnostics.push({ code: decision.rule, message: decision.reason, severity: \"block\" });\n\t\t}\n\t}\n\n\tif (input.networkRequest) {\n\t\tconst normalized = normalizeNetworkLoopback(input.networkRequest);\n\t\tnetworkDecision = decideNetworkV2(policy, normalized);\n\t\tif (!networkDecision.allowed) {\n\t\t\tworst = \"block\";\n\t\t\tdiagnostics.push({ code: networkDecision.rule, message: networkDecision.reason, severity: \"block\" });\n\t\t}\n\t}\n\n\tlet action: \"allow\" | \"confirm\" | \"block\";\n\tlet rule: string;\n\tlet reason: string;\n\tif (worst === \"allow\") {\n\t\taction = \"allow\";\n\t\trule = \"policy.composite_allow\";\n\t\treason = \"All sandbox checks passed.\";\n\t} else if (policy.mode === \"audit\") {\n\t\taction = \"confirm\";\n\t\trule = \"policy.audit_block\";\n\t\treason = \"Audit mode: a would-block check is downgraded to confirm.\";\n\t} else {\n\t\taction = \"block\";\n\t\trule = \"policy.block\";\n\t\treason = \"One or more sandbox checks blocked the request.\";\n\t}\n\n\treturn { action, rule, reason, diagnostics, pathDecisions, networkDecision, envDecision };\n}\n"]}
|