open-multi-agent-kit 1.0.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (622) hide show
  1. package/CHANGELOG.md +52 -1
  2. package/README.md +2 -2
  3. package/dist/approval-api.d.ts +5 -0
  4. package/dist/approval-api.d.ts.map +1 -0
  5. package/dist/approval-api.js +5 -0
  6. package/dist/approval-api.js.map +1 -0
  7. package/dist/cli/help.d.ts.map +1 -1
  8. package/dist/cli/help.js +1 -0
  9. package/dist/cli/help.js.map +1 -1
  10. package/dist/cli/session-picker.d.ts +2 -2
  11. package/dist/cli/session-picker.d.ts.map +1 -1
  12. package/dist/cli/session-picker.js.map +1 -1
  13. package/dist/commands/verified-run-cli.d.ts.map +1 -1
  14. package/dist/commands/verified-run-cli.js +69 -22
  15. package/dist/commands/verified-run-cli.js.map +1 -1
  16. package/dist/commands/verified-run-signal.d.ts +3 -0
  17. package/dist/commands/verified-run-signal.d.ts.map +1 -0
  18. package/dist/commands/verified-run-signal.js +15 -0
  19. package/dist/commands/verified-run-signal.js.map +1 -0
  20. package/dist/coordination/awareness.d.ts +32 -0
  21. package/dist/coordination/awareness.d.ts.map +1 -0
  22. package/dist/coordination/awareness.js +55 -0
  23. package/dist/coordination/awareness.js.map +1 -0
  24. package/dist/coordination/broker.d.ts +79 -0
  25. package/dist/coordination/broker.d.ts.map +1 -0
  26. package/dist/coordination/broker.js +202 -0
  27. package/dist/coordination/broker.js.map +1 -0
  28. package/dist/coordination/index.d.ts +16 -0
  29. package/dist/coordination/index.d.ts.map +1 -0
  30. package/dist/coordination/index.js +16 -0
  31. package/dist/coordination/index.js.map +1 -0
  32. package/dist/coordination/integration.d.ts +59 -0
  33. package/dist/coordination/integration.d.ts.map +1 -0
  34. package/dist/coordination/integration.js +126 -0
  35. package/dist/coordination/integration.js.map +1 -0
  36. package/dist/coordination/operation.d.ts +107 -0
  37. package/dist/coordination/operation.d.ts.map +1 -0
  38. package/dist/coordination/operation.js +231 -0
  39. package/dist/coordination/operation.js.map +1 -0
  40. package/dist/coordination/resource.d.ts +33 -0
  41. package/dist/coordination/resource.d.ts.map +1 -0
  42. package/dist/coordination/resource.js +95 -0
  43. package/dist/coordination/resource.js.map +1 -0
  44. package/dist/coordination/session.d.ts +74 -0
  45. package/dist/coordination/session.d.ts.map +1 -0
  46. package/dist/coordination/session.js +143 -0
  47. package/dist/coordination/session.js.map +1 -0
  48. package/dist/coordination/types.d.ts +68 -0
  49. package/dist/coordination/types.d.ts.map +1 -0
  50. package/dist/coordination/types.js +26 -0
  51. package/dist/coordination/types.js.map +1 -0
  52. package/dist/core/adaptorch-bridge.d.ts +1 -1
  53. package/dist/core/adaptorch-bridge.d.ts.map +1 -1
  54. package/dist/core/adaptorch-bridge.js +1 -1
  55. package/dist/core/adaptorch-bridge.js.map +1 -1
  56. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  57. package/dist/core/agent-session-runtime.js +16 -16
  58. package/dist/core/agent-session-runtime.js.map +1 -1
  59. package/dist/core/agent-session.d.ts.map +1 -1
  60. package/dist/core/agent-session.js +35 -15
  61. package/dist/core/agent-session.js.map +1 -1
  62. package/dist/core/canonical-json.d.ts +3 -0
  63. package/dist/core/canonical-json.d.ts.map +1 -0
  64. package/dist/core/canonical-json.js +20 -0
  65. package/dist/core/canonical-json.js.map +1 -0
  66. package/dist/core/compaction/compaction.d.ts +7 -3
  67. package/dist/core/compaction/compaction.d.ts.map +1 -1
  68. package/dist/core/compaction/compaction.js +14 -29
  69. package/dist/core/compaction/compaction.js.map +1 -1
  70. package/dist/core/compaction/control-state.d.ts +41 -0
  71. package/dist/core/compaction/control-state.d.ts.map +1 -0
  72. package/dist/core/compaction/control-state.js +85 -0
  73. package/dist/core/compaction/control-state.js.map +1 -0
  74. package/dist/core/compaction/fallback.d.ts +71 -0
  75. package/dist/core/compaction/fallback.d.ts.map +1 -0
  76. package/dist/core/compaction/fallback.js +118 -0
  77. package/dist/core/compaction/fallback.js.map +1 -0
  78. package/dist/core/compaction/index.d.ts +2 -0
  79. package/dist/core/compaction/index.d.ts.map +1 -1
  80. package/dist/core/compaction/index.js +2 -0
  81. package/dist/core/compaction/index.js.map +1 -1
  82. package/dist/core/compaction/model-failover.d.ts +21 -0
  83. package/dist/core/compaction/model-failover.d.ts.map +1 -0
  84. package/dist/core/compaction/model-failover.js +46 -0
  85. package/dist/core/compaction/model-failover.js.map +1 -0
  86. package/dist/core/compaction/session-summary.d.ts +21 -0
  87. package/dist/core/compaction/session-summary.d.ts.map +1 -0
  88. package/dist/core/compaction/session-summary.js +27 -0
  89. package/dist/core/compaction/session-summary.js.map +1 -0
  90. package/dist/core/context-budget-headroom-candidates.d.ts +16 -1
  91. package/dist/core/context-budget-headroom-candidates.d.ts.map +1 -1
  92. package/dist/core/context-budget-headroom-candidates.js +31 -13
  93. package/dist/core/context-budget-headroom-candidates.js.map +1 -1
  94. package/dist/core/context-budget-headroom-types.d.ts +7 -1
  95. package/dist/core/context-budget-headroom-types.d.ts.map +1 -1
  96. package/dist/core/context-budget-headroom-types.js +0 -1
  97. package/dist/core/context-budget-headroom-types.js.map +1 -1
  98. package/dist/core/context-budget-headroom.d.ts +10 -0
  99. package/dist/core/context-budget-headroom.d.ts.map +1 -1
  100. package/dist/core/context-budget-headroom.js +11 -2
  101. package/dist/core/context-budget-headroom.js.map +1 -1
  102. package/dist/core/context-budget-v2-global-pass.d.ts +21 -0
  103. package/dist/core/context-budget-v2-global-pass.d.ts.map +1 -0
  104. package/dist/core/context-budget-v2-global-pass.js +203 -0
  105. package/dist/core/context-budget-v2-global-pass.js.map +1 -0
  106. package/dist/core/context-budget-v2-planned-items.d.ts +12 -0
  107. package/dist/core/context-budget-v2-planned-items.d.ts.map +1 -1
  108. package/dist/core/context-budget-v2-planned-items.js +21 -2
  109. package/dist/core/context-budget-v2-planned-items.js.map +1 -1
  110. package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
  111. package/dist/core/context-budget-v2-planner.js +18 -19
  112. package/dist/core/context-budget-v2-planner.js.map +1 -1
  113. package/dist/core/context-budget-v2-scoring.d.ts +7 -1
  114. package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
  115. package/dist/core/context-budget-v2-scoring.js.map +1 -1
  116. package/dist/core/context-budget-v2-selection.d.ts +3 -0
  117. package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
  118. package/dist/core/context-budget-v2-selection.js +6 -2
  119. package/dist/core/context-budget-v2-selection.js.map +1 -1
  120. package/dist/core/context-budget-v2-types.d.ts +6 -1
  121. package/dist/core/context-budget-v2-types.d.ts.map +1 -1
  122. package/dist/core/context-budget-v2-types.js +6 -1
  123. package/dist/core/context-budget-v2-types.js.map +1 -1
  124. package/dist/core/export-html/template.js +14 -0
  125. package/dist/core/extensions/index.d.ts +1 -1
  126. package/dist/core/extensions/index.d.ts.map +1 -1
  127. package/dist/core/extensions/index.js.map +1 -1
  128. package/dist/core/extensions/session-lifecycle-types.d.ts +14 -0
  129. package/dist/core/extensions/session-lifecycle-types.d.ts.map +1 -0
  130. package/dist/core/extensions/session-lifecycle-types.js +2 -0
  131. package/dist/core/extensions/session-lifecycle-types.js.map +1 -0
  132. package/dist/core/extensions/types.d.ts +4 -9
  133. package/dist/core/extensions/types.d.ts.map +1 -1
  134. package/dist/core/extensions/types.js.map +1 -1
  135. package/dist/core/http-dispatcher.d.ts.map +1 -1
  136. package/dist/core/http-dispatcher.js +10 -1
  137. package/dist/core/http-dispatcher.js.map +1 -1
  138. package/dist/core/keybindings.d.ts.map +1 -1
  139. package/dist/core/keybindings.js +3 -6
  140. package/dist/core/keybindings.js.map +1 -1
  141. package/dist/core/legacy-resource-policy.d.ts +7 -0
  142. package/dist/core/legacy-resource-policy.d.ts.map +1 -0
  143. package/dist/core/legacy-resource-policy.js +9 -0
  144. package/dist/core/legacy-resource-policy.js.map +1 -0
  145. package/dist/core/mcp/config.d.ts.map +1 -1
  146. package/dist/core/mcp/config.js +17 -3
  147. package/dist/core/mcp/config.js.map +1 -1
  148. package/dist/core/mcp/connection-queue.d.ts +12 -0
  149. package/dist/core/mcp/connection-queue.d.ts.map +1 -0
  150. package/dist/core/mcp/connection-queue.js +46 -0
  151. package/dist/core/mcp/connection-queue.js.map +1 -0
  152. package/dist/core/mcp/manager-runtime.d.ts +55 -0
  153. package/dist/core/mcp/manager-runtime.d.ts.map +1 -0
  154. package/dist/core/mcp/manager-runtime.js +66 -0
  155. package/dist/core/mcp/manager-runtime.js.map +1 -0
  156. package/dist/core/mcp/manager.d.ts +12 -68
  157. package/dist/core/mcp/manager.d.ts.map +1 -1
  158. package/dist/core/mcp/manager.js +33 -113
  159. package/dist/core/mcp/manager.js.map +1 -1
  160. package/dist/core/mcp/protocol.d.ts.map +1 -1
  161. package/dist/core/mcp/protocol.js +70 -40
  162. package/dist/core/mcp/protocol.js.map +1 -1
  163. package/dist/core/package-manager.d.ts +4 -0
  164. package/dist/core/package-manager.d.ts.map +1 -1
  165. package/dist/core/package-manager.js +59 -129
  166. package/dist/core/package-manager.js.map +1 -1
  167. package/dist/core/package-resource-patterns.d.ts +7 -0
  168. package/dist/core/package-resource-patterns.d.ts.map +1 -0
  169. package/dist/core/package-resource-patterns.js +99 -0
  170. package/dist/core/package-resource-patterns.js.map +1 -0
  171. package/dist/core/provider-default-models.d.ts +1 -0
  172. package/dist/core/provider-default-models.d.ts.map +1 -1
  173. package/dist/core/provider-default-models.js +1 -0
  174. package/dist/core/provider-default-models.js.map +1 -1
  175. package/dist/core/provider-display-names.d.ts.map +1 -1
  176. package/dist/core/provider-display-names.js +1 -0
  177. package/dist/core/provider-display-names.js.map +1 -1
  178. package/dist/core/provider-resilience.d.ts +9 -0
  179. package/dist/core/provider-resilience.d.ts.map +1 -1
  180. package/dist/core/provider-resilience.js +15 -0
  181. package/dist/core/provider-resilience.js.map +1 -1
  182. package/dist/core/reasoning-router-resolver.d.ts +7 -0
  183. package/dist/core/reasoning-router-resolver.d.ts.map +1 -1
  184. package/dist/core/reasoning-router-resolver.js +21 -3
  185. package/dist/core/reasoning-router-resolver.js.map +1 -1
  186. package/dist/core/reasoning-router-v4.d.ts +13 -7
  187. package/dist/core/reasoning-router-v4.d.ts.map +1 -1
  188. package/dist/core/reasoning-router-v4.js +8 -5
  189. package/dist/core/reasoning-router-v4.js.map +1 -1
  190. package/dist/core/resource-loader.d.ts.map +1 -1
  191. package/dist/core/resource-loader.js +4 -8
  192. package/dist/core/resource-loader.js.map +1 -1
  193. package/dist/core/run-execution-api.d.ts +8 -1
  194. package/dist/core/run-execution-api.d.ts.map +1 -1
  195. package/dist/core/run-execution-api.js +4 -0
  196. package/dist/core/run-execution-api.js.map +1 -1
  197. package/dist/core/run-journal.d.ts +1 -2
  198. package/dist/core/run-journal.d.ts.map +1 -1
  199. package/dist/core/run-journal.js +2 -19
  200. package/dist/core/run-journal.js.map +1 -1
  201. package/dist/core/session-compaction-service.d.ts +15 -0
  202. package/dist/core/session-compaction-service.d.ts.map +1 -1
  203. package/dist/core/session-compaction-service.js +17 -4
  204. package/dist/core/session-compaction-service.js.map +1 -1
  205. package/dist/core/session-listing.d.ts +51 -0
  206. package/dist/core/session-listing.d.ts.map +1 -0
  207. package/dist/core/session-listing.js +111 -0
  208. package/dist/core/session-listing.js.map +1 -0
  209. package/dist/core/session-manager.d.ts +12 -37
  210. package/dist/core/session-manager.d.ts.map +1 -1
  211. package/dist/core/session-manager.js +12 -118
  212. package/dist/core/session-manager.js.map +1 -1
  213. package/dist/core/session-message-text.d.ts +5 -0
  214. package/dist/core/session-message-text.d.ts.map +1 -0
  215. package/dist/core/session-message-text.js +9 -0
  216. package/dist/core/session-message-text.js.map +1 -0
  217. package/dist/core/skills-catalog-cache.d.ts +2 -0
  218. package/dist/core/skills-catalog-cache.d.ts.map +1 -1
  219. package/dist/core/skills-catalog-cache.js +71 -17
  220. package/dist/core/skills-catalog-cache.js.map +1 -1
  221. package/dist/core/todo-runtime-state.d.ts +12 -0
  222. package/dist/core/todo-runtime-state.d.ts.map +1 -1
  223. package/dist/core/todo-runtime-state.js +23 -0
  224. package/dist/core/todo-runtime-state.js.map +1 -1
  225. package/dist/core/tools/read.d.ts.map +1 -1
  226. package/dist/core/tools/read.js +1 -1
  227. package/dist/core/tools/read.js.map +1 -1
  228. package/dist/core/verified-run/authority-clock.d.ts +3 -0
  229. package/dist/core/verified-run/authority-clock.d.ts.map +1 -0
  230. package/dist/core/verified-run/authority-clock.js +25 -0
  231. package/dist/core/verified-run/authority-clock.js.map +1 -0
  232. package/dist/core/verified-run/authority-errors.d.ts +10 -0
  233. package/dist/core/verified-run/authority-errors.d.ts.map +1 -0
  234. package/dist/core/verified-run/authority-errors.js +17 -0
  235. package/dist/core/verified-run/authority-errors.js.map +1 -0
  236. package/dist/core/verified-run/authority-events.d.ts +126 -0
  237. package/dist/core/verified-run/authority-events.d.ts.map +1 -0
  238. package/dist/core/verified-run/authority-events.js +482 -0
  239. package/dist/core/verified-run/authority-events.js.map +1 -0
  240. package/dist/core/verified-run/authority-journal.d.ts +27 -0
  241. package/dist/core/verified-run/authority-journal.d.ts.map +1 -0
  242. package/dist/core/verified-run/authority-journal.js +83 -0
  243. package/dist/core/verified-run/authority-journal.js.map +1 -0
  244. package/dist/core/verified-run/authority-meaning.d.ts +13 -0
  245. package/dist/core/verified-run/authority-meaning.d.ts.map +1 -0
  246. package/dist/core/verified-run/authority-meaning.js +40 -0
  247. package/dist/core/verified-run/authority-meaning.js.map +1 -0
  248. package/dist/core/verified-run/authority-runtime.d.ts +82 -0
  249. package/dist/core/verified-run/authority-runtime.d.ts.map +1 -0
  250. package/dist/core/verified-run/authority-runtime.js +169 -0
  251. package/dist/core/verified-run/authority-runtime.js.map +1 -0
  252. package/dist/core/verified-run/authority-store.d.ts +204 -0
  253. package/dist/core/verified-run/authority-store.d.ts.map +1 -0
  254. package/dist/core/verified-run/authority-store.js +852 -0
  255. package/dist/core/verified-run/authority-store.js.map +1 -0
  256. package/dist/core/verified-run/broker.d.ts +8 -1
  257. package/dist/core/verified-run/broker.d.ts.map +1 -1
  258. package/dist/core/verified-run/broker.js +94 -90
  259. package/dist/core/verified-run/broker.js.map +1 -1
  260. package/dist/core/verified-run/candidate-policy.d.ts +10 -0
  261. package/dist/core/verified-run/candidate-policy.d.ts.map +1 -0
  262. package/dist/core/verified-run/candidate-policy.js +33 -0
  263. package/dist/core/verified-run/candidate-policy.js.map +1 -0
  264. package/dist/core/verified-run/candidate.d.ts.map +1 -1
  265. package/dist/core/verified-run/candidate.js +5 -10
  266. package/dist/core/verified-run/candidate.js.map +1 -1
  267. package/dist/core/verified-run/coordinator.d.ts +35 -17
  268. package/dist/core/verified-run/coordinator.d.ts.map +1 -1
  269. package/dist/core/verified-run/coordinator.js +111 -57
  270. package/dist/core/verified-run/coordinator.js.map +1 -1
  271. package/dist/core/verified-run/dag-phase.d.ts.map +1 -1
  272. package/dist/core/verified-run/dag-phase.js +1 -1
  273. package/dist/core/verified-run/dag-phase.js.map +1 -1
  274. package/dist/core/verified-run/dag-recovery.d.ts +5 -1
  275. package/dist/core/verified-run/dag-recovery.d.ts.map +1 -1
  276. package/dist/core/verified-run/dag-recovery.js +10 -4
  277. package/dist/core/verified-run/dag-recovery.js.map +1 -1
  278. package/dist/core/verified-run/event-parser.d.ts.map +1 -1
  279. package/dist/core/verified-run/event-parser.js +33 -0
  280. package/dist/core/verified-run/event-parser.js.map +1 -1
  281. package/dist/core/verified-run/evidence-read-projection.d.ts +4 -0
  282. package/dist/core/verified-run/evidence-read-projection.d.ts.map +1 -0
  283. package/dist/core/verified-run/evidence-read-projection.js +27 -0
  284. package/dist/core/verified-run/evidence-read-projection.js.map +1 -0
  285. package/dist/core/verified-run/evidence.d.ts +12 -1
  286. package/dist/core/verified-run/evidence.d.ts.map +1 -1
  287. package/dist/core/verified-run/evidence.js +51 -2
  288. package/dist/core/verified-run/evidence.js.map +1 -1
  289. package/dist/core/verified-run/git-candidate-preflight.d.ts +4 -0
  290. package/dist/core/verified-run/git-candidate-preflight.d.ts.map +1 -0
  291. package/dist/core/verified-run/git-candidate-preflight.js +34 -0
  292. package/dist/core/verified-run/git-candidate-preflight.js.map +1 -0
  293. package/dist/core/verified-run/git-effect-supervisor.d.ts +24 -0
  294. package/dist/core/verified-run/git-effect-supervisor.d.ts.map +1 -0
  295. package/dist/core/verified-run/git-effect-supervisor.js +174 -0
  296. package/dist/core/verified-run/git-effect-supervisor.js.map +1 -0
  297. package/dist/core/verified-run/git-execution.d.ts +27 -0
  298. package/dist/core/verified-run/git-execution.d.ts.map +1 -0
  299. package/dist/core/verified-run/git-execution.js +118 -0
  300. package/dist/core/verified-run/git-execution.js.map +1 -0
  301. package/dist/core/verified-run/git-plumbing.d.ts +37 -0
  302. package/dist/core/verified-run/git-plumbing.d.ts.map +1 -0
  303. package/dist/core/verified-run/git-plumbing.js +171 -0
  304. package/dist/core/verified-run/git-plumbing.js.map +1 -0
  305. package/dist/core/verified-run/git-publication-worker.d.ts +2 -0
  306. package/dist/core/verified-run/git-publication-worker.d.ts.map +1 -0
  307. package/dist/core/verified-run/git-publication-worker.js +54 -0
  308. package/dist/core/verified-run/git-publication-worker.js.map +1 -0
  309. package/dist/core/verified-run/git-sandbox-layout.d.ts +4 -0
  310. package/dist/core/verified-run/git-sandbox-layout.d.ts.map +1 -0
  311. package/dist/core/verified-run/git-sandbox-layout.js +29 -0
  312. package/dist/core/verified-run/git-sandbox-layout.js.map +1 -0
  313. package/dist/core/verified-run/git-worker-protocol.d.ts +19 -0
  314. package/dist/core/verified-run/git-worker-protocol.d.ts.map +1 -0
  315. package/dist/core/verified-run/git-worker-protocol.js +109 -0
  316. package/dist/core/verified-run/git-worker-protocol.js.map +1 -0
  317. package/dist/core/verified-run/git-worker-runtime.d.ts +19 -0
  318. package/dist/core/verified-run/git-worker-runtime.d.ts.map +1 -0
  319. package/dist/core/verified-run/git-worker-runtime.js +74 -0
  320. package/dist/core/verified-run/git-worker-runtime.js.map +1 -0
  321. package/dist/core/verified-run/journal.d.ts +2 -3
  322. package/dist/core/verified-run/journal.d.ts.map +1 -1
  323. package/dist/core/verified-run/journal.js.map +1 -1
  324. package/dist/core/verified-run/namespace-identity.d.ts.map +1 -1
  325. package/dist/core/verified-run/namespace-identity.js +1 -1
  326. package/dist/core/verified-run/namespace-identity.js.map +1 -1
  327. package/dist/core/verified-run/owned-execution.d.ts +10 -1
  328. package/dist/core/verified-run/owned-execution.d.ts.map +1 -1
  329. package/dist/core/verified-run/owned-execution.js +124 -31
  330. package/dist/core/verified-run/owned-execution.js.map +1 -1
  331. package/dist/core/verified-run/phase-context.d.ts +2 -0
  332. package/dist/core/verified-run/phase-context.d.ts.map +1 -1
  333. package/dist/core/verified-run/phase-context.js.map +1 -1
  334. package/dist/core/verified-run/projection.d.ts.map +1 -1
  335. package/dist/core/verified-run/projection.js +51 -1
  336. package/dist/core/verified-run/projection.js.map +1 -1
  337. package/dist/core/verified-run/publish-preflight.d.ts +12 -0
  338. package/dist/core/verified-run/publish-preflight.d.ts.map +1 -0
  339. package/dist/core/verified-run/publish-preflight.js +38 -0
  340. package/dist/core/verified-run/publish-preflight.js.map +1 -0
  341. package/dist/core/verified-run/publish-start.d.ts +5 -0
  342. package/dist/core/verified-run/publish-start.d.ts.map +1 -0
  343. package/dist/core/verified-run/publish-start.js +7 -0
  344. package/dist/core/verified-run/publish-start.js.map +1 -0
  345. package/dist/core/verified-run/recovery-projection.d.ts.map +1 -1
  346. package/dist/core/verified-run/recovery-projection.js +5 -0
  347. package/dist/core/verified-run/recovery-projection.js.map +1 -1
  348. package/dist/core/verified-run/recovery.d.ts +5 -1
  349. package/dist/core/verified-run/recovery.d.ts.map +1 -1
  350. package/dist/core/verified-run/recovery.js +10 -4
  351. package/dist/core/verified-run/recovery.js.map +1 -1
  352. package/dist/core/verified-run/run-plan.d.ts +17 -0
  353. package/dist/core/verified-run/run-plan.d.ts.map +1 -0
  354. package/dist/core/verified-run/run-plan.js +18 -0
  355. package/dist/core/verified-run/run-plan.js.map +1 -0
  356. package/dist/core/verified-run/run-publish-owned.d.ts +6 -0
  357. package/dist/core/verified-run/run-publish-owned.d.ts.map +1 -0
  358. package/dist/core/verified-run/run-publish-owned.js +199 -0
  359. package/dist/core/verified-run/run-publish-owned.js.map +1 -0
  360. package/dist/core/verified-run/run-publish.d.ts +19 -0
  361. package/dist/core/verified-run/run-publish.d.ts.map +1 -0
  362. package/dist/core/verified-run/run-publish.js +210 -0
  363. package/dist/core/verified-run/run-publish.js.map +1 -0
  364. package/dist/core/verified-run/run-status-owned.d.ts +4 -0
  365. package/dist/core/verified-run/run-status-owned.d.ts.map +1 -0
  366. package/dist/core/verified-run/run-status-owned.js +14 -0
  367. package/dist/core/verified-run/run-status-owned.js.map +1 -0
  368. package/dist/core/verified-run/run-status.d.ts +133 -0
  369. package/dist/core/verified-run/run-status.d.ts.map +1 -0
  370. package/dist/core/verified-run/run-status.js +193 -0
  371. package/dist/core/verified-run/run-status.js.map +1 -0
  372. package/dist/core/verified-run/run-types.d.ts +31 -0
  373. package/dist/core/verified-run/run-types.d.ts.map +1 -1
  374. package/dist/core/verified-run/run-types.js.map +1 -1
  375. package/dist/core/verified-run/storage.d.ts.map +1 -1
  376. package/dist/core/verified-run/storage.js +1 -1
  377. package/dist/core/verified-run/storage.js.map +1 -1
  378. package/dist/core/verified-run/supervisor-adapter.d.ts +77 -0
  379. package/dist/core/verified-run/supervisor-adapter.d.ts.map +1 -0
  380. package/dist/core/verified-run/supervisor-adapter.js +164 -0
  381. package/dist/core/verified-run/supervisor-adapter.js.map +1 -0
  382. package/dist/core/verified-run/verification-phase.d.ts.map +1 -1
  383. package/dist/core/verified-run/verification-phase.js +1 -1
  384. package/dist/core/verified-run/verification-phase.js.map +1 -1
  385. package/dist/core/verified-run/writer-phase.d.ts.map +1 -1
  386. package/dist/core/verified-run/writer-phase.js +1 -0
  387. package/dist/core/verified-run/writer-phase.js.map +1 -1
  388. package/dist/core/verified-run/writer-recovery.d.ts +2 -0
  389. package/dist/core/verified-run/writer-recovery.d.ts.map +1 -1
  390. package/dist/core/verified-run/writer-recovery.js +1 -0
  391. package/dist/core/verified-run/writer-recovery.js.map +1 -1
  392. package/dist/core/workload-shard-execution-types.d.ts +4 -1
  393. package/dist/core/workload-shard-execution-types.d.ts.map +1 -1
  394. package/dist/core/workload-shard-execution-types.js.map +1 -1
  395. package/dist/core/workload-shard-executor.d.ts +2 -2
  396. package/dist/core/workload-shard-executor.d.ts.map +1 -1
  397. package/dist/core/workload-shard-executor.js +16 -37
  398. package/dist/core/workload-shard-executor.js.map +1 -1
  399. package/dist/core/workload-shard-frontier.d.ts +5 -0
  400. package/dist/core/workload-shard-frontier.d.ts.map +1 -0
  401. package/dist/core/workload-shard-frontier.js +47 -0
  402. package/dist/core/workload-shard-frontier.js.map +1 -0
  403. package/dist/core/workload-shard-runner.d.ts.map +1 -1
  404. package/dist/core/workload-shard-runner.js +28 -17
  405. package/dist/core/workload-shard-runner.js.map +1 -1
  406. package/dist/index.d.ts +4 -5
  407. package/dist/index.d.ts.map +1 -1
  408. package/dist/index.js +3 -4
  409. package/dist/index.js.map +1 -1
  410. package/dist/main.d.ts.map +1 -1
  411. package/dist/main.js +2 -1
  412. package/dist/main.js.map +1 -1
  413. package/dist/metacognition/bridge-result.d.ts +148 -0
  414. package/dist/metacognition/bridge-result.d.ts.map +1 -0
  415. package/dist/metacognition/bridge-result.js +46 -0
  416. package/dist/metacognition/bridge-result.js.map +1 -0
  417. package/dist/metacognition/calibration-selective.d.ts +78 -0
  418. package/dist/metacognition/calibration-selective.d.ts.map +1 -0
  419. package/dist/metacognition/calibration-selective.js +167 -0
  420. package/dist/metacognition/calibration-selective.js.map +1 -0
  421. package/dist/metacognition/calibration.d.ts +62 -0
  422. package/dist/metacognition/calibration.d.ts.map +1 -0
  423. package/dist/metacognition/calibration.js +122 -0
  424. package/dist/metacognition/calibration.js.map +1 -0
  425. package/dist/metacognition/checkpoint.d.ts +60 -0
  426. package/dist/metacognition/checkpoint.d.ts.map +1 -0
  427. package/dist/metacognition/checkpoint.js +57 -0
  428. package/dist/metacognition/checkpoint.js.map +1 -0
  429. package/dist/metacognition/context7.d.ts +48 -0
  430. package/dist/metacognition/context7.d.ts.map +1 -0
  431. package/dist/metacognition/context7.js +154 -0
  432. package/dist/metacognition/context7.js.map +1 -0
  433. package/dist/metacognition/decision.d.ts +44 -0
  434. package/dist/metacognition/decision.d.ts.map +1 -0
  435. package/dist/metacognition/decision.js +111 -0
  436. package/dist/metacognition/decision.js.map +1 -0
  437. package/dist/metacognition/evaluation.d.ts +73 -0
  438. package/dist/metacognition/evaluation.d.ts.map +1 -0
  439. package/dist/metacognition/evaluation.js +97 -0
  440. package/dist/metacognition/evaluation.js.map +1 -0
  441. package/dist/metacognition/index.d.ts +32 -0
  442. package/dist/metacognition/index.d.ts.map +1 -0
  443. package/dist/metacognition/index.js +32 -0
  444. package/dist/metacognition/index.js.map +1 -0
  445. package/dist/metacognition/knowledge-action.d.ts +43 -0
  446. package/dist/metacognition/knowledge-action.d.ts.map +1 -0
  447. package/dist/metacognition/knowledge-action.js +60 -0
  448. package/dist/metacognition/knowledge-action.js.map +1 -0
  449. package/dist/metacognition/knowledge.d.ts +84 -0
  450. package/dist/metacognition/knowledge.d.ts.map +1 -0
  451. package/dist/metacognition/knowledge.js +165 -0
  452. package/dist/metacognition/knowledge.js.map +1 -0
  453. package/dist/metacognition/obligations.d.ts +82 -0
  454. package/dist/metacognition/obligations.d.ts.map +1 -0
  455. package/dist/metacognition/obligations.js +139 -0
  456. package/dist/metacognition/obligations.js.map +1 -0
  457. package/dist/metacognition/observation-validity.d.ts +83 -0
  458. package/dist/metacognition/observation-validity.d.ts.map +1 -0
  459. package/dist/metacognition/observation-validity.js +118 -0
  460. package/dist/metacognition/observation-validity.js.map +1 -0
  461. package/dist/metacognition/observe.d.ts +45 -0
  462. package/dist/metacognition/observe.d.ts.map +1 -0
  463. package/dist/metacognition/observe.js +59 -0
  464. package/dist/metacognition/observe.js.map +1 -0
  465. package/dist/metacognition/policy.d.ts +53 -0
  466. package/dist/metacognition/policy.d.ts.map +1 -0
  467. package/dist/metacognition/policy.js +155 -0
  468. package/dist/metacognition/policy.js.map +1 -0
  469. package/dist/metacognition/predictions.d.ts +78 -0
  470. package/dist/metacognition/predictions.d.ts.map +1 -0
  471. package/dist/metacognition/predictions.js +181 -0
  472. package/dist/metacognition/predictions.js.map +1 -0
  473. package/dist/metacognition/retrieval.d.ts +53 -0
  474. package/dist/metacognition/retrieval.d.ts.map +1 -0
  475. package/dist/metacognition/retrieval.js +170 -0
  476. package/dist/metacognition/retrieval.js.map +1 -0
  477. package/dist/metacognition/risk.d.ts +48 -0
  478. package/dist/metacognition/risk.d.ts.map +1 -0
  479. package/dist/metacognition/risk.js +179 -0
  480. package/dist/metacognition/risk.js.map +1 -0
  481. package/dist/metacognition/route-economics.d.ts +95 -0
  482. package/dist/metacognition/route-economics.d.ts.map +1 -0
  483. package/dist/metacognition/route-economics.js +110 -0
  484. package/dist/metacognition/route-economics.js.map +1 -0
  485. package/dist/metacognition/runtime-bridge.d.ts +81 -0
  486. package/dist/metacognition/runtime-bridge.d.ts.map +1 -0
  487. package/dist/metacognition/runtime-bridge.js +458 -0
  488. package/dist/metacognition/runtime-bridge.js.map +1 -0
  489. package/dist/metacognition/skills.d.ts +42 -0
  490. package/dist/metacognition/skills.d.ts.map +1 -0
  491. package/dist/metacognition/skills.js +220 -0
  492. package/dist/metacognition/skills.js.map +1 -0
  493. package/dist/metacognition/state.d.ts +110 -0
  494. package/dist/metacognition/state.d.ts.map +1 -0
  495. package/dist/metacognition/state.js +52 -0
  496. package/dist/metacognition/state.js.map +1 -0
  497. package/dist/metacognition/validation.d.ts +19 -0
  498. package/dist/metacognition/validation.d.ts.map +1 -0
  499. package/dist/metacognition/validation.js +58 -0
  500. package/dist/metacognition/validation.js.map +1 -0
  501. package/dist/metacognition/verification.d.ts +93 -0
  502. package/dist/metacognition/verification.d.ts.map +1 -0
  503. package/dist/metacognition/verification.js +132 -0
  504. package/dist/metacognition/verification.js.map +1 -0
  505. package/dist/metacognition/verifier.d.ts +49 -0
  506. package/dist/metacognition/verifier.d.ts.map +1 -0
  507. package/dist/metacognition/verifier.js +88 -0
  508. package/dist/metacognition/verifier.js.map +1 -0
  509. package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
  510. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  511. package/dist/modes/interactive/components/assistant-message.js +42 -26
  512. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  513. package/dist/modes/interactive/components/chat-container.d.ts +7 -0
  514. package/dist/modes/interactive/components/chat-container.d.ts.map +1 -0
  515. package/dist/modes/interactive/components/chat-container.js +14 -0
  516. package/dist/modes/interactive/components/chat-container.js.map +1 -0
  517. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -1
  518. package/dist/modes/interactive/components/dynamic-border.js +4 -2
  519. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  520. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  521. package/dist/modes/interactive/components/login-dialog.js +0 -1
  522. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  523. package/dist/modes/interactive/components/session-selector-async-search.d.ts +33 -0
  524. package/dist/modes/interactive/components/session-selector-async-search.d.ts.map +1 -0
  525. package/dist/modes/interactive/components/session-selector-async-search.js +109 -0
  526. package/dist/modes/interactive/components/session-selector-async-search.js.map +1 -0
  527. package/dist/modes/interactive/components/session-selector-loaders.d.ts +6 -0
  528. package/dist/modes/interactive/components/session-selector-loaders.d.ts.map +1 -0
  529. package/dist/modes/interactive/components/session-selector-loaders.js +9 -0
  530. package/dist/modes/interactive/components/session-selector-loaders.js.map +1 -0
  531. package/dist/modes/interactive/components/session-selector-search.d.ts +1 -1
  532. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  533. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  534. package/dist/modes/interactive/components/session-selector-tree.d.ts +16 -0
  535. package/dist/modes/interactive/components/session-selector-tree.d.ts.map +1 -0
  536. package/dist/modes/interactive/components/session-selector-tree.js +46 -0
  537. package/dist/modes/interactive/components/session-selector-tree.js.map +1 -0
  538. package/dist/modes/interactive/components/session-selector.d.ts +6 -1
  539. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  540. package/dist/modes/interactive/components/session-selector.js +36 -76
  541. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  542. package/dist/modes/interactive/components/tool-execution-images.d.ts +32 -0
  543. package/dist/modes/interactive/components/tool-execution-images.d.ts.map +1 -0
  544. package/dist/modes/interactive/components/tool-execution-images.js +144 -0
  545. package/dist/modes/interactive/components/tool-execution-images.js.map +1 -0
  546. package/dist/modes/interactive/components/tool-execution.d.ts +3 -4
  547. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  548. package/dist/modes/interactive/components/tool-execution.js +22 -71
  549. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  550. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  551. package/dist/modes/interactive/interactive-mode.js +7 -9
  552. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  553. package/dist/modes/interactive/tui-diagnostics.d.ts +8 -4
  554. package/dist/modes/interactive/tui-diagnostics.d.ts.map +1 -1
  555. package/dist/modes/interactive/tui-diagnostics.js +35 -1
  556. package/dist/modes/interactive/tui-diagnostics.js.map +1 -1
  557. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  558. package/dist/modes/rpc/rpc-mode.js +14 -17
  559. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  560. package/dist/modes/rpc/rpc-response.d.ts +5 -0
  561. package/dist/modes/rpc/rpc-response.d.ts.map +1 -0
  562. package/dist/modes/rpc/rpc-response.js +17 -0
  563. package/dist/modes/rpc/rpc-response.js.map +1 -0
  564. package/dist/observation/identity.d.ts +14 -0
  565. package/dist/observation/identity.d.ts.map +1 -0
  566. package/dist/observation/identity.js +29 -0
  567. package/dist/observation/identity.js.map +1 -0
  568. package/dist/observation/index.d.ts +13 -0
  569. package/dist/observation/index.d.ts.map +1 -0
  570. package/dist/observation/index.js +13 -0
  571. package/dist/observation/index.js.map +1 -0
  572. package/dist/observation/observe-mode.d.ts +46 -0
  573. package/dist/observation/observe-mode.d.ts.map +1 -0
  574. package/dist/observation/observe-mode.js +83 -0
  575. package/dist/observation/observe-mode.js.map +1 -0
  576. package/dist/observation/store.d.ts +53 -0
  577. package/dist/observation/store.d.ts.map +1 -0
  578. package/dist/observation/store.js +126 -0
  579. package/dist/observation/store.js.map +1 -0
  580. package/dist/observation/types.d.ts +72 -0
  581. package/dist/observation/types.d.ts.map +1 -0
  582. package/dist/observation/types.js +9 -0
  583. package/dist/observation/types.js.map +1 -0
  584. package/dist/observation/view.d.ts +39 -0
  585. package/dist/observation/view.d.ts.map +1 -0
  586. package/dist/observation/view.js +173 -0
  587. package/dist/observation/view.js.map +1 -0
  588. package/dist/utils/exif-orientation.d.ts.map +1 -1
  589. package/dist/utils/exif-orientation.js +2 -3
  590. package/dist/utils/exif-orientation.js.map +1 -1
  591. package/dist/utils/tools-manager.d.ts.map +1 -1
  592. package/dist/utils/tools-manager.js +3 -5
  593. package/dist/utils/tools-manager.js.map +1 -1
  594. package/docs/adaptorch-preview-spec.md +7 -7
  595. package/docs/atomic-commit-planning.md +69 -0
  596. package/docs/compaction.md +26 -1
  597. package/docs/extensions.md +14 -0
  598. package/docs/mcp.md +22 -0
  599. package/docs/metacognition.md +130 -0
  600. package/docs/model-catalog-refresh.md +218 -1
  601. package/docs/models.md +1 -1
  602. package/docs/providers.md +53 -0
  603. package/docs/runtime-algorithms.md +156 -7
  604. package/docs/session-format.md +8 -0
  605. package/docs/sessions.md +19 -0
  606. package/docs/skills.md +19 -0
  607. package/docs/terminal-setup.md +15 -0
  608. package/docs/tui.md +41 -0
  609. package/docs/verified-run-safety.md +75 -0
  610. package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
  611. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  612. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  613. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  614. package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
  615. package/examples/extensions/gondolin/package-lock.json +2 -2
  616. package/examples/extensions/gondolin/package.json +1 -1
  617. package/examples/extensions/sandbox/package-lock.json +2 -2
  618. package/examples/extensions/sandbox/package.json +1 -1
  619. package/examples/extensions/with-deps/package-lock.json +2 -2
  620. package/examples/extensions/with-deps/package.json +1 -1
  621. package/npm-shrinkwrap.json +18 -18
  622. package/package.json +6 -8
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Finite-sample risk bounds for automation gating (Jev audit algorithm A4).
3
+ *
4
+ * A point estimate must never widen automation scope. Two failures in a
5
+ * hundred is not "a 2% error rate" — its one-sided 95% Clopper–Pearson upper
6
+ * bound is about 6.2%, and that bound is what a gate reads.
7
+ *
8
+ * Scope: this bounds the failure probability of samples drawn under the stated
9
+ * conditions. It is not a safety guarantee for the next action, and it assumes
10
+ * a fixed policy, a consistent failure event, and adequately independent
11
+ * samples. Three hundred repeated clicks inside one task are not three hundred
12
+ * independent trials; cluster by task or environment instance before using it.
13
+ */
14
+ import { ensure } from "./validation.js";
15
+ const LANCZOS_G = 7;
16
+ const LANCZOS_COEFFICIENTS = [
17
+ 0.999_999_999_999_809_93, 676.520_368_121_885_1, -1259.139_216_722_402_8, 771.323_428_777_653_13,
18
+ -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,
19
+ 1.505_632_735_149_311_6e-7,
20
+ ];
21
+ function logGamma(x) {
22
+ if (x < 0.5)
23
+ return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
24
+ const z = x - 1;
25
+ let a = LANCZOS_COEFFICIENTS[0];
26
+ const t = z + LANCZOS_G + 0.5;
27
+ for (const [index, coefficient] of LANCZOS_COEFFICIENTS.entries()) {
28
+ if (index > 0)
29
+ a += coefficient / (z + index);
30
+ }
31
+ return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(a);
32
+ }
33
+ /** Continued-fraction expansion for the incomplete beta (Lentz's method). */
34
+ function betaContinuedFraction(a, b, x) {
35
+ const maxIterations = 1000;
36
+ const epsilon = 1e-14;
37
+ const tiny = 1e-300;
38
+ const qab = a + b;
39
+ const qap = a + 1;
40
+ const qam = a - 1;
41
+ let c = 1;
42
+ let d = 1 - (qab * x) / qap;
43
+ if (Math.abs(d) < tiny)
44
+ d = tiny;
45
+ d = 1 / d;
46
+ let h = d;
47
+ for (let m = 1; m <= maxIterations; m += 1) {
48
+ const m2 = 2 * m;
49
+ let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
50
+ d = 1 + aa * d;
51
+ if (Math.abs(d) < tiny)
52
+ d = tiny;
53
+ c = 1 + aa / c;
54
+ if (Math.abs(c) < tiny)
55
+ c = tiny;
56
+ d = 1 / d;
57
+ h *= d * c;
58
+ aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
59
+ d = 1 + aa * d;
60
+ if (Math.abs(d) < tiny)
61
+ d = tiny;
62
+ c = 1 + aa / c;
63
+ if (Math.abs(c) < tiny)
64
+ c = tiny;
65
+ d = 1 / d;
66
+ const delta = d * c;
67
+ h *= delta;
68
+ if (Math.abs(delta - 1) < epsilon && Number.isFinite(h))
69
+ return h;
70
+ }
71
+ throw new RangeError("incomplete beta failed to converge");
72
+ }
73
+ /** Regularized incomplete beta I_x(a,b). */
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]");
77
+ if (x <= 0)
78
+ return 0;
79
+ if (x >= 1)
80
+ return 1;
81
+ const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));
82
+ const result = x < (a + 1) / (a + b + 2)
83
+ ? (front * betaContinuedFraction(a, b, x)) / a
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;
88
+ }
89
+ /** Invert the survival probability directly; never round 1-alpha to one. */
90
+ function betaUpperQuantile(alpha, a, b) {
91
+ let low = 0;
92
+ let high = 1;
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)
98
+ low = mid;
99
+ else
100
+ high = mid;
101
+ }
102
+ // Upper endpoint of the numerical bracket, not an interval-arithmetic proof.
103
+ return high;
104
+ }
105
+ function assertAlpha(alpha) {
106
+ ensure(typeof alpha === "number" && Number.isFinite(alpha) && alpha > 0 && alpha < 1, "alpha must be a probability strictly between 0 and 1");
107
+ }
108
+ /**
109
+ * One-sided Clopper–Pearson upper bound on the failure probability.
110
+ *
111
+ * `U(k,n) = Beta⁻¹(1−α; k+1, n−k)` for `0 ≤ k < n`, and `1` when every trial
112
+ * failed. Zero trials is not zero risk: it is absent evidence, so it throws.
113
+ */
114
+ export function clopperPearsonUpperBound(failures, trials, alpha) {
115
+ ensure(Number.isSafeInteger(trials) && trials > 0, "insufficient evidence: trials must be a positive integer");
116
+ ensure(Number.isSafeInteger(failures) && failures >= 0 && failures <= trials, "failures must be an integer in [0, trials]");
117
+ assertAlpha(alpha);
118
+ if (failures === trials)
119
+ return 1;
120
+ if (failures === 0)
121
+ return zeroFailureUpperBound(trials, alpha);
122
+ return betaUpperQuantile(alpha, failures + 1, trials - failures);
123
+ }
124
+ /** Closed form of {@link clopperPearsonUpperBound} when no trial failed. */
125
+ export function zeroFailureUpperBound(trials, alpha) {
126
+ ensure(Number.isSafeInteger(trials) && trials > 0, "insufficient evidence: trials must be a positive integer");
127
+ assertAlpha(alpha);
128
+ return -Math.expm1(Math.log(alpha) / trials);
129
+ }
130
+ /**
131
+ * Smallest failure-free sample size whose upper bound meets `targetEpsilon`.
132
+ *
133
+ * `n ≥ ⌈log α / log(1−ε)⌉`, then nudged against the bound itself so a
134
+ * floating-point boundary cannot return a sample size that misses the target.
135
+ */
136
+ export function minimumZeroFailureSamples(targetEpsilon, alpha) {
137
+ ensure(typeof targetEpsilon === "number" && Number.isFinite(targetEpsilon) && targetEpsilon > 0 && targetEpsilon < 1, "targetEpsilon must be strictly between 0 and 1");
138
+ assertAlpha(alpha);
139
+ let n = Math.max(1, Math.ceil(Math.log(alpha) / Math.log1p(-targetEpsilon)));
140
+ while (zeroFailureUpperBound(n, alpha) > targetEpsilon)
141
+ n += 1;
142
+ while (n > 1 && zeroFailureUpperBound(n - 1, alpha) <= targetEpsilon)
143
+ n -= 1;
144
+ return n;
145
+ }
146
+ /**
147
+ * Bonferroni split for `thresholds × groups` comparisons on one validation set.
148
+ *
149
+ * Searching many thresholds and reporting the best keeps none of a single
150
+ * interval's nominal guarantee; this is the conservative correction, and it
151
+ * raises the required sample size on purpose.
152
+ */
153
+ export function bonferroniAlpha(alpha, thresholds, groups) {
154
+ assertAlpha(alpha);
155
+ ensure(Number.isSafeInteger(thresholds) && thresholds > 0, "thresholds must be a positive integer");
156
+ ensure(Number.isSafeInteger(groups) && groups > 0, "groups must be a positive integer");
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;
162
+ }
163
+ /**
164
+ * Union bound over per-step failure risks.
165
+ *
166
+ * Holds without any independence assumption, which is the point: step risks in
167
+ * one task are usually correlated, so multiplying them would understate the
168
+ * whole-task risk.
169
+ */
170
+ export function unionBoundRisk(stepRisks) {
171
+ ensure(Array.isArray(stepRisks) && stepRisks.length > 0, "stepRisks must be a non-empty array");
172
+ let total = 0;
173
+ for (const risk of stepRisks) {
174
+ ensure(typeof risk === "number" && Number.isFinite(risk) && risk >= 0 && risk <= 1, "each step risk must be a probability in [0, 1]");
175
+ total += risk;
176
+ }
177
+ return Math.min(1, total);
178
+ }
179
+ //# sourceMappingURL=risk.js.map
@@ -0,0 +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,EAAE,CAAC;QACnE,IAAI,KAAK,GAAG,CAAC;YAAE,CAAC,IAAI,WAAW,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC;IAC/C,CAAC;IACD,OAAO,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,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e,CAAC,KAAa,EAAE,UAAkB,EAAE,MAAc,EAAU;IAC1F,WAAW,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,EAAE,uCAAuC,CAAC,CAAC;IACpG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,EAAE,mCAAmC,CAAC,CAAC;IACxF,MAAM,WAAW,GAAG,UAAU,GAAG,MAAM,CAAC;IACxC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,EAAE,2BAA2B,CAAC,CAAC;IACvE,MAAM,QAAQ,GAAG,KAAK,GAAG,WAAW,CAAC;IACrC,MAAM,CAAC,QAAQ,GAAG,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,0BAA0B,CAAC,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"]}
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Cost- and latency-aware route selection (Jev audit algorithm A5).
3
+ *
4
+ * Adding a selector call only pays if it *replaces* work. Inserting one in
5
+ * front of an existing free-text step adds a semantic inference instead of
6
+ * removing one, so routes are compared on a single utility:
7
+ *
8
+ * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)
9
+ *
10
+ * Safety and permission are deliberately not terms in that utility. They are a
11
+ * hard filter, because a cheap unsafe route must never win on weights.
12
+ *
13
+ * Latency is measured over the whole step, not the model call: when operator
14
+ * approval dominates, a faster decision step barely moves the total. Amdahl's
15
+ * bound is included so that limit is explicit rather than assumed away.
16
+ */
17
+ export interface RouteCandidate {
18
+ readonly id: string;
19
+ /** Probability this route completes the step correctly. */
20
+ readonly completionProbability: number;
21
+ readonly costUsd: number;
22
+ readonly latencyMs: number;
23
+ /** Policy and permission verdict. A false value is a veto, not a penalty. */
24
+ readonly approved: boolean;
25
+ }
26
+ export interface RouteUnits {
27
+ readonly costUnit: number;
28
+ readonly latencyUnit: number;
29
+ readonly costWeight: number;
30
+ readonly latencyWeight: number;
31
+ }
32
+ /** Dimensionless utility; cost and latency are normalized before weighting. */
33
+ export declare function routeUtility(route: RouteCandidate, units: RouteUnits): number;
34
+ /**
35
+ * Highest-utility approved route, or null when nothing is approved.
36
+ *
37
+ * Returning null rather than the best unapproved route keeps "we may not do
38
+ * this" distinct from "this is expensive".
39
+ */
40
+ export declare function selectRoute(routes: readonly RouteCandidate[], units: RouteUnits): RouteCandidate | null;
41
+ export interface StepPhases {
42
+ readonly queueMs: number;
43
+ readonly observeMs: number;
44
+ readonly packMs: number;
45
+ readonly decideMs: number;
46
+ readonly approvalMs: number;
47
+ readonly executeMs: number;
48
+ readonly verifyMs: number;
49
+ readonly recoveryMs: number;
50
+ }
51
+ /** Whole-step duration. Model response time is one term among eight. */
52
+ export declare function stepDuration(phases: StepPhases): number;
53
+ /**
54
+ * Amdahl bound: S = 1 / ((1−f) + f/s).
55
+ *
56
+ * `speedup` may be Infinity to ask what an instantaneous step would buy — the
57
+ * answer is still capped by the fraction it occupies, which is the point.
58
+ */
59
+ export declare function overallSpeedup(improvableFraction: number, speedup: number): number;
60
+ export interface FallbackCosts {
61
+ readonly selectorCost: number;
62
+ readonly verificationCost: number;
63
+ readonly fallbackProbability: number;
64
+ readonly fallbackCost: number;
65
+ }
66
+ /**
67
+ * E[C] = c_J + c_V + p_F·c_L.
68
+ *
69
+ * A cost decomposition, not an independence claim. Compare it against the
70
+ * incumbent path's cost under the same success and safety conditions; if it is
71
+ * larger, the cheap path is not cheap.
72
+ */
73
+ export declare function fallbackExpectedCost(costs: FallbackCosts): number;
74
+ export interface ReselectionInput {
75
+ /** Attempts already spent on this observation fingerprint. */
76
+ readonly attemptsForFingerprint: number;
77
+ readonly maxAttempts: number;
78
+ /** True when recovery changed the cause, not merely retried the same question. */
79
+ readonly causeChanged: boolean;
80
+ }
81
+ export type ReselectionDecision = {
82
+ readonly allowed: true;
83
+ } | {
84
+ readonly allowed: false;
85
+ readonly reason: "attempt-budget-exhausted";
86
+ };
87
+ /**
88
+ * Damp selector/model ping-pong on one observation generation.
89
+ *
90
+ * Re-asking the same question about the same state only adds calls. A further
91
+ * attempt is admitted when the budget remains, or when recovery genuinely
92
+ * changed the cause. The budget is a configured value, not a claimed optimum.
93
+ */
94
+ export declare function reselectionAllowed(input: ReselectionInput): ReselectionDecision;
95
+ //# sourceMappingURL=route-economics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-economics.d.ts","sourceRoot":"","sources":["../../src/metacognition/route-economics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,2DAA2D;IAC3D,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,6EAA6E;IAC7E,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC3B;AAED,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAC/B;AASD,+EAA+E;AAC/E,wBAAgB,YAAY,CAAC,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,UAAU,GA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AAE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAA;CAAE,GAC1B;IAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAA;CAAE,CAAC;AAE5E;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,gBAAgB,GAAG,mBAAmB,CAS/E","sourcesContent":["/**\n * Cost- and latency-aware route selection (Jev audit algorithm A5).\n *\n * Adding a selector call only pays if it *replaces* work. Inserting one in\n * front of an existing free-text step adds a semantic inference instead of\n * removing one, so routes are compared on a single utility:\n *\n * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)\n *\n * Safety and permission are deliberately not terms in that utility. They are a\n * hard filter, because a cheap unsafe route must never win on weights.\n *\n * Latency is measured over the whole step, not the model call: when operator\n * approval dominates, a faster decision step barely moves the total. Amdahl's\n * bound is included so that limit is explicit rather than assumed away.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nexport interface RouteCandidate {\n\treadonly id: string;\n\t/** Probability this route completes the step correctly. */\n\treadonly completionProbability: number;\n\treadonly costUsd: number;\n\treadonly latencyMs: number;\n\t/** Policy and permission verdict. A false value is a veto, not a penalty. */\n\treadonly approved: boolean;\n}\n\nexport interface RouteUnits {\n\treadonly costUnit: number;\n\treadonly latencyUnit: number;\n\treadonly costWeight: number;\n\treadonly latencyWeight: number;\n}\n\nfunction assertUnits(units: RouteUnits): void {\n\tensure(Number.isFinite(units.costUnit) && units.costUnit > 0, \"costUnit must be positive\");\n\tensure(Number.isFinite(units.latencyUnit) && units.latencyUnit > 0, \"latencyUnit must be positive\");\n\tensure(Number.isFinite(units.costWeight) && units.costWeight >= 0, \"costWeight must be nonnegative\");\n\tensure(Number.isFinite(units.latencyWeight) && units.latencyWeight >= 0, \"latencyWeight must be nonnegative\");\n}\n\n/** Dimensionless utility; cost and latency are normalized before weighting. */\nexport function routeUtility(route: RouteCandidate, units: RouteUnits): number {\n\tensure(\n\t\tNumber.isFinite(route.completionProbability) &&\n\t\t\troute.completionProbability >= 0 &&\n\t\t\troute.completionProbability <= 1,\n\t\t\"completionProbability must be in [0,1]\",\n\t);\n\tensure(Number.isFinite(route.costUsd) && route.costUsd >= 0, \"costUsd must be nonnegative\");\n\tensure(Number.isFinite(route.latencyMs) && route.latencyMs >= 0, \"latencyMs must be nonnegative\");\n\tassertUnits(units);\n\treturn (\n\t\troute.completionProbability -\n\t\tunits.costWeight * (route.costUsd / units.costUnit) -\n\t\tunits.latencyWeight * (route.latencyMs / units.latencyUnit)\n\t);\n}\n\n/**\n * Highest-utility approved route, or null when nothing is approved.\n *\n * Returning null rather than the best unapproved route keeps \"we may not do\n * this\" distinct from \"this is expensive\".\n */\nexport function selectRoute(routes: readonly RouteCandidate[], units: RouteUnits): RouteCandidate | null {\n\tensure(Array.isArray(routes) && routes.length > 0, \"routes must be a non-empty array\");\n\tlet best: RouteCandidate | undefined;\n\tlet bestUtility = Number.NEGATIVE_INFINITY;\n\tfor (const route of routes) {\n\t\tif (!route.approved) continue;\n\t\tconst utility = routeUtility(route, units);\n\t\tconst better = utility > bestUtility || (utility === bestUtility && best !== undefined && route.id < best.id);\n\t\tif (best === undefined || better) {\n\t\t\tbest = route;\n\t\t\tbestUtility = utility;\n\t\t}\n\t}\n\treturn best ?? null;\n}\n\nexport interface StepPhases {\n\treadonly queueMs: number;\n\treadonly observeMs: number;\n\treadonly packMs: number;\n\treadonly decideMs: number;\n\treadonly approvalMs: number;\n\treadonly executeMs: number;\n\treadonly verifyMs: number;\n\treadonly recoveryMs: number;\n}\n\n/** Whole-step duration. Model response time is one term among eight. */\nexport function stepDuration(phases: StepPhases): number {\n\tlet total = 0;\n\tfor (const [label, value] of Object.entries(phases)) {\n\t\tensure(Number.isFinite(value) && value >= 0, `${label} must be a nonnegative finite number`);\n\t\ttotal += value;\n\t}\n\treturn total;\n}\n\n/**\n * Amdahl bound: S = 1 / ((1−f) + f/s).\n *\n * `speedup` may be Infinity to ask what an instantaneous step would buy — the\n * answer is still capped by the fraction it occupies, which is the point.\n */\nexport function overallSpeedup(improvableFraction: number, speedup: number): number {\n\tensure(\n\t\tNumber.isFinite(improvableFraction) && improvableFraction >= 0 && improvableFraction <= 1,\n\t\t\"improvableFraction must be in [0,1]\",\n\t);\n\tensure(typeof speedup === \"number\" && !Number.isNaN(speedup) && speedup >= 1, \"speedup must be at least 1\");\n\tconst remaining = 1 - improvableFraction;\n\tconst improved = speedup === Number.POSITIVE_INFINITY ? 0 : improvableFraction / speedup;\n\treturn 1 / (remaining + improved);\n}\n\nexport interface FallbackCosts {\n\treadonly selectorCost: number;\n\treadonly verificationCost: number;\n\treadonly fallbackProbability: number;\n\treadonly fallbackCost: number;\n}\n\n/**\n * E[C] = c_J + c_V + p_F·c_L.\n *\n * A cost decomposition, not an independence claim. Compare it against the\n * incumbent path's cost under the same success and safety conditions; if it is\n * larger, the cheap path is not cheap.\n */\nexport function fallbackExpectedCost(costs: FallbackCosts): number {\n\tensure(Number.isFinite(costs.selectorCost) && costs.selectorCost >= 0, \"selectorCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.verificationCost) && costs.verificationCost >= 0,\n\t\t\"verificationCost must be nonnegative\",\n\t);\n\tensure(Number.isFinite(costs.fallbackCost) && costs.fallbackCost >= 0, \"fallbackCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.fallbackProbability) && costs.fallbackProbability >= 0 && costs.fallbackProbability <= 1,\n\t\t\"fallbackProbability must be in [0,1]\",\n\t);\n\treturn costs.selectorCost + costs.verificationCost + costs.fallbackProbability * costs.fallbackCost;\n}\n\nexport interface ReselectionInput {\n\t/** Attempts already spent on this observation fingerprint. */\n\treadonly attemptsForFingerprint: number;\n\treadonly maxAttempts: number;\n\t/** True when recovery changed the cause, not merely retried the same question. */\n\treadonly causeChanged: boolean;\n}\n\nexport type ReselectionDecision =\n\t| { readonly allowed: true }\n\t| { readonly allowed: false; readonly reason: \"attempt-budget-exhausted\" };\n\n/**\n * Damp selector/model ping-pong on one observation generation.\n *\n * Re-asking the same question about the same state only adds calls. A further\n * attempt is admitted when the budget remains, or when recovery genuinely\n * changed the cause. The budget is a configured value, not a claimed optimum.\n */\nexport function reselectionAllowed(input: ReselectionInput): ReselectionDecision {\n\tensure(\n\t\tNumber.isSafeInteger(input.attemptsForFingerprint) && input.attemptsForFingerprint >= 0,\n\t\t\"attemptsForFingerprint must be a nonnegative integer\",\n\t);\n\tensure(Number.isSafeInteger(input.maxAttempts) && input.maxAttempts > 0, \"maxAttempts must be a positive integer\");\n\tif (input.causeChanged) return { allowed: true };\n\tif (input.attemptsForFingerprint < input.maxAttempts) return { allowed: true };\n\treturn { allowed: false, reason: \"attempt-budget-exhausted\" };\n}\n"]}
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Cost- and latency-aware route selection (Jev audit algorithm A5).
3
+ *
4
+ * Adding a selector call only pays if it *replaces* work. Inserting one in
5
+ * front of an existing free-text step adds a semantic inference instead of
6
+ * removing one, so routes are compared on a single utility:
7
+ *
8
+ * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)
9
+ *
10
+ * Safety and permission are deliberately not terms in that utility. They are a
11
+ * hard filter, because a cheap unsafe route must never win on weights.
12
+ *
13
+ * Latency is measured over the whole step, not the model call: when operator
14
+ * approval dominates, a faster decision step barely moves the total. Amdahl's
15
+ * bound is included so that limit is explicit rather than assumed away.
16
+ */
17
+ import { ensure } from "./validation.js";
18
+ function assertUnits(units) {
19
+ ensure(Number.isFinite(units.costUnit) && units.costUnit > 0, "costUnit must be positive");
20
+ ensure(Number.isFinite(units.latencyUnit) && units.latencyUnit > 0, "latencyUnit must be positive");
21
+ ensure(Number.isFinite(units.costWeight) && units.costWeight >= 0, "costWeight must be nonnegative");
22
+ ensure(Number.isFinite(units.latencyWeight) && units.latencyWeight >= 0, "latencyWeight must be nonnegative");
23
+ }
24
+ /** Dimensionless utility; cost and latency are normalized before weighting. */
25
+ export function routeUtility(route, units) {
26
+ ensure(Number.isFinite(route.completionProbability) &&
27
+ route.completionProbability >= 0 &&
28
+ route.completionProbability <= 1, "completionProbability must be in [0,1]");
29
+ ensure(Number.isFinite(route.costUsd) && route.costUsd >= 0, "costUsd must be nonnegative");
30
+ ensure(Number.isFinite(route.latencyMs) && route.latencyMs >= 0, "latencyMs must be nonnegative");
31
+ assertUnits(units);
32
+ return (route.completionProbability -
33
+ units.costWeight * (route.costUsd / units.costUnit) -
34
+ units.latencyWeight * (route.latencyMs / units.latencyUnit));
35
+ }
36
+ /**
37
+ * Highest-utility approved route, or null when nothing is approved.
38
+ *
39
+ * Returning null rather than the best unapproved route keeps "we may not do
40
+ * this" distinct from "this is expensive".
41
+ */
42
+ export function selectRoute(routes, units) {
43
+ ensure(Array.isArray(routes) && routes.length > 0, "routes must be a non-empty array");
44
+ let best;
45
+ let bestUtility = Number.NEGATIVE_INFINITY;
46
+ for (const route of routes) {
47
+ if (!route.approved)
48
+ continue;
49
+ const utility = routeUtility(route, units);
50
+ const better = utility > bestUtility || (utility === bestUtility && best !== undefined && route.id < best.id);
51
+ if (best === undefined || better) {
52
+ best = route;
53
+ bestUtility = utility;
54
+ }
55
+ }
56
+ return best ?? null;
57
+ }
58
+ /** Whole-step duration. Model response time is one term among eight. */
59
+ export function stepDuration(phases) {
60
+ let total = 0;
61
+ for (const [label, value] of Object.entries(phases)) {
62
+ ensure(Number.isFinite(value) && value >= 0, `${label} must be a nonnegative finite number`);
63
+ total += value;
64
+ }
65
+ return total;
66
+ }
67
+ /**
68
+ * Amdahl bound: S = 1 / ((1−f) + f/s).
69
+ *
70
+ * `speedup` may be Infinity to ask what an instantaneous step would buy — the
71
+ * answer is still capped by the fraction it occupies, which is the point.
72
+ */
73
+ export function overallSpeedup(improvableFraction, speedup) {
74
+ ensure(Number.isFinite(improvableFraction) && improvableFraction >= 0 && improvableFraction <= 1, "improvableFraction must be in [0,1]");
75
+ ensure(typeof speedup === "number" && !Number.isNaN(speedup) && speedup >= 1, "speedup must be at least 1");
76
+ const remaining = 1 - improvableFraction;
77
+ const improved = speedup === Number.POSITIVE_INFINITY ? 0 : improvableFraction / speedup;
78
+ return 1 / (remaining + improved);
79
+ }
80
+ /**
81
+ * E[C] = c_J + c_V + p_F·c_L.
82
+ *
83
+ * A cost decomposition, not an independence claim. Compare it against the
84
+ * incumbent path's cost under the same success and safety conditions; if it is
85
+ * larger, the cheap path is not cheap.
86
+ */
87
+ export function fallbackExpectedCost(costs) {
88
+ ensure(Number.isFinite(costs.selectorCost) && costs.selectorCost >= 0, "selectorCost must be nonnegative");
89
+ ensure(Number.isFinite(costs.verificationCost) && costs.verificationCost >= 0, "verificationCost must be nonnegative");
90
+ ensure(Number.isFinite(costs.fallbackCost) && costs.fallbackCost >= 0, "fallbackCost must be nonnegative");
91
+ ensure(Number.isFinite(costs.fallbackProbability) && costs.fallbackProbability >= 0 && costs.fallbackProbability <= 1, "fallbackProbability must be in [0,1]");
92
+ return costs.selectorCost + costs.verificationCost + costs.fallbackProbability * costs.fallbackCost;
93
+ }
94
+ /**
95
+ * Damp selector/model ping-pong on one observation generation.
96
+ *
97
+ * Re-asking the same question about the same state only adds calls. A further
98
+ * attempt is admitted when the budget remains, or when recovery genuinely
99
+ * changed the cause. The budget is a configured value, not a claimed optimum.
100
+ */
101
+ export function reselectionAllowed(input) {
102
+ ensure(Number.isSafeInteger(input.attemptsForFingerprint) && input.attemptsForFingerprint >= 0, "attemptsForFingerprint must be a nonnegative integer");
103
+ ensure(Number.isSafeInteger(input.maxAttempts) && input.maxAttempts > 0, "maxAttempts must be a positive integer");
104
+ if (input.causeChanged)
105
+ return { allowed: true };
106
+ if (input.attemptsForFingerprint < input.maxAttempts)
107
+ return { allowed: true };
108
+ return { allowed: false, reason: "attempt-budget-exhausted" };
109
+ }
110
+ //# sourceMappingURL=route-economics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-economics.js","sourceRoot":"","sources":["../../src/metacognition/route-economics.ts"],"names":[],"mappings":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AK,CAAC,mBAAmB,CAAC,IAAI,KAAK,CAAC,mBAAmB,IAAI,CAAC,IAAI,KAAK,CAAC,mBAAmB,IAAI,CAAC,EAC9G,sCAAsC,CACtC,CAAC;IACF,OAAO,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,gBAAgB,GAAG,KAAK,CAAC,mBAAmB,GAAG,KAAK,CAAC,YAAY,CAAC;AAAA,CACpG;AAcD;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,KAAuB,EAAuB;IAChF,MAAM,CACL,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,sBAAsB,CAAC,IAAI,KAAK,CAAC,sBAAsB,IAAI,CAAC,EACvF,sDAAsD,CACtD,CAAC;IACF,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,CAAC,WAAW,GAAG,CAAC,EAAE,wCAAwC,CAAC,CAAC;IACnH,IAAI,KAAK,CAAC,YAAY;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IACjD,IAAI,KAAK,CAAC,sBAAsB,GAAG,KAAK,CAAC,WAAW;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC/E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,0BAA0B,EAAE,CAAC;AAAA,CAC9D","sourcesContent":["/**\n * Cost- and latency-aware route selection (Jev audit algorithm A5).\n *\n * Adding a selector call only pays if it *replaces* work. Inserting one in\n * front of an existing free-text step adds a semantic inference instead of\n * removing one, so routes are compared on a single utility:\n *\n * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)\n *\n * Safety and permission are deliberately not terms in that utility. They are a\n * hard filter, because a cheap unsafe route must never win on weights.\n *\n * Latency is measured over the whole step, not the model call: when operator\n * approval dominates, a faster decision step barely moves the total. Amdahl's\n * bound is included so that limit is explicit rather than assumed away.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nexport interface RouteCandidate {\n\treadonly id: string;\n\t/** Probability this route completes the step correctly. */\n\treadonly completionProbability: number;\n\treadonly costUsd: number;\n\treadonly latencyMs: number;\n\t/** Policy and permission verdict. A false value is a veto, not a penalty. */\n\treadonly approved: boolean;\n}\n\nexport interface RouteUnits {\n\treadonly costUnit: number;\n\treadonly latencyUnit: number;\n\treadonly costWeight: number;\n\treadonly latencyWeight: number;\n}\n\nfunction assertUnits(units: RouteUnits): void {\n\tensure(Number.isFinite(units.costUnit) && units.costUnit > 0, \"costUnit must be positive\");\n\tensure(Number.isFinite(units.latencyUnit) && units.latencyUnit > 0, \"latencyUnit must be positive\");\n\tensure(Number.isFinite(units.costWeight) && units.costWeight >= 0, \"costWeight must be nonnegative\");\n\tensure(Number.isFinite(units.latencyWeight) && units.latencyWeight >= 0, \"latencyWeight must be nonnegative\");\n}\n\n/** Dimensionless utility; cost and latency are normalized before weighting. */\nexport function routeUtility(route: RouteCandidate, units: RouteUnits): number {\n\tensure(\n\t\tNumber.isFinite(route.completionProbability) &&\n\t\t\troute.completionProbability >= 0 &&\n\t\t\troute.completionProbability <= 1,\n\t\t\"completionProbability must be in [0,1]\",\n\t);\n\tensure(Number.isFinite(route.costUsd) && route.costUsd >= 0, \"costUsd must be nonnegative\");\n\tensure(Number.isFinite(route.latencyMs) && route.latencyMs >= 0, \"latencyMs must be nonnegative\");\n\tassertUnits(units);\n\treturn (\n\t\troute.completionProbability -\n\t\tunits.costWeight * (route.costUsd / units.costUnit) -\n\t\tunits.latencyWeight * (route.latencyMs / units.latencyUnit)\n\t);\n}\n\n/**\n * Highest-utility approved route, or null when nothing is approved.\n *\n * Returning null rather than the best unapproved route keeps \"we may not do\n * this\" distinct from \"this is expensive\".\n */\nexport function selectRoute(routes: readonly RouteCandidate[], units: RouteUnits): RouteCandidate | null {\n\tensure(Array.isArray(routes) && routes.length > 0, \"routes must be a non-empty array\");\n\tlet best: RouteCandidate | undefined;\n\tlet bestUtility = Number.NEGATIVE_INFINITY;\n\tfor (const route of routes) {\n\t\tif (!route.approved) continue;\n\t\tconst utility = routeUtility(route, units);\n\t\tconst better = utility > bestUtility || (utility === bestUtility && best !== undefined && route.id < best.id);\n\t\tif (best === undefined || better) {\n\t\t\tbest = route;\n\t\t\tbestUtility = utility;\n\t\t}\n\t}\n\treturn best ?? null;\n}\n\nexport interface StepPhases {\n\treadonly queueMs: number;\n\treadonly observeMs: number;\n\treadonly packMs: number;\n\treadonly decideMs: number;\n\treadonly approvalMs: number;\n\treadonly executeMs: number;\n\treadonly verifyMs: number;\n\treadonly recoveryMs: number;\n}\n\n/** Whole-step duration. Model response time is one term among eight. */\nexport function stepDuration(phases: StepPhases): number {\n\tlet total = 0;\n\tfor (const [label, value] of Object.entries(phases)) {\n\t\tensure(Number.isFinite(value) && value >= 0, `${label} must be a nonnegative finite number`);\n\t\ttotal += value;\n\t}\n\treturn total;\n}\n\n/**\n * Amdahl bound: S = 1 / ((1−f) + f/s).\n *\n * `speedup` may be Infinity to ask what an instantaneous step would buy — the\n * answer is still capped by the fraction it occupies, which is the point.\n */\nexport function overallSpeedup(improvableFraction: number, speedup: number): number {\n\tensure(\n\t\tNumber.isFinite(improvableFraction) && improvableFraction >= 0 && improvableFraction <= 1,\n\t\t\"improvableFraction must be in [0,1]\",\n\t);\n\tensure(typeof speedup === \"number\" && !Number.isNaN(speedup) && speedup >= 1, \"speedup must be at least 1\");\n\tconst remaining = 1 - improvableFraction;\n\tconst improved = speedup === Number.POSITIVE_INFINITY ? 0 : improvableFraction / speedup;\n\treturn 1 / (remaining + improved);\n}\n\nexport interface FallbackCosts {\n\treadonly selectorCost: number;\n\treadonly verificationCost: number;\n\treadonly fallbackProbability: number;\n\treadonly fallbackCost: number;\n}\n\n/**\n * E[C] = c_J + c_V + p_F·c_L.\n *\n * A cost decomposition, not an independence claim. Compare it against the\n * incumbent path's cost under the same success and safety conditions; if it is\n * larger, the cheap path is not cheap.\n */\nexport function fallbackExpectedCost(costs: FallbackCosts): number {\n\tensure(Number.isFinite(costs.selectorCost) && costs.selectorCost >= 0, \"selectorCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.verificationCost) && costs.verificationCost >= 0,\n\t\t\"verificationCost must be nonnegative\",\n\t);\n\tensure(Number.isFinite(costs.fallbackCost) && costs.fallbackCost >= 0, \"fallbackCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.fallbackProbability) && costs.fallbackProbability >= 0 && costs.fallbackProbability <= 1,\n\t\t\"fallbackProbability must be in [0,1]\",\n\t);\n\treturn costs.selectorCost + costs.verificationCost + costs.fallbackProbability * costs.fallbackCost;\n}\n\nexport interface ReselectionInput {\n\t/** Attempts already spent on this observation fingerprint. */\n\treadonly attemptsForFingerprint: number;\n\treadonly maxAttempts: number;\n\t/** True when recovery changed the cause, not merely retried the same question. */\n\treadonly causeChanged: boolean;\n}\n\nexport type ReselectionDecision =\n\t| { readonly allowed: true }\n\t| { readonly allowed: false; readonly reason: \"attempt-budget-exhausted\" };\n\n/**\n * Damp selector/model ping-pong on one observation generation.\n *\n * Re-asking the same question about the same state only adds calls. A further\n * attempt is admitted when the budget remains, or when recovery genuinely\n * changed the cause. The budget is a configured value, not a claimed optimum.\n */\nexport function reselectionAllowed(input: ReselectionInput): ReselectionDecision {\n\tensure(\n\t\tNumber.isSafeInteger(input.attemptsForFingerprint) && input.attemptsForFingerprint >= 0,\n\t\t\"attemptsForFingerprint must be a nonnegative integer\",\n\t);\n\tensure(Number.isSafeInteger(input.maxAttempts) && input.maxAttempts > 0, \"maxAttempts must be a positive integer\");\n\tif (input.causeChanged) return { allowed: true };\n\tif (input.attemptsForFingerprint < input.maxAttempts) return { allowed: true };\n\treturn { allowed: false, reason: \"attempt-budget-exhausted\" };\n}\n"]}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Runtime bridge — §13 "기존 완료 판정 호출부": projects host-owned OMK
3
+ * runtime artifacts (protocol ClaimGraph claims, ObservationNodes, waiver
4
+ * records, workspace/session facts) onto the metacognition kernel's input
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.
17
+ */
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";
21
+ /** ClaimNode → kernel Claim. Severity maps to impact; leaves keep their check demands. */
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[];
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;
43
+ export interface RuntimeBridgeInput {
44
+ readonly taskId: string;
45
+ readonly stageId: string;
46
+ readonly goalScope: string;
47
+ readonly targetArtifact: string;
48
+ readonly candidateHash: string;
49
+ readonly environmentHash: string;
50
+ /** Current ledger generation; compared with each observation's own when present. */
51
+ readonly generation?: number;
52
+ readonly claims: readonly ClaimNode[];
53
+ readonly observations: readonly BridgeObservation[];
54
+ readonly trustedRunnerIds: readonly string[];
55
+ readonly decisionActorIds: readonly string[];
56
+ readonly authorizedActions: readonly string[];
57
+ readonly budget: {
58
+ remainingMs: number;
59
+ remainingRequests: number;
60
+ remainingTokens: number;
61
+ remainingConcurrent: number;
62
+ };
63
+ readonly policyVersion: string;
64
+ readonly modelRevision: string;
65
+ readonly interruptionReason?: string | null;
66
+ readonly stage: Stage;
67
+ readonly nowMs: number;
68
+ readonly progressHistory?: readonly {
69
+ key: string;
70
+ newEvidence: boolean;
71
+ resolvedObligations: number;
72
+ newValidChecks: number;
73
+ }[];
74
+ /** Extra admissible source identities beyond the built-in registry. */
75
+ readonly sources?: readonly SourceIdentity[];
76
+ }
77
+ /** Build kernel inputs plus a MetaState for one safe checkpoint. Host-owned inputs only. */
78
+ export declare function toMetaState(input: RuntimeBridgeInput): RuntimeBridgeResult;
79
+ /** Sources admitted for reference evidence: only repository/official qualify. */
80
+ export declare function sourceIdentities(overrides?: readonly SourceIdentity[]): readonly SourceIdentity[];
81
+ //# sourceMappingURL=runtime-bridge.d.ts.map
@@ -0,0 +1 @@
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,cAA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AAE,CAAC;IAC7C,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7C,QAAQ,CAAC,iBAAiB,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9C,QAAQ,CAAC,MAAM,EAAE;QAChB,WAAW,EAAE,MAAM,CAAC;QACpB,iBAAiB,EAAE,MAAM,CAAC;QAC1B,eAAe,EAAE,MAAM,CAAC;QACxB,mBAAmB,EAAE,MAAM,CAAC;KAC5B,CAAC;IACF,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;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;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"]}