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,188 @@
1
+ /**
2
+ * Medical Domain Pack v1
3
+ *
4
+ * Targets text-detectable failure modes in medical/clinical content:
5
+ * - HIPAA PHI Safe-Harbor identifier leakage (Aptible, AccountableHQ, MedGemma)
6
+ * - Drug dosing without indication / age / route
7
+ * - Drug-drug interactions without checked guardrail
8
+ * - Black-box warning omission
9
+ * - Off-label use without disclosure
10
+ * - Differential diagnosis without red-flag screen
11
+ * - Clinical advice without "consult a clinician" caveat
12
+ * - Imaging interpretation as definitive without radiologist sign-off
13
+ * - Pregnancy/lactation category absent for prescribing context
14
+ * - Pediatric dose extrapolated from adult mg, not mg/kg
15
+ */
16
+ import { type FlawDetector, type FlawIssue, type ScanContext } from "../flaw-registry";
17
+
18
+ const mk = (
19
+ severity: FlawIssue["severity"],
20
+ code: string,
21
+ message: string,
22
+ remediation: string,
23
+ ): FlawIssue => ({ severity, code, message, remediation });
24
+
25
+ function T(c: ScanContext): string { return `${c.prompt}\n${c.answer}`; }
26
+ function isMedical(c: ScanContext): boolean {
27
+ return /\b(patient|clinic|diagnos|dosage|dose|mg|mcg|prescrib|symptom|treatment|medicat|drug|disease|disorder|syndrome|hospital|physician|nurse|EHR|EMR|ICD-10|CPT|HIPAA|PHI|MRN|medical record|chart note|SOAP note|differential|lab result|radiology|pathology|surgery|protocol|guideline)\b/i.test(T(c));
28
+ }
29
+ function isPrescriptive(c: ScanContext): boolean {
30
+ return /\b(prescribe|administer|give|dose|dosage|recommend|protocol|regimen)\b/i.test(c.answer) && isMedical(c);
31
+ }
32
+ function isDiagnostic(c: ScanContext): boolean {
33
+ return /\b(diagnos|differential|workup|rule[-\s]?out|likely cause|what is wrong|what could this be)\b/i.test(T(c));
34
+ }
35
+
36
+ export const MEDICAL_FLAWS: FlawDetector[] = [
37
+ // ── HIPAA PHI Safe Harbor: structured identifier leakage ──────────────────
38
+ {
39
+ id: "med.phi-ssn-leak",
40
+ domain: "domain",
41
+ description: "HIPAA #19: Social Security Number pattern (XXX-XX-XXXX) in clinical content.",
42
+ appliesTo: isMedical,
43
+ scan: c => /\b\d{3}-\d{2}-\d{4}\b/.test(c.answer) && !/\b(example|fake|de-identified|synthetic)\b/i.test(c.answer)
44
+ ? [mk("critical", "MED_PHI_SSN_LEAK", "Social Security Number pattern detected in medical/clinical content — HIPAA Safe-Harbor #19 violation.", "Remove or replace with `XXX-XX-XXXX` placeholder. SSN must never appear in PHI unless de-identified per HIPAA Safe Harbor.")]
45
+ : [],
46
+ },
47
+ {
48
+ id: "med.phi-mrn-leak",
49
+ domain: "domain",
50
+ description: "HIPAA #6: Medical Record Number leakage.",
51
+ appliesTo: isMedical,
52
+ scan: c => /\b(?:MRN|Medical\s+Record\s+(?:Number|#)?)[\s:#]*[A-Z]?\d{6,}\b/i.test(c.answer) && !/\b(example|sample|de-identified|fake|synthetic|test patient)\b/i.test(c.answer)
53
+ ? [mk("critical", "MED_PHI_MRN_LEAK", "Medical Record Number leaked in clinical content (HIPAA #6).", "De-identify MRN per HIPAA Safe Harbor. Use surrogate IDs for examples; never include real MRNs in shared content.")]
54
+ : [],
55
+ },
56
+ {
57
+ id: "med.phi-dob-leak",
58
+ domain: "domain",
59
+ description: "HIPAA #3: Date of Birth leakage (full date, not just year).",
60
+ appliesTo: isMedical,
61
+ scan: c => /\b(?:DOB|Date\s+of\s+Birth|born\s+on)[\s:]*(?:0[1-9]|1[0-2])[\/\-](?:0[1-9]|[12]\d|3[01])[\/\-]\d{4}\b/i.test(c.answer) && !/\b(example|sample|de-identified|fake)\b/i.test(c.answer)
62
+ ? [mk("critical", "MED_PHI_DOB_LEAK", "Full Date of Birth detected (HIPAA Safe Harbor #3 — only year may remain).", "Replace DOB with year only, or aggregate ages 90+ per HIPAA Safe Harbor.")]
63
+ : [],
64
+ },
65
+ {
66
+ id: "med.phi-phone-leak",
67
+ domain: "domain",
68
+ description: "HIPAA #5: Phone number leakage in clinical content.",
69
+ appliesTo: isMedical,
70
+ scan: c => /\b(?:patient|home|cell|mobile)\s+(?:phone|number|tel)[\s:#]*(?:\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4})\b/i.test(c.answer) && !/\b(example|sample|fake|de-identified)\b/i.test(c.answer)
71
+ ? [mk("major", "MED_PHI_PHONE_LEAK", "Patient phone number detected (HIPAA #5).", "Remove or replace with placeholder. Phone numbers are Safe-Harbor identifiers.")]
72
+ : [],
73
+ },
74
+
75
+ // ── Clinical safety: dosing context ───────────────────────────────────────
76
+ {
77
+ id: "med.dose-no-weight-pediatric",
78
+ domain: "domain",
79
+ description: "Adult-style mg dose for a pediatric patient instead of weight-based mg/kg.",
80
+ appliesTo: isPrescriptive,
81
+ scan: c => /\b(child|pediatric|infant|neonate|toddler|kid|baby|<\s*12\s*y(?:r|ear)?|aged?\s+\d+\s*(?:month|year))/i.test(T(c))
82
+ && /\b\d+\s*(?:mg|mcg|µg|g)\b/i.test(c.answer)
83
+ && !/\b\d+(?:\.\d+)?\s*(?:mg|mcg|µg)\s*\/\s*kg\b/i.test(c.answer)
84
+ ? [mk("critical", "MED_DOSE_NO_PEDIATRIC_WEIGHT", "Pediatric dose given as flat mg without weight-based mg/kg calculation.", "Always express pediatric dosing as mg/kg (or mg/m²) with a stated max-dose ceiling. Flat adult-style dosing in pediatrics risks overdose or therapeutic failure.")]
85
+ : [],
86
+ },
87
+ {
88
+ id: "med.dose-no-route",
89
+ domain: "domain",
90
+ description: "Drug dose without route of administration (PO/IV/IM/SC).",
91
+ appliesTo: isPrescriptive,
92
+ scan: c => /\b\d+\s*(?:mg|mcg|µg|g|mL|units?)\b[\s\S]{0,40}\b(?:every|q\s*\d|daily|BID|TID|QID|once|twice)\b/i.test(c.answer)
93
+ && !/\b(PO|IV|IM|SC|SubQ|sublingual|SL|intranasal|topical|rectal|PR|inhaled|nebuli[sz]ed|by\s+mouth|orally|intravenous|intramuscular|subcutaneous)\b/i.test(c.answer)
94
+ ? [mk("major", "MED_DOSE_NO_ROUTE", "Drug dose and frequency given without an explicit route of administration.", "Always specify route (PO, IV, IM, SC, SL, etc.). Same dose by different routes has different bioavailability and onset.")]
95
+ : [],
96
+ },
97
+ {
98
+ id: "med.opioid-no-naloxone",
99
+ domain: "domain",
100
+ description: "Opioid prescription without naloxone co-prescription per CDC guidance.",
101
+ appliesTo: isPrescriptive,
102
+ scan: c => /\b(oxycodone|hydrocodone|morphine|fentanyl|methadone|hydromorphone|oxymorphone|tramadol|codeine)\b/i.test(c.answer)
103
+ && /\b(prescribe|prescription|Rx|outpatient|discharge|home with)\b/i.test(c.answer)
104
+ && !/\b(naloxone|Narcan|overdose education|risk mitigation)\b/i.test(c.answer)
105
+ ? [mk("major", "MED_OPIOID_NO_NALOXONE", "Outpatient opioid prescription without naloxone co-prescription / overdose-risk discussion.", "Per CDC 2022 Clinical Practice Guideline: co-prescribe naloxone for any patient receiving opioids, especially with concurrent benzodiazepines, sleep apnea, or substance use history.")]
106
+ : [],
107
+ },
108
+ {
109
+ id: "med.ddi-warfarin",
110
+ domain: "domain",
111
+ description: "Warfarin co-prescribed with NSAID/antibiotic without INR monitoring caveat.",
112
+ appliesTo: isPrescriptive,
113
+ scan: c => /\b(warfarin|coumadin)\b/i.test(c.answer)
114
+ && /\b(NSAID|ibuprofen|naproxen|aspirin|metronidazole|fluconazole|TMP[-\s]?SMX|trimethoprim|ciprofloxacin|amiodarone)\b/i.test(c.answer)
115
+ && !/\b(INR\s+(?:monitor|check|recheck)|bleeding risk|dose\s+adjust)\b/i.test(c.answer)
116
+ ? [mk("critical", "MED_DDI_WARFARIN", "Known major warfarin drug-drug interaction without INR monitoring/dose-adjustment plan.", "Document INR monitoring frequency and dose-adjustment plan; consider therapeutic alternative. Warfarin interactions with NSAIDs, fluconazole, metronidazole, TMP-SMX, and amiodarone are clinically significant.")]
117
+ : [],
118
+ },
119
+ {
120
+ id: "med.pregnancy-category-missing",
121
+ domain: "domain",
122
+ description: "Prescribing a drug to a pregnant patient without pregnancy-risk discussion.",
123
+ appliesTo: isPrescriptive,
124
+ scan: c => /\b(pregnan|gravid|prenatal|breastfeed|lactat)\b/i.test(T(c))
125
+ && /\b(prescribe|administer|start|initiate)\b/i.test(c.answer)
126
+ && !/\b(category\s+[ABCDX]|FDA\s+pregnancy|teratogen|fetal\s+risk|PLLR|risk[-\s]benefit)\b/i.test(c.answer)
127
+ ? [mk("major", "MED_PREGNANCY_CATEGORY_MISSING", "Prescribing in pregnancy/lactation context without explicit fetal/neonatal risk discussion.", "State FDA Pregnancy and Lactation Labeling Rule (PLLR) section or pre-2015 category; discuss known teratogenicity, lactation transfer, and risk-benefit explicitly.")]
128
+ : [],
129
+ },
130
+
131
+ // ── Diagnostic safety ─────────────────────────────────────────────────────
132
+ {
133
+ id: "med.diagnostic-no-red-flag",
134
+ domain: "domain",
135
+ description: "Common-presentation differential without red-flag/cant-miss screen.",
136
+ appliesTo: isDiagnostic,
137
+ scan: c => /\b(chest\s+pain|headache|abdominal\s+pain|back\s+pain|dyspnea|syncope|fever|altered mental status)\b/i.test(T(c))
138
+ && /\b(likely|most likely|probably|likely diagnosis|most common cause)\b/i.test(c.answer)
139
+ && !/\b(red\s+flags?|cannot\s+miss|emergent|life[-\s]?threatening|rule\s+out|ED evaluation|STEMI|PE|SAH|AAA|meningitis|sepsis)\b/i.test(c.answer)
140
+ ? [mk("critical", "MED_DIAGNOSTIC_NO_RED_FLAG", "Differential for a high-risk chief complaint without explicit red-flag / cant-miss diagnoses.", "For high-risk presentations (chest pain, headache, abdominal pain, syncope), always enumerate emergent must-not-miss diagnoses first (STEMI, PE, SAH, AAA, meningitis, sepsis) with disposition guidance.")]
141
+ : [],
142
+ },
143
+ {
144
+ id: "med.imaging-as-definitive",
145
+ domain: "domain",
146
+ description: "Imaging interpretation given as definitive without radiologist sign-off caveat.",
147
+ appliesTo: c => /\b(CT|MRI|X-ray|ultrasound|imaging|scan|radiograph|chest\s+film)\b/i.test(T(c)) && isMedical(c),
148
+ scan: c => /\b(shows|demonstrates|reveals|confirms)\b[\s\S]{0,80}\b(fracture|mass|tumor|lesion|effusion|infarct|hemorrhage)\b/i.test(c.answer)
149
+ && !/\b(radiologist|formal read|preliminary|wet read|requires\s+formal|pending\s+(?:formal|official)|consult\s+(?:radiology|imaging))\b/i.test(c.answer)
150
+ ? [mk("major", "MED_IMAGING_AS_DEFINITIVE", "Imaging interpretation stated as definitive without radiologist confirmation caveat.", "Always defer to formal radiologist interpretation. Preliminary reads (especially from non-radiologists) require explicit caveat and follow-up.")]
151
+ : [],
152
+ },
153
+
154
+ // ── Clinical advice scope ─────────────────────────────────────────────────
155
+ {
156
+ id: "med.advice-no-clinician-caveat",
157
+ domain: "domain",
158
+ description: "Direct clinical advice to a layperson without 'consult a clinician' guidance.",
159
+ appliesTo: c => isMedical(c) && !/\b(physician|nurse|clinician|provider|EHR|hospital|chart note|SOAP|protocol|guideline)\b/i.test(c.prompt),
160
+ scan: c => /\b(you should take|you should stop|increase your dose|reduce your dose|you have|you probably have|you most likely have)\b/i.test(c.answer)
161
+ && !/\b(consult\s+(?:your\s+)?(?:doctor|physician|clinician|provider)|seek\s+medical\s+(?:care|attention)|see\s+a\s+(?:doctor|physician|clinician)|not\s+a\s+substitute\s+for|medical\s+professional)\b/i.test(c.answer)
162
+ ? [mk("major", "MED_ADVICE_NO_CLINICIAN_CAVEAT", "Direct clinical instruction to a layperson without 'consult a clinician' / not-medical-advice caveat.", "Add: 'This is not medical advice. Consult a licensed healthcare provider before changing medications or treatment.' Required for safety and liability.")]
163
+ : [],
164
+ },
165
+ {
166
+ id: "med.off-label-undisclosed",
167
+ domain: "domain",
168
+ description: "Off-label use of a drug recommended without disclosure of off-label status.",
169
+ appliesTo: isPrescriptive,
170
+ scan: c => /\b(gabapentin\s+for\s+(?:anxiety|sleep)|propranolol\s+for\s+anxiety|amitriptyline\s+for\s+(?:migraine|pain|sleep)|ketamine\s+for\s+depression|trazodone\s+for\s+sleep|mirtazapine\s+for\s+appetite|hydroxyzine\s+for\s+anxiety)\b/i.test(c.answer)
171
+ && !/\b(off[-\s]?label|not\s+FDA[-\s]?approved\s+for|outside\s+(?:the\s+)?approved\s+indication)\b/i.test(c.answer)
172
+ ? [mk("warning", "MED_OFF_LABEL_UNDISCLOSED", "Off-label drug use recommended without disclosing off-label status.", "Disclose off-label status; cite evidence base; document informed-consent considerations.")]
173
+ : [],
174
+ },
175
+
176
+ // ── Misinformation / known anti-patterns ──────────────────────────────────
177
+ {
178
+ id: "med.antibiotic-viral",
179
+ domain: "domain",
180
+ description: "Antibiotics recommended for a clearly viral illness.",
181
+ appliesTo: isPrescriptive,
182
+ scan: c => /\b(common\s+cold|viral\s+URI|viral\s+pharyngitis|viral\s+gastroenteritis|influenza|bronchiolitis|RSV|COVID[-\s]?19|rhinovirus)\b/i.test(T(c))
183
+ && /\b(amoxicillin|azithromycin|cephalexin|doxycycline|ciprofloxacin|prescribe\s+antibiotic|start\s+antibiotic)\b/i.test(c.answer)
184
+ && !/\b(bacterial\s+superinfection|secondary\s+bacterial|not\s+routinely|antibiotic\s+steward)\b/i.test(c.answer)
185
+ ? [mk("critical", "MED_ANTIBIOTIC_VIRAL", "Antibiotics recommended for an explicitly viral illness — contributes to resistance and side-effect burden.", "Per antibiotic stewardship: viral URIs, viral pharyngitis, bronchiolitis do not require antibiotics. Reserve for confirmed/suspected bacterial superinfection.")]
186
+ : [],
187
+ },
188
+ ];
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Original 246-Defense Pack — additive V15 mapping of the FULL npm package
3
+ * defense corpus into the V15 flaw-registry.
4
+ *
5
+ * Sources (imported directly from the npm package — verbatim, no mutation):
6
+ * • FAILURE_MODES (186 named failure-mode → solution mappings)
7
+ * • KERNEL_DEFENSES (60 kernel-layer pipeline defenses)
8
+ *
9
+ * Total: 246 defenses (matches the "126 defenses / 4-stage pipeline" banner
10
+ * count plus the additional 120 catalogued classes).
11
+ *
12
+ * This pack ONLY registers META-DETECTORS: one info-severity anchor per
13
+ * defense, keyed to substring/regex hints derived from each defense's name +
14
+ * solution text, so V15 can surface exactly which named defense category a
15
+ * given answer touches. It NEVER mutates any of the existing flaw packs
16
+ * (builtin, statistics, medical, legal, finance, software-*), and it is
17
+ * loaded only via ensureOriginalDefensePackLoaded() called from the V15
18
+ * pipeline — the base flaws/index.ts is untouched.
19
+ */
20
+ import { FAILURE_MODES } from "@/lib/failure-modes";
21
+ import { KERNEL_DEFENSES } from "@/lib/defense-registry";
22
+ import type { FlawDetector, FlawIssue } from "../flaw-registry";
23
+ import { registerFlawPack } from "../flaw-registry";
24
+
25
+ const mk = (severity: FlawIssue["severity"], code: string, message: string, remediation: string): FlawIssue =>
26
+ ({ severity, code, message, remediation });
27
+
28
+ /**
29
+ * A defense fires as an INFO-level anchor when its trigger phrases appear
30
+ * anywhere in the answer or prompt. It is intentionally low-weight so it
31
+ * cannot dominate scoring — it exists to surface which of the 246 defenses
32
+ * a given answer engages, which V15's editor/critique loop can then use as
33
+ * remediation context.
34
+ */
35
+ function makeAnchorDetector(id: string, code: string, name: string, group: string, solution: string): FlawDetector {
36
+ // Build cheap triggers from the defense's own words.
37
+ const words = (name + " " + solution).toLowerCase();
38
+ const tokens = Array.from(new Set(words.match(/[a-z]{5,}/g) ?? []))
39
+ .filter(w => !STOPWORDS.has(w))
40
+ .slice(0, 6);
41
+ const trigger = tokens.length > 0 ? new RegExp(`\\b(?:${tokens.join("|")})\\b`, "i") : null;
42
+ return {
43
+ id: `orig.${id}`,
44
+ domain: "domain",
45
+ description: `${group}: ${name}`,
46
+ appliesTo: (c) => (trigger ? trigger.test(c.prompt) || trigger.test(c.answer) : false),
47
+ scan: () => [mk(
48
+ "info",
49
+ `ORIG_DEFENSE_${code}`,
50
+ `Answer touches the original defense catalog category "${name}" (${group}).`,
51
+ solution.slice(0, 240),
52
+ )],
53
+ };
54
+ }
55
+
56
+ const STOPWORDS = new Set([
57
+ "answer","every","against","without","which","should","would","could","those","these","their","being","other",
58
+ "return","because","between","through","before","after","under","above","never","always","cannot","doesnt","dont",
59
+ "match","input","output","claim","query","asked","using","given","based","cases","types","level","tools","across",
60
+ "chain","checks","checked","checker","source","sources","result","results","status","system","content","context",
61
+ "detail","details","format","string","strict","runtime","present","policy","module","modules","record","records",
62
+ "detection","detected","display","displayed","display","values","value","respond","response","responses",
63
+ ]);
64
+
65
+ const FAILURE_DETECTORS: FlawDetector[] = FAILURE_MODES.map((fm: any) =>
66
+ makeAnchorDetector(`fm.${fm.id}`, fm.id, fm.name, fm.superclassName, fm.solution)
67
+ );
68
+
69
+ const KERNEL_DETECTORS: FlawDetector[] = KERNEL_DEFENSES.map((k: any) =>
70
+ makeAnchorDetector(`kd.${k.id}`, k.id, k.name, k.group, k.wiredIn)
71
+ );
72
+
73
+ let loaded = false;
74
+ export function ensureOriginalDefensePackLoaded(): { ok: boolean; total: number } {
75
+ if (loaded) return { ok: true, total: FAILURE_DETECTORS.length + KERNEL_DETECTORS.length };
76
+ loaded = true;
77
+ registerFlawPack("original-246", [...FAILURE_DETECTORS, ...KERNEL_DETECTORS]);
78
+ return { ok: true, total: FAILURE_DETECTORS.length + KERNEL_DETECTORS.length };
79
+ }
80
+
81
+ export const ORIGINAL_DEFENSE_COUNT = FAILURE_MODES.length + KERNEL_DEFENSES.length;
@@ -0,0 +1,38 @@
1
+ {
2
+ "id": "org-policy",
3
+ "version": "1.0.0",
4
+ "description": "Example organization-specific policy pack loaded declaratively.",
5
+ "rules": [
6
+ {
7
+ "id": "org.internal-codename-leak",
8
+ "domain": "structural",
9
+ "severity": "major",
10
+ "code": "ORG_INTERNAL_CODENAME_LEAK",
11
+ "message": "Internal project codename leaked into external-facing content.",
12
+ "remediation": "Replace internal codenames (Project Bluebird, Operation Phoenix) with the approved public product name before publishing externally.",
13
+ "appliesWhenAny": ["external", "public", "blog", "press", "customer"],
14
+ "scanRegex": "\\b(Project Bluebird|Operation Phoenix|Skunkworks Alpha)\\b",
15
+ "scanFlags": "i"
16
+ },
17
+ {
18
+ "id": "org.secret-key-format",
19
+ "domain": "structural",
20
+ "severity": "critical",
21
+ "code": "ORG_SECRET_KEY_LEAK",
22
+ "message": "Live secret/API key pattern detected in output.",
23
+ "remediation": "Never emit live credentials. Replace with a placeholder like <YOUR_API_KEY> and rotate the leaked key immediately.",
24
+ "scanRegex": "\\b(sk-[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{36})\\b"
25
+ },
26
+ {
27
+ "id": "org.unapproved-vendor",
28
+ "domain": "domain",
29
+ "severity": "warning",
30
+ "code": "ORG_UNAPPROVED_VENDOR",
31
+ "message": "Recommends a vendor outside the approved procurement list.",
32
+ "remediation": "Recommend only vendors on the approved procurement allowlist, or flag the recommendation as requiring procurement review.",
33
+ "appliesWhenAny": ["vendor", "procurement", "purchase", "supplier"],
34
+ "scanRegex": "\\b(recommend|suggest|use|go with)\\b[\\s\\S]{0,60}\\b(UnapprovedCorp|ShadowVendor)\\b",
35
+ "scanFlags": "i"
36
+ }
37
+ ]
38
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Self-test harness (dev tool, not wired to UI).
3
+ * Run from a scratch script:
4
+ * import { runFlawSelfTest } from "./flaws/selftest";
5
+ * console.table(runFlawSelfTest());
6
+ * console.log(runFlawSelfTest().filter(t => !t.pass)); // failures only
7
+ */
8
+ import { ensureFlawsLoaded } from ".";
9
+ import { runFlawScan, runAutoFix, setPackEnabled, listPacks, type ScanContext } from "../flaw-registry";
10
+
11
+ function ctx(p: Partial<ScanContext>): ScanContext {
12
+ return {
13
+ prompt: p.prompt ?? "", answer: p.answer ?? "",
14
+ lowerAnswer: (p.answer ?? "").toLowerCase(),
15
+ computeRecords: p.computeRecords ?? [],
16
+ constraints: p.constraints ?? ({ explicitComparisonTargets: [], exclusions: [], formatHints: [], namedEntities: [] } as any),
17
+ sources: p.sources, anchorDateISO: p.anchorDateISO, domainTags: p.domainTags, templateId: p.templateId,
18
+ };
19
+ }
20
+ const has = (i: { code: string }[], code: string) => i.some((x) => x.code === code);
21
+
22
+ export function runFlawSelfTest(): { name: string; pass: boolean }[] {
23
+ ensureFlawsLoaded();
24
+ const t: { name: string; pass: boolean }[] = [];
25
+ const A = (name: string, pass: boolean) => t.push({ name, pass });
26
+
27
+ // ── BUILTIN: Numeric / Constraint ─────────────────────────────────────────
28
+ A("MISSING_UNITS", has(runFlawScan(ctx({ prompt: "calculate the cost", answer: "The total is 4200." })), "MISSING_UNITS"));
29
+ A("COMPUTE_VALUE_MISSING", has(runFlawScan(ctx({ prompt: "calc", answer: "no numbers here", computeRecords: [{ ok: true, label: "x", formula: "a+b", result: { y: 1234.56 } } as any] })), "COMPUTE_VALUE_MISSING"));
30
+ A("COMPUTE_VALUE tolerant (comma)", !has(runFlawScan(ctx({ prompt: "calc", answer: "result is 1,234.56 kg", computeRecords: [{ ok: true, label: "x", formula: "a+b", result: { y: 1234.56 } } as any] })), "COMPUTE_VALUE_MISSING"));
31
+ A("COMPUTE_VALUE nested", !has(runFlawScan(ctx({ prompt: "calc mass", answer: "final mass 1,234.56 kg", computeRecords: [{ ok: true, label: "mass", formula: "a+b", result: { nested: { massKg: 1234.56 } } } as any] })), "COMPUTE_VALUE_MISSING"));
32
+ A("COMPUTE_VALUE percent", !has(runFlawScan(ctx({ prompt: "calc rate", answer: "final rate is 50%", computeRecords: [{ ok: true, label: "rate", formula: "a/b", result: { rate: 0.5 } } as any] })), "COMPUTE_VALUE_MISSING"));
33
+ A("COMPUTE_FAILED", has(runFlawScan(ctx({ prompt: "calc", answer: "x", computeRecords: [{ ok: false, label: "psy", error: "div0" } as any] })), "COMPUTE_FAILED"));
34
+ A("OVERCONFIDENT_CERTAINTY", has(runFlawScan(ctx({ answer: "This is guaranteed to always work." })), "OVERCONFIDENT_CERTAINTY"));
35
+ A("SERIALIZATION_LEAK object", has(runFlawScan(ctx({ prompt: "calc", answer: "The yield is [object Object] kg." })), "SERIALIZATION_LEAK"));
36
+ A("SERIALIZATION_LEAK Infinity", has(runFlawScan(ctx({ prompt: "calc", answer: "Result: Infinity m/s" })), "SERIALIZATION_LEAK"));
37
+ A("SERIALIZATION_LEAK lowercase infinity NOT flagged", !has(runFlawScan(ctx({ prompt: "calc", answer: "the series tends to infinity gradually" })), "SERIALIZATION_LEAK"));
38
+
39
+ // ── BUILTIN: Citation / Format / Markup ───────────────────────────────────
40
+ A("CITATION_INDEX_OOR", has(runFlawScan(ctx({ answer: "per [S7] this holds", sources: [{ url: "a" }, { url: "b" }] })), "CITATION_INDEX_OOR"));
41
+ A("CITES_WITH_NO_SOURCES", has(runFlawScan(ctx({ answer: "supported by [Source 1].", sources: [] })), "CITES_WITH_NO_SOURCES"));
42
+ A("CRITIQUE_JSON_LEAK", has(runFlawScan(ctx({ answer: 'ok {"clear": false, "errors": ["a"]}' })), "CRITIQUE_JSON_LEAK"));
43
+ A("SYSTEM_MARKER_LEAK", has(runFlawScan(ctx({ answer: "intro\nREFERENCE OVERLAY\nbody" })), "SYSTEM_MARKER_LEAK"));
44
+ A("PLACEHOLDER_LEAK", has(runFlawScan(ctx({ answer: "Aims: [list of aims]" })), "PLACEHOLDER_LEAK"));
45
+ A("PERSONA_LEAKAGE", has(runFlawScan(ctx({ answer: "As an AI language model, I cannot fully answer." })), "PERSONA_LEAKAGE"));
46
+ A("VERIFICATION_PLAN_LEAKAGE", has(runFlawScan(ctx({ answer: "VERIFICATION PLAN MODE\nHypotheses:\n- H1" })), "VERIFICATION_PLAN_LEAKAGE"));
47
+ A("LAZY_TRUNCATION", has(runFlawScan(ctx({ answer: "Here is the start... rest of the code omitted for brevity." })), "LAZY_TRUNCATION"));
48
+ A("CODE_FENCE_UNCLOSED", has(runFlawScan(ctx({ answer: "```ts\nconst x = 1;\n" })), "CODE_FENCE_UNCLOSED"));
49
+ A("MATH_FENCE_UNCLOSED", has(runFlawScan(ctx({ answer: "Use $$ x^2 + y^2 = z^2 " })), "MATH_FENCE_UNCLOSED"));
50
+ A("MARKDOWN_LINK_EMPTY", has(runFlawScan(ctx({ answer: "Read more [here]()." })), "MARKDOWN_LINK_EMPTY"));
51
+ A("TABLE_COL_MISMATCH", has(runFlawScan(ctx({ answer: "| a | b | c |\n|---|---|---|\n| 1 | 2 |\n| 3 | 4 | 5 |" })), "TABLE_COL_MISMATCH"));
52
+ A("INTERNAL_NEGATION_CONTRADICTION", has(runFlawScan(ctx({ answer: ("The Treatment is effective. ").padEnd(160, "x") + " The Treatment is not effective." })), "INTERNAL_NEGATION_CONTRADICTION"));
53
+ A("TRUNCATED_OUTPUT", has(runFlawScan(ctx({ answer: "x".repeat(220) + " and" })), "TRUNCATED_OUTPUT"));
54
+ A("TRUNCATED list-item NOT flagged", !has(runFlawScan(ctx({ answer: ("Summary of risks across the horizon, expanded across domains so the gate is exceeded. ").padEnd(220, "z") + "\n- supply chain delay\n- currency exposure" })), "TRUNCATED_OUTPUT"));
55
+ A("REFUSAL_MIMICRY", has(runFlawScan(ctx({ answer: "The retrieved sources do not contain enough to propose anything.", sources: Array(9).fill({}) })), "REFUSAL_MIMICRY"));
56
+ A("BASE_RATE_NEGLECT", has(runFlawScan(ctx({ prompt: "cancer risk", answer: "Everyone who smokes gets cancer. 100% guaranteed." })), "BASE_RATE_NEGLECT"));
57
+ A("SYCOPHANCY_OUTPUT", has(runFlawScan(ctx({ prompt: "analyze data", answer: "Great question! The data shows..." })), "SYCOPHANCY_OUTPUT"));
58
+
59
+ // ── STATISTICS pack ───────────────────────────────────────────────────────
60
+ A("STAT_P_AS_PROB_NULL", has(runFlawScan(ctx({ prompt: "t-test", answer: "The p-value is the probability that the null hypothesis is true." })), "STAT_P_AS_PROB_NULL"));
61
+ A("STAT_THRESHOLD_WORSHIP", has(runFlawScan(ctx({ prompt: "regression", answer: "marginally significant (p = 0.06), a trend toward significance." })), "STAT_THRESHOLD_WORSHIP"));
62
+ A("STAT_NONSIG_AS_NO_EFFECT", has(runFlawScan(ctx({ prompt: "trial", answer: "p > 0.05, so there is no effect of the intervention." })), "STAT_NONSIG_AS_NO_EFFECT"));
63
+ A("STAT_P_EQUALS_ZERO", has(runFlawScan(ctx({ prompt: "chi-square", answer: "the test gave p = 0.000." })), "STAT_P_EQUALS_ZERO"));
64
+ A("STAT_SD_SE_CONFUSION", has(runFlawScan(ctx({ prompt: "trial outcome", answer: "The mean was 12.4 ± 0.8 SEM at baseline." })), "STAT_SD_SE_CONFUSION"));
65
+ A("STAT_CORR_CAUSATION", has(runFlawScan(ctx({ prompt: "cohort study", answer: "Coffee is correlated with longevity and therefore causes longer life." })), "STAT_CORR_CAUSATION"));
66
+ A("STAT_CORR_CAUSATION suppressed on disclaimer", !has(runFlawScan(ctx({ prompt: "pitfall", answer: "Correlation does not imply causation." })), "STAT_CORR_CAUSATION"));
67
+ A("STAT_DICHOTOMANIA", has(runFlawScan(ctx({ prompt: "analysis", answer: "We dichotomized the continuous biomarker at the median." })), "STAT_DICHOTOMANIA"));
68
+ A("STAT_CONTAMINATION", has(runFlawScan(ctx({ prompt: "LLM eval", answer: "GPT-4 achieved SOTA on the MMLU benchmark." })), "STAT_CONTAMINATION"));
69
+
70
+ // ── STATISTICS ADVANCED pack ──────────────────────────────────────────────
71
+ A("STAT_SOURCE_ACTIVITY", has(runFlawScan(ctx({ prompt: "forensic DNA", answer: "The likelihood ratio for the match proves he touched the weapon." })), "STAT_SOURCE_ACTIVITY"));
72
+ A("STAT_LINKAGE_PERFECT", has(runFlawScan(ctx({ prompt: "record linkage", answer: "We linked records and analyzed the matched dataset as final." })), "STAT_LINKAGE_PERFECT"));
73
+ A("STAT_CATE_OVERLAP_MISSING", has(runFlawScan(ctx({ prompt: "HTE", answer: "The causal forest found strong CATE variation across patients." })), "STAT_CATE_OVERLAP_MISSING"));
74
+ A("STAT_POSITION_BIAS", has(runFlawScan(ctx({ prompt: "recommender", answer: "We evaluated CTR and NDCG on clicks." })), "STAT_POSITION_BIAS"));
75
+ A("STAT_NEURO_DOUBLE_DIP", has(runFlawScan(ctx({ prompt: "fMRI", answer: "We selected voxels by the contrast and then tested them on the same contrast." })), "STAT_NEURO_DOUBLE_DIP"));
76
+ A("STAT_FAIRNESS_IMPOSSIBILITY", has(runFlawScan(ctx({ prompt: "fairness audit", answer: "The model achieved perfect calibration and equalized odds." })), "STAT_FAIRNESS_IMPOSSIBILITY"));
77
+
78
+ // ── SOFTWARE EXTENDED pack ────────────────────────────────────────────────
79
+ A("NODE_EVENT_LOOP_BLOCKING", has(runFlawScan(ctx({ prompt: "Express handler", answer: "app.get('/data', (req, res) => { const d = fs.readFileSync('./d.json'); res.json(JSON.parse(d)); });" })), "NODE_EVENT_LOOP_BLOCKING"));
80
+ A("NODE_PIPELINE_HTTP_DESTROY", has(runFlawScan(ctx({ prompt: "node stream", answer: "pipeline(fs.createReadStream(p), res, (err) => { if (err) res.end('error'); });" })), "NODE_PIPELINE_HTTP_DESTROY"));
81
+ A("NODE_CJS_ESM_INTEROP", has(runFlawScan(ctx({ prompt: "ESM module", answer: 'import { Router } from "express";\nconst dir = __dirname;' })), "NODE_CJS_ESM_INTEROP"));
82
+ A("NODE_FS_TOCTOU", has(runFlawScan(ctx({ prompt: "node fs", answer: "fs.access(p, fs.constants.F_OK, (e) => { if (!e) fs.readFile(p, cb); });" })), "NODE_FS_TOCTOU"));
83
+ A("NODE_SETMAXLISTENERS_MASK", has(runFlawScan(ctx({ prompt: "fix warning", answer: "server.setMaxListeners(0);" })), "NODE_SETMAXLISTENERS_MASK"));
84
+ A("NODE_HTTP_TIMEOUT_MISSING", has(runFlawScan(ctx({ prompt: "production server", answer: "const server = http.createServer(app); server.listen(3000);" })), "NODE_HTTP_TIMEOUT_MISSING"));
85
+ A("NODE_ASYNC_CONTEXT_LOSS", has(runFlawScan(ctx({ prompt: "observability", answer: "const als = new AsyncLocalStorage(); emitter.on('data', (d) => als.getStore());" })), "NODE_ASYNC_CONTEXT_LOSS"));
86
+ A("NODE_THEN_WITHOUT_CATCH", has(runFlawScan(ctx({ prompt: "node async", answer: "fetchData().then(data => process(data));" })), "NODE_THEN_WITHOUT_CATCH"));
87
+ A("NODE_THEN_WITHOUT_CATCH suppressed by .catch", !has(runFlawScan(ctx({ prompt: "node async", answer: "fetchData().then(d => process(d)).catch(e => log(e));" })), "NODE_THEN_WITHOUT_CATCH"));
88
+ A("TS_ANY_IO_BOUNDARY", has(runFlawScan(ctx({ prompt: "TS fetch", answer: "const data: any = await fetch('/api').then(r => r.json()); console.log(data.name);" })), "TS_ANY_IO_BOUNDARY"));
89
+ A("TS_STRICT_DISABLED", has(runFlawScan(ctx({ prompt: "tsconfig", answer: '{ "compilerOptions": { "strictNullChecks": false } }' })), "TS_STRICT_DISABLED"));
90
+ A("TS_STRICT_DISABLED suppressed when true", !has(runFlawScan(ctx({ prompt: "tsconfig", answer: '{ "compilerOptions": { "strict": true } }' })), "TS_STRICT_DISABLED"));
91
+ A("TS_SWITCH_NONEXHAUSTIVE", has(runFlawScan(ctx({ prompt: "reducer", answer: "switch (action.type) { case 'SET_LOADING': return 1; case 'SET_ERROR': return 2; default: return 0; }" })), "TS_SWITCH_NONEXHAUSTIVE"));
92
+ A("TS_MODULE_RESOLUTION_MISMATCH", has(runFlawScan(ctx({ prompt: "tsconfig", answer: '{ "type": "module", "compilerOptions": { "moduleResolution": "node", "module": "ESNext" } }' })), "TS_MODULE_RESOLUTION_MISMATCH"));
93
+ A("SWIFT_FORCE_UNWRAP", has(runFlawScan(ctx({ prompt: "Swift", answer: "let u = currentUser!.name\nlet t = authToken!.value" })), "SWIFT_FORCE_UNWRAP"));
94
+ A("SWIFT_GLOBAL_MUTABLE_STATE", has(runFlawScan(ctx({ prompt: "Swift Sendable", answer: "class Cache { static var shared: [String: Data] = [:] }" })), "SWIFT_GLOBAL_MUTABLE_STATE"));
95
+ A("SWIFT_MAINACTOR_NONISOLATED", has(runFlawScan(ctx({ prompt: "SwiftUI VM", answer: "class VM: ObservableObject { @Published var x = 0; func load(){ DispatchQueue.main.async { self.x = 1 } } }" })), "SWIFT_MAINACTOR_NONISOLATED"));
96
+ A("SWIFT_ACTOR_PROTOCOL_MISMATCH", has(runFlawScan(ctx({ prompt: "Swift protocol", answer: "protocol L { func load() }\n@MainActor final class VM: L { func load() {} }" })), "SWIFT_ACTOR_PROTOCOL_MISMATCH"));
97
+ A("SWIFT_TASK_DETACHED_ISOLATION", has(runFlawScan(ctx({ prompt: "Swift concurrency", answer: "Task.detached { self.viewModel.count += 1 }" })), "SWIFT_TASK_DETACHED_ISOLATION"));
98
+ A("SWIFT_NESTED_WEAK_SELF_NO_GUARDLET", has(runFlawScan(ctx({ prompt: "Swift Combine", answer: "publisher.sink { [weak self] _ in Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in self.update() } }" })), "SWIFT_NESTED_WEAK_SELF_NO_GUARDLET"));
99
+ A("TAILWIND_CONTAINER_NOT_CENTERED", has(runFlawScan(ctx({ prompt: "tailwind", answer: '<div className="container py-8">x</div>' })), "TAILWIND_CONTAINER_NOT_CENTERED"));
100
+ A("TAILWIND_DARK_MODE_FOUC", has(runFlawScan(ctx({ prompt: "dark mode", answer: "useEffect(() => { document.documentElement.classList.toggle('dark', localStorage.getItem('theme')==='dark'); }, []);" })), "TAILWIND_DARK_MODE_FOUC"));
101
+ A("TAILWIND_MONOREPO_SOURCE_MISSING", has(runFlawScan(ctx({ prompt: "tailwind monorepo packages/ui", answer: "module.exports = { theme: { extend: {} } }" })), "TAILWIND_MONOREPO_SOURCE_MISSING"));
102
+ A("TAILWIND_BREAKPOINT_UNIT_MISMATCH", has(runFlawScan(ctx({ prompt: "tailwind screens", answer: "screens: { sm: '640px', md: '48rem', lg: '1024px' }" })), "TAILWIND_BREAKPOINT_UNIT_MISMATCH"));
103
+ A("TAILWIND_RUNTIME_SAFELIST_MISSING", has(runFlawScan(ctx({ prompt: "tailwind cms contentful", answer: "const c = cms.theme; return <div className={`bg-${c}-500`} />;" })), "TAILWIND_RUNTIME_SAFELIST_MISSING"));
104
+ A("PY_EVAL_EXEC_UNTRUSTED", has(runFlawScan(ctx({ prompt: "flask", answer: "result = eval(request.form['expression'])" })), "PY_EVAL_EXEC_UNTRUSTED"));
105
+ A("PY_SQL_INJECTION", has(runFlawScan(ctx({ prompt: "python db", answer: "cursor.execute(f'SELECT * FROM users WHERE id = {user_id}')" })), "PY_SQL_INJECTION"));
106
+ A("PY_BARE_EXCEPT", has(runFlawScan(ctx({ prompt: "python", answer: "try:\n do_work()\nexcept:\n pass" })), "PY_BARE_EXCEPT"));
107
+ A("PY_BARE_EXCEPT suppressed when named", !has(runFlawScan(ctx({ prompt: "python", answer: "try:\n do_work()\nexcept Exception as e:\n log(e)" })), "PY_BARE_EXCEPT"));
108
+ A("GO_GOROUTINE_LEAK", has(runFlawScan(ctx({ prompt: "go worker", answer: "go func() { result := <-ch; process(result) }()" })), "GO_GOROUTINE_LEAK"));
109
+ A("GO_GOROUTINE suppressed with ctx.Done", !has(runFlawScan(ctx({ prompt: "go worker", answer: "go func() { select { case r := <-ch: process(r); case <-ctx.Done(): return } }()" })), "GO_GOROUTINE_LEAK"));
110
+ A("CPP_THREAD_NO_JOIN_DETACH", has(runFlawScan(ctx({ prompt: "C++ task", answer: "void run() { std::thread worker(processQueue); }" })), "CPP_THREAD_NO_JOIN_DETACH"));
111
+ A("CPP_THREAD suppressed with join", !has(runFlawScan(ctx({ prompt: "C++ thread", answer: "std::thread t(work); t.join();" })), "CPP_THREAD_NO_JOIN_DETACH"));
112
+
113
+ // ── SOFTWARE RN/WEBGL pack ────────────────────────────────────────────────
114
+ A("RN_EXPO_MANAGED_NATIVE_MODULE_CONFUSION", has(runFlawScan(ctx({ prompt: "Expo app", answer: "import { RNCamera } from 'react-native-camera';" })), "RN_EXPO_MANAGED_NATIVE_MODULE_CONFUSION"));
115
+ A("RN_TYPESCRIPT_PROP_TYPE_ERASURE", has(runFlawScan(ctx({ prompt: "React Native TurboModule TS", answer: "interface Props { x: any }; function Card(props: any) { return <View>{props.title}</View>; }" })), "RN_TYPESCRIPT_PROP_TYPE_ERASURE"));
116
+ A("RN_NEW_ARCH_CODEGEN_DRIFT", has(runFlawScan(ctx({ prompt: "TurboModule New Architecture", answer: "export interface Spec extends TurboModule { getData(): Promise<any>; }" })), "RN_NEW_ARCH_CODEGEN_DRIFT"));
117
+ A("RN_HERMES_ABI_MISMATCH", has(runFlawScan(ctx({ prompt: "RN New Architecture TurboModule", answer: "Set hermesEnabled: false to use JSC." })), "RN_HERMES_ABI_MISMATCH"));
118
+ A("RN_EXPO_UPDATES_OTA_BROKEN", has(runFlawScan(ctx({ prompt: "Expo Updates OTA Podfile upgrade helper", answer: "use_react_native!(:hermes_enabled => false)" })), "RN_EXPO_UPDATES_OTA_BROKEN"));
119
+ A("RN_NAVIGATION_VERSION_MIX", has(runFlawScan(ctx({ prompt: "RN nav", answer: "const S = createStackNavigator(); const N = createNativeStackNavigator();" })), "RN_NAVIGATION_VERSION_MIX"));
120
+ A("RN_FLATLIST_PERF", has(runFlawScan(ctx({ prompt: "RN list", answer: "<FlatList data={items} renderItem={({item}) => <Row item={item}/>} />" })), "RN_FLATLIST_PERF"));
121
+ A("RN_PLATFORM_OS_ASYMMETRY", has(runFlawScan(ctx({ prompt: "RN platform", answer: "if (Platform.OS === 'ios') { return <IosBtn/>; } return null;" })), "RN_PLATFORM_OS_ASYMMETRY"));
122
+ A("RN_USEEFFECT_LEAK", has(runFlawScan(ctx({ prompt: "RN keyboard", answer: "useEffect(() => { Keyboard.addListener('keyboardDidShow', onShow); }, []);" })), "RN_USEEFFECT_LEAK"));
123
+ A("RN_ABSOLUTEFILLOBJECT_REMOVED", has(runFlawScan(ctx({ prompt: "RN style", answer: "const o = { ...StyleSheet.absoluteFillObject };" })), "RN_ABSOLUTEFILLOBJECT_REMOVED"));
124
+ A("RN_PRESSABLE_HIDDEN_ACTIVITY_LEAK", has(runFlawScan(ctx({ prompt: "RN conditionally rendered Pressable hidden", answer: "{visible && <Pressable onPress={fn}><Text>Tap</Text></Pressable>}" })), "RN_PRESSABLE_HIDDEN_ACTIVITY_LEAK"));
125
+ A("RN_REANIMATED_RUNONJS_DEPRECATED", has(runFlawScan(ctx({ prompt: "Reanimated worklet", answer: "import { runOnJS, useSharedValue } from 'react-native-reanimated';" })), "RN_REANIMATED_RUNONJS_DEPRECATED"));
126
+ A("RN_KEYBOARD_AVOIDING_ANDROID_BROKEN", has(runFlawScan(ctx({ prompt: "RN keyboard", answer: '<KeyboardAvoidingView behavior="padding">' })), "RN_KEYBOARD_AVOIDING_ANDROID_BROKEN"));
127
+ A("WEBGL_NO_CTX_LOST_HANDLER", has(runFlawScan(ctx({ prompt: "Three.js", answer: "const renderer = new THREE.WebGLRenderer({ canvas });" })), "WEBGL_NO_CTX_LOST_HANDLER"));
128
+ A("WEBGL_SHADER_LEAK", has(runFlawScan(ctx({ prompt: "WebGL", answer: "const s = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(s, src); gl.compileShader(s); gl.getShaderInfoLog(s);" })), "WEBGL_SHADER_LEAK"));
129
+ A("WEBGL_NPOT", has(runFlawScan(ctx({ prompt: "webgl texture", answer: "const gl = canvas.getContext('webgl'); gl.generateMipmap(gl.TEXTURE_2D);" })), "WEBGL_NPOT"));
130
+ A("WEBGL_INSTANCED_UNCHECKED", has(runFlawScan(ctx({ prompt: "instanced", answer: "gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, count);" })), "WEBGL_INSTANCED_UNCHECKED"));
131
+ A("WEBGL_NO_GET_ERROR", has(runFlawScan(ctx({ prompt: "webgl draw", answer: "gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);" })), "WEBGL_NO_GET_ERROR"));
132
+ A("WEBGL_SHADER_INJECTION", has(runFlawScan(ctx({ prompt: "user shader", answer: "gl.shaderSource(shader, req.body.userShaderCode); gl.compileShader(shader);" })), "WEBGL_SHADER_INJECTION"));
133
+ A("WEBGL_SHADER_SILENT", has(runFlawScan(ctx({ prompt: "WebGL shader", answer: "const s = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(s, src); gl.compileShader(s); gl.attachShader(p, s);" })), "WEBGL_SHADER_SILENT"));
134
+ A("WEBGPU_DESTROY_MISSING", has(runFlawScan(ctx({ prompt: "WebGPU", answer: "device.createBuffer({ size: 1024, usage: GPUBufferUsage.STORAGE });" })), "WEBGPU_DESTROY_MISSING"));
135
+
136
+ // ── MEDICAL pack ──────────────────────────────────────────────────────────
137
+ A("MED_PHI_SSN_LEAK", has(runFlawScan(ctx({ prompt: "patient chart note", answer: "Patient SSN 123-45-6789 was admitted with chest pain." })), "MED_PHI_SSN_LEAK"));
138
+ A("MED_PHI_MRN_LEAK", has(runFlawScan(ctx({ prompt: "patient record", answer: "MRN: 4456721 admitted to the clinic." })), "MED_PHI_MRN_LEAK"));
139
+ A("MED_DOSE_NO_PEDIATRIC_WEIGHT", has(runFlawScan(ctx({ prompt: "pediatric dosing", answer: "Give the child 500 mg amoxicillin every 8 hours." })), "MED_DOSE_NO_PEDIATRIC_WEIGHT"));
140
+ A("MED_DOSE_NO_ROUTE", has(runFlawScan(ctx({ prompt: "prescribe medication", answer: "Administer 40 mg every 12 hours for the patient." })), "MED_DOSE_NO_ROUTE"));
141
+ A("MED_OPIOID_NO_NALOXONE", has(runFlawScan(ctx({ prompt: "prescribe opioid", answer: "Prescribe oxycodone for outpatient discharge pain management." })), "MED_OPIOID_NO_NALOXONE"));
142
+ A("MED_DDI_WARFARIN", has(runFlawScan(ctx({ prompt: "prescribe", answer: "Start warfarin and add fluconazole for the infection." })), "MED_DDI_WARFARIN"));
143
+ A("MED_PREGNANCY_CATEGORY_MISSING", has(runFlawScan(ctx({ prompt: "prescribe", answer: "The patient is pregnant; initiate the medication as needed." })), "MED_PREGNANCY_CATEGORY_MISSING"));
144
+ A("MED_DIAGNOSTIC_NO_RED_FLAG", has(runFlawScan(ctx({ prompt: "differential diagnosis", answer: "The chest pain is most likely musculoskeletal in origin." })), "MED_DIAGNOSTIC_NO_RED_FLAG"));
145
+ A("MED_IMAGING_AS_DEFINITIVE", has(runFlawScan(ctx({ prompt: "interpret imaging", answer: "The CT shows a fracture of the distal radius." })), "MED_IMAGING_AS_DEFINITIVE"));
146
+ A("MED_ADVICE_NO_CLINICIAN_CAVEAT", has(runFlawScan(ctx({ prompt: "I have a headache and fever", answer: "You probably have a viral infection. You should take ibuprofen." })), "MED_ADVICE_NO_CLINICIAN_CAVEAT"));
147
+ A("MED_ANTIBIOTIC_VIRAL", has(runFlawScan(ctx({ prompt: "common cold treatment", answer: "Prescribe amoxicillin for the common cold symptoms." })), "MED_ANTIBIOTIC_VIRAL"));
148
+ A("MED pack NOT firing on poem", !has(runFlawScan(ctx({ prompt: "poem about the sea", answer: "The patient tides return at dawn, a clinic of waves." })), "MED_DOSE_NO_ROUTE"));
149
+
150
+ // ── LEGAL pack ────────────────────────────────────────────────────────────
151
+ A("LEGAL_NO_ATTORNEY_DISCLAIMER", has(runFlawScan(ctx({ prompt: "Can I sue my landlord?", answer: "Yes, you should file a lawsuit and you can recover damages for the breach." })), "LEGAL_NO_ATTORNEY_DISCLAIMER"));
152
+ A("LEGAL_JURISDICTION_AGNOSTIC", has(runFlawScan(ctx({ prompt: "legal question", answer: "The statute of limitations is 2 years for this claim." })), "LEGAL_JURISDICTION_AGNOSTIC"));
153
+ A("LEGAL_CITATION_NO_REPORTER", has(runFlawScan(ctx({ prompt: "case law", answer: "As established in Smith v. Jones, the doctrine applies broadly here." })), "LEGAL_CITATION_NO_REPORTER"));
154
+ A("LEGAL_STATUTE_NO_SECTION", has(runFlawScan(ctx({ prompt: "federal law", answer: "This is governed by the United States Code on civil rights." })), "LEGAL_STATUTE_NO_SECTION"));
155
+ A("LEGAL_CONTRACT_NO_GOVERNING_LAW", has(runFlawScan(ctx({ prompt: "draft a contract", answer: "This Agreement: the parties hereby agree to the terms of service described herein." })), "LEGAL_CONTRACT_NO_GOVERNING_LAW"));
156
+ A("LEGAL_GDPR_CCPA_CONFLATION", has(runFlawScan(ctx({ prompt: "privacy law", answer: "GDPR and CCPA are basically the same; CCPA is the US GDPR." })), "LEGAL_GDPR_CCPA_CONFLATION"));
157
+ A("LEGAL_SOL_NO_JURISDICTION", has(runFlawScan(ctx({ prompt: "SOL", answer: "The statute of limitations is 3 years for this type of case." })), "LEGAL_SOL_NO_JURISDICTION"));
158
+ A("LEGAL pack NOT firing on prose", !has(runFlawScan(ctx({ prompt: "story", answer: "The law of the jungle ruled the ancient forest." })), "LEGAL_NO_ATTORNEY_DISCLAIMER"));
159
+
160
+ // ── FINANCE pack ──────────────────────────────────────────────────────────
161
+ A("FIN_NO_ADVISER_DISCLAIMER", has(runFlawScan(ctx({ prompt: "what stock should I buy", answer: "You should invest in NVDA now; put your money in tech." })), "FIN_NO_ADVISER_DISCLAIMER"));
162
+ A("FIN_GUARANTEED_RETURNS", has(runFlawScan(ctx({ prompt: "investment", answer: "This fund offers guaranteed returns with zero risk." })), "FIN_GUARANTEED_RETURNS"));
163
+ A("FIN_GUARANTEED suppressed for Treasury", !has(runFlawScan(ctx({ prompt: "investment", answer: "A U.S. Treasury T-bill is risk-free with guaranteed return of principal." })), "FIN_GUARANTEED_RETURNS"));
164
+ A("FIN_PAST_PERFORMANCE", has(runFlawScan(ctx({ prompt: "fund analysis", answer: "It returned 25% over the past 5 years and will continue to gain at that rate." })), "FIN_PAST_PERFORMANCE"));
165
+ A("FIN_TAX_NO_JURISDICTION", has(runFlawScan(ctx({ prompt: "tax question", answer: "Your capital gains tax rate is 15% on this sale." })), "FIN_TAX_NO_JURISDICTION"));
166
+ A("FIN_GAAP_IFRS_CONFLATION", has(runFlawScan(ctx({ prompt: "accounting", answer: "GAAP and IFRS are equivalent and interchangeable for reporting." })), "FIN_GAAP_IFRS_CONFLATION"));
167
+ A("FIN_BACKTEST_NO_OOS", has(runFlawScan(ctx({ prompt: "trading strategy", answer: "The backtest returned 40% annually on historical data." })), "FIN_BACKTEST_NO_OOS"));
168
+ A("FIN_SHARPE_NO_PERIOD", has(runFlawScan(ctx({ prompt: "portfolio metrics", answer: "The strategy has a Sharpe ratio of 2.3." })), "FIN_SHARPE_NO_PERIOD"));
169
+ A("FIN_CRYPTO_HOWEY", has(runFlawScan(ctx({ prompt: "token launch", answer: "Our token is not a security and won't be regulated by SEC." })), "FIN_CRYPTO_HOWEY"));
170
+ A("FIN_INSIDER_TRADING_MARKER", has(runFlawScan(ctx({ prompt: "trading", answer: "I got a tip from an insider; buy the stock before the announcement." })), "FIN_INSIDER_TRADING_MARKER"));
171
+ A("FIN_DEFI_NO_IL", has(runFlawScan(ctx({ prompt: "DeFi yield", answer: "This liquidity pool offers an APY of 80% on Uniswap." })), "FIN_DEFI_NO_IL"));
172
+ A("FIN pack NOT firing on prose", !has(runFlawScan(ctx({ prompt: "story", answer: "He invested his heart in the garden, yielding flowers each spring." })), "FIN_NO_ADVISER_DISCLAIMER"));
173
+
174
+ // ── AUTO-FIX smoke tests ──────────────────────────────────────────────────
175
+ const fx = runAutoFix('Real answer body sufficiently long to survive the safety floor of the auto fixer. {"clear":true,"errors":[]}');
176
+ A("autofix:strip-critique-json", fx.applied.includes("strip-critique-json"));
177
+ A("autofix:stat-fix-p-equals-zero", runAutoFix("The chi-square test gave p = 0.000 which was highly significant in this regression analysis.").applied.includes("stat-fix-p-equals-zero"));
178
+
179
+ // ── PACK toggle / introspection ───────────────────────────────────────────
180
+ A("setPackEnabled silences pack", (() => {
181
+ setPackEnabled("medical", false);
182
+ const fires = has(runFlawScan(ctx({ prompt: "patient chart", answer: "Patient SSN 123-45-6789." })), "MED_PHI_SSN_LEAK");
183
+ setPackEnabled("medical", true);
184
+ return !fires;
185
+ })());
186
+ A("listPacks includes all 8 packs", (() => {
187
+ const packs = listPacks().map(p => p.pack);
188
+ return ["builtin", "statistics", "statistics-advanced", "software-extended", "software-rn-webgl", "medical", "legal", "finance"].every(p => packs.includes(p));
189
+ })());
190
+
191
+ return t;
192
+ }
193
+
194
+ /** Convenience: throw if any assertion fails (CI gate). */
195
+ export function assertFlawSelfTest(): void {
196
+ const results = runFlawSelfTest();
197
+ const failures = results.filter(r => !r.pass);
198
+ if (failures.length > 0) {
199
+ throw new Error(`[selftest] ${failures.length}/${results.length} assertions FAILED:\n` + failures.map(f => ` ✗ ${f.name}`).join("\n"));
200
+ }
201
+ }