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