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,524 @@
1
+ /**
2
+ * UNIFIED ROLL — one seed, one archetype set, one directive.
3
+ * ---------------------------------------------------------------------------
4
+ * Type C net-new. Before this module SAGE (blueprint) and SAGA-OS v2
5
+ * (GenreSpec / Genesis-Grid / KALLOS) rolled on SEPARATE seeds from separate
6
+ * UI panels, so the panel could display a world the prompt never received.
7
+ * That is the "orphan component" failure. This module removes it:
8
+ *
9
+ * seed ──┬──> SAGE blueprint (rollSage)
10
+ * ├──> GenreSpec (DERIVED from the blueprint, not typed by hand)
11
+ * ├──> Genesis-Grid run (same seed)
12
+ * ├──> KALLOS report (over that run)
13
+ * └──> Reality grounding level (user-selected, not seeded)
14
+ * │
15
+ * └──> ONE ArchetypeSet ──> ONE directive ──> prompt
16
+ *
17
+ * Everything the UI shows is read from the SAME UnifiedRoll object that the
18
+ * prompt is compiled from, so display and output cannot diverge.
19
+ *
20
+ * RUNTIME HONESTY: pure and deterministic. No LLM, no network, no storage.
21
+ */
22
+
23
+ import {
24
+ rollSage, type SageBlueprint,
25
+ } from '@/lib/sage/engine.ts';
26
+ import {
27
+ compileGenreSpec, runGenesisGrid, computeKallos, wireCatalog,
28
+ buildWorldMap, buildCastGraph, modalShortcutTest,
29
+ type GenreSpec, type GridRun, type KallosReport, type ElementRecord,
30
+ type WorldMapPlace, type ModalShortcutReport,
31
+ } from "./saga-os-v2-engines";
32
+ import {
33
+ buildRealityDirective, realityLevel, type RealityLevel,
34
+ } from "./reality-grounding";
35
+ import {
36
+ compileGenreContract, defaultBuildRequest, loadBuildRequest, runMorphogenesis, generateNameSet,
37
+ compileCatalog, sha256Hex, type BuildRequest, type GenreContract, type MorphRun, type GeneratedName,
38
+ } from "./saga-os-v3-core";
39
+ import {
40
+ evaluateKallosV3, buildObligations, controlledRealizeScene, computeBuildId,
41
+ type KallosV3Report, type RealizationObligation,
42
+ } from "./saga-os-v3-release";
43
+ import {
44
+ buildStyleGenome, applyStylePack, loadStylePack, buildAureateDirective, genomeSummary,
45
+ type StyleGenome, type StylePackId,
46
+ } from "./saga-os-v4-aureate";
47
+
48
+ // Naming profile per genre family: one coherent phonology per book (v3 section 10.5).
49
+ const NAME_PROFILE_FOR_FAMILY: Record<string, string> = {
50
+ ROMANCE: "RIVERINE", THRILLER: "ARCHIVAL", MYSTERY: "ARCHIVAL", HORROR: "HIGHLAND", FANTASY: "HIGHLAND",
51
+ SF: "ARCHIVAL", LITERARY: "CANTON", HISTORICAL: "SALTMARCH", "FAMILY/SAGA": "SALTMARCH", "CHILDREN/YA": "RIVERINE", COMEDY: "CANTON",
52
+ };
53
+
54
+ // ── Genre inference from the SAGE blueprint (no free text needed) ───────────
55
+
56
+ /**
57
+ * Builds the GenreSpec request string FROM the blueprint so the v2 Genre Helm
58
+ * and the SAGE blueprint can never describe different books.
59
+ */
60
+ export function genreRequestFromBlueprint(bp: SageBlueprint): string {
61
+ const bits: string[] = [];
62
+ const t = `${bp.macro.name} ${bp.tone} ${bp.conflictAxis} ${bp.primarySetting.name} ${bp.theme}`.toLowerCase();
63
+
64
+ if (/horror|dread|monster|haunt/.test(t)) bits.push("horror");
65
+ else if (/mystery|detect|investigat|clue/.test(t)) bits.push("mystery");
66
+ else if (/thrill|chase|danger|pursuit/.test(t)) bits.push("thriller");
67
+ else if (/romance|love|courtship|marriage/.test(t)) bits.push("romance");
68
+ else if (/myth|god|magic|prophec|quest|monomyth|rebirth/.test(t)) bits.push("fantasy");
69
+ else if (/machine|technolog|space|future|science/.test(t)) bits.push("science fiction");
70
+ else if (/generation|inherit|family|succession/.test(t)) bits.push("family saga");
71
+ else if (/comic|comedy|farce|satire/.test(t)) bits.push("comedy");
72
+ else if (/history|historical|chronicle/.test(t)) bits.push("historical");
73
+ else bits.push("literary");
74
+
75
+ if (/institution|bureau|office|civic|maintenance/.test(t)) bits.push("maintenance");
76
+ if (/child|school|coming of age/.test(t)) bits.push("coming of age");
77
+
78
+ const V =
79
+ bp.chapters.length >= 40 ? 3 :
80
+ bp.chapters.length >= 20 ? 2 : 1;
81
+ if (V > 1) bits.push(`${V} book series`);
82
+ return bits.join(" ");
83
+ }
84
+
85
+ // ── The single canonical archetype set ──────────────────────────────────────
86
+
87
+ export type ArchetypeEntry = {
88
+ /** stable slot key used by the prompt */
89
+ slot: string;
90
+ /** human label shown in the UI */
91
+ label: string;
92
+ /** the chosen value */
93
+ value: string;
94
+ /** why it matters / how to use it in prose */
95
+ note: string;
96
+ /** provenance so nothing is unattributed */
97
+ source: "SAGE" | "SAGA-v2" | "SAGA-v3" | "SAGA-v4" | "EMPTY-SPACE" | "REALITY" | "ONOMASTRATA";
98
+ /** catalog id when there is one */
99
+ id?: string;
100
+ };
101
+
102
+ export type ArchetypeSet = {
103
+ seed: number;
104
+ entries: ArchetypeEntry[];
105
+ bySource: Record<string, number>;
106
+ /** the exact block injected into the prompt */
107
+ promptBlock: string;
108
+ };
109
+
110
+ function truncate(s: string, n: number): string {
111
+ const t = (s || "").replace(/\s+/g, " ").trim();
112
+ return t.length <= n ? t : `${t.slice(0, n - 1)}…`;
113
+ }
114
+
115
+ // ── UnifiedRoll ─────────────────────────────────────────────────────────────
116
+
117
+ export type UnifiedRollOpts = {
118
+ seed: number;
119
+ /**
120
+ * The EXACT blueprint to describe. When the packaged fiction runner calls us
121
+ * it already holds the blueprint the user previewed, and we must describe
122
+ * THAT one. Re-rolling from the seed is not equivalent: `rollSage` skips a
123
+ * `randPick` when `forceMacroId` is supplied, which shifts the whole PRNG
124
+ * stream and yields a different POV/tone/setting/cast — the prompt then
125
+ * described two different books at once (verified defect).
126
+ */
127
+ blueprint?: SageBlueprint;
128
+ chapters?: number;
129
+ wordsPerChapter?: number;
130
+ lengthId?: SageBlueprint["length"]["id"];
131
+ macroId?: string;
132
+ premise?: string;
133
+ cadenceSeed?: number;
134
+ /** 0..6 abstract → documentary. Not seeded: it is a user control. */
135
+ realityLevel?: number;
136
+ /** grid tick budget; derived from chapter count when omitted */
137
+ gridBudget?: number;
138
+ };
139
+
140
+ export type UnifiedRoll = {
141
+ seed: number;
142
+ blueprint: SageBlueprint;
143
+ spec: GenreSpec;
144
+ run: GridRun;
145
+ kallos: KallosReport;
146
+ reality: RealityLevel;
147
+ archetypes: ArchetypeSet;
148
+ world: WorldMapPlace[];
149
+ cast: ReturnType<typeof buildCastGraph>;
150
+ modal: ModalShortcutReport;
151
+ /** the complete block appended to every chapter prompt */
152
+ directive: string;
153
+ /** which subsystems actually contributed, for honest UI display */
154
+ contributions: { system: string; active: boolean; detail: string }[];
155
+ // v3 additions (P15)
156
+ request: BuildRequest;
157
+ requestSource: "studio" | "derived";
158
+ contract: GenreContract;
159
+ morph: MorphRun;
160
+ nameSet: GeneratedName[];
161
+ nameProfile: string;
162
+ kallosV3: KallosV3Report;
163
+ // v4 additions (B5) — AUREATE-SCRIBE
164
+ styleGenome: StyleGenome;
165
+ stylePack: StylePackId | null;
166
+ obligations: RealizationObligation[];
167
+ controlledSample: string;
168
+ buildId: string;
169
+ };
170
+
171
+ // Small LRU: the live panel, the studio (possibly on a lab seed) and the prompt
172
+ // compiler can each hold a different key; a single-entry memo would thrash.
173
+ const _cache = new Map<string, UnifiedRoll>();
174
+ const CACHE_MAX = 4;
175
+
176
+ /**
177
+ * THE single entry point. Same (seed, chapters, words, macro, premise, reality)
178
+ * always yields the same UnifiedRoll. Memoized on that key so the UI and the
179
+ * prompt compiler share one object without recomputing the CA every keystroke.
180
+ */
181
+ export function unifiedRoll(opts: UnifiedRollOpts): UnifiedRoll {
182
+ const seed = opts.seed >>> 0;
183
+ const rl = Math.max(0, Math.min(6, Math.round(opts.realityLevel ?? 4)));
184
+ const key = JSON.stringify([
185
+ seed, opts.chapters ?? null, opts.wordsPerChapter ?? null, opts.lengthId ?? null,
186
+ opts.macroId ?? null, opts.premise ?? null, opts.cadenceSeed ?? null, rl, opts.gridBudget ?? null,
187
+ // blueprint identity: two blueprints with the same seed can still differ
188
+ // (forceMacroId shifts the PRNG stream), so key on its distinguishing fields.
189
+ opts.blueprint
190
+ ? [opts.blueprint.macro.id, opts.blueprint.pov, opts.blueprint.tone,
191
+ opts.blueprint.primarySetting.id, opts.blueprint.protagonist.archetype.id,
192
+ opts.blueprint.chapters.length].join("|")
193
+ : null,
194
+ ]);
195
+ const hit = _cache.get(key);
196
+ if (hit) { _cache.delete(key); _cache.set(key, hit); return hit; }
197
+
198
+ // 1. SAGE blueprint — the spine. Use the caller's blueprint verbatim when
199
+ // given; only roll a fresh one for standalone UI use.
200
+ const blueprint = opts.blueprint ?? rollSage({
201
+ seed,
202
+ cadenceSeed: opts.cadenceSeed ?? seed,
203
+ premise: opts.premise,
204
+ lengthId: opts.lengthId,
205
+ chapters: opts.chapters,
206
+ wordsPerChapter: opts.wordsPerChapter,
207
+ forceMacroId: opts.macroId || undefined,
208
+ });
209
+
210
+ // 2. GenreSpec DERIVED from the blueprint (same book, guaranteed)
211
+ const spec = compileGenreSpec(genreRequestFromBlueprint(blueprint));
212
+
213
+ // 3. Genesis-Grid on the SAME seed; budget scaled to the chapter count
214
+ const gridBudget = Math.max(8, Math.min(96, opts.gridBudget ?? blueprint.chapters.length * 3 + 12));
215
+ const run = runGenesisGrid({ seed, spec, budget: gridBudget });
216
+
217
+ // 4. KALLOS over that run
218
+ const kallos = computeKallos({ run, profile: spec.kallosProfile });
219
+
220
+ // 5. Reality grounding
221
+ const reality = realityLevel(rl);
222
+
223
+ // 6. Derived views (same seed → deterministic names)
224
+ const world = buildWorldMap(run);
225
+ const cast = buildCastGraph(run);
226
+ const modal = modalShortcutTest(run);
227
+
228
+ // 6b. SAGA-OS v3: genre CONTRACT (studio-composed if present, else derived
229
+ // from the blueprint), MORPHOGENESIS lattice on the SAME user seed,
230
+ // ONOMASTRATA v3 audited names, KALLOS v3 with hard gates, BuildID.
231
+ const studioReq = loadBuildRequest();
232
+ const request: BuildRequest = studioReq
233
+ ? { ...studioReq, project: { ...studioReq.project, seed } }
234
+ : defaultBuildRequest(seed, spec.family);
235
+ const requestSource: UnifiedRoll["requestSource"] = studioReq ? "studio" : "derived";
236
+ const contract = compileGenreContract(request);
237
+ const morph = runMorphogenesis({
238
+ userSeed: seed, contract, spec,
239
+ targetWords: blueprint.chapters.reduce((a, c) => a + c.targetWords, 0),
240
+ lengthMode: spec.V >= 13 ? "serial" : spec.V >= 2 ? "saga" : blueprint.chapters.length <= 3 ? "short" : "novel",
241
+ budget: Math.max(8, Math.min(96, blueprint.chapters.length * 3 + 12)),
242
+ });
243
+ const nameProfile = NAME_PROFILE_FOR_FAMILY[contract.family] ?? "RIVERINE";
244
+ const ns = generateNameSet(morph.genome, nameProfile, {
245
+ PERSON: Math.max(3, cast.cast.filter((c) => c.kind === "agent").length),
246
+ INSTITUTION: Math.max(1, cast.cast.filter((c) => c.kind === "institution").length),
247
+ PLACE: Math.max(2, world.length), DOCUMENT: 1, LAW: 1, OFFICE: 1,
248
+ });
249
+ const nameSet = ns.names;
250
+ // Overlay the v3 audited names onto the v2 cast/world views so there is ONE
251
+ // canonical name set everywhere (UI, archetype set, prompt).
252
+ {
253
+ const persons = nameSet.filter((n) => n.nameClass === "PERSON");
254
+ const insts = nameSet.filter((n) => n.nameClass === "INSTITUTION");
255
+ const places = nameSet.filter((n) => n.nameClass === "PLACE");
256
+ let pi = 0, ii = 0;
257
+ for (const c of cast.cast) {
258
+ if (c.kind === "agent" && persons[pi]) c.name = persons[pi++].given;
259
+ else if (c.kind === "institution" && insts[ii]) c.name = insts[ii++].given;
260
+ }
261
+ world.forEach((w, i) => { if (places[i]) w.label = places[i].given; });
262
+ }
263
+ const controlledSample = morph.scenes.slice(0, 3).map((sc) => controlledRealizeScene(sc, nameSet).text).join(" ");
264
+ const obligations = buildObligations(morph, nameSet);
265
+ const kallosV3 = evaluateKallosV3({ run: morph, contract, controlledSample, scale: "K2" });
266
+
267
+ // 6c. SAGA-OS v4 AUREATE-SCRIBE: the style genotype. Derived from the SAME
268
+ // genre contract, so style, structure and reality all describe one book.
269
+ // The style pack is a user control (like the reality level) and is
270
+ // deliberately NOT seeded.
271
+ const stylePack = loadStylePack();
272
+ const styleGenome = applyStylePack(
273
+ buildStyleGenome(contract.dominant.key, contract.family),
274
+ stylePack,
275
+ );
276
+ const buildId = computeBuildId({
277
+ request, seedGenome: morph.genome, catalogManifestHash: compileCatalog().manifestHash,
278
+ genreProfileHash: sha256Hex(JSON.stringify(contract.mix)), audienceProfileHash: sha256Hex(contract.audienceSegment),
279
+ });
280
+
281
+ // 7. ONE archetype set
282
+ const archetypes = buildArchetypeSet({ seed, blueprint, spec, run, kallos, reality, world, cast, contract, morph, kallosV3, requestSource, styleGenome, stylePack });
283
+
284
+ // 8. ONE directive
285
+ const directive = buildUnifiedDirective({ blueprint, spec, run, kallos, reality, archetypes, contract, morph, kallosV3, styleGenome, stylePack });
286
+
287
+ const contributions = [
288
+ { system: "SAGE blueprint", active: true, detail: `${blueprint.macro.name} · ${blueprint.chapters.length} chapters · seed ${seed}` },
289
+ { system: "SAGA-OS v1 directive", active: true, detail: "throughline / pacing / promise discipline (package buildSagaDirectiveBlock)" },
290
+ { system: "SAGA-WIRE", active: true, detail: `${wireCatalog().length} catalog rows typed into 14 slot classes` },
291
+ { system: "GENRE HELM", active: true, detail: `${spec.family}/${spec.leaf} derived from the blueprint · CA ${spec.caRuleTableId}` },
292
+ { system: "GENESIS-GRID", active: true, detail: `${run.ticks.length} ticks → ${run.pattern} → ${run.endingFamily}` },
293
+ { system: "KALLOS", active: true, detail: `composite ${kallos.composite.toFixed(1)} · weakest ${kallos.weakest?.label ?? "n/a"}` },
294
+ { system: "ONOMASTRATA names", active: true, detail: `${cast.cast.length} cast + ${world.length} place names generated` },
295
+ { system: "Reality grounding", active: true, detail: `L${reality.id} ${reality.label}` },
296
+ { system: "v3 CATALOG-COMPILER", active: compileCatalog().releaseOk, detail: `${compileCatalog().compiledRows}/${compileCatalog().canonicalRows} rows compiled · manifest ${compileCatalog().manifestHash.slice(0, 10)}…` },
297
+ { system: "v3 GENRE HELM contract", active: true, detail: `${contract.mix.map((x) => `${x.key} ${Math.round(x.weight * 100)}%`).join(" + ")} · ${requestSource}` },
298
+ { system: "v3 MORPHOGENESIS-LATTICE", active: true, detail: `${morph.ticks.length} ticks → ${morph.attractor}${morph.attractorInTarget ? " (in target)" : ""} · ${morph.promises.length} promises · ${morph.volumes.length} vol` },
299
+ { system: "v3 ONOMASTRATA", active: nameSet.length > 0, detail: `${nameSet.length} audited names · profile ${nameProfile} · ${ns.audit.length} residual confusion findings` },
300
+ { system: "v3 KALLOS (12-dim, hard gates)", active: true, detail: `${kallosV3.composite} · gates ${kallosV3.gates.filter((g) => g.pass).length}/5 · release ${kallosV3.release}` },
301
+ { system: "v3 PROSE-COMPILER", active: true, detail: `${obligations.length} realization obligations · CONTROLLED_MODE sample certified · LITERARY_MODE delegated to host LLM` },
302
+ { system: "v3 SAGA-SCREEN", active: false, detail: "available on demand in the SAGA-OS studio (adaptation is not part of the chapter prompt)" },
303
+ { system: "v3 KALLOS-LIVE", active: false, detail: "needs ≥50 local audience observations before it adapts weights" },
304
+ { system: "v4 STYLE-GENOME", active: true, detail: genomeSummary(styleGenome, stylePack) },
305
+ { system: "v4 AUREATE style contract", active: true, detail: `injected into every chapter prompt · ${stylePack ?? "genre defaults (no pack)"}` },
306
+ { system: "v4 REVISION STACK + KALLOS-S", active: true, detail: "PASS-001..015 and the 12-dim style score run on generated prose (Studio → Style)" },
307
+ ];
308
+
309
+ const value: UnifiedRoll = {
310
+ seed, blueprint, spec, run, kallos, reality, archetypes, world, cast, modal, directive, contributions,
311
+ request, requestSource, contract, morph, nameSet, nameProfile, kallosV3, obligations, controlledSample, buildId,
312
+ styleGenome, stylePack,
313
+ };
314
+ _cache.set(key, value);
315
+ if (_cache.size > CACHE_MAX) _cache.delete(_cache.keys().next().value as string);
316
+ return value;
317
+ }
318
+
319
+ // ── Archetype set construction ──────────────────────────────────────────────
320
+
321
+ function buildArchetypeSet(x: {
322
+ seed: number; blueprint: SageBlueprint; spec: GenreSpec; run: GridRun;
323
+ kallos: KallosReport; reality: RealityLevel;
324
+ world: WorldMapPlace[]; cast: ReturnType<typeof buildCastGraph>;
325
+ contract: GenreContract; morph: MorphRun; kallosV3: KallosV3Report; requestSource: "studio" | "derived";
326
+ styleGenome: StyleGenome; stylePack: StylePackId | null;
327
+ }): ArchetypeSet {
328
+ const { seed, blueprint: bp, spec, run, reality, world, cast, contract, morph, kallosV3, requestSource, styleGenome, stylePack } = x;
329
+ const e: ArchetypeEntry[] = [];
330
+ const add = (
331
+ slot: string, label: string, value: string, note: string,
332
+ source: ArchetypeEntry["source"], id?: string,
333
+ ) => { if (value) e.push({ slot, label, value, note, source, id }); };
334
+
335
+ // — spine (SAGE)
336
+ add("TITLE", "Working title", bp.titleHint, "use as the book title", "SAGE");
337
+ add("MACRO", "Macro structure", bp.macro.name, bp.macro.function, "SAGE", bp.macro.id);
338
+ if (bp.secondaryMacro) add("MACRO2", "Braided structure", bp.secondaryMacro.name, bp.secondaryMacro.function, "SAGE", bp.secondaryMacro.id);
339
+ add("THEME", "Theme", bp.theme, "the argument the book makes", "SAGE");
340
+ add("QUESTION", "Dramatic question", bp.dramaticQuestion, "every chapter must load-bear this", "SAGE");
341
+ add("PREMISE", "Premise", bp.premise, "the situation at page one", "SAGE");
342
+ add("POV", "Point of view", bp.pov, "hold this rigorously", "SAGE");
343
+ add("CONFLICT", "Conflict axis", bp.conflictAxis, "the opposition's nature", "SAGE");
344
+ add("TONE", "Tone", bp.tone, "surface temperature of the prose", "SAGE");
345
+ add("ENDING", "Ending type", bp.ending, "the shape the last chapter must reach", "SAGE");
346
+
347
+ // — place
348
+ add("SETTING", "Primary setting", bp.primarySetting.name, bp.primarySetting.function, "SAGE", bp.primarySetting.id);
349
+ bp.secondarySettings.slice(0, 3).forEach((s, i) =>
350
+ add(`SETTING${i + 2}`, `Secondary setting ${i + 1}`, s.name, s.function, "SAGE", s.id));
351
+ world.slice(0, 4).forEach((p, i) =>
352
+ add(`PLACE${i + 1}`, `Named place ${i + 1}`, p.label, `${p.residents.length} residents; borders ${p.adjacentSettings.join(", ") || "none"}`, "ONOMASTRATA", p.settingId));
353
+
354
+ // — people: SAGE archetypes fused with ONOMASTRATA names (one set, not two)
355
+ const agentNames = cast.cast.filter((c) => c.kind === "agent");
356
+ const roleOf = (i: number) => agentNames[i]?.name;
357
+ add("PROTAGONIST", "Protagonist",
358
+ `${roleOf(0) ? `${roleOf(0)} — ` : ""}${bp.protagonist.archetype.name}`,
359
+ `wants ${bp.protagonist.want}; needs ${bp.protagonist.need}; wound: ${bp.protagonist.wound}; voice: ${bp.protagonist.voiceNote}`,
360
+ "SAGE", bp.protagonist.archetype.id);
361
+ add("DEUTERAGONIST", "Deuteragonist",
362
+ `${roleOf(1) ? `${roleOf(1)} — ` : ""}${bp.deuteragonist.archetype.name}`,
363
+ `wants ${bp.deuteragonist.want}; needs ${bp.deuteragonist.need}; wound: ${bp.deuteragonist.wound}`,
364
+ "SAGE", bp.deuteragonist.archetype.id);
365
+ add("ANTAGONIST", "Antagonist",
366
+ `${roleOf(2) ? `${roleOf(2)} — ` : ""}${bp.antagonist.archetype.name}`,
367
+ `wants ${bp.antagonist.want}; wound: ${bp.antagonist.wound}; function: ${bp.antagonist.archetype.function}`,
368
+ "SAGE", bp.antagonist.archetype.id);
369
+ bp.ensemble.slice(0, 4).forEach((c, i) =>
370
+ add(`ENSEMBLE${i + 1}`, `Ensemble ${i + 1}`,
371
+ `${roleOf(3 + i) ? `${roleOf(3 + i)} — ` : ""}${c.archetype.name}`,
372
+ `wants ${c.want}; voice: ${c.voiceNote}`, "SAGE", c.archetype.id));
373
+ cast.cast.filter((c) => c.kind === "institution").slice(0, 2).forEach((c, i) =>
374
+ add(`INSTITUTION${i + 1}`, `Institution ${i + 1}`, c.name, "applies pressure; has its own incentive", "ONOMASTRATA", c.id));
375
+ bp.nonhumanPresence.slice(0, 2).forEach((n, i) =>
376
+ add(`NONHUMAN${i + 1}`, `Non-human presence ${i + 1}`, n.name, n.function, "SAGE", n.id));
377
+
378
+ // — empty-space mechanisms (the load-bearing strangeness)
379
+ if (bp.worldMechanism) add("WORLD_MECH", "World mechanism", bp.worldMechanism.name, truncate(bp.worldMechanism.desc, 200), "EMPTY-SPACE", bp.worldMechanism.id);
380
+ if (bp.beatMechanism) add("BEAT_MECH", "Beat mechanism", bp.beatMechanism.name, truncate(bp.beatMechanism.desc, 200), "EMPTY-SPACE", bp.beatMechanism.id);
381
+ if (bp.relationshipMechanism) add("REL_MECH", "Relationship texture", bp.relationshipMechanism.name, truncate(bp.relationshipMechanism.desc, 200), "EMPTY-SPACE", bp.relationshipMechanism.id);
382
+
383
+ // — SAGA v2 structural verdicts
384
+ add("GENRE", "Genre (derived)", `${spec.family} / ${spec.leaf}`, `geometry ${spec.geometry}; container ${spec.container}`, "SAGA-v2");
385
+ add("PATTERN", "Genesis pattern", run.pattern, `${run.patternDetail} → ending family "${run.endingFamily}"`, "SAGA-v2");
386
+ add("ENDING_FAMILY", "Required ending family", run.endingFamily, "the last chapter must land in this family", "SAGA-v2");
387
+ add("STAKES_ROTATION", "Stakes rotation", spec.stakesRotation.join(" → "), "rotate; never escalate one axis monotonically", "SAGA-v2");
388
+ add("PACE", "Pace profile", spec.paceProfile, `tone gradient ${spec.toneGradient}`, "SAGA-v2");
389
+
390
+ // — load-bearing catalog elements actually selected by the grid,
391
+ // FILTERED BY THE REALITY LEVEL and capped so one chapter is not asked to
392
+ // carry eight mechanisms at once.
393
+ //
394
+ // Reality gate: SC-L rows are "laws of story" — impossible physics. At
395
+ // L>=4 the grounding contract forbids impossible events, so shipping an
396
+ // SC-L mechanism made the archetype set contradict the reality directive
397
+ // in the same prompt (verified defect). They are excluded there.
398
+ const elems: ElementRecord[] = [];
399
+ const seenEl = new Set<string>();
400
+ for (const s of run.plan.scenes) {
401
+ if (s.element && !seenEl.has(s.element.id)) { seenEl.add(s.element.id); elems.push(s.element); }
402
+ }
403
+ const allowsImpossible = reality.unexplainedTolerance >= 0.45; // L0..L3
404
+ const mechCap = reality.id >= 5 ? 4 : reality.id >= 3 ? 5 : 6;
405
+ const gated = elems.filter((el) => (allowsImpossible ? true : el.slotClass !== "SC-L"));
406
+ const dropped = elems.length - gated.length;
407
+ gated
408
+ .sort((a, b) => b.rarity - a.rarity)
409
+ .slice(0, mechCap)
410
+ .forEach((el, i) =>
411
+ add(`MECHANISM${i + 1}`, `Load-bearing mechanism ${i + 1}`, el.name,
412
+ `${truncate(el.desc, 160)} [${el.slotClass} · stakes ${el.stakesAxis} · cost ${el.costAxis}]`,
413
+ "SAGA-v2", el.id));
414
+ if (dropped > 0) {
415
+ add("REALITY_GATE", "Reality gate applied",
416
+ `${dropped} impossible-physics mechanism(s) withheld`,
417
+ `reality level L${reality.id} forbids unexplained phenomena, so SC-L "law of story" rows were excluded from this set`,
418
+ "REALITY");
419
+ }
420
+
421
+ // — SAGA-OS v3 contract + lattice verdict (studio-composed or derived; never silent)
422
+ add("GENRE_CONTRACT", "Genre contract", contract.mix.map((m) => `${m.key} ${Math.round(m.weight * 100)}%`).join(" + "),
423
+ `${requestSource === "studio" ? "composed in the SAGA-OS studio" : "derived from the blueprint"}; audience ${contract.audienceSegment}`, "SAGA-v3");
424
+ add("READER_QUESTION", "Dominant reader question", contract.dominantReaderQuestion, "every volume must move this question", "SAGA-v3");
425
+ contract.mandatoryPayoffs.slice(0, 3).forEach((mp, i) => add(`PAYOFF${i + 1}`, `Mandatory payoff ${i + 1}`, mp, "must be paid on page", "SAGA-v3"));
426
+ contract.forbiddenFailures.slice(0, 3).forEach((ff, i) => add(`FORBID${i + 1}`, `Forbidden failure ${i + 1}`, ff, "never write this", "SAGA-v3"));
427
+ add("TONE_CONTRACT", "Tone contract", contract.toneContract.slice(0, 3).join(" · "), contract.toneContract[3] ?? "", "SAGA-v3");
428
+ add("LATTICE_VERDICT", "Morphogenesis verdict", `${morph.attractor} → ${morph.endingFamily}`,
429
+ `${morph.ticks.length} ticks, ${morph.promises.length} promises (${morph.promises.filter((p) => p.state === "PAID").length} paid), ${morph.volumes.length} volume(s)${morph.attractorInTarget ? "" : " — attractor outside contract target, declared"}`, "SAGA-v3");
430
+ add("KALLOS_V3", "KALLOS v3 gate", `${kallosV3.composite}/100 · release ${kallosV3.release}`,
431
+ `hard gates ${kallosV3.gates.map((g) => `${g.id}:${g.pass ? "pass" : "FAIL"}`).join(", ")}; weakest ${kallosV3.weakest ? `${kallosV3.weakest.key} ${kallosV3.weakest.score}` : "n/a"}`, "SAGA-v3");
432
+
433
+ // — SAGA-OS v4 style genotype
434
+ add("STYLE_GENOME", "Style genome", genomeSummary(styleGenome, stylePack),
435
+ "governs sentence syntax, image density, rhythm and focal distance", "SAGA-v4");
436
+ add("PROSE_MODE", "Prose mode", styleGenome.proseMode,
437
+ `focal distance ${styleGenome.focalDistance}${stylePack ? `; pack ${stylePack}` : ""}`, "SAGA-v4");
438
+
439
+ // — reality grounding
440
+ add("REALITY", "Reality grounding", `L${reality.id} ${reality.label}`, reality.blurb, "REALITY");
441
+
442
+ const bySource = e.reduce<Record<string, number>>((a, x2) => { a[x2.source] = (a[x2.source] ?? 0) + 1; return a; }, {});
443
+
444
+ const promptBlock = [
445
+ `CANONICAL ARCHETYPE SET — seed ${seed}. These ${e.length} slots are the ONLY story facts. Do not invent replacements for them; extend them.`,
446
+ ...e.map((x2) => ` [${x2.slot}] ${x2.label}: ${x2.value}${x2.note ? ` — ${x2.note}` : ""}`),
447
+ ].join("\n");
448
+
449
+ return { seed, entries: e, bySource, promptBlock };
450
+ }
451
+
452
+ // ── The unified directive ───────────────────────────────────────────────────
453
+
454
+ function buildUnifiedDirective(x: {
455
+ blueprint: SageBlueprint; spec: GenreSpec; run: GridRun;
456
+ kallos: KallosReport; reality: RealityLevel; archetypes: ArchetypeSet;
457
+ contract: GenreContract; morph: MorphRun; kallosV3: KallosV3Report;
458
+ styleGenome: StyleGenome; stylePack: StylePackId | null;
459
+ }): string {
460
+ const { blueprint: bp, spec, run, kallos, reality, archetypes, contract, morph, kallosV3, styleGenome, stylePack } = x;
461
+ const wordsPerChapter = Math.round(
462
+ bp.chapters.reduce((a, c) => a + c.targetWords, 0) / Math.max(1, bp.chapters.length),
463
+ );
464
+
465
+ const stakeLine = run.plan.chapters.slice(0, 14)
466
+ .map((c) => `ch${c.index}:${c.dominantStakes ?? "—"}`).join(" · ");
467
+
468
+ const v2 = [
469
+ "SAGA-OS v2 COMPOSITION DISCIPLINE (apply silently; never name these rules in the prose):",
470
+ `- Genre: ${spec.family}/${spec.leaf}. Geometry ${spec.geometry}. Container ${spec.container}. Tone gradient ${spec.toneGradient}.`,
471
+ `- Structural verdict: ${run.pattern} — ${run.patternDetail}. The book must end in the "${run.endingFamily}" family.`,
472
+ `- Stakes rotation (do not let one axis dominate consecutive chapters): ${stakeLine}${run.plan.chapters.length > 14 ? " …" : ""}.`,
473
+ `- Cost routing: every apparent success charges a visible ${[...new Set(run.plan.scenes.map((s) => s.cost))].slice(0, 5).join("/")} cost to a named person, institution, or future.`,
474
+ `- Promise discipline: ${run.plan.promiseOps.length} closures are scheduled. Every setup must be PAID, TRANSFERRED, EXPIRED, or explicitly RESIDUALIZED. No orphan setups.`,
475
+ `- KALLOS weakest pillar: ${kallos.weakest ? `${kallos.weakest.label} (${kallos.weakest.score.toFixed(2)})` : "n/a"} — write to strengthen it specifically.`,
476
+ ].join("\n");
477
+
478
+ // At grounded levels the SAGE cast can still carry archetypal labels
479
+ // ("the personified abstraction", "the animal-as-protagonist"). Those are
480
+ // CASTING NOTES, not literal instructions, and the model must be told so or
481
+ // it will write a talking abstraction into a documentary. This clause is the
482
+ // bridge between the archetype vocabulary and the grounding contract.
483
+ const reconcile = reality.id >= 4
484
+ ? [
485
+ "ARCHETYPE ⇄ REALITY RECONCILIATION (mandatory at this grounding level):",
486
+ `- Character archetype labels above are CASTING NOTES describing a dramatic function, not literal beings. Render every one of them as an ordinary, physically real person with a job, an address, and a body.`,
487
+ `- "Personified abstraction", "non-human presence", and similar labels must be realised as a real institution, a real animal, a real document, a real machine, or a real person who embodies that pressure. Never as a literal supernatural entity.`,
488
+ `- If a listed mechanism cannot occur under level ${reality.id} physics, realise its SOCIAL and ECONOMIC shape instead of its impossible mechanism, and never state the impossible version.`,
489
+ ].join("\n")
490
+ : "";
491
+
492
+ const failedGates = kallosV3.gates.filter((g) => !g.pass).map((g) => g.id);
493
+ const v3 = [
494
+ "SAGA-OS v3 GENRE CONTRACT (binding; a chapter that breaks it fails the release gate):",
495
+ `- Reader question to move this chapter: ${contract.dominantReaderQuestion}`,
496
+ `- Expected pleasures to deliver across the book: ${contract.expectedPleasures.slice(0, 4).join("; ")}.`,
497
+ `- Mandatory payoffs (must land on page by the end): ${contract.mandatoryPayoffs.slice(0, 3).join("; ")}.`,
498
+ `- Forbidden failures (never): ${contract.forbiddenFailures.slice(0, 4).join("; ")}.`,
499
+ `- Tone: ${contract.toneContract.slice(0, 3).join("; ")}. ${contract.toneContract[3] ?? ""}`.trim(),
500
+ `- Audience constraints: ${contract.audienceConstraints.join("; ")}.`,
501
+ `- Prose register: ${contract.proseRegister}. Names follow one phonology: ${contract.nameRegister}.`,
502
+ `- Lattice verdict: ${morph.attractor} → the book must land in the "${morph.endingFamily}" ending family; ${morph.volumes.length > 1 ? `${morph.volumes.length} volumes, each with local closure and a series delta` : "single volume with local closure"}.`,
503
+ failedGates.length
504
+ ? `- KALLOS v3 release gate currently BLOCKED by: ${failedGates.join(", ")} — repair the plan-level defect in prose (close the open promise / avoid the canon conflict) rather than papering over it.`
505
+ : `- KALLOS v3 hard gates pass (grammar, logic, completeness, genre_contract, canon). Weakest dimension: ${kallosV3.weakest ? `${kallosV3.weakest.label} (${kallosV3.weakest.score})` : "n/a"} — strengthen it in this chapter.`,
506
+ ].join("\n");
507
+
508
+ return [
509
+ archetypes.promptBlock,
510
+ "",
511
+ buildRealityDirective(reality.id, { chapterWords: wordsPerChapter }),
512
+ reconcile ? "" : null,
513
+ reconcile || null,
514
+ "",
515
+ v2,
516
+ "",
517
+ v3,
518
+ "",
519
+ buildAureateDirective(styleGenome, stylePack, { chapterWords: wordsPerChapter }),
520
+ ].filter((l) => l !== null).join("\n");
521
+ }
522
+
523
+ /** Test helper: clears the memo (used by hand-trace scripts). */
524
+ export function __clearUnifiedRollCache(): void { _cache.clear(); }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * SAGE worked-sketch corpus — Turn 8 (append-only, verbatim).
3
+ * ---------------------------------------------------------------------------
4
+ * Source: user-provided P8 "§WORKED — 20 Story Sketches (proving playability
5
+ * of the strongest primitives)". Transcribed 1:1 (multi-line sketch text
6
+ * collapsed to single-line prose; wording preserved). These are demonstration
7
+ * fixtures proving the strongest empty-space primitives compose into viable
8
+ * narratives; they are exported for reference and can seed SAGE premises.
9
+ *
10
+ * HONESTY: static transcription from provided context. No external source,
11
+ * search, or novelty detector used.
12
+ */
13
+
14
+ export type WorkedSketch = {
15
+ id: string;
16
+ title: string;
17
+ primitives: string;
18
+ sketch: string;
19
+ };
20
+
21
+ export const WORKED_SKETCHES: readonly WorkedSketch[] = [
22
+ { id: "SKETCH-001", title: "The Ash Heir", primitives: "ES-HWA016 (Ash-Heir) + ES-HEC008 (Recovery Bond) + ES2-END005 (Maintenance Ending)", sketch: "A woman inherits monitoring duty for a landfill closed before her birth. She discovers the recovery bond her grandmother posted — released only at verified succession milestones. The landfill is growing wildflowers. She measures them against the milestone checklist. The story ends with her filing the report that releases the bond to her daughter, who will file the next one in thirty years. The ending is a schedule." },
23
+ { id: "SKETCH-002", title: "Counterfeit Indigo", primitives: "ES-HCO008 (Counterfeit Indigo Court) + ES2-CH014 (Witness Who Benefited)", sketch: "A dyer is called to testify that a rival's indigo is counterfeit. She knows it is — but her own business thrived because the rival's fake flooded the market and drove up prices for real indigo. Her testimony would be true, doubted (she benefits from the conviction), and self-ruinous (investigation would reveal her windfall). She sits in the witness box. The story is whether she speaks." },
24
+ { id: "SKETCH-003", title: "The Memory Baseline", primitives: "ES-HAI003 (Memory Baseline Herd) + ES2-SIT006 (Contested Non-Event)", sketch: "Two families dispute whether a boundary agreement was ever made, forty years ago. The court consults the elephant herd that roams the disputed ground. The elephants avoid a specific clearing — suggesting something happened there — but the clearing is on the wrong side of the claimed boundary. Both families realize the elephants remember an event neither family does." },
25
+ { id: "SKETCH-004", title: "Whisper Franchise", primitives: "ES-HBR006 (Whisper Franchise) + ES2-SUB007 (Anti-Confidant)", sketch: "In a dense vertical city, whisper-band rights are licensed. A woman holds the franchise for floors 14–18. Her neighbor tells her everything — falsely, carefully, lovingly — because the neighbor believes the whisper-franchise holder can hear through walls. She can't. She knows the stories are lies. She protects them anyway, because the neighbor needs to believe someone is listening." },
26
+ { id: "SKETCH-005", title: "The Losing Rite", primitives: "ES-HGA004 (Losing Rites) + ES2-CH010 (Calibrated Coward)", sketch: "Annual civic game. The loser becomes the town's Fool for a year — a ceremonial office with real power (licensed truth-telling, immunity from small debts). A man who has precisely mapped his own courage knows he can lose on purpose. The story is the game itself: he must lose convincingly enough to earn the office, but not so obviously that the loss is disqualified as intentional." },
27
+ { id: "SKETCH-006", title: "Erosion Witness", primitives: "ES-HLA001 (Erosion Witness) + ES2-NR005 (Translation-Loss Narrator)", sketch: "An old woman testifies about a cliff that has retreated forty meters in her lifetime. The proceedings are in a language she learned as an adult. She marks, honestly, where her testimony is certain, probable, and possible. The court must weigh geological truth delivered through linguistic uncertainty. Her most important memory — the sound the cliff made the night it took the church — she cannot translate at all." },
28
+ { id: "SKETCH-007", title: "The Ferment Calendar", primitives: "ES-HSU008 (Ferment Calendar) + GS-PHEN002 (Mismatch Year)", sketch: "A town measures its year by communal fermentation batches. This year the batch spoiled early — the calendar shortened. But the pollinator season hasn't shifted. Flowers bloom in what the town calls \"next year\" while the bees think it's still this one. The agricultural agent must reconcile two calendars that have never disagreed before." },
29
+ { id: "SKETCH-008", title: "Pioneer Household", primitives: "ES-HEC002 (Pioneer-Species Household) + ES2-TW004 (Maintenance Reveal)", sketch: "A family has lived on a floodplain for three generations under pioneer status — improving the soil, planting windbreaks, stabilizing the bank. Their contract says they must leave when the next succession stage arrives. An ecologist certifies: the stage has arrived. The family's own work caused it. The twist is that their departure was always the contractual definition of success, and they knew." },
30
+ { id: "SKETCH-009", title: "The Overlap Hour", primitives: "ES2-SET005 (Overlap Hour Place) + ES-HSITB004 (Elevator Pact)", sketch: "A building serves as a school by day and a shelter by night. During the one-hour overlap, a teacher and a shelter resident share the elevator. They have forty seconds. Every day for a year. The story is told in forty-second chapters. By the end, neither speaks, but the silence has become specific." },
31
+ { id: "SKETCH-010", title: "Glove Census", primitives: "ES-HTO005 (Glove Census) + ES2-CH006 (Second-Confirmer)", sketch: "In a city where bare palms are rationed to specific hours, a clerk certifies handshakes. She has never originated anything — only confirmed others' agreements. One day she is asked to certify her own marriage contract. She cannot: she is the confirmer, not the party. The story is her search for someone whose confirmation she would accept." },
32
+ { id: "SKETCH-011", title: "The Scent Executor", primitives: "ES-HSC003 (Smell Executor) + ES-HDEATH002 (Distributed Death)", sketch: "A woman's job is releasing the deceased's scent-signature to the public. The death must be announced in a specific order to specific people. She holds the perfume bottle. She holds the list. The first person on the list is herself — the deceased was her mother. She must smell it first, then carry it to the others, arriving at each door already grieving." },
33
+ { id: "SKETCH-012", title: "Meridian Court", primitives: "ES-HAS008 (Meridian Court) + ES2-SIT013 (Necessary Audience)", sketch: "A trial can proceed only at local solar noon, and only if a specific reluctant witness agrees to watch. The witness refuses. Every day the sun crosses the meridian and the court opens and closes empty. The defendant ages. The plaintiff ages. The witness tends her garden. The story is the negotiation to get her to look." },
34
+ { id: "SKETCH-013", title: "Blank-Page Ration", primitives: "ES-HPU008 (Blank-Page Ration) + ES2-TW009 (Off-Stage Payer Reveal)", sketch: "A poet has used all her certified blank pages for the year. She discovers her father has been buying black-market pages and slipping them into her desk for years. Every poem she thought she earned was written on purchased possibility. The twist isn't the gift — it's the invoice. Someone was paying, and the bill has arrived." },
35
+ { id: "SKETCH-014", title: "The Handoff", primitives: "GS-W004 (Night-Shift Continuity) + ES2-MB009 (Maintenance Litany)", sketch: "Two shift workers who have never met share a clipboard. Each night, one writes what is working. Each morning, the other reads it. The story is the clipboard. Over months, the entries become personal. One night, the litany includes: \"Pump 3 fine. Seals fine. I think I'm getting divorced.\" The morning reader must decide whether to respond in the maintenance log." },
36
+ { id: "SKETCH-015", title: "Eclipse Amnesty", primitives: "ES-HAS003 (Eclipse Amnesty) + ES-HDE001 (Debt Sabbath)", sketch: "An eclipse is predicted. All debts below a threshold will be extinguished. A woman owes exactly one unit above the threshold. She spends the week before the eclipse trying to pay down one unit — not to clear the debt, but to get it below the line so the sky will do the rest. The eclipse comes. She is one cent short." },
37
+ { id: "SKETCH-016", title: "Scar Sabbatical", primitives: "ES-HBI006 (Scar Sabbatical) + ES2-CH003 (Peak-Passed Protagonist)", sketch: "A body-modification artist is in her mandatory unmodified years. She is famous for one piece — a full-back design she did on herself a decade ago. During the sabbatical, it fades. She cannot touch it. The story is living as the site of a former masterpiece while it slowly becomes ordinary skin." },
38
+ { id: "SKETCH-017", title: "The Arrested Garden", primitives: "ES-HEC007 (Arrested-Succession Garden) + GS-P004 (Maintenance Plot)", sketch: "A meadow is being held at mid-succession by a family who mows, weeds, and burns on a precise schedule. The meadow wants to become forest. The family's heroism is preventing change. One summer, the youngest daughter asks: \"Why don't we let it grow?\" The story is the family's attempt to answer." },
39
+ { id: "SKETCH-018", title: "Sediment Parliament", primitives: "ES-HLA005 (Sediment Parliament) + GS-H2O002 (Upstream Promise)", sketch: "Upstream villages deposit silt that downstream villages need for farming but that also clogs the harbor. The Sediment Parliament meets annually. This year, the upstream delegate's daughter is marrying the downstream delegate's son. The silt allocation is the dowry negotiation. The river doesn't care." },
40
+ { id: "SKETCH-019", title: "The Recognition Estate", primitives: "ES-HAI008 (Recognition Estate) + ES2-END004 (Split-Custody Ending)", sketch: "An old woman's will leaves her estate to \"whoever the crows still approach.\" Two grandchildren — one kind, one practical — wait in the garden. The crows approach both. The court must split the estate by the crows' preference gradient, which is indistinguishable. The ending is a negotiated dual-custody agreement the crows will never ratify." },
41
+ { id: "SKETCH-020", title: "The Ante of Attention", primitives: "ES-HGA008 (Ante of Attention) + ES2-SUB009 (Rival's Advocate)", sketch: "In a dispute settled by civic game, the entry stake is minutes of listening. Before the game, each side must listen to the other's full case. A woman is assigned as her enemy's advocate — she must argue his position to the court. She does it so well that the court awards him the listening-minutes she earned. She loses the game with his words in her mouth." },
42
+ ] as const;
43
+
44
+ export const WORKED_SKETCHES_TOTAL = WORKED_SKETCHES.length;