stella-coder 3.9.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.mcp.json +11 -0
  2. package/.opencode/skills/banner-design/SKILL.md +196 -0
  3. package/.opencode/skills/banner-design/references/banner-sizes-and-styles.md +118 -0
  4. package/.opencode/skills/brand/SKILL.md +97 -0
  5. package/.opencode/skills/brand/references/approval-checklist.md +169 -0
  6. package/.opencode/skills/brand/references/asset-organization.md +157 -0
  7. package/.opencode/skills/brand/references/brand-guideline-template.md +140 -0
  8. package/.opencode/skills/brand/references/color-palette-management.md +186 -0
  9. package/.opencode/skills/brand/references/consistency-checklist.md +94 -0
  10. package/.opencode/skills/brand/references/logo-usage-rules.md +185 -0
  11. package/.opencode/skills/brand/references/messaging-framework.md +85 -0
  12. package/.opencode/skills/brand/references/typography-specifications.md +214 -0
  13. package/.opencode/skills/brand/references/update.md +118 -0
  14. package/.opencode/skills/brand/references/visual-identity.md +96 -0
  15. package/.opencode/skills/brand/references/voice-framework.md +88 -0
  16. package/.opencode/skills/brand/scripts/extract-colors.cjs +341 -0
  17. package/.opencode/skills/brand/scripts/inject-brand-context.cjs +349 -0
  18. package/.opencode/skills/brand/scripts/sync-brand-to-tokens.cjs +248 -0
  19. package/.opencode/skills/brand/scripts/tests/test_sync_brand_to_tokens.py +52 -0
  20. package/.opencode/skills/brand/scripts/validate-asset.cjs +387 -0
  21. package/.opencode/skills/brand/templates/brand-guidelines-starter.md +275 -0
  22. package/.opencode/skills/design/SKILL.md +313 -0
  23. package/.opencode/skills/design/data/cip/deliverables.csv +51 -0
  24. package/.opencode/skills/design/data/cip/industries.csv +21 -0
  25. package/.opencode/skills/design/data/cip/mockup-contexts.csv +21 -0
  26. package/.opencode/skills/design/data/cip/styles.csv +21 -0
  27. package/.opencode/skills/design/data/icon/styles.csv +16 -0
  28. package/.opencode/skills/design/data/logo/colors.csv +56 -0
  29. package/.opencode/skills/design/data/logo/industries.csv +56 -0
  30. package/.opencode/skills/design/data/logo/styles.csv +56 -0
  31. package/.opencode/skills/design/references/banner-sizes-and-styles.md +118 -0
  32. package/.opencode/skills/design/references/cip-deliverable-guide.md +95 -0
  33. package/.opencode/skills/design/references/cip-design.md +121 -0
  34. package/.opencode/skills/design/references/cip-prompt-engineering.md +84 -0
  35. package/.opencode/skills/design/references/cip-style-guide.md +68 -0
  36. package/.opencode/skills/design/references/design-routing.md +207 -0
  37. package/.opencode/skills/design/references/icon-design.md +122 -0
  38. package/.opencode/skills/design/references/logo-color-psychology.md +101 -0
  39. package/.opencode/skills/design/references/logo-design.md +92 -0
  40. package/.opencode/skills/design/references/logo-prompt-engineering.md +158 -0
  41. package/.opencode/skills/design/references/logo-style-guide.md +109 -0
  42. package/.opencode/skills/design/references/slides-copywriting-formulas.md +84 -0
  43. package/.opencode/skills/design/references/slides-create.md +4 -0
  44. package/.opencode/skills/design/references/slides-html-template.md +295 -0
  45. package/.opencode/skills/design/references/slides-layout-patterns.md +137 -0
  46. package/.opencode/skills/design/references/slides-strategies.md +94 -0
  47. package/.opencode/skills/design/references/slides.md +42 -0
  48. package/.opencode/skills/design/references/social-photos-design.md +329 -0
  49. package/.opencode/skills/design/scripts/cip/core.py +215 -0
  50. package/.opencode/skills/design/scripts/cip/generate.py +484 -0
  51. package/.opencode/skills/design/scripts/cip/render-html.py +424 -0
  52. package/.opencode/skills/design/scripts/cip/search.py +127 -0
  53. package/.opencode/skills/design/scripts/icon/generate.py +487 -0
  54. package/.opencode/skills/design/scripts/logo/core.py +175 -0
  55. package/.opencode/skills/design/scripts/logo/generate.py +362 -0
  56. package/.opencode/skills/design/scripts/logo/search.py +114 -0
  57. package/.opencode/skills/design-system/SKILL.md +244 -0
  58. package/.opencode/skills/design-system/data/slide-backgrounds.csv +11 -0
  59. package/.opencode/skills/design-system/data/slide-charts.csv +26 -0
  60. package/.opencode/skills/design-system/data/slide-color-logic.csv +14 -0
  61. package/.opencode/skills/design-system/data/slide-copy.csv +26 -0
  62. package/.opencode/skills/design-system/data/slide-layout-logic.csv +16 -0
  63. package/.opencode/skills/design-system/data/slide-layouts.csv +26 -0
  64. package/.opencode/skills/design-system/data/slide-strategies.csv +16 -0
  65. package/.opencode/skills/design-system/data/slide-typography.csv +15 -0
  66. package/.opencode/skills/design-system/references/component-specs.md +236 -0
  67. package/.opencode/skills/design-system/references/component-tokens.md +214 -0
  68. package/.opencode/skills/design-system/references/primitive-tokens.md +203 -0
  69. package/.opencode/skills/design-system/references/semantic-tokens.md +215 -0
  70. package/.opencode/skills/design-system/references/states-and-variants.md +241 -0
  71. package/.opencode/skills/design-system/references/tailwind-integration.md +251 -0
  72. package/.opencode/skills/design-system/references/token-architecture.md +224 -0
  73. package/.opencode/skills/design-system/scripts/embed-tokens.cjs +99 -0
  74. package/.opencode/skills/design-system/scripts/fetch-background.py +317 -0
  75. package/.opencode/skills/design-system/scripts/generate-slide.py +770 -0
  76. package/.opencode/skills/design-system/scripts/generate-tokens.cjs +205 -0
  77. package/.opencode/skills/design-system/scripts/html-token-validator.py +327 -0
  78. package/.opencode/skills/design-system/scripts/search-slides.py +218 -0
  79. package/.opencode/skills/design-system/scripts/slide-token-validator.py +35 -0
  80. package/.opencode/skills/design-system/scripts/slide_search_core.py +453 -0
  81. package/.opencode/skills/design-system/scripts/tests/test_validate_tokens.py +48 -0
  82. package/.opencode/skills/design-system/scripts/validate-tokens.cjs +246 -0
  83. package/.opencode/skills/design-system/templates/design-tokens-starter.json +143 -0
  84. package/.opencode/skills/slides/SKILL.md +40 -0
  85. package/.opencode/skills/slides/references/copywriting-formulas.md +84 -0
  86. package/.opencode/skills/slides/references/create.md +4 -0
  87. package/.opencode/skills/slides/references/html-template.md +295 -0
  88. package/.opencode/skills/slides/references/layout-patterns.md +137 -0
  89. package/.opencode/skills/slides/references/slide-strategies.md +94 -0
  90. package/.opencode/skills/ui-styling/LICENSE.txt +202 -0
  91. package/.opencode/skills/ui-styling/SKILL.md +324 -0
  92. package/.opencode/skills/ui-styling/references/canvas-design-system.md +320 -0
  93. package/.opencode/skills/ui-styling/references/shadcn-accessibility.md +471 -0
  94. package/.opencode/skills/ui-styling/references/shadcn-components.md +424 -0
  95. package/.opencode/skills/ui-styling/references/shadcn-theming.md +373 -0
  96. package/.opencode/skills/ui-styling/references/tailwind-customization.md +483 -0
  97. package/.opencode/skills/ui-styling/references/tailwind-responsive.md +382 -0
  98. package/.opencode/skills/ui-styling/references/tailwind-utilities.md +455 -0
  99. package/.opencode/skills/ui-styling/scripts/requirements.txt +17 -0
  100. package/.opencode/skills/ui-styling/scripts/shadcn_add.py +308 -0
  101. package/.opencode/skills/ui-styling/scripts/tailwind_config_gen.py +473 -0
  102. package/.opencode/skills/ui-styling/scripts/tests/coverage-ui.json +1 -0
  103. package/.opencode/skills/ui-styling/scripts/tests/requirements.txt +3 -0
  104. package/.opencode/skills/ui-styling/scripts/tests/test_shadcn_add.py +266 -0
  105. package/.opencode/skills/ui-styling/scripts/tests/test_tailwind_config_gen.py +394 -0
  106. package/.opencode/skills/ui-ux-pro-max/SKILL.md +396 -0
  107. package/.opencode/skills/ui-ux-pro-max/data/_sync_all.py +414 -0
  108. package/.opencode/skills/ui-ux-pro-max/data/app-interface.csv +31 -0
  109. package/.opencode/skills/ui-ux-pro-max/data/charts.csv +26 -0
  110. package/.opencode/skills/ui-ux-pro-max/data/colors.csv +193 -0
  111. package/.opencode/skills/ui-ux-pro-max/data/design.csv +1776 -0
  112. package/.opencode/skills/ui-ux-pro-max/data/draft.csv +1779 -0
  113. package/.opencode/skills/ui-ux-pro-max/data/google-fonts.csv +1924 -0
  114. package/.opencode/skills/ui-ux-pro-max/data/icons.csv +106 -0
  115. package/.opencode/skills/ui-ux-pro-max/data/landing.csv +35 -0
  116. package/.opencode/skills/ui-ux-pro-max/data/motion.csv +17 -0
  117. package/.opencode/skills/ui-ux-pro-max/data/products.csv +193 -0
  118. package/.opencode/skills/ui-ux-pro-max/data/react-performance.csv +45 -0
  119. package/.opencode/skills/ui-ux-pro-max/data/stacks/angular.csv +51 -0
  120. package/.opencode/skills/ui-ux-pro-max/data/stacks/astro.csv +54 -0
  121. package/.opencode/skills/ui-ux-pro-max/data/stacks/avalonia.csv +57 -0
  122. package/.opencode/skills/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  123. package/.opencode/skills/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  124. package/.opencode/skills/ui-ux-pro-max/data/stacks/javafx.csv +76 -0
  125. package/.opencode/skills/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
  126. package/.opencode/skills/ui-ux-pro-max/data/stacks/laravel.csv +51 -0
  127. package/.opencode/skills/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  128. package/.opencode/skills/ui-ux-pro-max/data/stacks/nuxt-ui.csv +71 -0
  129. package/.opencode/skills/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  130. package/.opencode/skills/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  131. package/.opencode/skills/ui-ux-pro-max/data/stacks/react.csv +54 -0
  132. package/.opencode/skills/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  133. package/.opencode/skills/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  134. package/.opencode/skills/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  135. package/.opencode/skills/ui-ux-pro-max/data/stacks/threejs.csv +54 -0
  136. package/.opencode/skills/ui-ux-pro-max/data/stacks/uno.csv +60 -0
  137. package/.opencode/skills/ui-ux-pro-max/data/stacks/uwp.csv +56 -0
  138. package/.opencode/skills/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  139. package/.opencode/skills/ui-ux-pro-max/data/stacks/winui.csv +60 -0
  140. package/.opencode/skills/ui-ux-pro-max/data/stacks/wpf.csv +57 -0
  141. package/.opencode/skills/ui-ux-pro-max/data/styles.csv +85 -0
  142. package/.opencode/skills/ui-ux-pro-max/data/typography.csv +75 -0
  143. package/.opencode/skills/ui-ux-pro-max/data/ui-reasoning.csv +162 -0
  144. package/.opencode/skills/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  145. package/.opencode/skills/ui-ux-pro-max/scripts/__pycache__/core.cpython-312.pyc +0 -0
  146. package/.opencode/skills/ui-ux-pro-max/scripts/__pycache__/design_system.cpython-312.pyc +0 -0
  147. package/.opencode/skills/ui-ux-pro-max/scripts/core.py +274 -0
  148. package/.opencode/skills/ui-ux-pro-max/scripts/design_system.py +1329 -0
  149. package/.opencode/skills/ui-ux-pro-max/scripts/search.py +127 -0
  150. package/README.md +5 -0
  151. package/STELLA.md +1 -1
  152. package/dist/antimalware/database.mjs +871 -0
  153. package/dist/antimalware/index.mjs +8 -0
  154. package/dist/antimalware/scanner.mjs +591 -0
  155. package/dist/antimalware/ui.mjs +570 -0
  156. package/dist/banner.mjs +46 -0
  157. package/dist/index.mjs +3073 -0
  158. package/dist/markdown.mjs +100 -0
  159. package/dist/sea-config.json +4 -0
  160. package/dist/security.mjs +237 -0
  161. package/dist/theme.mjs +89 -0
  162. package/dist/tools.mjs +3145 -0
  163. package/install-stella.bat +44 -0
  164. package/package.json +12 -3
  165. package/presentation-advanced-features-demo/README.md +27 -0
  166. package/presentation-advanced-features-demo/index.html +371 -0
  167. package/presentation-advanced-features-demo/print.html +81 -0
  168. package/presentation-advanced-features-demo/slide-01.html +98 -0
  169. package/presentation-advanced-features-demo/slide-02.html +101 -0
  170. package/presentation-advanced-features-demo/slide-03.html +100 -0
  171. package/presentation-advanced-features-demo/slide-04.html +100 -0
  172. package/presentation-advanced-features-demo/slide-05.html +100 -0
  173. package/presentation-advanced-features-demo/slide-06.html +64 -0
  174. package/presentation-advanced-features-demo/slide-07.html +101 -0
  175. package/presentation-advanced-features-demo/slide-08.html +91 -0
  176. package/presentation-stella-coder---ai-coding-agent/README.md +27 -0
  177. package/presentation-stella-coder---ai-coding-agent/index.html +168 -0
  178. package/presentation-stella-coder---ai-coding-agent/slide-01.html +98 -0
  179. package/presentation-stella-coder---ai-coding-agent/slide-02.html +101 -0
  180. package/presentation-stella-coder---ai-coding-agent/slide-03.html +100 -0
  181. package/presentation-stella-coder---ai-coding-agent/slide-04.html +100 -0
  182. package/presentation-stella-coder---ai-coding-agent/slide-05.html +100 -0
  183. package/presentation-stella-coder---ai-coding-agent/slide-06.html +100 -0
  184. package/presentation-stella-coder---ai-coding-agent/slide-07.html +100 -0
  185. package/presentation-stella-coder---ai-coding-agent/slide-08.html +64 -0
  186. package/presentation-stella-coder---ai-coding-agent/slide-09.html +101 -0
  187. package/presentation-stella-coder---ai-coding-agent/slide-10.html +91 -0
  188. package/presentation-stella-coder-demo/README.md +27 -0
  189. package/presentation-stella-coder-demo/index.html +371 -0
  190. package/presentation-stella-coder-demo/slide-01.html +98 -0
  191. package/presentation-stella-coder-demo/slide-02.html +101 -0
  192. package/presentation-stella-coder-demo/slide-03.html +100 -0
  193. package/presentation-stella-coder-demo/slide-04.html +100 -0
  194. package/presentation-stella-coder-demo/slide-05.html +100 -0
  195. package/presentation-stella-coder-demo/slide-06.html +64 -0
  196. package/presentation-stella-coder-demo/slide-07.html +101 -0
  197. package/presentation-stella-coder-demo/slide-08.html +91 -0
  198. package/presentation-stella-coder-features/README.md +27 -0
  199. package/presentation-stella-coder-features/index.html +364 -0
  200. package/presentation-stella-coder-features/print.html +77 -0
  201. package/presentation-stella-coder-features/slide-01.html +98 -0
  202. package/presentation-stella-coder-features/slide-02.html +101 -0
  203. package/presentation-stella-coder-features/slide-03.html +100 -0
  204. package/presentation-stella-coder-features/slide-04.html +100 -0
  205. package/presentation-stella-coder-features/slide-05.html +64 -0
  206. package/presentation-stella-coder-features/slide-06.html +101 -0
  207. package/presentation-stella-coder-features/slide-07.html +91 -0
  208. package/presentation-test-presentation/README.md +27 -0
  209. package/presentation-test-presentation/index.html +350 -0
  210. package/presentation-test-presentation/print.html +69 -0
  211. package/presentation-test-presentation/slide-01.html +98 -0
  212. package/presentation-test-presentation/slide-02.html +101 -0
  213. package/presentation-test-presentation/slide-03.html +64 -0
  214. package/presentation-test-presentation/slide-04.html +101 -0
  215. package/presentation-test-presentation/slide-05.html +91 -0
  216. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/README.md +27 -0
  217. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/index.html +159 -0
  218. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/slide-01.html +98 -0
  219. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/slide-02.html +101 -0
  220. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/slide-03.html +100 -0
  221. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/slide-04.html +100 -0
  222. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/slide-05.html +64 -0
  223. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/slide-06.html +101 -0
  224. package/presentation-/321/202/320/265/321/201/321/202/320/276/320/262/320/260/321/217-/320/277/321/200/320/265/320/267/320/265/320/275/321/202/320/260/321/206/320/270/321/217/slide-07.html +91 -0
  225. package/stella-cli/coding-brain.mjs +753 -0
  226. package/stella-cli/index.mjs +931 -15
  227. package/stella-cli/mcp.mjs +296 -0
  228. package/stella-cli/presentations.mjs +1106 -0
  229. package/stella-cli/subagents.mjs +142 -0
  230. package/stella-cli/telegram-bot.mjs +824 -0
  231. package/stella-cli/tg-bg.bat +13 -0
  232. package/stella-cli/tg-server.bat +15 -0
  233. package/stella-cli/tg-server.mjs +116 -0
  234. package/stella-cli/theme.mjs +6 -4
  235. package/stella-coder-3.9.2.tgz +0 -0
@@ -0,0 +1,1329 @@
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
+
11
+ # With persistence (Master + Overrides pattern)
12
+ result = generate_design_system("SaaS dashboard", "My Project", persist=True)
13
+ result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard")
14
+ """
15
+
16
+ import csv
17
+ import json
18
+ import os
19
+ import sys
20
+ import io
21
+ from datetime import datetime
22
+ from pathlib import Path
23
+ from core import search, DATA_DIR
24
+
25
+ # Force UTF-8 for stdout/stderr to handle emojis/box-drawing chars on Windows (cp1252 default)
26
+ if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
27
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
28
+ if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
29
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
30
+
31
+
32
+ # ============ CONFIGURATION ============
33
+ REASONING_FILE = "ui-reasoning.csv"
34
+
35
+ SEARCH_CONFIG = {
36
+ "product": {"max_results": 1},
37
+ "style": {"max_results": 3},
38
+ "color": {"max_results": 2},
39
+ "landing": {"max_results": 2},
40
+ "typography": {"max_results": 2}
41
+ }
42
+
43
+ # ============ DESIGN DIALS (1-10) ============
44
+ # Inspired by taste-skill's DESIGN_VARIANCE / MOTION_INTENSITY / VISUAL_DENSITY
45
+ # knobs: three optional 1-10 sliders that bias the existing query-based search
46
+ # instead of replacing it. Each dial buckets into a low/mid/high tier.
47
+ DIAL_TIERS = {
48
+ "variance": [
49
+ (1, 3, {"label": "Centered / Minimal", "style_keywords": ["Minimalism", "Exaggerated Minimalism", "centered", "symmetric", "grid-based"]}),
50
+ (4, 7, {"label": "Balanced / Modern", "style_keywords": ["modern", "structured", "balanced"]}),
51
+ (8, 10, {"label": "Bold / Asymmetric", "style_keywords": ["Brutalism", "Bento Grids", "asymmetric", "experimental"]}),
52
+ ],
53
+ "motion": [
54
+ (1, 3, {"label": "Subtle", "tier": "Subtle"}),
55
+ (4, 7, {"label": "Standard", "tier": "Standard"}),
56
+ (8, 10, {"label": "Complex", "tier": "Complex"}),
57
+ ],
58
+ "density": [
59
+ (1, 3, {"label": "Spacious", "spacing": {"xs": "4px", "sm": "8px", "md": "24px", "lg": "32px", "xl": "48px", "2xl": "64px", "3xl": "96px"}}),
60
+ (4, 7, {"label": "Standard", "spacing": {"xs": "4px", "sm": "8px", "md": "16px", "lg": "24px", "xl": "32px", "2xl": "48px", "3xl": "64px"}}),
61
+ (8, 10, {"label": "Dense / Dashboard", "spacing": {"xs": "2px", "sm": "4px", "md": "8px", "lg": "12px", "xl": "16px", "2xl": "24px", "3xl": "32px"}}),
62
+ ],
63
+ }
64
+
65
+
66
+ def _resolve_dial(dial_name: str, value) -> dict:
67
+ """Bucket a 1-10 dial value into its tier config. Returns None if value is None."""
68
+ if value is None:
69
+ return None
70
+ value = max(1, min(10, int(value)))
71
+ for lo, hi, info in DIAL_TIERS[dial_name]:
72
+ if lo <= value <= hi:
73
+ return {**info, "value": value}
74
+ return None
75
+
76
+
77
+ # ============ DESIGN SYSTEM GENERATOR ============
78
+ class DesignSystemGenerator:
79
+ """Generates design system recommendations from aggregated searches."""
80
+
81
+ def __init__(self):
82
+ self.reasoning_data = self._load_reasoning()
83
+
84
+ def _load_reasoning(self) -> list:
85
+ """Load reasoning rules from CSV."""
86
+ filepath = DATA_DIR / REASONING_FILE
87
+ if not filepath.exists():
88
+ return []
89
+ with open(filepath, 'r', encoding='utf-8') as f:
90
+ return list(csv.DictReader(f))
91
+
92
+ def _multi_domain_search(self, query: str, style_priority: list = None) -> dict:
93
+ """Execute searches across multiple domains."""
94
+ results = {}
95
+ for domain, config in SEARCH_CONFIG.items():
96
+ if domain == "style" and style_priority:
97
+ # For style, also search with priority keywords
98
+ priority_query = " ".join(style_priority[:2]) if style_priority else query
99
+ combined_query = f"{query} {priority_query}"
100
+ results[domain] = search(combined_query, domain, config["max_results"])
101
+ else:
102
+ results[domain] = search(query, domain, config["max_results"])
103
+ return results
104
+
105
+ def _find_reasoning_rule(self, category: str) -> dict:
106
+ """Find matching reasoning rule for a category."""
107
+ category_lower = category.lower()
108
+
109
+ # Try exact match first
110
+ for rule in self.reasoning_data:
111
+ if rule.get("UI_Category", "").lower() == category_lower:
112
+ return rule
113
+
114
+ # Try partial match
115
+ for rule in self.reasoning_data:
116
+ ui_cat = rule.get("UI_Category", "").lower()
117
+ if ui_cat in category_lower or category_lower in ui_cat:
118
+ return rule
119
+
120
+ # Try keyword match
121
+ for rule in self.reasoning_data:
122
+ ui_cat = rule.get("UI_Category", "").lower()
123
+ keywords = ui_cat.replace("/", " ").replace("-", " ").split()
124
+ if any(kw in category_lower for kw in keywords):
125
+ return rule
126
+
127
+ return {}
128
+
129
+ def _apply_reasoning(self, category: str, search_results: dict) -> dict:
130
+ """Apply reasoning rules to search results."""
131
+ rule = self._find_reasoning_rule(category)
132
+
133
+ if not rule:
134
+ return {
135
+ "pattern": "Hero + Features + CTA",
136
+ "style_priority": ["Minimalism", "Flat Design"],
137
+ "color_mood": "Professional",
138
+ "typography_mood": "Clean",
139
+ "key_effects": "Subtle hover transitions",
140
+ "anti_patterns": "",
141
+ "decision_rules": {},
142
+ "severity": "MEDIUM"
143
+ }
144
+
145
+ # Parse decision rules JSON
146
+ decision_rules = {}
147
+ try:
148
+ decision_rules = json.loads(rule.get("Decision_Rules", "{}"))
149
+ except json.JSONDecodeError:
150
+ pass
151
+
152
+ return {
153
+ "pattern": rule.get("Recommended_Pattern", ""),
154
+ "style_priority": [s.strip() for s in rule.get("Style_Priority", "").split("+")],
155
+ "color_mood": rule.get("Color_Mood", ""),
156
+ "typography_mood": rule.get("Typography_Mood", ""),
157
+ "key_effects": rule.get("Key_Effects", ""),
158
+ "anti_patterns": rule.get("Anti_Patterns", ""),
159
+ "decision_rules": decision_rules,
160
+ "severity": rule.get("Severity", "MEDIUM")
161
+ }
162
+
163
+ def _select_best_match(self, results: list, priority_keywords: list) -> dict:
164
+ """Select best matching result based on priority keywords."""
165
+ if not results:
166
+ return {}
167
+
168
+ if not priority_keywords:
169
+ return results[0]
170
+
171
+ # First: try exact style name match
172
+ for priority in priority_keywords:
173
+ priority_lower = priority.lower().strip()
174
+ for result in results:
175
+ style_name = result.get("Style Category", "").lower()
176
+ if priority_lower in style_name or style_name in priority_lower:
177
+ return result
178
+
179
+ # Second: score by keyword match in all fields
180
+ scored = []
181
+ for result in results:
182
+ result_str = str(result).lower()
183
+ score = 0
184
+ for kw in priority_keywords:
185
+ kw_lower = kw.lower().strip()
186
+ # Higher score for style name match
187
+ if kw_lower in result.get("Style Category", "").lower():
188
+ score += 10
189
+ # Lower score for keyword field match
190
+ elif kw_lower in result.get("Keywords", "").lower():
191
+ score += 3
192
+ # Even lower for other field matches
193
+ elif kw_lower in result_str:
194
+ score += 1
195
+ scored.append((score, result))
196
+
197
+ scored.sort(key=lambda x: x[0], reverse=True)
198
+ return scored[0][1] if scored and scored[0][0] > 0 else results[0]
199
+
200
+ def _extract_results(self, search_result: dict) -> list:
201
+ """Extract results list from search result dict."""
202
+ return search_result.get("results", [])
203
+
204
+ def generate(self, query: str, project_name: str = None,
205
+ variance: int = None, motion: int = None, density: int = None) -> dict:
206
+ """Generate complete design system recommendation.
207
+
208
+ variance/motion/density are optional 1-10 dials (see DIAL_TIERS) that bias
209
+ style selection, pull in a matching motion.csv snippet, and override the
210
+ spacing scale, without changing behavior when left unset.
211
+ """
212
+ variance_info = _resolve_dial("variance", variance)
213
+ motion_info = _resolve_dial("motion", motion)
214
+ density_info = _resolve_dial("density", density)
215
+
216
+ # Step 1: First search product to get category
217
+ product_result = search(query, "product", 1)
218
+ product_results = product_result.get("results", [])
219
+ category = "General"
220
+ if product_results:
221
+ category = product_results[0].get("Product Type", "General")
222
+
223
+ # Step 2: Get reasoning rules for this category
224
+ reasoning = self._apply_reasoning(category, {})
225
+ style_priority = reasoning.get("style_priority", [])
226
+
227
+ # DESIGN_VARIANCE dial: bias style retrieval/selection toward
228
+ # centered-minimal (low) or bold-asymmetric (high) keywords.
229
+ effective_style_priority = style_priority
230
+ if variance_info:
231
+ effective_style_priority = variance_info["style_keywords"] + style_priority
232
+
233
+ # Step 3: Multi-domain search with style priority hints
234
+ search_results = self._multi_domain_search(query, effective_style_priority)
235
+ search_results["product"] = product_result # Reuse product search
236
+
237
+ # Step 4: Select best matches from each domain using priority
238
+ style_results = self._extract_results(search_results.get("style", {}))
239
+ color_results = self._extract_results(search_results.get("color", {}))
240
+ typography_results = self._extract_results(search_results.get("typography", {}))
241
+ landing_results = self._extract_results(search_results.get("landing", {}))
242
+
243
+ best_style = self._select_best_match(style_results, effective_style_priority)
244
+ best_color = color_results[0] if color_results else {}
245
+ best_typography = typography_results[0] if typography_results else {}
246
+ best_landing = landing_results[0] if landing_results else {}
247
+
248
+ # MOTION_INTENSITY dial: pull a matching GSAP skeleton from motion.csv
249
+ # (domain key is "gsap", not "motion" - PR #296 already owns the "motion"
250
+ # domain for Emil Kowalski's motion-design principles, motion-principles.csv).
251
+ motion_snippet = {}
252
+ if motion_info:
253
+ motion_result = search(f"{query} {motion_info['tier']}", "gsap", 5)
254
+ motion_matches = motion_result.get("results", [])
255
+ tiered = [m for m in motion_matches if m.get("Intensity Tier") == motion_info["tier"]]
256
+ if tiered:
257
+ motion_snippet = tiered[0]
258
+ elif motion_matches:
259
+ motion_snippet = motion_matches[0]
260
+
261
+ # Step 5: Build final recommendation
262
+ # Combine effects from both reasoning and style search
263
+ style_effects = best_style.get("Effects & Animation", "")
264
+ reasoning_effects = reasoning.get("key_effects", "")
265
+ combined_effects = style_effects if style_effects else reasoning_effects
266
+
267
+ return {
268
+ "project_name": project_name or query.upper(),
269
+ "category": category,
270
+ "pattern": {
271
+ "name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
272
+ "sections": best_landing.get("Section Order", "Hero > Features > CTA"),
273
+ "cta_placement": best_landing.get("Primary CTA Placement", "Above fold"),
274
+ "color_strategy": best_landing.get("Color Strategy", ""),
275
+ "conversion": best_landing.get("Conversion Optimization", "")
276
+ },
277
+ "style": {
278
+ "name": best_style.get("Style Category", "Minimalism"),
279
+ "type": best_style.get("Type", "General"),
280
+ "effects": style_effects,
281
+ "keywords": best_style.get("Keywords", ""),
282
+ "best_for": best_style.get("Best For", ""),
283
+ "performance": best_style.get("Performance", ""),
284
+ "accessibility": best_style.get("Accessibility", ""),
285
+ "light_mode": best_style.get("Light Mode ✓", ""),
286
+ "dark_mode": best_style.get("Dark Mode ✓", ""),
287
+ },
288
+ "colors": {
289
+ "primary": best_color.get("Primary", "#2563EB"),
290
+ "on_primary": best_color.get("On Primary", ""),
291
+ "secondary": best_color.get("Secondary", "#3B82F6"),
292
+ "accent": best_color.get("Accent", "#F97316"),
293
+ "background": best_color.get("Background", "#F8FAFC"),
294
+ "foreground": best_color.get("Foreground", "#1E293B"),
295
+ "muted": best_color.get("Muted", ""),
296
+ "border": best_color.get("Border", ""),
297
+ "destructive": best_color.get("Destructive", ""),
298
+ "ring": best_color.get("Ring", ""),
299
+ "notes": best_color.get("Notes", ""),
300
+ # Keep legacy keys for backward compat in MASTER.md
301
+ "cta": best_color.get("Accent", "#F97316"),
302
+ "text": best_color.get("Foreground", "#1E293B"),
303
+ },
304
+ "typography": {
305
+ "heading": best_typography.get("Heading Font", "Inter"),
306
+ "body": best_typography.get("Body Font", "Inter"),
307
+ "mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
308
+ "best_for": best_typography.get("Best For", ""),
309
+ "google_fonts_url": best_typography.get("Google Fonts URL", ""),
310
+ "css_import": best_typography.get("CSS Import", "")
311
+ },
312
+ "key_effects": combined_effects,
313
+ "anti_patterns": reasoning.get("anti_patterns", ""),
314
+ "decision_rules": reasoning.get("decision_rules", {}),
315
+ "severity": reasoning.get("severity", "MEDIUM"),
316
+ "dials": {
317
+ "variance": variance_info["value"] if variance_info else None,
318
+ "variance_label": variance_info["label"] if variance_info else None,
319
+ "motion": motion_info["value"] if motion_info else None,
320
+ "motion_label": motion_info["label"] if motion_info else None,
321
+ "density": density_info["value"] if density_info else None,
322
+ "density_label": density_info["label"] if density_info else None,
323
+ },
324
+ "motion_snippet": motion_snippet,
325
+ "spacing_scale": density_info["spacing"] if density_info else None,
326
+ }
327
+
328
+
329
+ # ============ OUTPUT FORMATTERS ============
330
+ BOX_WIDTH = 90 # Wider box for more content
331
+
332
+
333
+ def hex_to_ansi(hex_color: str) -> str:
334
+ """Convert hex color to ANSI True Color swatch (██) with fallback."""
335
+ if not hex_color or not hex_color.startswith('#'):
336
+ return ""
337
+ colorterm = os.environ.get('COLORTERM', '')
338
+ if colorterm not in ('truecolor', '24bit'):
339
+ return ""
340
+ hex_color = hex_color.lstrip('#')
341
+ if len(hex_color) != 6:
342
+ return ""
343
+ r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
344
+ return f"\033[38;2;{r};{g};{b}m██\033[0m "
345
+
346
+
347
+ def ansi_ljust(s: str, width: int) -> str:
348
+ """Like str.ljust but accounts for zero-width ANSI escape sequences."""
349
+ import re
350
+ visible_len = len(re.sub(r'\033\[[0-9;]*m', '', s))
351
+ pad = width - visible_len
352
+ return s + (" " * max(0, pad))
353
+
354
+
355
+ def section_header(name: str, width: int) -> str:
356
+ """Create a Unicode section separator: ├─── NAME ───...┤"""
357
+ label = f"─── {name} "
358
+ fill = "─" * (width - len(label) - 1)
359
+ return f"├{label}{fill}┤"
360
+
361
+
362
+ def format_ascii_box(design_system: dict) -> str:
363
+ """Format design system as Unicode box with ANSI color swatches."""
364
+ project = design_system.get("project_name", "PROJECT")
365
+ pattern = design_system.get("pattern", {})
366
+ style = design_system.get("style", {})
367
+ colors = design_system.get("colors", {})
368
+ typography = design_system.get("typography", {})
369
+ effects = design_system.get("key_effects", "")
370
+ anti_patterns = design_system.get("anti_patterns", "")
371
+ dials = design_system.get("dials", {})
372
+ motion_snippet = design_system.get("motion_snippet", {})
373
+
374
+ def wrap_text(text: str, prefix: str, width: int) -> list:
375
+ """Wrap long text into multiple lines."""
376
+ if not text:
377
+ return []
378
+ words = text.split()
379
+ lines = []
380
+ current_line = prefix
381
+ for word in words:
382
+ if len(current_line) + len(word) + 1 <= width - 2:
383
+ current_line += (" " if current_line != prefix else "") + word
384
+ else:
385
+ if current_line != prefix:
386
+ lines.append(current_line)
387
+ current_line = prefix + word
388
+ if current_line != prefix:
389
+ lines.append(current_line)
390
+ return lines
391
+
392
+ # Build sections from pattern
393
+ sections = pattern.get("sections", "").split(">")
394
+ sections = [s.strip() for s in sections if s.strip()]
395
+
396
+ # Build output lines
397
+ lines = []
398
+ w = BOX_WIDTH - 1
399
+
400
+ # Header with double-line box
401
+ lines.append("╔" + "═" * w + "╗")
402
+ lines.append(ansi_ljust(f"║ TARGET: {project} - RECOMMENDED DESIGN SYSTEM", BOX_WIDTH) + "║")
403
+ lines.append("╚" + "═" * w + "╝")
404
+ lines.append("┌" + "─" * w + "┐")
405
+
406
+ # Design Dials section (only if at least one dial was set)
407
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
408
+ lines.append(section_header("DESIGN DIALS", BOX_WIDTH + 1))
409
+ if dials.get("variance") is not None:
410
+ lines.append(f"│ Variance: {dials['variance']}/10 — {dials['variance_label']}".ljust(BOX_WIDTH) + "│")
411
+ if dials.get("motion") is not None:
412
+ lines.append(f"│ Motion: {dials['motion']}/10 — {dials['motion_label']}".ljust(BOX_WIDTH) + "│")
413
+ if dials.get("density") is not None:
414
+ lines.append(f"│ Density: {dials['density']}/10 — {dials['density_label']}".ljust(BOX_WIDTH) + "│")
415
+
416
+ # Pattern section
417
+ lines.append(section_header("PATTERN", BOX_WIDTH + 1))
418
+ lines.append(f"│ Name: {pattern.get('name', '')}".ljust(BOX_WIDTH) + "│")
419
+ if pattern.get('conversion'):
420
+ lines.append(f"│ Conversion: {pattern.get('conversion', '')}".ljust(BOX_WIDTH) + "│")
421
+ if pattern.get('cta_placement'):
422
+ lines.append(f"│ CTA: {pattern.get('cta_placement', '')}".ljust(BOX_WIDTH) + "│")
423
+ lines.append("│ Sections:".ljust(BOX_WIDTH) + "│")
424
+ for i, section in enumerate(sections, 1):
425
+ lines.append(f"│ {i}. {section}".ljust(BOX_WIDTH) + "│")
426
+
427
+ # Style section
428
+ lines.append(section_header("STYLE", BOX_WIDTH + 1))
429
+ lines.append(f"│ Name: {style.get('name', '')}".ljust(BOX_WIDTH) + "│")
430
+ light = style.get("light_mode", "")
431
+ dark = style.get("dark_mode", "")
432
+ if light or dark:
433
+ lines.append(f"│ Mode Support: Light {light} Dark {dark}".ljust(BOX_WIDTH) + "│")
434
+ if style.get("keywords"):
435
+ for line in wrap_text(f"Keywords: {style.get('keywords', '')}", "│ ", BOX_WIDTH):
436
+ lines.append(line.ljust(BOX_WIDTH) + "│")
437
+ if style.get("best_for"):
438
+ for line in wrap_text(f"Best For: {style.get('best_for', '')}", "│ ", BOX_WIDTH):
439
+ lines.append(line.ljust(BOX_WIDTH) + "│")
440
+ if style.get("performance") or style.get("accessibility"):
441
+ perf_a11y = f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}"
442
+ lines.append(f"│ {perf_a11y}".ljust(BOX_WIDTH) + "│")
443
+
444
+ # Colors section (extended palette with ANSI swatches)
445
+ lines.append(section_header("COLORS", BOX_WIDTH + 1))
446
+ color_entries = [
447
+ ("Primary", "primary", "--color-primary"),
448
+ ("On Primary", "on_primary", "--color-on-primary"),
449
+ ("Secondary", "secondary", "--color-secondary"),
450
+ ("Accent/CTA", "accent", "--color-accent"),
451
+ ("Background", "background", "--color-background"),
452
+ ("Foreground", "foreground", "--color-foreground"),
453
+ ("Muted", "muted", "--color-muted"),
454
+ ("Border", "border", "--color-border"),
455
+ ("Destructive", "destructive", "--color-destructive"),
456
+ ("Ring", "ring", "--color-ring"),
457
+ ]
458
+ for label, key, css_var in color_entries:
459
+ hex_val = colors.get(key, "")
460
+ if not hex_val:
461
+ continue
462
+ swatch = hex_to_ansi(hex_val)
463
+ content = f"│ {swatch}{label + ':':14s} {hex_val:10s} ({css_var})"
464
+ lines.append(ansi_ljust(content, BOX_WIDTH) + "│")
465
+ if colors.get("notes"):
466
+ for line in wrap_text(f"Notes: {colors.get('notes', '')}", "│ ", BOX_WIDTH):
467
+ lines.append(line.ljust(BOX_WIDTH) + "│")
468
+
469
+ # Typography section
470
+ lines.append(section_header("TYPOGRAPHY", BOX_WIDTH + 1))
471
+ lines.append(f"│ {typography.get('heading', '')} / {typography.get('body', '')}".ljust(BOX_WIDTH) + "│")
472
+ if typography.get("mood"):
473
+ for line in wrap_text(f"Mood: {typography.get('mood', '')}", "│ ", BOX_WIDTH):
474
+ lines.append(line.ljust(BOX_WIDTH) + "│")
475
+ if typography.get("best_for"):
476
+ for line in wrap_text(f"Best For: {typography.get('best_for', '')}", "│ ", BOX_WIDTH):
477
+ lines.append(line.ljust(BOX_WIDTH) + "│")
478
+ if typography.get("google_fonts_url"):
479
+ lines.append(f"│ Google Fonts: {typography.get('google_fonts_url', '')}".ljust(BOX_WIDTH) + "│")
480
+ if typography.get("css_import"):
481
+ lines.append(f"│ CSS Import: {typography.get('css_import', '')[:70]}...".ljust(BOX_WIDTH) + "│")
482
+
483
+ # Key Effects section
484
+ if effects:
485
+ lines.append(section_header("KEY EFFECTS", BOX_WIDTH + 1))
486
+ for line in wrap_text(effects, "│ ", BOX_WIDTH):
487
+ lines.append(line.ljust(BOX_WIDTH) + "│")
488
+
489
+ # Motion section (GSAP skeleton, only if --motion dial was set)
490
+ if motion_snippet:
491
+ lines.append(section_header("MOTION", BOX_WIDTH + 1))
492
+ lines.append(f"│ {motion_snippet.get('Category', '')} ({motion_snippet.get('Intensity Tier', '')})".ljust(BOX_WIDTH) + "│")
493
+ lines.append(f"│ Trigger: {motion_snippet.get('Trigger', '')} | Duration: {motion_snippet.get('Duration', '')} | Easing: {motion_snippet.get('Easing', '')}".ljust(BOX_WIDTH) + "│")
494
+ for line in wrap_text(f"GSAP: {motion_snippet.get('GSAP Snippet', '')}", "│ ", BOX_WIDTH):
495
+ lines.append(line.ljust(BOX_WIDTH) + "│")
496
+ if motion_snippet.get("Framework Notes"):
497
+ for line in wrap_text(f"Framework: {motion_snippet.get('Framework Notes', '')}", "│ ", BOX_WIDTH):
498
+ lines.append(line.ljust(BOX_WIDTH) + "│")
499
+
500
+ # Anti-patterns section
501
+ if anti_patterns:
502
+ lines.append(section_header("AVOID", BOX_WIDTH + 1))
503
+ for line in wrap_text(anti_patterns, "│ ", BOX_WIDTH):
504
+ lines.append(line.ljust(BOX_WIDTH) + "│")
505
+
506
+ # Pre-Delivery Checklist section
507
+ lines.append(section_header("PRE-DELIVERY CHECKLIST", BOX_WIDTH + 1))
508
+ checklist_items = [
509
+ "[ ] No emojis as icons (use SVG: Heroicons/Lucide)",
510
+ "[ ] cursor-pointer on all clickable elements",
511
+ "[ ] Hover states with smooth transitions (150-300ms)",
512
+ "[ ] Light mode: text contrast 4.5:1 minimum",
513
+ "[ ] Focus states visible for keyboard nav",
514
+ "[ ] prefers-reduced-motion respected",
515
+ "[ ] Responsive: 375px, 768px, 1024px, 1440px"
516
+ ]
517
+ for item in checklist_items:
518
+ lines.append(f"│ {item}".ljust(BOX_WIDTH) + "│")
519
+
520
+ lines.append("└" + "─" * w + "┘")
521
+
522
+ return "\n".join(lines)
523
+
524
+
525
+ def format_markdown(design_system: dict) -> str:
526
+ """Format design system as markdown."""
527
+ project = design_system.get("project_name", "PROJECT")
528
+ pattern = design_system.get("pattern", {})
529
+ style = design_system.get("style", {})
530
+ colors = design_system.get("colors", {})
531
+ typography = design_system.get("typography", {})
532
+ effects = design_system.get("key_effects", "")
533
+ anti_patterns = design_system.get("anti_patterns", "")
534
+ dials = design_system.get("dials", {})
535
+ motion_snippet = design_system.get("motion_snippet", {})
536
+
537
+ lines = []
538
+ lines.append(f"## Design System: {project}")
539
+ lines.append("")
540
+
541
+ # Design Dials section (only if at least one dial was set)
542
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
543
+ lines.append("### Design Dials")
544
+ if dials.get("variance") is not None:
545
+ lines.append(f"- **Variance:** {dials['variance']}/10 — {dials['variance_label']}")
546
+ if dials.get("motion") is not None:
547
+ lines.append(f"- **Motion:** {dials['motion']}/10 — {dials['motion_label']}")
548
+ if dials.get("density") is not None:
549
+ lines.append(f"- **Density:** {dials['density']}/10 — {dials['density_label']}")
550
+ lines.append("")
551
+
552
+ # Pattern section
553
+ lines.append("### Pattern")
554
+ lines.append(f"- **Name:** {pattern.get('name', '')}")
555
+ if pattern.get('conversion'):
556
+ lines.append(f"- **Conversion Focus:** {pattern.get('conversion', '')}")
557
+ if pattern.get('cta_placement'):
558
+ lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
559
+ if pattern.get('color_strategy'):
560
+ lines.append(f"- **Color Strategy:** {pattern.get('color_strategy', '')}")
561
+ lines.append(f"- **Sections:** {pattern.get('sections', '')}")
562
+ lines.append("")
563
+
564
+ # Style section
565
+ lines.append("### Style")
566
+ lines.append(f"- **Name:** {style.get('name', '')}")
567
+ light = style.get("light_mode", "")
568
+ dark = style.get("dark_mode", "")
569
+ if light or dark:
570
+ lines.append(f"- **Mode Support:** Light {light} | Dark {dark}")
571
+ if style.get('keywords'):
572
+ lines.append(f"- **Keywords:** {style.get('keywords', '')}")
573
+ if style.get('best_for'):
574
+ lines.append(f"- **Best For:** {style.get('best_for', '')}")
575
+ if style.get('performance') or style.get('accessibility'):
576
+ lines.append(f"- **Performance:** {style.get('performance', '')} | **Accessibility:** {style.get('accessibility', '')}")
577
+ lines.append("")
578
+
579
+ # Colors section (extended palette)
580
+ lines.append("### Colors")
581
+ lines.append("| Role | Hex | CSS Variable |")
582
+ lines.append("|------|-----|--------------|")
583
+ md_color_entries = [
584
+ ("Primary", "primary", "--color-primary"),
585
+ ("On Primary", "on_primary", "--color-on-primary"),
586
+ ("Secondary", "secondary", "--color-secondary"),
587
+ ("Accent/CTA", "accent", "--color-accent"),
588
+ ("Background", "background", "--color-background"),
589
+ ("Foreground", "foreground", "--color-foreground"),
590
+ ("Muted", "muted", "--color-muted"),
591
+ ("Border", "border", "--color-border"),
592
+ ("Destructive", "destructive", "--color-destructive"),
593
+ ("Ring", "ring", "--color-ring"),
594
+ ]
595
+ for label, key, css_var in md_color_entries:
596
+ hex_val = colors.get(key, "")
597
+ if hex_val:
598
+ lines.append(f"| {label} | `{hex_val}` | `{css_var}` |")
599
+ if colors.get("notes"):
600
+ lines.append(f"\n*Notes: {colors.get('notes', '')}*")
601
+ lines.append("")
602
+
603
+ # Typography section
604
+ lines.append("### Typography")
605
+ lines.append(f"- **Heading:** {typography.get('heading', '')}")
606
+ lines.append(f"- **Body:** {typography.get('body', '')}")
607
+ if typography.get("mood"):
608
+ lines.append(f"- **Mood:** {typography.get('mood', '')}")
609
+ if typography.get("best_for"):
610
+ lines.append(f"- **Best For:** {typography.get('best_for', '')}")
611
+ if typography.get("google_fonts_url"):
612
+ lines.append(f"- **Google Fonts:** {typography.get('google_fonts_url', '')}")
613
+ if typography.get("css_import"):
614
+ lines.append(f"- **CSS Import:**")
615
+ lines.append(f"```css")
616
+ lines.append(f"{typography.get('css_import', '')}")
617
+ lines.append(f"```")
618
+ lines.append("")
619
+
620
+ # Key Effects section
621
+ if effects:
622
+ lines.append("### Key Effects")
623
+ lines.append(f"{effects}")
624
+ lines.append("")
625
+
626
+ # Motion section (GSAP skeleton, only if --motion dial was set)
627
+ if motion_snippet:
628
+ lines.append("### Motion")
629
+ 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', '')}`")
630
+ lines.append("```js")
631
+ lines.append(motion_snippet.get("GSAP Snippet", ""))
632
+ lines.append("```")
633
+ if motion_snippet.get("Framework Notes"):
634
+ lines.append(f"*Framework notes: {motion_snippet.get('Framework Notes', '')}*")
635
+ motion_do = motion_snippet.get("Do", "")
636
+ motion_dont = motion_snippet.get("Don't", "")
637
+ if motion_do:
638
+ lines.append(f"- ✅ {motion_do}")
639
+ if motion_dont:
640
+ lines.append(f"- ❌ {motion_dont}")
641
+ lines.append("")
642
+
643
+ # Anti-patterns section
644
+ if anti_patterns:
645
+ lines.append("### Avoid (Anti-patterns)")
646
+ newline_bullet = '\n- '
647
+ lines.append(f"- {anti_patterns.replace(' + ', newline_bullet)}")
648
+ lines.append("")
649
+
650
+ # Pre-Delivery Checklist section
651
+ lines.append("### Pre-Delivery Checklist")
652
+ lines.append("- [ ] No emojis as icons (use SVG: Heroicons/Lucide)")
653
+ lines.append("- [ ] cursor-pointer on all clickable elements")
654
+ lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
655
+ lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
656
+ lines.append("- [ ] Focus states visible for keyboard nav")
657
+ lines.append("- [ ] prefers-reduced-motion respected")
658
+ lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
659
+ lines.append("")
660
+
661
+ return "\n".join(lines)
662
+
663
+
664
+ # ============ MAIN ENTRY POINT ============
665
+ def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii",
666
+ persist: bool = False, page: str = None, output_dir: str = None,
667
+ variance: int = None, motion: int = None, density: int = None) -> str:
668
+ """
669
+ Main entry point for design system generation.
670
+
671
+ Args:
672
+ query: Search query (e.g., "SaaS dashboard", "e-commerce luxury")
673
+ project_name: Optional project name for output header
674
+ output_format: "ascii" (default) or "markdown"
675
+ persist: If True, save design system to design-system/ folder
676
+ page: Optional page name for page-specific override file
677
+ output_dir: Optional output directory (defaults to current working directory)
678
+ variance: Optional 1-10 DESIGN_VARIANCE dial (1=centered/minimal, 10=bold/asymmetric)
679
+ motion: Optional 1-10 MOTION_INTENSITY dial, pulls a matching GSAP snippet from motion.csv
680
+ density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense)
681
+
682
+ Returns:
683
+ Formatted design system string
684
+ """
685
+ generator = DesignSystemGenerator()
686
+ design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
687
+
688
+ # Persist to files if requested
689
+ if persist:
690
+ persist_design_system(design_system, page, output_dir, query)
691
+
692
+ if output_format == "markdown":
693
+ return format_markdown(design_system)
694
+ return format_ascii_box(design_system)
695
+
696
+
697
+ # ============ PERSISTENCE FUNCTIONS ============
698
+ def persist_design_system(design_system: dict, page: str = None, output_dir: str = None, page_query: str = None) -> dict:
699
+ """
700
+ Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
701
+
702
+ Args:
703
+ design_system: The generated design system dictionary
704
+ page: Optional page name for page-specific override file
705
+ output_dir: Optional output directory (defaults to current working directory)
706
+ page_query: Optional query string for intelligent page override generation
707
+
708
+ Returns:
709
+ dict with created file paths and status
710
+ """
711
+ base_dir = Path(output_dir) if output_dir else Path.cwd()
712
+
713
+ # Use project name for project-specific folder. Coalesce falsy values
714
+ # (missing key, explicit None, or "") so the .lower() below can't crash.
715
+ project_name = design_system.get("project_name") or "default"
716
+ project_slug = project_name.lower().replace(' ', '-')
717
+
718
+ design_system_dir = base_dir / "design-system" / project_slug
719
+ pages_dir = design_system_dir / "pages"
720
+
721
+ created_files = []
722
+
723
+ # Create directories
724
+ design_system_dir.mkdir(parents=True, exist_ok=True)
725
+ pages_dir.mkdir(parents=True, exist_ok=True)
726
+
727
+ master_file = design_system_dir / "MASTER.md"
728
+
729
+ # Generate and write MASTER.md
730
+ master_content = format_master_md(design_system)
731
+ with open(master_file, 'w', encoding='utf-8') as f:
732
+ f.write(master_content)
733
+ created_files.append(str(master_file))
734
+
735
+ # If page is specified, create page override file with intelligent content
736
+ if page:
737
+ page_file = pages_dir / f"{page.lower().replace(' ', '-')}.md"
738
+ page_content = format_page_override_md(design_system, page, page_query)
739
+ with open(page_file, 'w', encoding='utf-8') as f:
740
+ f.write(page_content)
741
+ created_files.append(str(page_file))
742
+
743
+ return {
744
+ "status": "success",
745
+ "design_system_dir": str(design_system_dir),
746
+ "created_files": created_files
747
+ }
748
+
749
+
750
+ def format_master_md(design_system: dict) -> str:
751
+ """Format design system as MASTER.md with hierarchical override logic."""
752
+ project = design_system.get("project_name", "PROJECT")
753
+ pattern = design_system.get("pattern", {})
754
+ style = design_system.get("style", {})
755
+ colors = design_system.get("colors", {})
756
+ typography = design_system.get("typography", {})
757
+ effects = design_system.get("key_effects", "")
758
+ anti_patterns = design_system.get("anti_patterns", "")
759
+ dials = design_system.get("dials", {})
760
+ motion_snippet = design_system.get("motion_snippet", {})
761
+ spacing_scale = design_system.get("spacing_scale")
762
+
763
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
764
+
765
+ lines = []
766
+
767
+ # Logic header
768
+ lines.append("# Design System Master File")
769
+ lines.append("")
770
+ lines.append("> **LOGIC:** When building a specific page, first check `design-system/pages/[page-name].md`.")
771
+ lines.append("> If that file exists, its rules **override** this Master file.")
772
+ lines.append("> If not, strictly follow the rules below.")
773
+ lines.append("")
774
+ lines.append("---")
775
+ lines.append("")
776
+ lines.append(f"**Project:** {project}")
777
+ lines.append(f"**Generated:** {timestamp}")
778
+ lines.append(f"**Category:** {design_system.get('category', 'General')}")
779
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
780
+ dial_parts = []
781
+ if dials.get("variance") is not None:
782
+ dial_parts.append(f"Variance {dials['variance']}/10 ({dials['variance_label']})")
783
+ if dials.get("motion") is not None:
784
+ dial_parts.append(f"Motion {dials['motion']}/10 ({dials['motion_label']})")
785
+ if dials.get("density") is not None:
786
+ dial_parts.append(f"Density {dials['density']}/10 ({dials['density_label']})")
787
+ lines.append(f"**Design Dials:** {' | '.join(dial_parts)}")
788
+ lines.append("")
789
+ lines.append("---")
790
+ lines.append("")
791
+
792
+ # Global Rules section
793
+ lines.append("## Global Rules")
794
+ lines.append("")
795
+
796
+ # Color Palette
797
+ lines.append("### Color Palette")
798
+ lines.append("")
799
+ lines.append("| Role | Hex | CSS Variable |")
800
+ lines.append("|------|-----|--------------|")
801
+ master_color_entries = [
802
+ ("Primary", "primary", "--color-primary"),
803
+ ("On Primary", "on_primary", "--color-on-primary"),
804
+ ("Secondary", "secondary", "--color-secondary"),
805
+ ("Accent/CTA", "accent", "--color-accent"),
806
+ ("Background", "background", "--color-background"),
807
+ ("Foreground", "foreground", "--color-foreground"),
808
+ ("Muted", "muted", "--color-muted"),
809
+ ("Border", "border", "--color-border"),
810
+ ("Destructive", "destructive", "--color-destructive"),
811
+ ("Ring", "ring", "--color-ring"),
812
+ ]
813
+ for label, key, css_var in master_color_entries:
814
+ hex_val = colors.get(key, "")
815
+ if hex_val:
816
+ lines.append(f"| {label} | `{hex_val}` | `{css_var}` |")
817
+ lines.append("")
818
+ if colors.get("notes"):
819
+ lines.append(f"**Color Notes:** {colors.get('notes', '')}")
820
+ lines.append("")
821
+
822
+ # Typography
823
+ lines.append("### Typography")
824
+ lines.append("")
825
+ lines.append(f"- **Heading Font:** {typography.get('heading', 'Inter')}")
826
+ lines.append(f"- **Body Font:** {typography.get('body', 'Inter')}")
827
+ if typography.get("mood"):
828
+ lines.append(f"- **Mood:** {typography.get('mood', '')}")
829
+ if typography.get("google_fonts_url"):
830
+ lines.append(f"- **Google Fonts:** [{typography.get('heading', '')} + {typography.get('body', '')}]({typography.get('google_fonts_url', '')})")
831
+ lines.append("")
832
+ if typography.get("css_import"):
833
+ lines.append("**CSS Import:**")
834
+ lines.append("```css")
835
+ lines.append(typography.get("css_import", ""))
836
+ lines.append("```")
837
+ lines.append("")
838
+
839
+ # Spacing Variables (overridden by the VISUAL_DENSITY dial when set)
840
+ default_spacing = DIAL_TIERS["density"][1][2]["spacing"] # mid-tier = the historical defaults
841
+ scale = spacing_scale or default_spacing
842
+ spacing_usage = {
843
+ "xs": "Tight gaps", "sm": "Icon gaps, inline spacing", "md": "Standard padding",
844
+ "lg": "Section padding", "xl": "Large gaps", "2xl": "Section margins", "3xl": "Hero padding",
845
+ }
846
+ lines.append("### Spacing Variables")
847
+ lines.append("")
848
+ if spacing_scale:
849
+ lines.append(f"*Density: {dials.get('density')}/10 — {dials.get('density_label')}*")
850
+ lines.append("")
851
+ lines.append("| Token | Value | Usage |")
852
+ lines.append("|-------|-------|-------|")
853
+ for token in ("xs", "sm", "md", "lg", "xl", "2xl", "3xl"):
854
+ px_value = scale[token]
855
+ rem_value = f"{int(px_value.rstrip('px')) / 16:g}rem"
856
+ lines.append(f"| `--space-{token}` | `{px_value}` / `{rem_value}` | {spacing_usage[token]} |")
857
+ lines.append("")
858
+
859
+ # Shadow Depths
860
+ lines.append("### Shadow Depths")
861
+ lines.append("")
862
+ lines.append("| Level | Value | Usage |")
863
+ lines.append("|-------|-------|-------|")
864
+ lines.append("| `--shadow-sm` | `0 1px 2px rgba(0,0,0,0.05)` | Subtle lift |")
865
+ lines.append("| `--shadow-md` | `0 4px 6px rgba(0,0,0,0.1)` | Cards, buttons |")
866
+ lines.append("| `--shadow-lg` | `0 10px 15px rgba(0,0,0,0.1)` | Modals, dropdowns |")
867
+ lines.append("| `--shadow-xl` | `0 20px 25px rgba(0,0,0,0.15)` | Hero images, featured cards |")
868
+ lines.append("")
869
+
870
+ # Component Specs section
871
+ lines.append("---")
872
+ lines.append("")
873
+ lines.append("## Component Specs")
874
+ lines.append("")
875
+
876
+ # Buttons
877
+ lines.append("### Buttons")
878
+ lines.append("")
879
+ lines.append("```css")
880
+ lines.append("/* Primary Button */")
881
+ lines.append(".btn-primary {")
882
+ lines.append(f" background: {colors.get('cta', '#F97316')};")
883
+ lines.append(" color: white;")
884
+ lines.append(" padding: 12px 24px;")
885
+ lines.append(" border-radius: 8px;")
886
+ lines.append(" font-weight: 600;")
887
+ lines.append(" transition: all 200ms ease;")
888
+ lines.append(" cursor: pointer;")
889
+ lines.append("}")
890
+ lines.append("")
891
+ lines.append(".btn-primary:hover {")
892
+ lines.append(" opacity: 0.9;")
893
+ lines.append(" transform: translateY(-1px);")
894
+ lines.append("}")
895
+ lines.append("")
896
+ lines.append("/* Secondary Button */")
897
+ lines.append(".btn-secondary {")
898
+ lines.append(f" background: transparent;")
899
+ lines.append(f" color: {colors.get('primary', '#2563EB')};")
900
+ lines.append(f" border: 2px solid {colors.get('primary', '#2563EB')};")
901
+ lines.append(" padding: 12px 24px;")
902
+ lines.append(" border-radius: 8px;")
903
+ lines.append(" font-weight: 600;")
904
+ lines.append(" transition: all 200ms ease;")
905
+ lines.append(" cursor: pointer;")
906
+ lines.append("}")
907
+ lines.append("```")
908
+ lines.append("")
909
+
910
+ # Cards
911
+ lines.append("### Cards")
912
+ lines.append("")
913
+ lines.append("```css")
914
+ lines.append(".card {")
915
+ lines.append(f" background: {colors.get('background', '#FFFFFF')};")
916
+ lines.append(" border-radius: 12px;")
917
+ lines.append(" padding: 24px;")
918
+ lines.append(" box-shadow: var(--shadow-md);")
919
+ lines.append(" transition: all 200ms ease;")
920
+ lines.append(" cursor: pointer;")
921
+ lines.append("}")
922
+ lines.append("")
923
+ lines.append(".card:hover {")
924
+ lines.append(" box-shadow: var(--shadow-lg);")
925
+ lines.append(" transform: translateY(-2px);")
926
+ lines.append("}")
927
+ lines.append("```")
928
+ lines.append("")
929
+
930
+ # Inputs
931
+ lines.append("### Inputs")
932
+ lines.append("")
933
+ lines.append("```css")
934
+ lines.append(".input {")
935
+ lines.append(" padding: 12px 16px;")
936
+ lines.append(" border: 1px solid #E2E8F0;")
937
+ lines.append(" border-radius: 8px;")
938
+ lines.append(" font-size: 16px;")
939
+ lines.append(" transition: border-color 200ms ease;")
940
+ lines.append("}")
941
+ lines.append("")
942
+ lines.append(".input:focus {")
943
+ lines.append(f" border-color: {colors.get('primary', '#2563EB')};")
944
+ lines.append(" outline: none;")
945
+ lines.append(f" box-shadow: 0 0 0 3px {colors.get('primary', '#2563EB')}20;")
946
+ lines.append("}")
947
+ lines.append("```")
948
+ lines.append("")
949
+
950
+ # Modals
951
+ lines.append("### Modals")
952
+ lines.append("")
953
+ lines.append("```css")
954
+ lines.append(".modal-overlay {")
955
+ lines.append(" background: rgba(0, 0, 0, 0.5);")
956
+ lines.append(" backdrop-filter: blur(4px);")
957
+ lines.append("}")
958
+ lines.append("")
959
+ lines.append(".modal {")
960
+ lines.append(" background: white;")
961
+ lines.append(" border-radius: 16px;")
962
+ lines.append(" padding: 32px;")
963
+ lines.append(" box-shadow: var(--shadow-xl);")
964
+ lines.append(" max-width: 500px;")
965
+ lines.append(" width: 90%;")
966
+ lines.append("}")
967
+ lines.append("```")
968
+ lines.append("")
969
+
970
+ # Style section
971
+ lines.append("---")
972
+ lines.append("")
973
+ lines.append("## Style Guidelines")
974
+ lines.append("")
975
+ lines.append(f"**Style:** {style.get('name', 'Minimalism')}")
976
+ lines.append("")
977
+ if style.get("keywords"):
978
+ lines.append(f"**Keywords:** {style.get('keywords', '')}")
979
+ lines.append("")
980
+ if style.get("best_for"):
981
+ lines.append(f"**Best For:** {style.get('best_for', '')}")
982
+ lines.append("")
983
+ if effects:
984
+ lines.append(f"**Key Effects:** {effects}")
985
+ lines.append("")
986
+
987
+ # Layout Pattern
988
+ lines.append("### Page Pattern")
989
+ lines.append("")
990
+ lines.append(f"**Pattern Name:** {pattern.get('name', '')}")
991
+ lines.append("")
992
+ if pattern.get('conversion'):
993
+ lines.append(f"- **Conversion Strategy:** {pattern.get('conversion', '')}")
994
+ if pattern.get('cta_placement'):
995
+ lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
996
+ lines.append(f"- **Section Order:** {pattern.get('sections', '')}")
997
+ lines.append("")
998
+
999
+ # Motion section (GSAP skeleton, only if --motion dial was set)
1000
+ if motion_snippet:
1001
+ lines.append("---")
1002
+ lines.append("")
1003
+ lines.append("## Motion")
1004
+ lines.append("")
1005
+ 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', '')}`")
1006
+ lines.append("")
1007
+ lines.append("```js")
1008
+ lines.append(motion_snippet.get("GSAP Snippet", ""))
1009
+ lines.append("```")
1010
+ lines.append("")
1011
+ if motion_snippet.get("Framework Notes"):
1012
+ lines.append(f"**Framework notes:** {motion_snippet.get('Framework Notes', '')}")
1013
+ lines.append("")
1014
+ motion_do = motion_snippet.get("Do", "")
1015
+ motion_dont = motion_snippet.get("Don't", "")
1016
+ if motion_do:
1017
+ lines.append(f"- ✅ {motion_do}")
1018
+ if motion_dont:
1019
+ lines.append(f"- ❌ {motion_dont}")
1020
+ if motion_snippet.get("Performance Notes"):
1021
+ lines.append(f"- ⚡ {motion_snippet.get('Performance Notes', '')}")
1022
+ lines.append("")
1023
+
1024
+ # Anti-Patterns section
1025
+ lines.append("---")
1026
+ lines.append("")
1027
+ lines.append("## Anti-Patterns (Do NOT Use)")
1028
+ lines.append("")
1029
+ if anti_patterns:
1030
+ anti_list = [a.strip() for a in anti_patterns.split("+")]
1031
+ for anti in anti_list:
1032
+ if anti:
1033
+ lines.append(f"- ❌ {anti}")
1034
+ lines.append("")
1035
+ lines.append("### Additional Forbidden Patterns")
1036
+ lines.append("")
1037
+ lines.append("- ❌ **Emojis as icons** — Use SVG icons (Heroicons, Lucide, Simple Icons)")
1038
+ lines.append("- ❌ **Missing cursor:pointer** — All clickable elements must have cursor:pointer")
1039
+ lines.append("- ❌ **Layout-shifting hovers** — Avoid scale transforms that shift layout")
1040
+ lines.append("- ❌ **Low contrast text** — Maintain 4.5:1 minimum contrast ratio")
1041
+ lines.append("- ❌ **Instant state changes** — Always use transitions (150-300ms)")
1042
+ lines.append("- ❌ **Invisible focus states** — Focus states must be visible for a11y")
1043
+ lines.append("")
1044
+
1045
+ # Pre-Delivery Checklist
1046
+ lines.append("---")
1047
+ lines.append("")
1048
+ lines.append("## Pre-Delivery Checklist")
1049
+ lines.append("")
1050
+ lines.append("Before delivering any UI code, verify:")
1051
+ lines.append("")
1052
+ lines.append("- [ ] No emojis used as icons (use SVG instead)")
1053
+ lines.append("- [ ] All icons from consistent icon set (Heroicons/Lucide)")
1054
+ lines.append("- [ ] `cursor-pointer` on all clickable elements")
1055
+ lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
1056
+ lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
1057
+ lines.append("- [ ] Focus states visible for keyboard navigation")
1058
+ lines.append("- [ ] `prefers-reduced-motion` respected")
1059
+ lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
1060
+ lines.append("- [ ] No content hidden behind fixed navbars")
1061
+ lines.append("- [ ] No horizontal scroll on mobile")
1062
+ lines.append("")
1063
+
1064
+ return "\n".join(lines)
1065
+
1066
+
1067
+ def format_page_override_md(design_system: dict, page_name: str, page_query: str = None) -> str:
1068
+ """Format a page-specific override file with intelligent AI-generated content."""
1069
+ project = design_system.get("project_name", "PROJECT")
1070
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1071
+ page_title = page_name.replace("-", " ").replace("_", " ").title()
1072
+
1073
+ # Detect page type and generate intelligent overrides
1074
+ page_overrides = _generate_intelligent_overrides(page_name, page_query, design_system)
1075
+
1076
+ lines = []
1077
+
1078
+ lines.append(f"# {page_title} Page Overrides")
1079
+ lines.append("")
1080
+ lines.append(f"> **PROJECT:** {project}")
1081
+ lines.append(f"> **Generated:** {timestamp}")
1082
+ lines.append(f"> **Page Type:** {page_overrides.get('page_type', 'General')}")
1083
+ lines.append("")
1084
+ lines.append("> ⚠️ **IMPORTANT:** Rules in this file **override** the Master file (`design-system/MASTER.md`).")
1085
+ lines.append("> Only deviations from the Master are documented here. For all other rules, refer to the Master.")
1086
+ lines.append("")
1087
+ lines.append("---")
1088
+ lines.append("")
1089
+
1090
+ # Page-specific rules with actual content
1091
+ lines.append("## Page-Specific Rules")
1092
+ lines.append("")
1093
+
1094
+ # Layout Overrides
1095
+ lines.append("### Layout Overrides")
1096
+ lines.append("")
1097
+ layout = page_overrides.get("layout", {})
1098
+ if layout:
1099
+ for key, value in layout.items():
1100
+ lines.append(f"- **{key}:** {value}")
1101
+ else:
1102
+ lines.append("- No overrides — use Master layout")
1103
+ lines.append("")
1104
+
1105
+ # Spacing Overrides
1106
+ lines.append("### Spacing Overrides")
1107
+ lines.append("")
1108
+ spacing = page_overrides.get("spacing", {})
1109
+ if spacing:
1110
+ for key, value in spacing.items():
1111
+ lines.append(f"- **{key}:** {value}")
1112
+ else:
1113
+ lines.append("- No overrides — use Master spacing")
1114
+ lines.append("")
1115
+
1116
+ # Typography Overrides
1117
+ lines.append("### Typography Overrides")
1118
+ lines.append("")
1119
+ typography = page_overrides.get("typography", {})
1120
+ if typography:
1121
+ for key, value in typography.items():
1122
+ lines.append(f"- **{key}:** {value}")
1123
+ else:
1124
+ lines.append("- No overrides — use Master typography")
1125
+ lines.append("")
1126
+
1127
+ # Color Overrides
1128
+ lines.append("### Color Overrides")
1129
+ lines.append("")
1130
+ colors = page_overrides.get("colors", {})
1131
+ if colors:
1132
+ for key, value in colors.items():
1133
+ lines.append(f"- **{key}:** {value}")
1134
+ else:
1135
+ lines.append("- No overrides — use Master colors")
1136
+ lines.append("")
1137
+
1138
+ # Component Overrides
1139
+ lines.append("### Component Overrides")
1140
+ lines.append("")
1141
+ components = page_overrides.get("components", [])
1142
+ if components:
1143
+ for comp in components:
1144
+ lines.append(f"- {comp}")
1145
+ else:
1146
+ lines.append("- No overrides — use Master component specs")
1147
+ lines.append("")
1148
+
1149
+ # Page-Specific Components
1150
+ lines.append("---")
1151
+ lines.append("")
1152
+ lines.append("## Page-Specific Components")
1153
+ lines.append("")
1154
+ unique_components = page_overrides.get("unique_components", [])
1155
+ if unique_components:
1156
+ for comp in unique_components:
1157
+ lines.append(f"- {comp}")
1158
+ else:
1159
+ lines.append("- No unique components for this page")
1160
+ lines.append("")
1161
+
1162
+ # Recommendations
1163
+ lines.append("---")
1164
+ lines.append("")
1165
+ lines.append("## Recommendations")
1166
+ lines.append("")
1167
+ recommendations = page_overrides.get("recommendations", [])
1168
+ if recommendations:
1169
+ for rec in recommendations:
1170
+ lines.append(f"- {rec}")
1171
+ lines.append("")
1172
+
1173
+ return "\n".join(lines)
1174
+
1175
+
1176
+ def _generate_intelligent_overrides(page_name: str, page_query: str, design_system: dict) -> dict:
1177
+ """
1178
+ Generate intelligent overrides based on page type using layered search.
1179
+
1180
+ Uses the existing search infrastructure to find relevant style, UX, and layout
1181
+ data instead of hardcoded page types.
1182
+ """
1183
+ from core import search
1184
+
1185
+ page_lower = page_name.lower()
1186
+ query_lower = (page_query or "").lower()
1187
+ combined_context = f"{page_lower} {query_lower}"
1188
+
1189
+ # Search across multiple domains for page-specific guidance
1190
+ style_search = search(combined_context, "style", max_results=1)
1191
+ ux_search = search(combined_context, "ux", max_results=3)
1192
+ landing_search = search(combined_context, "landing", max_results=1)
1193
+
1194
+ # Extract results from search response
1195
+ style_results = style_search.get("results", [])
1196
+ ux_results = ux_search.get("results", [])
1197
+ landing_results = landing_search.get("results", [])
1198
+
1199
+ # Detect page type from search results or context
1200
+ page_type = _detect_page_type(combined_context, style_results)
1201
+
1202
+ # Build overrides from search results
1203
+ layout = {}
1204
+ spacing = {}
1205
+ typography = {}
1206
+ colors = {}
1207
+ components = []
1208
+ unique_components = []
1209
+ recommendations = []
1210
+
1211
+ # Extract style-based overrides
1212
+ if style_results:
1213
+ style = style_results[0]
1214
+ style_name = style.get("Style Category", "")
1215
+ keywords = style.get("Keywords", "")
1216
+ best_for = style.get("Best For", "")
1217
+ effects = style.get("Effects & Animation", "")
1218
+
1219
+ # Infer layout from style keywords
1220
+ if any(kw in keywords.lower() for kw in ["data", "dense", "dashboard", "grid"]):
1221
+ layout["Max Width"] = "1400px or full-width"
1222
+ layout["Grid"] = "12-column grid for data flexibility"
1223
+ spacing["Content Density"] = "High — optimize for information display"
1224
+ elif any(kw in keywords.lower() for kw in ["minimal", "simple", "clean", "single"]):
1225
+ layout["Max Width"] = "800px (narrow, focused)"
1226
+ layout["Layout"] = "Single column, centered"
1227
+ spacing["Content Density"] = "Low — focus on clarity"
1228
+ else:
1229
+ layout["Max Width"] = "1200px (standard)"
1230
+ layout["Layout"] = "Full-width sections, centered content"
1231
+
1232
+ if effects:
1233
+ recommendations.append(f"Effects: {effects}")
1234
+
1235
+ # Extract UX guidelines as recommendations
1236
+ for ux in ux_results:
1237
+ category = ux.get("Category", "")
1238
+ do_text = ux.get("Do", "")
1239
+ dont_text = ux.get("Don't", "")
1240
+ if do_text:
1241
+ recommendations.append(f"{category}: {do_text}")
1242
+ if dont_text:
1243
+ components.append(f"Avoid: {dont_text}")
1244
+
1245
+ # Extract landing pattern info for section structure
1246
+ if landing_results:
1247
+ landing = landing_results[0]
1248
+ sections = landing.get("Section Order", "")
1249
+ cta_placement = landing.get("Primary CTA Placement", "")
1250
+ color_strategy = landing.get("Color Strategy", "")
1251
+
1252
+ if sections:
1253
+ layout["Sections"] = sections
1254
+ if cta_placement:
1255
+ recommendations.append(f"CTA Placement: {cta_placement}")
1256
+ if color_strategy:
1257
+ colors["Strategy"] = color_strategy
1258
+
1259
+ # Add page-type specific defaults if no search results
1260
+ if not layout:
1261
+ layout["Max Width"] = "1200px"
1262
+ layout["Layout"] = "Responsive grid"
1263
+
1264
+ if not recommendations:
1265
+ recommendations = [
1266
+ "Refer to MASTER.md for all design rules",
1267
+ "Add specific overrides as needed for this page"
1268
+ ]
1269
+
1270
+ return {
1271
+ "page_type": page_type,
1272
+ "layout": layout,
1273
+ "spacing": spacing,
1274
+ "typography": typography,
1275
+ "colors": colors,
1276
+ "components": components,
1277
+ "unique_components": unique_components,
1278
+ "recommendations": recommendations
1279
+ }
1280
+
1281
+
1282
+ def _detect_page_type(context: str, style_results: list) -> str:
1283
+ """Detect page type from context and search results."""
1284
+ context_lower = context.lower()
1285
+
1286
+ # Check for common page type patterns
1287
+ page_patterns = [
1288
+ (["dashboard", "admin", "analytics", "data", "metrics", "stats", "monitor", "overview"], "Dashboard / Data View"),
1289
+ (["checkout", "payment", "cart", "purchase", "order", "billing"], "Checkout / Payment"),
1290
+ (["settings", "profile", "account", "preferences", "config"], "Settings / Profile"),
1291
+ (["landing", "marketing", "homepage", "hero", "home", "promo"], "Landing / Marketing"),
1292
+ (["login", "signin", "signup", "register", "auth", "password"], "Authentication"),
1293
+ (["pricing", "plans", "subscription", "tiers", "packages"], "Pricing / Plans"),
1294
+ (["blog", "article", "post", "news", "content", "story"], "Blog / Article"),
1295
+ (["product", "item", "detail", "pdp", "shop", "store"], "Product Detail"),
1296
+ (["search", "results", "browse", "filter", "catalog", "list"], "Search Results"),
1297
+ (["empty", "404", "error", "not found", "zero"], "Empty State"),
1298
+ ]
1299
+
1300
+ for keywords, page_type in page_patterns:
1301
+ if any(kw in context_lower for kw in keywords):
1302
+ return page_type
1303
+
1304
+ # Fallback: try to infer from style results
1305
+ if style_results:
1306
+ style_name = style_results[0].get("Style Category", "").lower()
1307
+ best_for = style_results[0].get("Best For", "").lower()
1308
+
1309
+ if "dashboard" in best_for or "data" in best_for:
1310
+ return "Dashboard / Data View"
1311
+ elif "landing" in best_for or "marketing" in best_for:
1312
+ return "Landing / Marketing"
1313
+
1314
+ return "General"
1315
+
1316
+
1317
+ # ============ CLI SUPPORT ============
1318
+ if __name__ == "__main__":
1319
+ import argparse
1320
+
1321
+ parser = argparse.ArgumentParser(description="Generate Design System")
1322
+ parser.add_argument("query", help="Search query (e.g., 'SaaS dashboard')")
1323
+ parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name")
1324
+ parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format")
1325
+
1326
+ args = parser.parse_args()
1327
+
1328
+ result = generate_design_system(args.query, args.project_name, args.format)
1329
+ print(result)