@jack200714/mafw 4.5.1

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 (631) hide show
  1. package/.opencode/mafw/.backup-v61/parametric/base-skill-manifest.yaml +2 -0
  2. package/.opencode/mafw/STATUS.md +6 -0
  3. package/.opencode/mafw/ledger.md +20 -0
  4. package/.opencode/mafw/memory/.harmonic_index.json +28 -0
  5. package/.opencode/mafw/memory/.review_queue.json +1 -0
  6. package/.opencode/mafw/memory/tier3/parametric.json +13 -0
  7. package/.opencode/mafw/memory/tier3/test-goal.json +19 -0
  8. package/.opencode/mafw/memory-index.json +6 -0
  9. package/.opencode/mafw/parametric/base-skill-manifest.yaml +2 -0
  10. package/.opencode/mafw/waves.json +4 -0
  11. package/.opencode/opencode.json +3 -0
  12. package/.opencode/plugins/mafw-plugin.ts +8 -0
  13. package/.opencode/skills/banner-design/SKILL.md +196 -0
  14. package/.opencode/skills/banner-design/references/banner-sizes-and-styles.md +118 -0
  15. package/.opencode/skills/brand/SKILL.md +97 -0
  16. package/.opencode/skills/brand/references/approval-checklist.md +169 -0
  17. package/.opencode/skills/brand/references/asset-organization.md +157 -0
  18. package/.opencode/skills/brand/references/brand-guideline-template.md +140 -0
  19. package/.opencode/skills/brand/references/color-palette-management.md +186 -0
  20. package/.opencode/skills/brand/references/consistency-checklist.md +94 -0
  21. package/.opencode/skills/brand/references/logo-usage-rules.md +185 -0
  22. package/.opencode/skills/brand/references/messaging-framework.md +85 -0
  23. package/.opencode/skills/brand/references/typography-specifications.md +214 -0
  24. package/.opencode/skills/brand/references/update.md +118 -0
  25. package/.opencode/skills/brand/references/visual-identity.md +96 -0
  26. package/.opencode/skills/brand/references/voice-framework.md +88 -0
  27. package/.opencode/skills/brand/scripts/extract-colors.cjs +341 -0
  28. package/.opencode/skills/brand/scripts/inject-brand-context.cjs +349 -0
  29. package/.opencode/skills/brand/scripts/sync-brand-to-tokens.cjs +248 -0
  30. package/.opencode/skills/brand/scripts/tests/test_sync_brand_to_tokens.py +52 -0
  31. package/.opencode/skills/brand/scripts/validate-asset.cjs +387 -0
  32. package/.opencode/skills/brand/templates/brand-guidelines-starter.md +275 -0
  33. package/.opencode/skills/design/SKILL.md +313 -0
  34. package/.opencode/skills/design/data/cip/deliverables.csv +51 -0
  35. package/.opencode/skills/design/data/cip/industries.csv +21 -0
  36. package/.opencode/skills/design/data/cip/mockup-contexts.csv +21 -0
  37. package/.opencode/skills/design/data/cip/styles.csv +21 -0
  38. package/.opencode/skills/design/data/icon/styles.csv +16 -0
  39. package/.opencode/skills/design/data/logo/colors.csv +56 -0
  40. package/.opencode/skills/design/data/logo/industries.csv +56 -0
  41. package/.opencode/skills/design/data/logo/styles.csv +56 -0
  42. package/.opencode/skills/design/references/banner-sizes-and-styles.md +118 -0
  43. package/.opencode/skills/design/references/cip-deliverable-guide.md +95 -0
  44. package/.opencode/skills/design/references/cip-design.md +121 -0
  45. package/.opencode/skills/design/references/cip-prompt-engineering.md +84 -0
  46. package/.opencode/skills/design/references/cip-style-guide.md +68 -0
  47. package/.opencode/skills/design/references/design-routing.md +207 -0
  48. package/.opencode/skills/design/references/icon-design.md +122 -0
  49. package/.opencode/skills/design/references/logo-color-psychology.md +101 -0
  50. package/.opencode/skills/design/references/logo-design.md +92 -0
  51. package/.opencode/skills/design/references/logo-prompt-engineering.md +158 -0
  52. package/.opencode/skills/design/references/logo-style-guide.md +109 -0
  53. package/.opencode/skills/design/references/slides-copywriting-formulas.md +84 -0
  54. package/.opencode/skills/design/references/slides-create.md +4 -0
  55. package/.opencode/skills/design/references/slides-html-template.md +295 -0
  56. package/.opencode/skills/design/references/slides-layout-patterns.md +137 -0
  57. package/.opencode/skills/design/references/slides-strategies.md +94 -0
  58. package/.opencode/skills/design/references/slides.md +42 -0
  59. package/.opencode/skills/design/references/social-photos-design.md +329 -0
  60. package/.opencode/skills/design/scripts/cip/core.py +215 -0
  61. package/.opencode/skills/design/scripts/cip/generate.py +484 -0
  62. package/.opencode/skills/design/scripts/cip/render-html.py +424 -0
  63. package/.opencode/skills/design/scripts/cip/search.py +127 -0
  64. package/.opencode/skills/design/scripts/icon/generate.py +487 -0
  65. package/.opencode/skills/design/scripts/logo/core.py +175 -0
  66. package/.opencode/skills/design/scripts/logo/generate.py +362 -0
  67. package/.opencode/skills/design/scripts/logo/search.py +114 -0
  68. package/.opencode/skills/design-system/SKILL.md +244 -0
  69. package/.opencode/skills/design-system/data/slide-backgrounds.csv +11 -0
  70. package/.opencode/skills/design-system/data/slide-charts.csv +26 -0
  71. package/.opencode/skills/design-system/data/slide-color-logic.csv +14 -0
  72. package/.opencode/skills/design-system/data/slide-copy.csv +26 -0
  73. package/.opencode/skills/design-system/data/slide-layout-logic.csv +16 -0
  74. package/.opencode/skills/design-system/data/slide-layouts.csv +26 -0
  75. package/.opencode/skills/design-system/data/slide-strategies.csv +16 -0
  76. package/.opencode/skills/design-system/data/slide-typography.csv +15 -0
  77. package/.opencode/skills/design-system/references/component-specs.md +236 -0
  78. package/.opencode/skills/design-system/references/component-tokens.md +214 -0
  79. package/.opencode/skills/design-system/references/primitive-tokens.md +203 -0
  80. package/.opencode/skills/design-system/references/semantic-tokens.md +215 -0
  81. package/.opencode/skills/design-system/references/states-and-variants.md +241 -0
  82. package/.opencode/skills/design-system/references/tailwind-integration.md +251 -0
  83. package/.opencode/skills/design-system/references/token-architecture.md +224 -0
  84. package/.opencode/skills/design-system/scripts/embed-tokens.cjs +99 -0
  85. package/.opencode/skills/design-system/scripts/fetch-background.py +317 -0
  86. package/.opencode/skills/design-system/scripts/generate-slide.py +770 -0
  87. package/.opencode/skills/design-system/scripts/generate-tokens.cjs +205 -0
  88. package/.opencode/skills/design-system/scripts/html-token-validator.py +327 -0
  89. package/.opencode/skills/design-system/scripts/search-slides.py +218 -0
  90. package/.opencode/skills/design-system/scripts/slide-token-validator.py +35 -0
  91. package/.opencode/skills/design-system/scripts/slide_search_core.py +453 -0
  92. package/.opencode/skills/design-system/scripts/tests/test_validate_tokens.py +48 -0
  93. package/.opencode/skills/design-system/scripts/validate-tokens.cjs +246 -0
  94. package/.opencode/skills/design-system/templates/design-tokens-starter.json +143 -0
  95. package/.opencode/skills/frontend-design/LICENSE.txt +21 -0
  96. package/.opencode/skills/frontend-design/SKILL.md +115 -0
  97. package/.opencode/skills/mafw-automation-interview/SKILL.md +43 -0
  98. package/.opencode/skills/mafw-cli-scanner/SKILL.md +37 -0
  99. package/.opencode/skills/mafw-compression-verifier/SKILL.md +52 -0
  100. package/.opencode/skills/mafw-desktop-inspector/SKILL.md +170 -0
  101. package/.opencode/skills/mafw-execute/SKILL.md +62 -0
  102. package/.opencode/skills/mafw-gateway-restart/SKILL.md +87 -0
  103. package/.opencode/skills/mafw-github-scanner/SKILL.md +38 -0
  104. package/.opencode/skills/mafw-goal/SKILL.md +76 -0
  105. package/.opencode/skills/mafw-interview/SKILL.md +68 -0
  106. package/.opencode/skills/mafw-memory-extractor/SKILL.md +65 -0
  107. package/.opencode/skills/mafw-plan/SKILL.md +58 -0
  108. package/.opencode/skills/mafw-review/SKILL.md +85 -0
  109. package/.opencode/skills/runtime-plugin-authoring/SKILL.md +791 -0
  110. package/.opencode/skills/slides/SKILL.md +40 -0
  111. package/.opencode/skills/slides/references/copywriting-formulas.md +84 -0
  112. package/.opencode/skills/slides/references/create.md +4 -0
  113. package/.opencode/skills/slides/references/html-template.md +295 -0
  114. package/.opencode/skills/slides/references/layout-patterns.md +137 -0
  115. package/.opencode/skills/slides/references/slide-strategies.md +94 -0
  116. package/.opencode/skills/ui-styling/LICENSE.txt +202 -0
  117. package/.opencode/skills/ui-styling/SKILL.md +324 -0
  118. package/.opencode/skills/ui-styling/references/canvas-design-system.md +320 -0
  119. package/.opencode/skills/ui-styling/references/shadcn-accessibility.md +471 -0
  120. package/.opencode/skills/ui-styling/references/shadcn-components.md +424 -0
  121. package/.opencode/skills/ui-styling/references/shadcn-theming.md +373 -0
  122. package/.opencode/skills/ui-styling/references/tailwind-customization.md +483 -0
  123. package/.opencode/skills/ui-styling/references/tailwind-responsive.md +382 -0
  124. package/.opencode/skills/ui-styling/references/tailwind-utilities.md +455 -0
  125. package/.opencode/skills/ui-styling/scripts/requirements.txt +17 -0
  126. package/.opencode/skills/ui-styling/scripts/shadcn_add.py +308 -0
  127. package/.opencode/skills/ui-styling/scripts/tailwind_config_gen.py +473 -0
  128. package/.opencode/skills/ui-styling/scripts/tests/coverage-ui.json +1 -0
  129. package/.opencode/skills/ui-styling/scripts/tests/requirements.txt +3 -0
  130. package/.opencode/skills/ui-styling/scripts/tests/test_shadcn_add.py +266 -0
  131. package/.opencode/skills/ui-styling/scripts/tests/test_tailwind_config_gen.py +394 -0
  132. package/.opencode/skills/ui-ux-pro-max/SKILL.md +388 -0
  133. package/.opencode/skills/ui-ux-pro-max/data/app-interface.csv +31 -0
  134. package/.opencode/skills/ui-ux-pro-max/data/charts.csv +26 -0
  135. package/.opencode/skills/ui-ux-pro-max/data/colors.csv +193 -0
  136. package/.opencode/skills/ui-ux-pro-max/data/google-fonts.csv +1924 -0
  137. package/.opencode/skills/ui-ux-pro-max/data/icons.csv +106 -0
  138. package/.opencode/skills/ui-ux-pro-max/data/landing.csv +35 -0
  139. package/.opencode/skills/ui-ux-pro-max/data/motion.csv +17 -0
  140. package/.opencode/skills/ui-ux-pro-max/data/products.csv +193 -0
  141. package/.opencode/skills/ui-ux-pro-max/data/react-performance.csv +45 -0
  142. package/.opencode/skills/ui-ux-pro-max/data/stacks/angular.csv +51 -0
  143. package/.opencode/skills/ui-ux-pro-max/data/stacks/astro.csv +54 -0
  144. package/.opencode/skills/ui-ux-pro-max/data/stacks/avalonia.csv +57 -0
  145. package/.opencode/skills/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  146. package/.opencode/skills/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  147. package/.opencode/skills/ui-ux-pro-max/data/stacks/javafx.csv +76 -0
  148. package/.opencode/skills/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
  149. package/.opencode/skills/ui-ux-pro-max/data/stacks/laravel.csv +51 -0
  150. package/.opencode/skills/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  151. package/.opencode/skills/ui-ux-pro-max/data/stacks/nuxt-ui.csv +71 -0
  152. package/.opencode/skills/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  153. package/.opencode/skills/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  154. package/.opencode/skills/ui-ux-pro-max/data/stacks/react.csv +54 -0
  155. package/.opencode/skills/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  156. package/.opencode/skills/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  157. package/.opencode/skills/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  158. package/.opencode/skills/ui-ux-pro-max/data/stacks/threejs.csv +54 -0
  159. package/.opencode/skills/ui-ux-pro-max/data/stacks/uno.csv +60 -0
  160. package/.opencode/skills/ui-ux-pro-max/data/stacks/uwp.csv +56 -0
  161. package/.opencode/skills/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  162. package/.opencode/skills/ui-ux-pro-max/data/stacks/winui.csv +60 -0
  163. package/.opencode/skills/ui-ux-pro-max/data/stacks/wpf.csv +57 -0
  164. package/.opencode/skills/ui-ux-pro-max/data/styles.csv +85 -0
  165. package/.opencode/skills/ui-ux-pro-max/data/typography.csv +75 -0
  166. package/.opencode/skills/ui-ux-pro-max/data/ui-reasoning.csv +162 -0
  167. package/.opencode/skills/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  168. package/.opencode/skills/ui-ux-pro-max/scripts/core.py +464 -0
  169. package/.opencode/skills/ui-ux-pro-max/scripts/design_system.py +1479 -0
  170. package/.opencode/skills/ui-ux-pro-max/scripts/search.py +162 -0
  171. package/.opencode/skills/ui-ux-pro-max/scripts/tests/test_core.py +134 -0
  172. package/.opencode/skills/ui-ux-pro-max/scripts/tests/test_design_system_mode.py +159 -0
  173. package/.opencode/skills/ui-ux-pro-max/scripts/validate_data.py +114 -0
  174. package/LICENSE +21 -0
  175. package/README.md +199 -0
  176. package/bin/mafw.js +436 -0
  177. package/dist/hooks/bash-python-guide.d.ts +4 -0
  178. package/dist/hooks/bash-python-guide.d.ts.map +1 -0
  179. package/dist/hooks/bash-python-guide.js +67 -0
  180. package/dist/hooks/bash-python-guide.js.map +1 -0
  181. package/dist/hooks/handoff.d.ts +9 -0
  182. package/dist/hooks/handoff.d.ts.map +1 -0
  183. package/dist/hooks/handoff.js +8 -0
  184. package/dist/hooks/handoff.js.map +1 -0
  185. package/dist/hooks/hook-manager.d.ts +32 -0
  186. package/dist/hooks/hook-manager.d.ts.map +1 -0
  187. package/dist/hooks/hook-manager.js +91 -0
  188. package/dist/hooks/hook-manager.js.map +1 -0
  189. package/dist/hooks/llm-after.d.ts +8 -0
  190. package/dist/hooks/llm-after.d.ts.map +1 -0
  191. package/dist/hooks/llm-after.js +8 -0
  192. package/dist/hooks/llm-after.js.map +1 -0
  193. package/dist/hooks/media-ingest.d.ts +43 -0
  194. package/dist/hooks/media-ingest.d.ts.map +1 -0
  195. package/dist/hooks/media-ingest.js +269 -0
  196. package/dist/hooks/media-ingest.js.map +1 -0
  197. package/dist/hooks/memory-guide.d.ts +3 -0
  198. package/dist/hooks/memory-guide.d.ts.map +1 -0
  199. package/dist/hooks/memory-guide.js +47 -0
  200. package/dist/hooks/memory-guide.js.map +1 -0
  201. package/dist/hooks/observation-capture.d.ts +17 -0
  202. package/dist/hooks/observation-capture.d.ts.map +1 -0
  203. package/dist/hooks/observation-capture.js +20 -0
  204. package/dist/hooks/observation-capture.js.map +1 -0
  205. package/dist/hooks/session-compacting.d.ts +6 -0
  206. package/dist/hooks/session-compacting.d.ts.map +1 -0
  207. package/dist/hooks/session-compacting.js +6 -0
  208. package/dist/hooks/session-compacting.js.map +1 -0
  209. package/dist/hooks/session-ending.d.ts +20 -0
  210. package/dist/hooks/session-ending.d.ts.map +1 -0
  211. package/dist/hooks/session-ending.js +113 -0
  212. package/dist/hooks/session-ending.js.map +1 -0
  213. package/dist/hooks/session-recall.d.ts +2 -0
  214. package/dist/hooks/session-recall.d.ts.map +1 -0
  215. package/dist/hooks/session-recall.js +103 -0
  216. package/dist/hooks/session-recall.js.map +1 -0
  217. package/dist/hooks/session-start.d.ts +9 -0
  218. package/dist/hooks/session-start.d.ts.map +1 -0
  219. package/dist/hooks/session-start.js +42 -0
  220. package/dist/hooks/session-start.js.map +1 -0
  221. package/dist/hooks/tool-before.d.ts +10 -0
  222. package/dist/hooks/tool-before.d.ts.map +1 -0
  223. package/dist/hooks/tool-before.js +6 -0
  224. package/dist/hooks/tool-before.js.map +1 -0
  225. package/dist/hooks/tool-executed.d.ts +19 -0
  226. package/dist/hooks/tool-executed.d.ts.map +1 -0
  227. package/dist/hooks/tool-executed.js +12 -0
  228. package/dist/hooks/tool-executed.js.map +1 -0
  229. package/dist/hooks/user-profile.d.ts +2 -0
  230. package/dist/hooks/user-profile.d.ts.map +1 -0
  231. package/dist/hooks/user-profile.js +30 -0
  232. package/dist/hooks/user-profile.js.map +1 -0
  233. package/dist/hooks/user-prompt.d.ts +9 -0
  234. package/dist/hooks/user-prompt.d.ts.map +1 -0
  235. package/dist/hooks/user-prompt.js +8 -0
  236. package/dist/hooks/user-prompt.js.map +1 -0
  237. package/dist/hooks/voice-guide.d.ts +8 -0
  238. package/dist/hooks/voice-guide.d.ts.map +1 -0
  239. package/dist/hooks/voice-guide.js +101 -0
  240. package/dist/hooks/voice-guide.js.map +1 -0
  241. package/dist/plugin.d.ts +55 -0
  242. package/dist/plugin.d.ts.map +1 -0
  243. package/dist/plugin.js +342 -0
  244. package/dist/plugin.js.map +1 -0
  245. package/dist/tools/add-memory.d.ts +17 -0
  246. package/dist/tools/add-memory.d.ts.map +1 -0
  247. package/dist/tools/add-memory.js +60 -0
  248. package/dist/tools/add-memory.js.map +1 -0
  249. package/dist/tools/media-ask.d.ts +14 -0
  250. package/dist/tools/media-ask.d.ts.map +1 -0
  251. package/dist/tools/media-ask.js +224 -0
  252. package/dist/tools/media-ask.js.map +1 -0
  253. package/dist/tools/media-speak.d.ts +16 -0
  254. package/dist/tools/media-speak.d.ts.map +1 -0
  255. package/dist/tools/media-speak.js +78 -0
  256. package/dist/tools/media-speak.js.map +1 -0
  257. package/dist/tools/media-upload.d.ts +14 -0
  258. package/dist/tools/media-upload.d.ts.map +1 -0
  259. package/dist/tools/media-upload.js +155 -0
  260. package/dist/tools/media-upload.js.map +1 -0
  261. package/dist/tools/python-exec.d.ts +13 -0
  262. package/dist/tools/python-exec.d.ts.map +1 -0
  263. package/dist/tools/python-exec.js +99 -0
  264. package/dist/tools/python-exec.js.map +1 -0
  265. package/dist/tools/python-restart.d.ts +11 -0
  266. package/dist/tools/python-restart.d.ts.map +1 -0
  267. package/dist/tools/python-restart.js +33 -0
  268. package/dist/tools/python-restart.js.map +1 -0
  269. package/dist/utils/circuit-breaker.d.ts +23 -0
  270. package/dist/utils/circuit-breaker.d.ts.map +1 -0
  271. package/dist/utils/circuit-breaker.js +75 -0
  272. package/dist/utils/circuit-breaker.js.map +1 -0
  273. package/dist/utils/config-loader.d.ts +20 -0
  274. package/dist/utils/config-loader.d.ts.map +1 -0
  275. package/dist/utils/config-loader.js +194 -0
  276. package/dist/utils/config-loader.js.map +1 -0
  277. package/dist/utils/fallback.d.ts +7 -0
  278. package/dist/utils/fallback.d.ts.map +1 -0
  279. package/dist/utils/fallback.js +20 -0
  280. package/dist/utils/fallback.js.map +1 -0
  281. package/dist/utils/git.d.ts +24 -0
  282. package/dist/utils/git.d.ts.map +1 -0
  283. package/dist/utils/git.js +71 -0
  284. package/dist/utils/git.js.map +1 -0
  285. package/dist/utils/github.d.ts +37 -0
  286. package/dist/utils/github.d.ts.map +1 -0
  287. package/dist/utils/github.js +53 -0
  288. package/dist/utils/github.js.map +1 -0
  289. package/dist/utils/global-path.d.ts +2 -0
  290. package/dist/utils/global-path.d.ts.map +1 -0
  291. package/dist/utils/global-path.js +32 -0
  292. package/dist/utils/global-path.js.map +1 -0
  293. package/dist/utils/logger.d.ts +6 -0
  294. package/dist/utils/logger.d.ts.map +1 -0
  295. package/dist/utils/logger.js +69 -0
  296. package/dist/utils/logger.js.map +1 -0
  297. package/dist/utils/obs-capture.d.ts +7 -0
  298. package/dist/utils/obs-capture.d.ts.map +1 -0
  299. package/dist/utils/obs-capture.js +49 -0
  300. package/dist/utils/obs-capture.js.map +1 -0
  301. package/dist/utils/retry.d.ts +11 -0
  302. package/dist/utils/retry.d.ts.map +1 -0
  303. package/dist/utils/retry.js +45 -0
  304. package/dist/utils/retry.js.map +1 -0
  305. package/dist/utils/self-wiring.d.ts +13 -0
  306. package/dist/utils/self-wiring.d.ts.map +1 -0
  307. package/dist/utils/self-wiring.js +86 -0
  308. package/dist/utils/self-wiring.js.map +1 -0
  309. package/dist/utils/state.d.ts +106 -0
  310. package/dist/utils/state.d.ts.map +1 -0
  311. package/dist/utils/state.js +166 -0
  312. package/dist/utils/state.js.map +1 -0
  313. package/dist/utils/status.d.ts +47 -0
  314. package/dist/utils/status.d.ts.map +1 -0
  315. package/dist/utils/status.js +147 -0
  316. package/dist/utils/status.js.map +1 -0
  317. package/dist/utils/ttl-map.d.ts +17 -0
  318. package/dist/utils/ttl-map.d.ts.map +1 -0
  319. package/dist/utils/ttl-map.js +67 -0
  320. package/dist/utils/ttl-map.js.map +1 -0
  321. package/gateway/dist/automation-engine.js +729 -0
  322. package/gateway/dist/chat/chat-sessions.js +95 -0
  323. package/gateway/dist/chat/graph-runner.js +76 -0
  324. package/gateway/dist/chat/index.js +7 -0
  325. package/gateway/dist/chat/intent-classifier.js +23 -0
  326. package/gateway/dist/config.js +416 -0
  327. package/gateway/dist/core/auth.js +96 -0
  328. package/gateway/dist/core/budget-guard.js +52 -0
  329. package/gateway/dist/core/compression/bm25-index.js +176 -0
  330. package/gateway/dist/core/compression/compression-pipeline.js +157 -0
  331. package/gateway/dist/core/compression/compression-strategy-selector.js +32 -0
  332. package/gateway/dist/core/compression/compression-verifier.js +79 -0
  333. package/gateway/dist/core/compression/diff-compressor.js +69 -0
  334. package/gateway/dist/core/compression/hybrid-compressor.js +104 -0
  335. package/gateway/dist/core/compression/lesson-compactor.js +114 -0
  336. package/gateway/dist/core/compression/memory-index.js +190 -0
  337. package/gateway/dist/core/compression/observation-classifier.js +41 -0
  338. package/gateway/dist/core/compression/observation-deduplicator.js +43 -0
  339. package/gateway/dist/core/compression/rrf-fusion.js +63 -0
  340. package/gateway/dist/core/compression/session-pruner.js +137 -0
  341. package/gateway/dist/core/compression/token-budget-allocator.js +141 -0
  342. package/gateway/dist/core/compression/vector-index.js +117 -0
  343. package/gateway/dist/core/compression/zero-token-compressor.js +80 -0
  344. package/gateway/dist/core/cost/cognitive-router.js +41 -0
  345. package/gateway/dist/core/cost/cost-estimator.js +63 -0
  346. package/gateway/dist/core/cost/types.js +19 -0
  347. package/gateway/dist/core/engine/degradation.js +159 -0
  348. package/gateway/dist/core/engine/goal-worktree-manager.js +131 -0
  349. package/gateway/dist/core/engine/lesson-manager.js +222 -0
  350. package/gateway/dist/core/engine/optimistic-sync.js +100 -0
  351. package/gateway/dist/core/engine/phase-orchestrator.js +153 -0
  352. package/gateway/dist/core/engine/report-generator.js +131 -0
  353. package/gateway/dist/core/engine/state-lock.js +91 -0
  354. package/gateway/dist/core/engine/task-branch-manager.js +102 -0
  355. package/gateway/dist/core/engine/wave-dependency.js +67 -0
  356. package/gateway/dist/core/engine/wave-executor.js +112 -0
  357. package/gateway/dist/core/goal-budget.js +63 -0
  358. package/gateway/dist/core/graph/entity-extractor.js +53 -0
  359. package/gateway/dist/core/graph/graph-searcher.js +120 -0
  360. package/gateway/dist/core/graph/knowledge-graph-manager.js +138 -0
  361. package/gateway/dist/core/graph/relation-inferencer.js +67 -0
  362. package/gateway/dist/core/graph/types.js +2 -0
  363. package/gateway/dist/core/hooks/handoff.js +7 -0
  364. package/gateway/dist/core/hooks/hook-manager.js +91 -0
  365. package/gateway/dist/core/hooks/llm-after.js +7 -0
  366. package/gateway/dist/core/hooks/observation-capture.js +19 -0
  367. package/gateway/dist/core/hooks/session-compacting.js +5 -0
  368. package/gateway/dist/core/hooks/session-ending.js +123 -0
  369. package/gateway/dist/core/hooks/session-start.js +51 -0
  370. package/gateway/dist/core/hooks/tool-before.js +5 -0
  371. package/gateway/dist/core/hooks/tool-executed.js +11 -0
  372. package/gateway/dist/core/hooks/user-prompt.js +7 -0
  373. package/gateway/dist/core/index.js +119 -0
  374. package/gateway/dist/core/langchain/agent-adapter.js +39 -0
  375. package/gateway/dist/core/langchain/index.js +12 -0
  376. package/gateway/dist/core/langchain/memory.js +35 -0
  377. package/gateway/dist/core/langchain/node-runner.js +115 -0
  378. package/gateway/dist/core/langchain/retriever.js +28 -0
  379. package/gateway/dist/core/langgraph/checkpointer.js +200 -0
  380. package/gateway/dist/core/langgraph/graph.js +57 -0
  381. package/gateway/dist/core/langgraph/index.js +25 -0
  382. package/gateway/dist/core/langgraph/loop-state.js +71 -0
  383. package/gateway/dist/core/langgraph/nodes/archive.node.js +27 -0
  384. package/gateway/dist/core/langgraph/nodes/execute.node.js +5 -0
  385. package/gateway/dist/core/langgraph/nodes/plan.node.js +101 -0
  386. package/gateway/dist/core/langgraph/nodes/review.node.js +89 -0
  387. package/gateway/dist/core/langgraph/nodes/sync.node.js +70 -0
  388. package/gateway/dist/core/langgraph/review-parser.js +35 -0
  389. package/gateway/dist/core/langgraph/signature-detector.js +23 -0
  390. package/gateway/dist/core/manager/goal-snapshot.js +73 -0
  391. package/gateway/dist/core/manager/milestone-push.js +81 -0
  392. package/gateway/dist/core/manager/question-ledger.js +121 -0
  393. package/gateway/dist/core/manager/system-rule-templates.js +76 -0
  394. package/gateway/dist/core/mcp/tools.js +562 -0
  395. package/gateway/dist/core/mcp/validator.js +165 -0
  396. package/gateway/dist/core/mcp-server.js +86 -0
  397. package/gateway/dist/core/memory/abstraction-distiller.js +44 -0
  398. package/gateway/dist/core/memory/cognitive-graph.js +103 -0
  399. package/gateway/dist/core/memory/energy-system.js +69 -0
  400. package/gateway/dist/core/memory/extractor.js +164 -0
  401. package/gateway/dist/core/memory/harmonic-index.js +530 -0
  402. package/gateway/dist/core/memory/harmonic-types.js +6 -0
  403. package/gateway/dist/core/memory/injector.js +111 -0
  404. package/gateway/dist/core/memory/l5-store.js +141 -0
  405. package/gateway/dist/core/memory/matcher.js +66 -0
  406. package/gateway/dist/core/memory/merger.js +95 -0
  407. package/gateway/dist/core/memory/migrate-v6.1.js +133 -0
  408. package/gateway/dist/core/memory/minhash-merger.js +195 -0
  409. package/gateway/dist/core/memory/observation-service.js +87 -0
  410. package/gateway/dist/core/memory/privacy-filter.js +163 -0
  411. package/gateway/dist/core/memory/reranker.js +208 -0
  412. package/gateway/dist/core/memory/review-scheduler.js +100 -0
  413. package/gateway/dist/core/memory/salience-perceptor.js +24 -0
  414. package/gateway/dist/core/memory/store.js +284 -0
  415. package/gateway/dist/core/memory/t1-store.js +183 -0
  416. package/gateway/dist/core/memory/t1-to-t2-compressor.js +119 -0
  417. package/gateway/dist/core/memory/validator.js +66 -0
  418. package/gateway/dist/core/plugin.js +902 -0
  419. package/gateway/dist/core/skills/mafw-execute/entry.js +226 -0
  420. package/gateway/dist/core/skills/mafw-goal/entry.js +203 -0
  421. package/gateway/dist/core/skills/mafw-plan/entry.js +184 -0
  422. package/gateway/dist/core/skills/mafw-review/entry.js +200 -0
  423. package/gateway/dist/core/storage/file-storage.js +120 -0
  424. package/gateway/dist/core/storage/sqlite-storage.js +205 -0
  425. package/gateway/dist/core/storage/types.js +2 -0
  426. package/gateway/dist/core/tools/archive-worktree.js +208 -0
  427. package/gateway/dist/core/tools/remote-cli.js +106 -0
  428. package/gateway/dist/core/tools/run-ask-user.js +79 -0
  429. package/gateway/dist/core/tools/run-execute-wave.js +32 -0
  430. package/gateway/dist/core/tools/run-plan.js +42 -0
  431. package/gateway/dist/core/tools/run-record-feedback.js +55 -0
  432. package/gateway/dist/core/tools/run-review.js +46 -0
  433. package/gateway/dist/core/tools/write-lesson.js +97 -0
  434. package/gateway/dist/core/utils/circuit-breaker.js +74 -0
  435. package/gateway/dist/core/utils/config-loader.js +203 -0
  436. package/gateway/dist/core/utils/fallback.js +19 -0
  437. package/gateway/dist/core/utils/git.js +70 -0
  438. package/gateway/dist/core/utils/github.js +52 -0
  439. package/gateway/dist/core/utils/global-path.js +41 -0
  440. package/gateway/dist/core/utils/logger.js +71 -0
  441. package/gateway/dist/core/utils/retry.js +44 -0
  442. package/gateway/dist/core/utils/state.js +175 -0
  443. package/gateway/dist/core/utils/status.js +156 -0
  444. package/gateway/dist/cost/service.js +17 -0
  445. package/gateway/dist/dashboard/api.js +1156 -0
  446. package/gateway/dist/dashboard/public/assets/index-DOXm39dm.css +1 -0
  447. package/gateway/dist/dashboard/public/index.html +13 -0
  448. package/gateway/dist/dashboard/server.js +140 -0
  449. package/gateway/dist/dashboard/types.js +2 -0
  450. package/gateway/dist/desktop-client.js +124 -0
  451. package/gateway/dist/eval-endpoint.js +219 -0
  452. package/gateway/dist/event-bus.js +7 -0
  453. package/gateway/dist/feedback/anchor-promotion.js +99 -0
  454. package/gateway/dist/feedback/deferred-memory.js +13 -0
  455. package/gateway/dist/feedback/miss-attribution.js +20 -0
  456. package/gateway/dist/graph/anchor-graph-store.js +113 -0
  457. package/gateway/dist/graph/anchor-graph.js +48 -0
  458. package/gateway/dist/health.js +53 -0
  459. package/gateway/dist/heartbeat.js +109 -0
  460. package/gateway/dist/index.js +6377 -0
  461. package/gateway/dist/interceptors/memory-injector.js +79 -0
  462. package/gateway/dist/ledger.js +121 -0
  463. package/gateway/dist/loop-monitor.js +74 -0
  464. package/gateway/dist/mcp/handlers/add-memory.js +113 -0
  465. package/gateway/dist/mcp/handlers/ask-user.js +63 -0
  466. package/gateway/dist/mcp/handlers/commit-heuristic.js +19 -0
  467. package/gateway/dist/mcp/handlers/create-goal.js +83 -0
  468. package/gateway/dist/mcp/handlers/desktop-click.js +18 -0
  469. package/gateway/dist/mcp/handlers/desktop-get-state.js +15 -0
  470. package/gateway/dist/mcp/handlers/desktop-navigate.js +18 -0
  471. package/gateway/dist/mcp/handlers/desktop-screenshot.js +16 -0
  472. package/gateway/dist/mcp/handlers/desktop-scroll.js +19 -0
  473. package/gateway/dist/mcp/handlers/desktop-type.js +19 -0
  474. package/gateway/dist/mcp/handlers/draft-automation-rule.js +45 -0
  475. package/gateway/dist/mcp/handlers/get-automation-history.js +15 -0
  476. package/gateway/dist/mcp/handlers/get-automation-rule.js +26 -0
  477. package/gateway/dist/mcp/handlers/get-axioms.js +14 -0
  478. package/gateway/dist/mcp/handlers/get-deltas.js +77 -0
  479. package/gateway/dist/mcp/handlers/get-memory.js +67 -0
  480. package/gateway/dist/mcp/handlers/get-model-route.js +16 -0
  481. package/gateway/dist/mcp/handlers/get-triage-item.js +17 -0
  482. package/gateway/dist/mcp/handlers/list-automation-rules.js +24 -0
  483. package/gateway/dist/mcp/handlers/list-triage-items.js +14 -0
  484. package/gateway/dist/mcp/handlers/load-state.js +54 -0
  485. package/gateway/dist/mcp/handlers/manager-answer-question.js +67 -0
  486. package/gateway/dist/mcp/handlers/manager-cancel-goal.js +58 -0
  487. package/gateway/dist/mcp/handlers/manager-get-evidence.js +57 -0
  488. package/gateway/dist/mcp/handlers/manager-get-goal-status.js +58 -0
  489. package/gateway/dist/mcp/handlers/manager-list-goals.js +60 -0
  490. package/gateway/dist/mcp/handlers/manager-list-pending-questions.js +67 -0
  491. package/gateway/dist/mcp/handlers/manager-set-goal.js +78 -0
  492. package/gateway/dist/mcp/handlers/merge-memory.js +184 -0
  493. package/gateway/dist/mcp/handlers/pin-memory.js +53 -0
  494. package/gateway/dist/mcp/handlers/propose-triage-decision.js +38 -0
  495. package/gateway/dist/mcp/handlers/record-feedback.js +59 -0
  496. package/gateway/dist/mcp/handlers/resolve-merge.js +92 -0
  497. package/gateway/dist/mcp/handlers/restart-agent.js +22 -0
  498. package/gateway/dist/mcp/handlers/run-automation.js +28 -0
  499. package/gateway/dist/mcp/handlers/search-hybrid.js +181 -0
  500. package/gateway/dist/mcp/handlers/supersede-memory.js +47 -0
  501. package/gateway/dist/mcp/handlers/update-state.js +59 -0
  502. package/gateway/dist/mcp/handlers/validate-rule.js +39 -0
  503. package/gateway/dist/mcp/sse-transport.js +97 -0
  504. package/gateway/dist/mcp/streamable-endpoint.js +98 -0
  505. package/gateway/dist/mcp/tool-registry.js +630 -0
  506. package/gateway/dist/media/media-agent.js +755 -0
  507. package/gateway/dist/media/media-plugin-loader.js +254 -0
  508. package/gateway/dist/media/media-runtime-executor.js +227 -0
  509. package/gateway/dist/media/media-service.js +199 -0
  510. package/gateway/dist/media/pi-adapter.js +159 -0
  511. package/gateway/dist/media/plugin-context.js +14 -0
  512. package/gateway/dist/media/tts-service.js +173 -0
  513. package/gateway/dist/memory/abstraction-matcher.js +28 -0
  514. package/gateway/dist/memory/consolidation-service.js +209 -0
  515. package/gateway/dist/memory/derived-terms.js +50 -0
  516. package/gateway/dist/memory/embedding-provider.js +330 -0
  517. package/gateway/dist/memory/embedding-runtime.js +174 -0
  518. package/gateway/dist/memory/event-log.js +84 -0
  519. package/gateway/dist/memory/gateway-db.js +465 -0
  520. package/gateway/dist/memory/harmonic-file-store.js +338 -0
  521. package/gateway/dist/memory/llamacpp-provider.js +370 -0
  522. package/gateway/dist/memory/okf-index-renderer.js +61 -0
  523. package/gateway/dist/memory/okf-migrator.js +71 -0
  524. package/gateway/dist/memory/okf-parser.js +57 -0
  525. package/gateway/dist/memory/okf-writer.js +107 -0
  526. package/gateway/dist/memory/service.js +81 -0
  527. package/gateway/dist/memory/t1-db.js +139 -0
  528. package/gateway/dist/memory/unmerge-cleanup.js +82 -0
  529. package/gateway/dist/memory/vector-store.js +246 -0
  530. package/gateway/dist/memory/write-queue.js +31 -0
  531. package/gateway/dist/metrics/collector.js +28 -0
  532. package/gateway/dist/mobile/device-store.js +123 -0
  533. package/gateway/dist/mobile/mdns-advertiser.js +55 -0
  534. package/gateway/dist/mobile/media-proxy.js +292 -0
  535. package/gateway/dist/mobile/pairing.js +139 -0
  536. package/gateway/dist/mobile/push-gateway.js +126 -0
  537. package/gateway/dist/mobile/tts-artifact.js +43 -0
  538. package/gateway/dist/opencode-adapter.js +241 -0
  539. package/gateway/dist/orchestration/outcome-recorder.js +218 -0
  540. package/gateway/dist/orchestration/policy.js +57 -0
  541. package/gateway/dist/orchestration/registry.js +47 -0
  542. package/gateway/dist/plugins/hub.js +188 -0
  543. package/gateway/dist/poll.js +110 -0
  544. package/gateway/dist/python/kernel-service.js +762 -0
  545. package/gateway/dist/recall/constraints-migrate.js +108 -0
  546. package/gateway/dist/recall/data-dir-migrate.js +120 -0
  547. package/gateway/dist/recall/gateway-db-migrate.js +134 -0
  548. package/gateway/dist/recall/index-scan.js +437 -0
  549. package/gateway/dist/recall/inject-format.js +222 -0
  550. package/gateway/dist/recall/legacy-t1-archive.js +86 -0
  551. package/gateway/dist/recall/memory-worker.js +128 -0
  552. package/gateway/dist/recall/pipeline-rules.js +76 -0
  553. package/gateway/dist/recall/recall-context.js +297 -0
  554. package/gateway/dist/recall/reflect-cursor.js +50 -0
  555. package/gateway/dist/recall/reflection.js +318 -0
  556. package/gateway/dist/recall/session-worker-pool.js +100 -0
  557. package/gateway/dist/recall/stale-verify.js +72 -0
  558. package/gateway/dist/recall/step-inject.js +173 -0
  559. package/gateway/dist/recall/time-anchor.js +143 -0
  560. package/gateway/dist/recall/ttl-map.js +72 -0
  561. package/gateway/dist/recall/turn-completion.js +44 -0
  562. package/gateway/dist/recall/turn-pipeline.js +150 -0
  563. package/gateway/dist/recovery.js +158 -0
  564. package/gateway/dist/resources/sdk-session.js +202 -0
  565. package/gateway/dist/retrieval/guided-retriever.js +131 -0
  566. package/gateway/dist/retrieval/idf-stats.js +31 -0
  567. package/gateway/dist/routes/embedding-config.js +100 -0
  568. package/gateway/dist/routes/goal-sessions.js +45 -0
  569. package/gateway/dist/routes/manager-rotate.js +55 -0
  570. package/gateway/dist/routes/media-switch.js +78 -0
  571. package/gateway/dist/routes/model-config.js +132 -0
  572. package/gateway/dist/routes/note-board.js +51 -0
  573. package/gateway/dist/routes/permission.js +43 -0
  574. package/gateway/dist/routes/pinned-recall.js +36 -0
  575. package/gateway/dist/routes/plugins.js +77 -0
  576. package/gateway/dist/routes/restart-agent.js +28 -0
  577. package/gateway/dist/routes/runtime-switch.js +80 -0
  578. package/gateway/dist/routes/session-branch.js +63 -0
  579. package/gateway/dist/routes/session-mutations.js +58 -0
  580. package/gateway/dist/routes/session-summarize.js +49 -0
  581. package/gateway/dist/routes/usage-plugins.js +251 -0
  582. package/gateway/dist/runtime/agent-definition.js +2 -0
  583. package/gateway/dist/runtime/auth.js +80 -0
  584. package/gateway/dist/runtime/completion-http.js +97 -0
  585. package/gateway/dist/runtime/contract.js +37 -0
  586. package/gateway/dist/runtime/loader.js +240 -0
  587. package/gateway/dist/runtime/normalize.js +59 -0
  588. package/gateway/dist/runtime/opencode-runtime.js +336 -0
  589. package/gateway/dist/runtime/pi/pi-agent-config.js +294 -0
  590. package/gateway/dist/runtime/pi/pi-approval-bridge.js +44 -0
  591. package/gateway/dist/runtime/pi/pi-approval-extension.js +62 -0
  592. package/gateway/dist/runtime/pi/pi-events.js +122 -0
  593. package/gateway/dist/runtime/pi/pi-messages.js +20 -0
  594. package/gateway/dist/runtime/pi/pi-provider.js +19 -0
  595. package/gateway/dist/runtime/pi/pi-session-storage.js +44 -0
  596. package/gateway/dist/runtime/pi/pi-session.js +328 -0
  597. package/gateway/dist/runtime/plugins/pi-runtime.js +285 -0
  598. package/gateway/dist/runtime/serve-for-runtime.js +22 -0
  599. package/gateway/dist/runtime/serve-sidecar.js +164 -0
  600. package/gateway/dist/runtime/serve-supervisor.js +80 -0
  601. package/gateway/dist/self-update.js +309 -0
  602. package/gateway/dist/skills/manager-agent-config.js +37 -0
  603. package/gateway/dist/skills/manager-identity.js +11 -0
  604. package/gateway/dist/skills/memory-curator-agent.js +55 -0
  605. package/gateway/dist/trajectory/api.js +154 -0
  606. package/gateway/dist/trajectory/backfill-provider.js +41 -0
  607. package/gateway/dist/trajectory/collector.js +337 -0
  608. package/gateway/dist/trajectory/trajectory-store.js +336 -0
  609. package/gateway/dist/trajectory/types.js +17 -0
  610. package/gateway/dist/tray/index.js +131 -0
  611. package/gateway/dist/tray/tray.ps1 +96 -0
  612. package/gateway/dist/types.js +2 -0
  613. package/gateway/dist/usage/builtin-plugins/commandcode.js +71 -0
  614. package/gateway/dist/usage/builtin-plugins/deepseek.js +56 -0
  615. package/gateway/dist/usage/builtin-plugins/gateway.js +127 -0
  616. package/gateway/dist/usage/builtin-plugins/kimi-for-coding.js +93 -0
  617. package/gateway/dist/usage/builtin-plugins/kimi.js +48 -0
  618. package/gateway/dist/usage/builtin-plugins/opencode-go.js +54 -0
  619. package/gateway/dist/usage/builtin-plugins/openrouter.js +48 -0
  620. package/gateway/dist/usage/builtin-plugins/siliconflow-cn.js +49 -0
  621. package/gateway/dist/usage/builtin-plugins/zhipuai-coding-plan.js +44 -0
  622. package/gateway/dist/usage/model-prices.js +39 -0
  623. package/gateway/dist/usage/model-stats.js +21 -0
  624. package/gateway/dist/usage/plugin-context.js +79 -0
  625. package/gateway/dist/usage/plugin-loader.js +280 -0
  626. package/gateway/dist/usage/templates.js +227 -0
  627. package/gateway/dist/usage/types.js +2 -0
  628. package/gateway/dist/usage/usage-poller.js +216 -0
  629. package/gateway/package.json +37 -0
  630. package/package.json +78 -0
  631. package/packages/tui/dist/cli.js +4664 -0
@@ -0,0 +1,1479 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Design System Generator - Aggregates search results and applies reasoning
5
+ to generate comprehensive design system recommendations.
6
+
7
+ Usage:
8
+ from design_system import generate_design_system
9
+ result = generate_design_system("SaaS dashboard", "My Project")
10
+ print(result["text"])
11
+
12
+ # With persistence (Master + Overrides pattern)
13
+ result = generate_design_system("SaaS dashboard", "My Project", persist=True, output_dir="/path/to/project")
14
+ result["persistence"] # {"status": "success"|"skipped_exists", "created_files": [...], ...}
15
+ result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard", output_dir="/path/to/project")
16
+ """
17
+
18
+ import csv
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ import io
24
+ from datetime import datetime
25
+ from pathlib import Path
26
+ from core import search, DATA_DIR
27
+
28
+ # Force UTF-8 for stdout/stderr to handle emojis/box-drawing chars on Windows (cp1252 default)
29
+ if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
30
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
31
+ if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
32
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
33
+
34
+
35
+ # ============ CONFIGURATION ============
36
+ REASONING_FILE = "ui-reasoning.csv"
37
+
38
+ SEARCH_CONFIG = {
39
+ "product": {"max_results": 1},
40
+ "style": {"max_results": 3},
41
+ "color": {"max_results": 2},
42
+ "landing": {"max_results": 2},
43
+ "typography": {"max_results": 2}
44
+ }
45
+
46
+ # ============ DESIGN DIALS (1-10) ============
47
+ # Inspired by taste-skill's DESIGN_VARIANCE / MOTION_INTENSITY / VISUAL_DENSITY
48
+ # knobs: three optional 1-10 sliders that bias the existing query-based search
49
+ # instead of replacing it. Each dial buckets into a low/mid/high tier.
50
+ DIAL_TIERS = {
51
+ "variance": [
52
+ (1, 3, {"label": "Centered / Minimal", "style_keywords": ["Minimalism", "Exaggerated Minimalism", "centered", "symmetric", "grid-based"]}),
53
+ (4, 7, {"label": "Balanced / Modern", "style_keywords": ["modern", "structured", "balanced"]}),
54
+ (8, 10, {"label": "Bold / Asymmetric", "style_keywords": ["Brutalism", "Bento Grids", "asymmetric", "experimental"]}),
55
+ ],
56
+ "motion": [
57
+ (1, 3, {"label": "Subtle", "tier": "Subtle"}),
58
+ (4, 7, {"label": "Standard", "tier": "Standard"}),
59
+ (8, 10, {"label": "Complex", "tier": "Complex"}),
60
+ ],
61
+ "density": [
62
+ (1, 3, {"label": "Spacious", "spacing": {"xs": "4px", "sm": "8px", "md": "24px", "lg": "32px", "xl": "48px", "2xl": "64px", "3xl": "96px"}}),
63
+ (4, 7, {"label": "Standard", "spacing": {"xs": "4px", "sm": "8px", "md": "16px", "lg": "24px", "xl": "32px", "2xl": "48px", "3xl": "64px"}}),
64
+ (8, 10, {"label": "Dense / Dashboard", "spacing": {"xs": "2px", "sm": "4px", "md": "8px", "lg": "12px", "xl": "16px", "2xl": "24px", "3xl": "32px"}}),
65
+ ],
66
+ }
67
+
68
+
69
+ def _resolve_dial(dial_name: str, value) -> dict:
70
+ """Bucket a 1-10 dial value into its tier config. Returns None if value is None."""
71
+ if value is None:
72
+ return None
73
+ value = max(1, min(10, int(value)))
74
+ for lo, hi, info in DIAL_TIERS[dial_name]:
75
+ if lo <= value <= hi:
76
+ return {**info, "value": value}
77
+ return None
78
+
79
+
80
+ # ============ COLOR MODE RESOLUTION ============
81
+ # Style, palette and anti-patterns are resolved from separate CSVs. Without a
82
+ # shared notion of "which mode did we land on", a dark-primary style can be
83
+ # paired with a light palette and a "don't use dark mode" anti-pattern.
84
+
85
+ # Phrases in styles.csv "Light Mode ✓" / "Dark Mode ✓" that mark a style as
86
+ # dark-first rather than merely dark-capable ("✓ Full" means both work).
87
+ _DARK_PRIMARY_MARKERS = (
88
+ "dark mode primary", "dark primary", "dark-only", "dark only",
89
+ "dark preferred", "dark focused", "dark-first", "dark rich",
90
+ "light mode only as exception",
91
+ )
92
+
93
+ # Query phrases that are an explicit request for a dark theme.
94
+ _DARK_QUERY_MARKERS = (
95
+ "dark mode", "dark theme", "dark ui", "dark-mode", "darkmode",
96
+ "night mode", "midnight", "oled",
97
+ )
98
+
99
+ # Anti-pattern clauses that contradict a resolved dark mode.
100
+ _DARK_ANTI_PATTERN_MARKERS = ("dark mode", "dark modes", "dark theme")
101
+
102
+ # Relative luminance below which a Background hex counts as a dark surface.
103
+ # #1F2937 (the lightest dark background in colors.csv) sits at ~0.026 and
104
+ # #E8ECF1 (the darkest light background) at ~0.79, so the gap is wide.
105
+ _DARK_BACKGROUND_MAX_LUMINANCE = 0.18
106
+
107
+
108
+ def _relative_luminance(hex_color: str):
109
+ """WCAG relative luminance of a #RRGGBB string, or None if unparseable."""
110
+ if not hex_color:
111
+ return None
112
+ value = hex_color.strip().lstrip("#")
113
+ if len(value) == 3:
114
+ value = "".join(c * 2 for c in value)
115
+ if len(value) != 6:
116
+ return None
117
+ try:
118
+ channels = [int(value[i:i + 2], 16) / 255 for i in (0, 2, 4)]
119
+ except ValueError:
120
+ return None
121
+ linear = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
122
+ for c in channels]
123
+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
124
+
125
+
126
+ def _palette_is_dark(palette: dict) -> bool:
127
+ """True when a colors.csv row's Background is a dark surface."""
128
+ luminance = _relative_luminance((palette or {}).get("Background", ""))
129
+ return luminance is not None and luminance < _DARK_BACKGROUND_MAX_LUMINANCE
130
+
131
+
132
+ def _style_is_dark_primary(style: dict) -> bool:
133
+ """True when a styles.csv row describes itself as dark-first."""
134
+ if not style:
135
+ return False
136
+ declared = "{} {}".format(
137
+ style.get("Light Mode ✓", ""), style.get("Dark Mode ✓", "")
138
+ ).lower()
139
+ return any(marker in declared for marker in _DARK_PRIMARY_MARKERS)
140
+
141
+
142
+ def _query_wants_dark(query: str) -> bool:
143
+ """True when the query explicitly asks for a dark theme."""
144
+ lowered = (query or "").lower()
145
+ return any(marker in lowered for marker in _DARK_QUERY_MARKERS)
146
+
147
+
148
+ def _resolve_color_mode(query: str, style: dict) -> str:
149
+ """Resolve the mode the rest of the output has to agree with."""
150
+ if _query_wants_dark(query) or _style_is_dark_primary(style):
151
+ return "dark"
152
+ return "light"
153
+
154
+
155
+ def _select_palette_for_mode(palettes: list, mode: str) -> dict:
156
+ """Pick the highest-ranked palette matching the resolved mode.
157
+
158
+ Only the dark case filters. Light is left on the existing "top hit wins"
159
+ behaviour so queries that never mention a mode keep their current palette.
160
+ Falls back to the top hit when the data has no matching ramp.
161
+ """
162
+ if not palettes:
163
+ return {}
164
+ if mode == "dark":
165
+ for palette in palettes:
166
+ if _palette_is_dark(palette):
167
+ return palette
168
+ return palettes[0]
169
+
170
+
171
+ def _filter_anti_patterns_for_mode(anti_patterns: str, mode: str) -> str:
172
+ """Drop "avoid dark mode" advice once dark mode is the resolved answer."""
173
+ if mode != "dark" or not anti_patterns:
174
+ return anti_patterns
175
+ kept = [
176
+ clause for clause in anti_patterns.split("+")
177
+ if not any(marker in clause.lower() for marker in _DARK_ANTI_PATTERN_MARKERS)
178
+ ]
179
+ return " + ".join(clause.strip() for clause in kept if clause.strip())
180
+
181
+
182
+ # ============ DESIGN SYSTEM GENERATOR ============
183
+ class DesignSystemGenerator:
184
+ """Generates design system recommendations from aggregated searches."""
185
+
186
+ def __init__(self):
187
+ self.reasoning_data = self._load_reasoning()
188
+
189
+ def _load_reasoning(self) -> list:
190
+ """Load reasoning rules from CSV."""
191
+ filepath = DATA_DIR / REASONING_FILE
192
+ if not filepath.exists():
193
+ return []
194
+ with open(filepath, 'r', encoding='utf-8') as f:
195
+ return list(csv.DictReader(f))
196
+
197
+ def _multi_domain_search(self, query: str, style_priority: list = None) -> dict:
198
+ """Execute searches across multiple domains."""
199
+ results = {}
200
+ for domain, config in SEARCH_CONFIG.items():
201
+ if domain == "style" and style_priority:
202
+ # For style, also search with priority keywords
203
+ priority_query = " ".join(style_priority[:2]) if style_priority else query
204
+ combined_query = f"{query} {priority_query}"
205
+ results[domain] = search(combined_query, domain, config["max_results"])
206
+ else:
207
+ results[domain] = search(query, domain, config["max_results"])
208
+ return results
209
+
210
+ def _find_reasoning_rule(self, category: str) -> dict:
211
+ """Find matching reasoning rule for a category."""
212
+ category_lower = category.lower()
213
+
214
+ # Try exact match first
215
+ for rule in self.reasoning_data:
216
+ if rule.get("UI_Category", "").lower() == category_lower:
217
+ return rule
218
+
219
+ # Try partial match
220
+ for rule in self.reasoning_data:
221
+ ui_cat = rule.get("UI_Category", "").lower()
222
+ if ui_cat in category_lower or category_lower in ui_cat:
223
+ return rule
224
+
225
+ # Try keyword match
226
+ for rule in self.reasoning_data:
227
+ ui_cat = rule.get("UI_Category", "").lower()
228
+ keywords = ui_cat.replace("/", " ").replace("-", " ").split()
229
+ if any(kw in category_lower for kw in keywords):
230
+ return rule
231
+
232
+ return {}
233
+
234
+ def _apply_reasoning(self, category: str, search_results: dict) -> dict:
235
+ """Apply reasoning rules to search results."""
236
+ rule = self._find_reasoning_rule(category)
237
+
238
+ if not rule:
239
+ return {
240
+ "pattern": "Hero + Features + CTA",
241
+ "style_priority": ["Minimalism", "Flat Design"],
242
+ "color_mood": "Professional",
243
+ "typography_mood": "Clean",
244
+ "key_effects": "Subtle hover transitions",
245
+ "anti_patterns": "",
246
+ "decision_rules": {},
247
+ "severity": "MEDIUM"
248
+ }
249
+
250
+ # Parse decision rules JSON
251
+ decision_rules = {}
252
+ try:
253
+ decision_rules = json.loads(rule.get("Decision_Rules", "{}"))
254
+ except json.JSONDecodeError:
255
+ pass
256
+
257
+ return {
258
+ "pattern": rule.get("Recommended_Pattern", ""),
259
+ "style_priority": [s.strip() for s in rule.get("Style_Priority", "").split("+")],
260
+ "color_mood": rule.get("Color_Mood", ""),
261
+ "typography_mood": rule.get("Typography_Mood", ""),
262
+ "key_effects": rule.get("Key_Effects", ""),
263
+ "anti_patterns": rule.get("Anti_Patterns", ""),
264
+ "decision_rules": decision_rules,
265
+ "severity": rule.get("Severity", "MEDIUM")
266
+ }
267
+
268
+ def _select_best_match(self, results: list, priority_keywords: list) -> dict:
269
+ """Select best matching result based on priority keywords."""
270
+ if not results:
271
+ return {}
272
+
273
+ if not priority_keywords:
274
+ return results[0]
275
+
276
+ # First: try exact style name match
277
+ for priority in priority_keywords:
278
+ priority_lower = priority.lower().strip()
279
+ for result in results:
280
+ style_name = result.get("Style Category", "").lower()
281
+ if priority_lower in style_name or style_name in priority_lower:
282
+ return result
283
+
284
+ # Second: score by keyword match in all fields
285
+ scored = []
286
+ for result in results:
287
+ result_str = str(result).lower()
288
+ score = 0
289
+ for kw in priority_keywords:
290
+ kw_lower = kw.lower().strip()
291
+ # Higher score for style name match
292
+ if kw_lower in result.get("Style Category", "").lower():
293
+ score += 10
294
+ # Lower score for keyword field match
295
+ elif kw_lower in result.get("Keywords", "").lower():
296
+ score += 3
297
+ # Even lower for other field matches
298
+ elif kw_lower in result_str:
299
+ score += 1
300
+ scored.append((score, result))
301
+
302
+ scored.sort(key=lambda x: x[0], reverse=True)
303
+ return scored[0][1] if scored and scored[0][0] > 0 else results[0]
304
+
305
+ def _extract_results(self, search_result: dict) -> list:
306
+ """Extract results list from search result dict."""
307
+ return search_result.get("results", [])
308
+
309
+ def generate(self, query: str, project_name: str = None,
310
+ variance: int = None, motion: int = None, density: int = None) -> dict:
311
+ """Generate complete design system recommendation.
312
+
313
+ variance/motion/density are optional 1-10 dials (see DIAL_TIERS) that bias
314
+ style selection, pull in a matching motion.csv snippet, and override the
315
+ spacing scale, without changing behavior when left unset.
316
+ """
317
+ variance_info = _resolve_dial("variance", variance)
318
+ motion_info = _resolve_dial("motion", motion)
319
+ density_info = _resolve_dial("density", density)
320
+
321
+ # Step 1: First search product to get category
322
+ product_result = search(query, "product", 1)
323
+ product_results = product_result.get("results", [])
324
+ category = "General"
325
+ if product_results:
326
+ category = product_results[0].get("Product Type", "General")
327
+
328
+ # Step 2: Get reasoning rules for this category
329
+ reasoning = self._apply_reasoning(category, {})
330
+ style_priority = reasoning.get("style_priority", [])
331
+
332
+ # DESIGN_VARIANCE dial: bias style retrieval/selection toward
333
+ # centered-minimal (low) or bold-asymmetric (high) keywords.
334
+ effective_style_priority = style_priority
335
+ if variance_info:
336
+ effective_style_priority = variance_info["style_keywords"] + style_priority
337
+
338
+ # Step 3: Multi-domain search with style priority hints
339
+ search_results = self._multi_domain_search(query, effective_style_priority)
340
+ search_results["product"] = product_result # Reuse product search
341
+
342
+ # Step 4: Select best matches from each domain using priority
343
+ style_results = self._extract_results(search_results.get("style", {}))
344
+ color_results = self._extract_results(search_results.get("color", {}))
345
+ typography_results = self._extract_results(search_results.get("typography", {}))
346
+ landing_results = self._extract_results(search_results.get("landing", {}))
347
+
348
+ best_style = self._select_best_match(style_results, effective_style_priority)
349
+ # Resolve the mode from the style + query first, then pick a palette that
350
+ # agrees with it. Ranking colors independently is what let a dark-primary
351
+ # style ship with a light background.
352
+ color_mode = _resolve_color_mode(query, best_style)
353
+ best_color = _select_palette_for_mode(color_results, color_mode)
354
+ best_typography = typography_results[0] if typography_results else {}
355
+ best_landing = landing_results[0] if landing_results else {}
356
+
357
+ # MOTION_INTENSITY dial: pull a matching GSAP skeleton from motion.csv
358
+ # (domain key is "gsap", not "motion" - PR #296 already owns the "motion"
359
+ # domain for Emil Kowalski's motion-design principles, motion-principles.csv).
360
+ motion_snippet = {}
361
+ if motion_info:
362
+ motion_result = search(f"{query} {motion_info['tier']}", "gsap", 5)
363
+ motion_matches = motion_result.get("results", [])
364
+ tiered = [m for m in motion_matches if m.get("Intensity Tier") == motion_info["tier"]]
365
+ if tiered:
366
+ motion_snippet = tiered[0]
367
+ elif motion_matches:
368
+ motion_snippet = motion_matches[0]
369
+
370
+ # Step 5: Build final recommendation
371
+ # Combine effects from both reasoning and style search
372
+ style_effects = best_style.get("Effects & Animation", "")
373
+ reasoning_effects = reasoning.get("key_effects", "")
374
+ combined_effects = style_effects if style_effects else reasoning_effects
375
+
376
+ return {
377
+ "project_name": project_name or query.upper(),
378
+ "category": category,
379
+ "pattern": {
380
+ "name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
381
+ "sections": best_landing.get("Section Order", "Hero > Features > CTA"),
382
+ "cta_placement": best_landing.get("Primary CTA Placement", "Above fold"),
383
+ "color_strategy": best_landing.get("Color Strategy", ""),
384
+ "conversion": best_landing.get("Conversion Optimization", "")
385
+ },
386
+ "style": {
387
+ "name": best_style.get("Style Category", "Minimalism"),
388
+ "type": best_style.get("Type", "General"),
389
+ "effects": style_effects,
390
+ "keywords": best_style.get("Keywords", ""),
391
+ "best_for": best_style.get("Best For", ""),
392
+ "performance": best_style.get("Performance", ""),
393
+ "accessibility": best_style.get("Accessibility", ""),
394
+ "light_mode": best_style.get("Light Mode ✓", ""),
395
+ "dark_mode": best_style.get("Dark Mode ✓", ""),
396
+ },
397
+ "colors": {
398
+ "primary": best_color.get("Primary", "#2563EB"),
399
+ "on_primary": best_color.get("On Primary", ""),
400
+ "secondary": best_color.get("Secondary", "#3B82F6"),
401
+ "accent": best_color.get("Accent", "#F97316"),
402
+ "background": best_color.get("Background", "#F8FAFC"),
403
+ "foreground": best_color.get("Foreground", "#1E293B"),
404
+ "muted": best_color.get("Muted", ""),
405
+ "border": best_color.get("Border", ""),
406
+ "destructive": best_color.get("Destructive", ""),
407
+ "ring": best_color.get("Ring", ""),
408
+ "notes": best_color.get("Notes", ""),
409
+ # Keep legacy keys for backward compat in MASTER.md
410
+ "cta": best_color.get("Accent", "#F97316"),
411
+ "text": best_color.get("Foreground", "#1E293B"),
412
+ },
413
+ "typography": {
414
+ "heading": best_typography.get("Heading Font", "Inter"),
415
+ "body": best_typography.get("Body Font", "Inter"),
416
+ "mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
417
+ "best_for": best_typography.get("Best For", ""),
418
+ "google_fonts_url": best_typography.get("Google Fonts URL", ""),
419
+ "css_import": best_typography.get("CSS Import", "")
420
+ },
421
+ "key_effects": combined_effects,
422
+ "anti_patterns": _filter_anti_patterns_for_mode(
423
+ reasoning.get("anti_patterns", ""), color_mode
424
+ ),
425
+ "decision_rules": reasoning.get("decision_rules", {}),
426
+ "severity": reasoning.get("severity", "MEDIUM"),
427
+ "dials": {
428
+ "variance": variance_info["value"] if variance_info else None,
429
+ "variance_label": variance_info["label"] if variance_info else None,
430
+ "motion": motion_info["value"] if motion_info else None,
431
+ "motion_label": motion_info["label"] if motion_info else None,
432
+ "density": density_info["value"] if density_info else None,
433
+ "density_label": density_info["label"] if density_info else None,
434
+ },
435
+ "motion_snippet": motion_snippet,
436
+ "spacing_scale": density_info["spacing"] if density_info else None,
437
+ }
438
+
439
+
440
+ # ============ OUTPUT FORMATTERS ============
441
+ BOX_WIDTH = 90 # Wider box for more content
442
+
443
+
444
+ def hex_to_ansi(hex_color: str) -> str:
445
+ """Convert hex color to ANSI True Color swatch (██) with fallback."""
446
+ if not hex_color or not hex_color.startswith('#'):
447
+ return ""
448
+ colorterm = os.environ.get('COLORTERM', '')
449
+ if colorterm not in ('truecolor', '24bit'):
450
+ return ""
451
+ hex_color = hex_color.lstrip('#')
452
+ if len(hex_color) != 6:
453
+ return ""
454
+ r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
455
+ return f"\033[38;2;{r};{g};{b}m██\033[0m "
456
+
457
+
458
+ def ansi_ljust(s: str, width: int) -> str:
459
+ """Like str.ljust but accounts for zero-width ANSI escape sequences."""
460
+ import re
461
+ visible_len = len(re.sub(r'\033\[[0-9;]*m', '', s))
462
+ pad = width - visible_len
463
+ return s + (" " * max(0, pad))
464
+
465
+
466
+ def section_header(name: str, width: int) -> str:
467
+ """Create a Unicode section separator: ├─── NAME ───...┤"""
468
+ label = f"─── {name} "
469
+ fill = "─" * (width - len(label) - 1)
470
+ return f"├{label}{fill}┤"
471
+
472
+
473
+ def format_ascii_box(design_system: dict) -> str:
474
+ """Format design system as Unicode box with ANSI color swatches."""
475
+ project = design_system.get("project_name", "PROJECT")
476
+ pattern = design_system.get("pattern", {})
477
+ style = design_system.get("style", {})
478
+ colors = design_system.get("colors", {})
479
+ typography = design_system.get("typography", {})
480
+ effects = design_system.get("key_effects", "")
481
+ anti_patterns = design_system.get("anti_patterns", "")
482
+ dials = design_system.get("dials", {})
483
+ motion_snippet = design_system.get("motion_snippet", {})
484
+
485
+ def wrap_text(text: str, prefix: str, width: int) -> list:
486
+ """Wrap long text into multiple lines."""
487
+ if not text:
488
+ return []
489
+ words = text.split()
490
+ lines = []
491
+ current_line = prefix
492
+ for word in words:
493
+ if len(current_line) + len(word) + 1 <= width - 2:
494
+ current_line += (" " if current_line != prefix else "") + word
495
+ else:
496
+ if current_line != prefix:
497
+ lines.append(current_line)
498
+ current_line = prefix + word
499
+ if current_line != prefix:
500
+ lines.append(current_line)
501
+ return lines
502
+
503
+ # Build sections from pattern
504
+ sections = pattern.get("sections", "").split(">")
505
+ sections = [s.strip() for s in sections if s.strip()]
506
+
507
+ # Build output lines
508
+ lines = []
509
+ w = BOX_WIDTH - 1
510
+
511
+ # Header with double-line box
512
+ lines.append("╔" + "═" * w + "╗")
513
+ lines.append(ansi_ljust(f"║ TARGET: {project} - RECOMMENDED DESIGN SYSTEM", BOX_WIDTH) + "║")
514
+ lines.append("╚" + "═" * w + "╝")
515
+ lines.append("┌" + "─" * w + "┐")
516
+
517
+ # Design Dials section (only if at least one dial was set)
518
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
519
+ lines.append(section_header("DESIGN DIALS", BOX_WIDTH + 1))
520
+ if dials.get("variance") is not None:
521
+ lines.append(f"│ Variance: {dials['variance']}/10 — {dials['variance_label']}".ljust(BOX_WIDTH) + "│")
522
+ if dials.get("motion") is not None:
523
+ lines.append(f"│ Motion: {dials['motion']}/10 — {dials['motion_label']}".ljust(BOX_WIDTH) + "│")
524
+ if dials.get("density") is not None:
525
+ lines.append(f"│ Density: {dials['density']}/10 — {dials['density_label']}".ljust(BOX_WIDTH) + "│")
526
+
527
+ # Pattern section
528
+ lines.append(section_header("PATTERN", BOX_WIDTH + 1))
529
+ lines.append(f"│ Name: {pattern.get('name', '')}".ljust(BOX_WIDTH) + "│")
530
+ if pattern.get('conversion'):
531
+ lines.append(f"│ Conversion: {pattern.get('conversion', '')}".ljust(BOX_WIDTH) + "│")
532
+ if pattern.get('cta_placement'):
533
+ lines.append(f"│ CTA: {pattern.get('cta_placement', '')}".ljust(BOX_WIDTH) + "│")
534
+ lines.append("│ Sections:".ljust(BOX_WIDTH) + "│")
535
+ for i, section in enumerate(sections, 1):
536
+ lines.append(f"│ {i}. {section}".ljust(BOX_WIDTH) + "│")
537
+
538
+ # Style section
539
+ lines.append(section_header("STYLE", BOX_WIDTH + 1))
540
+ lines.append(f"│ Name: {style.get('name', '')}".ljust(BOX_WIDTH) + "│")
541
+ light = style.get("light_mode", "")
542
+ dark = style.get("dark_mode", "")
543
+ if light or dark:
544
+ lines.append(f"│ Mode Support: Light {light} Dark {dark}".ljust(BOX_WIDTH) + "│")
545
+ if style.get("keywords"):
546
+ for line in wrap_text(f"Keywords: {style.get('keywords', '')}", "│ ", BOX_WIDTH):
547
+ lines.append(line.ljust(BOX_WIDTH) + "│")
548
+ if style.get("best_for"):
549
+ for line in wrap_text(f"Best For: {style.get('best_for', '')}", "│ ", BOX_WIDTH):
550
+ lines.append(line.ljust(BOX_WIDTH) + "│")
551
+ if style.get("performance") or style.get("accessibility"):
552
+ perf_a11y = f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}"
553
+ lines.append(f"│ {perf_a11y}".ljust(BOX_WIDTH) + "│")
554
+
555
+ # Colors section (extended palette with ANSI swatches)
556
+ lines.append(section_header("COLORS", BOX_WIDTH + 1))
557
+ color_entries = [
558
+ ("Primary", "primary", "--color-primary"),
559
+ ("On Primary", "on_primary", "--color-on-primary"),
560
+ ("Secondary", "secondary", "--color-secondary"),
561
+ ("Accent/CTA", "accent", "--color-accent"),
562
+ ("Background", "background", "--color-background"),
563
+ ("Foreground", "foreground", "--color-foreground"),
564
+ ("Muted", "muted", "--color-muted"),
565
+ ("Border", "border", "--color-border"),
566
+ ("Destructive", "destructive", "--color-destructive"),
567
+ ("Ring", "ring", "--color-ring"),
568
+ ]
569
+ for label, key, css_var in color_entries:
570
+ hex_val = colors.get(key, "")
571
+ if not hex_val:
572
+ continue
573
+ swatch = hex_to_ansi(hex_val)
574
+ content = f"│ {swatch}{label + ':':14s} {hex_val:10s} ({css_var})"
575
+ lines.append(ansi_ljust(content, BOX_WIDTH) + "│")
576
+ if colors.get("notes"):
577
+ for line in wrap_text(f"Notes: {colors.get('notes', '')}", "│ ", BOX_WIDTH):
578
+ lines.append(line.ljust(BOX_WIDTH) + "│")
579
+
580
+ # Typography section
581
+ lines.append(section_header("TYPOGRAPHY", BOX_WIDTH + 1))
582
+ lines.append(f"│ {typography.get('heading', '')} / {typography.get('body', '')}".ljust(BOX_WIDTH) + "│")
583
+ if typography.get("mood"):
584
+ for line in wrap_text(f"Mood: {typography.get('mood', '')}", "│ ", BOX_WIDTH):
585
+ lines.append(line.ljust(BOX_WIDTH) + "│")
586
+ if typography.get("best_for"):
587
+ for line in wrap_text(f"Best For: {typography.get('best_for', '')}", "│ ", BOX_WIDTH):
588
+ lines.append(line.ljust(BOX_WIDTH) + "│")
589
+ if typography.get("google_fonts_url"):
590
+ lines.append(f"│ Google Fonts: {typography.get('google_fonts_url', '')}".ljust(BOX_WIDTH) + "│")
591
+ if typography.get("css_import"):
592
+ lines.append(f"│ CSS Import: {typography.get('css_import', '')[:70]}...".ljust(BOX_WIDTH) + "│")
593
+
594
+ # Key Effects section
595
+ if effects:
596
+ lines.append(section_header("KEY EFFECTS", BOX_WIDTH + 1))
597
+ for line in wrap_text(effects, "│ ", BOX_WIDTH):
598
+ lines.append(line.ljust(BOX_WIDTH) + "│")
599
+
600
+ # Motion section (GSAP skeleton, only if --motion dial was set)
601
+ if motion_snippet:
602
+ lines.append(section_header("MOTION", BOX_WIDTH + 1))
603
+ lines.append(f"│ {motion_snippet.get('Category', '')} ({motion_snippet.get('Intensity Tier', '')})".ljust(BOX_WIDTH) + "│")
604
+ lines.append(f"│ Trigger: {motion_snippet.get('Trigger', '')} | Duration: {motion_snippet.get('Duration', '')} | Easing: {motion_snippet.get('Easing', '')}".ljust(BOX_WIDTH) + "│")
605
+ for line in wrap_text(f"GSAP: {motion_snippet.get('GSAP Snippet', '')}", "│ ", BOX_WIDTH):
606
+ lines.append(line.ljust(BOX_WIDTH) + "│")
607
+ if motion_snippet.get("Framework Notes"):
608
+ for line in wrap_text(f"Framework: {motion_snippet.get('Framework Notes', '')}", "│ ", BOX_WIDTH):
609
+ lines.append(line.ljust(BOX_WIDTH) + "│")
610
+
611
+ # Anti-patterns section
612
+ if anti_patterns:
613
+ lines.append(section_header("AVOID", BOX_WIDTH + 1))
614
+ for line in wrap_text(anti_patterns, "│ ", BOX_WIDTH):
615
+ lines.append(line.ljust(BOX_WIDTH) + "│")
616
+
617
+ # Pre-Delivery Checklist section
618
+ lines.append(section_header("PRE-DELIVERY CHECKLIST", BOX_WIDTH + 1))
619
+ checklist_items = [
620
+ "[ ] No emojis as icons (use SVG: Heroicons/Lucide)",
621
+ "[ ] cursor-pointer on all clickable elements",
622
+ "[ ] Hover states with smooth transitions (150-300ms)",
623
+ "[ ] Light mode: text contrast 4.5:1 minimum",
624
+ "[ ] Focus states visible for keyboard nav",
625
+ "[ ] prefers-reduced-motion respected",
626
+ "[ ] Responsive: 375px, 768px, 1024px, 1440px"
627
+ ]
628
+ for item in checklist_items:
629
+ lines.append(f"│ {item}".ljust(BOX_WIDTH) + "│")
630
+
631
+ lines.append("└" + "─" * w + "┘")
632
+
633
+ return "\n".join(lines)
634
+
635
+
636
+ def format_markdown(design_system: dict) -> str:
637
+ """Format design system as markdown."""
638
+ project = design_system.get("project_name", "PROJECT")
639
+ pattern = design_system.get("pattern", {})
640
+ style = design_system.get("style", {})
641
+ colors = design_system.get("colors", {})
642
+ typography = design_system.get("typography", {})
643
+ effects = design_system.get("key_effects", "")
644
+ anti_patterns = design_system.get("anti_patterns", "")
645
+ dials = design_system.get("dials", {})
646
+ motion_snippet = design_system.get("motion_snippet", {})
647
+
648
+ lines = []
649
+ lines.append(f"## Design System: {project}")
650
+ lines.append("")
651
+
652
+ # Design Dials section (only if at least one dial was set)
653
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
654
+ lines.append("### Design Dials")
655
+ if dials.get("variance") is not None:
656
+ lines.append(f"- **Variance:** {dials['variance']}/10 — {dials['variance_label']}")
657
+ if dials.get("motion") is not None:
658
+ lines.append(f"- **Motion:** {dials['motion']}/10 — {dials['motion_label']}")
659
+ if dials.get("density") is not None:
660
+ lines.append(f"- **Density:** {dials['density']}/10 — {dials['density_label']}")
661
+ lines.append("")
662
+
663
+ # Pattern section
664
+ lines.append("### Pattern")
665
+ lines.append(f"- **Name:** {pattern.get('name', '')}")
666
+ if pattern.get('conversion'):
667
+ lines.append(f"- **Conversion Focus:** {pattern.get('conversion', '')}")
668
+ if pattern.get('cta_placement'):
669
+ lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
670
+ if pattern.get('color_strategy'):
671
+ lines.append(f"- **Color Strategy:** {pattern.get('color_strategy', '')}")
672
+ lines.append(f"- **Sections:** {pattern.get('sections', '')}")
673
+ lines.append("")
674
+
675
+ # Style section
676
+ lines.append("### Style")
677
+ lines.append(f"- **Name:** {style.get('name', '')}")
678
+ light = style.get("light_mode", "")
679
+ dark = style.get("dark_mode", "")
680
+ if light or dark:
681
+ lines.append(f"- **Mode Support:** Light {light} | Dark {dark}")
682
+ if style.get('keywords'):
683
+ lines.append(f"- **Keywords:** {style.get('keywords', '')}")
684
+ if style.get('best_for'):
685
+ lines.append(f"- **Best For:** {style.get('best_for', '')}")
686
+ if style.get('performance') or style.get('accessibility'):
687
+ lines.append(f"- **Performance:** {style.get('performance', '')} | **Accessibility:** {style.get('accessibility', '')}")
688
+ lines.append("")
689
+
690
+ # Colors section (extended palette)
691
+ lines.append("### Colors")
692
+ lines.append("| Role | Hex | CSS Variable |")
693
+ lines.append("|------|-----|--------------|")
694
+ md_color_entries = [
695
+ ("Primary", "primary", "--color-primary"),
696
+ ("On Primary", "on_primary", "--color-on-primary"),
697
+ ("Secondary", "secondary", "--color-secondary"),
698
+ ("Accent/CTA", "accent", "--color-accent"),
699
+ ("Background", "background", "--color-background"),
700
+ ("Foreground", "foreground", "--color-foreground"),
701
+ ("Muted", "muted", "--color-muted"),
702
+ ("Border", "border", "--color-border"),
703
+ ("Destructive", "destructive", "--color-destructive"),
704
+ ("Ring", "ring", "--color-ring"),
705
+ ]
706
+ for label, key, css_var in md_color_entries:
707
+ hex_val = colors.get(key, "")
708
+ if hex_val:
709
+ lines.append(f"| {label} | `{hex_val}` | `{css_var}` |")
710
+ if colors.get("notes"):
711
+ lines.append(f"\n*Notes: {colors.get('notes', '')}*")
712
+ lines.append("")
713
+
714
+ # Typography section
715
+ lines.append("### Typography")
716
+ lines.append(f"- **Heading:** {typography.get('heading', '')}")
717
+ lines.append(f"- **Body:** {typography.get('body', '')}")
718
+ if typography.get("mood"):
719
+ lines.append(f"- **Mood:** {typography.get('mood', '')}")
720
+ if typography.get("best_for"):
721
+ lines.append(f"- **Best For:** {typography.get('best_for', '')}")
722
+ if typography.get("google_fonts_url"):
723
+ lines.append(f"- **Google Fonts:** {typography.get('google_fonts_url', '')}")
724
+ if typography.get("css_import"):
725
+ lines.append(f"- **CSS Import:**")
726
+ lines.append(f"```css")
727
+ lines.append(f"{typography.get('css_import', '')}")
728
+ lines.append(f"```")
729
+ lines.append("")
730
+
731
+ # Key Effects section
732
+ if effects:
733
+ lines.append("### Key Effects")
734
+ lines.append(f"{effects}")
735
+ lines.append("")
736
+
737
+ # Motion section (GSAP skeleton, only if --motion dial was set)
738
+ if motion_snippet:
739
+ lines.append("### Motion")
740
+ lines.append(f"**{motion_snippet.get('Category', '')}** ({motion_snippet.get('Intensity Tier', '')}) — Trigger: {motion_snippet.get('Trigger', '')} | Duration: {motion_snippet.get('Duration', '')} | Easing: `{motion_snippet.get('Easing', '')}`")
741
+ lines.append("```js")
742
+ lines.append(motion_snippet.get("GSAP Snippet", ""))
743
+ lines.append("```")
744
+ if motion_snippet.get("Framework Notes"):
745
+ lines.append(f"*Framework notes: {motion_snippet.get('Framework Notes', '')}*")
746
+ motion_do = motion_snippet.get("Do", "")
747
+ motion_dont = motion_snippet.get("Don't", "")
748
+ if motion_do:
749
+ lines.append(f"- ✅ {motion_do}")
750
+ if motion_dont:
751
+ lines.append(f"- ❌ {motion_dont}")
752
+ lines.append("")
753
+
754
+ # Anti-patterns section
755
+ if anti_patterns:
756
+ lines.append("### Avoid (Anti-patterns)")
757
+ newline_bullet = '\n- '
758
+ lines.append(f"- {anti_patterns.replace(' + ', newline_bullet)}")
759
+ lines.append("")
760
+
761
+ # Pre-Delivery Checklist section
762
+ lines.append("### Pre-Delivery Checklist")
763
+ lines.append("- [ ] No emojis as icons (use SVG: Heroicons/Lucide)")
764
+ lines.append("- [ ] cursor-pointer on all clickable elements")
765
+ lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
766
+ lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
767
+ lines.append("- [ ] Focus states visible for keyboard nav")
768
+ lines.append("- [ ] prefers-reduced-motion respected")
769
+ lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
770
+ lines.append("")
771
+
772
+ return "\n".join(lines)
773
+
774
+
775
+ # ============ MAIN ENTRY POINT ============
776
+ def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii",
777
+ persist: bool = False, page: str = None, output_dir: str = None,
778
+ variance: int = None, motion: int = None, density: int = None,
779
+ force: bool = False) -> dict:
780
+ """
781
+ Main entry point for design system generation.
782
+
783
+ Args:
784
+ query: Search query (e.g., "SaaS dashboard", "e-commerce luxury")
785
+ project_name: Optional project name for output header
786
+ output_format: "ascii" (default) or "markdown"
787
+ persist: If True, save design system to design-system/ folder
788
+ page: Optional page name for page-specific override file
789
+ output_dir: Optional output directory (defaults to current working directory)
790
+ variance: Optional 1-10 DESIGN_VARIANCE dial (1=centered/minimal, 10=bold/asymmetric)
791
+ motion: Optional 1-10 MOTION_INTENSITY dial, pulls a matching GSAP snippet from motion.csv
792
+ density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense)
793
+ force: If True, overwrite an existing MASTER.md; otherwise persistence
794
+ is skipped (with a status message) when one already exists
795
+
796
+ Returns:
797
+ dict with keys: "text" (formatted design system string), "design_system"
798
+ (raw dict, useful for --json callers), and "persistence" (result of
799
+ persist_design_system(), or None if persist=False)
800
+ """
801
+ generator = DesignSystemGenerator()
802
+ design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
803
+
804
+ persistence_result = None
805
+ if persist:
806
+ persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
807
+
808
+ text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system)
809
+
810
+ return {
811
+ "text": text,
812
+ "design_system": design_system,
813
+ "persistence": persistence_result,
814
+ }
815
+
816
+
817
+ # ============ PERSISTENCE FUNCTIONS ============
818
+ def safe_slug(name, fallback: str = "default") -> str:
819
+ """Slugify a name into a single safe path segment.
820
+
821
+ Only [a-z0-9_-] survives; every other character (including '/', '\\' and
822
+ '.') collapses into '-'. This makes path traversal via project/page names
823
+ (e.g. "../../etc") impossible — the slug can never leave its parent dir.
824
+ """
825
+ slug = re.sub(r'[^a-z0-9_-]+', '-', str(name).lower()).strip('-')
826
+ return slug or fallback
827
+
828
+
829
+ def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
830
+ page_query: str = None, force: bool = False) -> dict:
831
+ """
832
+ Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
833
+
834
+ Args:
835
+ design_system: The generated design system dictionary
836
+ page: Optional page name for page-specific override file
837
+ output_dir: Optional output directory (defaults to current working directory)
838
+ page_query: Optional query string for intelligent page override generation
839
+ force: If True, overwrite an existing MASTER.md. If False (default) and
840
+ MASTER.md already exists, persistence is skipped so prior design
841
+ decisions aren't silently discarded.
842
+
843
+ Returns:
844
+ dict with created file paths and status. status is "skipped_exists" if
845
+ MASTER.md already existed and force was not set.
846
+ """
847
+ base_dir = Path(output_dir) if output_dir else Path.cwd()
848
+
849
+ # Use project name for project-specific folder. Coalesce falsy values
850
+ # (missing key, explicit None, or "") so the .lower() below can't crash.
851
+ project_name = design_system.get("project_name") or "default"
852
+ project_slug = safe_slug(project_name)
853
+
854
+ design_system_dir = base_dir / "design-system" / project_slug
855
+ pages_dir = design_system_dir / "pages"
856
+
857
+ master_file = design_system_dir / "MASTER.md"
858
+
859
+ if master_file.exists() and not force:
860
+ return {
861
+ "status": "skipped_exists",
862
+ "design_system_dir": str(design_system_dir),
863
+ "master_file": str(master_file),
864
+ "created_files": [],
865
+ "message": (
866
+ f"{master_file} already exists and was not modified. "
867
+ "Read it first to check for prior design decisions, then "
868
+ "re-run with force=True / --force to overwrite."
869
+ ),
870
+ }
871
+
872
+ created_files = []
873
+
874
+ # Create directories
875
+ design_system_dir.mkdir(parents=True, exist_ok=True)
876
+ pages_dir.mkdir(parents=True, exist_ok=True)
877
+
878
+ # Generate and write MASTER.md
879
+ master_content = format_master_md(design_system)
880
+ with open(master_file, 'w', encoding='utf-8') as f:
881
+ f.write(master_content)
882
+ created_files.append(str(master_file))
883
+
884
+ # If page is specified, create page override file with intelligent content
885
+ if page:
886
+ page_file = pages_dir / f"{safe_slug(page, 'page')}.md"
887
+ page_content = format_page_override_md(design_system, page, page_query)
888
+ with open(page_file, 'w', encoding='utf-8') as f:
889
+ f.write(page_content)
890
+ created_files.append(str(page_file))
891
+
892
+ return {
893
+ "status": "success",
894
+ "design_system_dir": str(design_system_dir),
895
+ "master_file": str(master_file),
896
+ "created_files": created_files
897
+ }
898
+
899
+
900
+ def format_master_md(design_system: dict) -> str:
901
+ """Format design system as MASTER.md with hierarchical override logic."""
902
+ project = design_system.get("project_name", "PROJECT")
903
+ pattern = design_system.get("pattern", {})
904
+ style = design_system.get("style", {})
905
+ colors = design_system.get("colors", {})
906
+ typography = design_system.get("typography", {})
907
+ effects = design_system.get("key_effects", "")
908
+ anti_patterns = design_system.get("anti_patterns", "")
909
+ dials = design_system.get("dials", {})
910
+ motion_snippet = design_system.get("motion_snippet", {})
911
+ spacing_scale = design_system.get("spacing_scale")
912
+
913
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
914
+
915
+ lines = []
916
+
917
+ # Logic header
918
+ lines.append("# Design System Master File")
919
+ lines.append("")
920
+ lines.append("> **LOGIC:** When building a specific page, first check `design-system/pages/[page-name].md`.")
921
+ lines.append("> If that file exists, its rules **override** this Master file.")
922
+ lines.append("> If not, strictly follow the rules below.")
923
+ lines.append("")
924
+ lines.append("---")
925
+ lines.append("")
926
+ lines.append(f"**Project:** {project}")
927
+ lines.append(f"**Generated:** {timestamp}")
928
+ lines.append(f"**Category:** {design_system.get('category', 'General')}")
929
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
930
+ dial_parts = []
931
+ if dials.get("variance") is not None:
932
+ dial_parts.append(f"Variance {dials['variance']}/10 ({dials['variance_label']})")
933
+ if dials.get("motion") is not None:
934
+ dial_parts.append(f"Motion {dials['motion']}/10 ({dials['motion_label']})")
935
+ if dials.get("density") is not None:
936
+ dial_parts.append(f"Density {dials['density']}/10 ({dials['density_label']})")
937
+ lines.append(f"**Design Dials:** {' | '.join(dial_parts)}")
938
+ lines.append("")
939
+ lines.append("---")
940
+ lines.append("")
941
+
942
+ # Global Rules section
943
+ lines.append("## Global Rules")
944
+ lines.append("")
945
+
946
+ # Color Palette
947
+ lines.append("### Color Palette")
948
+ lines.append("")
949
+ lines.append("| Role | Hex | CSS Variable |")
950
+ lines.append("|------|-----|--------------|")
951
+ master_color_entries = [
952
+ ("Primary", "primary", "--color-primary"),
953
+ ("On Primary", "on_primary", "--color-on-primary"),
954
+ ("Secondary", "secondary", "--color-secondary"),
955
+ ("Accent/CTA", "accent", "--color-accent"),
956
+ ("Background", "background", "--color-background"),
957
+ ("Foreground", "foreground", "--color-foreground"),
958
+ ("Muted", "muted", "--color-muted"),
959
+ ("Border", "border", "--color-border"),
960
+ ("Destructive", "destructive", "--color-destructive"),
961
+ ("Ring", "ring", "--color-ring"),
962
+ ]
963
+ for label, key, css_var in master_color_entries:
964
+ hex_val = colors.get(key, "")
965
+ if hex_val:
966
+ lines.append(f"| {label} | `{hex_val}` | `{css_var}` |")
967
+ lines.append("")
968
+ if colors.get("notes"):
969
+ lines.append(f"**Color Notes:** {colors.get('notes', '')}")
970
+ lines.append("")
971
+
972
+ # Typography
973
+ lines.append("### Typography")
974
+ lines.append("")
975
+ lines.append(f"- **Heading Font:** {typography.get('heading', 'Inter')}")
976
+ lines.append(f"- **Body Font:** {typography.get('body', 'Inter')}")
977
+ if typography.get("mood"):
978
+ lines.append(f"- **Mood:** {typography.get('mood', '')}")
979
+ if typography.get("google_fonts_url"):
980
+ lines.append(f"- **Google Fonts:** [{typography.get('heading', '')} + {typography.get('body', '')}]({typography.get('google_fonts_url', '')})")
981
+ lines.append("")
982
+ if typography.get("css_import"):
983
+ lines.append("**CSS Import:**")
984
+ lines.append("```css")
985
+ lines.append(typography.get("css_import", ""))
986
+ lines.append("```")
987
+ lines.append("")
988
+
989
+ # Spacing Variables (overridden by the VISUAL_DENSITY dial when set)
990
+ default_spacing = DIAL_TIERS["density"][1][2]["spacing"] # mid-tier = the historical defaults
991
+ scale = spacing_scale or default_spacing
992
+ spacing_usage = {
993
+ "xs": "Tight gaps", "sm": "Icon gaps, inline spacing", "md": "Standard padding",
994
+ "lg": "Section padding", "xl": "Large gaps", "2xl": "Section margins", "3xl": "Hero padding",
995
+ }
996
+ lines.append("### Spacing Variables")
997
+ lines.append("")
998
+ if spacing_scale:
999
+ lines.append(f"*Density: {dials.get('density')}/10 — {dials.get('density_label')}*")
1000
+ lines.append("")
1001
+ lines.append("| Token | Value | Usage |")
1002
+ lines.append("|-------|-------|-------|")
1003
+ for token in ("xs", "sm", "md", "lg", "xl", "2xl", "3xl"):
1004
+ px_value = scale[token]
1005
+ rem_value = f"{int(px_value.rstrip('px')) / 16:g}rem"
1006
+ lines.append(f"| `--space-{token}` | `{px_value}` / `{rem_value}` | {spacing_usage[token]} |")
1007
+ lines.append("")
1008
+
1009
+ # Shadow Depths
1010
+ lines.append("### Shadow Depths")
1011
+ lines.append("")
1012
+ lines.append("| Level | Value | Usage |")
1013
+ lines.append("|-------|-------|-------|")
1014
+ lines.append("| `--shadow-sm` | `0 1px 2px rgba(0,0,0,0.05)` | Subtle lift |")
1015
+ lines.append("| `--shadow-md` | `0 4px 6px rgba(0,0,0,0.1)` | Cards, buttons |")
1016
+ lines.append("| `--shadow-lg` | `0 10px 15px rgba(0,0,0,0.1)` | Modals, dropdowns |")
1017
+ lines.append("| `--shadow-xl` | `0 20px 25px rgba(0,0,0,0.15)` | Hero images, featured cards |")
1018
+ lines.append("")
1019
+
1020
+ # Component Specs section
1021
+ lines.append("---")
1022
+ lines.append("")
1023
+ lines.append("## Component Specs")
1024
+ lines.append("")
1025
+
1026
+ # Buttons
1027
+ lines.append("### Buttons")
1028
+ lines.append("")
1029
+ lines.append("```css")
1030
+ lines.append("/* Primary Button */")
1031
+ lines.append(".btn-primary {")
1032
+ lines.append(f" background: {colors.get('cta', '#F97316')};")
1033
+ lines.append(" color: white;")
1034
+ lines.append(" padding: 12px 24px;")
1035
+ lines.append(" border-radius: 8px;")
1036
+ lines.append(" font-weight: 600;")
1037
+ lines.append(" transition: all 200ms ease;")
1038
+ lines.append(" cursor: pointer;")
1039
+ lines.append("}")
1040
+ lines.append("")
1041
+ lines.append(".btn-primary:hover {")
1042
+ lines.append(" opacity: 0.9;")
1043
+ lines.append(" transform: translateY(-1px);")
1044
+ lines.append("}")
1045
+ lines.append("")
1046
+ lines.append("/* Secondary Button */")
1047
+ lines.append(".btn-secondary {")
1048
+ lines.append(f" background: transparent;")
1049
+ lines.append(f" color: {colors.get('primary', '#2563EB')};")
1050
+ lines.append(f" border: 2px solid {colors.get('primary', '#2563EB')};")
1051
+ lines.append(" padding: 12px 24px;")
1052
+ lines.append(" border-radius: 8px;")
1053
+ lines.append(" font-weight: 600;")
1054
+ lines.append(" transition: all 200ms ease;")
1055
+ lines.append(" cursor: pointer;")
1056
+ lines.append("}")
1057
+ lines.append("```")
1058
+ lines.append("")
1059
+
1060
+ # Cards
1061
+ lines.append("### Cards")
1062
+ lines.append("")
1063
+ lines.append("```css")
1064
+ lines.append(".card {")
1065
+ lines.append(f" background: {colors.get('background', '#FFFFFF')};")
1066
+ lines.append(" border-radius: 12px;")
1067
+ lines.append(" padding: 24px;")
1068
+ lines.append(" box-shadow: var(--shadow-md);")
1069
+ lines.append(" transition: all 200ms ease;")
1070
+ lines.append(" cursor: pointer;")
1071
+ lines.append("}")
1072
+ lines.append("")
1073
+ lines.append(".card:hover {")
1074
+ lines.append(" box-shadow: var(--shadow-lg);")
1075
+ lines.append(" transform: translateY(-2px);")
1076
+ lines.append("}")
1077
+ lines.append("```")
1078
+ lines.append("")
1079
+
1080
+ # Inputs
1081
+ lines.append("### Inputs")
1082
+ lines.append("")
1083
+ lines.append("```css")
1084
+ lines.append(".input {")
1085
+ lines.append(" padding: 12px 16px;")
1086
+ lines.append(" border: 1px solid #E2E8F0;")
1087
+ lines.append(" border-radius: 8px;")
1088
+ lines.append(" font-size: 16px;")
1089
+ lines.append(" transition: border-color 200ms ease;")
1090
+ lines.append("}")
1091
+ lines.append("")
1092
+ lines.append(".input:focus {")
1093
+ lines.append(f" border-color: {colors.get('primary', '#2563EB')};")
1094
+ lines.append(" outline: none;")
1095
+ lines.append(f" box-shadow: 0 0 0 3px {colors.get('primary', '#2563EB')}20;")
1096
+ lines.append("}")
1097
+ lines.append("```")
1098
+ lines.append("")
1099
+
1100
+ # Modals
1101
+ lines.append("### Modals")
1102
+ lines.append("")
1103
+ lines.append("```css")
1104
+ lines.append(".modal-overlay {")
1105
+ lines.append(" background: rgba(0, 0, 0, 0.5);")
1106
+ lines.append(" backdrop-filter: blur(4px);")
1107
+ lines.append("}")
1108
+ lines.append("")
1109
+ lines.append(".modal {")
1110
+ lines.append(" background: white;")
1111
+ lines.append(" border-radius: 16px;")
1112
+ lines.append(" padding: 32px;")
1113
+ lines.append(" box-shadow: var(--shadow-xl);")
1114
+ lines.append(" max-width: 500px;")
1115
+ lines.append(" width: 90%;")
1116
+ lines.append("}")
1117
+ lines.append("```")
1118
+ lines.append("")
1119
+
1120
+ # Style section
1121
+ lines.append("---")
1122
+ lines.append("")
1123
+ lines.append("## Style Guidelines")
1124
+ lines.append("")
1125
+ lines.append(f"**Style:** {style.get('name', 'Minimalism')}")
1126
+ lines.append("")
1127
+ if style.get("keywords"):
1128
+ lines.append(f"**Keywords:** {style.get('keywords', '')}")
1129
+ lines.append("")
1130
+ if style.get("best_for"):
1131
+ lines.append(f"**Best For:** {style.get('best_for', '')}")
1132
+ lines.append("")
1133
+ if effects:
1134
+ lines.append(f"**Key Effects:** {effects}")
1135
+ lines.append("")
1136
+
1137
+ # Layout Pattern
1138
+ lines.append("### Page Pattern")
1139
+ lines.append("")
1140
+ lines.append(f"**Pattern Name:** {pattern.get('name', '')}")
1141
+ lines.append("")
1142
+ if pattern.get('conversion'):
1143
+ lines.append(f"- **Conversion Strategy:** {pattern.get('conversion', '')}")
1144
+ if pattern.get('cta_placement'):
1145
+ lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
1146
+ lines.append(f"- **Section Order:** {pattern.get('sections', '')}")
1147
+ lines.append("")
1148
+
1149
+ # Motion section (GSAP skeleton, only if --motion dial was set)
1150
+ if motion_snippet:
1151
+ lines.append("---")
1152
+ lines.append("")
1153
+ lines.append("## Motion")
1154
+ lines.append("")
1155
+ lines.append(f"**{motion_snippet.get('Category', '')}** ({motion_snippet.get('Intensity Tier', '')}) — Trigger: {motion_snippet.get('Trigger', '')} | Duration: {motion_snippet.get('Duration', '')} | Easing: `{motion_snippet.get('Easing', '')}`")
1156
+ lines.append("")
1157
+ lines.append("```js")
1158
+ lines.append(motion_snippet.get("GSAP Snippet", ""))
1159
+ lines.append("```")
1160
+ lines.append("")
1161
+ if motion_snippet.get("Framework Notes"):
1162
+ lines.append(f"**Framework notes:** {motion_snippet.get('Framework Notes', '')}")
1163
+ lines.append("")
1164
+ motion_do = motion_snippet.get("Do", "")
1165
+ motion_dont = motion_snippet.get("Don't", "")
1166
+ if motion_do:
1167
+ lines.append(f"- ✅ {motion_do}")
1168
+ if motion_dont:
1169
+ lines.append(f"- ❌ {motion_dont}")
1170
+ if motion_snippet.get("Performance Notes"):
1171
+ lines.append(f"- ⚡ {motion_snippet.get('Performance Notes', '')}")
1172
+ lines.append("")
1173
+
1174
+ # Anti-Patterns section
1175
+ lines.append("---")
1176
+ lines.append("")
1177
+ lines.append("## Anti-Patterns (Do NOT Use)")
1178
+ lines.append("")
1179
+ if anti_patterns:
1180
+ anti_list = [a.strip() for a in anti_patterns.split("+")]
1181
+ for anti in anti_list:
1182
+ if anti:
1183
+ lines.append(f"- ❌ {anti}")
1184
+ lines.append("")
1185
+ lines.append("### Additional Forbidden Patterns")
1186
+ lines.append("")
1187
+ lines.append("- ❌ **Emojis as icons** — Use SVG icons (Heroicons, Lucide, Simple Icons)")
1188
+ lines.append("- ❌ **Missing cursor:pointer** — All clickable elements must have cursor:pointer")
1189
+ lines.append("- ❌ **Layout-shifting hovers** — Avoid scale transforms that shift layout")
1190
+ lines.append("- ❌ **Low contrast text** — Maintain 4.5:1 minimum contrast ratio")
1191
+ lines.append("- ❌ **Instant state changes** — Always use transitions (150-300ms)")
1192
+ lines.append("- ❌ **Invisible focus states** — Focus states must be visible for a11y")
1193
+ lines.append("")
1194
+
1195
+ # Pre-Delivery Checklist
1196
+ lines.append("---")
1197
+ lines.append("")
1198
+ lines.append("## Pre-Delivery Checklist")
1199
+ lines.append("")
1200
+ lines.append("Before delivering any UI code, verify:")
1201
+ lines.append("")
1202
+ lines.append("- [ ] No emojis used as icons (use SVG instead)")
1203
+ lines.append("- [ ] All icons from consistent icon set (Heroicons/Lucide)")
1204
+ lines.append("- [ ] `cursor-pointer` on all clickable elements")
1205
+ lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
1206
+ lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
1207
+ lines.append("- [ ] Focus states visible for keyboard navigation")
1208
+ lines.append("- [ ] `prefers-reduced-motion` respected")
1209
+ lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
1210
+ lines.append("- [ ] No content hidden behind fixed navbars")
1211
+ lines.append("- [ ] No horizontal scroll on mobile")
1212
+ lines.append("")
1213
+
1214
+ return "\n".join(lines)
1215
+
1216
+
1217
+ def format_page_override_md(design_system: dict, page_name: str, page_query: str = None) -> str:
1218
+ """Format a page-specific override file with intelligent AI-generated content."""
1219
+ project = design_system.get("project_name", "PROJECT")
1220
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1221
+ page_title = page_name.replace("-", " ").replace("_", " ").title()
1222
+
1223
+ # Detect page type and generate intelligent overrides
1224
+ page_overrides = _generate_intelligent_overrides(page_name, page_query, design_system)
1225
+
1226
+ lines = []
1227
+
1228
+ lines.append(f"# {page_title} Page Overrides")
1229
+ lines.append("")
1230
+ lines.append(f"> **PROJECT:** {project}")
1231
+ lines.append(f"> **Generated:** {timestamp}")
1232
+ lines.append(f"> **Page Type:** {page_overrides.get('page_type', 'General')}")
1233
+ lines.append("")
1234
+ lines.append("> ⚠️ **IMPORTANT:** Rules in this file **override** the Master file (`design-system/MASTER.md`).")
1235
+ lines.append("> Only deviations from the Master are documented here. For all other rules, refer to the Master.")
1236
+ lines.append("")
1237
+ lines.append("---")
1238
+ lines.append("")
1239
+
1240
+ # Page-specific rules with actual content
1241
+ lines.append("## Page-Specific Rules")
1242
+ lines.append("")
1243
+
1244
+ # Layout Overrides
1245
+ lines.append("### Layout Overrides")
1246
+ lines.append("")
1247
+ layout = page_overrides.get("layout", {})
1248
+ if layout:
1249
+ for key, value in layout.items():
1250
+ lines.append(f"- **{key}:** {value}")
1251
+ else:
1252
+ lines.append("- No overrides — use Master layout")
1253
+ lines.append("")
1254
+
1255
+ # Spacing Overrides
1256
+ lines.append("### Spacing Overrides")
1257
+ lines.append("")
1258
+ spacing = page_overrides.get("spacing", {})
1259
+ if spacing:
1260
+ for key, value in spacing.items():
1261
+ lines.append(f"- **{key}:** {value}")
1262
+ else:
1263
+ lines.append("- No overrides — use Master spacing")
1264
+ lines.append("")
1265
+
1266
+ # Typography Overrides
1267
+ lines.append("### Typography Overrides")
1268
+ lines.append("")
1269
+ typography = page_overrides.get("typography", {})
1270
+ if typography:
1271
+ for key, value in typography.items():
1272
+ lines.append(f"- **{key}:** {value}")
1273
+ else:
1274
+ lines.append("- No overrides — use Master typography")
1275
+ lines.append("")
1276
+
1277
+ # Color Overrides
1278
+ lines.append("### Color Overrides")
1279
+ lines.append("")
1280
+ colors = page_overrides.get("colors", {})
1281
+ if colors:
1282
+ for key, value in colors.items():
1283
+ lines.append(f"- **{key}:** {value}")
1284
+ else:
1285
+ lines.append("- No overrides — use Master colors")
1286
+ lines.append("")
1287
+
1288
+ # Component Overrides
1289
+ lines.append("### Component Overrides")
1290
+ lines.append("")
1291
+ components = page_overrides.get("components", [])
1292
+ if components:
1293
+ for comp in components:
1294
+ lines.append(f"- {comp}")
1295
+ else:
1296
+ lines.append("- No overrides — use Master component specs")
1297
+ lines.append("")
1298
+
1299
+ # Page-Specific Components
1300
+ lines.append("---")
1301
+ lines.append("")
1302
+ lines.append("## Page-Specific Components")
1303
+ lines.append("")
1304
+ unique_components = page_overrides.get("unique_components", [])
1305
+ if unique_components:
1306
+ for comp in unique_components:
1307
+ lines.append(f"- {comp}")
1308
+ else:
1309
+ lines.append("- No unique components for this page")
1310
+ lines.append("")
1311
+
1312
+ # Recommendations
1313
+ lines.append("---")
1314
+ lines.append("")
1315
+ lines.append("## Recommendations")
1316
+ lines.append("")
1317
+ recommendations = page_overrides.get("recommendations", [])
1318
+ if recommendations:
1319
+ for rec in recommendations:
1320
+ lines.append(f"- {rec}")
1321
+ lines.append("")
1322
+
1323
+ return "\n".join(lines)
1324
+
1325
+
1326
+ def _generate_intelligent_overrides(page_name: str, page_query: str, design_system: dict) -> dict:
1327
+ """
1328
+ Generate intelligent overrides based on page type using layered search.
1329
+
1330
+ Uses the existing search infrastructure to find relevant style, UX, and layout
1331
+ data instead of hardcoded page types.
1332
+ """
1333
+ from core import search
1334
+
1335
+ page_lower = page_name.lower()
1336
+ query_lower = (page_query or "").lower()
1337
+ combined_context = f"{page_lower} {query_lower}"
1338
+
1339
+ # Search across multiple domains for page-specific guidance
1340
+ style_search = search(combined_context, "style", max_results=1)
1341
+ ux_search = search(combined_context, "ux", max_results=3)
1342
+ landing_search = search(combined_context, "landing", max_results=1)
1343
+
1344
+ # Extract results from search response
1345
+ style_results = style_search.get("results", [])
1346
+ ux_results = ux_search.get("results", [])
1347
+ landing_results = landing_search.get("results", [])
1348
+
1349
+ # Detect page type from search results or context
1350
+ page_type = _detect_page_type(combined_context, style_results)
1351
+
1352
+ # Build overrides from search results
1353
+ layout = {}
1354
+ spacing = {}
1355
+ typography = {}
1356
+ colors = {}
1357
+ components = []
1358
+ unique_components = []
1359
+ recommendations = []
1360
+
1361
+ # Extract style-based overrides
1362
+ if style_results:
1363
+ style = style_results[0]
1364
+ style_name = style.get("Style Category", "")
1365
+ keywords = style.get("Keywords", "")
1366
+ best_for = style.get("Best For", "")
1367
+ effects = style.get("Effects & Animation", "")
1368
+
1369
+ # Infer layout from style keywords
1370
+ if any(kw in keywords.lower() for kw in ["data", "dense", "dashboard", "grid"]):
1371
+ layout["Max Width"] = "1400px or full-width"
1372
+ layout["Grid"] = "12-column grid for data flexibility"
1373
+ spacing["Content Density"] = "High — optimize for information display"
1374
+ elif any(kw in keywords.lower() for kw in ["minimal", "simple", "clean", "single"]):
1375
+ layout["Max Width"] = "800px (narrow, focused)"
1376
+ layout["Layout"] = "Single column, centered"
1377
+ spacing["Content Density"] = "Low — focus on clarity"
1378
+ else:
1379
+ layout["Max Width"] = "1200px (standard)"
1380
+ layout["Layout"] = "Full-width sections, centered content"
1381
+
1382
+ if effects:
1383
+ recommendations.append(f"Effects: {effects}")
1384
+
1385
+ # Extract UX guidelines as recommendations
1386
+ for ux in ux_results:
1387
+ category = ux.get("Category", "")
1388
+ do_text = ux.get("Do", "")
1389
+ dont_text = ux.get("Don't", "")
1390
+ if do_text:
1391
+ recommendations.append(f"{category}: {do_text}")
1392
+ if dont_text:
1393
+ components.append(f"Avoid: {dont_text}")
1394
+
1395
+ # Extract landing pattern info for section structure
1396
+ if landing_results:
1397
+ landing = landing_results[0]
1398
+ sections = landing.get("Section Order", "")
1399
+ cta_placement = landing.get("Primary CTA Placement", "")
1400
+ color_strategy = landing.get("Color Strategy", "")
1401
+
1402
+ if sections:
1403
+ layout["Sections"] = sections
1404
+ if cta_placement:
1405
+ recommendations.append(f"CTA Placement: {cta_placement}")
1406
+ if color_strategy:
1407
+ colors["Strategy"] = color_strategy
1408
+
1409
+ # Add page-type specific defaults if no search results
1410
+ if not layout:
1411
+ layout["Max Width"] = "1200px"
1412
+ layout["Layout"] = "Responsive grid"
1413
+
1414
+ if not recommendations:
1415
+ recommendations = [
1416
+ "Refer to MASTER.md for all design rules",
1417
+ "Add specific overrides as needed for this page"
1418
+ ]
1419
+
1420
+ return {
1421
+ "page_type": page_type,
1422
+ "layout": layout,
1423
+ "spacing": spacing,
1424
+ "typography": typography,
1425
+ "colors": colors,
1426
+ "components": components,
1427
+ "unique_components": unique_components,
1428
+ "recommendations": recommendations
1429
+ }
1430
+
1431
+
1432
+ def _detect_page_type(context: str, style_results: list) -> str:
1433
+ """Detect page type from context and search results."""
1434
+ context_lower = context.lower()
1435
+
1436
+ # Check for common page type patterns
1437
+ page_patterns = [
1438
+ (["dashboard", "admin", "analytics", "data", "metrics", "stats", "monitor", "overview"], "Dashboard / Data View"),
1439
+ (["checkout", "payment", "cart", "purchase", "order", "billing"], "Checkout / Payment"),
1440
+ (["settings", "profile", "account", "preferences", "config"], "Settings / Profile"),
1441
+ (["landing", "marketing", "homepage", "hero", "home", "promo"], "Landing / Marketing"),
1442
+ (["login", "signin", "signup", "register", "auth", "password"], "Authentication"),
1443
+ (["pricing", "plans", "subscription", "tiers", "packages"], "Pricing / Plans"),
1444
+ (["blog", "article", "post", "news", "content", "story"], "Blog / Article"),
1445
+ (["product", "item", "detail", "pdp", "shop", "store"], "Product Detail"),
1446
+ (["search", "results", "browse", "filter", "catalog", "list"], "Search Results"),
1447
+ (["empty", "404", "error", "not found", "zero"], "Empty State"),
1448
+ ]
1449
+
1450
+ for keywords, page_type in page_patterns:
1451
+ if any(kw in context_lower for kw in keywords):
1452
+ return page_type
1453
+
1454
+ # Fallback: try to infer from style results
1455
+ if style_results:
1456
+ style_name = style_results[0].get("Style Category", "").lower()
1457
+ best_for = style_results[0].get("Best For", "").lower()
1458
+
1459
+ if "dashboard" in best_for or "data" in best_for:
1460
+ return "Dashboard / Data View"
1461
+ elif "landing" in best_for or "marketing" in best_for:
1462
+ return "Landing / Marketing"
1463
+
1464
+ return "General"
1465
+
1466
+
1467
+ # ============ CLI SUPPORT ============
1468
+ if __name__ == "__main__":
1469
+ import argparse
1470
+
1471
+ parser = argparse.ArgumentParser(description="Generate Design System")
1472
+ parser.add_argument("query", help="Search query (e.g., 'SaaS dashboard')")
1473
+ parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name")
1474
+ parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format")
1475
+
1476
+ args = parser.parse_args()
1477
+
1478
+ result = generate_design_system(args.query, args.project_name, args.format)
1479
+ print(result["text"])