open-multi-agent-kit 1.2.0 → 1.2.3
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 +54 -0
- package/README.md +2 -2
- package/dist/approval-api.d.ts +5 -0
- package/dist/approval-api.d.ts.map +1 -0
- package/dist/approval-api.js +5 -0
- package/dist/approval-api.js.map +1 -0
- package/dist/cli/session-picker.d.ts +2 -2
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/commands/verified-run-cli.d.ts.map +1 -1
- package/dist/commands/verified-run-cli.js +69 -22
- package/dist/commands/verified-run-cli.js.map +1 -1
- package/dist/commands/verified-run-signal.d.ts +3 -0
- package/dist/commands/verified-run-signal.d.ts.map +1 -0
- package/dist/commands/verified-run-signal.js +15 -0
- package/dist/commands/verified-run-signal.js.map +1 -0
- package/dist/coordination/broker.d.ts.map +1 -1
- package/dist/coordination/broker.js +13 -6
- package/dist/coordination/broker.js.map +1 -1
- package/dist/coordination/operation.d.ts +1 -0
- package/dist/coordination/operation.d.ts.map +1 -1
- package/dist/coordination/operation.js +55 -3
- package/dist/coordination/operation.js.map +1 -1
- package/dist/coordination/resource.d.ts +1 -1
- package/dist/coordination/resource.d.ts.map +1 -1
- package/dist/coordination/resource.js +10 -4
- package/dist/coordination/resource.js.map +1 -1
- package/dist/coordination/types.d.ts.map +1 -1
- package/dist/coordination/types.js +1 -1
- package/dist/coordination/types.js.map +1 -1
- package/dist/core/adaptorch-bridge.d.ts +1 -1
- package/dist/core/adaptorch-bridge.d.ts.map +1 -1
- package/dist/core/adaptorch-bridge.js +1 -1
- package/dist/core/adaptorch-bridge.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +16 -16
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +32 -33
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/canonical-json.d.ts +3 -0
- package/dist/core/canonical-json.d.ts.map +1 -0
- package/dist/core/canonical-json.js +20 -0
- package/dist/core/canonical-json.js.map +1 -0
- package/dist/core/compaction/compaction.d.ts +7 -3
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +14 -29
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/fallback.d.ts +16 -5
- package/dist/core/compaction/fallback.d.ts.map +1 -1
- package/dist/core/compaction/fallback.js +4 -3
- package/dist/core/compaction/fallback.js.map +1 -1
- package/dist/core/compaction/model-failover.d.ts +21 -0
- package/dist/core/compaction/model-failover.d.ts.map +1 -0
- package/dist/core/compaction/model-failover.js +46 -0
- package/dist/core/compaction/model-failover.js.map +1 -0
- package/dist/core/compaction/session-summary.d.ts +21 -0
- package/dist/core/compaction/session-summary.d.ts.map +1 -0
- package/dist/core/compaction/session-summary.js +27 -0
- package/dist/core/compaction/session-summary.js.map +1 -0
- package/dist/core/export-html/template.js +14 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/session-lifecycle-types.d.ts +14 -0
- package/dist/core/extensions/session-lifecycle-types.d.ts.map +1 -0
- package/dist/core/extensions/session-lifecycle-types.js +2 -0
- package/dist/core/extensions/session-lifecycle-types.js.map +1 -0
- package/dist/core/extensions/types.d.ts +4 -9
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +10 -1
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +3 -6
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/legacy-resource-policy.d.ts +7 -0
- package/dist/core/legacy-resource-policy.d.ts.map +1 -0
- package/dist/core/legacy-resource-policy.js +9 -0
- package/dist/core/legacy-resource-policy.js.map +1 -0
- package/dist/core/mcp/config.d.ts.map +1 -1
- package/dist/core/mcp/config.js +17 -3
- package/dist/core/mcp/config.js.map +1 -1
- package/dist/core/mcp/connection-queue.d.ts +12 -0
- package/dist/core/mcp/connection-queue.d.ts.map +1 -0
- package/dist/core/mcp/connection-queue.js +46 -0
- package/dist/core/mcp/connection-queue.js.map +1 -0
- package/dist/core/mcp/manager-runtime.d.ts +55 -0
- package/dist/core/mcp/manager-runtime.d.ts.map +1 -0
- package/dist/core/mcp/manager-runtime.js +66 -0
- package/dist/core/mcp/manager-runtime.js.map +1 -0
- package/dist/core/mcp/manager.d.ts +12 -68
- package/dist/core/mcp/manager.d.ts.map +1 -1
- package/dist/core/mcp/manager.js +33 -113
- package/dist/core/mcp/manager.js.map +1 -1
- package/dist/core/mcp/protocol.d.ts.map +1 -1
- package/dist/core/mcp/protocol.js +70 -40
- package/dist/core/mcp/protocol.js.map +1 -1
- package/dist/core/package-manager.d.ts +4 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +59 -129
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/package-resource-patterns.d.ts +7 -0
- package/dist/core/package-resource-patterns.d.ts.map +1 -0
- package/dist/core/package-resource-patterns.js +99 -0
- package/dist/core/package-resource-patterns.js.map +1 -0
- package/dist/core/provider-resilience.d.ts +9 -0
- package/dist/core/provider-resilience.d.ts.map +1 -1
- package/dist/core/provider-resilience.js +15 -0
- package/dist/core/provider-resilience.js.map +1 -1
- package/dist/core/reasoning-router-v4.d.ts +5 -2
- package/dist/core/reasoning-router-v4.d.ts.map +1 -1
- package/dist/core/reasoning-router-v4.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +4 -8
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-execution-api.d.ts +8 -1
- package/dist/core/run-execution-api.d.ts.map +1 -1
- package/dist/core/run-execution-api.js +4 -0
- package/dist/core/run-execution-api.js.map +1 -1
- package/dist/core/run-journal.d.ts +1 -2
- package/dist/core/run-journal.d.ts.map +1 -1
- package/dist/core/run-journal.js +2 -19
- package/dist/core/run-journal.js.map +1 -1
- package/dist/core/session-listing.d.ts +51 -0
- package/dist/core/session-listing.d.ts.map +1 -0
- package/dist/core/session-listing.js +111 -0
- package/dist/core/session-listing.js.map +1 -0
- package/dist/core/session-manager.d.ts +12 -37
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +12 -118
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-message-text.d.ts +5 -0
- package/dist/core/session-message-text.d.ts.map +1 -0
- package/dist/core/session-message-text.js +9 -0
- package/dist/core/session-message-text.js.map +1 -0
- package/dist/core/skills-catalog-cache.d.ts +2 -0
- package/dist/core/skills-catalog-cache.d.ts.map +1 -1
- package/dist/core/skills-catalog-cache.js +71 -17
- package/dist/core/skills-catalog-cache.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/verified-run/authority-clock.d.ts +3 -0
- package/dist/core/verified-run/authority-clock.d.ts.map +1 -0
- package/dist/core/verified-run/authority-clock.js +25 -0
- package/dist/core/verified-run/authority-clock.js.map +1 -0
- package/dist/core/verified-run/authority-errors.d.ts +10 -0
- package/dist/core/verified-run/authority-errors.d.ts.map +1 -0
- package/dist/core/verified-run/authority-errors.js +17 -0
- package/dist/core/verified-run/authority-errors.js.map +1 -0
- package/dist/core/verified-run/authority-events.d.ts +126 -0
- package/dist/core/verified-run/authority-events.d.ts.map +1 -0
- package/dist/core/verified-run/authority-events.js +482 -0
- package/dist/core/verified-run/authority-events.js.map +1 -0
- package/dist/core/verified-run/authority-journal.d.ts +27 -0
- package/dist/core/verified-run/authority-journal.d.ts.map +1 -0
- package/dist/core/verified-run/authority-journal.js +83 -0
- package/dist/core/verified-run/authority-journal.js.map +1 -0
- package/dist/core/verified-run/authority-meaning.d.ts +13 -0
- package/dist/core/verified-run/authority-meaning.d.ts.map +1 -0
- package/dist/core/verified-run/authority-meaning.js +40 -0
- package/dist/core/verified-run/authority-meaning.js.map +1 -0
- package/dist/core/verified-run/authority-runtime.d.ts +82 -0
- package/dist/core/verified-run/authority-runtime.d.ts.map +1 -0
- package/dist/core/verified-run/authority-runtime.js +169 -0
- package/dist/core/verified-run/authority-runtime.js.map +1 -0
- package/dist/core/verified-run/authority-store.d.ts +204 -0
- package/dist/core/verified-run/authority-store.d.ts.map +1 -0
- package/dist/core/verified-run/authority-store.js +852 -0
- package/dist/core/verified-run/authority-store.js.map +1 -0
- package/dist/core/verified-run/broker.d.ts +8 -1
- package/dist/core/verified-run/broker.d.ts.map +1 -1
- package/dist/core/verified-run/broker.js +94 -90
- package/dist/core/verified-run/broker.js.map +1 -1
- package/dist/core/verified-run/candidate-policy.d.ts +10 -0
- package/dist/core/verified-run/candidate-policy.d.ts.map +1 -0
- package/dist/core/verified-run/candidate-policy.js +33 -0
- package/dist/core/verified-run/candidate-policy.js.map +1 -0
- package/dist/core/verified-run/candidate.d.ts.map +1 -1
- package/dist/core/verified-run/candidate.js +5 -10
- package/dist/core/verified-run/candidate.js.map +1 -1
- package/dist/core/verified-run/coordinator.d.ts +35 -17
- package/dist/core/verified-run/coordinator.d.ts.map +1 -1
- package/dist/core/verified-run/coordinator.js +111 -57
- package/dist/core/verified-run/coordinator.js.map +1 -1
- package/dist/core/verified-run/dag-phase.d.ts.map +1 -1
- package/dist/core/verified-run/dag-phase.js +1 -1
- package/dist/core/verified-run/dag-phase.js.map +1 -1
- package/dist/core/verified-run/dag-recovery.d.ts +5 -1
- package/dist/core/verified-run/dag-recovery.d.ts.map +1 -1
- package/dist/core/verified-run/dag-recovery.js +10 -4
- package/dist/core/verified-run/dag-recovery.js.map +1 -1
- package/dist/core/verified-run/event-parser.d.ts.map +1 -1
- package/dist/core/verified-run/event-parser.js +33 -0
- package/dist/core/verified-run/event-parser.js.map +1 -1
- package/dist/core/verified-run/evidence-read-projection.d.ts +4 -0
- package/dist/core/verified-run/evidence-read-projection.d.ts.map +1 -0
- package/dist/core/verified-run/evidence-read-projection.js +27 -0
- package/dist/core/verified-run/evidence-read-projection.js.map +1 -0
- package/dist/core/verified-run/evidence.d.ts +12 -1
- package/dist/core/verified-run/evidence.d.ts.map +1 -1
- package/dist/core/verified-run/evidence.js +51 -2
- package/dist/core/verified-run/evidence.js.map +1 -1
- package/dist/core/verified-run/git-candidate-preflight.d.ts +4 -0
- package/dist/core/verified-run/git-candidate-preflight.d.ts.map +1 -0
- package/dist/core/verified-run/git-candidate-preflight.js +34 -0
- package/dist/core/verified-run/git-candidate-preflight.js.map +1 -0
- package/dist/core/verified-run/git-effect-supervisor.d.ts +24 -0
- package/dist/core/verified-run/git-effect-supervisor.d.ts.map +1 -0
- package/dist/core/verified-run/git-effect-supervisor.js +174 -0
- package/dist/core/verified-run/git-effect-supervisor.js.map +1 -0
- package/dist/core/verified-run/git-execution.d.ts +27 -0
- package/dist/core/verified-run/git-execution.d.ts.map +1 -0
- package/dist/core/verified-run/git-execution.js +118 -0
- package/dist/core/verified-run/git-execution.js.map +1 -0
- package/dist/core/verified-run/git-plumbing.d.ts +37 -0
- package/dist/core/verified-run/git-plumbing.d.ts.map +1 -0
- package/dist/core/verified-run/git-plumbing.js +171 -0
- package/dist/core/verified-run/git-plumbing.js.map +1 -0
- package/dist/core/verified-run/git-publication-worker.d.ts +2 -0
- package/dist/core/verified-run/git-publication-worker.d.ts.map +1 -0
- package/dist/core/verified-run/git-publication-worker.js +54 -0
- package/dist/core/verified-run/git-publication-worker.js.map +1 -0
- package/dist/core/verified-run/git-sandbox-layout.d.ts +4 -0
- package/dist/core/verified-run/git-sandbox-layout.d.ts.map +1 -0
- package/dist/core/verified-run/git-sandbox-layout.js +29 -0
- package/dist/core/verified-run/git-sandbox-layout.js.map +1 -0
- package/dist/core/verified-run/git-worker-protocol.d.ts +19 -0
- package/dist/core/verified-run/git-worker-protocol.d.ts.map +1 -0
- package/dist/core/verified-run/git-worker-protocol.js +109 -0
- package/dist/core/verified-run/git-worker-protocol.js.map +1 -0
- package/dist/core/verified-run/git-worker-runtime.d.ts +19 -0
- package/dist/core/verified-run/git-worker-runtime.d.ts.map +1 -0
- package/dist/core/verified-run/git-worker-runtime.js +74 -0
- package/dist/core/verified-run/git-worker-runtime.js.map +1 -0
- package/dist/core/verified-run/journal.d.ts +2 -3
- package/dist/core/verified-run/journal.d.ts.map +1 -1
- package/dist/core/verified-run/journal.js.map +1 -1
- package/dist/core/verified-run/namespace-identity.d.ts.map +1 -1
- package/dist/core/verified-run/namespace-identity.js +1 -1
- package/dist/core/verified-run/namespace-identity.js.map +1 -1
- package/dist/core/verified-run/owned-execution.d.ts +10 -1
- package/dist/core/verified-run/owned-execution.d.ts.map +1 -1
- package/dist/core/verified-run/owned-execution.js +124 -31
- package/dist/core/verified-run/owned-execution.js.map +1 -1
- package/dist/core/verified-run/phase-context.d.ts +2 -0
- package/dist/core/verified-run/phase-context.d.ts.map +1 -1
- package/dist/core/verified-run/phase-context.js.map +1 -1
- package/dist/core/verified-run/projection.d.ts.map +1 -1
- package/dist/core/verified-run/projection.js +51 -1
- package/dist/core/verified-run/projection.js.map +1 -1
- package/dist/core/verified-run/publish-preflight.d.ts +12 -0
- package/dist/core/verified-run/publish-preflight.d.ts.map +1 -0
- package/dist/core/verified-run/publish-preflight.js +38 -0
- package/dist/core/verified-run/publish-preflight.js.map +1 -0
- package/dist/core/verified-run/publish-start.d.ts +5 -0
- package/dist/core/verified-run/publish-start.d.ts.map +1 -0
- package/dist/core/verified-run/publish-start.js +7 -0
- package/dist/core/verified-run/publish-start.js.map +1 -0
- package/dist/core/verified-run/recovery-projection.d.ts.map +1 -1
- package/dist/core/verified-run/recovery-projection.js +5 -0
- package/dist/core/verified-run/recovery-projection.js.map +1 -1
- package/dist/core/verified-run/recovery.d.ts +5 -1
- package/dist/core/verified-run/recovery.d.ts.map +1 -1
- package/dist/core/verified-run/recovery.js +10 -4
- package/dist/core/verified-run/recovery.js.map +1 -1
- package/dist/core/verified-run/run-plan.d.ts +17 -0
- package/dist/core/verified-run/run-plan.d.ts.map +1 -0
- package/dist/core/verified-run/run-plan.js +18 -0
- package/dist/core/verified-run/run-plan.js.map +1 -0
- package/dist/core/verified-run/run-publish-owned.d.ts +6 -0
- package/dist/core/verified-run/run-publish-owned.d.ts.map +1 -0
- package/dist/core/verified-run/run-publish-owned.js +199 -0
- package/dist/core/verified-run/run-publish-owned.js.map +1 -0
- package/dist/core/verified-run/run-publish.d.ts +19 -0
- package/dist/core/verified-run/run-publish.d.ts.map +1 -0
- package/dist/core/verified-run/run-publish.js +210 -0
- package/dist/core/verified-run/run-publish.js.map +1 -0
- package/dist/core/verified-run/run-status-owned.d.ts +4 -0
- package/dist/core/verified-run/run-status-owned.d.ts.map +1 -0
- package/dist/core/verified-run/run-status-owned.js +14 -0
- package/dist/core/verified-run/run-status-owned.js.map +1 -0
- package/dist/core/verified-run/run-status.d.ts +133 -0
- package/dist/core/verified-run/run-status.d.ts.map +1 -0
- package/dist/core/verified-run/run-status.js +193 -0
- package/dist/core/verified-run/run-status.js.map +1 -0
- package/dist/core/verified-run/run-types.d.ts +31 -0
- package/dist/core/verified-run/run-types.d.ts.map +1 -1
- package/dist/core/verified-run/run-types.js.map +1 -1
- package/dist/core/verified-run/storage.d.ts.map +1 -1
- package/dist/core/verified-run/storage.js +1 -1
- package/dist/core/verified-run/storage.js.map +1 -1
- package/dist/core/verified-run/supervisor-adapter.d.ts +81 -0
- package/dist/core/verified-run/supervisor-adapter.d.ts.map +1 -0
- package/dist/core/verified-run/supervisor-adapter.js +168 -0
- package/dist/core/verified-run/supervisor-adapter.js.map +1 -0
- package/dist/core/verified-run/verification-phase.d.ts.map +1 -1
- package/dist/core/verified-run/verification-phase.js +1 -1
- package/dist/core/verified-run/verification-phase.js.map +1 -1
- package/dist/core/verified-run/writer-phase.d.ts.map +1 -1
- package/dist/core/verified-run/writer-phase.js +1 -0
- package/dist/core/verified-run/writer-phase.js.map +1 -1
- package/dist/core/verified-run/writer-recovery.d.ts +2 -0
- package/dist/core/verified-run/writer-recovery.d.ts.map +1 -1
- package/dist/core/verified-run/writer-recovery.js +1 -0
- package/dist/core/verified-run/writer-recovery.js.map +1 -1
- package/dist/core/workload-shard-execution-types.d.ts +4 -1
- package/dist/core/workload-shard-execution-types.d.ts.map +1 -1
- package/dist/core/workload-shard-execution-types.js.map +1 -1
- package/dist/core/workload-shard-executor.d.ts +2 -2
- package/dist/core/workload-shard-executor.d.ts.map +1 -1
- package/dist/core/workload-shard-executor.js +16 -37
- package/dist/core/workload-shard-executor.js.map +1 -1
- package/dist/core/workload-shard-frontier.d.ts +5 -0
- package/dist/core/workload-shard-frontier.d.ts.map +1 -0
- package/dist/core/workload-shard-frontier.js +47 -0
- package/dist/core/workload-shard-frontier.js.map +1 -0
- package/dist/core/workload-shard-runner.d.ts.map +1 -1
- package/dist/core/workload-shard-runner.js +28 -17
- package/dist/core/workload-shard-runner.js.map +1 -1
- package/dist/index.d.ts +2 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -4
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +2 -1
- package/dist/main.js.map +1 -1
- package/dist/metacognition/bridge-result.d.ts +148 -0
- package/dist/metacognition/bridge-result.d.ts.map +1 -0
- package/dist/metacognition/bridge-result.js +46 -0
- package/dist/metacognition/bridge-result.js.map +1 -0
- package/dist/metacognition/calibration-selective.d.ts.map +1 -1
- package/dist/metacognition/calibration-selective.js +8 -2
- package/dist/metacognition/calibration-selective.js.map +1 -1
- package/dist/metacognition/index.d.ts +1 -0
- package/dist/metacognition/index.d.ts.map +1 -1
- package/dist/metacognition/index.js +1 -0
- package/dist/metacognition/index.js.map +1 -1
- package/dist/metacognition/risk.d.ts.map +1 -1
- package/dist/metacognition/risk.js +28 -14
- package/dist/metacognition/risk.js.map +1 -1
- package/dist/metacognition/runtime-bridge.d.ts +41 -14
- package/dist/metacognition/runtime-bridge.d.ts.map +1 -1
- package/dist/metacognition/runtime-bridge.js +357 -39
- package/dist/metacognition/runtime-bridge.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +42 -26
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/chat-container.d.ts +7 -0
- package/dist/modes/interactive/components/chat-container.d.ts.map +1 -0
- package/dist/modes/interactive/components/chat-container.js +14 -0
- package/dist/modes/interactive/components/chat-container.js.map +1 -0
- package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
- package/dist/modes/interactive/components/dynamic-border.js +4 -2
- package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +0 -1
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-async-search.d.ts +33 -0
- package/dist/modes/interactive/components/session-selector-async-search.d.ts.map +1 -0
- package/dist/modes/interactive/components/session-selector-async-search.js +109 -0
- package/dist/modes/interactive/components/session-selector-async-search.js.map +1 -0
- package/dist/modes/interactive/components/session-selector-loaders.d.ts +6 -0
- package/dist/modes/interactive/components/session-selector-loaders.d.ts.map +1 -0
- package/dist/modes/interactive/components/session-selector-loaders.js +9 -0
- package/dist/modes/interactive/components/session-selector-loaders.js.map +1 -0
- package/dist/modes/interactive/components/session-selector-search.d.ts +1 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-tree.d.ts +16 -0
- package/dist/modes/interactive/components/session-selector-tree.d.ts.map +1 -0
- package/dist/modes/interactive/components/session-selector-tree.js +46 -0
- package/dist/modes/interactive/components/session-selector-tree.js.map +1 -0
- package/dist/modes/interactive/components/session-selector.d.ts +6 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +36 -76
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution-images.d.ts +32 -0
- package/dist/modes/interactive/components/tool-execution-images.d.ts.map +1 -0
- package/dist/modes/interactive/components/tool-execution-images.js +144 -0
- package/dist/modes/interactive/components/tool-execution-images.js.map +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts +3 -4
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +22 -71
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +7 -9
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/tui-diagnostics.d.ts +8 -4
- package/dist/modes/interactive/tui-diagnostics.d.ts.map +1 -1
- package/dist/modes/interactive/tui-diagnostics.js +35 -1
- package/dist/modes/interactive/tui-diagnostics.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +14 -17
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-response.d.ts +5 -0
- package/dist/modes/rpc/rpc-response.d.ts.map +1 -0
- package/dist/modes/rpc/rpc-response.js +17 -0
- package/dist/modes/rpc/rpc-response.js.map +1 -0
- package/dist/utils/exif-orientation.d.ts.map +1 -1
- package/dist/utils/exif-orientation.js +2 -3
- package/dist/utils/exif-orientation.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +3 -5
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/adaptorch-preview-spec.md +7 -7
- package/docs/atomic-commit-planning.md +69 -0
- package/docs/compaction.md +26 -1
- package/docs/extensions.md +14 -0
- package/docs/mcp.md +22 -0
- package/docs/metacognition.md +79 -0
- package/docs/model-catalog-refresh.md +159 -1
- package/docs/models.md +1 -1
- package/docs/runtime-algorithms.md +49 -4
- package/docs/session-format.md +8 -0
- package/docs/sessions.md +19 -0
- package/docs/skills.md +19 -0
- package/docs/terminal-setup.md +15 -0
- package/docs/tui.md +41 -0
- package/docs/verified-run-safety.md +75 -0
- package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
- 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/doom-overlay/wad-finder.ts +7 -3
- 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 +6 -8
|
@@ -72,7 +72,12 @@ export function temperatureScale(probabilities, temperature, epsilon = TEMPERATU
|
|
|
72
72
|
assertDistribution(probabilities);
|
|
73
73
|
ensure(typeof temperature === "number" && Number.isFinite(temperature) && temperature > 0, "temperature must be positive");
|
|
74
74
|
ensure(typeof epsilon === "number" && epsilon > 0 && epsilon < 1, "epsilon must be in (0,1)");
|
|
75
|
-
|
|
75
|
+
// Subtract before dividing so even the smallest positive T leaves exp(0) = 1.
|
|
76
|
+
const logs = probabilities.map((p) => Math.log(Math.max(p, epsilon)));
|
|
77
|
+
let maximum = Number.NEGATIVE_INFINITY;
|
|
78
|
+
for (const value of logs)
|
|
79
|
+
maximum = Math.max(maximum, value);
|
|
80
|
+
const raised = logs.map((value) => Math.exp((value - maximum) / temperature));
|
|
76
81
|
const total = raised.reduce((sum, value) => sum + value, 0);
|
|
77
82
|
ensure(total > 0 && Number.isFinite(total), "temperature scaling produced a degenerate distribution");
|
|
78
83
|
return raised.map((value) => value / total);
|
|
@@ -97,10 +102,11 @@ export function brierScore(forecasts, outcomes) {
|
|
|
97
102
|
export function negativeLogLoss(forecasts, outcomes, clip = LOG_LOSS_CLIP) {
|
|
98
103
|
assertBinaryPaired(forecasts, outcomes);
|
|
99
104
|
ensure(typeof clip === "number" && clip > 0 && clip < 0.5, "clip must be in (0,0.5)");
|
|
105
|
+
ensure(1 - clip < 1, "clip is too small to represent at the upper boundary");
|
|
100
106
|
let total = 0;
|
|
101
107
|
for (const [i, raw] of forecasts.entries()) {
|
|
102
108
|
const q = Math.min(1 - clip, Math.max(clip, raw));
|
|
103
|
-
total -= outcomes[i] === 1 ? Math.log(q) : Math.
|
|
109
|
+
total -= outcomes[i] === 1 ? Math.log(q) : Math.log1p(-q);
|
|
104
110
|
}
|
|
105
111
|
return total / forecasts.length;
|
|
106
112
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"calibration-selective.js","sourceRoot":"","sources":["../../src/metacognition/calibration-selective.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,4FAA4F;AAC5F,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,CAAC;AACzC,wEAAwE;AACxE,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC;AAYnC,SAAS,kBAAkB,CAAC,aAAgC,EAAQ;IACnE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,gCAAgC,CAAC,CAAC;IACnG,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,CAAC,IAAI,aAAa,EAAE,CAAC;QAC/B,MAAM,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CA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,IAAI,SAAS,IAAI,CAAC,IAAI,SAAS,IAAI,CAAC,EAC/F,4BAA4B,CAC5B,CAAC;IACF,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;QAC3C,IAAI,KAAK,GAAG,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,KAAK,IAAI;YAAE,SAAS;QAC3D,QAAQ,IAAI,CAAC,CAAC;QACd,IAAI,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,CAAC,CAAC;IACvC,CAAC;IACD,OAAO;QACN,QAAQ;QACR,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM;QAClC,IAAI,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,SAAS;KAClD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Probability calibration and selective execution (Jev audit algorithm A3).\n *\n * A provider's `confidence` is a statistic over its own option distribution,\n * not a calibrated probability of any event we care about. Before it can gate\n * execution, the predicted event has to be named — \"the chosen candidate was\n * appropriate\" is a different event from \"the driver executed it\" and from\n * \"the task succeeded\" — and the score has to be measured on held-out data.\n *\n * These are the measurement primitives, deliberately small: distribution\n * features, a post-hoc temperature rule, scoring rules, and a selective gate\n * that always reports coverage next to risk. None of them makes a score\n * trustworthy; they make it measurable.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nconst SUM_TOLERANCE = 1e-9;\n/** Floor for numeric zeros in temperature scaling; recorded so results are reproducible. */\nexport const TEMPERATURE_EPSILON = 1e-12;\n/** Clip for log loss so one confident miss does not return Infinity. */\nexport const LOG_LOSS_CLIP = 1e-15;\n\nexport interface DistributionFeatures {\n\treadonly maxProbability: number;\n\t/** p(1) − p(2). Undefined for a single candidate: there is nothing to compare. */\n\treadonly margin: number | undefined;\n\t/** Undefined for a single candidate, where entropy carries no information. */\n\treadonly normalizedEntropy: number | undefined;\n\treadonly candidateCount: number;\n\treadonly logCandidateCount: number;\n}\n\nfunction assertDistribution(probabilities: readonly number[]): void {\n\tensure(Array.isArray(probabilities) && probabilities.length > 0, \"distribution must be non-empty\");\n\tlet total = 0;\n\tfor (const p of probabilities) {\n\t\tensure(typeof p === \"number\" && Number.isFinite(p) && p >= 0 && p <= 1, \"each probability must be in [0,1]\");\n\t\ttotal += p;\n\t}\n\tensure(Math.abs(total - 1) <= SUM_TOLERANCE, \"distribution must sum to one\");\n}\n\n/**\n * Summary features of a candidate distribution.\n *\n * A single candidate can show probability 1 while telling you nothing about\n * whether that candidate is correct, so its margin and entropy are undefined\n * rather than maximally confident.\n */\nexport function distributionFeatures(probabilities: readonly number[]): DistributionFeatures {\n\tassertDistribution(probabilities);\n\tconst sorted = [...probabilities].sort((a, b) => b - a);\n\tconst count = probabilities.length;\n\tconst maxProbability = sorted[0] ?? 0;\n\tif (count === 1) {\n\t\treturn {\n\t\t\tmaxProbability,\n\t\t\tmargin: undefined,\n\t\t\tnormalizedEntropy: undefined,\n\t\t\tcandidateCount: 1,\n\t\t\tlogCandidateCount: 0,\n\t\t};\n\t}\n\t// 0·log0 is defined as 0; skipping the term is exactly that definition.\n\tlet entropy = 0;\n\tfor (const p of probabilities) if (p > 0) entropy -= p * Math.log(p);\n\treturn {\n\t\tmaxProbability,\n\t\tmargin: maxProbability - (sorted[1] ?? 0),\n\t\tnormalizedEntropy: entropy / Math.log(count),\n\t\tcandidateCount: count,\n\t\tlogCandidateCount: Math.log(count),\n\t};\n}\n\n/**\n * Post-hoc temperature rule: p̃(a) ∝ max(p(a), ε)^(1/T).\n *\n * T is fitted on a calibration split, never on the data being scored. This\n * does not assume the input came from a softmax; whether it helps has to be\n * measured separately.\n */\nexport function temperatureScale(\n\tprobabilities: readonly number[],\n\ttemperature: number,\n\tepsilon: number = TEMPERATURE_EPSILON,\n): number[] {\n\tassertDistribution(probabilities);\n\tensure(\n\t\ttypeof temperature === \"number\" && Number.isFinite(temperature) && temperature > 0,\n\t\t\"temperature must be positive\",\n\t);\n\tensure(typeof epsilon === \"number\" && epsilon > 0 && epsilon < 1, \"epsilon must be in (0,1)\");\n\tconst raised = probabilities.map((p) => Math.max(p, epsilon) ** (1 / temperature));\n\tconst total = raised.reduce((sum, value) => sum + value, 0);\n\tensure(total > 0 && Number.isFinite(total), \"temperature scaling produced a degenerate distribution\");\n\treturn raised.map((value) => value / total);\n}\n\nfunction assertBinaryPaired(forecasts: readonly number[], outcomes: readonly number[]): void {\n\tensure(Array.isArray(forecasts) && Array.isArray(outcomes), \"forecasts and outcomes must be arrays\");\n\tensure(forecasts.length === outcomes.length, \"forecasts and outcomes must align\");\n\tensure(forecasts.length > 0, \"at least one paired observation is required\");\n\tfor (const q of forecasts) {\n\t\tensure(typeof q === \"number\" && Number.isFinite(q) && q >= 0 && q <= 1, \"each forecast must be in [0,1]\");\n\t}\n\tfor (const y of outcomes) ensure(y === 0 || y === 1, \"each outcome must be 0 or 1\");\n}\n\nexport function brierScore(forecasts: readonly number[], outcomes: readonly number[]): number {\n\tassertBinaryPaired(forecasts, outcomes);\n\tlet total = 0;\n\tfor (const [i, q] of forecasts.entries()) total += (q - outcomes[i]!) ** 2;\n\treturn total / forecasts.length;\n}\n\nexport function negativeLogLoss(\n\tforecasts: readonly number[],\n\toutcomes: readonly number[],\n\tclip: number = LOG_LOSS_CLIP,\n): number {\n\tassertBinaryPaired(forecasts, outcomes);\n\tensure(typeof clip === \"number\" && clip > 0 && clip < 0.5, \"clip must be in (0,0.5)\");\n\tlet total = 0;\n\tfor (const [i, raw] of forecasts.entries()) {\n\t\tconst q = Math.min(1 - clip, Math.max(clip, raw));\n\t\ttotal -= outcomes[i] === 1 ? Math.log(q) : Math.log(1 - q);\n\t}\n\treturn total / forecasts.length;\n}\n\nexport interface CalibrationBin {\n\treadonly lower: number;\n\treadonly upper: number;\n\treadonly count: number;\n\treadonly accuracy: number | undefined;\n\treadonly confidence: number | undefined;\n}\n\nexport interface CalibrationReport {\n\treadonly error: number;\n\treadonly bins: readonly CalibrationBin[];\n\treadonly samples: number;\n}\n\n/**\n * Expected calibration error with its bin occupancy.\n *\n * ECE is sensitive to binning, so the bins and their counts are returned with\n * it: a near-zero error over three samples is not evidence of calibration.\n */\nexport function expectedCalibrationError(\n\tforecasts: readonly number[],\n\toutcomes: readonly number[],\n\tbinCount: number,\n): CalibrationReport {\n\tassertBinaryPaired(forecasts, outcomes);\n\tensure(Number.isSafeInteger(binCount) && binCount > 0, \"binCount must be a positive integer\");\n\tconst sums = Array.from({ length: binCount }, () => ({ count: 0, outcome: 0, forecast: 0 }));\n\tfor (const [i, q] of forecasts.entries()) {\n\t\tconst index = Math.min(binCount - 1, Math.floor(q * binCount));\n\t\tconst bin = sums[index]!;\n\t\tbin.count += 1;\n\t\tbin.outcome += outcomes[i]!;\n\t\tbin.forecast += q;\n\t}\n\tconst samples = forecasts.length;\n\tlet error = 0;\n\tconst bins = sums.map((bin, index) => {\n\t\tconst accuracy = bin.count > 0 ? bin.outcome / bin.count : undefined;\n\t\tconst confidence = bin.count > 0 ? bin.forecast / bin.count : undefined;\n\t\tif (accuracy !== undefined && confidence !== undefined) {\n\t\t\terror += (bin.count / samples) * Math.abs(accuracy - confidence);\n\t\t}\n\t\treturn { lower: index / binCount, upper: (index + 1) / binCount, count: bin.count, accuracy, confidence };\n\t});\n\treturn { error, bins, samples };\n}\n\nexport interface SelectiveExecutionReport {\n\treadonly admitted: number;\n\treadonly coverage: number;\n\t/** Undefined when nothing was admitted: that is unmeasurable, not risk-free. */\n\treadonly risk: number | undefined;\n}\n\n/**\n * Selective execution gate: a(τ) = 1[q̂ ≥ τ] · 1[G = 1].\n *\n * Risk and coverage are returned together because refusing everything drives\n * measured risk to zero while delivering nothing.\n */\nexport function selectiveExecution(\n\tscores: readonly number[],\n\tappropriate: readonly number[],\n\tthreshold: number,\n\tpolicyGates: readonly boolean[],\n): SelectiveExecutionReport {\n\tassertBinaryPaired(scores, appropriate);\n\tensure(policyGates.length === scores.length, \"policy gates must align with scores\");\n\tensure(\n\t\ttypeof threshold === \"number\" && Number.isFinite(threshold) && threshold >= 0 && threshold <= 1,\n\t\t\"threshold must be in [0,1]\",\n\t);\n\tlet admitted = 0;\n\tlet errors = 0;\n\tfor (const [i, score] of scores.entries()) {\n\t\tif (score < threshold || policyGates[i] !== true) continue;\n\t\tadmitted += 1;\n\t\tif (appropriate[i] === 0) errors += 1;\n\t}\n\treturn {\n\t\tadmitted,\n\t\tcoverage: admitted / scores.length,\n\t\trisk: admitted > 0 ? errors / admitted : undefined,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"calibration-selective.js","sourceRoot":"","sources":["../../src/metacognition/calibration-selective.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,4FAA4F;AAC5F,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,CAAC;AACzC,wEAAwE;AACxE,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC;AAYnC,SAAS,kBAAkB,CAAC,aAAgC,EAAQ;IACnE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,gCAAgC,CAAC,CAAC;IACnG,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,CAAC,IAAI,aAAa,EAAE,CAAC;QAC/B,MAAM,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,mCAAmC,CAAC,CAAC;QAC7G,KAAK,IAAI,CAAC,CAAC;IACZ,CAAC;IACD,MAAM,CAAC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B,WAA8B,EAC9B,SAAiB,EACjB,WAA+B,EACJ;IAC3B,kBAAkB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACxC,MAAM,CAAC,WAAW,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE,qCAAqC,CAAC,CAAC;IACpF,MAAM,CACL,OAAO,SAAS,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,SAAS,IAAI,CAAC,IAAI,SAAS,IAAI,CAAC,EAC/F,4BAA4B,CAC5B,CAAC;IACF,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;QAC3C,IAAI,KAAK,GAAG,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,KAAK,IAAI;YAAE,SAAS;QAC3D,QAAQ,IAAI,CAAC,CAAC;QACd,IAAI,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,CAAC,CAAC;IACvC,CAAC;IACD,OAAO;QACN,QAAQ;QACR,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM;QAClC,IAAI,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,SAAS;KAClD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Probability calibration and selective execution (Jev audit algorithm A3).\n *\n * A provider's `confidence` is a statistic over its own option distribution,\n * not a calibrated probability of any event we care about. Before it can gate\n * execution, the predicted event has to be named — \"the chosen candidate was\n * appropriate\" is a different event from \"the driver executed it\" and from\n * \"the task succeeded\" — and the score has to be measured on held-out data.\n *\n * These are the measurement primitives, deliberately small: distribution\n * features, a post-hoc temperature rule, scoring rules, and a selective gate\n * that always reports coverage next to risk. None of them makes a score\n * trustworthy; they make it measurable.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nconst SUM_TOLERANCE = 1e-9;\n/** Floor for numeric zeros in temperature scaling; recorded so results are reproducible. */\nexport const TEMPERATURE_EPSILON = 1e-12;\n/** Clip for log loss so one confident miss does not return Infinity. */\nexport const LOG_LOSS_CLIP = 1e-15;\n\nexport interface DistributionFeatures {\n\treadonly maxProbability: number;\n\t/** p(1) − p(2). Undefined for a single candidate: there is nothing to compare. */\n\treadonly margin: number | undefined;\n\t/** Undefined for a single candidate, where entropy carries no information. */\n\treadonly normalizedEntropy: number | undefined;\n\treadonly candidateCount: number;\n\treadonly logCandidateCount: number;\n}\n\nfunction assertDistribution(probabilities: readonly number[]): void {\n\tensure(Array.isArray(probabilities) && probabilities.length > 0, \"distribution must be non-empty\");\n\tlet total = 0;\n\tfor (const p of probabilities) {\n\t\tensure(typeof p === \"number\" && Number.isFinite(p) && p >= 0 && p <= 1, \"each probability must be in [0,1]\");\n\t\ttotal += p;\n\t}\n\tensure(Math.abs(total - 1) <= SUM_TOLERANCE, \"distribution must sum to one\");\n}\n\n/**\n * Summary features of a candidate distribution.\n *\n * A single candidate can show probability 1 while telling you nothing about\n * whether that candidate is correct, so its margin and entropy are undefined\n * rather than maximally confident.\n */\nexport function distributionFeatures(probabilities: readonly number[]): DistributionFeatures {\n\tassertDistribution(probabilities);\n\tconst sorted = [...probabilities].sort((a, b) => b - a);\n\tconst count = probabilities.length;\n\tconst maxProbability = sorted[0] ?? 0;\n\tif (count === 1) {\n\t\treturn {\n\t\t\tmaxProbability,\n\t\t\tmargin: undefined,\n\t\t\tnormalizedEntropy: undefined,\n\t\t\tcandidateCount: 1,\n\t\t\tlogCandidateCount: 0,\n\t\t};\n\t}\n\t// 0·log0 is defined as 0; skipping the term is exactly that definition.\n\tlet entropy = 0;\n\tfor (const p of probabilities) if (p > 0) entropy -= p * Math.log(p);\n\treturn {\n\t\tmaxProbability,\n\t\tmargin: maxProbability - (sorted[1] ?? 0),\n\t\tnormalizedEntropy: entropy / Math.log(count),\n\t\tcandidateCount: count,\n\t\tlogCandidateCount: Math.log(count),\n\t};\n}\n\n/**\n * Post-hoc temperature rule: p̃(a) ∝ max(p(a), ε)^(1/T).\n *\n * T is fitted on a calibration split, never on the data being scored. This\n * does not assume the input came from a softmax; whether it helps has to be\n * measured separately.\n */\nexport function temperatureScale(\n\tprobabilities: readonly number[],\n\ttemperature: number,\n\tepsilon: number = TEMPERATURE_EPSILON,\n): number[] {\n\tassertDistribution(probabilities);\n\tensure(\n\t\ttypeof temperature === \"number\" && Number.isFinite(temperature) && temperature > 0,\n\t\t\"temperature must be positive\",\n\t);\n\tensure(typeof epsilon === \"number\" && epsilon > 0 && epsilon < 1, \"epsilon must be in (0,1)\");\n\t// Subtract before dividing so even the smallest positive T leaves exp(0) = 1.\n\tconst logs = probabilities.map((p) => Math.log(Math.max(p, epsilon)));\n\tlet maximum = Number.NEGATIVE_INFINITY;\n\tfor (const value of logs) maximum = Math.max(maximum, value);\n\tconst raised = logs.map((value) => Math.exp((value - maximum) / temperature));\n\tconst total = raised.reduce((sum, value) => sum + value, 0);\n\tensure(total > 0 && Number.isFinite(total), \"temperature scaling produced a degenerate distribution\");\n\treturn raised.map((value) => value / total);\n}\n\nfunction assertBinaryPaired(forecasts: readonly number[], outcomes: readonly number[]): void {\n\tensure(Array.isArray(forecasts) && Array.isArray(outcomes), \"forecasts and outcomes must be arrays\");\n\tensure(forecasts.length === outcomes.length, \"forecasts and outcomes must align\");\n\tensure(forecasts.length > 0, \"at least one paired observation is required\");\n\tfor (const q of forecasts) {\n\t\tensure(typeof q === \"number\" && Number.isFinite(q) && q >= 0 && q <= 1, \"each forecast must be in [0,1]\");\n\t}\n\tfor (const y of outcomes) ensure(y === 0 || y === 1, \"each outcome must be 0 or 1\");\n}\n\nexport function brierScore(forecasts: readonly number[], outcomes: readonly number[]): number {\n\tassertBinaryPaired(forecasts, outcomes);\n\tlet total = 0;\n\tfor (const [i, q] of forecasts.entries()) total += (q - outcomes[i]!) ** 2;\n\treturn total / forecasts.length;\n}\n\nexport function negativeLogLoss(\n\tforecasts: readonly number[],\n\toutcomes: readonly number[],\n\tclip: number = LOG_LOSS_CLIP,\n): number {\n\tassertBinaryPaired(forecasts, outcomes);\n\tensure(typeof clip === \"number\" && clip > 0 && clip < 0.5, \"clip must be in (0,0.5)\");\n\tensure(1 - clip < 1, \"clip is too small to represent at the upper boundary\");\n\tlet total = 0;\n\tfor (const [i, raw] of forecasts.entries()) {\n\t\tconst q = Math.min(1 - clip, Math.max(clip, raw));\n\t\ttotal -= outcomes[i] === 1 ? Math.log(q) : Math.log1p(-q);\n\t}\n\treturn total / forecasts.length;\n}\n\nexport interface CalibrationBin {\n\treadonly lower: number;\n\treadonly upper: number;\n\treadonly count: number;\n\treadonly accuracy: number | undefined;\n\treadonly confidence: number | undefined;\n}\n\nexport interface CalibrationReport {\n\treadonly error: number;\n\treadonly bins: readonly CalibrationBin[];\n\treadonly samples: number;\n}\n\n/**\n * Expected calibration error with its bin occupancy.\n *\n * ECE is sensitive to binning, so the bins and their counts are returned with\n * it: a near-zero error over three samples is not evidence of calibration.\n */\nexport function expectedCalibrationError(\n\tforecasts: readonly number[],\n\toutcomes: readonly number[],\n\tbinCount: number,\n): CalibrationReport {\n\tassertBinaryPaired(forecasts, outcomes);\n\tensure(Number.isSafeInteger(binCount) && binCount > 0, \"binCount must be a positive integer\");\n\tconst sums = Array.from({ length: binCount }, () => ({ count: 0, outcome: 0, forecast: 0 }));\n\tfor (const [i, q] of forecasts.entries()) {\n\t\tconst index = Math.min(binCount - 1, Math.floor(q * binCount));\n\t\tconst bin = sums[index]!;\n\t\tbin.count += 1;\n\t\tbin.outcome += outcomes[i]!;\n\t\tbin.forecast += q;\n\t}\n\tconst samples = forecasts.length;\n\tlet error = 0;\n\tconst bins = sums.map((bin, index) => {\n\t\tconst accuracy = bin.count > 0 ? bin.outcome / bin.count : undefined;\n\t\tconst confidence = bin.count > 0 ? bin.forecast / bin.count : undefined;\n\t\tif (accuracy !== undefined && confidence !== undefined) {\n\t\t\terror += (bin.count / samples) * Math.abs(accuracy - confidence);\n\t\t}\n\t\treturn { lower: index / binCount, upper: (index + 1) / binCount, count: bin.count, accuracy, confidence };\n\t});\n\treturn { error, bins, samples };\n}\n\nexport interface SelectiveExecutionReport {\n\treadonly admitted: number;\n\treadonly coverage: number;\n\t/** Undefined when nothing was admitted: that is unmeasurable, not risk-free. */\n\treadonly risk: number | undefined;\n}\n\n/**\n * Selective execution gate: a(τ) = 1[q̂ ≥ τ] · 1[G = 1].\n *\n * Risk and coverage are returned together because refusing everything drives\n * measured risk to zero while delivering nothing.\n */\nexport function selectiveExecution(\n\tscores: readonly number[],\n\tappropriate: readonly number[],\n\tthreshold: number,\n\tpolicyGates: readonly boolean[],\n): SelectiveExecutionReport {\n\tassertBinaryPaired(scores, appropriate);\n\tensure(policyGates.length === scores.length, \"policy gates must align with scores\");\n\tensure(\n\t\ttypeof threshold === \"number\" && Number.isFinite(threshold) && threshold >= 0 && threshold <= 1,\n\t\t\"threshold must be in [0,1]\",\n\t);\n\tlet admitted = 0;\n\tlet errors = 0;\n\tfor (const [i, score] of scores.entries()) {\n\t\tif (score < threshold || policyGates[i] !== true) continue;\n\t\tadmitted += 1;\n\t\tif (appropriate[i] === 0) errors += 1;\n\t}\n\treturn {\n\t\tadmitted,\n\t\tcoverage: admitted / scores.length,\n\t\trisk: admitted > 0 ? errors / admitted : undefined,\n\t};\n}\n"]}
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* Host-owned state only; no model output is ever treated as runner truth,
|
|
7
7
|
* and learned scores never relax a required approval or check.
|
|
8
8
|
*/
|
|
9
|
+
export * from "./bridge-result.ts";
|
|
9
10
|
export * from "./calibration.ts";
|
|
10
11
|
export * from "./calibration-selective.ts";
|
|
11
12
|
export * from "./checkpoint.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/metacognition/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC","sourcesContent":["/**\n * Metacognitive control kernel for OMK.\n *\n * Pure, deterministic, bounded modules implementing the observation /\n * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.\n * Host-owned state only; no model output is ever treated as runner truth,\n * and learned scores never relax a required approval or check.\n */\n\nexport * from \"./calibration.ts\";\nexport * from \"./calibration-selective.ts\";\nexport * from \"./checkpoint.ts\";\nexport * from \"./context7.ts\";\nexport * from \"./decision.ts\";\nexport * from \"./evaluation.ts\";\nexport * from \"./knowledge.ts\";\nexport * from \"./knowledge-action.ts\";\nexport * from \"./obligations.ts\";\nexport * from \"./observation-validity.ts\";\nexport * from \"./observe.ts\";\nexport * from \"./policy.ts\";\nexport * from \"./predictions.ts\";\nexport * from \"./retrieval.ts\";\nexport * from \"./risk.ts\";\nexport * from \"./route-economics.ts\";\nexport * from \"./runtime-bridge.ts\";\nexport * from \"./skills.ts\";\nexport * from \"./state.ts\";\nexport * from \"./validation.ts\";\nexport * from \"./verification.ts\";\nexport * from \"./verifier.ts\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/metacognition/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC","sourcesContent":["/**\n * Metacognitive control kernel for OMK.\n *\n * Pure, deterministic, bounded modules implementing the observation /\n * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.\n * Host-owned state only; no model output is ever treated as runner truth,\n * and learned scores never relax a required approval or check.\n */\n\nexport * from \"./bridge-result.ts\";\nexport * from \"./calibration.ts\";\nexport * from \"./calibration-selective.ts\";\nexport * from \"./checkpoint.ts\";\nexport * from \"./context7.ts\";\nexport * from \"./decision.ts\";\nexport * from \"./evaluation.ts\";\nexport * from \"./knowledge.ts\";\nexport * from \"./knowledge-action.ts\";\nexport * from \"./obligations.ts\";\nexport * from \"./observation-validity.ts\";\nexport * from \"./observe.ts\";\nexport * from \"./policy.ts\";\nexport * from \"./predictions.ts\";\nexport * from \"./retrieval.ts\";\nexport * from \"./risk.ts\";\nexport * from \"./route-economics.ts\";\nexport * from \"./runtime-bridge.ts\";\nexport * from \"./skills.ts\";\nexport * from \"./state.ts\";\nexport * from \"./validation.ts\";\nexport * from \"./verification.ts\";\nexport * from \"./verifier.ts\";\n"]}
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* Host-owned state only; no model output is ever treated as runner truth,
|
|
7
7
|
* and learned scores never relax a required approval or check.
|
|
8
8
|
*/
|
|
9
|
+
export * from "./bridge-result.js";
|
|
9
10
|
export * from "./calibration.js";
|
|
10
11
|
export * from "./calibration-selective.js";
|
|
11
12
|
export * from "./checkpoint.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/metacognition/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC","sourcesContent":["/**\n * Metacognitive control kernel for OMK.\n *\n * Pure, deterministic, bounded modules implementing the observation /\n * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.\n * Host-owned state only; no model output is ever treated as runner truth,\n * and learned scores never relax a required approval or check.\n */\n\nexport * from \"./calibration.ts\";\nexport * from \"./calibration-selective.ts\";\nexport * from \"./checkpoint.ts\";\nexport * from \"./context7.ts\";\nexport * from \"./decision.ts\";\nexport * from \"./evaluation.ts\";\nexport * from \"./knowledge.ts\";\nexport * from \"./knowledge-action.ts\";\nexport * from \"./obligations.ts\";\nexport * from \"./observation-validity.ts\";\nexport * from \"./observe.ts\";\nexport * from \"./policy.ts\";\nexport * from \"./predictions.ts\";\nexport * from \"./retrieval.ts\";\nexport * from \"./risk.ts\";\nexport * from \"./route-economics.ts\";\nexport * from \"./runtime-bridge.ts\";\nexport * from \"./skills.ts\";\nexport * from \"./state.ts\";\nexport * from \"./validation.ts\";\nexport * from \"./verification.ts\";\nexport * from \"./verifier.ts\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/metacognition/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC","sourcesContent":["/**\n * Metacognitive control kernel for OMK.\n *\n * Pure, deterministic, bounded modules implementing the observation /\n * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.\n * Host-owned state only; no model output is ever treated as runner truth,\n * and learned scores never relax a required approval or check.\n */\n\nexport * from \"./bridge-result.ts\";\nexport * from \"./calibration.ts\";\nexport * from \"./calibration-selective.ts\";\nexport * from \"./checkpoint.ts\";\nexport * from \"./context7.ts\";\nexport * from \"./decision.ts\";\nexport * from \"./evaluation.ts\";\nexport * from \"./knowledge.ts\";\nexport * from \"./knowledge-action.ts\";\nexport * from \"./obligations.ts\";\nexport * from \"./observation-validity.ts\";\nexport * from \"./observe.ts\";\nexport * from \"./policy.ts\";\nexport * from \"./predictions.ts\";\nexport * from \"./retrieval.ts\";\nexport * from \"./risk.ts\";\nexport * from \"./route-economics.ts\";\nexport * from \"./runtime-bridge.ts\";\nexport * from \"./skills.ts\";\nexport * from \"./state.ts\";\nexport * from \"./validation.ts\";\nexport * from \"./verification.ts\";\nexport * from \"./verifier.ts\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"risk.d.ts","sourceRoot":"","sources":["../../src/metacognition/risk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAyDH,4CAA4C;AAC5C,wBAAgB,yBAAyB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"risk.d.ts","sourceRoot":"","sources":["../../src/metacognition/risk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAyDH,4CAA4C;AAC5C,wBAAgB,yBAAyB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAYjF;AAuBD;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAUhG;AAED,4EAA4E;AAC5E,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAI3E;AAED;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,aAAa,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAUtF;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CASzF;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAWnE","sourcesContent":["/**\n * Finite-sample risk bounds for automation gating (Jev audit algorithm A4).\n *\n * A point estimate must never widen automation scope. Two failures in a\n * hundred is not \"a 2% error rate\" — its one-sided 95% Clopper–Pearson upper\n * bound is about 6.2%, and that bound is what a gate reads.\n *\n * Scope: this bounds the failure probability of samples drawn under the stated\n * conditions. It is not a safety guarantee for the next action, and it assumes\n * a fixed policy, a consistent failure event, and adequately independent\n * samples. Three hundred repeated clicks inside one task are not three hundred\n * independent trials; cluster by task or environment instance before using it.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nconst LANCZOS_G = 7;\nconst LANCZOS_COEFFICIENTS = [\n\t0.999_999_999_999_809_93, 676.520_368_121_885_1, -1259.139_216_722_402_8, 771.323_428_777_653_13,\n\t-176.615_029_162_140_59, 12.507_343_278_686_905, -0.138_571_095_265_720_12, 9.984_369_578_019_571_6e-6,\n\t1.505_632_735_149_311_6e-7,\n] as const;\n\nfunction logGamma(x: number): number {\n\tif (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);\n\tconst z = x - 1;\n\tlet a = LANCZOS_COEFFICIENTS[0];\n\tconst t = z + LANCZOS_G + 0.5;\n\tfor (const [index, coefficient] of LANCZOS_COEFFICIENTS.entries()) {\n\t\tif (index > 0) a += coefficient / (z + index);\n\t}\n\treturn 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(a);\n}\n\n/** Continued-fraction expansion for the incomplete beta (Lentz's method). */\nfunction betaContinuedFraction(a: number, b: number, x: number): number {\n\tconst maxIterations = 1000;\n\tconst epsilon = 1e-14;\n\tconst tiny = 1e-300;\n\tconst qab = a + b;\n\tconst qap = a + 1;\n\tconst qam = a - 1;\n\tlet c = 1;\n\tlet d = 1 - (qab * x) / qap;\n\tif (Math.abs(d) < tiny) d = tiny;\n\td = 1 / d;\n\tlet h = d;\n\tfor (let m = 1; m <= maxIterations; m += 1) {\n\t\tconst m2 = 2 * m;\n\t\tlet aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\th *= d * c;\n\t\taa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\tconst delta = d * c;\n\t\th *= delta;\n\t\tif (Math.abs(delta - 1) < epsilon && Number.isFinite(h)) return h;\n\t}\n\tthrow new RangeError(\"incomplete beta failed to converge\");\n}\n\n/** Regularized incomplete beta I_x(a,b). */\nexport function regularizedIncompleteBeta(a: number, b: number, x: number): number {\n\tensure(Number.isFinite(a) && a > 0 && Number.isFinite(b) && b > 0 && Number.isFinite(a + b), \"invalid beta shapes\");\n\tensure(Number.isFinite(x) && x >= 0 && x <= 1, \"beta x must be in [0,1]\");\n\tif (x <= 0) return 0;\n\tif (x >= 1) return 1;\n\tconst front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));\n\tconst result =\n\t\tx < (a + 1) / (a + b + 2)\n\t\t\t? (front * betaContinuedFraction(a, b, x)) / a\n\t\t\t: 1 - (front * betaContinuedFraction(b, a, 1 - x)) / b;\n\tif (!Number.isFinite(result) || result < 0 || result > 1) throw new RangeError(\"invalid incomplete beta result\");\n\treturn result;\n}\n\n/** Invert the survival probability directly; never round 1-alpha to one. */\nfunction betaUpperQuantile(alpha: number, a: number, b: number): number {\n\tlet low = 0;\n\tlet high = 1;\n\tfor (let i = 0; i < 200; i += 1) {\n\t\tconst mid = low + (high - low) / 2;\n\t\tif (mid === low || mid === high) break;\n\t\tif (regularizedIncompleteBeta(b, a, 1 - mid) > alpha) low = mid;\n\t\telse high = mid;\n\t}\n\t// Upper endpoint of the numerical bracket, not an interval-arithmetic proof.\n\treturn high;\n}\n\nfunction assertAlpha(alpha: number): void {\n\tensure(\n\t\ttypeof alpha === \"number\" && Number.isFinite(alpha) && alpha > 0 && alpha < 1,\n\t\t\"alpha must be a probability strictly between 0 and 1\",\n\t);\n}\n\n/**\n * One-sided Clopper–Pearson upper bound on the failure probability.\n *\n * `U(k,n) = Beta⁻¹(1−α; k+1, n−k)` for `0 ≤ k < n`, and `1` when every trial\n * failed. Zero trials is not zero risk: it is absent evidence, so it throws.\n */\nexport function clopperPearsonUpperBound(failures: number, trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tensure(\n\t\tNumber.isSafeInteger(failures) && failures >= 0 && failures <= trials,\n\t\t\"failures must be an integer in [0, trials]\",\n\t);\n\tassertAlpha(alpha);\n\tif (failures === trials) return 1;\n\tif (failures === 0) return zeroFailureUpperBound(trials, alpha);\n\treturn betaUpperQuantile(alpha, failures + 1, trials - failures);\n}\n\n/** Closed form of {@link clopperPearsonUpperBound} when no trial failed. */\nexport function zeroFailureUpperBound(trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tassertAlpha(alpha);\n\treturn -Math.expm1(Math.log(alpha) / trials);\n}\n\n/**\n * Smallest failure-free sample size whose upper bound meets `targetEpsilon`.\n *\n * `n ≥ ⌈log α / log(1−ε)⌉`, then nudged against the bound itself so a\n * floating-point boundary cannot return a sample size that misses the target.\n */\nexport function minimumZeroFailureSamples(targetEpsilon: number, alpha: number): number {\n\tensure(\n\t\ttypeof targetEpsilon === \"number\" && Number.isFinite(targetEpsilon) && targetEpsilon > 0 && targetEpsilon < 1,\n\t\t\"targetEpsilon must be strictly between 0 and 1\",\n\t);\n\tassertAlpha(alpha);\n\tlet n = Math.max(1, Math.ceil(Math.log(alpha) / Math.log1p(-targetEpsilon)));\n\twhile (zeroFailureUpperBound(n, alpha) > targetEpsilon) n += 1;\n\twhile (n > 1 && zeroFailureUpperBound(n - 1, alpha) <= targetEpsilon) n -= 1;\n\treturn n;\n}\n\n/**\n * Bonferroni split for `thresholds × groups` comparisons on one validation set.\n *\n * Searching many thresholds and reporting the best keeps none of a single\n * interval's nominal guarantee; this is the conservative correction, and it\n * raises the required sample size on purpose.\n */\nexport function bonferroniAlpha(alpha: number, thresholds: number, groups: number): number {\n\tassertAlpha(alpha);\n\tensure(Number.isSafeInteger(thresholds) && thresholds > 0, \"thresholds must be a positive integer\");\n\tensure(Number.isSafeInteger(groups) && groups > 0, \"groups must be a positive integer\");\n\tconst comparisons = thresholds * groups;\n\tensure(Number.isSafeInteger(comparisons), \"comparison count overflow\");\n\tconst adjusted = alpha / comparisons;\n\tensure(adjusted > 0 && Number.isFinite(adjusted), \"adjusted alpha underflow\");\n\treturn adjusted;\n}\n\n/**\n * Union bound over per-step failure risks.\n *\n * Holds without any independence assumption, which is the point: step risks in\n * one task are usually correlated, so multiplying them would understate the\n * whole-task risk.\n */\nexport function unionBoundRisk(stepRisks: readonly number[]): number {\n\tensure(Array.isArray(stepRisks) && stepRisks.length > 0, \"stepRisks must be a non-empty array\");\n\tlet total = 0;\n\tfor (const risk of stepRisks) {\n\t\tensure(\n\t\t\ttypeof risk === \"number\" && Number.isFinite(risk) && risk >= 0 && risk <= 1,\n\t\t\t\"each step risk must be a probability in [0, 1]\",\n\t\t);\n\t\ttotal += risk;\n\t}\n\treturn Math.min(1, total);\n}\n"]}
|
|
@@ -32,8 +32,8 @@ function logGamma(x) {
|
|
|
32
32
|
}
|
|
33
33
|
/** Continued-fraction expansion for the incomplete beta (Lentz's method). */
|
|
34
34
|
function betaContinuedFraction(a, b, x) {
|
|
35
|
-
const maxIterations =
|
|
36
|
-
const epsilon =
|
|
35
|
+
const maxIterations = 1000;
|
|
36
|
+
const epsilon = 1e-14;
|
|
37
37
|
const tiny = 1e-300;
|
|
38
38
|
const qab = a + b;
|
|
39
39
|
const qap = a + 1;
|
|
@@ -65,34 +65,42 @@ function betaContinuedFraction(a, b, x) {
|
|
|
65
65
|
d = 1 / d;
|
|
66
66
|
const delta = d * c;
|
|
67
67
|
h *= delta;
|
|
68
|
-
if (Math.abs(delta - 1) < epsilon)
|
|
69
|
-
|
|
68
|
+
if (Math.abs(delta - 1) < epsilon && Number.isFinite(h))
|
|
69
|
+
return h;
|
|
70
70
|
}
|
|
71
|
-
|
|
71
|
+
throw new RangeError("incomplete beta failed to converge");
|
|
72
72
|
}
|
|
73
73
|
/** Regularized incomplete beta I_x(a,b). */
|
|
74
74
|
export function regularizedIncompleteBeta(a, b, x) {
|
|
75
|
+
ensure(Number.isFinite(a) && a > 0 && Number.isFinite(b) && b > 0 && Number.isFinite(a + b), "invalid beta shapes");
|
|
76
|
+
ensure(Number.isFinite(x) && x >= 0 && x <= 1, "beta x must be in [0,1]");
|
|
75
77
|
if (x <= 0)
|
|
76
78
|
return 0;
|
|
77
79
|
if (x >= 1)
|
|
78
80
|
return 1;
|
|
79
81
|
const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));
|
|
80
|
-
|
|
82
|
+
const result = x < (a + 1) / (a + b + 2)
|
|
81
83
|
? (front * betaContinuedFraction(a, b, x)) / a
|
|
82
84
|
: 1 - (front * betaContinuedFraction(b, a, 1 - x)) / b;
|
|
85
|
+
if (!Number.isFinite(result) || result < 0 || result > 1)
|
|
86
|
+
throw new RangeError("invalid incomplete beta result");
|
|
87
|
+
return result;
|
|
83
88
|
}
|
|
84
|
-
/**
|
|
85
|
-
function
|
|
89
|
+
/** Invert the survival probability directly; never round 1-alpha to one. */
|
|
90
|
+
function betaUpperQuantile(alpha, a, b) {
|
|
86
91
|
let low = 0;
|
|
87
92
|
let high = 1;
|
|
88
|
-
for (let i = 0; i < 200
|
|
89
|
-
const mid =
|
|
90
|
-
if (
|
|
93
|
+
for (let i = 0; i < 200; i += 1) {
|
|
94
|
+
const mid = low + (high - low) / 2;
|
|
95
|
+
if (mid === low || mid === high)
|
|
96
|
+
break;
|
|
97
|
+
if (regularizedIncompleteBeta(b, a, 1 - mid) > alpha)
|
|
91
98
|
low = mid;
|
|
92
99
|
else
|
|
93
100
|
high = mid;
|
|
94
101
|
}
|
|
95
|
-
|
|
102
|
+
// Upper endpoint of the numerical bracket, not an interval-arithmetic proof.
|
|
103
|
+
return high;
|
|
96
104
|
}
|
|
97
105
|
function assertAlpha(alpha) {
|
|
98
106
|
ensure(typeof alpha === "number" && Number.isFinite(alpha) && alpha > 0 && alpha < 1, "alpha must be a probability strictly between 0 and 1");
|
|
@@ -109,7 +117,9 @@ export function clopperPearsonUpperBound(failures, trials, alpha) {
|
|
|
109
117
|
assertAlpha(alpha);
|
|
110
118
|
if (failures === trials)
|
|
111
119
|
return 1;
|
|
112
|
-
|
|
120
|
+
if (failures === 0)
|
|
121
|
+
return zeroFailureUpperBound(trials, alpha);
|
|
122
|
+
return betaUpperQuantile(alpha, failures + 1, trials - failures);
|
|
113
123
|
}
|
|
114
124
|
/** Closed form of {@link clopperPearsonUpperBound} when no trial failed. */
|
|
115
125
|
export function zeroFailureUpperBound(trials, alpha) {
|
|
@@ -144,7 +154,11 @@ export function bonferroniAlpha(alpha, thresholds, groups) {
|
|
|
144
154
|
assertAlpha(alpha);
|
|
145
155
|
ensure(Number.isSafeInteger(thresholds) && thresholds > 0, "thresholds must be a positive integer");
|
|
146
156
|
ensure(Number.isSafeInteger(groups) && groups > 0, "groups must be a positive integer");
|
|
147
|
-
|
|
157
|
+
const comparisons = thresholds * groups;
|
|
158
|
+
ensure(Number.isSafeInteger(comparisons), "comparison count overflow");
|
|
159
|
+
const adjusted = alpha / comparisons;
|
|
160
|
+
ensure(adjusted > 0 && Number.isFinite(adjusted), "adjusted alpha underflow");
|
|
161
|
+
return adjusted;
|
|
148
162
|
}
|
|
149
163
|
/**
|
|
150
164
|
* Union bound over per-step failure risks.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"risk.js","sourceRoot":"","sources":["../../src/metacognition/risk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,oBAAoB,GAAG;IAC5B,wBAAwB,EAAE,qBAAqB,EAAE,CAAC,sBAAsB,EAAE,sBAAsB;IAChG,CAAC,sBAAsB,EAAE,sBAAsB,EAAE,CAAC,wBAAwB,EAAE,0BAA0B;IACtG,0BAA0B;CACjB,CAAC;AAEX,SAAS,QAAQ,CAAC,CAAS,EAAU;IACpC,IAAI,CAAC,GAAG,GAAG;QAAE,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAChF,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChB,IAAI,CAAC,GAAG,oBAAoB,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,CAAC,GAAG,CAAC,GAAG,SAAS,GAAG,GAAG,CAAC;IAC9B,KAAK,MAAM,CAAC,KAAK,EAAE,WAAW,CAAC,IAAI,oBAAoB,CAAC,OAAO,EAAE,EAA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ChG,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,SAAS,EAAE,CAAC;QAC9B,MAAM,CACL,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,EAC3E,gDAAgD,CAChD,CAAC;QACF,KAAK,IAAI,IAAI,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AAAA,CAC1B","sourcesContent":["/**\n * Finite-sample risk bounds for automation gating (Jev audit algorithm A4).\n *\n * A point estimate must never widen automation scope. Two failures in a\n * hundred is not \"a 2% error rate\" — its one-sided 95% Clopper–Pearson upper\n * bound is about 6.2%, and that bound is what a gate reads.\n *\n * Scope: this bounds the failure probability of samples drawn under the stated\n * conditions. It is not a safety guarantee for the next action, and it assumes\n * a fixed policy, a consistent failure event, and adequately independent\n * samples. Three hundred repeated clicks inside one task are not three hundred\n * independent trials; cluster by task or environment instance before using it.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nconst LANCZOS_G = 7;\nconst LANCZOS_COEFFICIENTS = [\n\t0.999_999_999_999_809_93, 676.520_368_121_885_1, -1259.139_216_722_402_8, 771.323_428_777_653_13,\n\t-176.615_029_162_140_59, 12.507_343_278_686_905, -0.138_571_095_265_720_12, 9.984_369_578_019_571_6e-6,\n\t1.505_632_735_149_311_6e-7,\n] as const;\n\nfunction logGamma(x: number): number {\n\tif (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);\n\tconst z = x - 1;\n\tlet a = LANCZOS_COEFFICIENTS[0];\n\tconst t = z + LANCZOS_G + 0.5;\n\tfor (const [index, coefficient] of LANCZOS_COEFFICIENTS.entries()) {\n\t\tif (index > 0) a += coefficient / (z + index);\n\t}\n\treturn 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(a);\n}\n\n/** Continued-fraction expansion for the incomplete beta (Lentz's method). */\nfunction betaContinuedFraction(a: number, b: number, x: number): number {\n\tconst maxIterations = 300;\n\tconst epsilon = 3e-16;\n\tconst tiny = 1e-300;\n\tconst qab = a + b;\n\tconst qap = a + 1;\n\tconst qam = a - 1;\n\tlet c = 1;\n\tlet d = 1 - (qab * x) / qap;\n\tif (Math.abs(d) < tiny) d = tiny;\n\td = 1 / d;\n\tlet h = d;\n\tfor (let m = 1; m <= maxIterations; m += 1) {\n\t\tconst m2 = 2 * m;\n\t\tlet aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\th *= d * c;\n\t\taa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\tconst delta = d * c;\n\t\th *= delta;\n\t\tif (Math.abs(delta - 1) < epsilon) break;\n\t}\n\treturn h;\n}\n\n/** Regularized incomplete beta I_x(a,b). */\nexport function regularizedIncompleteBeta(a: number, b: number, x: number): number {\n\tif (x <= 0) return 0;\n\tif (x >= 1) return 1;\n\tconst front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));\n\treturn x < (a + 1) / (a + b + 2)\n\t\t? (front * betaContinuedFraction(a, b, x)) / a\n\t\t: 1 - (front * betaContinuedFraction(b, a, 1 - x)) / b;\n}\n\n/** Inverse of {@link regularizedIncompleteBeta} by bisection; I_x is monotone in x. */\nfunction betaQuantile(p: number, a: number, b: number): number {\n\tlet low = 0;\n\tlet high = 1;\n\tfor (let i = 0; i < 200 && high - low > 1e-15; i += 1) {\n\t\tconst mid = (low + high) / 2;\n\t\tif (regularizedIncompleteBeta(a, b, mid) < p) low = mid;\n\t\telse high = mid;\n\t}\n\treturn (low + high) / 2;\n}\n\nfunction assertAlpha(alpha: number): void {\n\tensure(\n\t\ttypeof alpha === \"number\" && Number.isFinite(alpha) && alpha > 0 && alpha < 1,\n\t\t\"alpha must be a probability strictly between 0 and 1\",\n\t);\n}\n\n/**\n * One-sided Clopper–Pearson upper bound on the failure probability.\n *\n * `U(k,n) = Beta⁻¹(1−α; k+1, n−k)` for `0 ≤ k < n`, and `1` when every trial\n * failed. Zero trials is not zero risk: it is absent evidence, so it throws.\n */\nexport function clopperPearsonUpperBound(failures: number, trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tensure(\n\t\tNumber.isSafeInteger(failures) && failures >= 0 && failures <= trials,\n\t\t\"failures must be an integer in [0, trials]\",\n\t);\n\tassertAlpha(alpha);\n\tif (failures === trials) return 1;\n\treturn betaQuantile(1 - alpha, failures + 1, trials - failures);\n}\n\n/** Closed form of {@link clopperPearsonUpperBound} when no trial failed. */\nexport function zeroFailureUpperBound(trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tassertAlpha(alpha);\n\treturn -Math.expm1(Math.log(alpha) / trials);\n}\n\n/**\n * Smallest failure-free sample size whose upper bound meets `targetEpsilon`.\n *\n * `n ≥ ⌈log α / log(1−ε)⌉`, then nudged against the bound itself so a\n * floating-point boundary cannot return a sample size that misses the target.\n */\nexport function minimumZeroFailureSamples(targetEpsilon: number, alpha: number): number {\n\tensure(\n\t\ttypeof targetEpsilon === \"number\" && Number.isFinite(targetEpsilon) && targetEpsilon > 0 && targetEpsilon < 1,\n\t\t\"targetEpsilon must be strictly between 0 and 1\",\n\t);\n\tassertAlpha(alpha);\n\tlet n = Math.max(1, Math.ceil(Math.log(alpha) / Math.log1p(-targetEpsilon)));\n\twhile (zeroFailureUpperBound(n, alpha) > targetEpsilon) n += 1;\n\twhile (n > 1 && zeroFailureUpperBound(n - 1, alpha) <= targetEpsilon) n -= 1;\n\treturn n;\n}\n\n/**\n * Bonferroni split for `thresholds × groups` comparisons on one validation set.\n *\n * Searching many thresholds and reporting the best keeps none of a single\n * interval's nominal guarantee; this is the conservative correction, and it\n * raises the required sample size on purpose.\n */\nexport function bonferroniAlpha(alpha: number, thresholds: number, groups: number): number {\n\tassertAlpha(alpha);\n\tensure(Number.isSafeInteger(thresholds) && thresholds > 0, \"thresholds must be a positive integer\");\n\tensure(Number.isSafeInteger(groups) && groups > 0, \"groups must be a positive integer\");\n\treturn alpha / (thresholds * groups);\n}\n\n/**\n * Union bound over per-step failure risks.\n *\n * Holds without any independence assumption, which is the point: step risks in\n * one task are usually correlated, so multiplying them would understate the\n * whole-task risk.\n */\nexport function unionBoundRisk(stepRisks: readonly number[]): number {\n\tensure(Array.isArray(stepRisks) && stepRisks.length > 0, \"stepRisks must be a non-empty array\");\n\tlet total = 0;\n\tfor (const risk of stepRisks) {\n\t\tensure(\n\t\t\ttypeof risk === \"number\" && Number.isFinite(risk) && risk >= 0 && risk <= 1,\n\t\t\t\"each step risk must be a probability in [0, 1]\",\n\t\t);\n\t\ttotal += risk;\n\t}\n\treturn Math.min(1, total);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"risk.js","sourceRoot":"","sources":["../../src/metacognition/risk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,oBAAoB,GAAG;IAC5B,wBAAwB,EAAE,qBAAqB,EAAE,CAAC,sBAAsB,EAAE,sBAAsB;IAChG,CAAC,sBAAsB,EAAE,sBAAsB,EAAE,CAAC,wBAAwB,EAAE,0BAA0B;IACtG,0BAA0B;CACjB,CAAC;AAEX,SAAS,QAAQ,CAAC,CAAS,EA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,CAAC;IAC9E,OAAO,QAAQ,CAAC;AAAA,CAChB;AAED;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,SAA4B,EAAU;IACpE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,qCAAqC,CAAC,CAAC;IAChG,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,SAAS,EAAE,CAAC;QAC9B,MAAM,CACL,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,EAC3E,gDAAgD,CAChD,CAAC;QACF,KAAK,IAAI,IAAI,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AAAA,CAC1B","sourcesContent":["/**\n * Finite-sample risk bounds for automation gating (Jev audit algorithm A4).\n *\n * A point estimate must never widen automation scope. Two failures in a\n * hundred is not \"a 2% error rate\" — its one-sided 95% Clopper–Pearson upper\n * bound is about 6.2%, and that bound is what a gate reads.\n *\n * Scope: this bounds the failure probability of samples drawn under the stated\n * conditions. It is not a safety guarantee for the next action, and it assumes\n * a fixed policy, a consistent failure event, and adequately independent\n * samples. Three hundred repeated clicks inside one task are not three hundred\n * independent trials; cluster by task or environment instance before using it.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nconst LANCZOS_G = 7;\nconst LANCZOS_COEFFICIENTS = [\n\t0.999_999_999_999_809_93, 676.520_368_121_885_1, -1259.139_216_722_402_8, 771.323_428_777_653_13,\n\t-176.615_029_162_140_59, 12.507_343_278_686_905, -0.138_571_095_265_720_12, 9.984_369_578_019_571_6e-6,\n\t1.505_632_735_149_311_6e-7,\n] as const;\n\nfunction logGamma(x: number): number {\n\tif (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);\n\tconst z = x - 1;\n\tlet a = LANCZOS_COEFFICIENTS[0];\n\tconst t = z + LANCZOS_G + 0.5;\n\tfor (const [index, coefficient] of LANCZOS_COEFFICIENTS.entries()) {\n\t\tif (index > 0) a += coefficient / (z + index);\n\t}\n\treturn 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(a);\n}\n\n/** Continued-fraction expansion for the incomplete beta (Lentz's method). */\nfunction betaContinuedFraction(a: number, b: number, x: number): number {\n\tconst maxIterations = 1000;\n\tconst epsilon = 1e-14;\n\tconst tiny = 1e-300;\n\tconst qab = a + b;\n\tconst qap = a + 1;\n\tconst qam = a - 1;\n\tlet c = 1;\n\tlet d = 1 - (qab * x) / qap;\n\tif (Math.abs(d) < tiny) d = tiny;\n\td = 1 / d;\n\tlet h = d;\n\tfor (let m = 1; m <= maxIterations; m += 1) {\n\t\tconst m2 = 2 * m;\n\t\tlet aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\th *= d * c;\n\t\taa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\tconst delta = d * c;\n\t\th *= delta;\n\t\tif (Math.abs(delta - 1) < epsilon && Number.isFinite(h)) return h;\n\t}\n\tthrow new RangeError(\"incomplete beta failed to converge\");\n}\n\n/** Regularized incomplete beta I_x(a,b). */\nexport function regularizedIncompleteBeta(a: number, b: number, x: number): number {\n\tensure(Number.isFinite(a) && a > 0 && Number.isFinite(b) && b > 0 && Number.isFinite(a + b), \"invalid beta shapes\");\n\tensure(Number.isFinite(x) && x >= 0 && x <= 1, \"beta x must be in [0,1]\");\n\tif (x <= 0) return 0;\n\tif (x >= 1) return 1;\n\tconst front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));\n\tconst result =\n\t\tx < (a + 1) / (a + b + 2)\n\t\t\t? (front * betaContinuedFraction(a, b, x)) / a\n\t\t\t: 1 - (front * betaContinuedFraction(b, a, 1 - x)) / b;\n\tif (!Number.isFinite(result) || result < 0 || result > 1) throw new RangeError(\"invalid incomplete beta result\");\n\treturn result;\n}\n\n/** Invert the survival probability directly; never round 1-alpha to one. */\nfunction betaUpperQuantile(alpha: number, a: number, b: number): number {\n\tlet low = 0;\n\tlet high = 1;\n\tfor (let i = 0; i < 200; i += 1) {\n\t\tconst mid = low + (high - low) / 2;\n\t\tif (mid === low || mid === high) break;\n\t\tif (regularizedIncompleteBeta(b, a, 1 - mid) > alpha) low = mid;\n\t\telse high = mid;\n\t}\n\t// Upper endpoint of the numerical bracket, not an interval-arithmetic proof.\n\treturn high;\n}\n\nfunction assertAlpha(alpha: number): void {\n\tensure(\n\t\ttypeof alpha === \"number\" && Number.isFinite(alpha) && alpha > 0 && alpha < 1,\n\t\t\"alpha must be a probability strictly between 0 and 1\",\n\t);\n}\n\n/**\n * One-sided Clopper–Pearson upper bound on the failure probability.\n *\n * `U(k,n) = Beta⁻¹(1−α; k+1, n−k)` for `0 ≤ k < n`, and `1` when every trial\n * failed. Zero trials is not zero risk: it is absent evidence, so it throws.\n */\nexport function clopperPearsonUpperBound(failures: number, trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tensure(\n\t\tNumber.isSafeInteger(failures) && failures >= 0 && failures <= trials,\n\t\t\"failures must be an integer in [0, trials]\",\n\t);\n\tassertAlpha(alpha);\n\tif (failures === trials) return 1;\n\tif (failures === 0) return zeroFailureUpperBound(trials, alpha);\n\treturn betaUpperQuantile(alpha, failures + 1, trials - failures);\n}\n\n/** Closed form of {@link clopperPearsonUpperBound} when no trial failed. */\nexport function zeroFailureUpperBound(trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tassertAlpha(alpha);\n\treturn -Math.expm1(Math.log(alpha) / trials);\n}\n\n/**\n * Smallest failure-free sample size whose upper bound meets `targetEpsilon`.\n *\n * `n ≥ ⌈log α / log(1−ε)⌉`, then nudged against the bound itself so a\n * floating-point boundary cannot return a sample size that misses the target.\n */\nexport function minimumZeroFailureSamples(targetEpsilon: number, alpha: number): number {\n\tensure(\n\t\ttypeof targetEpsilon === \"number\" && Number.isFinite(targetEpsilon) && targetEpsilon > 0 && targetEpsilon < 1,\n\t\t\"targetEpsilon must be strictly between 0 and 1\",\n\t);\n\tassertAlpha(alpha);\n\tlet n = Math.max(1, Math.ceil(Math.log(alpha) / Math.log1p(-targetEpsilon)));\n\twhile (zeroFailureUpperBound(n, alpha) > targetEpsilon) n += 1;\n\twhile (n > 1 && zeroFailureUpperBound(n - 1, alpha) <= targetEpsilon) n -= 1;\n\treturn n;\n}\n\n/**\n * Bonferroni split for `thresholds × groups` comparisons on one validation set.\n *\n * Searching many thresholds and reporting the best keeps none of a single\n * interval's nominal guarantee; this is the conservative correction, and it\n * raises the required sample size on purpose.\n */\nexport function bonferroniAlpha(alpha: number, thresholds: number, groups: number): number {\n\tassertAlpha(alpha);\n\tensure(Number.isSafeInteger(thresholds) && thresholds > 0, \"thresholds must be a positive integer\");\n\tensure(Number.isSafeInteger(groups) && groups > 0, \"groups must be a positive integer\");\n\tconst comparisons = thresholds * groups;\n\tensure(Number.isSafeInteger(comparisons), \"comparison count overflow\");\n\tconst adjusted = alpha / comparisons;\n\tensure(adjusted > 0 && Number.isFinite(adjusted), \"adjusted alpha underflow\");\n\treturn adjusted;\n}\n\n/**\n * Union bound over per-step failure risks.\n *\n * Holds without any independence assumption, which is the point: step risks in\n * one task are usually correlated, so multiplying them would understate the\n * whole-task risk.\n */\nexport function unionBoundRisk(stepRisks: readonly number[]): number {\n\tensure(Array.isArray(stepRisks) && stepRisks.length > 0, \"stepRisks must be a non-empty array\");\n\tlet total = 0;\n\tfor (const risk of stepRisks) {\n\t\tensure(\n\t\t\ttypeof risk === \"number\" && Number.isFinite(risk) && risk >= 0 && risk <= 1,\n\t\t\t\"each step risk must be a probability in [0, 1]\",\n\t\t);\n\t\ttotal += risk;\n\t}\n\treturn Math.min(1, total);\n}\n"]}
|
|
@@ -2,21 +2,44 @@
|
|
|
2
2
|
* Runtime bridge — §13 "기존 완료 판정 호출부": projects host-owned OMK
|
|
3
3
|
* runtime artifacts (protocol ClaimGraph claims, ObservationNodes, waiver
|
|
4
4
|
* records, workspace/session facts) onto the metacognition kernel's input
|
|
5
|
-
* types.
|
|
6
|
-
*
|
|
5
|
+
* types.
|
|
6
|
+
*
|
|
7
|
+
* WP05 (docs/06_METACOGNITION_BRIDGE.md): every translation is loss-aware.
|
|
8
|
+
* Each claim and observation maps to `mapped`, `partial`, or `rejected`.
|
|
9
|
+
* What the previous mapper silently did — collapse claimIds to the first,
|
|
10
|
+
* force sequence 0, substitute checkId with receiptId/invalidation keys,
|
|
11
|
+
* stamp observedAtMs with bridge time, fabricate expiry as now+1, rebind any
|
|
12
|
+
* evidence to the current candidate, coerce unknown polarity to a boolean —
|
|
13
|
+
* is now either preserved verbatim or declared in `loss`, never repeated.
|
|
14
|
+
*
|
|
15
|
+
* It only translates; it never relaxes trust floors, never admits a model's
|
|
16
|
+
* JSON as runner truth, and never fabricates completion.
|
|
7
17
|
*/
|
|
8
|
-
import type
|
|
9
|
-
import
|
|
10
|
-
import type {
|
|
18
|
+
import { type ClaimNode, type ObservationSource } from "omk-protocol";
|
|
19
|
+
import { type BridgeObservation, type ClaimMapResult, type ObservationMapResult, type RuntimeBridgeResult } from "./bridge-result.ts";
|
|
20
|
+
import type { Claim, SourceIdentity, Stage } from "./knowledge.ts";
|
|
11
21
|
/** ClaimNode → kernel Claim. Severity maps to impact; leaves keep their check demands. */
|
|
12
|
-
export declare function
|
|
13
|
-
/**
|
|
14
|
-
export
|
|
15
|
-
|
|
16
|
-
readonly
|
|
17
|
-
readonly
|
|
18
|
-
readonly
|
|
22
|
+
export declare function mapClaim(node: ClaimNode, stage: Stage, binding: string): ClaimMapResult;
|
|
23
|
+
/** Context every observation edge is translated against. */
|
|
24
|
+
export interface ObservationMapContext {
|
|
25
|
+
/** `candidateHash@environmentHash` of the *current* candidate — never assigned to foreign evidence. */
|
|
26
|
+
readonly binding: string;
|
|
27
|
+
readonly nowMs: number;
|
|
28
|
+
readonly generation?: number;
|
|
29
|
+
/** Leaf claims already mapped, id → kernel claim. Unresolvable ids are declared loss. */
|
|
30
|
+
readonly claimById: ReadonlyMap<string, Claim>;
|
|
31
|
+
/** Per-claim trust floor; a missing floor defaults to `deterministic_validator`. */
|
|
32
|
+
readonly claimFloors: ReadonlyMap<string, ObservationSource>;
|
|
33
|
+
readonly sources: readonly SourceIdentity[];
|
|
19
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* ObservationNode → kernel observations.
|
|
37
|
+
*
|
|
38
|
+
* The result carries every emitted edge (one per resolvable claim — the
|
|
39
|
+
* explicit relation table docs/06 asks for) or the declared reason none
|
|
40
|
+
* could be emitted. No edge is ever emitted with fabricated provenance.
|
|
41
|
+
*/
|
|
42
|
+
export declare function mapObservation(node: BridgeObservation, ctx: ObservationMapContext): ObservationMapResult;
|
|
20
43
|
export interface RuntimeBridgeInput {
|
|
21
44
|
readonly taskId: string;
|
|
22
45
|
readonly stageId: string;
|
|
@@ -24,8 +47,10 @@ export interface RuntimeBridgeInput {
|
|
|
24
47
|
readonly targetArtifact: string;
|
|
25
48
|
readonly candidateHash: string;
|
|
26
49
|
readonly environmentHash: string;
|
|
50
|
+
/** Current ledger generation; compared with each observation's own when present. */
|
|
51
|
+
readonly generation?: number;
|
|
27
52
|
readonly claims: readonly ClaimNode[];
|
|
28
|
-
readonly observations: readonly
|
|
53
|
+
readonly observations: readonly BridgeObservation[];
|
|
29
54
|
readonly trustedRunnerIds: readonly string[];
|
|
30
55
|
readonly decisionActorIds: readonly string[];
|
|
31
56
|
readonly authorizedActions: readonly string[];
|
|
@@ -46,9 +71,11 @@ export interface RuntimeBridgeInput {
|
|
|
46
71
|
resolvedObligations: number;
|
|
47
72
|
newValidChecks: number;
|
|
48
73
|
}[];
|
|
74
|
+
/** Extra admissible source identities beyond the built-in registry. */
|
|
75
|
+
readonly sources?: readonly SourceIdentity[];
|
|
49
76
|
}
|
|
50
77
|
/** Build kernel inputs plus a MetaState for one safe checkpoint. Host-owned inputs only. */
|
|
51
|
-
export declare function toMetaState(input: RuntimeBridgeInput):
|
|
78
|
+
export declare function toMetaState(input: RuntimeBridgeInput): RuntimeBridgeResult;
|
|
52
79
|
/** Sources admitted for reference evidence: only repository/official qualify. */
|
|
53
80
|
export declare function sourceIdentities(overrides?: readonly SourceIdentity[]): readonly SourceIdentity[];
|
|
54
81
|
//# sourceMappingURL=runtime-bridge.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-bridge.d.ts","sourceRoot":"","sources":["../../src/metacognition/runtime-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/D,OAAO,KAAK,EACX,gBAAgB,EAChB,KAAK,EACL,mBAAmB,EACnB,oBAAoB,EACpB,cAAc,EACd,KAAK,EACL,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAS5C,4FAA0F;AAC1F,wBAAgB,aAAa,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,GAAG,KAAK,CAsBnF;AAED,6FAA2F;AAC3F,wBAAgB,mBAAmB,CAClC,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EAC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AC;IAC5C,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS;QACnC,GAAG,EAAE,MAAM,CAAC;QACZ,WAAW,EAAE,OAAO,CAAC;QACrB,mBAAmB,EAAE,MAAM,CAAC;QAC5B,cAAc,EAAE,MAAM,CAAC;KACvB,EAAE,CAAC;CACJ;AAED,4FAA4F;AAC5F,wBAAgB,WAAW,CAAC,KAAK,EAAE,kBAAkB,GAAG,mBAAmB,CAwD1E;AAED,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,SAAS,GAAE,SAAS,cAAc,EAAO,GAAG,SAAS,cAAc,EAAE,CAWrG","sourcesContent":["/**\n * Runtime bridge — §13 \"기존 완료 판정 호출부\": projects host-owned OMK\n * runtime artifacts (protocol ClaimGraph claims, ObservationNodes, waiver\n * records, workspace/session facts) onto the metacognition kernel's input\n * types. It only translates; it never relaxes trust floors, never admits a\n * model's JSON as runner truth, and never fabricates completion.\n */\nimport type { ClaimNode, ObservationNode } from \"omk-protocol\";\nimport { createCalibrationStore } from \"./calibration.ts\";\nimport type {\n\tCheckObservation,\n\tClaim,\n\tDecisionObservation,\n\tReferenceObservation,\n\tSourceIdentity,\n\tStage,\n} from \"./knowledge.ts\";\nimport type { MetaState } from \"./state.ts\";\nimport { ensure, integer, lexical, member, text } from \"./validation.ts\";\n\nconst ISO_MS = (iso: string): number => {\n\tconst ms = Date.parse(iso);\n\tensure(Number.isFinite(ms), `invalid ISO timestamp: ${iso}`);\n\treturn ms;\n};\n\n/** ClaimNode → kernel Claim. Severity maps to impact; leaves keep their check demands. */\nexport function toKernelClaim(node: ClaimNode, stage: Stage, binding: string): Claim {\n\ttext(node.claimId, \"claimId\", 256);\n\ttext(node.statement, \"statement\", 2048);\n\tmember(stage, [\"before-change\", \"after-change\"], \"stage\");\n\tlet impact = 100;\n\tif (node.kind === \"safety\") impact = 1_000;\n\telse if (node.severity === \"required\") impact = 500;\n\treturn {\n\t\tid: node.claimId,\n\t\tbinding,\n\t\tphase: node.kind === \"requirement\" || node.kind === \"safety\" ? \"precondition\" : \"postcondition\",\n\t\tstatement: node.statement,\n\t\trequired: node.severity === \"required\",\n\t\timpact,\n\t\tneedsReference: false,\n\t\trequiresVersion: false,\n\t\tversion: null,\n\t\tminSourceFamilies: node.requiredWitnesses ?? 1,\n\t\trequiredCheckIds: node.invalidationKeys,\n\t\tneedsUserDecision: node.trustFloor === \"model_narrative\",\n\t\tpublicQuery: null,\n\t};\n}\n\n/** ObservationNode → kernel observation. Trust floor rank maps to source admissibility. */\nexport function toKernelObservation(\n\tnode: ObservationNode,\n\tbinding: string,\n\tnowMs: number,\n\tclaimById?: ReadonlyMap<string, Claim>,\n): CheckObservation | ReferenceObservation | DecisionObservation {\n\ttext(node.observationId, \"observationId\", 256);\n\ttext(binding, \"binding\", 512);\n\tinteger(nowMs, \"nowMs\");\n\tconst observedAtMs = nowMs;\n\tconst expiresAtMs = node.validUntil !== undefined ? ISO_MS(node.validUntil) : nowMs + 1;\n\tconst claimId = node.claimIds[0] ?? \"\";\n\tconst base = { id: node.observationId, claimId, binding, observedAtMs, expiresAtMs };\n\tif (node.receiptId !== undefined) {\n\t\t// checkId is the claim's required check predicate (its invalidation key),\n\t\t// not the receipt id — receipts are evidence artifacts, checkIds are obligations.\n\t\tconst checkId = claimById?.get(claimId)?.requiredCheckIds[0] ?? node.receiptId;\n\t\treturn {\n\t\t\t...base,\n\t\t\tkind: \"check\",\n\t\t\trunnerId: node.source,\n\t\t\tcheckId,\n\t\t\tsequence: 0,\n\t\t\tverdict: node.polarity === \"supports\" ? \"pass\" : \"fail\",\n\t\t};\n\t}\n\tif (node.source === \"model_narrative\") {\n\t\treturn { ...base, kind: \"decision\", actorId: \"model\", accepted: node.polarity === \"supports\" };\n\t}\n\treturn {\n\t\t...base,\n\t\tkind: \"reference\",\n\t\tsourceId: node.source,\n\t\tversion: null,\n\t\tstance: node.polarity === \"supports\" ? \"support\" : \"refute\",\n\t\tdocumentDigest: node.environmentDigest,\n\t\tlocator: node.sourceRoot,\n\t};\n}\n\nexport interface RuntimeBridgeOutput {\n\treadonly state: MetaState;\n\treadonly claims: readonly Claim[];\n\treadonly observations: readonly (CheckObservation | ReferenceObservation | DecisionObservation)[];\n}\nexport interface RuntimeBridgeInput {\n\treadonly taskId: string;\n\treadonly stageId: string;\n\treadonly goalScope: string;\n\treadonly targetArtifact: string;\n\treadonly candidateHash: string;\n\treadonly environmentHash: string;\n\treadonly claims: readonly ClaimNode[];\n\treadonly observations: readonly ObservationNode[];\n\treadonly trustedRunnerIds: readonly string[];\n\treadonly decisionActorIds: readonly string[];\n\treadonly authorizedActions: readonly string[];\n\treadonly budget: {\n\t\tremainingMs: number;\n\t\tremainingRequests: number;\n\t\tremainingTokens: number;\n\t\tremainingConcurrent: number;\n\t};\n\treadonly policyVersion: string;\n\treadonly modelRevision: string;\n\treadonly interruptionReason?: string | null;\n\treadonly stage: Stage;\n\treadonly nowMs: number;\n\treadonly progressHistory?: readonly {\n\t\tkey: string;\n\t\tnewEvidence: boolean;\n\t\tresolvedObligations: number;\n\t\tnewValidChecks: number;\n\t}[];\n}\n\n/** Build kernel inputs plus a MetaState for one safe checkpoint. Host-owned inputs only. */\nexport function toMetaState(input: RuntimeBridgeInput): RuntimeBridgeOutput {\n\ttext(input.taskId, \"taskId\", 128);\n\ttext(input.stageId, \"stageId\", 128);\n\ttext(input.goalScope, \"goalScope\", 256);\n\ttext(input.targetArtifact, \"targetArtifact\", 512);\n\ttext(input.candidateHash, \"candidateHash\", 128);\n\ttext(input.environmentHash, \"environmentHash\", 128);\n\ttext(input.policyVersion, \"policyVersion\", 64);\n\ttext(input.modelRevision, \"modelRevision\", 128);\n\tinteger(input.nowMs, \"nowMs\");\n\tensure(input.claims.length <= 128 && input.observations.length <= 4096, \"runtime bridge input too large\");\n\t// Only leaf claims map to kernel claims — compound satisfaction is the\n\t// protocol layer's job, not a kernel evidence predicate.\n\tconst binding = `${input.candidateHash}@${input.environmentHash}`;\n\tconst leafClaims = input.claims.filter((c) => c.satisfaction.inputs.length === 0);\n\tconst claimById = new Map(leafClaims.map((c) => [c.claimId, toKernelClaim(c, input.stage, binding)]));\n\tconst kernelClaims = [...claimById.values()].sort((a, b) => lexical(a.id, b.id));\n\tconst kernelObservations = input.observations.map((o) => toKernelObservation(o, binding, input.nowMs, claimById));\n\tconst state: MetaState = {\n\t\tgoal: {\n\t\t\ttaskId: input.taskId,\n\t\t\tstageId: input.stageId,\n\t\t\ttargetArtifact: input.targetArtifact,\n\t\t\tgoalScope: input.goalScope,\n\t\t},\n\t\tfacts: {\n\t\t\tcandidateHash: input.candidateHash,\n\t\t\tenvironmentHash: input.environmentHash,\n\t\t\tchangeScope: [input.targetArtifact],\n\t\t\tanalyzerCoverage: \"unknown\",\n\t\t},\n\t\tobligations: [],\n\t\tevidence: { report: null, adoptedSourceIds: [] },\n\t\tpredictions: [],\n\t\thypotheses: { open: [], discriminatorCandidates: [], modelMismatch: false },\n\t\tcalibration: createCalibrationStore({\n\t\t\tminSamples: 5,\n\t\t\tpriorAlpha: 1,\n\t\t\tpriorBeta: 1,\n\t\t\treferenceMean: 0.3,\n\t\t\tslack: 0.15,\n\t\t\tthreshold: 3,\n\t\t}),\n\t\tverifier: { evaluations: [], runnerHealth: \"unverified\" },\n\t\tbudget: input.budget,\n\t\tpolicy: {\n\t\t\tpolicyVersion: input.policyVersion,\n\t\t\tauthorizedActions: input.authorizedActions,\n\t\t\trequiredApprovals: [],\n\t\t\tinterruptionReason: input.interruptionReason ?? null,\n\t\t},\n\t\thostSequence: 0,\n\t\tprogressHistory: input.progressHistory ?? [],\n\t\tcheckpointCount: 0,\n\t};\n\treturn { state, claims: kernelClaims, observations: kernelObservations };\n}\n\n/** Sources admitted for reference evidence: only repository/official qualify. */\nexport function sourceIdentities(overrides: readonly SourceIdentity[] = []): readonly SourceIdentity[] {\n\treturn [\n\t\t{ id: \"deterministic_validator\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"workspace_witness\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"trusted_attestation\", family: \"attestation\", kind: \"official\" },\n\t\t{ id: \"effect_reconciliation\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"independent_review\", family: \"review\", kind: \"official\" },\n\t\t{ id: \"self_review\", family: \"model\", kind: \"model\" },\n\t\t{ id: \"model_narrative\", family: \"model\", kind: \"model\" },\n\t\t...overrides,\n\t];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime-bridge.d.ts","sourceRoot":"","sources":["../../src/metacognition/runtime-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,KAAK,SAAS,EAA0B,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAC9F,OAAO,EAEN,KAAK,iBAAiB,EAEtB,KAAK,cAAc,EAGnB,KAAK,oBAAoB,EAEzB,KAAK,mBAAmB,EACxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAoB,KAAK,EAAe,cAAc,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAalG,4FAA0F;AAC1F,wBAAgB,QAAQ,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,GAAG,cAAc,CAoCvF;AAED,4DAA4D;AAC5D,MAAM,WAAW,qBAAqB;IACrC,yGAAuG;IACvG,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,2FAAyF;IACzF,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC/C,oFAAoF;IACpF,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,iBAAiB,CAAC,CA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;IACvB,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS;QACnC,GAAG,EAAE,MAAM,CAAC;QACZ,WAAW,EAAE,OAAO,CAAC;QACrB,mBAAmB,EAAE,MAAM,CAAC;QAC5B,cAAc,EAAE,MAAM,CAAC;KACvB,EAAE,CAAC;IACJ,uEAAuE;IACvE,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,CAAC;CAC7C;AA2ED,4FAA4F;AAC5F,wBAAgB,WAAW,CAAC,KAAK,EAAE,kBAAkB,GAAG,mBAAmB,CA0I1E;AAED,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,SAAS,GAAE,SAAS,cAAc,EAAO,GAAG,SAAS,cAAc,EAAE,CAWrG","sourcesContent":["/**\n * Runtime bridge — §13 \"기존 완료 판정 호출부\": projects host-owned OMK\n * runtime artifacts (protocol ClaimGraph claims, ObservationNodes, waiver\n * records, workspace/session facts) onto the metacognition kernel's input\n * types.\n *\n * WP05 (docs/06_METACOGNITION_BRIDGE.md): every translation is loss-aware.\n * Each claim and observation maps to `mapped`, `partial`, or `rejected`.\n * What the previous mapper silently did — collapse claimIds to the first,\n * force sequence 0, substitute checkId with receiptId/invalidation keys,\n * stamp observedAtMs with bridge time, fabricate expiry as now+1, rebind any\n * evidence to the current candidate, coerce unknown polarity to a boolean —\n * is now either preserved verbatim or declared in `loss`, never repeated.\n *\n * It only translates; it never relaxes trust floors, never admits a model's\n * JSON as runner truth, and never fabricates completion.\n */\nimport { type ClaimNode, OBSERVATION_TRUST_RANK, type ObservationSource } from \"omk-protocol\";\nimport {\n\ttype BridgeLoss,\n\ttype BridgeObservation,\n\ttype BridgePolarity,\n\ttype ClaimMapResult,\n\tlossOf,\n\tmergeBridgeLoss,\n\ttype ObservationMapResult,\n\ttype RuntimeBridgeOutput,\n\ttype RuntimeBridgeResult,\n} from \"./bridge-result.ts\";\nimport { createCalibrationStore } from \"./calibration.ts\";\nimport type { CheckObservation, Claim, Observation, SourceIdentity, Stage } from \"./knowledge.ts\";\nimport type { MetaState } from \"./state.ts\";\nimport { canonical, ensure, integer, lexical, member, text } from \"./validation.ts\";\n\nconst ISO_MS = (iso: string): number => {\n\tconst ms = Date.parse(iso);\n\tensure(Number.isFinite(ms), `invalid ISO timestamp: ${iso}`);\n\treturn ms;\n};\n\nconst UNKNOWN_POLARITY: readonly BridgePolarity[] = [\"unknown\", \"neutral\", \"inconclusive\"];\nconst isUnknownPolarity = (p: BridgePolarity): boolean => UNKNOWN_POLARITY.includes(p);\n\n/** ClaimNode → kernel Claim. Severity maps to impact; leaves keep their check demands. */\nexport function mapClaim(node: ClaimNode, stage: Stage, binding: string): ClaimMapResult {\n\ttext(node.claimId, \"claimId\", 256);\n\ttext(node.statement, \"statement\", 2048);\n\tmember(stage, [\"before-change\", \"after-change\"], \"stage\");\n\tlet impact = 100;\n\tif (node.kind === \"safety\") impact = 1_000;\n\telse if (node.severity === \"required\") impact = 500;\n\tconst needsUserDecision = node.trustFloor === \"model_narrative\";\n\t// A leaf needs at least one kernel evidence predicate. Checks come from\n\t// invalidationKeys; multi-witness demands and keyless leaves need\n\t// reference families; model-narrative floors need a decision.\n\tconst needsReference =\n\t\tnode.invalidationKeys.length === 0 && !needsUserDecision ? true : (node.requiredWitnesses ?? 1) > 1;\n\tconst claim: Claim = {\n\t\tid: node.claimId,\n\t\tbinding,\n\t\tphase: node.kind === \"requirement\" || node.kind === \"safety\" ? \"precondition\" : \"postcondition\",\n\t\tstatement: node.statement,\n\t\trequired: node.severity === \"required\",\n\t\timpact,\n\t\tneedsReference,\n\t\trequiresVersion: false,\n\t\tversion: null,\n\t\tminSourceFamilies: Math.max(node.requiredWitnesses ?? 1, 1),\n\t\trequiredCheckIds: node.invalidationKeys,\n\t\tneedsUserDecision,\n\t\tpublicQuery: null,\n\t};\n\tif (node.scopeSensitive === true) {\n\t\treturn {\n\t\t\tstatus: \"partial\",\n\t\t\tclaim,\n\t\t\tloss: lossOf({ lostFields: [`claim:${node.claimId}.scopeSensitive`] }),\n\t\t};\n\t}\n\treturn { status: \"mapped\", claim };\n}\n\n/** Context every observation edge is translated against. */\nexport interface ObservationMapContext {\n\t/** `candidateHash@environmentHash` of the *current* candidate — never assigned to foreign evidence. */\n\treadonly binding: string;\n\treadonly nowMs: number;\n\treadonly generation?: number;\n\t/** Leaf claims already mapped, id → kernel claim. Unresolvable ids are declared loss. */\n\treadonly claimById: ReadonlyMap<string, Claim>;\n\t/** Per-claim trust floor; a missing floor defaults to `deterministic_validator`. */\n\treadonly claimFloors: ReadonlyMap<string, ObservationSource>;\n\treadonly sources: readonly SourceIdentity[];\n}\n\nconst floorRank = (floors: ReadonlyMap<string, ObservationSource>, claimId: string): number =>\n\tOBSERVATION_TRUST_RANK[floors.get(claimId) ?? \"deterministic_validator\"];\n\nconst findSource = (sources: readonly SourceIdentity[], id: string): SourceIdentity | undefined =>\n\tsources.find((s) => s.id === id);\n\n/**\n * ObservationNode → kernel observations.\n *\n * The result carries every emitted edge (one per resolvable claim — the\n * explicit relation table docs/06 asks for) or the declared reason none\n * could be emitted. No edge is ever emitted with fabricated provenance.\n */\nexport function mapObservation(node: BridgeObservation, ctx: ObservationMapContext): ObservationMapResult {\n\ttext(node.observationId, \"observationId\", 256);\n\ttext(node.sourceRoot, \"sourceRoot\", 512);\n\ttext(node.environmentDigest, \"environmentDigest\", 256);\n\tmember(node.source, Object.keys(OBSERVATION_TRUST_RANK), \"observation source\");\n\tinteger(ctx.nowMs, \"nowMs\");\n\tif (node.claimIds.length === 0) {\n\t\treturn { status: \"rejected\", reason: `${node.observationId}: no claim ids` };\n\t}\n\t// Clock and generation conflicts reject outright — docs/06 lists\n\t// generation moves, future timestamps and expiry as invalid on arrival.\n\tif (node.generation !== undefined && ctx.generation !== undefined && node.generation !== ctx.generation) {\n\t\treturn { status: \"rejected\", reason: `${node.observationId}: generation-mismatch` };\n\t}\n\tif (node.observedAtMs !== undefined && node.observedAtMs > ctx.nowMs) {\n\t\treturn { status: \"rejected\", reason: `${node.observationId}: future-observation` };\n\t}\n\tconst expiresAtMs = node.validUntil !== undefined ? ISO_MS(node.validUntil) : undefined;\n\tif (expiresAtMs !== undefined && expiresAtMs <= ctx.nowMs) {\n\t\treturn { status: \"rejected\", reason: `${node.observationId}: expired-observation` };\n\t}\n\tif (expiresAtMs !== undefined && node.observedAtMs !== undefined && expiresAtMs < node.observedAtMs) {\n\t\treturn { status: \"rejected\", reason: `${node.observationId}: invalid-validity-interval` };\n\t}\n\t// Binding: equal ⇒ kept, different ⇒ rejected, absent ⇒ unknownBindings.\n\t// The one thing that never happens is reattaching foreign or unbound\n\t// evidence to ctx.binding.\n\tif (node.binding !== undefined && node.binding !== ctx.binding) {\n\t\treturn { status: \"rejected\", reason: `${node.observationId}: binding-mismatch` };\n\t}\n\t// Polarity must be expressible by the kind this observation maps to.\n\tconst checkIds = [...new Set([...(node.checkId ? [node.checkId] : []), ...(node.checkIds ?? [])])];\n\tconst isCheck = node.receiptId !== undefined || checkIds.length > 0;\n\tconst isDecision = !isCheck && (node.source === \"model_narrative\" || node.actorId !== undefined);\n\tif (isUnknownPolarity(node.polarity) && !isCheck) {\n\t\treturn { status: \"rejected\", reason: `${node.observationId}: unexpressible-polarity` };\n\t}\n\t// Fields required to emit an edge without fabrication. Absent provenance\n\t// is declared loss; the edge is not emitted.\n\tconst missing: string[] = [];\n\tif (node.observedAtMs === undefined) missing.push(\"observedAtMs\");\n\tif (expiresAtMs === undefined) missing.push(\"validUntil\");\n\tif (isCheck) {\n\t\tif (checkIds.length === 0) missing.push(\"checkId\");\n\t\tif (node.sequence === undefined) missing.push(\"sequence\");\n\t}\n\tconst lostFields: string[] = missing.map((f) => `${node.observationId}.${f}`);\n\tconst unknownBindings: string[] = [];\n\tif (node.binding === undefined) unknownBindings.push(node.observationId);\n\tconst blockedByMissing = missing.length > 0 || node.binding === undefined;\n\n\tconst observations: Observation[] = [];\n\tconst usedSources = new Map<string, SourceIdentity>();\n\tconst unmappedClaims: string[] = [];\n\tconst family =\n\t\tnode.sourceFamily ?? node.independenceGroup ?? findSource(ctx.sources, node.source)?.family ?? node.source;\n\t// Edge ids stay unique when one observation emits several edges.\n\tconst edgeCount = node.claimIds.filter((c) => ctx.claimById.has(c)).length * Math.max(checkIds.length, 1);\n\tconst multi = edgeCount > 1;\n\tfor (const claimId of node.claimIds) {\n\t\tconst claim = ctx.claimById.get(claimId);\n\t\tif (!claim) {\n\t\t\tunmappedClaims.push(`${node.observationId}->${claimId}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (OBSERVATION_TRUST_RANK[node.source] < floorRank(ctx.claimFloors, claimId)) {\n\t\t\tunmappedClaims.push(`${node.observationId}->${claimId}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (blockedByMissing) continue; // declared above; emitted only with full provenance\n\t\t// Guaranteed present by the missing-fields computation above. `ensure`\n\t\t// narrows for the compiler and fails loudly instead of defaulting.\n\t\tensure(node.observedAtMs !== undefined, `${node.observationId}: observedAtMs required`);\n\t\tensure(expiresAtMs !== undefined, `${node.observationId}: validUntil required`);\n\t\tensure(node.binding !== undefined, `${node.observationId}: binding required`);\n\t\tconst base = {\n\t\t\tid: node.observationId,\n\t\t\tclaimId,\n\t\t\tbinding: node.binding,\n\t\t\tobservedAtMs: node.observedAtMs,\n\t\t\texpiresAtMs,\n\t\t};\n\t\tif (isCheck) {\n\t\t\tensure(node.sequence !== undefined, `${node.observationId}: sequence required`);\n\t\t\tconst verdict: CheckObservation[\"verdict\"] =\n\t\t\t\tnode.polarity === \"supports\" ? \"pass\" : node.polarity === \"violates\" ? \"fail\" : \"pending\";\n\t\t\tfor (const checkId of checkIds) {\n\t\t\t\tobservations.push({\n\t\t\t\t\t...base,\n\t\t\t\t\tid: multi ? `${node.observationId}#${claimId}#${checkId}` : node.observationId,\n\t\t\t\t\tkind: \"check\",\n\t\t\t\t\trunnerId: node.source,\n\t\t\t\t\tcheckId,\n\t\t\t\t\tsequence: node.sequence,\n\t\t\t\t\tverdict,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (isDecision) {\n\t\t\tobservations.push({\n\t\t\t\t...base,\n\t\t\t\tid: multi ? `${node.observationId}#${claimId}` : node.observationId,\n\t\t\t\tkind: \"decision\",\n\t\t\t\tactorId: node.actorId ?? \"model\",\n\t\t\t\taccepted: node.polarity === \"supports\",\n\t\t\t});\n\t\t} else {\n\t\t\t// Synthesized identity carries the witness's independence group so\n\t\t\t// the kernel counts families, not citation count.\n\t\t\tconst sourceId = `${node.source}@${family}`;\n\t\t\tif (!usedSources.has(sourceId)) {\n\t\t\t\tconst registered = findSource(ctx.sources, node.source);\n\t\t\t\tusedSources.set(sourceId, {\n\t\t\t\t\tid: sourceId,\n\t\t\t\t\tfamily,\n\t\t\t\t\tkind: registered?.kind === \"model\" || registered === undefined ? \"community\" : registered.kind,\n\t\t\t\t});\n\t\t\t}\n\t\t\tobservations.push({\n\t\t\t\t...base,\n\t\t\t\tid: multi ? `${node.observationId}#${claimId}` : node.observationId,\n\t\t\t\tkind: \"reference\",\n\t\t\t\tsourceId,\n\t\t\t\tversion: null,\n\t\t\t\tstance: node.polarity === \"supports\" ? \"support\" : \"refute\",\n\t\t\t\tdocumentDigest: node.environmentDigest,\n\t\t\t\tlocator: node.sourceRoot,\n\t\t\t});\n\t\t}\n\t}\n\tconst sources = [...usedSources.values()];\n\tif (lostFields.length === 0 && unknownBindings.length === 0 && unmappedClaims.length === 0) {\n\t\treturn { status: \"mapped\", observations, sources };\n\t}\n\treturn {\n\t\tstatus: \"partial\",\n\t\tobservations,\n\t\tsources,\n\t\tloss: lossOf({ lostFields, unmappedClaims, unknownBindings }),\n\t};\n}\n\nexport interface RuntimeBridgeInput {\n\treadonly taskId: string;\n\treadonly stageId: string;\n\treadonly goalScope: string;\n\treadonly targetArtifact: string;\n\treadonly candidateHash: string;\n\treadonly environmentHash: string;\n\t/** Current ledger generation; compared with each observation's own when present. */\n\treadonly generation?: number;\n\treadonly claims: readonly ClaimNode[];\n\treadonly observations: readonly BridgeObservation[];\n\treadonly trustedRunnerIds: readonly string[];\n\treadonly decisionActorIds: readonly string[];\n\treadonly authorizedActions: readonly string[];\n\treadonly budget: {\n\t\tremainingMs: number;\n\t\tremainingRequests: number;\n\t\tremainingTokens: number;\n\t\tremainingConcurrent: number;\n\t};\n\treadonly policyVersion: string;\n\treadonly modelRevision: string;\n\treadonly interruptionReason?: string | null;\n\treadonly stage: Stage;\n\treadonly nowMs: number;\n\treadonly progressHistory?: readonly {\n\t\tkey: string;\n\t\tnewEvidence: boolean;\n\t\tresolvedObligations: number;\n\t\tnewValidChecks: number;\n\t}[];\n\t/** Extra admissible source identities beyond the built-in registry. */\n\treadonly sources?: readonly SourceIdentity[];\n}\n\n/** Witness pairs that conflict on independence or polarity. */\nfunction familyConflicts(\n\tedges: readonly Observation[],\n\trejected: readonly { id: string; reason: string }[],\n\tinputs: readonly BridgeObservation[],\n\tclaimById: ReadonlyMap<string, Claim>,\n): string[] {\n\tconst conflicts: string[] = [];\n\tconst byClaim = new Map<string, Observation[]>();\n\tfor (const e of edges) byClaim.set(e.claimId, [...(byClaim.get(e.claimId) ?? []), e]);\n\tfor (const [claimId, list] of byClaim) {\n\t\t// Opposing witnesses (support vs refute / pass vs fail) from the same\n\t\t// source family on one claim.\n\t\tconst signs = new Map<string, Set<string>>();\n\t\tfor (const e of list) {\n\t\t\tconst fam = e.kind === \"reference\" ? e.sourceId : e.kind === \"check\" ? e.runnerId : e.actorId;\n\t\t\tconst sign =\n\t\t\t\te.kind === \"reference\"\n\t\t\t\t\t? e.stance\n\t\t\t\t\t: e.kind === \"check\"\n\t\t\t\t\t\t? e.verdict === \"pending\"\n\t\t\t\t\t\t\t? \"pending\"\n\t\t\t\t\t\t\t: e.verdict === \"pass\"\n\t\t\t\t\t\t\t\t? \"support\"\n\t\t\t\t\t\t\t\t: \"refute\"\n\t\t\t\t\t\t: e.accepted\n\t\t\t\t\t\t\t? \"support\"\n\t\t\t\t\t\t\t: \"refute\";\n\t\t\tsigns.set(fam, new Set([...(signs.get(fam) ?? []), sign]));\n\t\t}\n\t\tfor (const [fam, s] of signs) {\n\t\t\tif (s.has(\"support\") && s.has(\"refute\")) conflicts.push(`conflicting-witness:${claimId}:${fam}`);\n\t\t}\n\t}\n\t// Same (claim, family) cited by several distinct observations duplicates\n\t// one independence group — counted once by the kernel, declared here.\n\tconst cited = new Map<string, Set<string>>();\n\tfor (const o of inputs) {\n\t\tif (rejected.some((r) => r.id === o.observationId)) continue;\n\t\tfor (const claimId of o.claimIds) {\n\t\t\tif (!claimById.has(claimId)) continue;\n\t\t\tconst key = `${claimId}|${o.sourceFamily ?? o.independenceGroup ?? o.source}`;\n\t\t\tcited.set(key, new Set([...(cited.get(key) ?? []), o.observationId]));\n\t\t}\n\t}\n\tfor (const [key, ids] of cited) {\n\t\tif (ids.size > 1) conflicts.push(`duplicate-citation:${key}`);\n\t}\n\treturn conflicts.sort(lexical);\n}\n\n/**\n * Check edges sharing (claimId, binding, checkId, sequence) must agree\n * verbatim — the kernel `ensure`s that and would throw. Conflicting slots\n * are ledger corruption: suppress *all* edges in the slot (admit neither)\n * and leave the conflict declared in sourceFamilyConflicts.\n */\nfunction suppressConflictingSequences(edges: readonly Observation[]): Observation[] {\n\tconst slots = new Map<string, Observation[]>();\n\tfor (const e of edges) {\n\t\tif (e.kind !== \"check\") continue;\n\t\tconst key = canonical([e.claimId, e.binding, e.checkId, e.sequence]);\n\t\tslots.set(key, [...(slots.get(key) ?? []), e]);\n\t}\n\tconst drop = new Set<string>();\n\tfor (const list of slots.values()) {\n\t\tif (new Set(list.map((e) => canonical(e))).size > 1) {\n\t\t\tfor (const e of list) drop.add(e.id);\n\t\t}\n\t}\n\treturn edges.filter((e) => !drop.has(e.id));\n}\n\n/** Build kernel inputs plus a MetaState for one safe checkpoint. Host-owned inputs only. */\nexport function toMetaState(input: RuntimeBridgeInput): RuntimeBridgeResult {\n\ttext(input.taskId, \"taskId\", 128);\n\ttext(input.stageId, \"stageId\", 128);\n\ttext(input.goalScope, \"goalScope\", 256);\n\ttext(input.targetArtifact, \"targetArtifact\", 512);\n\ttext(input.candidateHash, \"candidateHash\", 128);\n\ttext(input.environmentHash, \"environmentHash\", 128);\n\ttext(input.policyVersion, \"policyVersion\", 64);\n\ttext(input.modelRevision, \"modelRevision\", 128);\n\tinteger(input.nowMs, \"nowMs\");\n\tensure(input.claims.length <= 128 && input.observations.length <= 4096, \"runtime bridge input too large\");\n\tconst binding = `${input.candidateHash}@${input.environmentHash}`;\n\t// Only leaf claims map to kernel claims — compound satisfaction is the\n\t// protocol layer's job, and is now declared instead of dropped silently.\n\tconst compoundIds = input.claims.filter((c) => c.satisfaction.inputs.length > 0).map((c) => c.claimId);\n\tconst leafClaims = input.claims.filter((c) => c.satisfaction.inputs.length === 0);\n\tconst claimById = new Map<string, Claim>();\n\tconst claimLosses: BridgeLoss[] = [];\n\tfor (const c of leafClaims) {\n\t\tconst m = mapClaim(c, input.stage, binding);\n\t\tif (m.status === \"rejected\") {\n\t\t\tclaimLosses.push(lossOf({ unmappedClaims: [`claim:${c.claimId}`], rejectedObservations: [] }));\n\t\t\tcontinue;\n\t\t}\n\t\tclaimById.set(c.claimId, m.claim);\n\t\tif (m.status === \"partial\") claimLosses.push(m.loss);\n\t}\n\tconst kernelClaims = [...claimById.values()].sort((a, b) => lexical(a.id, b.id));\n\tconst claimFloors = new Map(leafClaims.map((c) => [c.claimId, c.trustFloor] as const));\n\tconst baseSources = sourceIdentities(input.sources ?? []);\n\tconst ctx: ObservationMapContext = {\n\t\tbinding,\n\t\tnowMs: input.nowMs,\n\t\tgeneration: input.generation,\n\t\tclaimById,\n\t\tclaimFloors,\n\t\tsources: baseSources,\n\t};\n\tconst emitted: Observation[] = [];\n\tconst usedSources = new Map<string, SourceIdentity>();\n\tconst obsLosses: BridgeLoss[] = [];\n\tconst rejectedObs: { id: string; reason: string }[] = [];\n\tfor (const o of input.observations) {\n\t\tconst r = mapObservation(o, ctx);\n\t\tif (r.status === \"rejected\") {\n\t\t\trejectedObs.push({ id: o.observationId, reason: r.reason });\n\t\t\tcontinue;\n\t\t}\n\t\temitted.push(...r.observations);\n\t\tfor (const s of r.sources) usedSources.set(s.id, s);\n\t\tif (r.status === \"partial\") obsLosses.push(r.loss);\n\t}\n\tconst kernelObservations = suppressConflictingSequences(emitted);\n\tconst bridgeLoss = mergeBridgeLoss([...claimLosses, ...obsLosses]);\n\tconst conflicts = familyConflicts(emitted, rejectedObs, input.observations, claimById);\n\tconst loss: BridgeLoss = {\n\t\t...bridgeLoss,\n\t\tunmappedClaims: [...bridgeLoss.unmappedClaims, ...compoundIds.map((id) => `claim:${id}`)].sort(lexical),\n\t\tsourceFamilyConflicts: [...bridgeLoss.sourceFamilyConflicts, ...conflicts].sort(lexical),\n\t\trejectedObservations: [...bridgeLoss.rejectedObservations, ...rejectedObs].sort((a, b) => lexical(a.id, b.id)),\n\t};\n\tconst requiredIds = new Set(input.claims.filter((c) => c.severity === \"required\").map((c) => c.claimId));\n\tconst touched = new Set<string>();\n\tfor (const u of loss.unmappedClaims) {\n\t\tfor (const id of requiredIds) {\n\t\t\tif (u === `claim:${id}` || u.endsWith(`->${id}`)) touched.add(id);\n\t\t}\n\t}\n\tfor (const obsId of loss.unknownBindings) {\n\t\tconst src = input.observations.find((o) => o.observationId === obsId);\n\t\tfor (const c of src?.claimIds ?? []) if (requiredIds.has(c)) touched.add(c);\n\t}\n\tfor (const r of loss.rejectedObservations) {\n\t\tconst src = input.observations.find((o) => o.observationId === r.id);\n\t\tfor (const c of src?.claimIds ?? []) if (requiredIds.has(c)) touched.add(c);\n\t}\n\tfor (const f of loss.lostFields) {\n\t\tif (f.startsWith(\"claim:\")) {\n\t\t\tconst id = f.slice(\"claim:\".length).split(\".\")[0] ?? \"\";\n\t\t\tif (requiredIds.has(id)) touched.add(id);\n\t\t\tcontinue;\n\t\t}\n\t\tconst obsId = f.split(\".\")[0] ?? \"\";\n\t\tconst src = input.observations.find((o) => o.observationId === obsId);\n\t\tfor (const c of src?.claimIds ?? []) if (requiredIds.has(c)) touched.add(c);\n\t}\n\tconst state: MetaState = {\n\t\tgoal: {\n\t\t\ttaskId: input.taskId,\n\t\t\tstageId: input.stageId,\n\t\t\ttargetArtifact: input.targetArtifact,\n\t\t\tgoalScope: input.goalScope,\n\t\t},\n\t\tfacts: {\n\t\t\tcandidateHash: input.candidateHash,\n\t\t\tenvironmentHash: input.environmentHash,\n\t\t\tchangeScope: [input.targetArtifact],\n\t\t\tanalyzerCoverage: \"unknown\",\n\t\t},\n\t\tobligations: [],\n\t\tevidence: { report: null, adoptedSourceIds: [] },\n\t\tpredictions: [],\n\t\thypotheses: { open: [], discriminatorCandidates: [], modelMismatch: false },\n\t\tcalibration: createCalibrationStore({\n\t\t\tminSamples: 5,\n\t\t\tpriorAlpha: 1,\n\t\t\tpriorBeta: 1,\n\t\t\treferenceMean: 0.3,\n\t\t\tslack: 0.15,\n\t\t\tthreshold: 3,\n\t\t}),\n\t\tverifier: { evaluations: [], runnerHealth: \"unverified\" },\n\t\tbudget: input.budget,\n\t\tpolicy: {\n\t\t\tpolicyVersion: input.policyVersion,\n\t\t\tauthorizedActions: input.authorizedActions,\n\t\t\trequiredApprovals: [],\n\t\t\tinterruptionReason: input.interruptionReason ?? null,\n\t\t},\n\t\thostSequence: 0,\n\t\tprogressHistory: input.progressHistory ?? [],\n\t\tcheckpointCount: 0,\n\t};\n\tconst sources = [...new Map([...baseSources, ...usedSources.values()].map((s) => [s.id, s])).values()];\n\tconst value: RuntimeBridgeOutput = { state, claims: kernelClaims, observations: kernelObservations, sources };\n\tconst empty =\n\t\tloss.lostFields.length === 0 &&\n\t\tloss.unmappedClaims.length === 0 &&\n\t\tloss.unknownBindings.length === 0 &&\n\t\tloss.sourceFamilyConflicts.length === 0 &&\n\t\tloss.rejectedObservations.length === 0;\n\tif (empty) return { status: \"mapped\", value };\n\treturn {\n\t\tstatus: \"partial\",\n\t\tvalue,\n\t\tloss,\n\t\ttouchesRequiredClaims: [...touched].sort(lexical),\n\t};\n}\n\n/** Sources admitted for reference evidence: only repository/official qualify. */\nexport function sourceIdentities(overrides: readonly SourceIdentity[] = []): readonly SourceIdentity[] {\n\treturn [\n\t\t{ id: \"deterministic_validator\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"workspace_witness\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"trusted_attestation\", family: \"attestation\", kind: \"official\" },\n\t\t{ id: \"effect_reconciliation\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"independent_review\", family: \"review\", kind: \"official\" },\n\t\t{ id: \"self_review\", family: \"model\", kind: \"model\" },\n\t\t{ id: \"model_narrative\", family: \"model\", kind: \"model\" },\n\t\t...overrides,\n\t];\n}\n"]}
|