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,223 @@
1
+ /**
2
+ * Adaptive SLOOP Runner — v2
3
+ *
4
+ * Strategy selection based on model intelligence (Arena Elo-aligned):
5
+ *
6
+ * NATIVE MODE (intel ≥ NATIVE_THRESHOLD, default 85):
7
+ * One single LLM call produces the entire report with SLOOP section
8
+ * structure preserved (## headings). Fast, lowest memory overhead.
9
+ * N-Deep can still process it section-by-section via the digest path.
10
+ *
11
+ * SECTIONED MODE (intel < NATIVE_THRESHOLD):
12
+ * Original streaming section-per-call approach. Each section is
13
+ * generated independently; prior summaries provide continuity.
14
+ * Memory: O(max_section_size) peak per call vs O(full_report) for native.
15
+ *
16
+ * The choice is transparent — callers always receive { finalText, trace, calls }.
17
+ * N-Deep downstream uses buildDraftDigest() regardless of how the draft was
18
+ * produced, so the two modes are fully interchangeable as N-Deep input.
19
+ */
20
+ import { generateSynthesizedResponse, type GenerateParams } from "./models";
21
+ import { buildReportSpec } from "./sloop";
22
+ import type { PipelineTrace } from "./pipeline";
23
+ import { settleHeap } from "./memory-governor";
24
+ import { intelligenceOf } from "./model-intelligence";
25
+
26
+ export interface SloopRunResult {
27
+ finalText: string;
28
+ trace: PipelineTrace[];
29
+ calls: number;
30
+ mode: "native" | "sectioned";
31
+ }
32
+
33
+ /** Models at or above this score produce the full report in one call. */
34
+ const NATIVE_THRESHOLD = 85;
35
+
36
+ /**
37
+ * Hard ceiling on pages for native single-call mode. Frontier models have an
38
+ * 8192 token output limit; 8 pages is the upper bound where native can still
39
+ * succeed on strong models. A completeness gate below catches truncation and
40
+ * falls back to sectioned mode if native output returns only late sections.
41
+ */
42
+ const NATIVE_PAGE_CEILING = 8;
43
+
44
+ function compactSources(sources: { title: string; url: string; content: string }[], sectionIndex: number) {
45
+ if (sources.length === 0) return [];
46
+ const start = (sectionIndex * 3) % Math.max(1, sources.length);
47
+ const rotated = [...sources.slice(start), ...sources.slice(0, start)];
48
+ return rotated.slice(0, 8).map(s => ({ title: s.title, url: s.url, content: (s.content || "").slice(0, 700) }));
49
+ }
50
+
51
+ function allSources(sources: { title: string; url: string; content: string }[]) {
52
+ // For native mode: provide all sources but cap content more aggressively
53
+ // to prevent the single prompt from blowing up the context window.
54
+ return sources.slice(0, 16).map(s => ({
55
+ title: s.title, url: s.url,
56
+ content: (s.content || "").slice(0, 1500),
57
+ }));
58
+ }
59
+
60
+ type SloopSection = ReturnType<typeof buildReportSpec>["sections"][number];
61
+
62
+ function sectionCoverage(text: string, sections: SloopSection[]): { hits: number; required: number; firstOk: boolean } {
63
+ const lower = text.toLowerCase();
64
+ const hits = sections.filter(s => lower.includes(s.name.toLowerCase())).length;
65
+ const required = Math.max(3, Math.ceil(sections.length * 0.7));
66
+ const firstIdx = lower.indexOf(sections[0]?.name.toLowerCase() ?? "");
67
+ return { hits, required, firstOk: firstIdx >= 0 && firstIdx < 1200 };
68
+ }
69
+
70
+ function chooseArchetype(templateId?: string): string {
71
+ if (templateId === "NIH-GRANT-SRF" || templateId === "OMEGA-SCIENCE") return "scientific-academic";
72
+ if (templateId === "OMEGA-DILIGENCE") return "audit-assurance";
73
+ if (templateId === "OMEGA-BUILD") return "implementation-tech";
74
+ if (templateId === "OMEGA-DISCOVERY") return "market-commercial";
75
+ if (templateId === "OMEGA-COMPLIANCE") return "audit-assurance";
76
+ return "decision-strategy";
77
+ }
78
+
79
+ // ─── Native mode: one call, full report ───────────────────────────────────────
80
+
81
+ async function runNativeReport(opts: {
82
+ query: string;
83
+ baseParams: GenerateParams;
84
+ sources: { title: string; url: string; content: string }[];
85
+ templateId?: string;
86
+ pages: number;
87
+ onTrace?: (t: PipelineTrace) => void;
88
+ onDebug?: (msg: string) => void;
89
+ }): Promise<SloopRunResult> {
90
+ const spec = buildReportSpec(chooseArchetype(opts.templateId), opts.templateId ?? null);
91
+ const targetSections = spec.sections.slice(0, Math.max(4, Math.min(spec.sections.length, opts.pages + 2)));
92
+ const sectionList = targetSections.map((s, i) => `${i + 1}. ## ${s.name}`).join("\n");
93
+ const wordTarget = Math.max(300, opts.pages * 650);
94
+
95
+ const prompt = [
96
+ `Produce a COMPLETE, FULLY WRITTEN ${opts.pages}-page report using the SLOOP structure below.`,
97
+ `Use EXACTLY these section headings (## prefix). Do not add, rename, or merge sections.`,
98
+ `Target total length: ~${wordTarget} words. Write each section with full substance — no stubs, no placeholders, no meta-commentary.`,
99
+ `Use evidence from the retrieved sources. Where gaps exist, write professional investigator-owned analysis.`,
100
+ ``,
101
+ `SLOOP SECTIONS (generate all of them):`,
102
+ sectionList,
103
+ ``,
104
+ `USER ASK: ${opts.query}`,
105
+ ].filter(Boolean).join("\n");
106
+
107
+ opts.onDebug?.(`[SLOOP native] single-call for ${targetSections.length} sections (~${wordTarget} words)`);
108
+ const text = await generateSynthesizedResponse({
109
+ ...opts.baseParams,
110
+ userMessage: prompt,
111
+ retrievedWebData: allSources(opts.sources),
112
+ conversationHistory: [],
113
+ });
114
+
115
+ const cleaned = text.trim();
116
+ const coverage = sectionCoverage(cleaned, targetSections);
117
+ const minChars = Math.max(1200, opts.pages * 1500);
118
+ if (coverage.hits < coverage.required || !coverage.firstOk || cleaned.length < minChars) {
119
+ opts.onDebug?.(`[SLOOP native] incomplete/truncated (${coverage.hits}/${targetSections.length} headings, firstOk=${coverage.firstOk}, chars=${cleaned.length}) — falling back to sectioned mode`);
120
+ const fallback = await runSectionedReport(opts);
121
+ return { ...fallback, calls: fallback.calls + 1 };
122
+ }
123
+ const t: PipelineTrace = {
124
+ stage: 4,
125
+ label: `SLOOP native: ${targetSections.length} sections, ${cleaned.length} chars`,
126
+ ts: Date.now(),
127
+ ok: cleaned.length > 200,
128
+ data: { chars: cleaned.length, sections: targetSections.length, mode: "native" },
129
+ };
130
+ opts.onTrace?.(t);
131
+ opts.onDebug?.(`[SLOOP native] complete: ${cleaned.length} chars`);
132
+
133
+ return { finalText: String(cleaned), trace: [t], calls: 1, mode: "native" };
134
+ }
135
+
136
+ // ─── Sectioned mode: stream section-by-section ────────────────────────────────
137
+
138
+ async function runSectionedReport(opts: {
139
+ query: string;
140
+ baseParams: GenerateParams;
141
+ sources: { title: string; url: string; content: string }[];
142
+ templateId?: string;
143
+ pages: number;
144
+ onTrace?: (t: PipelineTrace) => void;
145
+ onDebug?: (msg: string) => void;
146
+ }): Promise<SloopRunResult> {
147
+ const spec = buildReportSpec(chooseArchetype(opts.templateId), opts.templateId ?? null);
148
+ const targetSections = spec.sections.slice(0, Math.max(4, Math.min(spec.sections.length, opts.pages + 2)));
149
+ const trace: PipelineTrace[] = [];
150
+ let calls = 0;
151
+ let consolidated = "";
152
+ const priorSummaries: string[] = [];
153
+
154
+ for (let i = 0; i < targetSections.length; i++) {
155
+ const section = targetSections[i];
156
+ const evidence = compactSources(opts.sources, i);
157
+ const prompt = [
158
+ `Generate ONLY the "${section.name}" section for the report requested by the user.`,
159
+ `This is SLOOP section ${i + 1}/${targetSections.length}; do not generate other sections.`,
160
+ `No placeholders, no meta-commentary, no raw [Source N] tokens.`,
161
+ `Use concrete, specific content from the evidence. If a detail is missing, write a professional investigator-owned note, not an AI refusal.`,
162
+ `Target depth: ${Math.max(250, Math.round((opts.pages * 700) / targetSections.length))} words for this section.`,
163
+ section.requiredFields?.length ? `Required fields: ${section.requiredFields.join(", ")}` : "",
164
+ `Prior section summaries for continuity:\n${priorSummaries.slice(-3).join("\n")}`,
165
+ `USER ASK: ${opts.query}`,
166
+ ].filter(Boolean).join("\n\n");
167
+
168
+ opts.onDebug?.(`[SLOOP sectioned] section ${i + 1}/${targetSections.length}: ${section.name}`);
169
+ const text = await generateSynthesizedResponse({
170
+ ...opts.baseParams,
171
+ userMessage: prompt,
172
+ retrievedWebData: evidence,
173
+ conversationHistory: [],
174
+ });
175
+ calls++;
176
+ const cleaned = text.trim();
177
+ const block = `## ${section.name}\n\n${cleaned}`;
178
+ consolidated = consolidated ? `${consolidated}\n\n${block}` : block;
179
+ const preview = String(cleaned.slice(0, 200));
180
+ opts.onDebug?.(`[SLOOP preview ${i + 1}/${targetSections.length}] ${preview}${cleaned.length > 200 ? "..." : ""}`);
181
+ priorSummaries.push(String(`${section.name}: ${cleaned.slice(0, 240).replace(/\s+/g, " ")}`));
182
+ const t: PipelineTrace = {
183
+ stage: 4 + (i + 1) / 100,
184
+ label: `SLOOP section: ${section.name}`,
185
+ ts: Date.now(),
186
+ ok: cleaned.length > 80,
187
+ data: { chars: cleaned.length, preview },
188
+ };
189
+ trace.push(t);
190
+ opts.onTrace?.(t);
191
+ await settleHeap(12);
192
+ }
193
+
194
+ return { finalText: String(consolidated), trace, calls, mode: "sectioned" };
195
+ }
196
+
197
+ // ─── Public API ───────────────────────────────────────────────────────────────
198
+
199
+ export async function runSloopReport(opts: {
200
+ query: string;
201
+ baseParams: GenerateParams;
202
+ sources: { title: string; url: string; content: string }[];
203
+ templateId?: string;
204
+ pages: number;
205
+ onTrace?: (t: PipelineTrace) => void;
206
+ onDebug?: (msg: string) => void;
207
+ }): Promise<SloopRunResult> {
208
+ const intel = intelligenceOf(opts.baseParams.model);
209
+ // Native mode requires BOTH (a) strong-enough model AND (b) requested pages
210
+ // within the 8192-token output ceiling. For >NATIVE_PAGE_CEILING pages,
211
+ // ALWAYS fall back to sectioned mode to prevent silent truncation
212
+ // (the "only appendix returned" failure mode observed in field testing).
213
+ const wouldTruncate = opts.pages > NATIVE_PAGE_CEILING;
214
+ const useNative = intel >= NATIVE_THRESHOLD && !wouldTruncate;
215
+ opts.onDebug?.(
216
+ `[SLOOP] model=${opts.baseParams.model} intel=${intel} pages=${opts.pages} → mode=${useNative ? "native (single-call)" : wouldTruncate ? `sectioned (pages ${opts.pages} > ${NATIVE_PAGE_CEILING} native ceiling — avoiding output truncation)` : "sectioned (stream)"}`
217
+ );
218
+ if (useNative) {
219
+ return runNativeReport(opts);
220
+ } else {
221
+ return runSectionedReport(opts);
222
+ }
223
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Persistent OMEGA-aware SLOOP runner.
3
+ * Fixes the package runner's lossy generic mapping and page-based section drop.
4
+ */
5
+ export * from "./sloop-runner.base";
6
+ import { runSloopReport as baseRunSloopReport, type SloopRunResult } from "./sloop-runner.base";
7
+ import { generateSynthesizedResponse, type GenerateParams } from "@/lib/models";
8
+ import type { PipelineTrace } from "@/lib/pipeline";
9
+ import { intelligenceOf } from "@/lib/model-intelligence";
10
+ import { settleHeap } from "@/lib/memory-governor";
11
+ import { buildAdaptiveTemplateContract, getOmegaTemplate } from "./omega-templates";
12
+
13
+ type Opts = {
14
+ query: string;
15
+ baseParams: GenerateParams;
16
+ sources: { title: string; url: string; content: string }[];
17
+ templateId?: string;
18
+ pages: number;
19
+ onTrace?: (t: PipelineTrace) => void;
20
+ onDebug?: (msg: string) => void;
21
+ };
22
+
23
+ const NATIVE_THRESHOLD = 85;
24
+ const NATIVE_PAGE_CEILING = 8;
25
+
26
+ function sourceSlice(sources: Opts["sources"], sectionIndex = 0, max = 10) {
27
+ if (!sources.length) return [];
28
+ const start = (sectionIndex * 3) % sources.length;
29
+ return [...sources.slice(start), ...sources.slice(0, start)].slice(0, max).map(s => ({ ...s, content: (s.content || "").slice(0, 900) }));
30
+ }
31
+
32
+ function sectionCoverage(text: string, headings: string[]) {
33
+ const lower = text.toLowerCase();
34
+ const hits = headings.filter(h => lower.includes(h.toLowerCase())).length;
35
+ const empty = headings.filter(h => {
36
+ const at = lower.indexOf(h.toLowerCase());
37
+ if (at < 0) return false;
38
+ const next = headings.map(x => lower.indexOf(x.toLowerCase(), at + h.length)).filter(x => x > at).sort((a, b) => a - b)[0] ?? text.length;
39
+ return text.slice(at + h.length, next).replace(/\s/g, "").length < 40;
40
+ });
41
+ return { hits, empty };
42
+ }
43
+
44
+ async function sectioned(opts: Opts, contract: string): Promise<SloopRunResult> {
45
+ const t = getOmegaTemplate(opts.templateId)!;
46
+ const trace: PipelineTrace[] = [];
47
+ const summaries: string[] = [];
48
+ const targetWords = Math.max(700, opts.pages * 550);
49
+ const mainCount = Math.max(1, t.sections.filter(s => !/^§A/.test(s.id)).length);
50
+ const wordsPer = Math.max(90, Math.floor(targetWords / mainCount));
51
+ let full = "";
52
+ for (let i = 0; i < t.sections.length; i++) {
53
+ const s = t.sections[i];
54
+ const prompt = [
55
+ `Write ONLY the "${s.title}" section of a ${t.id} report.`,
56
+ `Section contract: ${s.hint}`,
57
+ `Target: ${/^§A/.test(s.id) ? "a compact evidence/method appendix" : `about ${wordsPer} words`}.`,
58
+ "Use the exact heading shown below. No other report sections. No placeholders, invented evidence, fake interviews, fake calculations, or bare headings.",
59
+ `Exact heading: ## ${s.title}`,
60
+ contract,
61
+ summaries.length ? `Prior-section continuity summaries:\n${summaries.slice(-3).join("\n")}` : "",
62
+ `USER ASK: ${opts.query}`,
63
+ ].filter(Boolean).join("\n\n");
64
+ opts.onDebug?.(`[SLOOP OMEGA sectioned] ${i + 1}/${t.sections.length}: ${s.title}`);
65
+ const raw = await generateSynthesizedResponse({ ...opts.baseParams, userMessage: prompt, retrievedWebData: sourceSlice(opts.sources, i), conversationHistory: [] });
66
+ const cleaned = raw.trim().replace(new RegExp(`^#{1,6}\\s*${s.title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*`, "i"), "").trim();
67
+ const block = `## ${s.title}\n\n${cleaned || "[DATA GAP] Section generation returned no substantive content."}`;
68
+ full += (full ? "\n\n" : "") + block;
69
+ summaries.push(`${s.title}: ${cleaned.slice(0, 220).replace(/\s+/g, " ")}`);
70
+ const tr: PipelineTrace = { stage: 4 + (i + 1) / 100, label: `SLOOP OMEGA section: ${s.title}`, ts: Date.now(), ok: cleaned.length >= 40, data: { chars: cleaned.length, preview: cleaned.slice(0, 160) } };
71
+ trace.push(tr); opts.onTrace?.(tr);
72
+ await settleHeap(12);
73
+ }
74
+ return { finalText: full, trace, calls: t.sections.length, mode: "sectioned" };
75
+ }
76
+
77
+ export async function runSloopReport(opts: Opts): Promise<SloopRunResult> {
78
+ const template = getOmegaTemplate(opts.templateId);
79
+ if (!template) return baseRunSloopReport(opts);
80
+ const contract = buildAdaptiveTemplateContract({ templateId: opts.templateId, targetPages: opts.pages, evidenceAvailable: opts.sources.length > 0 });
81
+ const native = intelligenceOf(opts.baseParams.model) >= NATIVE_THRESHOLD && opts.pages <= NATIVE_PAGE_CEILING;
82
+ if (!native) return sectioned(opts, contract);
83
+
84
+ const headings = template.sections.map(s => s.title);
85
+ const wordTarget = Math.max(700, opts.pages * 550);
86
+ opts.onDebug?.(`[SLOOP OMEGA native] ${template.id}: ALL ${headings.length} sections, ~${wordTarget} words`);
87
+ const raw = await generateSynthesizedResponse({
88
+ ...opts.baseParams,
89
+ userMessage: `${contract}\n\nWrite the complete report now. Include ALL contracted sections in order, fully written. USER ASK: ${opts.query}`,
90
+ retrievedWebData: sourceSlice(opts.sources, 0, 16),
91
+ conversationHistory: [],
92
+ });
93
+ const text = raw.trim();
94
+ const coverage = sectionCoverage(text, headings);
95
+ const minChars = Math.max(1200, opts.pages * 1300);
96
+ if (coverage.hits < headings.length || coverage.empty.length || text.length < minChars) {
97
+ opts.onDebug?.(`[SLOOP OMEGA native] incomplete (${coverage.hits}/${headings.length}, empty=${coverage.empty.join(",") || "none"}, chars=${text.length}) — sectioned fallback`);
98
+ const fallback = await sectioned(opts, contract);
99
+ return { ...fallback, calls: fallback.calls + 1 };
100
+ }
101
+ const tr: PipelineTrace = { stage: 4, label: `SLOOP OMEGA native: ${headings.length} sections`, ts: Date.now(), ok: true, data: { chars: text.length, sections: headings.length } };
102
+ opts.onTrace?.(tr);
103
+ return { finalText: text, trace: [tr], calls: 1, mode: "native" };
104
+ }
@@ -0,0 +1,114 @@
1
+ // MODULE D — SLOOP: Small-LLM Orchestration for Output Production.
2
+ // Decomposes a report into per-section sessions, each fitting inside a small
3
+ // model's context window (default 4096 tokens). Pure orchestration code;
4
+ // the LLM is called per section, never given the whole report at once.
5
+
6
+ export interface SectionSpec {
7
+ id: string;
8
+ name: string;
9
+ promptTemplate: string; // small, focused prompt for THIS section only
10
+ evidenceChunks: string[]; // IDs of evidence chunks to inject
11
+ dependsOn: string[]; // sections whose summaries we need
12
+ outputSchema?: string; // JSON schema name (for structured decoding)
13
+ maxOutputTokens: number;
14
+ requiredFields?: string[];
15
+ }
16
+
17
+ export interface ReportSpec {
18
+ reportId: string;
19
+ template: string; // OMEGA archetype id
20
+ styleOverride: string | null;
21
+ sections: SectionSpec[];
22
+ assemblyOrder: string[];
23
+ calculations?: Record<string, { fn: string; inputsFrom: string }>;
24
+ }
25
+
26
+ export interface SessionBudget {
27
+ systemPromptTok: number;
28
+ contextSummaryTok: number;
29
+ evidenceTok: number;
30
+ outputReserveTok: number;
31
+ safetyMarginTok: number;
32
+ }
33
+
34
+ export const DEFAULT_BUDGET_4K: SessionBudget = {
35
+ systemPromptTok: 600,
36
+ contextSummaryTok: 500,
37
+ evidenceTok: 1200,
38
+ outputReserveTok: 1200,
39
+ safetyMarginTok: 596,
40
+ };
41
+
42
+ export function totalBudget(b: SessionBudget): number {
43
+ return b.systemPromptTok + b.contextSummaryTok + b.evidenceTok + b.outputReserveTok + b.safetyMarginTok;
44
+ }
45
+
46
+ // Rough token estimate (≈4 chars / token, std English heuristic).
47
+ export const estTokens = (s: string) => Math.max(1, Math.round(s.length / 4));
48
+
49
+ export interface ModelProfile {
50
+ id: string;
51
+ name: string;
52
+ ctxTokens: number;
53
+ budget: SessionBudget;
54
+ notes: string;
55
+ }
56
+
57
+ export const MODEL_PROFILES: ModelProfile[] = [
58
+ { id: "apple-fm", name: "Apple Foundation Model (on-device)", ctxTokens: 4096, budget: DEFAULT_BUDGET_4K, notes: "Standard SLOOP loop." },
59
+ { id: "phi-3-mini", name: "Phi-3 mini", ctxTokens: 4096, budget: DEFAULT_BUDGET_4K, notes: "Same budget; use JSON mode." },
60
+ { id: "qwen2-5-3b", name: "Qwen2.5 3B", ctxTokens: 4096, budget: DEFAULT_BUDGET_4K, notes: "Standard SLOOP loop." },
61
+ { id: "gemma-2b", name: "Gemma 2B", ctxTokens: 8192, budget: { ...DEFAULT_BUDGET_4K, evidenceTok: 2400, outputReserveTok: 2400, safetyMarginTok: 600 }, notes: "Double evidence chunks." },
62
+ { id: "llama-3-2-1b", name: "Llama 3.2 1B", ctxTokens: 8192, budget: { ...DEFAULT_BUDGET_4K, evidenceTok: 2400, outputReserveTok: 2000, safetyMarginTok: 800 }, notes: "Add verification session." },
63
+ { id: "phi-4", name: "Phi-4", ctxTokens: 16384, budget: { ...DEFAULT_BUDGET_4K, evidenceTok: 6000, outputReserveTok: 4000, safetyMarginTok: 2000 }, notes: "Can batch 2-3 sections." },
64
+ { id: "mistral-7b", name: "Mistral 7B", ctxTokens: 32768, budget: { ...DEFAULT_BUDGET_4K, evidenceTok: 12000, outputReserveTok: 8000, safetyMarginTok: 4000 }, notes: "Can batch 4-6 sections." },
65
+ ];
66
+
67
+ export interface EscalationTrigger { id: string; label: string; }
68
+ export const ESCALATION_TRIGGERS: EscalationTrigger[] = [
69
+ { id: "world-knowledge", label: "Task requires world knowledge not in evidence chunks" },
70
+ { id: "deep-reasoning", label: "Section requires >3 inference steps" },
71
+ { id: "cross-synthesis", label: "Creative synthesis across >4 evidence sources" },
72
+ { id: "tier-5", label: "User explicitly requested deep / Tier-5 mode" },
73
+ { id: "contradiction", label: "Verification detected contradictions requiring judgment" },
74
+ { id: "crisis-legal", label: "OMEGA-CRISIS with privilege / legal implications" },
75
+ ];
76
+
77
+ export const SLOOP_PRINCIPLES = [
78
+ "Calculations are deterministic, not LLM-generated",
79
+ "Each session is stateless (memory is in controller-side summaries)",
80
+ "Structured output only (JSON schema → prose formatter)",
81
+ "Verification is controller-side, not another LLM pass",
82
+ "Graceful degradation: retry once, then emit [INCOMPLETE] tag",
83
+ "Evidence pre-chunked and ranked by relevance",
84
+ ];
85
+
86
+ /** Build a default per-archetype section pipeline. */
87
+ export function buildReportSpec(archetypeId: string, styleOverride: string | null = null): ReportSpec {
88
+ const orderByArchetype: Record<string, string[]> = {
89
+ "decision-strategy": ["bluf", "situation", "diagnostic", "options", "recommendation", "implementation", "risks", "appendix"],
90
+ "investment-financial": ["thesis", "asset", "market", "commercial-dd", "financial-dd", "value-plan", "valuation", "risks", "decision-pkg", "appendix"],
91
+ "implementation-tech": ["summary", "current-state", "target-state", "portfolio", "operating-model", "roadmap", "business-case", "risk-rai", "adoption", "appendix"],
92
+ "audit-assurance": ["assurance-summary", "scope", "methodology", "findings", "risk", "controls", "recommendations", "governance", "appendix"],
93
+ "scientific-academic": ["abstract", "background", "aims", "methods", "results", "discussion", "impact", "compliance", "references", "supplementary"],
94
+ "policy-public": ["policy-summary", "mandate", "diagnostic", "evidence", "options", "impact", "preferred", "implementation", "annexes"],
95
+ "market-commercial": ["sector-summary", "market-def", "sizing", "demand", "competitive", "economics", "trends", "implications", "appendix"],
96
+ };
97
+ const sections = (orderByArchetype[archetypeId] ?? orderByArchetype["decision-strategy"]).map<SectionSpec>(id => ({
98
+ id, name: id.replace(/-/g, " "),
99
+ promptTemplate: `Generate the "${id}" section only. Do not echo other sections. Output JSON matching the section schema.`,
100
+ evidenceChunks: [], dependsOn: [], maxOutputTokens: 800,
101
+ }));
102
+ return {
103
+ reportId: `r-${Date.now().toString(36)}`, template: archetypeId, styleOverride,
104
+ sections, assemblyOrder: sections.map(s => s.id),
105
+ };
106
+ }
107
+
108
+ /** Estimate how many sessions a model needs for a given report spec. */
109
+ export function plannedSessions(spec: ReportSpec, profile: ModelProfile): { sessions: number; words: number } {
110
+ const sectionsPerSession = profile.ctxTokens >= 16384 ? 2 : profile.ctxTokens >= 32000 ? 4 : 1;
111
+ const sessions = Math.ceil(spec.sections.length / sectionsPerSession);
112
+ const wordsPerSection = Math.round(profile.budget.outputReserveTok * 0.75); // tokens -> words
113
+ return { sessions, words: spec.sections.length * wordsPerSection };
114
+ }
@@ -0,0 +1,82 @@
1
+ import type { DriverId } from "./resource-estimator";
2
+
3
+ export interface AdapterDescriptor {
4
+ id: DriverId;
5
+ label: string;
6
+ role: string;
7
+ anchorRequirement: "optional" | "preferred" | "required";
8
+ context: string;
9
+ toolMode: string;
10
+ degradePath: string[];
11
+ bestFor: string;
12
+ caveat: string;
13
+ }
14
+
15
+ export const ADAPTERS: AdapterDescriptor[] = [
16
+ {
17
+ id: "frontier",
18
+ label: "Frontier cloud model",
19
+ role: "Full federation lead, synthesis judge, and fallback worker.",
20
+ anchorRequirement: "optional",
21
+ context: "Large enough for broad briefs; still benefits from anchor-first retrieval.",
22
+ toolMode: "Native or API-level tool routing, model-dependent.",
23
+ degradePath: ["full", "verified-lite", "anchor-only"],
24
+ bestFor: "Tier 4-5 exhaustive runs and high-stakes synthesis.",
25
+ caveat: "External verification is still required; self-evaluation is not treated as proof.",
26
+ },
27
+ {
28
+ id: "gemma4-31b",
29
+ label: "Gemma 4 31B",
30
+ role: "Primary small-frontier orchestrator with high-context synthesis.",
31
+ anchorRequirement: "preferred",
32
+ context: "Designed in this app as a long-context anchor-brief reader.",
33
+ toolMode: "Gemini API generateContent path, with model availability checked per API key.",
34
+ degradePath: ["full", "lite", "anchor-only-rag"],
35
+ bestFor: "Tier 2-4 chat and dashboard runs when a Google AI key supports the model.",
36
+ caveat: "The app wires the requested model id. Runtime availability is confirmed by the provider response/model list.",
37
+ },
38
+ {
39
+ id: "qwen3.6",
40
+ label: "Qwen 3.6 class adapter",
41
+ role: "Reasoning-heavy worker and falsification specialist.",
42
+ anchorRequirement: "preferred",
43
+ context: "Configured as a large-brief worker when available behind a compatible gateway.",
44
+ toolMode: "Structured JSON harness if native function calling is unavailable.",
45
+ degradePath: ["worker", "sequential-worker", "anchor-only-rag"],
46
+ bestFor: "Hard verification plans, contradiction analysis, and boundary searches.",
47
+ caveat: "No direct connector is installed yet; descriptor is ready for an OpenAI-compatible gateway.",
48
+ },
49
+ {
50
+ id: "gemma4-e4b",
51
+ label: "Gemma 4 E4B class adapter",
52
+ role: "Laptop or browser worker for low-cost anchor-grounded runs.",
53
+ anchorRequirement: "required",
54
+ context: "Uses chunked baseline briefs rather than broad free-recall.",
55
+ toolMode: "Constrained JSON harness, one worker at a time.",
56
+ degradePath: ["lite", "single-worker", "anchor-only-rag"],
57
+ bestFor: "Tier 0-2 local/private research with Kiwix/Wikidata anchors.",
58
+ caveat: "Small models must not assert unsupported technical facts.",
59
+ },
60
+ {
61
+ id: "apple-ondevice",
62
+ label: "Apple on-device class adapter",
63
+ role: "Private-data handler and offline worker.",
64
+ anchorRequirement: "required",
65
+ context: "Local files and local anchor store first; cloud optional.",
66
+ toolMode: "No remote tool calls unless user explicitly enables cloud access.",
67
+ degradePath: ["private-worker", "anchor-only-rag", "abstain"],
68
+ bestFor: "Sensitive notes, local documents, and privacy-first summaries.",
69
+ caveat: "Exact model capability is treated as runtime-probed, not assumed.",
70
+ },
71
+ {
72
+ id: "bonsai-8b",
73
+ label: "Bonsai 8B class adapter",
74
+ role: "Extreme-edge retrieval shell over a verified anchor.",
75
+ anchorRequirement: "required",
76
+ context: "Tiny context strategy: search, read one chunk, verify, then synthesize.",
77
+ toolMode: "Strict extractor mode; no free-form factual recall.",
78
+ degradePath: ["extractor", "anchor-only-rag", "abstain"],
79
+ bestFor: "Phone-sized/offline fact lookup and short anchored answers.",
80
+ caveat: "Full-power quality comes from the anchor and verifiers, not from parametric recall.",
81
+ },
82
+ ];
@@ -0,0 +1,86 @@
1
+ /**
2
+ * SSCP Receipt + Merkle seal — REAL cryptography via Web Crypto API (SHA-256).
3
+ * No mock hashes. Every receipt is reproducible from its inputs.
4
+ *
5
+ * A receipt binds together the claim ledger, tool log, gate results, and
6
+ * evidence index into a Merkle tree, then exposes the root hash as the
7
+ * audit seal printed in the OMEGA unified header block.
8
+ */
9
+
10
+ export type EvidenceTier = "CTX" | "SRC" | "TOOL" | "DERIV";
11
+
12
+ export interface SSCPLeaf {
13
+ domain: string; // e.g. "claim", "tool", "gate", "evidence"
14
+ text: string; // canonical content of the leaf
15
+ status: string; // e.g. VERIFIED / CONFIRMED / PASS
16
+ }
17
+
18
+ export interface SSCPReceipt {
19
+ stateRootHash: string;
20
+ claimLedgerRootHash: string;
21
+ toolLogRootHash: string;
22
+ gateRootHash: string;
23
+ evidenceTier: EvidenceTier;
24
+ leafCount: number;
25
+ hashAlg: "SHA-256";
26
+ tsUtc: number;
27
+ allGatesPass: boolean;
28
+ }
29
+
30
+ async function sha256Hex(input: string): Promise<string> {
31
+ const data = new TextEncoder().encode(input);
32
+ const buf = await crypto.subtle.digest("SHA-256", data);
33
+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
34
+ }
35
+
36
+ /** CT-style domain separation: leaf prefix 0x00, node prefix 0x01. */
37
+ async function merkleRoot(leaves: string[]): Promise<string> {
38
+ if (leaves.length === 0) return sha256Hex("EMPTY");
39
+ let level = await Promise.all(leaves.map((l) => sha256Hex("\x00" + l)));
40
+ while (level.length > 1) {
41
+ const next: string[] = [];
42
+ for (let i = 0; i < level.length; i += 2) {
43
+ const a = level[i];
44
+ const b = i + 1 < level.length ? level[i + 1] : level[i];
45
+ next.push(await sha256Hex("\x01" + a + b));
46
+ }
47
+ level = next;
48
+ }
49
+ return level[0];
50
+ }
51
+
52
+ export interface BuildReceiptInput {
53
+ claims: SSCPLeaf[];
54
+ tools: SSCPLeaf[];
55
+ gates: SSCPLeaf[];
56
+ evidence: SSCPLeaf[];
57
+ evidenceTier: EvidenceTier;
58
+ allGatesPass: boolean;
59
+ }
60
+
61
+ const leafStr = (l: SSCPLeaf) => `${l.domain}|${l.status}|${l.text}`;
62
+
63
+ export async function buildSSCPReceipt(input: BuildReceiptInput): Promise<SSCPReceipt> {
64
+ const claimRoot = await merkleRoot(input.claims.map(leafStr));
65
+ const toolRoot = await merkleRoot(input.tools.map(leafStr));
66
+ const gateRoot = await merkleRoot(input.gates.map(leafStr));
67
+ const evidenceRoot = await merkleRoot(input.evidence.map(leafStr));
68
+ const stateRoot = await merkleRoot([claimRoot, toolRoot, gateRoot, evidenceRoot]);
69
+ return {
70
+ stateRootHash: stateRoot,
71
+ claimLedgerRootHash: claimRoot,
72
+ toolLogRootHash: toolRoot,
73
+ gateRootHash: gateRoot,
74
+ evidenceTier: input.evidenceTier,
75
+ leafCount: input.claims.length + input.tools.length + input.gates.length + input.evidence.length,
76
+ hashAlg: "SHA-256",
77
+ tsUtc: Date.now(),
78
+ allGatesPass: input.allGatesPass,
79
+ };
80
+ }
81
+
82
+ /** Short display form of a hash: first 8 + last 4. */
83
+ export function shortHash(h: string): string {
84
+ if (h.length <= 14) return h;
85
+ return `${h.slice(0, 8)}…${h.slice(-4)}`;
86
+ }