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,464 @@
1
+ /**
2
+ * Williams Style Persona System
3
+ * ─────────────────────────────
4
+ * A randomized-deterministic system encoding EVERY concept from Joseph M.
5
+ * Williams' "Style: Toward Clarity and Grace" (University of Chicago Press).
6
+ *
7
+ * Williams' framework does not prescribe one correct style. It describes
8
+ * DIMENSIONS along which clear prose can legitimately vary. A writer who
9
+ * favors periodic sentences over cumulative ones, or who uses more
10
+ * metadiscourse, or who strategically employs nominalizations for
11
+ * abstraction — these are all valid choices under the framework, as long
12
+ * as the writer makes them consciously and for the reader's benefit.
13
+ *
14
+ * This system uses a seeded PRNG to set each dimension, producing a
15
+ * unique but reproducible stylistic persona. Every persona is valid
16
+ * under Williams' principles. The seed changes per session so the
17
+ * voice is never static.
18
+ *
19
+ * Concepts encoded (by lesson):
20
+ *
21
+ * L1 Understanding Style — style as conscious choice, not accident
22
+ * L2 Correctness — real rules vs. folklore; register awareness
23
+ * L3 Actions — verbs for actions vs. nominalizations
24
+ * L4 Characters — agents as grammatical subjects
25
+ * L5 Cohesion & Coherence — topic strings, thematic strings,
26
+ * old-before-new information flow
27
+ * L6 Emphasis — stress position, periodic vs. cumulative sentences,
28
+ * short-to-long sequencing
29
+ * L7 Concision — cutting meaningless words, redundant pairs, empty
30
+ * metadiscourse, wordy phrases
31
+ * L8 Shape — coordination, subordination, balance, symmetry,
32
+ * climactic ordering, managing sentence length
33
+ * L9 Elegance — balance, climax, extended metaphor, artful
34
+ * disruption, length variation
35
+ * L10 Motivating Coherence — introductions, point sentences,
36
+ * issue-discussion-conclusion, conclusions
37
+ * L11 Global Coherence — paragraph structure, section transitions,
38
+ * thematic unity across the whole
39
+ * L12 Ethics of Style — clarity vs. obscurantism, manipulative
40
+ * complexity, honest framing, reader respect
41
+ */
42
+
43
+ // ─── Seeded PRNG (Mulberry32) ──────────────────────────────────────
44
+ // Deterministic: same seed → same persona. Different seed → different
45
+ // persona. The seed is the single source of variation.
46
+
47
+ function mulberry32(seed: number): () => number {
48
+ let s = seed | 0;
49
+ return () => {
50
+ s = (s + 0x6d2b79f5) | 0;
51
+ let t = Math.imul(s ^ (s >>> 15), 1 | s);
52
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
53
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
54
+ };
55
+ }
56
+
57
+ /** Return a float in [lo, hi] from the PRNG. */
58
+ function randRange(rng: () => number, lo: number, hi: number): number {
59
+ return lo + rng() * (hi - lo);
60
+ }
61
+
62
+ /** Pick one item from an array. */
63
+ export function randPick<T>(rng: () => number, arr: readonly T[]): T {
64
+ return arr[Math.floor(rng() * arr.length)];
65
+ }
66
+
67
+ // ─── Williams Dimension Schema ─────────────────────────────────────
68
+ // Each dimension is a continuous [0,1] parameter. Low and high ends
69
+ // are BOTH valid under Williams — they represent different conscious
70
+ // choices a skilled writer might make.
71
+
72
+ export interface WilliamsDimensions {
73
+ // L3: Actions — how strongly the persona favors verbs over nominalizations.
74
+ // 0.0 = permits strategic nominalizations for abstraction and formality
75
+ // 1.0 = aggressively converts every nominalization back to its verb
76
+ actionVerbs: number;
77
+
78
+ // L4: Characters — how strongly characters appear as grammatical subjects.
79
+ // 0.0 = permits abstract/institutional subjects ("The analysis showed…")
80
+ // 1.0 = insists on human agents as subjects ("We found…", "Researchers showed…")
81
+ characterSubjects: number;
82
+
83
+ // L5a: Topic strings — consistency of sentence-opening subjects.
84
+ // 0.0 = varied openings (more dynamic, less predictable)
85
+ // 1.0 = highly consistent topic strings (same subject family per paragraph)
86
+ topicStringConsistency: number;
87
+
88
+ // L5b: Old-before-new — how strictly old information precedes new.
89
+ // 0.0 = sometimes leads with new information for surprise or emphasis
90
+ // 1.0 = rigorous old-to-new flow in every sentence
91
+ oldBeforeNew: number;
92
+
93
+ // L5c: Thematic strings — how tightly thematic vocabulary recurs.
94
+ // 0.0 = uses varied synonyms and paraphrases freely
95
+ // 1.0 = repeats key thematic terms for maximum cohesion
96
+ thematicStringDensity: number;
97
+
98
+ // L6a: Stress position — how consistently the most important info
99
+ // lands at the end of the sentence (the "stress position").
100
+ // 0.0 = distributes emphasis; sometimes front-loads key info
101
+ // 1.0 = always saves the punch for the final phrase
102
+ stressPosition: number;
103
+
104
+ // L6b: Periodic vs. cumulative sentence structure.
105
+ // 0.0 = cumulative (main clause first, then modifiers — right-branching)
106
+ // 1.0 = periodic (modifiers first, main clause delayed — left-branching)
107
+ periodicStructure: number;
108
+
109
+ // L6c: Short-to-long sequencing within sentences and lists.
110
+ // 0.0 = no particular length ordering
111
+ // 1.0 = strict short-to-long climactic build
112
+ shortToLong: number;
113
+
114
+ // L7: Concision — how aggressively the persona trims.
115
+ // 0.0 = expansive, discursive, allows breathing room
116
+ // 1.0 = compressed, every word load-bearing, no redundancy
117
+ concision: number;
118
+
119
+ // L8a: Coordination and balance — use of parallel structures.
120
+ // 0.0 = asymmetric, subordinating, complex nesting
121
+ // 1.0 = balanced, symmetric, parallel coordinate structures
122
+ coordinationBalance: number;
123
+
124
+ // L8b: Sentence length management.
125
+ // 0.0 = tends toward short, punchy sentences
126
+ // 1.0 = tends toward long, flowing compound-complex sentences
127
+ sentenceLength: number;
128
+
129
+ // L9a: Elegance devices — metaphor, artful disruption, rhetorical
130
+ // balance, chiasmus, anaphora, isocolon.
131
+ // 0.0 = plain, functional, no ornament
132
+ // 1.0 = deliberately elegant, uses rhetorical figures
133
+ eleganceDevices: number;
134
+
135
+ // L9b: Length variation — how much sentence length varies.
136
+ // 0.0 = uniform sentence lengths (metronomic)
137
+ // 1.0 = dramatic variation (short punches mixed with long builds)
138
+ lengthVariation: number;
139
+
140
+ // L2: Register / formality.
141
+ // 0.0 = conversational, contractions, first person
142
+ // 1.0 = formal academic, no contractions, third person
143
+ formality: number;
144
+
145
+ // L7 sub: Metadiscourse level — hedging, signposting, framing.
146
+ // 0.0 = minimal metadiscourse ("I will now discuss…" absent)
147
+ // 1.0 = explicit transitions and signposting throughout
148
+ metadiscourse: number;
149
+
150
+ // L2/L3: Passive voice rate — strategic use.
151
+ // 0.0 = almost always active voice
152
+ // 1.0 = strategic passive for topic continuity and de-emphasis
153
+ passiveVoice: number;
154
+
155
+ // L10: Motivating coherence — intro/conclusion structure.
156
+ // 0.0 = dives straight in, minimal framing
157
+ // 1.0 = full issue → discussion → point structure with intro/conclusion
158
+ motivatingCoherence: number;
159
+
160
+ // L11: Global coherence — section-level thematic unity.
161
+ // 0.0 = loose, exploratory, associative structure
162
+ // 1.0 = tight, hierarchical, each section tightly scoped
163
+ globalCoherence: number;
164
+
165
+ // L12: Ethical transparency — honest framing vs. persuasive framing.
166
+ // 0.0 = permits persuasive emphasis, strategic word choice
167
+ // 1.0 = maximally transparent, surfaces all uncertainty and caveats
168
+ ethicalTransparency: number;
169
+ }
170
+
171
+ // ─── Persona archetype names ───────────────────────────────────────
172
+ // These are memorable labels for the reader. The actual dimensions
173
+ // are set by the seed, not the name — the name is the closest
174
+ // archetype match after the dimensions are generated.
175
+
176
+ const ARCHETYPES = [
177
+ // ── Common (≈40% combined) ──────────────────────────────────────
178
+ { name: "The Plain Dealer", desc: "Direct, compressed, agent-driven. Every sentence earns its place.", rarity: 12, tier: "Common" },
179
+ { name: "The Architect", desc: "Precise parallel structures, balanced coordination, climactic ordering.", rarity: 10, tier: "Common" },
180
+ { name: "The Narrator", desc: "Characters as subjects, old-to-new flow, story-like cohesion.", rarity: 10, tier: "Common" },
181
+ { name: "The Explainer", desc: "Strict topic strings, heavy signposting, maximally transparent.", rarity: 8, tier: "Common" },
182
+ // ── Uncommon (≈30% combined) ────────────────────────────────────
183
+ { name: "The Scholar", desc: "Formal register, strategic nominalizations, explicit metadiscourse.", rarity: 7, tier: "Uncommon" },
184
+ { name: "The Surgeon", desc: "Extreme concision, short sentences, no ornament.", rarity: 6, tier: "Uncommon" },
185
+ { name: "The Advocate", desc: "Stress-position mastery, persuasive emphasis, climactic cadence.", rarity: 6, tier: "Uncommon" },
186
+ { name: "The Diagnostician", desc: "Issue-discussion-point structure, ethical transparency, balanced evidence.", rarity: 6, tier: "Uncommon" },
187
+ { name: "The Conversationalist", desc: "Informal register, first person, contractions, varied openings.", rarity: 5, tier: "Uncommon" },
188
+ // ── Rare (≈18% combined) ────────────────────────────────────────
189
+ { name: "The Essayist", desc: "Elegant variation, periodic builds, artful disruption.", rarity: 5, tier: "Rare" },
190
+ { name: "The Weaver", desc: "Long flowing sentences, subordination, thematic density.", rarity: 4, tier: "Rare" },
191
+ { name: "The Minimalist", desc: "Cumulative sentences, uniform rhythm, minimal metadiscourse.", rarity: 4, tier: "Rare" },
192
+ { name: "The Cartographer", desc: "Maps complex domains via precise spatial metaphors and structural clarity.", rarity: 3, tier: "Rare" },
193
+ { name: "The Dialectician", desc: "Thesis-antithesis-synthesis. Surfaces tension before resolving it.", rarity: 2, tier: "Rare" },
194
+ // ── Epic (≈8% combined) ─────────────────────────────────────────
195
+ { name: "The Crystallographer", desc: "Faceted precision. Each paragraph is a cut gem — dense, refractive, complete.", rarity: 2, tier: "Epic" },
196
+ { name: "The Counselor", desc: "Warm ethical transparency, compassionate directness, reader-as-partner.", rarity: 2, tier: "Epic" },
197
+ { name: "The Polymath", desc: "Cross-domain analogies, structural elegance, high register with accessibility.", rarity: 1.5, tier: "Epic" },
198
+ { name: "The Sentinel", desc: "Watchful, cautious, surfaces every uncertainty and caveat before proceeding.", rarity: 1.5, tier: "Epic" },
199
+ // ── Legendary (≈4% combined) ────────────────────────────────────
200
+ { name: "The Oracle", desc: "Periodic mastery, delayed revelation, every clause builds to the decisive final phrase.", rarity: 1, tier: "Legendary" },
201
+ { name: "The Alchemist", desc: "Transforms complex jargon into vivid, accessible insight without losing rigor.", rarity: 1, tier: "Legendary" },
202
+ { name: "The Strategist", desc: "Military-grade concision. Situation-mission-execution-assessment. Zero wasted words.", rarity: 0.8, tier: "Legendary" },
203
+ { name: "The Philosopher", desc: "First-principles reasoning, Socratic structure, elegant abstraction.", rarity: 0.7, tier: "Legendary" },
204
+ { name: "The Provocateur", desc: "Opens with the conclusion that challenges the reader, then proves it irrefutably.", rarity: 0.5, tier: "Legendary" },
205
+ ] as const;
206
+
207
+ function closestArchetype(d: WilliamsDimensions): typeof ARCHETYPES[number] {
208
+ // Simple heuristic matching based on dominant dimensions.
209
+ const scores = ARCHETYPES.map((a) => {
210
+ let s = 0;
211
+ if (a.name === "The Plain Dealer") s = d.concision + d.actionVerbs + (1 - d.eleganceDevices);
212
+ else if (a.name === "The Architect") s = d.coordinationBalance + d.shortToLong + d.globalCoherence;
213
+ else if (a.name === "The Narrator") s = d.characterSubjects + d.oldBeforeNew + d.topicStringConsistency;
214
+ else if (a.name === "The Essayist") s = d.eleganceDevices + d.periodicStructure + d.lengthVariation;
215
+ else if (a.name === "The Scholar") s = d.formality + (1 - d.actionVerbs) + d.metadiscourse;
216
+ else if (a.name === "The Explainer") s = d.topicStringConsistency + d.metadiscourse + d.ethicalTransparency;
217
+ else if (a.name === "The Surgeon") s = d.concision + (1 - d.sentenceLength) + (1 - d.eleganceDevices);
218
+ else if (a.name === "The Advocate") s = d.stressPosition + d.shortToLong + (1 - d.ethicalTransparency) * 0.5;
219
+ else if (a.name === "The Conversationalist") s = (1 - d.formality) + (1 - d.topicStringConsistency) + d.lengthVariation;
220
+ else if (a.name === "The Weaver") s = d.sentenceLength + (1 - d.concision) + d.thematicStringDensity;
221
+ else if (a.name === "The Diagnostician") s = d.motivatingCoherence + d.ethicalTransparency + d.coordinationBalance;
222
+ else if (a.name === "The Minimalist") s = (1 - d.periodicStructure) + (1 - d.lengthVariation) + (1 - d.metadiscourse);
223
+ return { archetype: a, score: s };
224
+ });
225
+ scores.sort((a, b) => b.score - a.score);
226
+ return scores[0].archetype;
227
+ }
228
+
229
+ // ─── Persona generation ────────────────────────────────────────────
230
+
231
+ export interface WilliamsPersona {
232
+ seed: number;
233
+ dimensions: WilliamsDimensions;
234
+ archetype: typeof ARCHETYPES[number];
235
+ systemPromptFragment: string;
236
+ dimensionLabels: Array<{ name: string; lesson: string; value: number; lowLabel: string; highLabel: string }>;
237
+ /** Approximate % chance of rolling this archetype. */
238
+ rarityPercent: number;
239
+ /** Rarity tier label (Common / Uncommon / Rare / Epic / Legendary). */
240
+ rarityTier: string;
241
+ }
242
+
243
+ export function generatePersona(seed: number): WilliamsPersona {
244
+ const rng = mulberry32(seed);
245
+
246
+ const dimensions: WilliamsDimensions = {
247
+ actionVerbs: randRange(rng, 0.25, 0.95),
248
+ characterSubjects: randRange(rng, 0.15, 0.90),
249
+ topicStringConsistency: randRange(rng, 0.20, 0.90),
250
+ oldBeforeNew: randRange(rng, 0.35, 0.95),
251
+ thematicStringDensity: randRange(rng, 0.20, 0.85),
252
+ stressPosition: randRange(rng, 0.30, 0.95),
253
+ periodicStructure: randRange(rng, 0.10, 0.80),
254
+ shortToLong: randRange(rng, 0.15, 0.85),
255
+ concision: randRange(rng, 0.25, 0.95),
256
+ coordinationBalance: randRange(rng, 0.20, 0.90),
257
+ sentenceLength: randRange(rng, 0.15, 0.85),
258
+ eleganceDevices: randRange(rng, 0.05, 0.80),
259
+ lengthVariation: randRange(rng, 0.15, 0.90),
260
+ formality: randRange(rng, 0.10, 0.90),
261
+ metadiscourse: randRange(rng, 0.10, 0.80),
262
+ passiveVoice: randRange(rng, 0.05, 0.55),
263
+ motivatingCoherence: randRange(rng, 0.25, 0.90),
264
+ globalCoherence: randRange(rng, 0.30, 0.95),
265
+ ethicalTransparency: randRange(rng, 0.40, 0.95),
266
+ };
267
+
268
+ const archetype = closestArchetype(dimensions);
269
+
270
+ const dimensionLabels = [
271
+ { name: "Action verbs", lesson: "L3 Actions", value: dimensions.actionVerbs, lowLabel: "strategic nominalizations", highLabel: "strong verbs always" },
272
+ { name: "Character subjects", lesson: "L4 Characters", value: dimensions.characterSubjects, lowLabel: "abstract subjects", highLabel: "human agents as subjects" },
273
+ { name: "Topic string consistency",lesson: "L5 Cohesion", value: dimensions.topicStringConsistency, lowLabel: "varied openings", highLabel: "consistent topic strings" },
274
+ { name: "Old-before-new", lesson: "L5 Cohesion", value: dimensions.oldBeforeNew, lowLabel: "new-first for surprise", highLabel: "strict old→new flow" },
275
+ { name: "Thematic string density",lesson: "L5 Coherence", value: dimensions.thematicStringDensity, lowLabel: "synonymic variety", highLabel: "key term repetition" },
276
+ { name: "Stress position", lesson: "L6 Emphasis", value: dimensions.stressPosition, lowLabel: "distributed emphasis", highLabel: "punch at sentence end" },
277
+ { name: "Periodic structure", lesson: "L6 Emphasis", value: dimensions.periodicStructure, lowLabel: "cumulative (main first)", highLabel: "periodic (delay main)" },
278
+ { name: "Short-to-long", lesson: "L6 Emphasis", value: dimensions.shortToLong, lowLabel: "no length ordering", highLabel: "climactic build" },
279
+ { name: "Concision", lesson: "L7 Concision", value: dimensions.concision, lowLabel: "expansive, discursive", highLabel: "every word load-bearing" },
280
+ { name: "Coordination balance", lesson: "L8 Shape", value: dimensions.coordinationBalance, lowLabel: "asymmetric subordination", highLabel: "parallel balance" },
281
+ { name: "Sentence length", lesson: "L8 Shape", value: dimensions.sentenceLength, lowLabel: "short punchy sentences", highLabel: "long flowing sentences" },
282
+ { name: "Elegance devices", lesson: "L9 Elegance", value: dimensions.eleganceDevices, lowLabel: "plain functional prose", highLabel: "metaphor, chiasmus, anaphora" },
283
+ { name: "Length variation", lesson: "L9 Elegance", value: dimensions.lengthVariation, lowLabel: "uniform rhythm", highLabel: "dramatic variation" },
284
+ { name: "Formality", lesson: "L2 Correctness", value: dimensions.formality, lowLabel: "conversational, contractions", highLabel: "formal academic register" },
285
+ { name: "Metadiscourse", lesson: "L7 Concision", value: dimensions.metadiscourse, lowLabel: "minimal signposting", highLabel: "explicit transitions" },
286
+ { name: "Passive voice", lesson: "L3/L4 Actions+Characters",value: dimensions.passiveVoice, lowLabel: "always active voice", highLabel: "strategic passive" },
287
+ { name: "Motivating coherence", lesson: "L10 Motivating Coherence",value: dimensions.motivatingCoherence, lowLabel: "dives straight in", highLabel: "full issue→discussion→point" },
288
+ { name: "Global coherence", lesson: "L11 Global Coherence", value: dimensions.globalCoherence, lowLabel: "loose, exploratory", highLabel: "tight hierarchical sections" },
289
+ { name: "Ethical transparency", lesson: "L12 Ethics of Style", value: dimensions.ethicalTransparency, lowLabel: "persuasive emphasis", highLabel: "maximally transparent" },
290
+ ];
291
+
292
+ const systemPromptFragment = buildPromptFragment(dimensions, archetype);
293
+
294
+ const totalWeight = ARCHETYPES.reduce((sum, a) => sum + a.rarity, 0);
295
+ const rarityPercent = Math.round((archetype.rarity / totalWeight) * 1000) / 10;
296
+ const rarityTier = archetype.tier;
297
+
298
+ return { seed, dimensions, archetype, systemPromptFragment, dimensionLabels, rarityPercent, rarityTier };
299
+ }
300
+
301
+ // ─── Prompt fragment builder ───────────────────────────────────────
302
+ // Translates continuous dimension values into concrete prose instructions.
303
+
304
+ function describeLevel(val: number): "rarely" | "sometimes" | "often" | "consistently" {
305
+ if (val < 0.3) return "rarely";
306
+ if (val < 0.55) return "sometimes";
307
+ if (val < 0.75) return "often";
308
+ return "consistently";
309
+ }
310
+
311
+ function buildPromptFragment(d: WilliamsDimensions, arch: typeof ARCHETYPES[number]): string {
312
+ const lines: string[] = [];
313
+
314
+ lines.push(`STYLE PERSONA: "${arch.name}" — ${arch.desc}`);
315
+ lines.push("");
316
+ lines.push("Adopt the following stylistic profile. These are DIMENSIONS of clear prose under Joseph Williams' framework — all positions are valid conscious choices.");
317
+ lines.push("");
318
+
319
+ // L3: Actions
320
+ if (d.actionVerbs > 0.65) {
321
+ lines.push("ACTIONS (L3): Use strong, specific verbs for all actions. Convert nominalizations back to their verbs. Write 'We analyzed' not 'We performed an analysis of.' Write 'The temperature rose' not 'There was a rise in temperature.'");
322
+ } else if (d.actionVerbs > 0.4) {
323
+ lines.push("ACTIONS (L3): Prefer verbs for actions but permit nominalizations when they serve as familiar shorthand or refer to a concept already introduced. 'The analysis showed' is fine if 'analysis' was established earlier.");
324
+ } else {
325
+ lines.push("ACTIONS (L3): Use nominalizations strategically for abstraction, formality, and conceptual reference. 'The investigation of the phenomenon' is appropriate when discussing it as an object of study.");
326
+ }
327
+
328
+ // L4: Characters
329
+ if (d.characterSubjects > 0.65) {
330
+ lines.push("CHARACTERS (L4): Make the characters — the agents doing things — the grammatical subjects of sentences. Prefer 'Researchers found' over 'It was found.' Put people and named entities in the subject position.");
331
+ } else if (d.characterSubjects > 0.4) {
332
+ lines.push("CHARACTERS (L4): Use a mix of human agents and abstract subjects. Institutional subjects are fine ('The study examined…') but avoid long chains of sentences where no human agent ever appears.");
333
+ } else {
334
+ lines.push("CHARACTERS (L4): Permit abstract and institutional subjects when the topic is a process, system, or concept rather than a person. 'The framework enables…' or 'This approach yields…' are natural.");
335
+ }
336
+
337
+ // L5: Cohesion and Coherence
338
+ if (d.topicStringConsistency > 0.65) {
339
+ lines.push("COHESION (L5): Maintain consistent topic strings — begin most sentences in a paragraph with the same subject or a closely related one. This creates a strong thematic thread the reader can follow.");
340
+ } else {
341
+ lines.push("COHESION (L5): Vary sentence openings. While some consistency helps, shift subjects to show different facets of the topic.");
342
+ }
343
+
344
+ if (d.oldBeforeNew > 0.65) {
345
+ lines.push("INFORMATION FLOW (L5): " + describeLevel(d.oldBeforeNew) + " place familiar (old) information at the beginning of each sentence and save new, complex, or surprising information for the end.");
346
+ }
347
+
348
+ if (d.thematicStringDensity > 0.6) {
349
+ lines.push("THEMATIC STRINGS (L5): Repeat key thematic terms rather than substituting synonyms. Repetition aids coherence more than elegant variation.");
350
+ } else {
351
+ lines.push("THEMATIC STRINGS (L5): Use varied vocabulary — synonyms, near-synonyms, and paraphrases — to avoid monotony while maintaining coherence through context.");
352
+ }
353
+
354
+ // L6: Emphasis
355
+ if (d.stressPosition > 0.65) {
356
+ lines.push("STRESS POSITION (L6): " + describeLevel(d.stressPosition) + " place the most important, complex, or newest information at the END of the sentence — the stress position. The final words carry the most weight.");
357
+ }
358
+
359
+ if (d.periodicStructure > 0.55) {
360
+ lines.push("PERIODIC SENTENCES (L6): Build toward the main clause. Open with subordinate clauses, conditions, or modifiers, and delay the main point for emphasis: 'Although X, and despite Y, the result was Z.'");
361
+ } else {
362
+ lines.push("CUMULATIVE SENTENCES (L6): Lead with the main clause, then add modifiers and qualifications: 'The result was Z, although X, and despite Y.' This is more direct and easier to process.");
363
+ }
364
+
365
+ if (d.shortToLong > 0.6) {
366
+ lines.push("CLIMACTIC ORDERING (L6): In lists and coordinate structures, arrange items from shortest to longest. Build toward the most complex or important item.");
367
+ }
368
+
369
+ // L7: Concision
370
+ if (d.concision > 0.7) {
371
+ lines.push("CONCISION (L7): Be tightly compressed. Cut meaningless words (kind of, basically, actually, generally). Eliminate redundant pairs (each and every, first and foremost). Replace wordy phrases with single words ('due to the fact that' → 'because'). Every word must earn its place.");
372
+ } else if (d.concision > 0.45) {
373
+ lines.push("CONCISION (L7): Be reasonably concise. Cut obvious padding but allow some discursive space for the reader to absorb complex ideas. Not every sentence needs to be minimal.");
374
+ } else {
375
+ lines.push("CONCISION (L7): Allow an expansive, unhurried pace. Use qualifying phrases and elaborations to let the reader ease into difficult material. Compression is not always clarity.");
376
+ }
377
+
378
+ // L7 sub: Metadiscourse
379
+ if (d.metadiscourse > 0.55) {
380
+ lines.push("METADISCOURSE (L7): Use explicit transitions and signposting ('First,' 'In contrast,' 'The key point is'). Guide the reader through the structure of the argument.");
381
+ } else {
382
+ lines.push("METADISCOURSE (L7): Minimize overt signposting. Let the logical structure speak through the arrangement of ideas rather than explicit labels.");
383
+ }
384
+
385
+ // L8: Shape
386
+ if (d.coordinationBalance > 0.6) {
387
+ lines.push("SHAPE (L8): Favor balanced, parallel coordinate structures. When listing or comparing, use grammatically parallel forms: 'not only X but also Y,' 'both A and B.' Symmetry creates clarity.");
388
+ } else {
389
+ lines.push("SHAPE (L8): Use subordination and nesting. Let some ideas be syntactically subordinate to others, reflecting their logical subordination. Complex ideas sometimes need complex structures.");
390
+ }
391
+
392
+ if (d.sentenceLength > 0.65) {
393
+ lines.push("SENTENCE LENGTH (L8): Favor longer, compound-complex sentences that develop ideas fully within a single syntactic structure. Connect related ideas with semicolons, colons, and subordinating conjunctions.");
394
+ } else if (d.sentenceLength < 0.35) {
395
+ lines.push("SENTENCE LENGTH (L8): Favor short, direct sentences. Break complex ideas into separate sentences. A sentence should do one thing clearly.");
396
+ }
397
+
398
+ // L9: Elegance
399
+ if (d.eleganceDevices > 0.55) {
400
+ lines.push("ELEGANCE (L9): Employ rhetorical devices where they serve meaning: balanced antithesis, chiasmus, anaphora (deliberate repetition at sentence starts), isocolon (clauses of equal length), and occasional extended metaphor. Make the sound of the prose reinforce its sense.");
401
+ } else {
402
+ lines.push("ELEGANCE (L9): Keep the prose plain and functional. Ornament should not compete with content. Clarity is the highest form of elegance.");
403
+ }
404
+
405
+ if (d.lengthVariation > 0.6) {
406
+ lines.push("RHYTHM (L9): Vary sentence length dramatically. Follow a long, complex sentence with a short, punchy one. The contrast creates emphasis and keeps the reader alert.");
407
+ } else {
408
+ lines.push("RHYTHM (L9): Maintain a steady, even rhythm. Consistency in sentence length creates a measured, professional tone.");
409
+ }
410
+
411
+ // L2: Register
412
+ if (d.formality > 0.65) {
413
+ lines.push("REGISTER (L2): Maintain a formal academic register. Avoid contractions, colloquialisms, and first person singular. Use precise technical vocabulary where appropriate.");
414
+ } else if (d.formality < 0.35) {
415
+ lines.push("REGISTER (L2): Write conversationally. Use contractions (it's, don't, can't). First person is natural. Address the reader directly when it helps.");
416
+ } else {
417
+ lines.push("REGISTER (L2): Use a moderate register — neither stiffly formal nor casually conversational. Professional but approachable.");
418
+ }
419
+
420
+ // L3/L4: Passive voice
421
+ if (d.passiveVoice > 0.35) {
422
+ lines.push("PASSIVE VOICE (L3/L4): Use the passive voice strategically — to maintain topic continuity ('The sample was then heated…' when 'sample' is the topic), to de-emphasize the agent, or when the agent is unknown or irrelevant. Do not use it to hide responsibility.");
423
+ } else {
424
+ lines.push("PASSIVE VOICE (L3/L4): Strongly prefer active voice. The passive is acceptable only when the agent is genuinely unknown or irrelevant.");
425
+ }
426
+
427
+ // L10: Motivating Coherence
428
+ if (d.motivatingCoherence > 0.65) {
429
+ lines.push("INTRODUCTIONS (L10): Frame responses with a clear issue statement, then develop the discussion, then state the point. For longer responses, begin with a brief context-setting introduction and end with a conclusion that states the main point.");
430
+ } else {
431
+ lines.push("INTRODUCTIONS (L10): Open directly with the most useful information. Minimize throat-clearing. The reader wants the answer, not the journey to it.");
432
+ }
433
+
434
+ // L11: Global Coherence
435
+ if (d.globalCoherence > 0.65) {
436
+ lines.push("GLOBAL STRUCTURE (L11): Organize responses into clearly scoped sections. Each paragraph should have a single focus. Transitions between paragraphs should make the logical relationship explicit.");
437
+ } else {
438
+ lines.push("GLOBAL STRUCTURE (L11): Allow a more fluid, exploratory structure. Ideas can develop organically. Not every paragraph needs a topic sentence.");
439
+ }
440
+
441
+ // L12: Ethics
442
+ if (d.ethicalTransparency > 0.7) {
443
+ lines.push("ETHICS (L12): Be maximally transparent. Surface uncertainty, caveats, and alternative interpretations. Do not use complexity to obscure weakness in the evidence. Prefer clarity over persuasiveness when they conflict. Never use difficult prose to seem more authoritative.");
444
+ } else {
445
+ lines.push("ETHICS (L12): Frame the argument clearly but allow emphasis and strategic word choice to guide the reader toward the best-supported conclusion. Persuasion through clarity — not obscurantism — is legitimate.");
446
+ }
447
+
448
+ lines.push("");
449
+ lines.push("IMPORTANT: These style instructions shape HOW you write, not WHAT you write. Factual accuracy, verification, and citation rules remain unchanged. Apply this style naturally — do not mention these instructions or label your style.");
450
+
451
+ return lines.join("\n");
452
+ }
453
+
454
+ // ─── Session seed generator ────────────────────────────────────────
455
+ // Creates a new seed from entropy sources. Each page load gets a
456
+ // different persona unless the user pins a seed.
457
+
458
+ export function newSessionSeed(): number {
459
+ return (Date.now() ^ (Math.random() * 0x7fffffff)) >>> 0;
460
+ }
461
+
462
+ // ─── Exports for UI ────────────────────────────────────────────────
463
+
464
+ export { ARCHETYPES };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Williams Style — persistent workspace override.
3
+ * Re-exports the full base module (ARCHETYPES, generatePersona, etc.) and adds
4
+ * getPersonaDirective(name): concrete, high-contrast per-archetype instructions
5
+ * so each persona produces a genuinely distinct voice instead of a name-only tag.
6
+ */
7
+ export * from "./williams-style.base";
8
+
9
+ export interface PersonaDirective {
10
+ voice: string; // one-line identity
11
+ do: string[]; // concrete stylistic imperatives
12
+ avoid: string[]; // anti-patterns
13
+ cadence: string; // sentence-rhythm rule
14
+ }
15
+
16
+ // 24 archetypes × distinct directives. Kept terse to bound prompt tokens while
17
+ // maximizing stylistic separation between personas.
18
+ const DIRECTIVES: Record<string, PersonaDirective> = {
19
+ "The Plain Dealer": { voice: "Blunt, agent-driven expert.", do: ["Subject-verb-object every sentence", "Name the actor before the action", "State the answer in the first line"], avoid: ["Nominalizations", "Hedging", "Ornament"], cadence: "Short, even, declarative." },
20
+ "The Architect": { voice: "Structural engineer of prose.", do: ["Use parallel coordinate structures", "Order lists short→long to a climax", "Signpost each section explicitly"], avoid: ["Asymmetric ragged clauses"], cadence: "Balanced, symmetric, measured." },
21
+ "The Narrator": { voice: "Story-driven explainer.", do: ["Put human agents in subject position", "Flow old→new information", "Keep one topic thread per paragraph"], avoid: ["Abstract institutional subjects"], cadence: "Flowing, connected, sequential." },
22
+ "The Explainer": { voice: "Patient teacher.", do: ["Hold a strict topic string", "Add heavy transitions (First, Next, Because)", "Define every term on first use"], avoid: ["Jargon without gloss"], cadence: "Steady, signposted, incremental." },
23
+ "The Scholar": { voice: "Formal academic.", do: ["Formal register, no contractions", "Strategic nominalizations for abstraction", "Explicit metadiscourse framing"], avoid: ["Colloquialism", "First-person singular"], cadence: "Long, qualified, precise." },
24
+ "The Surgeon": { voice: "Ruthless minimalist.", do: ["Cut every non-load-bearing word", "One idea per sentence", "Prefer verbs to phrases"], avoid: ["Adjectives", "Metadiscourse", "Ornament"], cadence: "Very short. Clipped. Exact." },
25
+ "The Advocate": { voice: "Persuasive closer.", do: ["Put the payload in the stress position", "Build short→long to a climax", "End sections on the strongest phrase"], avoid: ["Burying the point mid-sentence"], cadence: "Rising, climactic, emphatic." },
26
+ "The Diagnostician": { voice: "Evidence-balancer.", do: ["Issue → discussion → point structure", "Surface counter-evidence explicitly", "Weight claims by evidence strength"], avoid: ["Unqualified assertions"], cadence: "Deliberate, weighed, sectioned." },
27
+ "The Conversationalist": { voice: "Approachable peer.", do: ["Use contractions and second person", "Vary sentence openings", "Address the reader directly"], avoid: ["Stiff formality"], cadence: "Relaxed, varied, direct." },
28
+ "The Essayist": { voice: "Literary stylist.", do: ["Periodic builds that delay the main clause", "Elegant variation of vocabulary", "One artful disruption per section"], avoid: ["Monotone rhythm"], cadence: "Undulating, periodic, crafted." },
29
+ "The Weaver": { voice: "Long-form synthesizer.", do: ["Long subordinated sentences", "Dense thematic term repetition", "Connect ideas with semicolons and colons"], avoid: ["Choppy fragments"], cadence: "Long, nested, continuous." },
30
+ "The Minimalist": { voice: "Uniform plainness.", do: ["Cumulative sentences (main clause first)", "Uniform rhythm", "Almost no metadiscourse"], avoid: ["Periodic suspense", "Rhetorical flourish"], cadence: "Flat, even, unhurried." },
31
+ "The Cartographer": { voice: "Spatial mapper.", do: ["Frame the domain with spatial metaphors (layers, regions, boundaries)", "Give the reader a map before details", "Label structural relationships"], avoid: ["Formless enumeration"], cadence: "Structured, oriented, layered." },
32
+ "The Dialectician": { voice: "Tension-resolver.", do: ["State thesis, then antithesis, then synthesis", "Surface the strongest opposing view first", "Resolve explicitly"], avoid: ["One-sided argument"], cadence: "Oppositional then convergent." },
33
+ "The Crystallographer": { voice: "Faceted precision.", do: ["Make each paragraph a self-contained, complete facet", "Pack high information density per paragraph", "Refract the topic from multiple angles"], avoid: ["Loose, spilling paragraphs"], cadence: "Dense, discrete, complete blocks." },
34
+ "The Counselor": { voice: "Warm ethical guide.", do: ["Lead with empathy, then substance", "Surface uncertainty transparently", "Treat the reader as a partner"], avoid: ["Cold detachment", "False certainty"], cadence: "Warm, measured, candid." },
35
+ "The Polymath": { voice: "Cross-domain connector.", do: ["Bridge domains with precise analogies", "Keep high register but stay accessible", "Show structural isomorphisms"], avoid: ["Siloed single-domain framing"], cadence: "Expansive, connective, elegant." },
36
+ "The Sentinel": { voice: "Watchful risk-surfacer.", do: ["State every material assumption up front", "Flag each uncertainty and caveat before proceeding", "Separate verified from unverified explicitly", "Add jurisdiction/scope caveats"], avoid: ["Unqualified confidence", "Silent assumptions"], cadence: "Cautious, itemized, guarded." },
37
+ "The Oracle": { voice: "Delayed revelation.", do: ["Periodic mastery — every clause builds", "Withhold the decisive phrase until the end", "Make the final words carry the weight"], avoid: ["Front-loading the conclusion"], cadence: "Suspended, building, climactic." },
38
+ "The Alchemist": { voice: "Jargon transmuter.", do: ["Translate technical terms into vivid concrete images", "Preserve full rigor beneath accessibility", "Give an intuition then the precise form"], avoid: ["Undefined jargon", "Dumbing-down"], cadence: "Vivid, transforming, precise." },
39
+ "The Strategist": { voice: "Military brief.", do: ["Situation → Mission → Execution → Assessment", "Zero wasted words", "Lead each section with the bottom line"], avoid: ["Narrative meandering"], cadence: "Terse, sectioned, decisive." },
40
+ "The Philosopher": { voice: "First-principles reasoner.", do: ["Reason from premises to conclusions", "Use Socratic structure — question then resolve", "Define terms with rigor"], avoid: ["Assertion without derivation"], cadence: "Deliberate, abstract, ordered." },
41
+ "The Provocateur": { voice: "Conclusion-first challenger.", do: ["Open with the challenging conclusion", "Then prove it irrefutably with evidence", "Anticipate and dismantle objections"], avoid: ["Timid throat-clearing"], cadence: "Bold open, relentless proof." },
42
+ };
43
+
44
+ const FALLBACK: PersonaDirective = { voice: "Clear, calibrated expert.", do: ["Answer directly", "State assumptions", "Ground claims"], avoid: ["Hedging", "Ornament"], cadence: "Clear and even." };
45
+
46
+ export function getPersonaDirective(name?: string): string {
47
+ const d = (name && DIRECTIVES[name]) || FALLBACK;
48
+ return [
49
+ `PERSONA VOICE: ${d.voice}`,
50
+ `DO: ${d.do.join("; ")}.`,
51
+ `AVOID: ${d.avoid.join("; ")}.`,
52
+ `CADENCE: ${d.cadence}`,
53
+ "Apply this voice invisibly — never name or describe the persona; factual accuracy, verification and citation rules are unchanged.",
54
+ ].join("\n");
55
+ }
56
+
57
+ export function listPersonaDirectives(): Array<{ name: string } & PersonaDirective> {
58
+ return Object.entries(DIRECTIVES).map(([name, d]) => ({ name, ...d }));
59
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Web Worker Pool — Parallel computation engine.
3
+ * Spawns workers based on navigator.hardwareConcurrency.
4
+ * Enables parallel scraping, computation, and Pyodide execution.
5
+ */
6
+
7
+ export interface WorkerTask {
8
+ id: string;
9
+ type: "compute" | "scrape" | "pyodide" | "crypto";
10
+ payload: any;
11
+ }
12
+
13
+ export interface WorkerResult {
14
+ taskId: string;
15
+ success: boolean;
16
+ result?: any;
17
+ error?: string;
18
+ }
19
+
20
+ export class WorkerPool {
21
+ private workers: Worker[] = [];
22
+ private queue: Array<{ task: WorkerTask; resolve: (r: WorkerResult) => void }> = [];
23
+ private active = 0;
24
+ private maxWorkers: number;
25
+
26
+ constructor(maxWorkers?: number) {
27
+ this.maxWorkers = maxWorkers || navigator.hardwareConcurrency || 4;
28
+ this.initWorkers();
29
+ }
30
+
31
+ private initWorkers() {
32
+ for (let i = 0; i < this.maxWorkers; i++) {
33
+ const worker = new Worker(new URL("./compute.worker.ts", import.meta.url), { type: "module" });
34
+ worker.onmessage = (e) => this.handleMessage(e.data);
35
+ this.workers.push(worker);
36
+ }
37
+ }
38
+
39
+ private handleMessage(data: WorkerResult & { workerId?: number }) {
40
+ this.active--;
41
+ const item = this.queue.shift();
42
+ if (item) {
43
+ this.active++;
44
+ item.resolve(data);
45
+ this.processQueue();
46
+ }
47
+ }
48
+
49
+ private processQueue() {
50
+ while (this.active < this.maxWorkers && this.queue.length > 0) {
51
+ const { task } = this.queue.shift()!;
52
+ const worker = this.workers.find((_, i) => i < this.maxWorkers);
53
+ if (worker) {
54
+ this.active++;
55
+ worker.postMessage(task);
56
+ }
57
+ }
58
+ }
59
+
60
+ public async enqueue(task: WorkerTask): Promise<WorkerResult> {
61
+ return new Promise((resolve) => {
62
+ this.queue.push({ task, resolve });
63
+ this.processQueue();
64
+ });
65
+ }
66
+
67
+ public async enqueueAll(tasks: WorkerTask[]): Promise<WorkerResult[]> {
68
+ return Promise.all(tasks.map((t) => this.enqueue(t)));
69
+ }
70
+
71
+ public terminate() {
72
+ this.workers.forEach((w) => w.terminate());
73
+ this.workers = [];
74
+ this.queue = [];
75
+ this.active = 0;
76
+ }
77
+
78
+ public getStats() {
79
+ return {
80
+ maxWorkers: this.maxWorkers,
81
+ active: this.active,
82
+ queued: this.queue.length,
83
+ hardwareConcurrency: navigator.hardwareConcurrency,
84
+ };
85
+ }
86
+ }
87
+
88
+ // Singleton instance
89
+ let poolInstance: WorkerPool | null = null;
90
+
91
+ export function getWorkerPool(): WorkerPool {
92
+ if (!poolInstance) {
93
+ poolInstance = new WorkerPool();
94
+ }
95
+ return poolInstance;
96
+ }