2sagaco48 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/diagnostics.mjs +141 -0
  2. package/dist/compute.worker-j5ahIpF-.js +1 -0
  3. package/dist/graph.worker-DG6iGCB9.js +1 -0
  4. package/dist/index.html +2314 -0
  5. package/flatten-guide.md +248 -0
  6. package/index.html +12 -0
  7. package/package.json +38 -0
  8. package/src/App.orig.tsx +204 -0
  9. package/src/App.orig1.tsx +27 -0
  10. package/src/App.orig2.tsx +25 -0
  11. package/src/App.tsx +3 -0
  12. package/src/BaseApp.tsx +18 -0
  13. package/src/INTEGRATION_LEDGER.md +22 -0
  14. package/src/PERSIST_CANARY.orig.txt +1 -0
  15. package/src/PERSIST_CANARY.txt +1 -0
  16. package/src/REGRESSION_LEDGER.md +651 -0
  17. package/src/TEMPLATE_PIPELINE_AUDIT.md +208 -0
  18. package/src/WILLIAMS_PERSONA_GUIDE.md +62 -0
  19. package/src/chat/VeritasChat.tsx +69 -0
  20. package/src/chat/synthesis.ts +31 -0
  21. package/src/chat/tier.ts +45 -0
  22. package/src/components/AdaptersPage.orig.tsx +99 -0
  23. package/src/components/AdaptersPage.tsx +3 -0
  24. package/src/components/AdversarialPanel.tsx +136 -0
  25. package/src/components/AnchorBaselinePanel.tsx +75 -0
  26. package/src/components/AnswerPanel.tsx +60 -0
  27. package/src/components/ArtifactPanel.tsx +43 -0
  28. package/src/components/ChatApp.orig.tsx +1582 -0
  29. package/src/components/ChatApp.orig1.tsx +722 -0
  30. package/src/components/ChatApp.tsx +95 -0
  31. package/src/components/ChatAugmentPanels.tsx +73 -0
  32. package/src/components/CitationLedgerPanel.tsx +313 -0
  33. package/src/components/ComputeSandboxPanel.tsx +130 -0
  34. package/src/components/ConfigPanel.tsx +110 -0
  35. package/src/components/ControlPlanePage.tsx +195 -0
  36. package/src/components/CreativeTreeLifePage.tsx +234 -0
  37. package/src/components/CreativeTreeOfLifePanel.tsx +149 -0
  38. package/src/components/DebugTracePanel.tsx +137 -0
  39. package/src/components/DeepReasoningTrace.tsx +48 -0
  40. package/src/components/EntitySheetPanel.tsx +51 -0
  41. package/src/components/FailureModesPanel.tsx +104 -0
  42. package/src/components/GBSDashboard.tsx +239 -0
  43. package/src/components/GraphView.tsx +116 -0
  44. package/src/components/HUD.tsx +125 -0
  45. package/src/components/HypothesisPanel.tsx +67 -0
  46. package/src/components/InnovationGenomeEngine.tsx +792 -0
  47. package/src/components/InnovationPersonaGuide.tsx +348 -0
  48. package/src/components/InnovationPersonaPanel.tsx +289 -0
  49. package/src/components/LiveResourceHUD.tsx +109 -0
  50. package/src/components/LongWriterPanel.tsx +112 -0
  51. package/src/components/MainPipelineV10Bridge.tsx +72 -0
  52. package/src/components/MarkdownLite.tsx +63 -0
  53. package/src/components/MemoryInspector.tsx +38 -0
  54. package/src/components/MemoryMonitor.tsx +52 -0
  55. package/src/components/MemoryStressPanel.tsx +176 -0
  56. package/src/components/ModulesPage.tsx +171 -0
  57. package/src/components/PipelineDebugConsole.orig.tsx +1856 -0
  58. package/src/components/PipelineDebugConsole.tsx +3 -0
  59. package/src/components/PreFlightHUD.tsx +67 -0
  60. package/src/components/PrismaFetchTracePanel.tsx +87 -0
  61. package/src/components/ReportOSPanel.tsx +165 -0
  62. package/src/components/ResourceEstimatorPage.tsx +327 -0
  63. package/src/components/RichText.tsx +181 -0
  64. package/src/components/SagaOsPanel.tsx +605 -0
  65. package/src/components/SagaOsReference.tsx +421 -0
  66. package/src/components/SagaOsV2Panel.tsx +594 -0
  67. package/src/components/SagaStyleTab.tsx +382 -0
  68. package/src/components/SageBlueprintPanel.tsx +416 -0
  69. package/src/components/SharedChatInput.tsx +77 -0
  70. package/src/components/StatFinancePanel.tsx +190 -0
  71. package/src/components/StylePersonaPanel.tsx +128 -0
  72. package/src/components/TemplatesPage.tsx +300 -0
  73. package/src/components/TestPanel.tsx +63 -0
  74. package/src/components/TraceLog.tsx +89 -0
  75. package/src/components/V15CalibrationAugment.tsx +1134 -0
  76. package/src/components/V15CalibrationDialog.tsx +1871 -0
  77. package/src/components/V15Overlay.orig.tsx +120 -0
  78. package/src/components/V15Overlay.tsx +4 -0
  79. package/src/components/V15OverlayWrapper.tsx +362 -0
  80. package/src/components/V15Toggle.tsx +34 -0
  81. package/src/console/DiagnosticRecoveryPanel.tsx +358 -0
  82. package/src/console/EngineeringConsole.tsx +103 -0
  83. package/src/console/FictionSystemPanels.tsx +882 -0
  84. package/src/console/InspectorPanels.tsx +254 -0
  85. package/src/console/ManuscriptGraderPanel.tsx +182 -0
  86. package/src/console/RecursiveReviserPanel.tsx +245 -0
  87. package/src/console/SeedControlPanel.tsx +135 -0
  88. package/src/console/StoryControllerPanel.tsx +443 -0
  89. package/src/console/engineBridge.ts +258 -0
  90. package/src/console/gemini.ts +106 -0
  91. package/src/console/grading.ts +250 -0
  92. package/src/console/util.ts +45 -0
  93. package/src/fiction/continuity.ts +372 -0
  94. package/src/fiction/crash-protection.ts +111 -0
  95. package/src/fiction/diagnostics.ts +208 -0
  96. package/src/fiction/diff.ts +74 -0
  97. package/src/fiction/entity-state-machine.ts +214 -0
  98. package/src/fiction/nive-engine.ts +404 -0
  99. package/src/fiction/pipeline-selftest.ts +132 -0
  100. package/src/fiction/seed-control.ts +193 -0
  101. package/src/fiction/story-engine.ts +326 -0
  102. package/src/fiction/types.ts +68 -0
  103. package/src/flatten-guide.md +379 -0
  104. package/src/index.css +14 -0
  105. package/src/index.orig.css +13 -0
  106. package/src/lib/academic-sources.base.ts +188 -0
  107. package/src/lib/academic-sources.orig.ts +28 -0
  108. package/src/lib/academic-sources.ts +10 -0
  109. package/src/lib/advanced-math.ts +119 -0
  110. package/src/lib/adversarial-engine.base.ts +409 -0
  111. package/src/lib/adversarial-engine.ts +82 -0
  112. package/src/lib/ai-revision.ts +623 -0
  113. package/src/lib/app-state.tsx +426 -0
  114. package/src/lib/artifact-registry.ts +97 -0
  115. package/src/lib/artifacts.ts +180 -0
  116. package/src/lib/atlas-dr.ts +167 -0
  117. package/src/lib/browser-mtls.ts +127 -0
  118. package/src/lib/browser-queue.ts +221 -0
  119. package/src/lib/browser-search-scraper.base.ts +382 -0
  120. package/src/lib/browser-search-scraper.orig.ts +90 -0
  121. package/src/lib/browser-search-scraper.ts +10 -0
  122. package/src/lib/calc-interceptor.ts +82 -0
  123. package/src/lib/citation-lane-tap.ts +78 -0
  124. package/src/lib/citation-ledger-store.ts +369 -0
  125. package/src/lib/citation-ledger.ts +203 -0
  126. package/src/lib/compute-sandbox.ts +215 -0
  127. package/src/lib/compute.worker.ts +153 -0
  128. package/src/lib/connectors/gemini.ts +120 -0
  129. package/src/lib/connectors/jina.ts +233 -0
  130. package/src/lib/connectors/marketdata.ts +51 -0
  131. package/src/lib/connectors/prismafetch.base.ts +175 -0
  132. package/src/lib/connectors/prismafetch.ts +1 -0
  133. package/src/lib/connectors/serpapi.ts +65 -0
  134. package/src/lib/connectors/wikidata.ts +44 -0
  135. package/src/lib/constraints.ts +331 -0
  136. package/src/lib/continuation-detector.base.ts +153 -0
  137. package/src/lib/continuation-detector.ts +48 -0
  138. package/src/lib/contradraft.ts +168 -0
  139. package/src/lib/cors-proxy.ts +120 -0
  140. package/src/lib/coverage.ts +81 -0
  141. package/src/lib/debug/architecture-prescription.ts +556 -0
  142. package/src/lib/debug/covea-repair.ts +543 -0
  143. package/src/lib/debug/helios-ground.ts +319 -0
  144. package/src/lib/debug/intent-decomposer.ts +281 -0
  145. package/src/lib/debug/intent-lattice.ts +349 -0
  146. package/src/lib/debug/pipeline-diagnosis.ts +1149 -0
  147. package/src/lib/debug/pipeline-trace-bus.ts +424 -0
  148. package/src/lib/debug/prompt-forge.ts +678 -0
  149. package/src/lib/debug/repair-sites.ts +513 -0
  150. package/src/lib/debug/research-phase.ts +266 -0
  151. package/src/lib/debug/retrieval-context.ts +76 -0
  152. package/src/lib/debug/retrieval-hardener.ts +142 -0
  153. package/src/lib/debug/scraper-debug-runner.ts +576 -0
  154. package/src/lib/debug/scraper-forensics.ts +418 -0
  155. package/src/lib/debug/scraper-lane-roadmap.ts +136 -0
  156. package/src/lib/debug/self-test.ts +415 -0
  157. package/src/lib/debug/step-attribution.ts +211 -0
  158. package/src/lib/debug/template-rubric.ts +301 -0
  159. package/src/lib/debug/unified-innovation.ts +126 -0
  160. package/src/lib/debug/veritas-hybrid-scraper.ts +335 -0
  161. package/src/lib/defense-registry.ts +104 -0
  162. package/src/lib/defenses.ts +162 -0
  163. package/src/lib/deterministic-citation-ledger.ts +174 -0
  164. package/src/lib/elo-registry.base.ts +117 -0
  165. package/src/lib/elo-registry.ts +1 -0
  166. package/src/lib/entity-resolver.ts +291 -0
  167. package/src/lib/failure-modes.ts +267 -0
  168. package/src/lib/feature-registry.ts +69 -0
  169. package/src/lib/flaw-registry.ts +143 -0
  170. package/src/lib/flaws/_template.ts +52 -0
  171. package/src/lib/flaws/builtins.ts +63 -0
  172. package/src/lib/flaws/finance.ts +169 -0
  173. package/src/lib/flaws/fixers.ts +10 -0
  174. package/src/lib/flaws/index.ts +32 -0
  175. package/src/lib/flaws/legal.ts +157 -0
  176. package/src/lib/flaws/medical.ts +188 -0
  177. package/src/lib/flaws/original-defenses-pack.ts +81 -0
  178. package/src/lib/flaws/sample-declarative-pack.json +38 -0
  179. package/src/lib/flaws/selftest.ts +201 -0
  180. package/src/lib/flaws/software-extended.ts +125 -0
  181. package/src/lib/flaws/software-rn-webgl.ts +182 -0
  182. package/src/lib/flaws/statistics-advanced.ts +46 -0
  183. package/src/lib/flaws/statistics.ts +61 -0
  184. package/src/lib/gbse/config.ts +20 -0
  185. package/src/lib/gbse/engine.ts +226 -0
  186. package/src/lib/gbse/graph.ts +118 -0
  187. package/src/lib/gbse/graph.worker.ts +21 -0
  188. package/src/lib/gbse/tests.ts +117 -0
  189. package/src/lib/gbse/tiers.ts +65 -0
  190. package/src/lib/gbse/types.ts +94 -0
  191. package/src/lib/innovation-genome-engine-v2.orig.ts +1001 -0
  192. package/src/lib/innovation-genome-engine-v2.ts +3 -0
  193. package/src/lib/innovation-genome-engine.orig.ts +330 -0
  194. package/src/lib/innovation-genome-engine.ts +3 -0
  195. package/src/lib/innovation-genome-v10.orig.ts +314 -0
  196. package/src/lib/innovation-genome-v10.ts +2 -0
  197. package/src/lib/innovation-genome-v3.orig.ts +2015 -0
  198. package/src/lib/innovation-genome-v3.ts +2 -0
  199. package/src/lib/innovation-genome-v4.orig.ts +1959 -0
  200. package/src/lib/innovation-genome-v4.ts +2 -0
  201. package/src/lib/innovation-genome-v5.orig.ts +1210 -0
  202. package/src/lib/innovation-genome-v5.ts +2 -0
  203. package/src/lib/innovation-genome-v7.orig.ts +2549 -0
  204. package/src/lib/innovation-genome-v7.ts +2 -0
  205. package/src/lib/innovation-genome-v8.orig.ts +1485 -0
  206. package/src/lib/innovation-genome-v8.ts +2 -0
  207. package/src/lib/innovation-genome-v9.orig.ts +643 -0
  208. package/src/lib/innovation-genome-v9.ts +2 -0
  209. package/src/lib/jina.base.ts +293 -0
  210. package/src/lib/jina.ts +1 -0
  211. package/src/lib/live-telemetry.ts +61 -0
  212. package/src/lib/longwriter.ts +84 -0
  213. package/src/lib/manuscript-grade-v2.ts +298 -0
  214. package/src/lib/memory-governor.ts +173 -0
  215. package/src/lib/memory-stress-tests.ts +248 -0
  216. package/src/lib/model-intelligence.ts +48 -0
  217. package/src/lib/model-rotator.ts +75 -0
  218. package/src/lib/models.orig.ts +513 -0
  219. package/src/lib/models.ts +151 -0
  220. package/src/lib/n-deep.base.ts +592 -0
  221. package/src/lib/n-deep.ts +51 -0
  222. package/src/lib/nih-simulator.ts +56 -0
  223. package/src/lib/nih-vulnerability-fixes.ts +460 -0
  224. package/src/lib/omega-templates.base.ts +294 -0
  225. package/src/lib/omega-templates.ts +225 -0
  226. package/src/lib/omni-nexus.ts +64 -0
  227. package/src/lib/oracle-adapters.ts +67 -0
  228. package/src/lib/oracle-registry.ts +163 -0
  229. package/src/lib/orchestrator.ts +357 -0
  230. package/src/lib/output-boundary.ts +235 -0
  231. package/src/lib/overrides/vite-native-chaos-harness.ts +154 -0
  232. package/src/lib/overrides/vite-native-contract-plane.ts +245 -0
  233. package/src/lib/overrides/vite-native-doctor-plane.ts +208 -0
  234. package/src/lib/overrides/vite-native-knowledge-store.ts +267 -0
  235. package/src/lib/overrides/vite-native-policy-plane.ts +190 -0
  236. package/src/lib/overrides/vite-native-replay-plane.ts +197 -0
  237. package/src/lib/overrides/vite-native-runtime-plane.ts +106 -0
  238. package/src/lib/overrides/vite-native-scraper.ts +848 -0
  239. package/src/lib/overrides/vite-native-selftest-functional.ts +217 -0
  240. package/src/lib/overrides/vite-native-selftest.ts +183 -0
  241. package/src/lib/overrides/vite-native-snapshot-plane.ts +123 -0
  242. package/src/lib/philosophy-toolkit.ts +75 -0
  243. package/src/lib/pipeline.orig.ts +659 -0
  244. package/src/lib/pipeline.ts +42 -0
  245. package/src/lib/precache.ts +128 -0
  246. package/src/lib/py-sandbox.ts +205 -0
  247. package/src/lib/quality-score.ts +96 -0
  248. package/src/lib/quant-engine.ts +231 -0
  249. package/src/lib/quant-lib.ts +80 -0
  250. package/src/lib/reportos.ts +175 -0
  251. package/src/lib/research-os.ts +306 -0
  252. package/src/lib/resource-estimator.ts +114 -0
  253. package/src/lib/rpm-governor.ts +93 -0
  254. package/src/lib/runtime-estimator.ts +135 -0
  255. package/src/lib/sage/empty-space-v6.ts +560 -0
  256. package/src/lib/sage/empty-space-v7.ts +222 -0
  257. package/src/lib/sage/empty-space.ts +733 -0
  258. package/src/lib/sage/engine.ts +786 -0
  259. package/src/lib/sage/index.ts +17 -0
  260. package/src/lib/sage/judge.ts +246 -0
  261. package/src/lib/sage/prng.ts +53 -0
  262. package/src/lib/sage/reality-grounding.ts +380 -0
  263. package/src/lib/sage/repetition.ts +151 -0
  264. package/src/lib/sage/saga-os-v2-engines.ts +1870 -0
  265. package/src/lib/sage/saga-os-v2.ts +274 -0
  266. package/src/lib/sage/saga-os-v3-core.ts +1491 -0
  267. package/src/lib/sage/saga-os-v3-release.ts +739 -0
  268. package/src/lib/sage/saga-os-v4-aureate.ts +1161 -0
  269. package/src/lib/sage/saga-os-v4.ts +212 -0
  270. package/src/lib/sage/saga-os-v5.ts +205 -0
  271. package/src/lib/sage/saga-os-v6.ts +346 -0
  272. package/src/lib/sage/saga-os-v7.ts +314 -0
  273. package/src/lib/sage/saga-os-v8.ts +505 -0
  274. package/src/lib/sage/saga-os.ts +329 -0
  275. package/src/lib/sage/taxonomy.ts +403 -0
  276. package/src/lib/sage/unified-roll.ts +524 -0
  277. package/src/lib/sage/worked-sketches.ts +44 -0
  278. package/src/lib/sage.ts +166 -0
  279. package/src/lib/scraper-debug-bus.ts +53 -0
  280. package/src/lib/scraper-enhanced.orig.ts +153 -0
  281. package/src/lib/scraper-enhanced.ts +10 -0
  282. package/src/lib/scraper-hardener.base.orig.ts +155 -0
  283. package/src/lib/scraper-hardener.base.ts +317 -0
  284. package/src/lib/scraper-hardener.ts +1 -0
  285. package/src/lib/scraper-palisade/palisade-adjudicator.orig.ts +419 -0
  286. package/src/lib/scraper-palisade/palisade-adjudicator.ts +13 -0
  287. package/src/lib/scraper-vnext/arbiter-omega.orig.ts +688 -0
  288. package/src/lib/scraper-vnext/arbiter-omega.ts +13 -0
  289. package/src/lib/scraper-vnext/canonical-portfolio-augments.ts +479 -0
  290. package/src/lib/scraper-vnext/canonical-portfolio-orchestrator.orig.ts +1529 -0
  291. package/src/lib/scraper-vnext/canonical-portfolio-orchestrator.ts +13 -0
  292. package/src/lib/scraper-vnext/conclave-omega.ts +1830 -0
  293. package/src/lib/scraper-vnext/content-extractor-v2.ts +226 -0
  294. package/src/lib/scraper-vnext/diagnostics-suite.ts +36 -0
  295. package/src/lib/scraper-vnext/epistemic-packer.ts +97 -0
  296. package/src/lib/scraper-vnext/fusion-v2.ts +65 -0
  297. package/src/lib/scraper-vnext/hydra-reader.orig.ts +1216 -0
  298. package/src/lib/scraper-vnext/hydra-reader.ts +13 -0
  299. package/src/lib/scraper-vnext/native-scraper-browser-vnext.orig.ts +91 -0
  300. package/src/lib/scraper-vnext/native-scraper-browser-vnext.ts +13 -0
  301. package/src/lib/scraper-vnext/nexus-consensus.orig.ts +905 -0
  302. package/src/lib/scraper-vnext/nexus-consensus.ts +13 -0
  303. package/src/lib/scraper-vnext/portfolio-consensus-adjudicator.ts +804 -0
  304. package/src/lib/scraper-vnext/portfolio-consensus-memory.ts +377 -0
  305. package/src/lib/scraper-vnext/portfolio-terminal-governor.ts +548 -0
  306. package/src/lib/scraper-vnext/query-strategist.orig.ts +224 -0
  307. package/src/lib/scraper-vnext/query-strategist.ts +423 -0
  308. package/src/lib/scraper-vnext/retrieval-accelerator.ts +708 -0
  309. package/src/lib/scraper-vnext/retrieval-audit-augments.ts +477 -0
  310. package/src/lib/scraper-vnext/retrieval-control-plane.ts +904 -0
  311. package/src/lib/scraper-vnext/retrieval-policy-augments.ts +358 -0
  312. package/src/lib/scraper-vnext/safe-fetch-v2.ts +157 -0
  313. package/src/lib/scraper-vnext/sentinel-omega.ts +56 -0
  314. package/src/lib/scraper-vnext/sentinel-orchestrator.ts +69 -0
  315. package/src/lib/scraper-vnext/sibyl-oracle.orig.ts +413 -0
  316. package/src/lib/scraper-vnext/sibyl-oracle.ts +13 -0
  317. package/src/lib/scraper-vnext/smart-read-v2.ts +55 -0
  318. package/src/lib/scraper-vnext/spa-rescue-bridge.ts +608 -0
  319. package/src/lib/scraper-vnext/strata-engine.orig.ts +2666 -0
  320. package/src/lib/scraper-vnext/strata-engine.ts +13 -0
  321. package/src/lib/scraper-vnext/structured-source-adapter.orig.ts +369 -0
  322. package/src/lib/scraper-vnext/structured-source-adapter.ts +34 -0
  323. package/src/lib/scraper-vnext/terminal-complete.ts +224 -0
  324. package/src/lib/scraper-vnext/terminal-final.ts +277 -0
  325. package/src/lib/scraper-vnext/terminal-saturation.ts +345 -0
  326. package/src/lib/scraper-vnext/terminal-wire.ts +425 -0
  327. package/src/lib/scraper-vnext/vanguard-titanium.orig.ts +467 -0
  328. package/src/lib/scraper-vnext/vanguard-titanium.ts +17 -0
  329. package/src/lib/search-cache.ts +138 -0
  330. package/src/lib/sloop-runner.base.ts +223 -0
  331. package/src/lib/sloop-runner.ts +104 -0
  332. package/src/lib/sloop.ts +114 -0
  333. package/src/lib/small-model-adapters.ts +82 -0
  334. package/src/lib/sscp.ts +86 -0
  335. package/src/lib/system-map.ts +54 -0
  336. package/src/lib/uni-node.ts +86 -0
  337. package/src/lib/universal-rigor-guard.ts +433 -0
  338. package/src/lib/v15-gate-testbed.ts +274 -0
  339. package/src/lib/v15-gemini.base.ts +89 -0
  340. package/src/lib/v15-gemini.ts +1 -0
  341. package/src/lib/v15-grounding.orig.ts +241 -0
  342. package/src/lib/v15-grounding.ts +79 -0
  343. package/src/lib/v15-pipeline.base.ts +769 -0
  344. package/src/lib/v15-pipeline.orig.ts +1154 -0
  345. package/src/lib/v15-pipeline.ts +674 -0
  346. package/src/lib/v15-questions.ts +64 -0
  347. package/src/lib/v15-rate-limiter.orig.ts +91 -0
  348. package/src/lib/v15-rate-limiter.ts +48 -0
  349. package/src/lib/v15-state.base.ts +87 -0
  350. package/src/lib/v15-state.ts +28 -0
  351. package/src/lib/visual-table-generator.tsx +207 -0
  352. package/src/lib/wasm-runtime.ts +133 -0
  353. package/src/lib/williams-persona-guide.ts +265 -0
  354. package/src/lib/williams-style.base.ts +464 -0
  355. package/src/lib/williams-style.ts +59 -0
  356. package/src/lib/worker-pool.ts +96 -0
  357. package/src/lib/writing-tiers.ts +125 -0
  358. package/src/main.orig.tsx +10 -0
  359. package/src/main.tsx +10 -0
  360. package/src/utils/cn.orig.ts +6 -0
  361. package/src/utils/cn.ts +6 -0
  362. package/src/vite-env.d.ts +1 -0
  363. package/tsconfig.json +31 -0
  364. package/unify.mjs +537 -0
  365. package/vite.config.ts +18 -0
@@ -0,0 +1,1001 @@
1
+ /**
2
+ * innovation-genome-engine-v2.ts
3
+ * ============================================================================
4
+ * ADDITIVE v2 over innovation-genome-engine.ts. v1 source and exports remain
5
+ * untouched. Browser/Node compatible, zero external dependencies.
6
+ *
7
+ * Adds:
8
+ * - 14 personas (25 total with v1), 8 cyclic paths (24 total with v1)
9
+ * - five deterministic systematic mutations
10
+ * - three deterministic crossover operators
11
+ * - four-objective FitnessVector + Pareto/MAP-Elites archive
12
+ * - deterministic island migration and evaluator-driven evolution
13
+ * - persistent anomaly and failure-certificate archives
14
+ * - 16 domain packs, safety and capability-reality gates
15
+ * - JSON Schema export and pure diagnostics
16
+ *
17
+ * No candidate receives fitness without a caller-supplied evaluator. This
18
+ * engine compiles and evolves search directives; it does not claim that an
19
+ * unevaluated directive solves the user's problem.
20
+ * ============================================================================ */
21
+
22
+ import {
23
+ DIMENSIONS,
24
+ classifyPersona,
25
+ compileInnovationPrompt,
26
+ seedToGenome,
27
+ selectPath,
28
+ type DiscoveryPath,
29
+ type Genome,
30
+ type InnovationPersona,
31
+ } from "./innovation-genome-engine";
32
+
33
+ export { DIMENSIONS } from "./innovation-genome-engine";
34
+
35
+ // ── Deterministic random source ─────────────────────────────────────────────
36
+
37
+ function hash32(value: string): number {
38
+ let h = 0x811c9dc5;
39
+ for (let i = 0; i < value.length; i += 1) {
40
+ h ^= value.charCodeAt(i);
41
+ h = Math.imul(h, 0x01000193) >>> 0;
42
+ }
43
+ h ^= h >>> 16;
44
+ h = Math.imul(h, 0x7feb352d) >>> 0;
45
+ h ^= h >>> 15;
46
+ h = Math.imul(h, 0x846ca68b) >>> 0;
47
+ return (h ^ (h >>> 16)) >>> 0;
48
+ }
49
+
50
+ class SeededRng {
51
+ private state: number;
52
+
53
+ constructor(seed: number) {
54
+ this.state = seed >>> 0 || 0x6d2b79f5;
55
+ }
56
+
57
+ next(): number {
58
+ let x = this.state;
59
+ x ^= x << 13;
60
+ x ^= x >>> 17;
61
+ x ^= x << 5;
62
+ this.state = x >>> 0;
63
+ return this.state / 0x100000000;
64
+ }
65
+
66
+ int(min: number, maxInclusive: number): number {
67
+ return min + Math.floor(this.next() * (maxInclusive - min + 1));
68
+ }
69
+
70
+ choice<T>(values: readonly T[]): T {
71
+ if (!values.length) throw new Error("choice requires a non-empty array");
72
+ return values[this.int(0, values.length - 1)];
73
+ }
74
+
75
+ shuffle<T>(values: readonly T[]): T[] {
76
+ const output = [...values];
77
+ for (let i = output.length - 1; i > 0; i -= 1) {
78
+ const j = this.int(0, i);
79
+ [output[i], output[j]] = [output[j], output[i]];
80
+ }
81
+ return output;
82
+ }
83
+
84
+ sample<T>(values: readonly T[], count: number): T[] {
85
+ return this.shuffle(values).slice(0, Math.max(0, Math.min(count, values.length)));
86
+ }
87
+ }
88
+
89
+ function seededRng(parentSeed: number, operationIndex = 0, namespace = "mut"): SeededRng {
90
+ return new SeededRng(hash32(`${namespace}:${parentSeed}:${operationIndex}`));
91
+ }
92
+
93
+ function clampUnit(value: number): number {
94
+ return Math.round(Math.max(0, Math.min(1, value)) * 100) / 100;
95
+ }
96
+
97
+ function cloneGenome(genome: Genome): Genome {
98
+ return Object.fromEntries(Object.entries(genome).map(([key, value]) => [key, value]));
99
+ }
100
+
101
+ // ── Extended personas and paths ─────────────────────────────────────────────
102
+
103
+ interface PersonaRule extends InnovationPersona {
104
+ match: (genome: Genome) => boolean;
105
+ }
106
+
107
+ export const EXTENDED_PERSONAS: readonly PersonaRule[] = [
108
+ { name: "The Diagonalizer", tagline: "The system contains its own contradiction. Find it.", match: (g) => g.problem_framing > 0.75 && g.adversarial_intensity > 0.75 },
109
+ { name: "The Dormancy Prospector", tagline: "The tool you need was invented 50 years ago for something else.", match: (g) => g.analogy_distance > 0.85 && g.anomaly_memory > 0.6 },
110
+ { name: "The Reality Grinder", tagline: "The world pushes back. Listen to the wreckage.", match: (g) => g.world_contact > 0.85 && g.failure_treatment > 0.7 },
111
+ { name: "The Category Creator", tagline: "Name the new kind of thing. Solving it comes second.", match: (g) => g.problem_framing > 0.85 && g.novelty_vs_utility > 0.7 },
112
+ { name: "The Meta-Problemist", tagline: "Why does this class of problems even exist?", match: (g) => g.problem_source > 0.8 && g.goal_fixity > 0.75 },
113
+ { name: "The Serendipity Fisher", tagline: "Cast wide nets. Recognize the strange catch.", match: (g) => g.anomaly_sensitivity > 0.7 && g.portfolio_breadth > 0.7 },
114
+ { name: "The Symmetry Elevator", tagline: "The pattern isn't coincidence. Make it the first principle.", match: (g) => g.representation_diversity > 0.75 && g.taste_weight > 0.7 },
115
+ { name: "The Constraint Injector", tagline: "Add a rule to expose what the old rules were hiding.", match: (g) => g.adversarial_intensity > 0.75 && g.problem_framing > 0.6 },
116
+ { name: "The Failure Archivist", tagline: "The dead ends map the live ones.", match: (g) => g.failure_treatment > 0.85 && g.anomaly_memory > 0.7 },
117
+ { name: "The Reformulator", tagline: "Change the language. The answer appears.", match: (g) => g.representation_diversity > 0.85 && g.analogy_distance > 0.6 },
118
+ { name: "The Slow Hunch", tagline: "Years of accumulation. One moment of connection.", match: (g) => g.anomaly_memory > 0.85 && g.termination_resistance > 0.7 },
119
+ { name: "The Aesthetic Adversary", tagline: "Ugly proofs are wrong proofs waiting to fail.", match: (g) => g.taste_weight > 0.85 && g.adversarial_intensity > 0.6 },
120
+ { name: "The Reduction Artist", tagline: "Show that this problem IS that solved problem.", match: (g) => g.analogy_distance > 0.7 && g.artifact_concreteness > 0.7 },
121
+ { name: "The Boundary Interrogator", tagline: "Extreme cases reveal what typical cases hide.", match: (g) => g.anomaly_sensitivity > 0.65 && g.cheap_falsification > 0.75 },
122
+ ];
123
+
124
+ export function classifyPersonaExtended(genome: Genome): InnovationPersona {
125
+ for (const persona of EXTENDED_PERSONAS) {
126
+ if (persona.match(genome)) return { name: persona.name, tagline: persona.tagline };
127
+ }
128
+ const v1 = classifyPersona(genome);
129
+ // Keep v1 untouched, but avoid name collision with the Williams writer
130
+ // roster in the live v2 system.
131
+ return v1.name === "The Plain Dealer"
132
+ ? { name: "The Unvarnished Operator", tagline: v1.tagline }
133
+ : v1;
134
+ }
135
+
136
+ interface PathRule extends DiscoveryPath {
137
+ trigger: (genome: Genome) => boolean;
138
+ }
139
+
140
+ export const EXTENDED_PATH_TABLE: readonly PathRule[] = [
141
+ { id: "ρ", name: "Evaluator-Anomaly Spiral", seq: "P→(A↔V)*→N→T→S", trigger: (g) => g.evaluator_mutability > 0.7 && g.anomaly_sensitivity > 0.7 },
142
+ { id: "σ", name: "Build-Test-Import Cycle", seq: "E→A→N→V→(E↔A)*→T→S", trigger: (g) => g.world_contact > 0.7 && g.representation_diversity > 0.65 },
143
+ { id: "τ", name: "Taste-Gated Traversal", seq: "T→P→T→A→T→N→T→V→T→E→T→S", trigger: (g) => g.taste_weight > 0.9 },
144
+ { id: "υ", name: "Community-Feedback Loop", seq: "P→A→E→N→V→T→S→P'→...", trigger: (g) => g.independence_vs_consensus < 0.15 && g.portfolio_breadth > 0.5 },
145
+ { id: "φ", name: "Portfolio-Then-Prune", seq: "P→[N₁,N₂,...,Nₖ]→A→V→T→E→S", trigger: (g) => g.portfolio_breadth > 0.85 && g.mechanism_independence > 0.75 },
146
+ { id: "χ", name: "Adversary-First", seq: "V→P→A→E→N→T→S", trigger: (g) => g.adversarial_intensity > 0.85 && g.evaluator_source > 0.5 },
147
+ { id: "ψ", name: "Reformulation Cascade", seq: "P→N₁→N₂→N₃→A→V→E→T→S", trigger: (g) => g.representation_diversity > 0.85 && g.problem_framing > 0.7 },
148
+ { id: "ω", name: "Terminal-Node Amplifier", seq: "P→A→E→N→V→T→S→S'→S''", trigger: (g) => g.termination_resistance > 0.85 && g.independence_vs_consensus > 0.6 },
149
+ ];
150
+
151
+ export function selectPathExtended(genome: Genome): DiscoveryPath {
152
+ for (const path of EXTENDED_PATH_TABLE) {
153
+ if (path.trigger(genome)) return { id: path.id, name: path.name, seq: path.seq };
154
+ }
155
+ return selectPath(genome);
156
+ }
157
+
158
+ // ── Systematic mutation operators ──────────────────────────────────────────
159
+
160
+ export const DIMENSION_BLOCKS: Readonly<Record<string, readonly string[]>> = (() => {
161
+ const blocks: Record<string, string[]> = {};
162
+ for (const dimension of DIMENSIONS) {
163
+ (blocks[dimension.block] ??= []).push(dimension.id);
164
+ }
165
+ return blocks;
166
+ })();
167
+
168
+ export type MutationKind = "nudge" | "flip" | "block_rotate" | "pole_swap" | "dimension_mask";
169
+
170
+ export interface MutationOptions {
171
+ magnitude?: number;
172
+ fraction?: number;
173
+ keepIds?: readonly string[];
174
+ }
175
+
176
+ export function mutateNudge(base: Genome, parentSeed: number, operationIndex = 0, options: MutationOptions = {}): Genome {
177
+ const rng = seededRng(parentSeed, operationIndex, "nudge");
178
+ const output = cloneGenome(base);
179
+ const keys = rng.shuffle(Object.keys(output));
180
+ const count = Math.max(1, Math.floor(keys.length * Math.max(0, Math.min(1, options.fraction ?? 0.3))));
181
+ const magnitude = Math.max(0, Math.min(1, options.magnitude ?? 0.15));
182
+ for (const key of keys.slice(0, count)) {
183
+ output[key] = clampUnit(output[key] + (rng.next() * 2 - 1) * magnitude);
184
+ }
185
+ return output;
186
+ }
187
+
188
+ export function mutateFlip(base: Genome, parentSeed: number, operationIndex = 0, options: MutationOptions = {}): Genome {
189
+ const rng = seededRng(parentSeed, operationIndex, "flip");
190
+ const output = cloneGenome(base);
191
+ const keys = rng.shuffle(Object.keys(output));
192
+ const count = Math.max(1, Math.floor(keys.length * Math.max(0, Math.min(1, options.fraction ?? 0.2))));
193
+ for (const key of keys.slice(0, count)) output[key] = clampUnit(1 - output[key]);
194
+ return output;
195
+ }
196
+
197
+ export function mutateBlockRotate(base: Genome, parentSeed: number, operationIndex = 0): Genome {
198
+ const rng = seededRng(parentSeed, operationIndex, "block-rotate");
199
+ const output = cloneGenome(base);
200
+ const blocks = Object.keys(DIMENSION_BLOCKS).filter((block) => DIMENSION_BLOCKS[block].length > 1);
201
+ const ids = [...DIMENSION_BLOCKS[rng.choice(blocks)]];
202
+ const values = ids.map((id) => output[id]);
203
+ const shift = rng.int(1, values.length - 1);
204
+ ids.forEach((id, index) => { output[id] = values[(index - shift + values.length) % values.length]; });
205
+ return output;
206
+ }
207
+
208
+ export function mutatePoleSwap(base: Genome, parentSeed: number, operationIndex = 0): Genome {
209
+ const rng = seededRng(parentSeed, operationIndex, "pole-swap");
210
+ const output = cloneGenome(base);
211
+ const blocks = Object.keys(DIMENSION_BLOCKS).filter((block) => DIMENSION_BLOCKS[block].length >= 2);
212
+ const [left, right] = rng.sample(DIMENSION_BLOCKS[rng.choice(blocks)], 2);
213
+ [output[left], output[right]] = [output[right], output[left]];
214
+ return output;
215
+ }
216
+
217
+ export function mutateDimensionMask(base: Genome, parentSeed: number, operationIndex = 0, options: MutationOptions = {}): Genome {
218
+ const rng = seededRng(parentSeed, operationIndex, "dimension-mask");
219
+ const output = cloneGenome(base);
220
+ const keep = new Set(options.keepIds ?? ["taste_weight", "adversarial_intensity", "world_contact"]);
221
+ for (const key of Object.keys(output)) {
222
+ if (!keep.has(key)) output[key] = clampUnit(rng.next());
223
+ }
224
+ return output;
225
+ }
226
+
227
+ export function applyMutation(base: Genome, parentSeed: number, kind: MutationKind = "nudge", operationIndex = 0, options: MutationOptions = {}): Genome {
228
+ switch (kind) {
229
+ case "nudge": return mutateNudge(base, parentSeed, operationIndex, options);
230
+ case "flip": return mutateFlip(base, parentSeed, operationIndex, options);
231
+ case "block_rotate": return mutateBlockRotate(base, parentSeed, operationIndex);
232
+ case "pole_swap": return mutatePoleSwap(base, parentSeed, operationIndex);
233
+ case "dimension_mask": return mutateDimensionMask(base, parentSeed, operationIndex, options);
234
+ default: throw new Error(`Unknown mutation kind: ${String(kind)}`);
235
+ }
236
+ }
237
+
238
+ // ── Semantic crossover operators ────────────────────────────────────────────
239
+
240
+ export type CrossoverKind = "uniform" | "block" | "pareto_weighted";
241
+
242
+ export function crossoverUniform(parentA: Genome, parentB: Genome, seed: number, operationIndex = 0): Genome {
243
+ const rng = seededRng(seed, operationIndex, "cross-uniform");
244
+ const output: Genome = {};
245
+ for (const key of Object.keys(parentA)) output[key] = rng.next() < 0.5 ? parentA[key] : parentB[key];
246
+ return output;
247
+ }
248
+
249
+ export function crossoverBlock(parentA: Genome, parentB: Genome, seed: number, operationIndex = 0): Genome {
250
+ const rng = seededRng(seed, operationIndex, "cross-block");
251
+ const output: Genome = {};
252
+ for (const ids of Object.values(DIMENSION_BLOCKS)) {
253
+ const source = rng.next() < 0.5 ? parentA : parentB;
254
+ for (const id of ids) output[id] = source[id];
255
+ }
256
+ return output;
257
+ }
258
+
259
+ export function crossoverParetoWeighted(
260
+ parentA: Genome,
261
+ parentB: Genome,
262
+ fitnessA: number,
263
+ fitnessB: number,
264
+ seed: number,
265
+ operationIndex = 0,
266
+ ): Genome {
267
+ const rng = seededRng(seed, operationIndex, "cross-pareto");
268
+ const total = Math.max(1e-9, Math.max(0, fitnessA) + Math.max(0, fitnessB));
269
+ const weightA = Math.max(0, fitnessA) / total;
270
+ const output: Genome = {};
271
+ for (const key of Object.keys(parentA)) {
272
+ output[key] = rng.next() < 0.7
273
+ ? clampUnit(weightA * parentA[key] + (1 - weightA) * parentB[key])
274
+ : (rng.next() < weightA ? parentA[key] : parentB[key]);
275
+ }
276
+ return output;
277
+ }
278
+
279
+ export function applyCrossover(
280
+ parentA: Genome,
281
+ parentB: Genome,
282
+ kind: CrossoverKind,
283
+ seed: number,
284
+ operationIndex = 0,
285
+ fitnessA = 0.5,
286
+ fitnessB = 0.5,
287
+ ): Genome {
288
+ switch (kind) {
289
+ case "uniform": return crossoverUniform(parentA, parentB, seed, operationIndex);
290
+ case "block": return crossoverBlock(parentA, parentB, seed, operationIndex);
291
+ case "pareto_weighted": return crossoverParetoWeighted(parentA, parentB, fitnessA, fitnessB, seed, operationIndex);
292
+ default: throw new Error(`Unknown crossover kind: ${String(kind)}`);
293
+ }
294
+ }
295
+
296
+ // ── Multi-objective fitness and MAP-Elites/Pareto archive ───────────────────
297
+
298
+ export class FitnessVector {
299
+ constructor(
300
+ public readonly novelty = 0,
301
+ public readonly utility = 0,
302
+ public readonly tractability = 0,
303
+ public readonly robustness = 0,
304
+ ) {
305
+ for (const value of this.asTuple()) {
306
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new Error("Fitness values must be finite and in [0,1]");
307
+ }
308
+ }
309
+
310
+ asTuple(): readonly [number, number, number, number] {
311
+ return [this.novelty, this.utility, this.tractability, this.robustness];
312
+ }
313
+
314
+ score(weights: readonly [number, number, number, number] = [0.25, 0.25, 0.25, 0.25]): number {
315
+ return this.asTuple().reduce((sum, value, index) => sum + value * weights[index], 0);
316
+ }
317
+
318
+ dominates(other: FitnessVector): boolean {
319
+ const mine = this.asTuple();
320
+ const theirs = other.asTuple();
321
+ return mine.every((value, index) => value >= theirs[index]) && mine.some((value, index) => value > theirs[index]);
322
+ }
323
+ }
324
+
325
+ export interface GenomeEntryInit {
326
+ seed: number;
327
+ genome: Genome;
328
+ fitness?: FitnessVector;
329
+ lineage?: number[];
330
+ notes?: string;
331
+ }
332
+
333
+ export class GenomeEntry {
334
+ readonly seed: number;
335
+ readonly genome: Genome;
336
+ readonly fitness: FitnessVector;
337
+ readonly lineage: number[];
338
+ readonly notes: string;
339
+
340
+ constructor(init: GenomeEntryInit) {
341
+ this.seed = init.seed;
342
+ this.genome = cloneGenome(init.genome);
343
+ this.fitness = init.fitness ?? new FitnessVector();
344
+ this.lineage = [...(init.lineage ?? [init.seed])];
345
+ this.notes = init.notes ?? "";
346
+ }
347
+
348
+ behavioralSignature(): readonly [number, number, number] {
349
+ const bin = (id: string) => Math.min(9, Math.floor(this.genome[id] * 10));
350
+ return [bin("analogy_distance"), bin("world_contact"), bin("taste_weight")];
351
+ }
352
+
353
+ clone(): GenomeEntry {
354
+ return new GenomeEntry({ seed: this.seed, genome: this.genome, fitness: this.fitness, lineage: this.lineage, notes: this.notes });
355
+ }
356
+ }
357
+
358
+ export class ParetoArchive {
359
+ private readonly cells = new Map<string, GenomeEntry>();
360
+ private pareto: GenomeEntry[] = [];
361
+
362
+ add(entry: GenomeEntry): boolean {
363
+ const cellKey = entry.behavioralSignature().join(":");
364
+ const incumbent = this.cells.get(cellKey);
365
+ let changed = false;
366
+ if (!incumbent || entry.fitness.score() > incumbent.fitness.score()) {
367
+ this.cells.set(cellKey, entry.clone());
368
+ changed = true;
369
+ }
370
+
371
+ if (!this.pareto.some((existing) => existing.fitness.dominates(entry.fitness))) {
372
+ this.pareto = this.pareto.filter((existing) => !entry.fitness.dominates(existing.fitness) && existing.seed !== entry.seed);
373
+ this.pareto.push(entry.clone());
374
+ this.pareto.sort((a, b) => b.fitness.score() - a.fitness.score() || a.seed - b.seed);
375
+ changed = true;
376
+ }
377
+ return changed;
378
+ }
379
+
380
+ size(): number { return this.cells.size; }
381
+ front(): GenomeEntry[] { return this.pareto.map((entry) => entry.clone()); }
382
+ entries(): GenomeEntry[] { return Array.from(this.cells.values()).map((entry) => entry.clone()); }
383
+
384
+ sampleParent(seed: number): GenomeEntry | null {
385
+ const values = this.entries();
386
+ if (!values.length) return null;
387
+ return seededRng(seed, 0, "archive-parent").choice(values);
388
+ }
389
+
390
+ toJSON(): unknown {
391
+ return {
392
+ nCells: this.cells.size,
393
+ nParetoFront: this.pareto.length,
394
+ cells: this.entries().map((entry) => ({ signature: entry.behavioralSignature(), seed: entry.seed, fitness: entry.fitness.asTuple(), lineage: entry.lineage, notes: entry.notes })),
395
+ paretoFront: this.front().map((entry) => ({ seed: entry.seed, fitness: entry.fitness.asTuple() })),
396
+ };
397
+ }
398
+ }
399
+
400
+ // ── Island model and evaluator-driven evolution ─────────────────────────────
401
+
402
+ export class Island {
403
+ readonly population: GenomeEntry[] = [];
404
+ readonly archive = new ParetoArchive();
405
+ generation = 0;
406
+
407
+ constructor(public readonly name: string) {}
408
+
409
+ add(entry: GenomeEntry): void {
410
+ this.population.push(entry.clone());
411
+ this.archive.add(entry);
412
+ }
413
+ }
414
+
415
+ export class IslandManager {
416
+ readonly islands: Island[];
417
+
418
+ constructor(count = 3) {
419
+ if (!Number.isInteger(count) || count < 1) throw new Error("Island count must be a positive integer");
420
+ this.islands = Array.from({ length: count }, (_, index) => new Island(`island-${index}`));
421
+ }
422
+
423
+ migrate(seed: number, migrantsPerIsland = 1): number {
424
+ if (this.islands.length < 2) return 0;
425
+ const rng = seededRng(seed, 0, "island-migrate");
426
+ const transfers: Array<{ target: Island; entries: GenomeEntry[] }> = [];
427
+ this.islands.forEach((island, index) => {
428
+ const front = island.archive.front();
429
+ if (!front.length) return;
430
+ transfers.push({
431
+ target: this.islands[(index + 1) % this.islands.length],
432
+ entries: rng.sample(front, Math.min(Math.max(0, migrantsPerIsland), front.length)),
433
+ });
434
+ });
435
+ let migrations = 0;
436
+ for (const transfer of transfers) {
437
+ for (const entry of transfer.entries) {
438
+ transfer.target.add(entry);
439
+ migrations += 1;
440
+ }
441
+ }
442
+ return migrations;
443
+ }
444
+
445
+ toJSON(): unknown {
446
+ return { nIslands: this.islands.length, islands: this.islands.map((island) => ({ name: island.name, generation: island.generation, nCells: island.archive.size(), population: island.population.length })) };
447
+ }
448
+ }
449
+
450
+ export type GenomeEvaluator = (candidate: Genome, context: { seed: number; lineage: number[] }) => Promise<FitnessVector> | FitnessVector;
451
+
452
+ /**
453
+ * Generate and genuinely evaluate one deterministic mutation generation.
454
+ * Fitness comes only from the supplied evaluator; the engine never invents it.
455
+ */
456
+ export async function evolveGeneration(
457
+ parent: GenomeEntry,
458
+ evaluator: GenomeEvaluator,
459
+ options: { count?: number; operationSeed?: number; kinds?: readonly MutationKind[] } = {},
460
+ ): Promise<GenomeEntry[]> {
461
+ const count = Math.max(1, Math.min(64, Math.floor(options.count ?? 5)));
462
+ const kinds = options.kinds?.length ? options.kinds : (["nudge", "flip", "block_rotate", "pole_swap", "dimension_mask"] as const);
463
+ const operationSeed = options.operationSeed ?? parent.seed;
464
+ const children: GenomeEntry[] = [];
465
+ for (let index = 0; index < count; index += 1) {
466
+ const kind = kinds[index % kinds.length];
467
+ const childSeed = hash32(`child:${operationSeed}:${parent.seed}:${index}`);
468
+ const genome = applyMutation(parent.genome, parent.seed, kind, index);
469
+ const lineage = [...parent.lineage, childSeed];
470
+ const fitness = await evaluator(genome, { seed: childSeed, lineage });
471
+ children.push(new GenomeEntry({ seed: childSeed, genome, fitness, lineage, notes: `mutation=${kind}; parent=${parent.seed}` }));
472
+ }
473
+ return children;
474
+ }
475
+
476
+ // ── Persistent anomaly and failure certificate memory ──────────────────────
477
+
478
+ export interface AnomalyRecord {
479
+ id: string;
480
+ description: string;
481
+ roundSeen: number;
482
+ resolved?: boolean;
483
+ hypothesizedMechanism?: string;
484
+ }
485
+
486
+ export class AnomalyBuffer {
487
+ private records: AnomalyRecord[];
488
+
489
+ constructor(initial: readonly AnomalyRecord[] = []) {
490
+ this.records = initial.map((record) => ({ ...record }));
491
+ }
492
+
493
+ log(record: AnomalyRecord): void {
494
+ const index = this.records.findIndex((item) => item.id === record.id);
495
+ if (index >= 0) this.records[index] = { ...record };
496
+ else this.records.push({ ...record });
497
+ }
498
+
499
+ unresolved(): AnomalyRecord[] { return this.records.filter((record) => !record.resolved).map((record) => ({ ...record })); }
500
+
501
+ resolve(id: string, mechanism: string): boolean {
502
+ const record = this.records.find((item) => item.id === id);
503
+ if (!record) return false;
504
+ record.resolved = true;
505
+ record.hypothesizedMechanism = mechanism;
506
+ return true;
507
+ }
508
+
509
+ toPromptBlock(): string {
510
+ if (!this.records.length) return "No anomalies logged yet.";
511
+ return ["ANOMALY BUFFER (persistent across rounds):", ...this.records.map((record) => ` [${record.resolved ? "RESOLVED" : "OPEN"}] ${record.id} (round ${record.roundSeen}): ${record.description}${record.hypothesizedMechanism ? `\n → mechanism: ${record.hypothesizedMechanism}` : ""}`)].join("\n");
512
+ }
513
+
514
+ toJSON(): AnomalyRecord[] { return this.records.map((record) => ({ ...record })); }
515
+ }
516
+
517
+ export interface FailureCertificate {
518
+ route: string;
519
+ centralMechanism: string;
520
+ strongestEstablished: string;
521
+ minimalCounterexample: string;
522
+ unresolvedObligation: string;
523
+ gapClass: "local" | "theorem-strength" | "model-mismatch" | "resource-barrier";
524
+ reopenCondition: string;
525
+ }
526
+
527
+ export class FailureArchive {
528
+ private certificates: FailureCertificate[];
529
+
530
+ constructor(initial: readonly FailureCertificate[] = []) {
531
+ this.certificates = initial.map((certificate) => ({ ...certificate }));
532
+ }
533
+
534
+ add(certificate: FailureCertificate): void { this.certificates.push({ ...certificate }); }
535
+ matching(route: string): FailureCertificate[] { return this.certificates.filter((certificate) => certificate.route === route).map((certificate) => ({ ...certificate })); }
536
+
537
+ toPromptBlock(): string {
538
+ if (!this.certificates.length) return "No failure certificates logged.";
539
+ return ["FAILURE CERTIFICATES (previously blocked routes):", ...this.certificates.map((certificate) => ` Route: ${certificate.route} (${certificate.gapClass})\n Mechanism: ${certificate.centralMechanism}\n Unresolved: ${certificate.unresolvedObligation}\n Reopen if: ${certificate.reopenCondition}`)].join("\n");
540
+ }
541
+
542
+ toJSON(): FailureCertificate[] { return this.certificates.map((certificate) => ({ ...certificate })); }
543
+ }
544
+
545
+ const ANOMALY_STORAGE_KEY = "veritas.v15.innovationGenome.v2.anomalies";
546
+ const FAILURE_STORAGE_KEY = "veritas.v15.innovationGenome.v2.failures";
547
+
548
+ export function loadPersistentDiscoveryMemory(): { anomalyBuffer: AnomalyBuffer; failureArchive: FailureArchive } {
549
+ try {
550
+ const anomalies = JSON.parse(localStorage.getItem(ANOMALY_STORAGE_KEY) || "[]");
551
+ const failures = JSON.parse(localStorage.getItem(FAILURE_STORAGE_KEY) || "[]");
552
+ return { anomalyBuffer: new AnomalyBuffer(Array.isArray(anomalies) ? anomalies : []), failureArchive: new FailureArchive(Array.isArray(failures) ? failures : []) };
553
+ } catch {
554
+ return { anomalyBuffer: new AnomalyBuffer(), failureArchive: new FailureArchive() };
555
+ }
556
+ }
557
+
558
+ export function savePersistentDiscoveryMemory(anomalyBuffer: AnomalyBuffer, failureArchive: FailureArchive): void {
559
+ try {
560
+ localStorage.setItem(ANOMALY_STORAGE_KEY, JSON.stringify(anomalyBuffer.toJSON()));
561
+ localStorage.setItem(FAILURE_STORAGE_KEY, JSON.stringify(failureArchive.toJSON()));
562
+ } catch {
563
+ /* storage unavailable: fail open; prompt still compiles */
564
+ }
565
+ }
566
+
567
+ // ── Domain packs ────────────────────────────────────────────────────────────
568
+
569
+ export interface DomainPack {
570
+ name: string;
571
+ candidateArtifact: string;
572
+ candidateSpecificAttacker: string;
573
+ verifier: string;
574
+ representations: readonly string[];
575
+ mandatoryGates: readonly string[];
576
+ nearMisses: readonly string[];
577
+ highStakes?: boolean;
578
+ }
579
+
580
+ function pack(
581
+ name: string,
582
+ candidateArtifact: string,
583
+ attacker: string,
584
+ verifier: string,
585
+ representations: readonly string[],
586
+ mandatoryGates: readonly string[],
587
+ nearMisses: readonly string[],
588
+ highStakes = false,
589
+ ): DomainPack {
590
+ return { name, candidateArtifact, candidateSpecificAttacker: attacker, verifier, representations, mandatoryGates, nearMisses, highStakes };
591
+ }
592
+
593
+ const COMMON_GATES = ["Explicit success criterion", "Quantifier order", "Resource accounting", "Adversary survival", "Reproducibility"] as const;
594
+
595
+ export const DOMAIN_PACKS: Readonly<Record<string, DomainPack>> = {
596
+ mathematics: pack("mathematics", "proof, disproof, explicit construction, or matching bound", "Construct minimal counterexamples, negate every load-bearing lemma, check quantifier order, and search for a countermodel.", "Lean/Coq/Isabelle, symbolic algebra, or independent expert audit", ["primal/dual", "extremal/minimal-counterexample", "geometric/algebraic/analytic", "flow/polyhedral/optimization", "proof-assistant encoding", "executable finite falsification"], ["Explicit quantifier order", "Imported-theorem hypothesis alignment", "No hidden regularity", "Global consistency", "Exact constants and asymptotics"], ["Proof for a strict subclass", "Numerical verification in fixed dimension", "Unproved bridge equivalent to target", "Randomized substituted for deterministic", "Different oracle/norm/topology/regime"]),
597
+ algorithms: pack("algorithms", "algorithm, optimization formulation, or matching complexity bound", "Generate worst-case inputs, adversarial oracles, integrality-gap instances, pathological scaling, and output-handling failures.", "Formal complexity proof, solver certificates, exact enumeration, and benchmarks", ["primal/dual optimization", "online/offline", "communication complexity", "potential function", "flow/matching/polyhedral", "DP/state compression"], ["Complete cost accounting", "Worst-case not average-case", "No hidden oracle", "Feasible output and exact objective", "Precision propagation"], ["Faster arithmetic without oracle-complexity change", "Empirical solver success without theorem", "Unproved rounding/relaxation", "Ignoring preprocessing/retries"]),
598
+ software: pack("software", "production implementation with explicit behavioral contract", "Attack malformed input, Unicode/path edges, races, partial failure, dependency failure, overload, and abuse cases.", "Unit + integration + property + fuzz + concurrency + security tests", ["state machine", "data-flow graph", "event-sourced", "actor model", "transactional", "differential test"], ["Acceptance tests before implementation", "Compatibility/migration", "Dependency/license review", "Failure and rollback", "Observability"], ["Happy-path-only", "Mocks replacing production", "Uncounted retries", "Claimed but unexecuted tests"]),
599
+ medicine: pack("medicine", "mechanistic hypothesis, diagnostic, or therapeutic proposal", "Attack off-target effects, compensation, subgroup harm, adverse events, non-replication, and confounding.", "Independent assays, animal/clinical trials, prospective validation, and clinician review", ["causal pathway", "dynamical system", "dose-response", "trial estimand", "clinical decision analysis"], ["Evidence hierarchy", "Population/endpoint alignment", "Safety analysis", "Prospective validation", "Human/regulatory review"], ["In-vitro to patient leap", "Surrogate to clinical benefit substitution", "Retrospective to prospective claim", "Prompt-forced certainty"], true),
600
+ legal: pack("legal", "legal interpretation, compliance position, or contract clause", "Search contrary primary authority, jurisdictional conflicts, adverse facts, procedural barriers, and unintended incentives.", "Current primary law, official regulatory material, and jurisdiction-qualified counsel", ["IRAC", "authority hierarchy", "rights-obligations graph", "policy causal model", "contract state machine"], ["Jurisdiction/effective date", "Primary authority", "Adverse authority", "Facts-to-rule alignment", "Human legal approval"], ["Outdated law", "Secondary summary as binding", "Dicta as holding", "Jurisdiction over-generalization"], true),
601
+ physics: pack("physics", "model, mechanism, device, or quantitative bound", "Attack conservation laws, limiting cases, noise, decoherence, and boundary conditions.", "Dimensional analysis, simulation, uncertainty propagation, and experiment", ["Hamiltonian/Lagrangian", "field equation", "circuit analog", "statistical mechanics", "information-theoretic limit", "dimensionless scaling"], ["Units and dimensions", "Conservation laws", "Boundary/initial conditions", "Approximation-domain validity", "Uncertainty budget"], ["Expansion outside validity", "Idealized boundary substitution", "Classical/quantum conflation", "Simulation as experimental proof"]),
602
+ chemistry: pack("chemistry", "molecule, catalyst, material, or synthesis route", "Attack side reactions, unstable intermediates, kinetic traps, degradation, and scale-up failure.", "Quantum chemistry, reaction modeling, synthesis, spectroscopy, and characterization", ["reaction network", "free-energy landscape", "orbital structure", "phase diagram", "process flow"], ["Mass/charge balance", "Thermo/kinetic plausibility", "Conditions/solvent effects", "Characterization plan", "Safety and scale-up"], ["Computed minimum to synthesizable material", "Yield transfer across scales", "Side products omitted", "Novelty without structure search"]),
603
+ ml: pack("ml", "model, dataset, estimator, or empirical claim", "Attack leakage, benchmark contamination, distribution shift, subgroup failure, adversarial examples, and alternative causal graphs.", "Locked holdout, preregistration, ablations, calibration, and replication", ["predictive model", "causal graph", "probabilistic program", "optimization objective", "policy", "error decomposition"], ["Train/val/test separation", "Data provenance", "Baseline and ablation", "Uncertainty and calibration", "Subgroup and shift analysis"], ["Train performance as generalization", "Correlation as causation", "Test-set benchmark tuning", "Average metric hiding subgroup failure"]),
604
+ engineering: pack("engineering", "dimensioned design, model, tolerance stack, and verification plan", "Attack load cases, tolerances, fatigue, manufacturing variance, interfaces, and maintenance conditions.", "Analysis, simulation, prototype test, inspection, and qualified design review", ["requirements graph", "free-body/energy model", "reliability block diagram", "FMEA/STPA", "digital twin", "test article"], ["Units", "Boundary/load cases", "Factors of safety", "Tolerance/uncertainty budget", "Verification traceability"], ["Nominal-only design", "Simulation without validation", "Material property guess", "Ignored interface failure"]),
605
+ finance: pack("finance", "valuation, risk model, strategy, or decision bound", "Attack model risk, liquidity, leverage, tail dependence, regime shift, incentives, and adverse selection.", "Audited data, independent model validation, backtest with holdout, stress tests, and qualified financial review", ["cash-flow model", "scenario tree", "factor model", "option/real-option", "portfolio optimization", "causal market model"], ["Source/date currency", "Units/currency", "Tail stress", "Sensitivity", "No guaranteed-return language"], ["Backtest overfit", "Point estimate without interval", "Illiquidity ignored", "Correlation assumed stable"], true),
606
+ cybersecurity: pack("cybersecurity", "threat model, secure design, exploit proof, or verified mitigation", "Attack trust boundaries, privilege transitions, parser ambiguity, supply chain, secrets, replay, and side channels.", "Static/dynamic analysis, fuzzing, penetration test in authorized scope, and independent security review", ["attack graph", "STRIDE", "protocol state machine", "capability model", "information-flow", "abuse case"], ["Authorization/scope", "Least privilege", "Secret handling", "Input validation", "Patch/regression tests"], ["Security by obscurity", "Scanner-only proof", "Unauthenticated test claim", "Mitigation without threat mapping"], true),
607
+ biology: pack("biology", "mechanistic model, experimental design, or falsifiable biological hypothesis", "Attack confounding, batch effects, compensatory pathways, contamination, selection bias, and non-replication.", "Independent replication, orthogonal assay, controls, preregistered analysis, and expert review", ["causal pathway", "population model", "regulatory network", "phylogenetic", "dose-response", "experimental design"], ["Positive/negative controls", "Sample-size rationale", "Batch correction", "Endpoint alignment", "Biosafety"], ["Correlation as mechanism", "Single-cell-line generalization", "Post-hoc endpoint", "No replication"]),
608
+ product: pack("product", "validated problem, product concept, business model, and experiment", "Attack false demand, willingness-to-pay gaps, channel friction, incumbents, switching cost, and metric gaming.", "User interviews, behavioral prototype, pricing test, cohort data, and falsifiable launch gates", ["jobs-to-be-done", "value chain", "service blueprint", "unit economics", "adoption funnel", "experiment tree"], ["Problem evidence", "Target segment", "Success metric", "Kill criterion", "Unit economics"], ["Survey-only demand", "Feature without job", "TAM as adoption proof", "Vanity metric"]),
609
+ policy: pack("policy", "policy mechanism, implementation design, and distributional impact model", "Attack displacement, gaming, enforcement failure, inequity, jurisdiction conflict, and second-order incentives.", "Primary data, causal evaluation, consultation, pilot, legal review, and public audit", ["theory of change", "causal DAG", "agent-based model", "rights/obligations", "implementation system", "distributional analysis"], ["Authority", "Affected groups", "Counterfactual", "Implementation capacity", "Appeal/accountability"], ["Intent as outcome", "Average effect hiding harms", "No implementation mechanism", "Unfunded mandate"]),
610
+ operations: pack("operations", "operating model, process design, schedule, or capacity bound", "Attack bottlenecks, variability, queues, rework, supplier failure, human workload, and recovery paths.", "Discrete-event model, pilot, control chart, capacity test, and operational review", ["process map", "queueing network", "constraint model", "inventory flow", "schedule", "resilience model"], ["Arrival/service units", "Variability", "Bottleneck proof", "Recovery mode", "Observable KPI"], ["Average-rate capacity", "No variability", "Local optimization", "No failure recovery"]),
611
+ general: pack("general", "the specific verifiable artifact for this problem", "Construct attacker as f(candidate): weakest premise, least stable interface, smallest counterexample shape.", "Strongest available checker for this problem's target", ["primary formal representation", "dual/inverse formulation", "constructive/algorithmic", "impossibility/lower-bound", "executable/testable"], COMMON_GATES, ["Solving an adjacent easier problem", "Progress without falsifiable object", "Unproved standard step"]),
612
+ };
613
+
614
+ // ── Safety and capability reality gates ─────────────────────────────────────
615
+
616
+ export type RiskTier = "low" | "medium" | "high" | "critical";
617
+
618
+ export class SafetyGate {
619
+ constructor(public readonly risk: RiskTier, public readonly domainPack: DomainPack) {}
620
+
621
+ isHighStakes(): boolean {
622
+ return this.domainPack.highStakes === true || this.risk === "high" || this.risk === "critical";
623
+ }
624
+
625
+ transformGenome(genome: Genome): Genome {
626
+ const output = cloneGenome(genome);
627
+ if (this.isHighStakes()) {
628
+ output.termination_resistance = Math.min(output.termination_resistance, 0.5);
629
+ output.goal_fixity = Math.min(output.goal_fixity, 0.3);
630
+ }
631
+ return output;
632
+ }
633
+
634
+ promptAddendum(): string {
635
+ if (!this.isHighStakes()) return "";
636
+ return `## HIGH-STAKES SAFETY GATE (mandatory)
637
+ Do NOT assume the desired conclusion is true. Preserve disproof, uncertainty, and abstention branches. No destructive, clinical, financial, legal, physical, or external action may be taken without qualified human authorization. Uncertainty outranks persistence.`;
638
+ }
639
+ }
640
+
641
+ export interface CapabilityGateOptions {
642
+ runtimeSupportsParallelAgents?: boolean;
643
+ verifierAvailable?: boolean;
644
+ webRetrieval?: boolean;
645
+ formalProver?: boolean;
646
+ executionSandbox?: boolean;
647
+ declaredTools?: readonly string[];
648
+ }
649
+
650
+ export class CapabilityGate {
651
+ readonly runtimeSupportsParallelAgents: boolean;
652
+ readonly verifierAvailable: boolean;
653
+ readonly webRetrieval: boolean;
654
+ readonly formalProver: boolean;
655
+ readonly executionSandbox: boolean;
656
+ readonly declaredTools: readonly string[];
657
+
658
+ constructor(options: CapabilityGateOptions = {}) {
659
+ this.runtimeSupportsParallelAgents = options.runtimeSupportsParallelAgents ?? false;
660
+ this.verifierAvailable = options.verifierAvailable ?? false;
661
+ this.webRetrieval = options.webRetrieval ?? false;
662
+ this.formalProver = options.formalProver ?? false;
663
+ this.executionSandbox = options.executionSandbox ?? false;
664
+ this.declaredTools = [...(options.declaredTools ?? [])];
665
+ }
666
+
667
+ promptAddendum(): string {
668
+ return [
669
+ "## CAPABILITY REALITY GATE",
670
+ `- Parallel-worker runtime: ${this.runtimeSupportsParallelAgents ? "available" : "NOT AVAILABLE (serialize branches; do not fabricate worker messages)"}`,
671
+ `- External verifier: ${this.verifierAvailable ? "available" : "NOT AVAILABLE (label results unverified where a checker was not run)"}`,
672
+ `- Web retrieval: ${this.webRetrieval ? "available" : "NOT AVAILABLE (do not fabricate citations)"}`,
673
+ `- Formal prover: ${this.formalProver ? "available" : "NOT AVAILABLE"}`,
674
+ `- Execution sandbox: ${this.executionSandbox ? "available" : "NOT AVAILABLE (code claims are static-reviewed unless a real tool result exists)"}`,
675
+ `- Declared tools: ${this.declaredTools.length ? this.declaredTools.join(", ") : "none. Do not claim tool execution."}`,
676
+ ].join("\n");
677
+ }
678
+ }
679
+
680
+ function domainPackAddendum(domainPack: DomainPack): string {
681
+ return [
682
+ `## DOMAIN PACK: ${domainPack.name.toUpperCase()}`,
683
+ `Required candidate artifact: ${domainPack.candidateArtifact}`,
684
+ `Candidate-specific attacker: ${domainPack.candidateSpecificAttacker}`,
685
+ `Available verifier: ${domainPack.verifier}`,
686
+ "Representations to attempt:",
687
+ ...domainPack.representations.map((item) => `- ${item}`),
688
+ "Mandatory domain gates:",
689
+ ...domainPack.mandatoryGates.map((item) => `- ${item}`),
690
+ "Banned near-miss result-shapes:",
691
+ ...domainPack.nearMisses.map((item) => `- ${item}`),
692
+ ].join("\n");
693
+ }
694
+
695
+ // ── V2 compiler and JSON schema ─────────────────────────────────────────────
696
+
697
+ export interface InnovationGenomeV2 {
698
+ version: "v2.0";
699
+ seed: number;
700
+ genome: Genome;
701
+ persona: InnovationPersona;
702
+ path: DiscoveryPath;
703
+ prompt: string;
704
+ domainPack: DomainPack;
705
+ safetyGate: SafetyGate;
706
+ capabilityGate: CapabilityGate;
707
+ anomalyBuffer: AnomalyBuffer;
708
+ failureArchive: FailureArchive;
709
+ fitness: FitnessVector;
710
+ }
711
+
712
+ export interface RollV2Options {
713
+ seed?: number;
714
+ userProblem?: string;
715
+ domain?: string;
716
+ risk?: RiskTier;
717
+ capabilityGate?: CapabilityGate;
718
+ anomalyBuffer?: AnomalyBuffer;
719
+ failureArchive?: FailureArchive;
720
+ fitness?: FitnessVector;
721
+ }
722
+
723
+ /** Lightweight domain inference used by the live V15 integration. */
724
+ export function inferInnovationDomain(problem: string): keyof typeof DOMAIN_PACKS {
725
+ const value = problem.toLowerCase();
726
+ if (/\b(theorem|proof|lemma|conjecture|integer|graph theory|topology|algebra|geometry)\b/.test(value)) return "mathematics";
727
+ if (/\b(algorithm|complexity|runtime|data structure|optimization algorithm)\b/.test(value)) return "algorithms";
728
+ if (/\b(code|software|typescript|javascript|python|api|database|frontend|backend|bug)\b/.test(value)) return "software";
729
+ if (/\b(patient|clinical|diagnos|therap|medicine|medical|drug|disease)\b/.test(value)) return "medicine";
730
+ if (/\b(law|legal|court|statute|regulation|contract|jurisdiction)\b/.test(value)) return "legal";
731
+ if (/\b(physics|quantum|force|energy|particle|thermodynamic)\b/.test(value)) return "physics";
732
+ if (/\b(chemistry|chemical|molecule|catalyst|reaction|synthesis)\b/.test(value)) return "chemistry";
733
+ if (/\b(machine learning|\bml\b|neural network|dataset|classifier|model training)\b/.test(value)) return "ml";
734
+ if (/\b(engineer|mechanical|electrical|structural|tolerance|fatigue|manufactur)\b/.test(value)) return "engineering";
735
+ if (/\b(invest|portfolio|finance|financial|valuation|market|return on investment)\b/.test(value)) return "finance";
736
+ if (/\b(cyber|security|vulnerability|exploit|authentication|encryption|threat)\b/.test(value)) return "cybersecurity";
737
+ if (/\b(biology|biological|gene|cell|organism|protein|ecology)\b/.test(value)) return "biology";
738
+ if (/\b(product|customer|market fit|startup|business model|user need)\b/.test(value)) return "product";
739
+ if (/\b(policy|government|public administration|legislation|social program)\b/.test(value)) return "policy";
740
+ if (/\b(operations|supply chain|inventory|queue|capacity|workflow|schedule)\b/.test(value)) return "operations";
741
+ return "general";
742
+ }
743
+
744
+ /** Generate a recorded random seed for live diversity; all downstream behavior
745
+ * remains deterministic once this seed is recorded. */
746
+ export function newInnovationSeed(): number {
747
+ try {
748
+ const values = new Uint32Array(1);
749
+ crypto.getRandomValues(values);
750
+ return values[0];
751
+ } catch {
752
+ return (Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0;
753
+ }
754
+ }
755
+
756
+ function derivedSeed(problem: string, domain: string, risk: RiskTier): number {
757
+ return hash32(`${problem}|${domain}|${risk}`);
758
+ }
759
+
760
+ export function rollV2(options: RollV2Options = {}): InnovationGenomeV2 {
761
+ const userProblem = options.userProblem ?? "[INSERT PROBLEM HERE]";
762
+ const domain = options.domain ?? "general";
763
+ const risk = options.risk ?? "medium";
764
+ const domainPack = DOMAIN_PACKS[domain];
765
+ if (!domainPack) throw new Error(`Unknown domain: ${domain}. Available: ${Object.keys(DOMAIN_PACKS).join(", ")}`);
766
+ const seed = options.seed ?? derivedSeed(userProblem, domain, risk);
767
+ const safetyGate = new SafetyGate(risk, domainPack);
768
+ const capabilityGate = options.capabilityGate ?? new CapabilityGate();
769
+ const anomalyBuffer = options.anomalyBuffer ?? new AnomalyBuffer();
770
+ const failureArchive = options.failureArchive ?? new FailureArchive();
771
+ const genome = safetyGate.transformGenome(seedToGenome(seed));
772
+ const persona = classifyPersonaExtended(genome);
773
+ const path = selectPathExtended(genome);
774
+ const prompt = [
775
+ compileInnovationPrompt(genome, persona, path, userProblem, domain),
776
+ domainPackAddendum(domainPack),
777
+ safetyGate.promptAddendum(),
778
+ capabilityGate.promptAddendum(),
779
+ "## PERSISTENT MEMORY BLOCKS",
780
+ anomalyBuffer.toPromptBlock(),
781
+ failureArchive.toPromptBlock(),
782
+ ].filter(Boolean).join("\n\n");
783
+ return {
784
+ version: "v2.0",
785
+ seed,
786
+ genome,
787
+ persona,
788
+ path,
789
+ prompt,
790
+ domainPack,
791
+ safetyGate,
792
+ capabilityGate,
793
+ anomalyBuffer,
794
+ failureArchive,
795
+ fitness: options.fitness ?? new FitnessVector(),
796
+ };
797
+ }
798
+
799
+ /** Compact v2 directive used by the live pipeline and query strategist. */
800
+ export function compileCompactDirectiveV2(result: InnovationGenomeV2): string {
801
+ const genome = result.genome;
802
+ const families = Math.max(2, Math.min(12, Math.floor(genome.portfolio_breadth * 12) + 1));
803
+ const negatives = Math.max(5, Math.min(35, Math.floor(genome.negative_space_density * 35) + 1));
804
+ return [
805
+ `INNOVATION GENOME v2.0 (seed ${result.seed}) — ${result.persona.name}: ${result.persona.tagline}`,
806
+ `PATH ${result.path.id} (${result.path.name}): ${result.path.seq}`,
807
+ `DOMAIN ${result.domainPack.name}: artifact=${result.domainPack.candidateArtifact}`,
808
+ `PORTFOLIO: maintain ${families} mechanism-distinct branches; do not collapse them before evidence eliminates them.`,
809
+ `NEGATIVE SPACE: enumerate at least ${negatives} near-miss answer shapes; poison the most tempting shortcut with a test.`,
810
+ `ATTACKER: ${result.domainPack.candidateSpecificAttacker}`,
811
+ `VERIFIER: ${result.domainPack.verifier}`,
812
+ `MANDATORY GATES: ${result.domainPack.mandatoryGates.join("; ")}.`,
813
+ genome.evaluator_mutability > 0.6 ? "EVALUATOR: derive and revise success criteria, but preserve an audit trail and rerun repaired candidates from zero trust." : "EVALUATOR: keep the supplied success criterion fixed.",
814
+ genome.anomaly_memory > 0.6 ? result.anomalyBuffer.toPromptBlock() : "",
815
+ result.failureArchive.toPromptBlock(),
816
+ result.safetyGate.promptAddendum(),
817
+ result.capabilityGate.promptAddendum(),
818
+ ].filter(Boolean).join("\n");
819
+ }
820
+
821
+ export interface ExplorationBranchV2 {
822
+ branchId: string;
823
+ mutation: "base" | MutationKind;
824
+ genome: Genome;
825
+ persona: InnovationPersona;
826
+ path: DiscoveryPath;
827
+ }
828
+
829
+ /**
830
+ * Build a deterministic, mechanism-distinct exploration population without
831
+ * inventing fitness. These branches are search instructions, not evaluated
832
+ * solutions; Pareto admission remains reserved for a real evaluator.
833
+ */
834
+ export function buildExplorationPopulationV2(result: InnovationGenomeV2, count = 6): ExplorationBranchV2[] {
835
+ const boundedCount = Math.max(1, Math.min(16, Math.floor(count)));
836
+ const mutationKinds: MutationKind[] = ["nudge", "flip", "block_rotate", "pole_swap", "dimension_mask"];
837
+ const branches: ExplorationBranchV2[] = [
838
+ {
839
+ branchId: "B0",
840
+ mutation: "base",
841
+ genome: cloneGenome(result.genome),
842
+ persona: result.persona,
843
+ path: result.path,
844
+ },
845
+ ];
846
+ for (let index = 1; index < boundedCount; index += 1) {
847
+ const mutation = mutationKinds[(index - 1) % mutationKinds.length];
848
+ const genome = applyMutation(result.genome, result.seed, mutation, index);
849
+ branches.push({
850
+ branchId: `B${index}`,
851
+ mutation,
852
+ genome,
853
+ persona: classifyPersonaExtended(genome),
854
+ path: selectPathExtended(genome),
855
+ });
856
+ }
857
+ return branches;
858
+ }
859
+
860
+ /** Compact branch contract injected into live ideation/retrieval/synthesis. */
861
+ export function compileExplorationPortfolioV2(result: InnovationGenomeV2, count = 6): string {
862
+ const branches = buildExplorationPopulationV2(result, count);
863
+ return [
864
+ `V2 EXPLORATION POPULATION (${branches.length} deterministic branches; no branch has inferred fitness):`,
865
+ ...branches.map((branch) =>
866
+ `${branch.branchId} [${branch.mutation}] ${branch.persona.name} · path ${branch.path.id} ${branch.path.seq} · ` +
867
+ `anomaly=${branch.genome.anomaly_sensitivity.toFixed(2)} analogy=${branch.genome.analogy_distance.toFixed(2)} ` +
868
+ `world=${branch.genome.world_contact.toFixed(2)} adversary=${branch.genome.adversarial_intensity.toFixed(2)} taste=${branch.genome.taste_weight.toFixed(2)}`,
869
+ ),
870
+ "Keep branch mechanisms independent through ideation and retrieval. Merge only after candidate-specific attacks and evidence eliminate or support branches. Do not call this a Pareto front until a real evaluator assigns FitnessVector values.",
871
+ ].join("\n");
872
+ }
873
+
874
+ export const INNOVATION_GENOME_V2_SCHEMA = {
875
+ $schema: "https://json-schema.org/draft/2020-12/schema",
876
+ $id: "innovation-genome-v2.schema.json",
877
+ title: "InnovationGenomeV2",
878
+ type: "object",
879
+ required: ["version", "seed", "genome", "persona", "path", "domain", "risk", "capabilities"],
880
+ properties: {
881
+ version: { const: "v2.0" },
882
+ seed: { type: "integer", minimum: 0 },
883
+ genome: { type: "object", additionalProperties: { type: "number", minimum: 0, maximum: 1 } },
884
+ persona: { type: "object", required: ["name", "tagline"], properties: { name: { type: "string" }, tagline: { type: "string" } } },
885
+ path: { type: "object", required: ["id", "name", "seq"], properties: { id: { type: "string" }, name: { type: "string" }, seq: { type: "string" } } },
886
+ domain: { enum: Object.keys(DOMAIN_PACKS) },
887
+ risk: { enum: ["low", "medium", "high", "critical"] },
888
+ capabilities: {
889
+ type: "object",
890
+ properties: {
891
+ parallelAgents: { type: "boolean" }, verifier: { type: "boolean" }, web: { type: "boolean" }, formalProver: { type: "boolean" }, sandbox: { type: "boolean" }, tools: { type: "array", items: { type: "string" } },
892
+ },
893
+ },
894
+ },
895
+ } as const;
896
+
897
+ export function innovationGenomeV2ToJSON(result: InnovationGenomeV2): unknown {
898
+ return {
899
+ version: result.version,
900
+ seed: result.seed,
901
+ genome: result.genome,
902
+ persona: result.persona,
903
+ path: result.path,
904
+ domain: result.domainPack.name,
905
+ risk: result.safetyGate.risk,
906
+ highStakes: result.safetyGate.isHighStakes(),
907
+ fitness: result.fitness.asTuple(),
908
+ capabilities: {
909
+ parallelAgents: result.capabilityGate.runtimeSupportsParallelAgents,
910
+ verifier: result.capabilityGate.verifierAvailable,
911
+ web: result.capabilityGate.webRetrieval,
912
+ formalProver: result.capabilityGate.formalProver,
913
+ sandbox: result.capabilityGate.executionSandbox,
914
+ tools: [...result.capabilityGate.declaredTools],
915
+ },
916
+ };
917
+ }
918
+
919
+ // ── Diagnostics ─────────────────────────────────────────────────────────────
920
+
921
+ export async function runInnovationGenomeV2Diagnostics(): Promise<{ ok: boolean; checks: Array<{ id: string; passed: boolean; detail: string }> }> {
922
+ const checks: Array<{ id: string; passed: boolean; detail: string }> = [];
923
+ const add = (id: string, passed: boolean, detail: string) => checks.push({ id, passed, detail });
924
+ const base = seedToGenome(42);
925
+ const kinds: MutationKind[] = ["nudge", "flip", "block_rotate", "pole_swap", "dimension_mask"];
926
+ for (const kind of kinds) {
927
+ const first = applyMutation(base, 42, kind, 0, kind === "flip" ? { fraction: 1 } : {});
928
+ const second = applyMutation(base, 42, kind, 0, kind === "flip" ? { fraction: 1 } : {});
929
+ add(`mutation-${kind}-deterministic`, JSON.stringify(first) === JSON.stringify(second), kind);
930
+ add(`mutation-${kind}-bounded`, Object.values(first).every((value) => value >= 0 && value <= 1), kind);
931
+ }
932
+ const allHigh = Object.fromEntries(Object.keys(base).map((key) => [key, 0.9]));
933
+ const flipped = mutateFlip(allHigh, 1, 0, { fraction: 1 });
934
+ add("flip-inverse", Object.values(flipped).every((value) => Math.abs(value - 0.1) < 1e-9), "all 0.9 → 0.1");
935
+
936
+ const left = seedToGenome(1);
937
+ const right = seedToGenome(2);
938
+ const uniformA = crossoverUniform(left, right, 100);
939
+ const uniformB = crossoverUniform(left, right, 100);
940
+ add("uniform-crossover-deterministic", JSON.stringify(uniformA) === JSON.stringify(uniformB), "same seed");
941
+ add("uniform-inherits-only", Object.keys(uniformA).every((key) => uniformA[key] === left[key] || uniformA[key] === right[key]), "parent alleles only");
942
+ const blockChild = crossoverBlock(Object.fromEntries(Object.keys(left).map((key) => [key, 0.1])), Object.fromEntries(Object.keys(right).map((key) => [key, 0.9])), 100);
943
+ add("block-crossover-structure", Object.values(blockChild).every((value) => value === 0.1 || value === 0.9), "whole-block inheritance");
944
+ const weighted = crossoverParetoWeighted(Object.fromEntries(Object.keys(left).map((key) => [key, 0])), Object.fromEntries(Object.keys(right).map((key) => [key, 1])), 0.01, 0.99, 100);
945
+ add("pareto-favors-fitter", Object.values(weighted).reduce((sum, value) => sum + value, 0) / Object.keys(weighted).length > 0.5, "mean > 0.5");
946
+
947
+ const low = new FitnessVector(0.1, 0.1, 0.1, 0.1);
948
+ const high = new FitnessVector(0.9, 0.9, 0.9, 0.9);
949
+ add("fitness-dominance", high.dominates(low) && !low.dominates(high), "strict Pareto");
950
+ const tradeA = new FitnessVector(0.9, 0.1, 0.5, 0.5);
951
+ const tradeB = new FitnessVector(0.1, 0.9, 0.5, 0.5);
952
+ add("fitness-tradeoff-nondominated", !tradeA.dominates(tradeB) && !tradeB.dominates(tradeA), "trade-off preserved");
953
+
954
+ const archive = new ParetoArchive();
955
+ archive.add(new GenomeEntry({ seed: 1, genome: left, fitness: low }));
956
+ archive.add(new GenomeEntry({ seed: 2, genome: right, fitness: high }));
957
+ add("archive-pareto-prunes-dominated", archive.front().length === 1 && archive.front()[0].seed === 2, `front=${archive.front().map((entry) => entry.seed)}`);
958
+
959
+ const manager = new IslandManager(3);
960
+ manager.islands.forEach((island, islandIndex) => {
961
+ for (let index = 0; index < 3; index += 1) {
962
+ const seed = islandIndex * 100 + index;
963
+ island.add(new GenomeEntry({ seed, genome: seedToGenome(seed), fitness: new FitnessVector(index / 3, index / 3, index / 3, index / 3) }));
964
+ }
965
+ });
966
+ add("island-migration", manager.migrate(42) > 0, "migrants moved");
967
+
968
+ const anomalies = new AnomalyBuffer();
969
+ anomalies.log({ id: "A1", description: "unexplained peak", roundSeen: 1 });
970
+ add("anomaly-log", anomalies.unresolved().length === 1, "one unresolved");
971
+ add("anomaly-resolve", anomalies.resolve("A1", "phase boundary artifact") && anomalies.unresolved().length === 0, "resolved");
972
+ const failures = new FailureArchive();
973
+ failures.add({ route: "direct-induction", centralMechanism: "strong induction", strongestEstablished: "base case", minimalCounterexample: "n=3", unresolvedObligation: "handle n=3", gapClass: "local", reopenCondition: "stronger hypothesis" });
974
+ add("failure-archive", failures.matching("direct-induction").length === 1, "matchable");
975
+
976
+ const medicalGate = new SafetyGate("critical", DOMAIN_PACKS.medicine);
977
+ const safeGenome = medicalGate.transformGenome(Object.fromEntries(Object.keys(base).map((key) => [key, 0.95])));
978
+ add("safety-caps-high-stakes", medicalGate.isHighStakes() && safeGenome.termination_resistance <= 0.5 && safeGenome.goal_fixity <= 0.3, "caps active");
979
+ add("capability-honesty", new CapabilityGate().promptAddendum().includes("NOT AVAILABLE") && new CapabilityGate().promptAddendum().includes("Do not claim tool execution"), "unavailable disclosed");
980
+
981
+ const rolled = rollV2({ seed: 42, userProblem: "Prove X.", domain: "mathematics" });
982
+ add("roll-v2-end-to-end", rolled.seed === 42 && rolled.prompt.includes("DOMAIN PACK: MATHEMATICS") && rolled.prompt.includes("CAPABILITY REALITY GATE"), rolled.persona.name);
983
+ const critical = rollV2({ seed: 42, userProblem: "Should we prescribe X?", domain: "medicine", risk: "critical" });
984
+ add("roll-v2-high-stakes", critical.prompt.includes("HIGH-STAKES SAFETY GATE") && critical.genome.termination_resistance <= 0.5, "safety addendum");
985
+ const exported = innovationGenomeV2ToJSON(rolled) as Record<string, unknown>;
986
+ add("json-export", exported.version === "v2.0" && exported.seed === 42, JSON.stringify(exported).slice(0, 80));
987
+ add("schema-domains", new Set(INNOVATION_GENOME_V2_SCHEMA.properties.domain.enum).size === Object.keys(DOMAIN_PACKS).length, `domains=${Object.keys(DOMAIN_PACKS).length}`);
988
+
989
+ const evaluated = await evolveGeneration(
990
+ new GenomeEntry({ seed: 42, genome: base, fitness: low }),
991
+ (genome) => new FitnessVector(genome.novelty_vs_utility, genome.world_contact, genome.artifact_concreteness, genome.adversarial_intensity),
992
+ { count: 5, operationSeed: 100 },
993
+ );
994
+ add("evaluator-driven-evolution", evaluated.length === 5 && evaluated.every((entry) => entry.lineage[0] === 42), `children=${evaluated.length}`);
995
+ const population = buildExplorationPopulationV2(rolled, 6);
996
+ add("live-exploration-population", population.length === 6 && new Set(population.map((branch) => branch.mutation)).size === 6, `branches=${population.length}`);
997
+ add("population-no-fake-fitness", compileExplorationPortfolioV2(rolled).includes("no branch has inferred fitness"), "fitness honesty explicit");
998
+ add("v1-invariance", Object.keys(seedToGenome(42)).length === 21, "v1 API unchanged");
999
+
1000
+ return { ok: checks.every((check) => check.passed), checks };
1001
+ }