pulseed 0.5.4 → 0.6.1

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 (804) hide show
  1. package/README.md +21 -15
  2. package/dist/adapters/datasources/artifact-metric-datasource.d.ts +18 -0
  3. package/dist/adapters/datasources/artifact-metric-datasource.d.ts.map +1 -0
  4. package/dist/adapters/datasources/artifact-metric-datasource.js +592 -0
  5. package/dist/adapters/datasources/artifact-metric-datasource.js.map +1 -0
  6. package/dist/adapters/types/mcp.d.ts +6 -6
  7. package/dist/base/config/identity-loader.d.ts +12 -3
  8. package/dist/base/config/identity-loader.d.ts.map +1 -1
  9. package/dist/base/config/identity-loader.js +15 -7
  10. package/dist/base/config/identity-loader.js.map +1 -1
  11. package/dist/base/types/goal-activation.d.ts +14 -2
  12. package/dist/base/types/goal-activation.d.ts.map +1 -1
  13. package/dist/base/types/goal-activation.js +4 -0
  14. package/dist/base/types/goal-activation.js.map +1 -1
  15. package/dist/grounding/contracts.d.ts +13 -0
  16. package/dist/grounding/contracts.d.ts.map +1 -1
  17. package/dist/grounding/providers/knowledge-provider.d.ts.map +1 -1
  18. package/dist/grounding/providers/knowledge-provider.js +25 -3
  19. package/dist/grounding/providers/knowledge-provider.js.map +1 -1
  20. package/dist/grounding/providers/soil-provider.d.ts.map +1 -1
  21. package/dist/grounding/providers/soil-provider.js +28 -3
  22. package/dist/grounding/providers/soil-provider.js.map +1 -1
  23. package/dist/grounding/providers/static-policy-provider.d.ts +3 -1
  24. package/dist/grounding/providers/static-policy-provider.d.ts.map +1 -1
  25. package/dist/grounding/providers/static-policy-provider.js +4 -3
  26. package/dist/grounding/providers/static-policy-provider.js.map +1 -1
  27. package/dist/index.d.ts +14 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +8 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/interface/chat/chat-event-state.d.ts.map +1 -1
  32. package/dist/interface/chat/chat-event-state.js +92 -9
  33. package/dist/interface/chat/chat-event-state.js.map +1 -1
  34. package/dist/interface/chat/chat-events.d.ts +15 -1
  35. package/dist/interface/chat/chat-events.d.ts.map +1 -1
  36. package/dist/interface/chat/chat-runner-commands.d.ts +6 -0
  37. package/dist/interface/chat/chat-runner-commands.d.ts.map +1 -1
  38. package/dist/interface/chat/chat-runner-commands.js +94 -2
  39. package/dist/interface/chat/chat-runner-commands.js.map +1 -1
  40. package/dist/interface/chat/chat-runner-event-bridge.d.ts +11 -1
  41. package/dist/interface/chat/chat-runner-event-bridge.d.ts.map +1 -1
  42. package/dist/interface/chat/chat-runner-event-bridge.js +123 -11
  43. package/dist/interface/chat/chat-runner-event-bridge.js.map +1 -1
  44. package/dist/interface/chat/chat-runner-routes.d.ts +20 -0
  45. package/dist/interface/chat/chat-runner-routes.d.ts.map +1 -1
  46. package/dist/interface/chat/chat-runner-routes.js +99 -7
  47. package/dist/interface/chat/chat-runner-routes.js.map +1 -1
  48. package/dist/interface/chat/chat-runner-support.d.ts +25 -1
  49. package/dist/interface/chat/chat-runner-support.d.ts.map +1 -1
  50. package/dist/interface/chat/chat-runner-support.js +66 -12
  51. package/dist/interface/chat/chat-runner-support.js.map +1 -1
  52. package/dist/interface/chat/chat-runner.d.ts.map +1 -1
  53. package/dist/interface/chat/chat-runner.js +64 -10
  54. package/dist/interface/chat/chat-runner.js.map +1 -1
  55. package/dist/interface/chat/cross-platform-session.d.ts.map +1 -1
  56. package/dist/interface/chat/cross-platform-session.js +19 -1
  57. package/dist/interface/chat/cross-platform-session.js.map +1 -1
  58. package/dist/interface/chat/event-subscriber.d.ts.map +1 -1
  59. package/dist/interface/chat/event-subscriber.js +20 -0
  60. package/dist/interface/chat/event-subscriber.js.map +1 -1
  61. package/dist/interface/chat/failure-recovery.d.ts +43 -1
  62. package/dist/interface/chat/failure-recovery.d.ts.map +1 -1
  63. package/dist/interface/chat/failure-recovery.js +259 -89
  64. package/dist/interface/chat/failure-recovery.js.map +1 -1
  65. package/dist/interface/chat/freeform-route-classifier.d.ts +21 -0
  66. package/dist/interface/chat/freeform-route-classifier.d.ts.map +1 -0
  67. package/dist/interface/chat/freeform-route-classifier.js +42 -0
  68. package/dist/interface/chat/freeform-route-classifier.js.map +1 -0
  69. package/dist/interface/chat/grounding.js +1 -1
  70. package/dist/interface/chat/grounding.js.map +1 -1
  71. package/dist/interface/chat/ingress-router.d.ts +11 -1
  72. package/dist/interface/chat/ingress-router.d.ts.map +1 -1
  73. package/dist/interface/chat/ingress-router.js +21 -3
  74. package/dist/interface/chat/ingress-router.js.map +1 -1
  75. package/dist/interface/chat/tend-command.js +1 -0
  76. package/dist/interface/chat/tend-command.js.map +1 -1
  77. package/dist/interface/cli/cli-command-registry.d.ts.map +1 -1
  78. package/dist/interface/cli/cli-command-registry.js +28 -4
  79. package/dist/interface/cli/cli-command-registry.js.map +1 -1
  80. package/dist/interface/cli/cli-runner.d.ts.map +1 -1
  81. package/dist/interface/cli/cli-runner.js +4 -1
  82. package/dist/interface/cli/cli-runner.js.map +1 -1
  83. package/dist/interface/cli/commands/daemon-shared.d.ts +2 -1
  84. package/dist/interface/cli/commands/daemon-shared.d.ts.map +1 -1
  85. package/dist/interface/cli/commands/daemon-shared.js +33 -1
  86. package/dist/interface/cli/commands/daemon-shared.js.map +1 -1
  87. package/dist/interface/cli/commands/daemon.d.ts.map +1 -1
  88. package/dist/interface/cli/commands/daemon.js +76 -9
  89. package/dist/interface/cli/commands/daemon.js.map +1 -1
  90. package/dist/interface/cli/commands/goal-read.d.ts.map +1 -1
  91. package/dist/interface/cli/commands/goal-read.js +14 -3
  92. package/dist/interface/cli/commands/goal-read.js.map +1 -1
  93. package/dist/interface/cli/commands/memory.d.ts +3 -0
  94. package/dist/interface/cli/commands/memory.d.ts.map +1 -0
  95. package/dist/interface/cli/commands/memory.js +78 -0
  96. package/dist/interface/cli/commands/memory.js.map +1 -0
  97. package/dist/interface/cli/commands/notify.d.ts.map +1 -1
  98. package/dist/interface/cli/commands/notify.js +7 -1
  99. package/dist/interface/cli/commands/notify.js.map +1 -1
  100. package/dist/interface/cli/commands/plugin.d.ts.map +1 -1
  101. package/dist/interface/cli/commands/plugin.js +134 -12
  102. package/dist/interface/cli/commands/plugin.js.map +1 -1
  103. package/dist/interface/cli/commands/profile.d.ts +3 -0
  104. package/dist/interface/cli/commands/profile.d.ts.map +1 -0
  105. package/dist/interface/cli/commands/profile.js +459 -0
  106. package/dist/interface/cli/commands/profile.js.map +1 -0
  107. package/dist/interface/cli/commands/run.d.ts.map +1 -1
  108. package/dist/interface/cli/commands/run.js +29 -0
  109. package/dist/interface/cli/commands/run.js.map +1 -1
  110. package/dist/interface/cli/commands/runtime.d.ts +1 -1
  111. package/dist/interface/cli/commands/runtime.d.ts.map +1 -1
  112. package/dist/interface/cli/commands/runtime.js +506 -2
  113. package/dist/interface/cli/commands/runtime.js.map +1 -1
  114. package/dist/interface/cli/commands/setup-wizard.d.ts.map +1 -1
  115. package/dist/interface/cli/commands/setup-wizard.js +30 -0
  116. package/dist/interface/cli/commands/setup-wizard.js.map +1 -1
  117. package/dist/interface/cli/data-source-bootstrap.d.ts.map +1 -1
  118. package/dist/interface/cli/data-source-bootstrap.js +25 -12
  119. package/dist/interface/cli/data-source-bootstrap.js.map +1 -1
  120. package/dist/interface/cli/setup.d.ts.map +1 -1
  121. package/dist/interface/cli/setup.js +14 -0
  122. package/dist/interface/cli/setup.js.map +1 -1
  123. package/dist/interface/cli/utils/loop-runner.d.ts.map +1 -1
  124. package/dist/interface/cli/utils/loop-runner.js +2 -1
  125. package/dist/interface/cli/utils/loop-runner.js.map +1 -1
  126. package/dist/interface/cli/utils.d.ts.map +1 -1
  127. package/dist/interface/cli/utils.js +12 -3
  128. package/dist/interface/cli/utils.js.map +1 -1
  129. package/dist/interface/tui/app.d.ts +4 -1
  130. package/dist/interface/tui/app.d.ts.map +1 -1
  131. package/dist/interface/tui/app.js +268 -10
  132. package/dist/interface/tui/app.js.map +1 -1
  133. package/dist/interface/tui/chat-surface.d.ts +2 -0
  134. package/dist/interface/tui/chat-surface.d.ts.map +1 -1
  135. package/dist/interface/tui/chat-surface.js +3 -0
  136. package/dist/interface/tui/chat-surface.js.map +1 -1
  137. package/dist/interface/tui/dashboard.d.ts +37 -1
  138. package/dist/interface/tui/dashboard.d.ts.map +1 -1
  139. package/dist/interface/tui/dashboard.js +264 -1
  140. package/dist/interface/tui/dashboard.js.map +1 -1
  141. package/dist/interface/tui/entry-deps.d.ts +3 -1
  142. package/dist/interface/tui/entry-deps.d.ts.map +1 -1
  143. package/dist/interface/tui/entry-deps.js +19 -1
  144. package/dist/interface/tui/entry-deps.js.map +1 -1
  145. package/dist/interface/tui/entry.d.ts.map +1 -1
  146. package/dist/interface/tui/entry.js +4 -2
  147. package/dist/interface/tui/entry.js.map +1 -1
  148. package/dist/interface/tui/intent-recognizer.d.ts +8 -3
  149. package/dist/interface/tui/intent-recognizer.d.ts.map +1 -1
  150. package/dist/interface/tui/intent-recognizer.js +75 -69
  151. package/dist/interface/tui/intent-recognizer.js.map +1 -1
  152. package/dist/orchestrator/execution/agent-loop/agent-loop-context-assembler.d.ts +2 -0
  153. package/dist/orchestrator/execution/agent-loop/agent-loop-context-assembler.d.ts.map +1 -1
  154. package/dist/orchestrator/execution/agent-loop/agent-loop-context-assembler.js +1 -0
  155. package/dist/orchestrator/execution/agent-loop/agent-loop-context-assembler.js.map +1 -1
  156. package/dist/orchestrator/execution/agent-loop/agent-loop-default-profile.d.ts.map +1 -1
  157. package/dist/orchestrator/execution/agent-loop/agent-loop-default-profile.js +42 -0
  158. package/dist/orchestrator/execution/agent-loop/agent-loop-default-profile.js.map +1 -1
  159. package/dist/orchestrator/execution/agent-loop/agent-loop-events.d.ts +1 -0
  160. package/dist/orchestrator/execution/agent-loop/agent-loop-events.d.ts.map +1 -1
  161. package/dist/orchestrator/execution/agent-loop/agent-loop-events.js.map +1 -1
  162. package/dist/orchestrator/execution/agent-loop/agent-loop-prompts.d.ts.map +1 -1
  163. package/dist/orchestrator/execution/agent-loop/agent-loop-prompts.js +3 -0
  164. package/dist/orchestrator/execution/agent-loop/agent-loop-prompts.js.map +1 -1
  165. package/dist/orchestrator/execution/agent-loop/agent-timeline.d.ts +109 -0
  166. package/dist/orchestrator/execution/agent-loop/agent-timeline.d.ts.map +1 -0
  167. package/dist/orchestrator/execution/agent-loop/agent-timeline.js +261 -0
  168. package/dist/orchestrator/execution/agent-loop/agent-timeline.js.map +1 -0
  169. package/dist/orchestrator/execution/agent-loop/bounded-agent-loop-runner.d.ts.map +1 -1
  170. package/dist/orchestrator/execution/agent-loop/bounded-agent-loop-runner.js +1 -0
  171. package/dist/orchestrator/execution/agent-loop/bounded-agent-loop-runner.js.map +1 -1
  172. package/dist/orchestrator/execution/agent-loop/chat-agent-loop-runner.d.ts +1 -1
  173. package/dist/orchestrator/execution/agent-loop/core-loop-control-tools.d.ts +1 -1
  174. package/dist/orchestrator/execution/agent-loop/core-loop-control-tools.d.ts.map +1 -1
  175. package/dist/orchestrator/execution/agent-loop/core-loop-control-tools.js +3 -2
  176. package/dist/orchestrator/execution/agent-loop/core-loop-control-tools.js.map +1 -1
  177. package/dist/orchestrator/execution/agent-loop/core-phase-runner.d.ts +1 -1
  178. package/dist/orchestrator/execution/agent-loop/core-phase-runner.d.ts.map +1 -1
  179. package/dist/orchestrator/execution/agent-loop/core-phase-runner.js +10 -1
  180. package/dist/orchestrator/execution/agent-loop/core-phase-runner.js.map +1 -1
  181. package/dist/orchestrator/execution/agent-loop/execution-policy.d.ts +2 -0
  182. package/dist/orchestrator/execution/agent-loop/execution-policy.d.ts.map +1 -1
  183. package/dist/orchestrator/execution/agent-loop/execution-policy.js +9 -3
  184. package/dist/orchestrator/execution/agent-loop/execution-policy.js.map +1 -1
  185. package/dist/orchestrator/execution/agent-loop/kaggle-training-benchmark.d.ts +2 -0
  186. package/dist/orchestrator/execution/agent-loop/kaggle-training-benchmark.d.ts.map +1 -1
  187. package/dist/orchestrator/execution/agent-loop/kaggle-training-benchmark.js +4 -0
  188. package/dist/orchestrator/execution/agent-loop/kaggle-training-benchmark.js.map +1 -1
  189. package/dist/orchestrator/execution/agent-loop/self-protection.d.ts +9 -0
  190. package/dist/orchestrator/execution/agent-loop/self-protection.d.ts.map +1 -0
  191. package/dist/orchestrator/execution/agent-loop/self-protection.js +74 -0
  192. package/dist/orchestrator/execution/agent-loop/self-protection.js.map +1 -0
  193. package/dist/orchestrator/execution/agent-loop/task-agent-loop-result.d.ts +8 -8
  194. package/dist/orchestrator/execution/task/task-generation.d.ts +3 -1
  195. package/dist/orchestrator/execution/task/task-generation.d.ts.map +1 -1
  196. package/dist/orchestrator/execution/task/task-generation.js +17 -2
  197. package/dist/orchestrator/execution/task/task-generation.js.map +1 -1
  198. package/dist/orchestrator/execution/task/task-lifecycle-runner.d.ts +5 -1
  199. package/dist/orchestrator/execution/task/task-lifecycle-runner.d.ts.map +1 -1
  200. package/dist/orchestrator/execution/task/task-lifecycle-runner.js +9 -5
  201. package/dist/orchestrator/execution/task/task-lifecycle-runner.js.map +1 -1
  202. package/dist/orchestrator/execution/task/task-lifecycle.d.ts +10 -1
  203. package/dist/orchestrator/execution/task/task-lifecycle.d.ts.map +1 -1
  204. package/dist/orchestrator/execution/task/task-lifecycle.js +108 -7
  205. package/dist/orchestrator/execution/task/task-lifecycle.js.map +1 -1
  206. package/dist/orchestrator/execution/task/task-prompt-builder.d.ts +2 -1
  207. package/dist/orchestrator/execution/task/task-prompt-builder.d.ts.map +1 -1
  208. package/dist/orchestrator/execution/task/task-prompt-builder.js +4 -2
  209. package/dist/orchestrator/execution/task/task-prompt-builder.js.map +1 -1
  210. package/dist/orchestrator/execution/types/pipeline.d.ts +6 -6
  211. package/dist/orchestrator/goal/types/goal.d.ts +282 -0
  212. package/dist/orchestrator/goal/types/goal.d.ts.map +1 -1
  213. package/dist/orchestrator/goal/types/goal.js +20 -0
  214. package/dist/orchestrator/goal/types/goal.js.map +1 -1
  215. package/dist/orchestrator/loop/core-loop/contracts.d.ts +46 -3
  216. package/dist/orchestrator/loop/core-loop/contracts.d.ts.map +1 -1
  217. package/dist/orchestrator/loop/core-loop/contracts.js.map +1 -1
  218. package/dist/orchestrator/loop/core-loop/decision-engine.d.ts.map +1 -1
  219. package/dist/orchestrator/loop/core-loop/decision-engine.js +4 -0
  220. package/dist/orchestrator/loop/core-loop/decision-engine.js.map +1 -1
  221. package/dist/orchestrator/loop/core-loop/dream-review-checkpoint.d.ts +48 -0
  222. package/dist/orchestrator/loop/core-loop/dream-review-checkpoint.d.ts.map +1 -0
  223. package/dist/orchestrator/loop/core-loop/dream-review-checkpoint.js +386 -0
  224. package/dist/orchestrator/loop/core-loop/dream-review-checkpoint.js.map +1 -0
  225. package/dist/orchestrator/loop/core-loop/evidence-ledger.js +1 -1
  226. package/dist/orchestrator/loop/core-loop/evidence-ledger.js.map +1 -1
  227. package/dist/orchestrator/loop/core-loop/iteration-kernel.d.ts +1 -0
  228. package/dist/orchestrator/loop/core-loop/iteration-kernel.d.ts.map +1 -1
  229. package/dist/orchestrator/loop/core-loop/iteration-kernel.js +492 -1
  230. package/dist/orchestrator/loop/core-loop/iteration-kernel.js.map +1 -1
  231. package/dist/orchestrator/loop/core-loop/phase-policy.d.ts.map +1 -1
  232. package/dist/orchestrator/loop/core-loop/phase-policy.js +35 -0
  233. package/dist/orchestrator/loop/core-loop/phase-policy.js.map +1 -1
  234. package/dist/orchestrator/loop/core-loop/phase-runtime.d.ts +2 -0
  235. package/dist/orchestrator/loop/core-loop/phase-runtime.d.ts.map +1 -1
  236. package/dist/orchestrator/loop/core-loop/phase-runtime.js +43 -2
  237. package/dist/orchestrator/loop/core-loop/phase-runtime.js.map +1 -1
  238. package/dist/orchestrator/loop/core-loop/phase-specs.d.ts +1054 -2
  239. package/dist/orchestrator/loop/core-loop/phase-specs.d.ts.map +1 -1
  240. package/dist/orchestrator/loop/core-loop/phase-specs.js +205 -0
  241. package/dist/orchestrator/loop/core-loop/phase-specs.js.map +1 -1
  242. package/dist/orchestrator/loop/core-loop/public-research.d.ts +32 -0
  243. package/dist/orchestrator/loop/core-loop/public-research.d.ts.map +1 -0
  244. package/dist/orchestrator/loop/core-loop/public-research.js +112 -0
  245. package/dist/orchestrator/loop/core-loop/public-research.js.map +1 -0
  246. package/dist/orchestrator/loop/core-loop/task-cycle-stall.d.ts.map +1 -1
  247. package/dist/orchestrator/loop/core-loop/task-cycle-stall.js +141 -5
  248. package/dist/orchestrator/loop/core-loop/task-cycle-stall.js.map +1 -1
  249. package/dist/orchestrator/loop/core-loop/task-cycle.d.ts +4 -0
  250. package/dist/orchestrator/loop/core-loop/task-cycle.d.ts.map +1 -1
  251. package/dist/orchestrator/loop/core-loop/task-cycle.js +31 -2
  252. package/dist/orchestrator/loop/core-loop/task-cycle.js.map +1 -1
  253. package/dist/orchestrator/loop/core-loop.d.ts +15 -5
  254. package/dist/orchestrator/loop/core-loop.d.ts.map +1 -1
  255. package/dist/orchestrator/loop/core-loop.js +283 -17
  256. package/dist/orchestrator/loop/core-loop.js.map +1 -1
  257. package/dist/orchestrator/loop/loop-report-helper.d.ts.map +1 -1
  258. package/dist/orchestrator/loop/loop-report-helper.js +4 -0
  259. package/dist/orchestrator/loop/loop-report-helper.js.map +1 -1
  260. package/dist/orchestrator/loop/loop-result-types.d.ts +20 -1
  261. package/dist/orchestrator/loop/loop-result-types.d.ts.map +1 -1
  262. package/dist/orchestrator/loop/loop-result-types.js.map +1 -1
  263. package/dist/orchestrator/loop/post-loop-hooks.d.ts +1 -0
  264. package/dist/orchestrator/loop/post-loop-hooks.d.ts.map +1 -1
  265. package/dist/orchestrator/loop/post-loop-hooks.js +34 -1
  266. package/dist/orchestrator/loop/post-loop-hooks.js.map +1 -1
  267. package/dist/orchestrator/loop/run-policy.d.ts +10 -0
  268. package/dist/orchestrator/loop/run-policy.d.ts.map +1 -0
  269. package/dist/orchestrator/loop/run-policy.js +30 -0
  270. package/dist/orchestrator/loop/run-policy.js.map +1 -0
  271. package/dist/orchestrator/strategy/divergent-exploration.d.ts +37 -0
  272. package/dist/orchestrator/strategy/divergent-exploration.d.ts.map +1 -0
  273. package/dist/orchestrator/strategy/divergent-exploration.js +324 -0
  274. package/dist/orchestrator/strategy/divergent-exploration.js.map +1 -0
  275. package/dist/orchestrator/strategy/strategy-helpers.d.ts +108 -0
  276. package/dist/orchestrator/strategy/strategy-helpers.d.ts.map +1 -1
  277. package/dist/orchestrator/strategy/strategy-helpers.js +34 -2
  278. package/dist/orchestrator/strategy/strategy-helpers.js.map +1 -1
  279. package/dist/orchestrator/strategy/strategy-manager-base.d.ts +20 -1
  280. package/dist/orchestrator/strategy/strategy-manager-base.d.ts.map +1 -1
  281. package/dist/orchestrator/strategy/strategy-manager-base.js +71 -6
  282. package/dist/orchestrator/strategy/strategy-manager-base.js.map +1 -1
  283. package/dist/orchestrator/strategy/types/cross-portfolio.d.ts +2 -2
  284. package/dist/orchestrator/strategy/types/strategy.d.ts +364 -0
  285. package/dist/orchestrator/strategy/types/strategy.d.ts.map +1 -1
  286. package/dist/orchestrator/strategy/types/strategy.js +43 -0
  287. package/dist/orchestrator/strategy/types/strategy.js.map +1 -1
  288. package/dist/platform/corrections/index.d.ts +2 -0
  289. package/dist/platform/corrections/index.d.ts.map +1 -0
  290. package/dist/platform/corrections/index.js +2 -0
  291. package/dist/platform/corrections/index.js.map +1 -0
  292. package/dist/platform/corrections/memory-correction-ledger.d.ts +656 -0
  293. package/dist/platform/corrections/memory-correction-ledger.d.ts.map +1 -0
  294. package/dist/platform/corrections/memory-correction-ledger.js +120 -0
  295. package/dist/platform/corrections/memory-correction-ledger.js.map +1 -0
  296. package/dist/platform/corrections/memory-governance.d.ts +118 -0
  297. package/dist/platform/corrections/memory-governance.d.ts.map +1 -0
  298. package/dist/platform/corrections/memory-governance.js +32 -0
  299. package/dist/platform/corrections/memory-governance.js.map +1 -0
  300. package/dist/platform/corrections/memory-quarantine.d.ts +57 -0
  301. package/dist/platform/corrections/memory-quarantine.d.ts.map +1 -0
  302. package/dist/platform/corrections/memory-quarantine.js +42 -0
  303. package/dist/platform/corrections/memory-quarantine.js.map +1 -0
  304. package/dist/platform/corrections/user-memory-operations.d.ts +31 -0
  305. package/dist/platform/corrections/user-memory-operations.d.ts.map +1 -0
  306. package/dist/platform/corrections/user-memory-operations.js +139 -0
  307. package/dist/platform/corrections/user-memory-operations.js.map +1 -0
  308. package/dist/platform/dream/dream-activation.d.ts +1 -1
  309. package/dist/platform/dream/dream-consolidator.d.ts +5 -0
  310. package/dist/platform/dream/dream-consolidator.d.ts.map +1 -1
  311. package/dist/platform/dream/dream-consolidator.js +235 -13
  312. package/dist/platform/dream/dream-consolidator.js.map +1 -1
  313. package/dist/platform/dream/dream-event-workflows.d.ts +6 -6
  314. package/dist/platform/dream/dream-soil-mutation.d.ts.map +1 -1
  315. package/dist/platform/dream/dream-soil-mutation.js +10 -0
  316. package/dist/platform/dream/dream-soil-mutation.js.map +1 -1
  317. package/dist/platform/dream/dream-types.d.ts +503 -91
  318. package/dist/platform/dream/dream-types.d.ts.map +1 -1
  319. package/dist/platform/dream/dream-types.js +3 -0
  320. package/dist/platform/dream/dream-types.js.map +1 -1
  321. package/dist/platform/dream/playbook-memory.d.ts +14 -14
  322. package/dist/platform/drive/metric-history.d.ts +61 -0
  323. package/dist/platform/drive/metric-history.d.ts.map +1 -0
  324. package/dist/platform/drive/metric-history.js +206 -0
  325. package/dist/platform/drive/metric-history.js.map +1 -0
  326. package/dist/platform/drive/progress-predictor.d.ts +7 -0
  327. package/dist/platform/drive/progress-predictor.d.ts.map +1 -1
  328. package/dist/platform/drive/progress-predictor.js +23 -0
  329. package/dist/platform/drive/progress-predictor.js.map +1 -1
  330. package/dist/platform/drive/stall-detector.d.ts +3 -1
  331. package/dist/platform/drive/stall-detector.d.ts.map +1 -1
  332. package/dist/platform/drive/stall-detector.js +40 -1
  333. package/dist/platform/drive/stall-detector.js.map +1 -1
  334. package/dist/platform/drive/types/satisficing.d.ts +2 -2
  335. package/dist/platform/drive/types/stall.d.ts +4 -0
  336. package/dist/platform/drive/types/stall.d.ts.map +1 -1
  337. package/dist/platform/drive/types/stall.js +1 -0
  338. package/dist/platform/drive/types/stall.js.map +1 -1
  339. package/dist/platform/knowledge/knowledge-manager-agent-memory.d.ts +48 -0
  340. package/dist/platform/knowledge/knowledge-manager-agent-memory.d.ts.map +1 -1
  341. package/dist/platform/knowledge/knowledge-manager-agent-memory.js +154 -4
  342. package/dist/platform/knowledge/knowledge-manager-agent-memory.js.map +1 -1
  343. package/dist/platform/knowledge/knowledge-manager-lint.d.ts.map +1 -1
  344. package/dist/platform/knowledge/knowledge-manager-lint.js +98 -4
  345. package/dist/platform/knowledge/knowledge-manager-lint.js.map +1 -1
  346. package/dist/platform/knowledge/knowledge-manager.d.ts +41 -2
  347. package/dist/platform/knowledge/knowledge-manager.d.ts.map +1 -1
  348. package/dist/platform/knowledge/knowledge-manager.js +45 -5
  349. package/dist/platform/knowledge/knowledge-manager.js.map +1 -1
  350. package/dist/platform/knowledge/types/agent-memory.d.ts +1170 -42
  351. package/dist/platform/knowledge/types/agent-memory.d.ts.map +1 -1
  352. package/dist/platform/knowledge/types/agent-memory.js +13 -3
  353. package/dist/platform/knowledge/types/agent-memory.js.map +1 -1
  354. package/dist/platform/knowledge/types/learning.d.ts +2 -2
  355. package/dist/platform/observation/data-source-adapter.d.ts +1 -0
  356. package/dist/platform/observation/data-source-adapter.d.ts.map +1 -1
  357. package/dist/platform/observation/data-source-adapter.js.map +1 -1
  358. package/dist/platform/observation/observation-datasource.d.ts.map +1 -1
  359. package/dist/platform/observation/observation-datasource.js +2 -0
  360. package/dist/platform/observation/observation-datasource.js.map +1 -1
  361. package/dist/platform/observation/types/data-source.d.ts +153 -9
  362. package/dist/platform/observation/types/data-source.d.ts.map +1 -1
  363. package/dist/platform/observation/types/data-source.js +13 -1
  364. package/dist/platform/observation/types/data-source.js.map +1 -1
  365. package/dist/platform/profile/proactive-feedback-proposals.d.ts +11 -0
  366. package/dist/platform/profile/proactive-feedback-proposals.d.ts.map +1 -0
  367. package/dist/platform/profile/proactive-feedback-proposals.js +106 -0
  368. package/dist/platform/profile/proactive-feedback-proposals.js.map +1 -0
  369. package/dist/platform/profile/profile-change-proposal.d.ts +464 -0
  370. package/dist/platform/profile/profile-change-proposal.d.ts.map +1 -0
  371. package/dist/platform/profile/profile-change-proposal.js +352 -0
  372. package/dist/platform/profile/profile-change-proposal.js.map +1 -0
  373. package/dist/platform/profile/relationship-profile.d.ts +351 -0
  374. package/dist/platform/profile/relationship-profile.d.ts.map +1 -0
  375. package/dist/platform/profile/relationship-profile.js +351 -0
  376. package/dist/platform/profile/relationship-profile.js.map +1 -0
  377. package/dist/platform/profile/retrieval-context.d.ts +12 -0
  378. package/dist/platform/profile/retrieval-context.d.ts.map +1 -0
  379. package/dist/platform/profile/retrieval-context.js +21 -0
  380. package/dist/platform/profile/retrieval-context.js.map +1 -0
  381. package/dist/platform/profile/user-md-profile-import.d.ts +73 -0
  382. package/dist/platform/profile/user-md-profile-import.d.ts.map +1 -0
  383. package/dist/platform/profile/user-md-profile-import.js +179 -0
  384. package/dist/platform/profile/user-md-profile-import.js.map +1 -0
  385. package/dist/platform/soil/content-projections.d.ts.map +1 -1
  386. package/dist/platform/soil/content-projections.js +17 -7
  387. package/dist/platform/soil/content-projections.js.map +1 -1
  388. package/dist/platform/soil/context-compiler.d.ts +16 -1
  389. package/dist/platform/soil/context-compiler.d.ts.map +1 -1
  390. package/dist/platform/soil/context-compiler.js +142 -4
  391. package/dist/platform/soil/context-compiler.js.map +1 -1
  392. package/dist/platform/soil/contracts.d.ts +749 -89
  393. package/dist/platform/soil/contracts.d.ts.map +1 -1
  394. package/dist/platform/soil/contracts.js +22 -0
  395. package/dist/platform/soil/contracts.js.map +1 -1
  396. package/dist/platform/soil/ddl.d.ts.map +1 -1
  397. package/dist/platform/soil/ddl.js +19 -0
  398. package/dist/platform/soil/ddl.js.map +1 -1
  399. package/dist/platform/soil/display/materialize.d.ts.map +1 -1
  400. package/dist/platform/soil/display/materialize.js.map +1 -1
  401. package/dist/platform/soil/importer.d.ts +12 -12
  402. package/dist/platform/soil/sqlite-repository-helpers.d.ts +4 -0
  403. package/dist/platform/soil/sqlite-repository-helpers.d.ts.map +1 -1
  404. package/dist/platform/soil/sqlite-repository-helpers.js.map +1 -1
  405. package/dist/platform/soil/sqlite-repository-search.d.ts.map +1 -1
  406. package/dist/platform/soil/sqlite-repository-search.js +48 -3
  407. package/dist/platform/soil/sqlite-repository-search.js.map +1 -1
  408. package/dist/platform/soil/sqlite-repository-storage.d.ts +3 -1
  409. package/dist/platform/soil/sqlite-repository-storage.d.ts.map +1 -1
  410. package/dist/platform/soil/sqlite-repository-storage.js +124 -3
  411. package/dist/platform/soil/sqlite-repository-storage.js.map +1 -1
  412. package/dist/platform/soil/sqlite-repository.d.ts +10 -1
  413. package/dist/platform/soil/sqlite-repository.d.ts.map +1 -1
  414. package/dist/platform/soil/sqlite-repository.js +46 -4
  415. package/dist/platform/soil/sqlite-repository.js.map +1 -1
  416. package/dist/platform/soil/types.d.ts +16 -16
  417. package/dist/platform/time/deadline-finalization.d.ts +57 -0
  418. package/dist/platform/time/deadline-finalization.d.ts.map +1 -0
  419. package/dist/platform/time/deadline-finalization.js +136 -0
  420. package/dist/platform/time/deadline-finalization.js.map +1 -0
  421. package/dist/platform/time/execution-mode.d.ts +29 -0
  422. package/dist/platform/time/execution-mode.d.ts.map +1 -0
  423. package/dist/platform/time/execution-mode.js +84 -0
  424. package/dist/platform/time/execution-mode.js.map +1 -0
  425. package/dist/platform/traits/curiosity-engine.d.ts +3 -1
  426. package/dist/platform/traits/curiosity-engine.d.ts.map +1 -1
  427. package/dist/platform/traits/curiosity-engine.js +3 -1
  428. package/dist/platform/traits/curiosity-engine.js.map +1 -1
  429. package/dist/platform/traits/curiosity-proposals.d.ts +6 -2
  430. package/dist/platform/traits/curiosity-proposals.d.ts.map +1 -1
  431. package/dist/platform/traits/curiosity-proposals.js +9 -3
  432. package/dist/platform/traits/curiosity-proposals.js.map +1 -1
  433. package/dist/platform/traits/types/curiosity.d.ts +9 -9
  434. package/dist/platform/traits/types/guardrail.d.ts +6 -6
  435. package/dist/reflection/evening-catchup.d.ts.map +1 -1
  436. package/dist/reflection/evening-catchup.js +4 -1
  437. package/dist/reflection/evening-catchup.js.map +1 -1
  438. package/dist/reflection/morning-planning.d.ts.map +1 -1
  439. package/dist/reflection/morning-planning.js +4 -1
  440. package/dist/reflection/morning-planning.js.map +1 -1
  441. package/dist/reflection/weekly-review.d.ts.map +1 -1
  442. package/dist/reflection/weekly-review.js +4 -1
  443. package/dist/reflection/weekly-review.js.map +1 -1
  444. package/dist/reporting/report-formatters.d.ts.map +1 -1
  445. package/dist/reporting/report-formatters.js +67 -2
  446. package/dist/reporting/report-formatters.js.map +1 -1
  447. package/dist/reporting/reporting-engine.d.ts.map +1 -1
  448. package/dist/reporting/reporting-engine.js +3 -1
  449. package/dist/reporting/reporting-engine.js.map +1 -1
  450. package/dist/reporting/reporting-types.d.ts +4 -0
  451. package/dist/reporting/reporting-types.d.ts.map +1 -1
  452. package/dist/reporting/types/report.d.ts +59 -0
  453. package/dist/reporting/types/report.d.ts.map +1 -1
  454. package/dist/reporting/types/report.js +9 -0
  455. package/dist/reporting/types/report.js.map +1 -1
  456. package/dist/runtime/command-dispatcher.d.ts +2 -0
  457. package/dist/runtime/command-dispatcher.d.ts.map +1 -1
  458. package/dist/runtime/command-dispatcher.js +16 -0
  459. package/dist/runtime/command-dispatcher.js.map +1 -1
  460. package/dist/runtime/confirmation-decision.d.ts +94 -0
  461. package/dist/runtime/confirmation-decision.d.ts.map +1 -0
  462. package/dist/runtime/confirmation-decision.js +109 -0
  463. package/dist/runtime/confirmation-decision.js.map +1 -0
  464. package/dist/runtime/control/daemon-runtime-control-executor.d.ts.map +1 -1
  465. package/dist/runtime/control/daemon-runtime-control-executor.js +31 -1
  466. package/dist/runtime/control/daemon-runtime-control-executor.js.map +1 -1
  467. package/dist/runtime/control/runtime-control-intent.d.ts +9 -1
  468. package/dist/runtime/control/runtime-control-intent.d.ts.map +1 -1
  469. package/dist/runtime/control/runtime-control-intent.js +82 -16
  470. package/dist/runtime/control/runtime-control-intent.js.map +1 -1
  471. package/dist/runtime/control/runtime-control-service.d.ts +35 -1
  472. package/dist/runtime/control/runtime-control-service.d.ts.map +1 -1
  473. package/dist/runtime/control/runtime-control-service.js +285 -5
  474. package/dist/runtime/control/runtime-control-service.js.map +1 -1
  475. package/dist/runtime/daemon/client.d.ts +12 -0
  476. package/dist/runtime/daemon/client.d.ts.map +1 -1
  477. package/dist/runtime/daemon/client.js +9 -0
  478. package/dist/runtime/daemon/client.js.map +1 -1
  479. package/dist/runtime/daemon/maintenance.d.ts.map +1 -1
  480. package/dist/runtime/daemon/maintenance.js +21 -2
  481. package/dist/runtime/daemon/maintenance.js.map +1 -1
  482. package/dist/runtime/daemon/runner-commands.d.ts +6 -2
  483. package/dist/runtime/daemon/runner-commands.d.ts.map +1 -1
  484. package/dist/runtime/daemon/runner-commands.js +237 -1
  485. package/dist/runtime/daemon/runner-commands.js.map +1 -1
  486. package/dist/runtime/daemon/runner-goal-cycle.d.ts.map +1 -1
  487. package/dist/runtime/daemon/runner-goal-cycle.js +59 -1
  488. package/dist/runtime/daemon/runner-goal-cycle.js.map +1 -1
  489. package/dist/runtime/daemon/runner-resident-curiosity.d.ts.map +1 -1
  490. package/dist/runtime/daemon/runner-resident-curiosity.js +5 -1
  491. package/dist/runtime/daemon/runner-resident-curiosity.js.map +1 -1
  492. package/dist/runtime/daemon/runner-resident-shared.d.ts +1 -1
  493. package/dist/runtime/daemon/runner-resident-shared.d.ts.map +1 -1
  494. package/dist/runtime/daemon/runner-resident-shared.js +16 -0
  495. package/dist/runtime/daemon/runner-resident-shared.js.map +1 -1
  496. package/dist/runtime/daemon/runner-startup.d.ts.map +1 -1
  497. package/dist/runtime/daemon/runner-startup.js +12 -2
  498. package/dist/runtime/daemon/runner-startup.js.map +1 -1
  499. package/dist/runtime/daemon/runner.d.ts +4 -0
  500. package/dist/runtime/daemon/runner.d.ts.map +1 -1
  501. package/dist/runtime/daemon/runner.js +14 -1
  502. package/dist/runtime/daemon/runner.js.map +1 -1
  503. package/dist/runtime/daemon/runtime-ownership.d.ts +9 -0
  504. package/dist/runtime/daemon/runtime-ownership.d.ts.map +1 -1
  505. package/dist/runtime/daemon/runtime-ownership.js +250 -1
  506. package/dist/runtime/daemon/runtime-ownership.js.map +1 -1
  507. package/dist/runtime/dream-sidecar-review.d.ts +93 -0
  508. package/dist/runtime/dream-sidecar-review.d.ts.map +1 -0
  509. package/dist/runtime/dream-sidecar-review.js +489 -0
  510. package/dist/runtime/dream-sidecar-review.js.map +1 -0
  511. package/dist/runtime/event/server-command-handler.d.ts +2 -4
  512. package/dist/runtime/event/server-command-handler.d.ts.map +1 -1
  513. package/dist/runtime/event/server-command-handler.js +36 -6
  514. package/dist/runtime/event/server-command-handler.js.map +1 -1
  515. package/dist/runtime/event/server-snapshot-reader.d.ts +15 -1
  516. package/dist/runtime/event/server-snapshot-reader.d.ts.map +1 -1
  517. package/dist/runtime/event/server-snapshot-reader.js +66 -2
  518. package/dist/runtime/event/server-snapshot-reader.js.map +1 -1
  519. package/dist/runtime/event/server-types.d.ts +7 -0
  520. package/dist/runtime/event/server-types.d.ts.map +1 -1
  521. package/dist/runtime/event/server.d.ts +5 -0
  522. package/dist/runtime/event/server.d.ts.map +1 -1
  523. package/dist/runtime/event/server.js +43 -11
  524. package/dist/runtime/event/server.js.map +1 -1
  525. package/dist/runtime/evidence-answer.d.ts +41 -0
  526. package/dist/runtime/evidence-answer.d.ts.map +1 -0
  527. package/dist/runtime/evidence-answer.js +366 -0
  528. package/dist/runtime/evidence-answer.js.map +1 -0
  529. package/dist/runtime/executor/goal-worker.d.ts +4 -1
  530. package/dist/runtime/executor/goal-worker.d.ts.map +1 -1
  531. package/dist/runtime/executor/goal-worker.js +5 -1
  532. package/dist/runtime/executor/goal-worker.js.map +1 -1
  533. package/dist/runtime/executor/loop-supervisor.d.ts +4 -0
  534. package/dist/runtime/executor/loop-supervisor.d.ts.map +1 -1
  535. package/dist/runtime/executor/loop-supervisor.js +35 -6
  536. package/dist/runtime/executor/loop-supervisor.js.map +1 -1
  537. package/dist/runtime/gateway/telegram-gateway-adapter.d.ts.map +1 -1
  538. package/dist/runtime/gateway/telegram-gateway-adapter.js +4 -3
  539. package/dist/runtime/gateway/telegram-gateway-adapter.js.map +1 -1
  540. package/dist/runtime/guardrails/backpressure-controller.d.ts +32 -0
  541. package/dist/runtime/guardrails/backpressure-controller.d.ts.map +1 -0
  542. package/dist/runtime/guardrails/backpressure-controller.js +88 -0
  543. package/dist/runtime/guardrails/backpressure-controller.js.map +1 -0
  544. package/dist/runtime/guardrails/circuit-breaker.d.ts +32 -0
  545. package/dist/runtime/guardrails/circuit-breaker.d.ts.map +1 -0
  546. package/dist/runtime/guardrails/circuit-breaker.js +88 -0
  547. package/dist/runtime/guardrails/circuit-breaker.js.map +1 -0
  548. package/dist/runtime/guardrails/guardrail-store.d.ts +23 -0
  549. package/dist/runtime/guardrails/guardrail-store.d.ts.map +1 -0
  550. package/dist/runtime/guardrails/guardrail-store.js +95 -0
  551. package/dist/runtime/guardrails/guardrail-store.js.map +1 -0
  552. package/dist/runtime/guardrails/index.d.ts +4 -0
  553. package/dist/runtime/guardrails/index.d.ts.map +1 -0
  554. package/dist/runtime/guardrails/index.js +4 -0
  555. package/dist/runtime/guardrails/index.js.map +1 -0
  556. package/dist/runtime/interactive-automation/browser-session-store.d.ts +43 -0
  557. package/dist/runtime/interactive-automation/browser-session-store.d.ts.map +1 -0
  558. package/dist/runtime/interactive-automation/browser-session-store.js +104 -0
  559. package/dist/runtime/interactive-automation/browser-session-store.js.map +1 -0
  560. package/dist/runtime/interactive-automation/failure-classifier.d.ts +12 -0
  561. package/dist/runtime/interactive-automation/failure-classifier.d.ts.map +1 -0
  562. package/dist/runtime/interactive-automation/failure-classifier.js +50 -0
  563. package/dist/runtime/interactive-automation/failure-classifier.js.map +1 -0
  564. package/dist/runtime/interactive-automation/index.d.ts +2 -0
  565. package/dist/runtime/interactive-automation/index.d.ts.map +1 -1
  566. package/dist/runtime/interactive-automation/index.js +2 -0
  567. package/dist/runtime/interactive-automation/index.js.map +1 -1
  568. package/dist/runtime/interactive-automation/providers/manus-browser.d.ts.map +1 -1
  569. package/dist/runtime/interactive-automation/providers/manus-browser.js +17 -1
  570. package/dist/runtime/interactive-automation/providers/manus-browser.js.map +1 -1
  571. package/dist/runtime/interactive-automation/types.d.ts +4 -0
  572. package/dist/runtime/interactive-automation/types.d.ts.map +1 -1
  573. package/dist/runtime/interactive-automation/types.js.map +1 -1
  574. package/dist/runtime/notification-routing.d.ts +45 -2
  575. package/dist/runtime/notification-routing.d.ts.map +1 -1
  576. package/dist/runtime/notification-routing.js +196 -79
  577. package/dist/runtime/notification-routing.js.map +1 -1
  578. package/dist/runtime/plugin-loader.d.ts +1 -0
  579. package/dist/runtime/plugin-loader.d.ts.map +1 -1
  580. package/dist/runtime/plugin-loader.js +7 -2
  581. package/dist/runtime/plugin-loader.js.map +1 -1
  582. package/dist/runtime/run-spec/confirmation.d.ts +34 -0
  583. package/dist/runtime/run-spec/confirmation.d.ts.map +1 -0
  584. package/dist/runtime/run-spec/confirmation.js +176 -0
  585. package/dist/runtime/run-spec/confirmation.js.map +1 -0
  586. package/dist/runtime/run-spec/derive.d.ts +284 -0
  587. package/dist/runtime/run-spec/derive.d.ts.map +1 -0
  588. package/dist/runtime/run-spec/derive.js +379 -0
  589. package/dist/runtime/run-spec/derive.js.map +1 -0
  590. package/dist/runtime/run-spec/index.d.ts +5 -0
  591. package/dist/runtime/run-spec/index.d.ts.map +1 -0
  592. package/dist/runtime/run-spec/index.js +5 -0
  593. package/dist/runtime/run-spec/index.js.map +1 -0
  594. package/dist/runtime/run-spec/store.d.ts +11 -0
  595. package/dist/runtime/run-spec/store.d.ts.map +1 -0
  596. package/dist/runtime/run-spec/store.js +36 -0
  597. package/dist/runtime/run-spec/store.js.map +1 -0
  598. package/dist/runtime/run-spec/types.d.ts +495 -0
  599. package/dist/runtime/run-spec/types.d.ts.map +1 -0
  600. package/dist/runtime/run-spec/types.js +87 -0
  601. package/dist/runtime/run-spec/types.js.map +1 -0
  602. package/dist/runtime/schedule/engine-execution.d.ts +2 -1
  603. package/dist/runtime/schedule/engine-execution.d.ts.map +1 -1
  604. package/dist/runtime/schedule/engine-execution.js +1 -1
  605. package/dist/runtime/schedule/engine-execution.js.map +1 -1
  606. package/dist/runtime/schedule/engine-layers.d.ts +2 -1
  607. package/dist/runtime/schedule/engine-layers.d.ts.map +1 -1
  608. package/dist/runtime/schedule/engine-layers.js +3 -1
  609. package/dist/runtime/schedule/engine-layers.js.map +1 -1
  610. package/dist/runtime/schedule/engine.d.ts +2 -1
  611. package/dist/runtime/schedule/engine.d.ts.map +1 -1
  612. package/dist/runtime/schedule/engine.js.map +1 -1
  613. package/dist/runtime/schedule/history.d.ts +4 -4
  614. package/dist/runtime/session-registry/registry.d.ts.map +1 -1
  615. package/dist/runtime/session-registry/registry.js +2 -0
  616. package/dist/runtime/session-registry/registry.js.map +1 -1
  617. package/dist/runtime/session-registry/types.d.ts +102 -94
  618. package/dist/runtime/session-registry/types.d.ts.map +1 -1
  619. package/dist/runtime/session-registry/types.js +2 -0
  620. package/dist/runtime/session-registry/types.js.map +1 -1
  621. package/dist/runtime/store/artifact-retention.d.ts +44 -0
  622. package/dist/runtime/store/artifact-retention.d.ts.map +1 -0
  623. package/dist/runtime/store/artifact-retention.js +263 -0
  624. package/dist/runtime/store/artifact-retention.js.map +1 -0
  625. package/dist/runtime/store/background-run-store.d.ts +1 -0
  626. package/dist/runtime/store/background-run-store.d.ts.map +1 -1
  627. package/dist/runtime/store/background-run-store.js +1 -0
  628. package/dist/runtime/store/background-run-store.js.map +1 -1
  629. package/dist/runtime/store/budget-store.d.ts +442 -0
  630. package/dist/runtime/store/budget-store.d.ts.map +1 -0
  631. package/dist/runtime/store/budget-store.js +318 -0
  632. package/dist/runtime/store/budget-store.js.map +1 -0
  633. package/dist/runtime/store/dream-checkpoints.d.ts +12 -0
  634. package/dist/runtime/store/dream-checkpoints.d.ts.map +1 -0
  635. package/dist/runtime/store/dream-checkpoints.js +18 -0
  636. package/dist/runtime/store/dream-checkpoints.js.map +1 -0
  637. package/dist/runtime/store/evaluator-results.d.ts +97 -0
  638. package/dist/runtime/store/evaluator-results.d.ts.map +1 -0
  639. package/dist/runtime/store/evaluator-results.js +355 -0
  640. package/dist/runtime/store/evaluator-results.js.map +1 -0
  641. package/dist/runtime/store/evidence-ledger.d.ts +6575 -0
  642. package/dist/runtime/store/evidence-ledger.d.ts.map +1 -0
  643. package/dist/runtime/store/evidence-ledger.js +1717 -0
  644. package/dist/runtime/store/evidence-ledger.js.map +1 -0
  645. package/dist/runtime/store/experiment-queue-store.d.ts +1164 -0
  646. package/dist/runtime/store/experiment-queue-store.d.ts.map +1 -0
  647. package/dist/runtime/store/experiment-queue-store.js +341 -0
  648. package/dist/runtime/store/experiment-queue-store.js.map +1 -0
  649. package/dist/runtime/store/health-store.d.ts.map +1 -1
  650. package/dist/runtime/store/health-store.js +6 -0
  651. package/dist/runtime/store/health-store.js.map +1 -1
  652. package/dist/runtime/store/index.d.ts +27 -2
  653. package/dist/runtime/store/index.d.ts.map +1 -1
  654. package/dist/runtime/store/index.js +14 -1
  655. package/dist/runtime/store/index.js.map +1 -1
  656. package/dist/runtime/store/metric-history.d.ts +10 -0
  657. package/dist/runtime/store/metric-history.d.ts.map +1 -0
  658. package/dist/runtime/store/metric-history.js +56 -0
  659. package/dist/runtime/store/metric-history.js.map +1 -0
  660. package/dist/runtime/store/operator-handoff-store.d.ts +179 -0
  661. package/dist/runtime/store/operator-handoff-store.d.ts.map +1 -0
  662. package/dist/runtime/store/operator-handoff-store.js +120 -0
  663. package/dist/runtime/store/operator-handoff-store.js.map +1 -0
  664. package/dist/runtime/store/postmortem-report.d.ts +485 -0
  665. package/dist/runtime/store/postmortem-report.d.ts.map +1 -0
  666. package/dist/runtime/store/postmortem-report.js +561 -0
  667. package/dist/runtime/store/postmortem-report.js.map +1 -0
  668. package/dist/runtime/store/proactive-intervention-store.d.ts +360 -0
  669. package/dist/runtime/store/proactive-intervention-store.d.ts.map +1 -0
  670. package/dist/runtime/store/proactive-intervention-store.js +252 -0
  671. package/dist/runtime/store/proactive-intervention-store.js.map +1 -0
  672. package/dist/runtime/store/reproducibility-manifest.d.ts +565 -0
  673. package/dist/runtime/store/reproducibility-manifest.d.ts.map +1 -0
  674. package/dist/runtime/store/reproducibility-manifest.js +392 -0
  675. package/dist/runtime/store/reproducibility-manifest.js.map +1 -0
  676. package/dist/runtime/store/research-evidence.d.ts +8 -0
  677. package/dist/runtime/store/research-evidence.d.ts.map +1 -0
  678. package/dist/runtime/store/research-evidence.js +15 -0
  679. package/dist/runtime/store/research-evidence.js.map +1 -0
  680. package/dist/runtime/store/runtime-operation-schemas.d.ts +70 -24
  681. package/dist/runtime/store/runtime-operation-schemas.d.ts.map +1 -1
  682. package/dist/runtime/store/runtime-operation-schemas.js +16 -1
  683. package/dist/runtime/store/runtime-operation-schemas.js.map +1 -1
  684. package/dist/runtime/store/runtime-paths.d.ts +27 -0
  685. package/dist/runtime/store/runtime-paths.d.ts.map +1 -1
  686. package/dist/runtime/store/runtime-paths.js +77 -0
  687. package/dist/runtime/store/runtime-paths.js.map +1 -1
  688. package/dist/runtime/store/runtime-schemas.d.ts +1936 -17
  689. package/dist/runtime/store/runtime-schemas.d.ts.map +1 -1
  690. package/dist/runtime/store/runtime-schemas.js +201 -0
  691. package/dist/runtime/store/runtime-schemas.js.map +1 -1
  692. package/dist/runtime/store/safe-pause-store.d.ts +28 -0
  693. package/dist/runtime/store/safe-pause-store.d.ts.map +1 -0
  694. package/dist/runtime/store/safe-pause-store.js +103 -0
  695. package/dist/runtime/store/safe-pause-store.js.map +1 -0
  696. package/dist/runtime/types/daemon.d.ts +232 -14
  697. package/dist/runtime/types/daemon.d.ts.map +1 -1
  698. package/dist/runtime/types/daemon.js +28 -2
  699. package/dist/runtime/types/daemon.js.map +1 -1
  700. package/dist/runtime/types/envelope.d.ts +10 -10
  701. package/dist/runtime/types/hook.d.ts +9 -9
  702. package/dist/runtime/types/notification.d.ts +6 -6
  703. package/dist/runtime/types/plugin.d.ts +2 -2
  704. package/dist/runtime/types/plugin.d.ts.map +1 -1
  705. package/dist/runtime/types/plugin.js +1 -1
  706. package/dist/runtime/types/plugin.js.map +1 -1
  707. package/dist/runtime/types/schedule.d.ts +107 -64
  708. package/dist/runtime/types/schedule.d.ts.map +1 -1
  709. package/dist/runtime/types/schedule.js +10 -1
  710. package/dist/runtime/types/schedule.js.map +1 -1
  711. package/dist/runtime/types/trigger.d.ts +2 -2
  712. package/dist/tools/automation/InteractiveAutomationTools.d.ts +10 -0
  713. package/dist/tools/automation/InteractiveAutomationTools.d.ts.map +1 -1
  714. package/dist/tools/automation/InteractiveAutomationTools.js +139 -8
  715. package/dist/tools/automation/InteractiveAutomationTools.js.map +1 -1
  716. package/dist/tools/builtin/exports.d.ts +2 -1
  717. package/dist/tools/builtin/exports.d.ts.map +1 -1
  718. package/dist/tools/builtin/exports.js +2 -1
  719. package/dist/tools/builtin/exports.js.map +1 -1
  720. package/dist/tools/builtin/factory.d.ts +5 -0
  721. package/dist/tools/builtin/factory.d.ts.map +1 -1
  722. package/dist/tools/builtin/factory.js +20 -3
  723. package/dist/tools/builtin/factory.js.map +1 -1
  724. package/dist/tools/execution/MemoryConsolidateTool/MemoryConsolidateTool.d.ts +4 -4
  725. package/dist/tools/execution/MemoryCorrectionTool/MemoryCorrectionTool.d.ts +76 -0
  726. package/dist/tools/execution/MemoryCorrectionTool/MemoryCorrectionTool.d.ts.map +1 -0
  727. package/dist/tools/execution/MemoryCorrectionTool/MemoryCorrectionTool.js +79 -0
  728. package/dist/tools/execution/MemoryCorrectionTool/MemoryCorrectionTool.js.map +1 -0
  729. package/dist/tools/execution/MemoryCorrectionTool/constants.d.ts +6 -0
  730. package/dist/tools/execution/MemoryCorrectionTool/constants.d.ts.map +1 -0
  731. package/dist/tools/execution/MemoryCorrectionTool/constants.js +6 -0
  732. package/dist/tools/execution/MemoryCorrectionTool/constants.js.map +1 -0
  733. package/dist/tools/execution/MemoryCorrectionTool/prompt.d.ts +2 -0
  734. package/dist/tools/execution/MemoryCorrectionTool/prompt.d.ts.map +1 -0
  735. package/dist/tools/execution/MemoryCorrectionTool/prompt.js +2 -0
  736. package/dist/tools/execution/MemoryCorrectionTool/prompt.js.map +1 -0
  737. package/dist/tools/execution/MemorySaveTool/MemorySaveTool.d.ts +306 -4
  738. package/dist/tools/execution/MemorySaveTool/MemorySaveTool.d.ts.map +1 -1
  739. package/dist/tools/execution/MemorySaveTool/MemorySaveTool.js +8 -0
  740. package/dist/tools/execution/MemorySaveTool/MemorySaveTool.js.map +1 -1
  741. package/dist/tools/fs/ApplyPatchTool/ApplyPatchTool.d.ts.map +1 -1
  742. package/dist/tools/fs/ApplyPatchTool/ApplyPatchTool.js +37 -4
  743. package/dist/tools/fs/ApplyPatchTool/ApplyPatchTool.js.map +1 -1
  744. package/dist/tools/fs/FileValidationTool/protected-path-policy.d.ts.map +1 -1
  745. package/dist/tools/fs/FileValidationTool/protected-path-policy.js +12 -0
  746. package/dist/tools/fs/FileValidationTool/protected-path-policy.js.map +1 -1
  747. package/dist/tools/kaggle/KaggleExperimentTools.d.ts +792 -8
  748. package/dist/tools/kaggle/KaggleExperimentTools.d.ts.map +1 -1
  749. package/dist/tools/kaggle/KaggleExperimentTools.js +284 -19
  750. package/dist/tools/kaggle/KaggleExperimentTools.js.map +1 -1
  751. package/dist/tools/kaggle/KaggleSubmissionTools.d.ts +18 -12
  752. package/dist/tools/kaggle/KaggleSubmissionTools.d.ts.map +1 -1
  753. package/dist/tools/kaggle/KaggleSubmissionTools.js +23 -4
  754. package/dist/tools/kaggle/KaggleSubmissionTools.js.map +1 -1
  755. package/dist/tools/kaggle/KaggleWorkspacePrepareTool.d.ts +28 -9
  756. package/dist/tools/kaggle/KaggleWorkspacePrepareTool.d.ts.map +1 -1
  757. package/dist/tools/kaggle/KaggleWorkspacePrepareTool.js +182 -4
  758. package/dist/tools/kaggle/KaggleWorkspacePrepareTool.js.map +1 -1
  759. package/dist/tools/kaggle/index.d.ts +1 -1
  760. package/dist/tools/kaggle/index.d.ts.map +1 -1
  761. package/dist/tools/kaggle/index.js +1 -1
  762. package/dist/tools/kaggle/index.js.map +1 -1
  763. package/dist/tools/kaggle/metrics.d.ts +845 -4
  764. package/dist/tools/kaggle/metrics.d.ts.map +1 -1
  765. package/dist/tools/kaggle/metrics.js +410 -1
  766. package/dist/tools/kaggle/metrics.js.map +1 -1
  767. package/dist/tools/mutation/ConfigureNotificationRoutingTool/ConfigureNotificationRoutingTool.d.ts +6 -0
  768. package/dist/tools/mutation/ConfigureNotificationRoutingTool/ConfigureNotificationRoutingTool.d.ts.map +1 -1
  769. package/dist/tools/mutation/ConfigureNotificationRoutingTool/ConfigureNotificationRoutingTool.js +9 -2
  770. package/dist/tools/mutation/ConfigureNotificationRoutingTool/ConfigureNotificationRoutingTool.js.map +1 -1
  771. package/dist/tools/mutation/TaskCreateTool/TaskCreateTool.d.ts +4 -4
  772. package/dist/tools/network/McpStdioTool/McpStdioTool.d.ts +4 -4
  773. package/dist/tools/query/MemoryRecallTool/MemoryRecallTool.d.ts +18 -6
  774. package/dist/tools/query/MemoryRecallTool/MemoryRecallTool.d.ts.map +1 -1
  775. package/dist/tools/query/MemoryRecallTool/MemoryRecallTool.js +12 -0
  776. package/dist/tools/query/MemoryRecallTool/MemoryRecallTool.js.map +1 -1
  777. package/dist/tools/query/SoilQueryTool/SoilQueryTool.d.ts +7 -0
  778. package/dist/tools/query/SoilQueryTool/SoilQueryTool.d.ts.map +1 -1
  779. package/dist/tools/query/SoilQueryTool/SoilQueryTool.js +20 -0
  780. package/dist/tools/query/SoilQueryTool/SoilQueryTool.js.map +1 -1
  781. package/dist/tools/query/runtime-dream-review-tool.d.ts +34 -0
  782. package/dist/tools/query/runtime-dream-review-tool.d.ts.map +1 -0
  783. package/dist/tools/query/runtime-dream-review-tool.js +62 -0
  784. package/dist/tools/query/runtime-dream-review-tool.js.map +1 -0
  785. package/dist/tools/query/runtime-session-tools.d.ts.map +1 -1
  786. package/dist/tools/query/runtime-session-tools.js +2 -0
  787. package/dist/tools/query/runtime-session-tools.js.map +1 -1
  788. package/dist/tools/runtime/LongRunningRuntimeTools.d.ts +103 -103
  789. package/dist/tools/runtime/LongRunningRuntimeTools.d.ts.map +1 -1
  790. package/dist/tools/runtime/LongRunningRuntimeTools.js +60 -0
  791. package/dist/tools/runtime/LongRunningRuntimeTools.js.map +1 -1
  792. package/dist/tools/schedule/CreateScheduleTool/CreateScheduleTool.d.ts +62 -32
  793. package/dist/tools/schedule/CreateScheduleTool/CreateScheduleTool.d.ts.map +1 -1
  794. package/dist/tools/schedule/UpdateScheduleTool/UpdateScheduleTool.d.ts +78 -44
  795. package/dist/tools/schedule/UpdateScheduleTool/UpdateScheduleTool.d.ts.map +1 -1
  796. package/dist/tools/system/ShellTool/ShellTool.d.ts.map +1 -1
  797. package/dist/tools/system/ShellTool/ShellTool.js +1 -1
  798. package/dist/tools/system/ShellTool/ShellTool.js.map +1 -1
  799. package/dist/tools/system/ShellTool/command-policy.d.ts +1 -1
  800. package/dist/tools/system/ShellTool/command-policy.d.ts.map +1 -1
  801. package/dist/tools/system/ShellTool/command-policy.js +25 -1
  802. package/dist/tools/system/ShellTool/command-policy.js.map +1 -1
  803. package/dist/tools/system/TestRunnerTool/TestRunnerTool.d.ts +4 -4
  804. package/package.json +5 -2
@@ -0,0 +1,1717 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fsp from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ import { z } from "zod";
5
+ import { createRuntimeStorePaths, ensureRuntimeStorePaths, } from "./runtime-paths.js";
6
+ import { correctionStateForTarget, MemoryCorrectionEntrySchema, MemoryCorrectionTargetStateSchema, summarizeMemoryCorrectionState, } from "../../platform/corrections/memory-correction-ledger.js";
7
+ import { MemoryProvenanceSchema, MemoryQuarantineStateSchema, MemoryVerificationStatusSchema, } from "../../platform/corrections/memory-quarantine.js";
8
+ import { summarizeEvidenceMetricTrends } from "./metric-history.js";
9
+ import { summarizeEvidenceEvaluatorResults, } from "./evaluator-results.js";
10
+ import { summarizeEvidenceResearchMemos, } from "./research-evidence.js";
11
+ import { summarizeEvidenceDreamCheckpoints, } from "./dream-checkpoints.js";
12
+ import { summarizeArtifactRetention, RuntimeArtifactRetentionClassSchema, } from "./artifact-retention.js";
13
+ export const RuntimeEvidenceOutcomeSchema = z.enum([
14
+ "improved",
15
+ "regressed",
16
+ "inconclusive",
17
+ "failed",
18
+ "blocked",
19
+ "continued",
20
+ ]);
21
+ export const RuntimeEvidenceEntryKindSchema = z.enum([
22
+ "observation",
23
+ "strategy",
24
+ "task_generation",
25
+ "execution",
26
+ "verification",
27
+ "decision",
28
+ "metric",
29
+ "evaluator",
30
+ "research",
31
+ "dream_checkpoint",
32
+ "artifact",
33
+ "failure",
34
+ "correction",
35
+ "other",
36
+ ]);
37
+ export const RuntimeEvidenceArtifactRefSchema = z.object({
38
+ label: z.string().min(1),
39
+ path: z.string().min(1).optional(),
40
+ state_relative_path: z.string().min(1).optional(),
41
+ url: z.string().url().optional(),
42
+ kind: z.enum(["log", "metrics", "report", "diff", "url", "other"]).default("other"),
43
+ retention_class: RuntimeArtifactRetentionClassSchema.optional(),
44
+ size_bytes: z.number().int().nonnegative().optional(),
45
+ source: z.string().min(1).optional(),
46
+ dependency_refs: z.array(z.string().min(1)).optional(),
47
+ }).strict();
48
+ export const RuntimeEvidenceMetricSchema = z.object({
49
+ label: z.string().min(1),
50
+ value: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
51
+ unit: z.string().min(1).optional(),
52
+ direction: z.enum(["maximize", "minimize", "neutral"]).optional(),
53
+ confidence: z.number().min(0).max(1).optional(),
54
+ observed_at: z.string().datetime().optional(),
55
+ source: z.string().min(1).optional(),
56
+ summary: z.string().min(1).optional(),
57
+ }).strict();
58
+ export const RuntimeEvidenceCandidateDispositionSchema = z.enum(["retained", "promoted", "retired"]);
59
+ export const RuntimeEvidenceCandidateLineageSchema = z.object({
60
+ parent_candidate_id: z.string().min(1).optional(),
61
+ source_candidate_id: z.string().min(1).optional(),
62
+ source_strategy_id: z.string().min(1).optional(),
63
+ source_strategy: z.string().min(1).optional(),
64
+ strategy_family: z.string().min(1),
65
+ feature_lineage: z.array(z.string().min(1)).default([]),
66
+ model_lineage: z.array(z.string().min(1)).default([]),
67
+ config_lineage: z.array(z.string().min(1)).default([]),
68
+ seed_lineage: z.array(z.string().min(1)).default([]),
69
+ fold_lineage: z.array(z.string().min(1)).default([]),
70
+ postprocess_lineage: z.array(z.string().min(1)).default([]),
71
+ notes: z.string().min(1).optional(),
72
+ }).strict();
73
+ export const RuntimeEvidenceCandidateSimilaritySchema = z.object({
74
+ candidate_id: z.string().min(1),
75
+ similarity: z.number().min(0).max(1),
76
+ signal: z.enum(["declared", "lineage", "metric_correlation", "artifact_overlap", "other"]).default("declared"),
77
+ summary: z.string().min(1).optional(),
78
+ }).strict();
79
+ export const RuntimeEvidenceCandidateNearMissReasonSchema = z.enum([
80
+ "close_to_best",
81
+ "stability",
82
+ "novelty",
83
+ "weak_dimension_improvement",
84
+ "complementarity",
85
+ "ensemble_potential",
86
+ ]);
87
+ export const RuntimeEvidenceCandidateNearMissSchema = z.object({
88
+ status: z.enum(["retained", "promoted", "rejected"]).default("retained"),
89
+ reason_to_keep: z.array(RuntimeEvidenceCandidateNearMissReasonSchema).min(1),
90
+ margin_to_best: z.number().min(0).optional(),
91
+ weak_dimensions: z.array(z.string().min(1)).default([]),
92
+ complementary_candidate_ids: z.array(z.string().min(1)).default([]),
93
+ follow_up: z.object({
94
+ title: z.string().min(1),
95
+ rationale: z.string().min(1),
96
+ target_dimensions: z.array(z.string().min(1)).default([]),
97
+ expected_evidence_gain: z.string().min(1).optional(),
98
+ }).strict().optional(),
99
+ evidence_refs: z.array(z.string().min(1)).default([]),
100
+ summary: z.string().min(1).optional(),
101
+ }).strict();
102
+ export const RuntimeEvidenceCandidateRecordSchema = z.object({
103
+ candidate_id: z.string().min(1),
104
+ label: z.string().min(1).optional(),
105
+ lineage: RuntimeEvidenceCandidateLineageSchema,
106
+ metrics: z.array(RuntimeEvidenceMetricSchema).default([]),
107
+ artifacts: z.array(RuntimeEvidenceArtifactRefSchema).default([]),
108
+ similarity: z.array(RuntimeEvidenceCandidateSimilaritySchema).default([]),
109
+ robustness: z.object({
110
+ stability_score: z.number().min(0).max(1).optional(),
111
+ diversity_score: z.number().min(0).max(1).optional(),
112
+ risk_penalty: z.number().min(0).max(1).optional(),
113
+ robust_score: z.number().min(0).max(1).optional(),
114
+ evidence_confidence: z.number().min(0).max(1).optional(),
115
+ repeated_evaluations: z.number().int().nonnegative().optional(),
116
+ mean_score: z.number().optional(),
117
+ max_score: z.number().optional(),
118
+ score_stddev: z.number().min(0).optional(),
119
+ fold_score_range: z.number().min(0).optional(),
120
+ seed_score_range: z.number().min(0).optional(),
121
+ weak_dimensions: z.array(z.string().min(1)).default([]),
122
+ provenance_refs: z.array(z.string().min(1)).default([]),
123
+ summary: z.string().min(1).optional(),
124
+ }).strict().optional(),
125
+ near_miss: RuntimeEvidenceCandidateNearMissSchema.optional(),
126
+ disposition: RuntimeEvidenceCandidateDispositionSchema.default("retained"),
127
+ disposition_reason: z.string().min(1).optional(),
128
+ produced_at: z.string().datetime().optional(),
129
+ }).strict();
130
+ export const RuntimeEvidenceEvaluatorSignalSchema = z.enum(["local", "external"]);
131
+ export const RuntimeEvidenceEvaluatorStatusSchema = z.enum([
132
+ "pending",
133
+ "ready",
134
+ "approval_required",
135
+ "submitted",
136
+ "passed",
137
+ "succeeded",
138
+ "completed",
139
+ "failed",
140
+ "regressed",
141
+ "blocked",
142
+ "unknown",
143
+ ]);
144
+ export const RuntimeEvidenceEvaluatorPublishActionSchema = z.object({
145
+ id: z.string().min(1),
146
+ label: z.string().min(1),
147
+ tool_name: z.string().min(1).optional(),
148
+ payload_ref: z.string().min(1).optional(),
149
+ approval_required: z.literal(true).default(true),
150
+ status: z.enum(["approval_required", "approved", "submitted", "completed", "blocked"]).optional(),
151
+ }).strict();
152
+ export const RuntimeEvidenceEvaluatorValidationSchema = z.object({
153
+ status: z.enum(["pending", "passed", "failed", "blocked", "unknown"]).default("unknown"),
154
+ command: z.string().min(1).optional(),
155
+ summary: z.string().min(1).optional(),
156
+ }).strict();
157
+ export const RuntimeEvidenceEvaluatorProvenanceSchema = z.object({
158
+ kind: z.enum(["local_command", "external_url", "ci", "benchmark", "human_review", "other"]).default("other"),
159
+ command: z.string().min(1).optional(),
160
+ url: z.string().url().optional(),
161
+ run_id: z.string().min(1).optional(),
162
+ external_id: z.string().min(1).optional(),
163
+ raw_ref: z.string().min(1).optional(),
164
+ retrieved_at: z.string().datetime().optional(),
165
+ }).strict();
166
+ export const RuntimeEvidenceEvaluatorBudgetSchema = z.object({
167
+ policy_id: z.string().min(1).optional(),
168
+ max_attempts: z.number().int().positive().optional(),
169
+ used_attempts: z.number().int().nonnegative().optional(),
170
+ remaining_attempts: z.number().int().nonnegative(),
171
+ approval_required: z.boolean().default(true),
172
+ deadline_at: z.string().datetime().optional(),
173
+ phase: z.enum(["exploration", "consolidation", "finalization", "other"]).optional(),
174
+ portfolio_policy: z.object({
175
+ diversified_portfolio_required: z.boolean().default(false),
176
+ reserve_for_finalization: z.boolean().default(false),
177
+ min_strategy_families: z.number().int().positive().optional(),
178
+ }).strict().optional(),
179
+ }).strict();
180
+ export const RuntimeEvidenceEvaluatorCandidateSnapshotSchema = z.object({
181
+ evidence_entry_id: z.string().min(1).optional(),
182
+ primary_metric_label: z.string().min(1).optional(),
183
+ local_metrics: z.array(RuntimeEvidenceMetricSchema).default([]),
184
+ robust_selection: z.object({
185
+ raw_rank: z.number().int().positive().optional(),
186
+ robust_score: z.number().min(0).max(1).optional(),
187
+ stability_score: z.number().min(0).max(1).optional(),
188
+ diversity_score: z.number().min(0).max(1).optional(),
189
+ risk_penalty: z.number().min(0).max(1).optional(),
190
+ portfolio_role: z.enum(["raw_best", "robust_best", "safe", "aggressive", "diverse", "near_miss", "other"]).optional(),
191
+ }).strict().optional(),
192
+ summary: z.string().min(1).optional(),
193
+ }).strict();
194
+ export const RuntimeEvidenceEvaluatorCalibrationSchema = z.object({
195
+ mode: z.literal("calibration_only").default("calibration_only"),
196
+ use_for_selection: z.boolean().default(false),
197
+ direct_optimization_allowed: z.literal(false).default(false),
198
+ minimum_observations: z.number().int().positive().default(1),
199
+ conclusion: z.string().min(1).optional(),
200
+ }).strict();
201
+ export const RuntimeEvidenceEvaluatorObservationSchema = z.object({
202
+ evaluator_id: z.string().min(1),
203
+ signal: RuntimeEvidenceEvaluatorSignalSchema,
204
+ source: z.string().min(1),
205
+ candidate_id: z.string().min(1),
206
+ candidate_label: z.string().min(1).optional(),
207
+ artifact_labels: z.array(z.string().min(1)).optional(),
208
+ status: RuntimeEvidenceEvaluatorStatusSchema.default("unknown"),
209
+ score: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
210
+ score_label: z.string().min(1).optional(),
211
+ direction: z.enum(["maximize", "minimize", "neutral"]).optional(),
212
+ observed_at: z.string().datetime().optional(),
213
+ expected_score: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
214
+ expected_status: RuntimeEvidenceEvaluatorStatusSchema.optional(),
215
+ expectation_source: z.string().min(1).optional(),
216
+ validation: RuntimeEvidenceEvaluatorValidationSchema.optional(),
217
+ publish_action: RuntimeEvidenceEvaluatorPublishActionSchema.optional(),
218
+ provenance: RuntimeEvidenceEvaluatorProvenanceSchema.optional(),
219
+ budget: RuntimeEvidenceEvaluatorBudgetSchema.optional(),
220
+ candidate_snapshot: RuntimeEvidenceEvaluatorCandidateSnapshotSchema.optional(),
221
+ calibration: RuntimeEvidenceEvaluatorCalibrationSchema.optional(),
222
+ summary: z.string().min(1).optional(),
223
+ }).strict();
224
+ export const RuntimeEvidenceResearchSourceSchema = z.object({
225
+ url: z.string().url(),
226
+ title: z.string().min(1).optional(),
227
+ source_type: z.enum(["official_docs", "maintainer", "paper", "issue_thread", "example", "writeup", "other"]).default("other"),
228
+ provenance: z.enum(["quoted", "paraphrased", "summarized"]).default("summarized"),
229
+ relevance: z.string().min(1).optional(),
230
+ }).strict();
231
+ export const RuntimeEvidenceResearchFindingSchema = z.object({
232
+ finding: z.string().min(1),
233
+ source_urls: z.array(z.string().url()).min(1),
234
+ applicability: z.string().min(1),
235
+ risks_constraints: z.array(z.string().min(1)).default([]),
236
+ proposed_experiment: z.string().min(1),
237
+ expected_metric_impact: z.string().min(1),
238
+ fact_vs_adaptation: z.object({
239
+ facts: z.array(z.string().min(1)).default([]),
240
+ adaptation: z.string().min(1),
241
+ }).strict(),
242
+ }).strict();
243
+ export const RuntimeEvidenceResearchExternalActionSchema = z.object({
244
+ label: z.string().min(1),
245
+ reason: z.string().min(1),
246
+ approval_required: z.literal(true).default(true),
247
+ }).strict();
248
+ export const RuntimeEvidenceResearchMemoSchema = z.object({
249
+ trigger: z.enum(["plateau", "uncertainty", "knowledge_gap"]),
250
+ query: z.string().min(1),
251
+ summary: z.string().min(1),
252
+ sources: z.array(RuntimeEvidenceResearchSourceSchema).min(1),
253
+ findings: z.array(RuntimeEvidenceResearchFindingSchema).min(1),
254
+ candidate_playbook: z.object({
255
+ title: z.string().min(1),
256
+ steps: z.array(z.string().min(1)).default([]),
257
+ source_urls: z.array(z.string().url()).default([]),
258
+ }).strict().optional(),
259
+ untrusted_content_policy: z.literal("webpage_instructions_are_untrusted").default("webpage_instructions_are_untrusted"),
260
+ external_actions: z.array(RuntimeEvidenceResearchExternalActionSchema).default([]),
261
+ confidence: z.number().min(0).max(1).default(0.5),
262
+ }).strict();
263
+ export const RuntimeEvidenceDreamCheckpointTriggerSchema = z.enum([
264
+ "iteration",
265
+ "plateau",
266
+ "breakthrough",
267
+ "pre_finalization",
268
+ ]);
269
+ export const RuntimeEvidenceMemoryUsageStatsSchema = z.object({
270
+ last_used_at: z.string().datetime().nullable().default(null),
271
+ use_count: z.number().int().nonnegative().default(0),
272
+ validated_count: z.number().int().nonnegative().default(0),
273
+ negative_outcome_count: z.number().int().nonnegative().default(0),
274
+ }).strict();
275
+ export const RuntimeEvidenceDreamCheckpointMemoryRefSchema = z.object({
276
+ source_type: z.enum(["soil", "playbook", "runtime_evidence", "other"]),
277
+ ref: z.string().min(1).optional(),
278
+ summary: z.string().min(1),
279
+ authority: z.literal("advisory_only").default("advisory_only"),
280
+ relevance_score: z.number().min(0).max(1).optional(),
281
+ source_reliability: z.number().min(0).max(1).optional(),
282
+ verification_status: MemoryVerificationStatusSchema.optional(),
283
+ provenance: MemoryProvenanceSchema.optional(),
284
+ quarantine_state: MemoryQuarantineStateSchema.optional(),
285
+ recency_score: z.number().min(0).max(1).optional(),
286
+ prior_success_contribution: z.number().min(0).max(1).optional(),
287
+ retrieval: z.object({
288
+ kind: z.enum(["route_hit", "fallback_hit", "checkpoint", "manual", "unknown"]).default("unknown"),
289
+ score: z.number().min(0).max(1).optional(),
290
+ confidence: z.number().min(0).max(1).optional(),
291
+ }).strict().optional(),
292
+ usage_stats: RuntimeEvidenceMemoryUsageStatsSchema.optional(),
293
+ ranking_trace: z.object({
294
+ score: z.number().min(0).max(1),
295
+ decision: z.enum(["admitted", "rejected"]),
296
+ reason: z.string().min(1),
297
+ }).strict().optional(),
298
+ }).strict();
299
+ export const RuntimeEvidenceDreamCheckpointStrategyCandidateSchema = z.object({
300
+ candidate_ref: z.string().min(1).optional(),
301
+ title: z.string().min(1),
302
+ rationale: z.string().min(1),
303
+ target_dimensions: z.array(z.string().min(1)).default([]),
304
+ expected_evidence_gain: z.string().min(1).optional(),
305
+ retry_reason: z.string().min(1).optional(),
306
+ failed_lineage_warning: z.object({
307
+ fingerprint: z.string().min(1),
308
+ count: z.number().int().positive(),
309
+ reason: z.string().min(1),
310
+ }).strict().optional(),
311
+ }).strict();
312
+ export const RuntimeEvidenceDreamCheckpointActiveHypothesisSchema = z.object({
313
+ hypothesis: z.string().min(1),
314
+ supporting_evidence_ref: z.string().min(1).optional(),
315
+ target_metric_or_dimension: z.string().min(1),
316
+ expected_next_observation: z.string().min(1),
317
+ status: z.enum(["active", "testing", "supported", "weakened"]).default("active"),
318
+ }).strict();
319
+ export const RuntimeEvidenceDreamCheckpointRejectedApproachSchema = z.object({
320
+ approach: z.string().min(1),
321
+ rejection_reason: z.string().min(1),
322
+ candidate_ref: z.string().min(1).optional(),
323
+ evidence_ref: z.string().min(1).optional(),
324
+ revisit_condition: z.string().min(1).optional(),
325
+ confidence: z.number().min(0).max(1).default(0.5),
326
+ }).strict();
327
+ export const RuntimeEvidenceDreamRunControlRecommendationSchema = z.object({
328
+ id: z.string().min(1).optional(),
329
+ action: z.enum([
330
+ "stay_current_mode",
331
+ "widen_exploration",
332
+ "consolidate_candidates",
333
+ "freeze_experiment_queue",
334
+ "enter_finalization",
335
+ "preserve_near_miss_candidates",
336
+ "retire_low_value_lineage",
337
+ "request_operator_approval",
338
+ ]),
339
+ rationale: z.string().min(1),
340
+ evidence: z.array(z.object({
341
+ kind: z.enum(["metric", "artifact", "lineage", "task_history", "deadline", "external_feedback", "memory", "runtime_state"]),
342
+ ref: z.string().min(1).optional(),
343
+ summary: z.string().min(1),
344
+ }).strict()).min(1),
345
+ target_mode: z.enum(["exploration", "consolidation", "finalization"]).optional(),
346
+ target_strategy_family: z.string().min(1).optional(),
347
+ candidate_refs: z.array(z.string().min(1)).default([]),
348
+ lineage_refs: z.array(z.string().min(1)).default([]),
349
+ approval_required: z.boolean().default(false),
350
+ risk: z.enum(["low", "medium", "high"]).default("medium"),
351
+ confidence: z.number().min(0).max(1).default(0.5),
352
+ policy_decision: z.object({
353
+ disposition: z.enum(["auto_apply", "approval_required", "advisory_only"]),
354
+ reason: z.string().min(1),
355
+ }).strict().optional(),
356
+ }).strict();
357
+ export const RuntimeEvidenceDreamCheckpointSchema = z.object({
358
+ trigger: RuntimeEvidenceDreamCheckpointTriggerSchema,
359
+ summary: z.string().min(1),
360
+ current_goal: z.string().min(1),
361
+ active_dimensions: z.array(z.string().min(1)).default([]),
362
+ best_evidence_so_far: z.string().min(1).optional(),
363
+ recent_strategy_families: z.array(z.string().min(1)).default([]),
364
+ exhausted: z.array(z.string().min(1)).default([]),
365
+ promising: z.array(z.string().min(1)).default([]),
366
+ relevant_memories: z.array(RuntimeEvidenceDreamCheckpointMemoryRefSchema).default([]),
367
+ active_hypotheses: z.array(RuntimeEvidenceDreamCheckpointActiveHypothesisSchema).default([]),
368
+ rejected_approaches: z.array(RuntimeEvidenceDreamCheckpointRejectedApproachSchema).default([]),
369
+ next_strategy_candidates: z.array(RuntimeEvidenceDreamCheckpointStrategyCandidateSchema).default([]),
370
+ run_control_recommendations: z.array(RuntimeEvidenceDreamRunControlRecommendationSchema).optional(),
371
+ guidance: z.string().min(1),
372
+ uncertainty: z.array(z.string().min(1)).default([]),
373
+ context_authority: z.literal("advisory_only").default("advisory_only"),
374
+ confidence: z.number().min(0).max(1).default(0.5),
375
+ }).strict();
376
+ export const RuntimeEvidenceDivergentHypothesisSchema = z.object({
377
+ strategy_id: z.string().min(1).optional(),
378
+ hypothesis: z.string().min(1),
379
+ strategy_family: z.string().min(1),
380
+ role: z.enum(["exploitation", "adjacent_exploration", "divergent_exploration"]),
381
+ novelty_score: z.number().min(0).max(1),
382
+ similarity_to_recent_failures: z.number().min(0).max(1).default(0),
383
+ expected_cost: z.enum(["low", "medium", "high"]),
384
+ relationship_to_lineage: z.enum([
385
+ "current_best",
386
+ "neighbor",
387
+ "failed_lineage",
388
+ "different_mechanism",
389
+ "different_assumption",
390
+ "unknown",
391
+ ]),
392
+ prior_evidence: z.string().min(1).optional(),
393
+ downrank_reason: z.string().min(1).optional(),
394
+ smoke_status: z.enum(["not_run", "promote", "defer", "retire"]).default("not_run"),
395
+ smoke_reason: z.string().min(1).optional(),
396
+ smoke_evidence_ref: z.string().min(1).optional(),
397
+ evidence_authority: z.literal("speculative_hypothesis").default("speculative_hypothesis"),
398
+ }).strict();
399
+ export const RuntimeEvidenceEntrySchema = z.object({
400
+ schema_version: z.literal("runtime-evidence-entry-v1"),
401
+ id: z.string().min(1),
402
+ occurred_at: z.string().datetime(),
403
+ kind: RuntimeEvidenceEntryKindSchema,
404
+ scope: z.object({
405
+ goal_id: z.string().min(1).optional(),
406
+ run_id: z.string().min(1).optional(),
407
+ task_id: z.string().min(1).optional(),
408
+ loop_index: z.number().int().nonnegative().optional(),
409
+ phase: z.string().min(1).optional(),
410
+ }).strict(),
411
+ hypothesis: z.string().min(1).optional(),
412
+ strategy: z.string().min(1).optional(),
413
+ task: z.object({
414
+ id: z.string().min(1).optional(),
415
+ description: z.string().min(1).optional(),
416
+ action: z.string().min(1).optional(),
417
+ primary_dimension: z.string().min(1).optional(),
418
+ }).strict().optional(),
419
+ verification: z.object({
420
+ command: z.string().min(1).optional(),
421
+ verdict: z.string().min(1).optional(),
422
+ confidence: z.number().min(0).max(1).optional(),
423
+ summary: z.string().min(1).optional(),
424
+ }).strict().optional(),
425
+ metrics: z.array(RuntimeEvidenceMetricSchema).default([]),
426
+ evaluators: z.array(RuntimeEvidenceEvaluatorObservationSchema).optional(),
427
+ research: z.array(RuntimeEvidenceResearchMemoSchema).optional(),
428
+ dream_checkpoints: z.array(RuntimeEvidenceDreamCheckpointSchema).optional(),
429
+ divergent_exploration: z.array(RuntimeEvidenceDivergentHypothesisSchema).optional(),
430
+ correction: MemoryCorrectionEntrySchema.optional(),
431
+ correction_state: MemoryCorrectionTargetStateSchema.optional(),
432
+ verification_status: MemoryVerificationStatusSchema.optional(),
433
+ provenance: MemoryProvenanceSchema.optional(),
434
+ quarantine_state: MemoryQuarantineStateSchema.optional(),
435
+ candidates: z.array(RuntimeEvidenceCandidateRecordSchema).optional(),
436
+ artifacts: z.array(RuntimeEvidenceArtifactRefSchema).default([]),
437
+ result: z.object({
438
+ status: z.string().min(1).optional(),
439
+ summary: z.string().min(1).optional(),
440
+ error: z.string().min(1).optional(),
441
+ }).strict().optional(),
442
+ outcome: RuntimeEvidenceOutcomeSchema.optional(),
443
+ decision_reason: z.string().min(1).optional(),
444
+ raw_refs: z.array(z.object({
445
+ kind: z.string().min(1),
446
+ id: z.string().min(1).optional(),
447
+ path: z.string().min(1).optional(),
448
+ state_relative_path: z.string().min(1).optional(),
449
+ url: z.string().url().optional(),
450
+ }).strict()).default([]),
451
+ summary: z.string().min(1).optional(),
452
+ }).strict().refine((entry) => entry.scope.goal_id || entry.scope.run_id, {
453
+ message: "goal_id or run_id is required",
454
+ path: ["scope"],
455
+ });
456
+ const summaryIndexUpdateLocks = new Map();
457
+ export class RuntimeEvidenceLedger {
458
+ paths;
459
+ constructor(runtimeRootOrPaths) {
460
+ this.paths =
461
+ typeof runtimeRootOrPaths === "string"
462
+ ? createRuntimeStorePaths(runtimeRootOrPaths)
463
+ : runtimeRootOrPaths ?? createRuntimeStorePaths();
464
+ }
465
+ async ensureReady() {
466
+ await ensureRuntimeStorePaths(this.paths);
467
+ }
468
+ goalPath(goalId) {
469
+ return this.paths.evidenceGoalPath(goalId);
470
+ }
471
+ runPath(runId) {
472
+ return this.paths.evidenceRunPath(runId);
473
+ }
474
+ async append(input) {
475
+ const entry = RuntimeEvidenceEntrySchema.parse({
476
+ schema_version: "runtime-evidence-entry-v1",
477
+ id: input.id ?? randomUUID(),
478
+ occurred_at: input.occurred_at ?? new Date().toISOString(),
479
+ metrics: input.metrics ?? [],
480
+ evaluators: input.evaluators ?? [],
481
+ research: input.research ?? [],
482
+ dream_checkpoints: input.dream_checkpoints ?? [],
483
+ divergent_exploration: input.divergent_exploration ?? [],
484
+ candidates: input.candidates ?? [],
485
+ artifacts: input.artifacts ?? [],
486
+ raw_refs: input.raw_refs ?? [],
487
+ ...input,
488
+ });
489
+ await this.ensureReady();
490
+ const targets = new Set();
491
+ if (entry.scope.goal_id)
492
+ targets.add(this.paths.evidenceGoalPath(entry.scope.goal_id));
493
+ if (entry.scope.run_id)
494
+ targets.add(this.paths.evidenceRunPath(entry.scope.run_id));
495
+ await Promise.all([...targets].map(async (target) => {
496
+ await withSummaryIndexUpdateLock(target, async () => {
497
+ await fsp.mkdir(path.dirname(target), { recursive: true });
498
+ const preAppendCheckpoint = await readPreAppendCheckpoint(target);
499
+ await fsp.appendFile(target, `${JSON.stringify(entry)}\n`, "utf8");
500
+ await updateSummaryIndexAfterAppend(target, this.paths, [entry], preAppendCheckpoint);
501
+ });
502
+ }));
503
+ return [entry];
504
+ }
505
+ async appendCorrection(input) {
506
+ const { scope, evidence_id, ...correctionInput } = input;
507
+ const correction = MemoryCorrectionEntrySchema.parse(correctionInput);
508
+ await this.append({
509
+ id: evidence_id ?? correction.correction_id,
510
+ occurred_at: correction.created_at,
511
+ kind: "correction",
512
+ scope,
513
+ correction,
514
+ summary: correction.reason,
515
+ raw_refs: [{
516
+ kind: correction.target_ref.kind,
517
+ id: correction.target_ref.id,
518
+ }],
519
+ });
520
+ return correction;
521
+ }
522
+ async readByGoal(goalId) {
523
+ return readEvidenceFile(this.paths.evidenceGoalPath(goalId));
524
+ }
525
+ async readByRun(runId) {
526
+ return readEvidenceFile(this.paths.evidenceRunPath(runId));
527
+ }
528
+ async summarizeGoal(goalId) {
529
+ const manifests = await readReproducibilityManifests(this.paths, { goal_id: goalId });
530
+ const indexed = manifests.length === 0
531
+ ? await readSummaryIndex(this.paths.evidenceGoalPath(goalId), { goal_id: goalId })
532
+ : null;
533
+ if (indexed)
534
+ return indexed.summary;
535
+ const read = await this.readByGoal(goalId);
536
+ const summary = summarizeEvidence({ goal_id: goalId }, read, manifests);
537
+ return summary;
538
+ }
539
+ async summarizeRun(runId) {
540
+ const manifests = await readReproducibilityManifests(this.paths, { run_id: runId });
541
+ const indexed = manifests.length === 0
542
+ ? await readSummaryIndex(this.paths.evidenceRunPath(runId), { run_id: runId })
543
+ : null;
544
+ if (indexed)
545
+ return indexed.summary;
546
+ const read = await this.readByRun(runId);
547
+ const summary = summarizeEvidence({ run_id: runId }, read, manifests);
548
+ return summary;
549
+ }
550
+ async rebuildSummaryIndexForGoal(goalId) {
551
+ return rebuildSummaryIndex(this.paths.evidenceGoalPath(goalId), this.paths);
552
+ }
553
+ async rebuildSummaryIndexForRun(runId) {
554
+ return rebuildSummaryIndex(this.paths.evidenceRunPath(runId), this.paths);
555
+ }
556
+ }
557
+ async function rebuildSummaryIndex(canonicalPath, paths) {
558
+ const scope = summaryScopeFromPath(canonicalPath);
559
+ const read = await readEvidenceFile(canonicalPath);
560
+ const manifests = await readReproducibilityManifests(paths, scope);
561
+ const summary = summarizeEvidence(scope, read, manifests);
562
+ await writeSummaryIndex(canonicalPath, summary, manifests.length === 0 ? read : undefined);
563
+ return summary;
564
+ }
565
+ async function withSummaryIndexUpdateLock(canonicalPath, action) {
566
+ const previous = summaryIndexUpdateLocks.get(canonicalPath) ?? Promise.resolve();
567
+ let release = () => undefined;
568
+ const current = new Promise((resolve) => {
569
+ release = resolve;
570
+ });
571
+ const next = previous.then(() => current, () => current);
572
+ summaryIndexUpdateLocks.set(canonicalPath, next);
573
+ await previous;
574
+ try {
575
+ return await action();
576
+ }
577
+ finally {
578
+ release();
579
+ if (summaryIndexUpdateLocks.get(canonicalPath) === next) {
580
+ summaryIndexUpdateLocks.delete(canonicalPath);
581
+ }
582
+ }
583
+ }
584
+ async function updateSummaryIndexAfterAppend(canonicalPath, paths, appendedEntries, preAppendCheckpoint) {
585
+ const scope = summaryScopeFromPath(canonicalPath);
586
+ const manifests = await readReproducibilityManifests(paths, scope);
587
+ if (manifests.length > 0) {
588
+ return rebuildSummaryIndex(canonicalPath, paths);
589
+ }
590
+ if (!preAppendCheckpoint) {
591
+ return rebuildSummaryIndex(canonicalPath, paths);
592
+ }
593
+ const read = {
594
+ entries: [...preAppendCheckpoint.entries, ...appendedEntries],
595
+ warnings: preAppendCheckpoint.warnings,
596
+ };
597
+ const summary = summarizeEvidence(scope, read);
598
+ await writeSummaryIndex(canonicalPath, summary, read);
599
+ return summary;
600
+ }
601
+ function summaryIndexPath(canonicalPath) {
602
+ return `${canonicalPath}.summary.json`;
603
+ }
604
+ function summaryScopeFromPath(canonicalPath) {
605
+ const basename = path.basename(canonicalPath, ".jsonl");
606
+ const decoded = decodeURIComponent(basename);
607
+ return canonicalPath.includes(`${path.sep}runs${path.sep}`) ? { run_id: decoded } : { goal_id: decoded };
608
+ }
609
+ async function readReproducibilityManifests(paths, scope) {
610
+ let fileNames;
611
+ try {
612
+ fileNames = await fsp.readdir(paths.reproducibilityManifestsDir);
613
+ }
614
+ catch (err) {
615
+ if (err.code === "ENOENT")
616
+ return [];
617
+ throw err;
618
+ }
619
+ const manifests = [];
620
+ for (const fileName of fileNames) {
621
+ if (!fileName.endsWith(".json"))
622
+ continue;
623
+ try {
624
+ const parsed = JSON.parse(await fsp.readFile(path.join(paths.reproducibilityManifestsDir, fileName), "utf8"));
625
+ if (parsed.schema_version !== "runtime-reproducibility-manifest-v1")
626
+ continue;
627
+ if (scope.goal_id && parsed.scope?.goal_id !== scope.goal_id)
628
+ continue;
629
+ if (scope.run_id && parsed.scope?.run_id !== scope.run_id)
630
+ continue;
631
+ manifests.push({
632
+ ...parsed,
633
+ artifacts: Array.isArray(parsed.artifacts) ? parsed.artifacts.filter(isManifestArtifactRef) : [],
634
+ });
635
+ }
636
+ catch {
637
+ continue;
638
+ }
639
+ }
640
+ return manifests;
641
+ }
642
+ function isManifestArtifactRef(value) {
643
+ return typeof value === "object"
644
+ && value !== null
645
+ && typeof value.label === "string";
646
+ }
647
+ async function readSummaryIndex(canonicalPath, expectedScope) {
648
+ return readSummaryIndexWithStat(canonicalPath, expectedScope);
649
+ }
650
+ async function readPreAppendCheckpoint(canonicalPath) {
651
+ try {
652
+ const stat = await fsp.stat(canonicalPath);
653
+ if (stat.size === 0)
654
+ return { entries: [], warnings: [] };
655
+ }
656
+ catch (err) {
657
+ if (err.code === "ENOENT")
658
+ return { entries: [], warnings: [] };
659
+ throw err;
660
+ }
661
+ const scope = summaryScopeFromPath(canonicalPath);
662
+ const index = await readSummaryIndexWithStat(canonicalPath, scope);
663
+ return index ? readCheckpointFromSummaryIndex(index) : null;
664
+ }
665
+ async function readSummaryIndexWithStat(canonicalPath, expectedScope) {
666
+ let text;
667
+ try {
668
+ text = await fsp.readFile(summaryIndexPath(canonicalPath), "utf8");
669
+ }
670
+ catch (err) {
671
+ if (err.code === "ENOENT")
672
+ return null;
673
+ throw err;
674
+ }
675
+ try {
676
+ const parsed = JSON.parse(text);
677
+ if (parsed.schema_version !== "runtime-evidence-summary-index-v1")
678
+ return null;
679
+ if (parsed.summary.schema_version !== "runtime-evidence-summary-v1")
680
+ return null;
681
+ if (!isCurrentEvidenceSummaryShape(parsed.summary))
682
+ return null;
683
+ const stat = await fsp.stat(canonicalPath);
684
+ if (parsed.canonical_log_size !== stat.size)
685
+ return null;
686
+ if (parsed.canonical_log_mtime_ms !== stat.mtimeMs)
687
+ return null;
688
+ if (expectedScope.goal_id && parsed.summary.scope.goal_id !== expectedScope.goal_id)
689
+ return null;
690
+ if (expectedScope.run_id && parsed.summary.scope.run_id !== expectedScope.run_id)
691
+ return null;
692
+ return parsed;
693
+ }
694
+ catch {
695
+ return null;
696
+ }
697
+ }
698
+ function readCheckpointFromSummaryIndex(index) {
699
+ const checkpoint = index.checkpoint;
700
+ if (!checkpoint || checkpoint.schema_version !== "runtime-evidence-summary-checkpoint-v1")
701
+ return null;
702
+ if (!Array.isArray(checkpoint.entries) || !Array.isArray(checkpoint.warnings))
703
+ return null;
704
+ const entries = [];
705
+ for (const entry of checkpoint.entries) {
706
+ const parsed = RuntimeEvidenceEntrySchema.safeParse(entry);
707
+ if (!parsed.success)
708
+ return null;
709
+ entries.push(parsed.data);
710
+ }
711
+ const warnings = [];
712
+ for (const warning of checkpoint.warnings) {
713
+ if (typeof warning !== "object"
714
+ || warning === null
715
+ || typeof warning.file !== "string"
716
+ || typeof warning.line !== "number"
717
+ || typeof warning.message !== "string") {
718
+ return null;
719
+ }
720
+ warnings.push(warning);
721
+ }
722
+ return { entries, warnings };
723
+ }
724
+ function isCurrentEvidenceSummaryShape(summary) {
725
+ return summary.context_policy_version === "quarantine-filtered-planning-context-v2"
726
+ && Array.isArray(summary.candidate_lineages)
727
+ && Array.isArray(summary.corrections)
728
+ && typeof summary.correction_state === "object"
729
+ && summary.correction_state !== null
730
+ && Array.isArray(summary.recommended_candidate_portfolio)
731
+ && Array.isArray(summary.near_miss_candidates)
732
+ && typeof summary.artifact_retention === "object"
733
+ && summary.artifact_retention !== null
734
+ && Array.isArray(summary.evaluator_summary.budgets)
735
+ && Array.isArray(summary.evaluator_summary.calibration)
736
+ && typeof summary.candidate_selection_summary === "object"
737
+ && summary.candidate_selection_summary !== null;
738
+ }
739
+ async function writeSummaryIndex(canonicalPath, summary, checkpointRead) {
740
+ const stat = await fsp.stat(canonicalPath);
741
+ const index = {
742
+ schema_version: "runtime-evidence-summary-index-v1",
743
+ generated_at: new Date().toISOString(),
744
+ canonical_log_path: canonicalPath,
745
+ canonical_log_size: stat.size,
746
+ canonical_log_mtime_ms: stat.mtimeMs,
747
+ summary,
748
+ ...(checkpointRead
749
+ ? {
750
+ checkpoint: {
751
+ schema_version: "runtime-evidence-summary-checkpoint-v1",
752
+ entries: checkpointRead.entries,
753
+ warnings: checkpointRead.warnings,
754
+ },
755
+ }
756
+ : {}),
757
+ };
758
+ await fsp.mkdir(path.dirname(canonicalPath), { recursive: true });
759
+ await fsp.writeFile(summaryIndexPath(canonicalPath), `${JSON.stringify(index)}\n`, "utf8");
760
+ }
761
+ async function readEvidenceFile(filePath) {
762
+ let text;
763
+ try {
764
+ text = await fsp.readFile(filePath, "utf8");
765
+ }
766
+ catch (err) {
767
+ if (err.code === "ENOENT") {
768
+ return { entries: [], warnings: [] };
769
+ }
770
+ throw err;
771
+ }
772
+ const entries = [];
773
+ const warnings = [];
774
+ const lines = text.split(/\r?\n/);
775
+ for (let index = 0; index < lines.length; index += 1) {
776
+ const line = lines[index];
777
+ if (!line?.trim())
778
+ continue;
779
+ try {
780
+ const parsed = RuntimeEvidenceEntrySchema.safeParse(JSON.parse(line));
781
+ if (parsed.success) {
782
+ entries.push(parsed.data);
783
+ }
784
+ else {
785
+ warnings.push({
786
+ file: filePath,
787
+ line: index + 1,
788
+ message: parsed.error.issues.map((issue) => issue.message).join("; "),
789
+ });
790
+ }
791
+ }
792
+ catch (err) {
793
+ warnings.push({
794
+ file: filePath,
795
+ line: index + 1,
796
+ message: err instanceof Error ? err.message : String(err),
797
+ });
798
+ }
799
+ }
800
+ return { entries, warnings };
801
+ }
802
+ function summarizeEvidence(scope, read, manifests = []) {
803
+ const entries = [...read.entries].sort((a, b) => a.occurred_at.localeCompare(b.occurred_at));
804
+ const corrections = entries.flatMap((entry) => entry.correction ? [entry.correction] : []);
805
+ const correctionState = summarizeMemoryCorrectionState(corrections);
806
+ const activeEntries = entries.filter((entry) => isRuntimeEvidenceEntryActive(entry, correctionState));
807
+ const newestFirst = [...activeEntries].reverse();
808
+ const evaluatorSummary = summarizeEvidenceEvaluatorResults(activeEntries);
809
+ const activeDreamCheckpoints = filterRetractedDreamCheckpointMemories(summarizeEvidenceDreamCheckpoints(activeEntries), correctionState, scope);
810
+ return {
811
+ schema_version: "runtime-evidence-summary-v1",
812
+ context_policy_version: "quarantine-filtered-planning-context-v2",
813
+ generated_at: new Date().toISOString(),
814
+ scope,
815
+ total_entries: entries.length,
816
+ latest_strategy: newestFirst.find((entry) => entry.kind === "strategy" || Boolean(entry.strategy) || Boolean(entry.decision_reason)) ?? null,
817
+ best_evidence: chooseBestEvidence(newestFirst),
818
+ metric_trends: summarizeEvidenceMetricTrends(activeEntries),
819
+ evaluator_summary: evaluatorSummary,
820
+ research_memos: summarizeEvidenceResearchMemos(activeEntries),
821
+ dream_checkpoints: activeDreamCheckpoints,
822
+ divergent_exploration: activeEntries
823
+ .flatMap((entry) => entry.divergent_exploration ?? [])
824
+ .slice(-10)
825
+ .reverse(),
826
+ corrections,
827
+ correction_state: correctionState,
828
+ candidate_lineages: summarizeCandidateLineages(activeEntries),
829
+ recommended_candidate_portfolio: selectDiversifiedCandidatePortfolio(activeEntries),
830
+ candidate_selection_summary: summarizeCandidateSelection(activeEntries, evaluatorSummary),
831
+ near_miss_candidates: summarizeNearMissCandidates(activeEntries),
832
+ artifact_retention: summarizeArtifactRetention(activeEntries, { manifests }),
833
+ recent_failed_attempts: newestFirst
834
+ .filter((entry) => entry.outcome === "failed"
835
+ || entry.outcome === "regressed"
836
+ || entry.kind === "failure"
837
+ || entry.result?.status === "failed"
838
+ || entry.verification?.verdict === "fail")
839
+ .slice(0, 5),
840
+ failed_lineages: summarizeFailedLineages(activeEntries),
841
+ recent_entries: newestFirst.slice(0, 10),
842
+ warnings: read.warnings,
843
+ };
844
+ }
845
+ function isRuntimeEvidenceEntryActive(entry, correctionState) {
846
+ if (entry.kind === "correction")
847
+ return false;
848
+ if (entry.quarantine_state?.status === "quarantined")
849
+ return false;
850
+ if (entry.verification_status === "suspicious" || entry.verification_status === "contradicted")
851
+ return false;
852
+ if (isSuspiciousProvenance(entry.provenance))
853
+ return false;
854
+ return runtimeEvidenceCorrectionRefs(entry).every((ref) => correctionStateForTarget(correctionState, ref).active);
855
+ }
856
+ function runtimeEvidenceCorrectionRefs(entry) {
857
+ const refs = [
858
+ { kind: "runtime_evidence", id: entry.id },
859
+ ];
860
+ if (entry.scope.run_id) {
861
+ refs.push({ kind: "runtime_evidence", id: entry.id, scope: { run_id: entry.scope.run_id } });
862
+ }
863
+ if (entry.scope.goal_id) {
864
+ refs.push({ kind: "runtime_evidence", id: entry.id, scope: { goal_id: entry.scope.goal_id } });
865
+ }
866
+ if (entry.scope.goal_id || entry.scope.run_id || entry.scope.task_id) {
867
+ refs.push({
868
+ kind: "runtime_evidence",
869
+ id: entry.id,
870
+ scope: {
871
+ ...(entry.scope.goal_id ? { goal_id: entry.scope.goal_id } : {}),
872
+ ...(entry.scope.run_id ? { run_id: entry.scope.run_id } : {}),
873
+ ...(entry.scope.task_id ? { task_id: entry.scope.task_id } : {}),
874
+ },
875
+ });
876
+ }
877
+ return refs;
878
+ }
879
+ function filterRetractedDreamCheckpointMemories(checkpoints, correctionState, scope) {
880
+ return checkpoints
881
+ .map((checkpoint) => {
882
+ const relevant_memories = checkpoint.relevant_memories.filter((memory) => isDreamCheckpointMemoryRefAdmissible(memory)
883
+ && (!memory.ref || dreamMemoryCorrectionRefs(memory.ref, checkpoint, scope).every((ref) => correctionStateForTarget(correctionState, ref).active)));
884
+ return {
885
+ checkpoint,
886
+ relevant_memories,
887
+ planning_context_status: relevant_memories.length === checkpoint.relevant_memories.length
888
+ ? "active"
889
+ : "partially_retracted",
890
+ };
891
+ })
892
+ .filter(({ checkpoint, relevant_memories }) => checkpoint.relevant_memories.length === 0 || relevant_memories.length > 0)
893
+ .map(({ checkpoint, relevant_memories, planning_context_status }) => ({
894
+ ...checkpoint,
895
+ relevant_memories,
896
+ planning_context_status,
897
+ }));
898
+ }
899
+ function isDreamCheckpointMemoryRefAdmissible(memory) {
900
+ if (memory.quarantine_state?.status === "quarantined")
901
+ return false;
902
+ if (memory.verification_status === "suspicious" || memory.verification_status === "contradicted")
903
+ return false;
904
+ if (isSuspiciousProvenance(memory.provenance))
905
+ return false;
906
+ if (memory.provenance
907
+ && (memory.provenance.source_type === "web" || memory.provenance.source_type === "external")
908
+ && memory.provenance.reliability !== undefined
909
+ && memory.provenance.reliability < 0.5) {
910
+ return false;
911
+ }
912
+ return true;
913
+ }
914
+ function isSuspiciousProvenance(provenance) {
915
+ if (!provenance)
916
+ return false;
917
+ if (provenance.verification_status === "suspicious" || provenance.verification_status === "contradicted") {
918
+ return true;
919
+ }
920
+ const riskSignals = new Set(provenance.risk_signals);
921
+ return riskSignals.has("hallucinated")
922
+ || riskSignals.has("low_provenance")
923
+ || riskSignals.has("contradiction")
924
+ || riskSignals.has("prompt_injection_like")
925
+ || riskSignals.has("unverified_external");
926
+ }
927
+ function dreamMemoryCorrectionRefs(ref, checkpoint, scope) {
928
+ const refs = [{ kind: "dream_checkpoint", id: ref }];
929
+ if (checkpoint.run_id)
930
+ refs.push({ kind: "dream_checkpoint", id: ref, scope: { run_id: checkpoint.run_id } });
931
+ if (checkpoint.goal_id)
932
+ refs.push({ kind: "dream_checkpoint", id: ref, scope: { goal_id: checkpoint.goal_id } });
933
+ if (scope.run_id)
934
+ refs.push({ kind: "dream_checkpoint", id: ref, scope: { run_id: scope.run_id } });
935
+ if (scope.goal_id)
936
+ refs.push({ kind: "dream_checkpoint", id: ref, scope: { goal_id: scope.goal_id } });
937
+ return refs;
938
+ }
939
+ export function selectDiversifiedCandidatePortfolio(entriesOldestFirst, options = {}) {
940
+ const limit = options.limit ?? 3;
941
+ if (limit <= 0)
942
+ return [];
943
+ const nearDuplicateSimilarity = options.nearDuplicateSimilarity ?? 0.85;
944
+ const primaryMetric = resolvePrimaryCandidateMetricKey(entriesOldestFirst);
945
+ const candidates = extractCandidateEvidenceContexts(entriesOldestFirst, primaryMetric)
946
+ .filter((context) => context.candidate.disposition !== "retired")
947
+ .sort(compareCandidateEvidenceContexts);
948
+ const selected = [];
949
+ const skipped = [];
950
+ for (const candidate of candidates) {
951
+ if (selected.length >= limit)
952
+ break;
953
+ const duplicateSignal = mostSimilarSelectedCandidate(candidate, selected);
954
+ if (duplicateSignal && duplicateSignal.similarity >= nearDuplicateSimilarity) {
955
+ skipped.push({ ...candidate, similarity_to_selected: duplicateSignal });
956
+ continue;
957
+ }
958
+ selected.push({
959
+ ...candidate,
960
+ role: selected.length === 0 ? "top_metric" : "diverse_representative",
961
+ ...(duplicateSignal ? { similarity_to_selected: duplicateSignal } : {}),
962
+ });
963
+ }
964
+ for (const candidate of skipped) {
965
+ if (selected.length >= limit)
966
+ break;
967
+ selected.push({
968
+ ...candidate,
969
+ role: "lineage_representative",
970
+ });
971
+ }
972
+ return selected.map(toPortfolioSlot);
973
+ }
974
+ function summarizeCandidateSelection(entriesOldestFirst, evaluatorSummary) {
975
+ const primaryMetric = resolvePrimaryCandidateMetricKey(entriesOldestFirst);
976
+ const contexts = extractCandidateEvidenceContexts(entriesOldestFirst, primaryMetric)
977
+ .filter((context) => context.candidate.disposition !== "retired");
978
+ const rawRanked = [...contexts].sort(compareCandidateEvidenceContexts);
979
+ const scored = scoreCandidateSelectionContexts(rawRanked, evaluatorSummary?.calibration ?? []);
980
+ const ranked = [...scored].sort((a, b) => b.robust_score - a.robust_score || a.raw_rank - b.raw_rank);
981
+ const rawBest = scored.find((candidate) => candidate.raw_rank === 1) ?? null;
982
+ const robustBest = ranked[0] ?? null;
983
+ return {
984
+ primary_metric: primaryMetric,
985
+ raw_best: rawBest,
986
+ robust_best: robustBest,
987
+ ranked,
988
+ final_portfolio: {
989
+ safe: selectSafeCandidate(scored),
990
+ aggressive: rawBest,
991
+ diverse: selectDiverseCandidate(scored, robustBest),
992
+ },
993
+ };
994
+ }
995
+ function scoreCandidateSelectionContexts(rawRanked, calibration = []) {
996
+ const metricValues = rawRanked
997
+ .map((context) => context.metric?.value)
998
+ .filter((value) => typeof value === "number" && Number.isFinite(value));
999
+ const minMetric = metricValues.length > 0 ? Math.min(...metricValues) : 0;
1000
+ const maxMetric = metricValues.length > 0 ? Math.max(...metricValues) : 0;
1001
+ const rawBestFamily = rawRanked[0]?.candidate.lineage.strategy_family;
1002
+ const allCandidates = rawRanked.map((context) => context.candidate);
1003
+ return rawRanked.map((context, index) => {
1004
+ const candidate = context.candidate;
1005
+ const metricScore = normalizedMetricScore(context.metric, minMetric, maxMetric);
1006
+ const stabilityScore = clamp01(candidate.robustness?.stability_score ?? context.metric?.confidence ?? 0.5);
1007
+ const inferredDiversity = inferredDiversityScore(candidate, rawBestFamily, allCandidates);
1008
+ const diversityScore = clamp01(candidate.robustness?.diversity_score === undefined
1009
+ ? inferredDiversity
1010
+ : Math.min(candidate.robustness.diversity_score, inferredDiversity));
1011
+ const riskPenalty = clamp01(candidate.robustness?.risk_penalty ?? inferredCandidateRiskPenalty(candidate));
1012
+ const evidenceConfidence = clamp01(candidate.robustness?.evidence_confidence ?? context.metric?.confidence ?? 0.5);
1013
+ const calibrationAdjustment = evaluatorCalibrationAdjustment(candidate.candidate_id, calibration);
1014
+ const robustScore = clamp01(candidate.robustness?.robust_score
1015
+ ?? (metricScore * 0.45 + stabilityScore * 0.3 + diversityScore * 0.15 + evidenceConfidence * 0.1 - riskPenalty + calibrationAdjustment));
1016
+ return {
1017
+ candidate_id: candidate.candidate_id,
1018
+ ...(candidate.label ? { label: candidate.label } : {}),
1019
+ strategy_family: candidate.lineage.strategy_family,
1020
+ evidence_entry_id: context.entry_id,
1021
+ raw_rank: index + 1,
1022
+ ...(context.metric ? { raw_metric: context.metric } : {}),
1023
+ robust_score: roundScore(robustScore),
1024
+ calibration_adjustment: roundScore(calibrationAdjustment),
1025
+ metric_score: roundScore(metricScore),
1026
+ stability_score: roundScore(stabilityScore),
1027
+ diversity_score: roundScore(diversityScore),
1028
+ risk_penalty: roundScore(riskPenalty),
1029
+ evidence_confidence: roundScore(evidenceConfidence),
1030
+ reasons: candidateSelectionReasons(candidate, {
1031
+ metricScore,
1032
+ stabilityScore,
1033
+ diversityScore,
1034
+ riskPenalty,
1035
+ evidenceConfidence,
1036
+ calibrationAdjustment,
1037
+ }),
1038
+ };
1039
+ });
1040
+ }
1041
+ function evaluatorCalibrationAdjustment(candidateId, calibration) {
1042
+ const relevant = calibration.filter((item) => item.candidate_id === candidateId
1043
+ && item.use_for_selection
1044
+ && item.direct_optimization_allowed === false);
1045
+ if (relevant.length === 0)
1046
+ return 0;
1047
+ const average = relevant.reduce((sum, item) => sum + item.selection_adjustment, 0) / relevant.length;
1048
+ if (relevant.length < Math.max(...relevant.map((item) => item.minimum_observations)))
1049
+ return 0;
1050
+ return Math.min(0.08, Math.max(-0.08, average));
1051
+ }
1052
+ function normalizedMetricScore(metric, minMetric, maxMetric) {
1053
+ if (!metric)
1054
+ return 0;
1055
+ if (maxMetric === minMetric)
1056
+ return 0.5;
1057
+ const distance = metric.direction === "maximize"
1058
+ ? (metric.value - minMetric) / (maxMetric - minMetric)
1059
+ : (maxMetric - metric.value) / (maxMetric - minMetric);
1060
+ return clamp01(distance);
1061
+ }
1062
+ function inferredDiversityScore(candidate, rawBestFamily, allCandidates) {
1063
+ if (!rawBestFamily)
1064
+ return 0.5;
1065
+ const highestSimilarity = highestKnownSimilarity(candidate, allCandidates);
1066
+ const lineageBase = candidate.lineage.strategy_family !== rawBestFamily ? 0.75 : 0.45;
1067
+ if (highestSimilarity > 0)
1068
+ return clamp01(Math.min(lineageBase, 1 - highestSimilarity));
1069
+ return lineageBase;
1070
+ }
1071
+ function highestKnownSimilarity(candidate, allCandidates) {
1072
+ let highest = candidate.similarity.reduce((max, similarity) => Math.max(max, similarity.similarity), 0);
1073
+ for (const other of allCandidates) {
1074
+ if (other.candidate_id === candidate.candidate_id)
1075
+ continue;
1076
+ for (const similarity of other.similarity) {
1077
+ if (similarity.candidate_id === candidate.candidate_id) {
1078
+ highest = Math.max(highest, similarity.similarity);
1079
+ }
1080
+ }
1081
+ }
1082
+ return highest;
1083
+ }
1084
+ function inferredCandidateRiskPenalty(candidate) {
1085
+ const lineageText = [
1086
+ ...candidate.lineage.config_lineage,
1087
+ ...candidate.lineage.postprocess_lineage,
1088
+ ].map(normalizeLineageText).join(" ");
1089
+ if (lineageText.includes("manual") || lineageText.includes("threshold") || lineageText.includes("postprocess")) {
1090
+ return 0.15;
1091
+ }
1092
+ if (lineageText.includes("calibration") || lineageText.includes("weight")) {
1093
+ return 0.08;
1094
+ }
1095
+ return 0;
1096
+ }
1097
+ function candidateSelectionReasons(candidate, scores) {
1098
+ const reasons = [];
1099
+ if (scores.stabilityScore >= 0.8)
1100
+ reasons.push("strong stability evidence");
1101
+ if (scores.diversityScore >= 0.8)
1102
+ reasons.push("diverse lineage");
1103
+ if (scores.riskPenalty >= 0.15)
1104
+ reasons.push("penalized for overfit-prone lineage or post-processing");
1105
+ if (scores.metricScore >= 0.95)
1106
+ reasons.push("top raw metric evidence");
1107
+ if (scores.calibrationAdjustment > 0)
1108
+ reasons.push("external feedback calibrates local validation upward");
1109
+ if (scores.calibrationAdjustment < 0)
1110
+ reasons.push("external feedback calibrates local validation downward");
1111
+ if (candidate.robustness?.summary)
1112
+ reasons.push(candidate.robustness.summary);
1113
+ return reasons.length > 0 ? reasons : ["risk-adjusted candidate evidence"];
1114
+ }
1115
+ function selectSafeCandidate(candidates) {
1116
+ return [...candidates].sort((a, b) => b.stability_score - a.stability_score
1117
+ || a.risk_penalty - b.risk_penalty
1118
+ || b.robust_score - a.robust_score
1119
+ || a.raw_rank - b.raw_rank)[0] ?? null;
1120
+ }
1121
+ function selectDiverseCandidate(candidates, robustBest) {
1122
+ const robustFamily = robustBest?.strategy_family;
1123
+ return [...candidates]
1124
+ .filter((candidate) => !robustFamily || candidate.strategy_family !== robustFamily)
1125
+ .filter((candidate) => candidate.diversity_score >= 0.5)
1126
+ .sort((a, b) => b.diversity_score - a.diversity_score
1127
+ || b.robust_score - a.robust_score
1128
+ || a.raw_rank - b.raw_rank)[0] ?? null;
1129
+ }
1130
+ function summarizeNearMissCandidates(entriesOldestFirst) {
1131
+ const primaryMetric = resolvePrimaryCandidateMetricKey(entriesOldestFirst);
1132
+ const contexts = extractCandidateEvidenceContexts(entriesOldestFirst, primaryMetric)
1133
+ .filter((context) => context.candidate.disposition !== "retired");
1134
+ const rawRanked = [...contexts].sort(compareCandidateEvidenceContexts);
1135
+ const rawBest = rawRanked[0] ?? null;
1136
+ const scoredByCandidateId = new Map(scoreCandidateSelectionContexts(rawRanked).map((candidate) => [candidate.candidate_id, candidate]));
1137
+ const result = [];
1138
+ for (const context of rawRanked) {
1139
+ if (!rawBest || context.candidate.candidate_id === rawBest.candidate.candidate_id)
1140
+ continue;
1141
+ const scored = scoredByCandidateId.get(context.candidate.candidate_id);
1142
+ const reasons = nearMissReasonsForCandidate(context, rawBest, scored);
1143
+ if (reasons.length === 0)
1144
+ continue;
1145
+ const nearMiss = context.candidate.near_miss;
1146
+ if (nearMiss?.status === "rejected")
1147
+ continue;
1148
+ result.push({
1149
+ candidate_id: context.candidate.candidate_id,
1150
+ ...(context.candidate.label ? { label: context.candidate.label } : {}),
1151
+ strategy_family: context.candidate.lineage.strategy_family,
1152
+ evidence_entry_id: context.entry_id,
1153
+ occurred_at: context.occurred_at,
1154
+ raw_rank: scored?.raw_rank ?? rawRanked.indexOf(context) + 1,
1155
+ ...(context.metric ? { raw_metric: context.metric } : {}),
1156
+ raw_best_candidate_id: rawBest.candidate.candidate_id,
1157
+ ...nearMissMarginContext(context, rawBest, nearMiss),
1158
+ reason_to_keep: reasons,
1159
+ weak_dimensions: nearMiss?.weak_dimensions ?? context.candidate.robustness?.weak_dimensions ?? [],
1160
+ complementary_candidate_ids: nearMiss?.complementary_candidate_ids ?? complementaryCandidateIds(context.candidate),
1161
+ ...(nearMiss?.follow_up ? { follow_up: nearMiss.follow_up } : {}),
1162
+ ...(context.candidate.disposition_reason ? { retained_reason: context.candidate.disposition_reason } : {}),
1163
+ evidence_refs: nearMiss?.evidence_refs ?? context.candidate.robustness?.provenance_refs ?? [],
1164
+ ...(nearMiss?.summary ?? context.candidate.robustness?.summary
1165
+ ? { summary: nearMiss?.summary ?? context.candidate.robustness?.summary }
1166
+ : {}),
1167
+ });
1168
+ }
1169
+ return result.sort((a, b) => nearMissReasonRank(b.reason_to_keep) - nearMissReasonRank(a.reason_to_keep)
1170
+ || (b.raw_metric?.confidence ?? 0) - (a.raw_metric?.confidence ?? 0)
1171
+ || a.raw_rank - b.raw_rank).slice(0, 8);
1172
+ }
1173
+ function nearMissReasonsForCandidate(context, rawBest, scored) {
1174
+ const explicit = context.candidate.near_miss?.reason_to_keep ?? [];
1175
+ const reasons = new Set(explicit);
1176
+ if (context.candidate.near_miss?.status === "retained" || context.candidate.near_miss?.status === "promoted") {
1177
+ for (const reason of inferredNearMissReasons(context, rawBest, scored))
1178
+ reasons.add(reason);
1179
+ }
1180
+ else if (context.candidate.near_miss) {
1181
+ for (const reason of inferredNearMissReasons(context, rawBest, scored))
1182
+ reasons.add(reason);
1183
+ }
1184
+ else if (isImplicitNearMiss(context, rawBest, scored)) {
1185
+ for (const reason of inferredNearMissReasons(context, rawBest, scored))
1186
+ reasons.add(reason);
1187
+ }
1188
+ return [...reasons];
1189
+ }
1190
+ function inferredNearMissReasons(context, rawBest, scored) {
1191
+ const reasons = [];
1192
+ const margin = candidateMetricMargin(context.metric, rawBest.metric);
1193
+ if (margin !== null && isCloseToBestMargin(margin, rawBest.metric))
1194
+ reasons.push("close_to_best");
1195
+ if ((context.candidate.robustness?.stability_score ?? 0) >= 0.8)
1196
+ reasons.push("stability");
1197
+ if ((context.candidate.near_miss?.weak_dimensions.length ?? context.candidate.robustness?.weak_dimensions.length ?? 0) > 0) {
1198
+ reasons.push("weak_dimension_improvement");
1199
+ }
1200
+ if (context.candidate.lineage.strategy_family !== rawBest.candidate.lineage.strategy_family
1201
+ && (scored?.diversity_score ?? inferredDiversityScore(context.candidate, rawBest.candidate.lineage.strategy_family, [context.candidate, rawBest.candidate])) >= 0.5) {
1202
+ reasons.push("novelty");
1203
+ }
1204
+ if (complementaryCandidateIds(context.candidate).length > 0 || highestKnownSimilarity(context.candidate, [context.candidate, rawBest.candidate]) <= 0.5) {
1205
+ reasons.push("complementarity");
1206
+ }
1207
+ const lineageText = [
1208
+ ...context.candidate.lineage.model_lineage,
1209
+ ...context.candidate.lineage.config_lineage,
1210
+ ...(context.candidate.near_miss?.summary ? [context.candidate.near_miss.summary] : []),
1211
+ ].map(normalizeLineageText).join(" ");
1212
+ if (lineageText.includes("stack") || lineageText.includes("ensemble") || lineageText.includes("blend")) {
1213
+ reasons.push("ensemble_potential");
1214
+ }
1215
+ return reasons;
1216
+ }
1217
+ function isImplicitNearMiss(context, rawBest, scored) {
1218
+ if (context.candidate.disposition !== "retained" && context.candidate.disposition !== "promoted")
1219
+ return false;
1220
+ const margin = candidateMetricMargin(context.metric, rawBest.metric);
1221
+ const close = margin !== null && isCloseToBestMargin(margin, rawBest.metric);
1222
+ const weakDimension = (context.candidate.robustness?.weak_dimensions.length ?? 0) > 0;
1223
+ const distinctFamily = context.candidate.lineage.strategy_family !== rawBest.candidate.lineage.strategy_family
1224
+ && (scored?.diversity_score ?? 0) >= 0.5;
1225
+ return close || weakDimension || distinctFamily;
1226
+ }
1227
+ function nearMissMarginContext(context, rawBest, nearMiss) {
1228
+ const margin = nearMiss?.margin_to_best ?? candidateMetricMargin(context.metric, rawBest.metric);
1229
+ return margin === null || margin === undefined ? {} : { margin_to_raw_best: Math.round(margin * 1_000_000) / 1_000_000 };
1230
+ }
1231
+ function candidateMetricMargin(candidateMetric, bestMetric) {
1232
+ if (!candidateMetric || !bestMetric || candidateMetric.direction !== bestMetric.direction)
1233
+ return null;
1234
+ const margin = candidateMetric.direction === "maximize"
1235
+ ? bestMetric.value - candidateMetric.value
1236
+ : candidateMetric.value - bestMetric.value;
1237
+ return Number.isFinite(margin) ? Math.max(0, margin) : null;
1238
+ }
1239
+ function isCloseToBestMargin(margin, bestMetric) {
1240
+ if (!bestMetric)
1241
+ return false;
1242
+ const tolerance = Math.max(Math.abs(bestMetric.value) * 0.005, 0.001);
1243
+ return margin <= tolerance;
1244
+ }
1245
+ function complementaryCandidateIds(candidate) {
1246
+ const explicit = candidate.near_miss?.complementary_candidate_ids ?? [];
1247
+ if (explicit.length > 0)
1248
+ return explicit;
1249
+ return candidate.similarity
1250
+ .filter((similarity) => similarity.signal === "metric_correlation" && similarity.similarity <= 0.5)
1251
+ .map((similarity) => similarity.candidate_id);
1252
+ }
1253
+ function nearMissReasonRank(reasons) {
1254
+ const weights = {
1255
+ weak_dimension_improvement: 5,
1256
+ novelty: 4,
1257
+ complementarity: 4,
1258
+ ensemble_potential: 3,
1259
+ stability: 2,
1260
+ close_to_best: 1,
1261
+ };
1262
+ return reasons.reduce((score, reason) => score + weights[reason], 0);
1263
+ }
1264
+ function summarizeCandidateLineages(entriesOldestFirst) {
1265
+ const primaryMetric = resolvePrimaryCandidateMetricKey(entriesOldestFirst);
1266
+ const byFamily = new Map();
1267
+ for (const context of extractCandidateEvidenceContexts(entriesOldestFirst, primaryMetric)) {
1268
+ const family = context.candidate.lineage.strategy_family;
1269
+ byFamily.set(family, [...(byFamily.get(family) ?? []), context]);
1270
+ }
1271
+ return [...byFamily.entries()]
1272
+ .map(([strategyFamily, contexts]) => {
1273
+ const sorted = [...contexts].sort(compareCandidateEvidenceContexts);
1274
+ const best = sorted[0];
1275
+ const diversityNotes = new Set();
1276
+ for (const context of contexts) {
1277
+ for (const similarity of context.candidate.similarity) {
1278
+ if (similarity.similarity >= 0.85) {
1279
+ diversityNotes.add(`${context.candidate.candidate_id} near-duplicate of ${similarity.candidate_id}`);
1280
+ }
1281
+ }
1282
+ }
1283
+ return {
1284
+ strategy_family: strategyFamily,
1285
+ candidate_ids: contexts.map((context) => context.candidate.candidate_id),
1286
+ retained_representative_ids: sorted
1287
+ .filter((context) => context.candidate.disposition === "retained" || context.candidate.disposition === "promoted")
1288
+ .map((context) => context.candidate.candidate_id)
1289
+ .slice(0, 3),
1290
+ promoted_ids: contexts
1291
+ .filter((context) => context.candidate.disposition === "promoted")
1292
+ .map((context) => context.candidate.candidate_id),
1293
+ retired_ids: contexts
1294
+ .filter((context) => context.candidate.disposition === "retired")
1295
+ .map((context) => context.candidate.candidate_id),
1296
+ ...(best ? { best_candidate_id: best.candidate.candidate_id } : {}),
1297
+ ...(best?.metric
1298
+ ? {
1299
+ best_metric: {
1300
+ label: best.metric.label,
1301
+ value: best.metric.value,
1302
+ direction: best.metric.direction,
1303
+ },
1304
+ }
1305
+ : {}),
1306
+ diversity_notes: [...diversityNotes].slice(0, 5),
1307
+ };
1308
+ })
1309
+ .sort((a, b) => {
1310
+ const aMetric = a.best_metric;
1311
+ const bMetric = b.best_metric;
1312
+ if (aMetric && bMetric && aMetric.direction === bMetric.direction) {
1313
+ const delta = aMetric.direction === "maximize" ? bMetric.value - aMetric.value : aMetric.value - bMetric.value;
1314
+ if (delta !== 0)
1315
+ return delta;
1316
+ }
1317
+ if (aMetric && !bMetric)
1318
+ return -1;
1319
+ if (!aMetric && bMetric)
1320
+ return 1;
1321
+ return a.strategy_family.localeCompare(b.strategy_family);
1322
+ });
1323
+ }
1324
+ function extractCandidateEvidenceContexts(entriesOldestFirst, primaryMetric) {
1325
+ const contexts = [];
1326
+ for (const entry of entriesOldestFirst) {
1327
+ for (const candidate of entry.candidates ?? []) {
1328
+ contexts.push({
1329
+ entry_id: entry.id,
1330
+ occurred_at: candidate.produced_at ?? entry.occurred_at,
1331
+ candidate,
1332
+ metric: candidateComparableMetric(candidate, primaryMetric),
1333
+ });
1334
+ }
1335
+ }
1336
+ return contexts;
1337
+ }
1338
+ function resolvePrimaryCandidateMetricKey(entriesOldestFirst) {
1339
+ const candidates = entriesOldestFirst.flatMap((entry) => entry.candidates ?? []);
1340
+ const byMetric = new Map();
1341
+ candidates.forEach((candidate, candidateIndex) => {
1342
+ const seenForCandidate = new Set();
1343
+ candidate.metrics.forEach((metric, metricIndex) => {
1344
+ if (typeof metric.value !== "number" || !Number.isFinite(metric.value))
1345
+ return;
1346
+ if (metric.direction !== "maximize" && metric.direction !== "minimize")
1347
+ return;
1348
+ const key = { label: metric.label, direction: metric.direction };
1349
+ const mapKey = `${key.label}:${key.direction}`;
1350
+ if (seenForCandidate.has(mapKey))
1351
+ return;
1352
+ seenForCandidate.add(mapKey);
1353
+ const existing = byMetric.get(mapKey);
1354
+ if (!existing) {
1355
+ byMetric.set(mapKey, {
1356
+ key,
1357
+ candidate_count: 1,
1358
+ position_sum: metricIndex,
1359
+ latest_index: candidateIndex,
1360
+ });
1361
+ return;
1362
+ }
1363
+ existing.candidate_count += 1;
1364
+ existing.position_sum += metricIndex;
1365
+ existing.latest_index = candidateIndex;
1366
+ });
1367
+ });
1368
+ return [...byMetric.values()].sort((a, b) => {
1369
+ const coverageDelta = b.candidate_count - a.candidate_count;
1370
+ if (coverageDelta !== 0)
1371
+ return coverageDelta;
1372
+ const localityDelta = Number(isLocalValidationMetricLabel(b.key.label)) - Number(isLocalValidationMetricLabel(a.key.label));
1373
+ if (localityDelta !== 0)
1374
+ return localityDelta;
1375
+ const positionDelta = a.position_sum / a.candidate_count - b.position_sum / b.candidate_count;
1376
+ if (positionDelta !== 0)
1377
+ return positionDelta;
1378
+ return b.latest_index - a.latest_index;
1379
+ })[0]?.key ?? null;
1380
+ }
1381
+ function isLocalValidationMetricLabel(label) {
1382
+ const normalized = normalizeLineageText(label);
1383
+ const externalHints = ["public", "private", "leaderboard", "external", "lb", "submission"];
1384
+ for (const hint of externalHints) {
1385
+ if (normalized === hint || normalized.includes(hint)) {
1386
+ return false;
1387
+ }
1388
+ }
1389
+ return true;
1390
+ }
1391
+ function candidateComparableMetric(candidate, primaryMetric) {
1392
+ for (const metric of candidate.metrics) {
1393
+ if (primaryMetric && (metric.label !== primaryMetric.label || metric.direction !== primaryMetric.direction))
1394
+ continue;
1395
+ if (typeof metric.value !== "number" || !Number.isFinite(metric.value))
1396
+ continue;
1397
+ if (metric.direction !== "maximize" && metric.direction !== "minimize")
1398
+ continue;
1399
+ return {
1400
+ label: metric.label,
1401
+ value: metric.value,
1402
+ direction: metric.direction,
1403
+ confidence: metric.confidence ?? 1,
1404
+ };
1405
+ }
1406
+ return null;
1407
+ }
1408
+ function compareCandidateEvidenceContexts(a, b) {
1409
+ const metricDelta = compareCandidateMetrics(a.metric, b.metric);
1410
+ if (metricDelta !== 0)
1411
+ return metricDelta;
1412
+ const dispositionDelta = dispositionRank(b.candidate.disposition) - dispositionRank(a.candidate.disposition);
1413
+ if (dispositionDelta !== 0)
1414
+ return dispositionDelta;
1415
+ const confidenceDelta = (b.metric?.confidence ?? 0) - (a.metric?.confidence ?? 0);
1416
+ if (confidenceDelta !== 0)
1417
+ return confidenceDelta;
1418
+ return b.occurred_at.localeCompare(a.occurred_at);
1419
+ }
1420
+ function compareCandidateMetrics(a, b) {
1421
+ if (a && b && a.direction === b.direction) {
1422
+ const valueDelta = a.direction === "maximize" ? b.value - a.value : a.value - b.value;
1423
+ if (valueDelta !== 0)
1424
+ return valueDelta;
1425
+ }
1426
+ if (a && !b)
1427
+ return -1;
1428
+ if (!a && b)
1429
+ return 1;
1430
+ return 0;
1431
+ }
1432
+ function dispositionRank(disposition) {
1433
+ if (disposition === "promoted")
1434
+ return 2;
1435
+ if (disposition === "retained")
1436
+ return 1;
1437
+ return 0;
1438
+ }
1439
+ function mostSimilarSelectedCandidate(candidate, selected) {
1440
+ let best;
1441
+ for (const selectedCandidate of selected) {
1442
+ const similarity = similarityBetweenCandidates(candidate.candidate, selectedCandidate.candidate);
1443
+ if (!similarity)
1444
+ continue;
1445
+ if (!best || similarity.similarity > best.similarity)
1446
+ best = similarity;
1447
+ }
1448
+ return best;
1449
+ }
1450
+ function similarityBetweenCandidates(candidate, selected) {
1451
+ const direct = candidate.similarity.find((similarity) => similarity.candidate_id === selected.candidate_id);
1452
+ const inverse = selected.similarity.find((similarity) => similarity.candidate_id === candidate.candidate_id);
1453
+ if (direct && inverse)
1454
+ return direct.similarity >= inverse.similarity ? direct : inverse;
1455
+ if (direct)
1456
+ return direct;
1457
+ if (inverse) {
1458
+ return {
1459
+ ...inverse,
1460
+ candidate_id: selected.candidate_id,
1461
+ };
1462
+ }
1463
+ if (candidate.lineage.strategy_family === selected.lineage.strategy_family
1464
+ && candidateLineageFingerprint(candidate) === candidateLineageFingerprint(selected)) {
1465
+ return {
1466
+ candidate_id: selected.candidate_id,
1467
+ similarity: 0.9,
1468
+ signal: "lineage",
1469
+ summary: "candidate shares strategy family and lineage fingerprint",
1470
+ };
1471
+ }
1472
+ return undefined;
1473
+ }
1474
+ function candidateLineageFingerprint(candidate) {
1475
+ const lineage = candidate.lineage;
1476
+ return [
1477
+ lineage.strategy_family,
1478
+ ...lineage.feature_lineage,
1479
+ ...lineage.model_lineage,
1480
+ ...lineage.config_lineage,
1481
+ ...lineage.postprocess_lineage,
1482
+ ].map(normalizeLineageText).filter(Boolean).join("|");
1483
+ }
1484
+ function toPortfolioSlot(context) {
1485
+ const candidate = context.candidate;
1486
+ return {
1487
+ candidate_id: candidate.candidate_id,
1488
+ ...(candidate.label ? { label: candidate.label } : {}),
1489
+ strategy_family: candidate.lineage.strategy_family,
1490
+ role: context.role,
1491
+ evidence_entry_id: context.entry_id,
1492
+ occurred_at: context.occurred_at,
1493
+ ...(context.metric ? { metric: context.metric } : {}),
1494
+ ...(candidate.lineage.parent_candidate_id ? { parent_candidate_id: candidate.lineage.parent_candidate_id } : {}),
1495
+ ...(candidate.lineage.source_candidate_id ? { source_candidate_id: candidate.lineage.source_candidate_id } : {}),
1496
+ ...(candidate.lineage.source_strategy_id ? { source_strategy_id: candidate.lineage.source_strategy_id } : {}),
1497
+ disposition: candidate.disposition,
1498
+ ...(candidate.disposition_reason ? { retained_reason: candidate.disposition_reason } : {}),
1499
+ ...(context.similarity_to_selected ? { similarity_to_selected: context.similarity_to_selected } : {}),
1500
+ };
1501
+ }
1502
+ function summarizeFailedLineages(entriesOldestFirst) {
1503
+ const lineages = new Map();
1504
+ for (const entry of entriesOldestFirst) {
1505
+ if (!isFailedEvidenceEntry(entry))
1506
+ continue;
1507
+ const fingerprintInput = failedLineageFingerprintInput(entry);
1508
+ const normalizedIdentityParts = [
1509
+ normalizeLineageText(fingerprintInput.strategy_family),
1510
+ normalizeLineageText(fingerprintInput.hypothesis),
1511
+ normalizeLineageText(fingerprintInput.primary_dimension),
1512
+ normalizeLineageText(fingerprintInput.task_action),
1513
+ ].filter(Boolean);
1514
+ const normalizedFallbackParts = [normalizeLineageText(fingerprintInput.failure_reason)].filter(Boolean);
1515
+ const fingerprintParts = normalizedIdentityParts.length > 0 ? normalizedIdentityParts : normalizedFallbackParts;
1516
+ if (fingerprintParts.length === 0)
1517
+ continue;
1518
+ const fingerprint = fingerprintParts.join("|");
1519
+ const summary = entry.summary
1520
+ ?? entry.result?.summary
1521
+ ?? entry.verification?.summary
1522
+ ?? entry.result?.error
1523
+ ?? `${entry.kind} failed`;
1524
+ const existing = lineages.get(fingerprint);
1525
+ if (!existing) {
1526
+ lineages.set(fingerprint, {
1527
+ fingerprint,
1528
+ count: 1,
1529
+ first_seen_at: entry.occurred_at,
1530
+ last_seen_at: entry.occurred_at,
1531
+ ...(fingerprintInput.strategy_family ? { strategy_family: fingerprintInput.strategy_family } : {}),
1532
+ ...(fingerprintInput.hypothesis ? { hypothesis: fingerprintInput.hypothesis } : {}),
1533
+ ...(fingerprintInput.primary_dimension ? { primary_dimension: fingerprintInput.primary_dimension } : {}),
1534
+ ...(fingerprintInput.task_action ? { task_action: fingerprintInput.task_action } : {}),
1535
+ ...(fingerprintInput.failure_reason ? { failure_reason: fingerprintInput.failure_reason } : {}),
1536
+ representative_entry_id: entry.id,
1537
+ representative_summary: summary,
1538
+ evidence_entry_ids: [entry.id],
1539
+ });
1540
+ continue;
1541
+ }
1542
+ existing.count += 1;
1543
+ existing.last_seen_at = entry.occurred_at;
1544
+ existing.representative_entry_id = entry.id;
1545
+ existing.representative_summary = summary;
1546
+ existing.evidence_entry_ids = [...existing.evidence_entry_ids, entry.id].slice(-5);
1547
+ }
1548
+ return [...lineages.values()]
1549
+ .sort((a, b) => b.count - a.count || b.last_seen_at.localeCompare(a.last_seen_at))
1550
+ .slice(0, 10);
1551
+ }
1552
+ function isFailedEvidenceEntry(entry) {
1553
+ return entry.outcome === "failed"
1554
+ || entry.outcome === "regressed"
1555
+ || entry.kind === "failure"
1556
+ || entry.result?.status === "failed"
1557
+ || entry.verification?.verdict === "fail";
1558
+ }
1559
+ function failedLineageFingerprintInput(entry) {
1560
+ const strategyFamily = entry.strategy ?? entry.task?.action;
1561
+ return {
1562
+ ...(strategyFamily ? { strategy_family: strategyFamily } : {}),
1563
+ ...(entry.hypothesis ? { hypothesis: entry.hypothesis } : {}),
1564
+ ...(entry.task?.primary_dimension ? { primary_dimension: entry.task.primary_dimension } : {}),
1565
+ ...(entry.task?.action ? { task_action: entry.task.action } : {}),
1566
+ ...(entry.result?.error || entry.result?.summary || entry.verification?.summary
1567
+ ? { failure_reason: entry.result?.error ?? entry.result?.summary ?? entry.verification?.summary }
1568
+ : {}),
1569
+ };
1570
+ }
1571
+ function normalizeLineageText(value) {
1572
+ return value?.normalize("NFKC").toLocaleLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu, " ").trim() ?? "";
1573
+ }
1574
+ function clamp01(value) {
1575
+ if (!Number.isFinite(value))
1576
+ return 0;
1577
+ return Math.min(1, Math.max(0, value));
1578
+ }
1579
+ function roundScore(value) {
1580
+ return Math.round(value * 1_000_000) / 1_000_000;
1581
+ }
1582
+ function chooseBestEvidence(entriesNewestFirst) {
1583
+ const metricBest = chooseBestMetricEvidence(entriesNewestFirst);
1584
+ if (metricBest)
1585
+ return metricBest;
1586
+ return chooseBestFallbackEvidence(entriesNewestFirst);
1587
+ }
1588
+ function chooseBestFallbackEvidence(entriesNewestFirst) {
1589
+ return entriesNewestFirst.find((entry) => entry.outcome === "improved")
1590
+ ?? entriesNewestFirst.find((entry) => entry.verification?.verdict === "pass")
1591
+ ?? entriesNewestFirst.find((entry) => entry.metrics.length > 0)
1592
+ ?? entriesNewestFirst.find((entry) => entry.kind === "artifact")
1593
+ ?? null;
1594
+ }
1595
+ function chooseBestMetricEvidence(entriesNewestFirst) {
1596
+ const primaryMetric = resolvePrimaryMetricKey(entriesNewestFirst);
1597
+ if (!primaryMetric)
1598
+ return null;
1599
+ const oldestFirst = [...entriesNewestFirst].reverse();
1600
+ const baseline = findComparableMetric(oldestFirst, primaryMetric)?.value;
1601
+ const candidates = entriesNewestFirst
1602
+ .map((entry) => {
1603
+ const metric = findComparableMetric([entry], primaryMetric);
1604
+ if (!metric)
1605
+ return null;
1606
+ return {
1607
+ entry,
1608
+ metric: metric.metric,
1609
+ value: metric.value,
1610
+ direction: metric.direction,
1611
+ primary_metric: primaryMetric,
1612
+ improvement_strength: baseline === undefined
1613
+ ? 0
1614
+ : metric.direction === "maximize"
1615
+ ? metric.value - baseline
1616
+ : baseline - metric.value,
1617
+ confidence: metric.metric.confidence ?? entry.verification?.confidence ?? 1,
1618
+ has_pass_verification: entry.verification?.verdict === "pass",
1619
+ has_artifact: entry.artifacts.length > 0 || entry.kind === "artifact",
1620
+ };
1621
+ })
1622
+ .filter((candidate) => Boolean(candidate));
1623
+ if (candidates.length === 0)
1624
+ return null;
1625
+ return candidates.sort(compareComparableEvidenceMetrics)[0]?.entry ?? null;
1626
+ }
1627
+ function resolvePrimaryMetricKey(entriesNewestFirst) {
1628
+ const oldestFirst = [...entriesNewestFirst].reverse();
1629
+ const byMetric = new Map();
1630
+ oldestFirst.forEach((entry, entryIndex) => {
1631
+ const seenForEntry = new Set();
1632
+ entry.metrics.forEach((metric, metricIndex) => {
1633
+ const comparable = toComparableMetric(metric);
1634
+ if (!comparable)
1635
+ return;
1636
+ const key = { label: metric.label, direction: comparable.direction };
1637
+ const mapKey = `${key.label}:${key.direction}`;
1638
+ if (seenForEntry.has(mapKey))
1639
+ return;
1640
+ seenForEntry.add(mapKey);
1641
+ const existing = byMetric.get(mapKey);
1642
+ const explicitPrimary = entry.task?.primary_dimension === metric.label ? 1 : 0;
1643
+ if (!existing) {
1644
+ byMetric.set(mapKey, {
1645
+ key,
1646
+ entry_count: 1,
1647
+ explicit_primary_count: explicitPrimary,
1648
+ position_sum: metricIndex,
1649
+ latest_index: entryIndex,
1650
+ });
1651
+ return;
1652
+ }
1653
+ existing.entry_count += 1;
1654
+ existing.explicit_primary_count += explicitPrimary;
1655
+ existing.position_sum += metricIndex;
1656
+ existing.latest_index = entryIndex;
1657
+ });
1658
+ });
1659
+ // Primary evidence metric inference is intentionally structural: exact
1660
+ // task.primary_dimension matches win, then broadest repeated metric coverage,
1661
+ // then stable first-position metric ordering, then recency as the final tie.
1662
+ return [...byMetric.values()].sort((a, b) => {
1663
+ const explicitDelta = b.explicit_primary_count - a.explicit_primary_count;
1664
+ if (explicitDelta !== 0)
1665
+ return explicitDelta;
1666
+ const coverageDelta = b.entry_count - a.entry_count;
1667
+ if (coverageDelta !== 0)
1668
+ return coverageDelta;
1669
+ const positionDelta = a.position_sum / a.entry_count - b.position_sum / b.entry_count;
1670
+ if (positionDelta !== 0)
1671
+ return positionDelta;
1672
+ return b.latest_index - a.latest_index;
1673
+ })[0]?.key ?? null;
1674
+ }
1675
+ function findComparableMetric(entries, key) {
1676
+ for (const entry of entries) {
1677
+ for (const metric of entry.metrics) {
1678
+ if (metric.label !== key.label || metric.direction !== key.direction)
1679
+ continue;
1680
+ const comparable = toComparableMetric(metric);
1681
+ if (comparable)
1682
+ return comparable;
1683
+ }
1684
+ }
1685
+ return null;
1686
+ }
1687
+ function toComparableMetric(metric) {
1688
+ if (typeof metric.value !== "number" || !Number.isFinite(metric.value))
1689
+ return null;
1690
+ if (metric.direction !== "maximize" && metric.direction !== "minimize")
1691
+ return null;
1692
+ return {
1693
+ metric,
1694
+ value: metric.value,
1695
+ direction: metric.direction,
1696
+ };
1697
+ }
1698
+ function compareComparableEvidenceMetrics(a, b) {
1699
+ const direction = a.direction;
1700
+ const valueDelta = direction === "maximize" ? b.value - a.value : a.value - b.value;
1701
+ if (valueDelta !== 0)
1702
+ return valueDelta;
1703
+ const passDelta = Number(b.has_pass_verification) - Number(a.has_pass_verification);
1704
+ if (passDelta !== 0)
1705
+ return passDelta;
1706
+ const artifactDelta = Number(b.has_artifact) - Number(a.has_artifact);
1707
+ if (artifactDelta !== 0)
1708
+ return artifactDelta;
1709
+ const confidenceDelta = b.confidence - a.confidence;
1710
+ if (confidenceDelta !== 0)
1711
+ return confidenceDelta;
1712
+ const improvementDelta = b.improvement_strength - a.improvement_strength;
1713
+ if (improvementDelta !== 0)
1714
+ return improvementDelta;
1715
+ return b.entry.occurred_at.localeCompare(a.entry.occurred_at);
1716
+ }
1717
+ //# sourceMappingURL=evidence-ledger.js.map