spec-to-ui 0.1.0 → 0.2.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 (143) hide show
  1. package/LICENSE +2 -0
  2. package/README.ko.md +129 -0
  3. package/README.md +96 -29
  4. package/RELEASE.md +26 -0
  5. package/THIRD-PARTY.md +14 -0
  6. package/bin/cli.mjs +70 -91
  7. package/bundle-manifest.json +140 -0
  8. package/package.json +40 -8
  9. package/plugin.json +16 -0
  10. package/skills/design-taste-frontend/LICENSE +21 -0
  11. package/skills/design-taste-frontend/README.md +81 -0
  12. package/skills/design-taste-frontend/SKILL.md +546 -0
  13. package/skills/design-taste-frontend/assets/app.css +216 -0
  14. package/skills/design-taste-frontend/assets/base.css +105 -0
  15. package/skills/design-taste-frontend/assets/base.js +37 -0
  16. package/skills/design-taste-frontend/assets/charts.js +619 -0
  17. package/skills/design-taste-frontend/assets/scenes/stage.css +28 -0
  18. package/skills/design-taste-frontend/assets/scenes/stage.js +134 -0
  19. package/skills/design-taste-frontend/evals/evals.json +76 -0
  20. package/skills/design-taste-frontend/library/app.json +1327 -0
  21. package/skills/design-taste-frontend/library/directions.json +1078 -0
  22. package/skills/design-taste-frontend/library/heroes.json +1086 -0
  23. package/skills/design-taste-frontend/library/motions.json +92 -0
  24. package/skills/design-taste-frontend/library/palettes.json +1485 -0
  25. package/skills/design-taste-frontend/library/photos.json +7240 -0
  26. package/skills/design-taste-frontend/library/sections.json +4429 -0
  27. package/skills/design-taste-frontend/library/sites.json +8350 -0
  28. package/skills/design-taste-frontend/library/type.json +2024 -0
  29. package/skills/design-taste-frontend/references/app-screens.md +1199 -0
  30. package/skills/design-taste-frontend/references/colour.md +141 -0
  31. package/skills/design-taste-frontend/references/copy.md +177 -0
  32. package/skills/design-taste-frontend/references/critique.md +182 -0
  33. package/skills/design-taste-frontend/references/imagery.md +791 -0
  34. package/skills/design-taste-frontend/references/layout.md +292 -0
  35. package/skills/design-taste-frontend/references/motion.md +980 -0
  36. package/skills/design-taste-frontend/references/research.md +356 -0
  37. package/skills/design-taste-frontend/references/scenes.md +174 -0
  38. package/skills/design-taste-frontend/references/tells.md +115 -0
  39. package/skills/design-taste-frontend/references/type.md +170 -0
  40. package/skills/design-taste-frontend/scripts/assets.mjs +865 -0
  41. package/skills/design-taste-frontend/scripts/draw.mjs +584 -0
  42. package/skills/design-taste-frontend/scripts/inspect.mjs +308 -0
  43. package/skills/design-taste-frontend/scripts/lib/app-draw.mjs +203 -0
  44. package/skills/design-taste-frontend/scripts/lib/cdp.mjs +248 -0
  45. package/skills/design-taste-frontend/scripts/lib/inspection-files.mjs +9 -0
  46. package/skills/design-taste-frontend/scripts/lib/probe.mjs +929 -0
  47. package/skills/design-taste-frontend/scripts/lib/rules.mjs +243 -0
  48. package/skills/design-taste-frontend/scripts/lint.mjs +119 -0
  49. package/skills/design-taste-frontend/scripts/scenes.mjs +124 -0
  50. package/skills/spec-to-ui/SKILL.md +61 -0
  51. package/{skill → skills/spec-to-ui}/references/composition-and-validation.md +6 -0
  52. package/{skill → skills/spec-to-ui}/references/drafts-and-feedback.md +10 -0
  53. package/skills/spec-to-ui/references/requirements-supplement.md +21 -0
  54. package/{skill → skills/spec-to-ui}/references/review-and-handoff.md +9 -0
  55. package/skills/spec-to-ui/references/skill-composition.md +21 -0
  56. package/{skill → skills/spec-to-ui}/references/structure-and-decisions.md +4 -0
  57. package/skills/specframe/NOTICE.md +7 -0
  58. package/skills/specframe/SKILL.md +58 -0
  59. package/skills/specframe/agents/openai.yaml +3 -0
  60. package/skills/specframe/references/operating-contract.md +137 -0
  61. package/skills/specframe/references/visual.md +3 -0
  62. package/skills/specframe/references/web.md +15 -0
  63. package/skills/specframe/scripts/state.py +182 -0
  64. package/skills/ui-ux-pro-max/LICENSE +21 -0
  65. package/skills/ui-ux-pro-max/SKILL.md +218 -0
  66. package/skills/ui-ux-pro-max/data/app-interface.csv +33 -0
  67. package/skills/ui-ux-pro-max/data/catalog-summary.json +78 -0
  68. package/skills/ui-ux-pro-max/data/charts.csv +26 -0
  69. package/skills/ui-ux-pro-max/data/colors.csv +193 -0
  70. package/skills/ui-ux-pro-max/data/data-provenance.json +1348 -0
  71. package/skills/ui-ux-pro-max/data/google-font-licenses.json +20185 -0
  72. package/skills/ui-ux-pro-max/data/google-fonts.csv +1935 -0
  73. package/skills/ui-ux-pro-max/data/icons.csv +106 -0
  74. package/skills/ui-ux-pro-max/data/landing.csv +35 -0
  75. package/skills/ui-ux-pro-max/data/motion.csv +18 -0
  76. package/skills/ui-ux-pro-max/data/phosphor-icons-upstream.json +32582 -0
  77. package/skills/ui-ux-pro-max/data/products.csv +193 -0
  78. package/skills/ui-ux-pro-max/data/react-performance.csv +45 -0
  79. package/skills/ui-ux-pro-max/data/stacks/angular.csv +51 -0
  80. package/skills/ui-ux-pro-max/data/stacks/astro.csv +54 -0
  81. package/skills/ui-ux-pro-max/data/stacks/avalonia.csv +57 -0
  82. package/skills/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  83. package/skills/ui-ux-pro-max/data/stacks/html-tailwind.csv +60 -0
  84. package/skills/ui-ux-pro-max/data/stacks/javafx.csv +76 -0
  85. package/skills/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
  86. package/skills/ui-ux-pro-max/data/stacks/laravel.csv +51 -0
  87. package/skills/ui-ux-pro-max/data/stacks/nextjs.csv +62 -0
  88. package/skills/ui-ux-pro-max/data/stacks/nuxt-ui.csv +84 -0
  89. package/skills/ui-ux-pro-max/data/stacks/nuxtjs.csv +68 -0
  90. package/skills/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  91. package/skills/ui-ux-pro-max/data/stacks/react.csv +67 -0
  92. package/skills/ui-ux-pro-max/data/stacks/shadcn.csv +69 -0
  93. package/skills/ui-ux-pro-max/data/stacks/svelte.csv +56 -0
  94. package/skills/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  95. package/skills/ui-ux-pro-max/data/stacks/threejs.csv +54 -0
  96. package/skills/ui-ux-pro-max/data/stacks/uno.csv +60 -0
  97. package/skills/ui-ux-pro-max/data/stacks/uwp.csv +56 -0
  98. package/skills/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  99. package/skills/ui-ux-pro-max/data/stacks/winui.csv +60 -0
  100. package/skills/ui-ux-pro-max/data/stacks/wpf.csv +57 -0
  101. package/skills/ui-ux-pro-max/data/styles.csv +89 -0
  102. package/skills/ui-ux-pro-max/data/typography.csv +75 -0
  103. package/skills/ui-ux-pro-max/data/ui-reasoning.csv +193 -0
  104. package/skills/ui-ux-pro-max/data/ux-guidelines.csv +120 -0
  105. package/skills/ui-ux-pro-max/references/pro-rules.md +117 -0
  106. package/skills/ui-ux-pro-max/references/quick-reference.md +256 -0
  107. package/skills/ui-ux-pro-max/scripts/core.py +993 -0
  108. package/skills/ui-ux-pro-max/scripts/design_system.py +1668 -0
  109. package/skills/ui-ux-pro-max/scripts/reasoning_contract.py +123 -0
  110. package/skills/ui-ux-pro-max/scripts/search.py +184 -0
  111. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/google-api.json +36 -0
  112. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/google-catalog.json +33 -0
  113. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/google-existing.csv +3 -0
  114. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/google-metadata.json +17 -0
  115. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/google-overrides.json +7 -0
  116. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/icons-curated.csv +4 -0
  117. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/phosphor-core.json +23 -0
  118. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/phosphor-package.json +13 -0
  119. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/phosphor-react-exports.json +4 -0
  120. package/skills/ui-ux-pro-max/scripts/tests/fixtures/catalogs/phosphor-react-package.json +5 -0
  121. package/skills/ui-ux-pro-max/scripts/tests/fixtures/relevance-baseline.json +3366 -0
  122. package/skills/ui-ux-pro-max/scripts/tests/fixtures/relevance-cases.json +111 -0
  123. package/skills/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json +100 -0
  124. package/skills/ui-ux-pro-max/scripts/tests/test_catalog_refresh.py +354 -0
  125. package/skills/ui-ux-pro-max/scripts/tests/test_catalog_summary_line_endings.py +78 -0
  126. package/skills/ui-ux-pro-max/scripts/tests/test_core.py +343 -0
  127. package/skills/ui-ux-pro-max/scripts/tests/test_core_data_quality.py +198 -0
  128. package/skills/ui-ux-pro-max/scripts/tests/test_data_contracts.py +421 -0
  129. package/skills/ui-ux-pro-max/scripts/tests/test_design_system_mode.py +233 -0
  130. package/skills/ui-ux-pro-max/scripts/tests/test_design_system_stack.py +61 -0
  131. package/skills/ui-ux-pro-max/scripts/tests/test_native_desktop_stack_freshness.py +179 -0
  132. package/skills/ui-ux-pro-max/scripts/tests/test_relevance_evaluator.py +182 -0
  133. package/skills/ui-ux-pro-max/scripts/tests/test_skill_script_paths.py +82 -0
  134. package/skills/ui-ux-pro-max/scripts/tests/test_style_taxonomy.py +175 -0
  135. package/skills/ui-ux-pro-max/scripts/tests/test_text_layout_resilience.py +120 -0
  136. package/skills/ui-ux-pro-max/scripts/tests/test_web_stack_freshness.py +191 -0
  137. package/skills/ui-ux-pro-max/scripts/validate_data.py +1095 -0
  138. package/sources.json +58 -0
  139. package/skill/SKILL.md +0 -68
  140. package/skill-manifest.json +0 -10
  141. /package/{skill → skills/spec-to-ui}/LICENSE +0 -0
  142. /package/{skill → skills/spec-to-ui}/agents/openai.yaml +0 -0
  143. /package/{skill → skills/spec-to-ui}/references/reference-selection.md +0 -0
@@ -0,0 +1,1668 @@
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
+ import tempfile
25
+ from datetime import datetime
26
+ from pathlib import Path
27
+ from core import search, DATA_DIR
28
+ from reasoning_contract import apply_decision_rules, parse_decision_rules
29
+
30
+ # Force UTF-8 for stdout/stderr to handle emojis/box-drawing chars on Windows (cp1252 default)
31
+ if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
32
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
33
+ if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
34
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
35
+
36
+
37
+ # ============ CONFIGURATION ============
38
+ REASONING_FILE = "ui-reasoning.csv"
39
+
40
+ SEARCH_CONFIG = {
41
+ "product": {"max_results": 1},
42
+ "style": {"max_results": 3},
43
+ "color": {"max_results": 5},
44
+ "landing": {"max_results": 2},
45
+ "typography": {"max_results": 2}
46
+ }
47
+
48
+ SEMANTIC_COLOR_ENTRIES = (
49
+ ("Primary", "primary", "--color-primary"),
50
+ ("On Primary", "on_primary", "--color-on-primary"),
51
+ ("Secondary", "secondary", "--color-secondary"),
52
+ ("On Secondary", "on_secondary", "--color-on-secondary"),
53
+ ("Accent/CTA", "accent", "--color-accent"),
54
+ ("On Accent/CTA", "on_accent", "--color-on-accent"),
55
+ ("Background", "background", "--color-background"),
56
+ ("Foreground", "foreground", "--color-foreground"),
57
+ ("Card", "card", "--color-card"),
58
+ ("Card Foreground", "card_foreground", "--color-card-foreground"),
59
+ ("Muted", "muted", "--color-muted"),
60
+ ("Muted Foreground", "muted_foreground", "--color-muted-foreground"),
61
+ ("Border", "border", "--color-border"),
62
+ ("Destructive", "destructive", "--color-destructive"),
63
+ ("On Destructive", "on_destructive", "--color-on-destructive"),
64
+ ("Ring", "ring", "--color-ring"),
65
+ )
66
+
67
+ # ============ DESIGN DIALS (1-10) ============
68
+ # Inspired by taste-skill's DESIGN_VARIANCE / MOTION_INTENSITY / VISUAL_DENSITY
69
+ # knobs: three optional 1-10 sliders that bias the existing query-based search
70
+ # instead of replacing it. Each dial buckets into a low/mid/high tier.
71
+ DIAL_TIERS = {
72
+ "variance": [
73
+ (1, 3, {"label": "Centered / Minimal", "style_keywords": ["Minimalism", "Exaggerated Minimalism", "centered", "symmetric", "grid-based"]}),
74
+ (4, 7, {"label": "Balanced / Modern", "style_keywords": ["modern", "structured", "balanced"]}),
75
+ (8, 10, {"label": "Bold / Asymmetric", "style_keywords": ["Brutalism", "Bento Grids", "asymmetric", "experimental"]}),
76
+ ],
77
+ "motion": [
78
+ (1, 3, {"label": "Subtle", "tier": "Subtle"}),
79
+ (4, 7, {"label": "Standard", "tier": "Standard"}),
80
+ (8, 10, {"label": "Complex", "tier": "Complex"}),
81
+ ],
82
+ "density": [
83
+ (1, 3, {"label": "Spacious", "spacing": {"xs": "4px", "sm": "8px", "md": "24px", "lg": "32px", "xl": "48px", "2xl": "64px", "3xl": "96px"}}),
84
+ (4, 7, {"label": "Standard", "spacing": {"xs": "4px", "sm": "8px", "md": "16px", "lg": "24px", "xl": "32px", "2xl": "48px", "3xl": "64px"}}),
85
+ (8, 10, {"label": "Dense / Dashboard", "spacing": {"xs": "2px", "sm": "4px", "md": "8px", "lg": "12px", "xl": "16px", "2xl": "24px", "3xl": "32px"}}),
86
+ ],
87
+ }
88
+
89
+
90
+ def _resolve_dial(dial_name: str, value) -> dict:
91
+ """Bucket a 1-10 dial value into its tier config. Returns None if value is None."""
92
+ if value is None:
93
+ return None
94
+ value = max(1, min(10, int(value)))
95
+ for lo, hi, info in DIAL_TIERS[dial_name]:
96
+ if lo <= value <= hi:
97
+ return {**info, "value": value}
98
+ return None
99
+
100
+
101
+ # ============ COLOR MODE RESOLUTION ============
102
+ # Style, palette and anti-patterns are resolved from separate CSVs. Without a
103
+ # shared notion of "which mode did we land on", a dark-primary style can be
104
+ # paired with a light palette and a "don't use dark mode" anti-pattern.
105
+
106
+ # Phrases in styles.csv "Light Mode ✓" / "Dark Mode ✓" that mark a style as
107
+ # dark-first rather than merely dark-capable ("✓ Full" means both work).
108
+ _DARK_PRIMARY_MARKERS = (
109
+ "dark mode primary", "dark primary", "dark-only", "dark only",
110
+ "dark preferred", "dark focused", "dark-first", "dark rich",
111
+ "light mode only as exception",
112
+ )
113
+
114
+ # Query phrases that are an explicit request for a dark theme.
115
+ _DARK_QUERY_MARKERS = (
116
+ "dark mode", "dark theme", "dark ui", "dark-mode", "darkmode",
117
+ "night mode", "midnight", "oled",
118
+ )
119
+
120
+ # Anti-pattern clauses that contradict a resolved dark mode.
121
+ _DARK_ANTI_PATTERN_MARKERS = ("dark mode", "dark modes", "dark theme")
122
+
123
+ # Relative luminance below which a Background hex counts as a dark surface.
124
+ # #1F2937 (the lightest dark background in colors.csv) sits at ~0.026 and
125
+ # #E8ECF1 (the darkest light background) at ~0.79, so the gap is wide.
126
+ _DARK_BACKGROUND_MAX_LUMINANCE = 0.18
127
+
128
+
129
+ def _relative_luminance(hex_color: str):
130
+ """WCAG relative luminance of a #RRGGBB string, or None if unparseable."""
131
+ if not hex_color:
132
+ return None
133
+ value = hex_color.strip().lstrip("#")
134
+ if len(value) == 3:
135
+ value = "".join(c * 2 for c in value)
136
+ if len(value) != 6:
137
+ return None
138
+ try:
139
+ channels = [int(value[i:i + 2], 16) / 255 for i in (0, 2, 4)]
140
+ except ValueError:
141
+ return None
142
+ linear = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
143
+ for c in channels]
144
+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
145
+
146
+
147
+ def _palette_is_dark(palette: dict) -> bool:
148
+ """True when a colors.csv row's Background is a dark surface."""
149
+ luminance = _relative_luminance((palette or {}).get("Background", ""))
150
+ return luminance is not None and luminance < _DARK_BACKGROUND_MAX_LUMINANCE
151
+
152
+
153
+ def _contrast_ratio(first: str, second: str):
154
+ """WCAG contrast ratio for two hex colors, or None if either is invalid."""
155
+ first_luminance = _relative_luminance(first)
156
+ second_luminance = _relative_luminance(second)
157
+ if first_luminance is None or second_luminance is None:
158
+ return None
159
+ lighter = max(first_luminance, second_luminance)
160
+ darker = min(first_luminance, second_luminance)
161
+ return (lighter + 0.05) / (darker + 0.05)
162
+
163
+
164
+ def _style_is_dark_primary(style: dict) -> bool:
165
+ """True when a styles.csv row describes itself as dark-first."""
166
+ if not style:
167
+ return False
168
+ preferred_mode = style.get("Preferred Mode", "").strip().lower()
169
+ if preferred_mode in {"dark", "light"}:
170
+ return preferred_mode == "dark"
171
+ if (style.get("Light Mode ✓") == "not-recommended"
172
+ and style.get("Dark Mode ✓") == "supported"):
173
+ return True
174
+ declared = "{} {}".format(
175
+ style.get("Light Mode ✓", ""), style.get("Dark Mode ✓", "")
176
+ ).lower()
177
+ return any(marker in declared for marker in _DARK_PRIMARY_MARKERS)
178
+
179
+
180
+ def _query_wants_dark(query: str) -> bool:
181
+ """True when the query explicitly asks for a dark theme."""
182
+ lowered = (query or "").lower()
183
+ return any(marker in lowered for marker in _DARK_QUERY_MARKERS)
184
+
185
+
186
+ def _resolve_color_mode(query: str, style: dict) -> str:
187
+ """Resolve the mode the rest of the output has to agree with."""
188
+ if _query_wants_dark(query) or _style_is_dark_primary(style):
189
+ return "dark"
190
+ return "light"
191
+
192
+
193
+ def _derive_dark_palette(palette: dict) -> dict:
194
+ """Keep product brand tokens while deriving accessible dark surfaces."""
195
+ derived = dict(palette)
196
+ background = "#0F172A"
197
+ ring_candidates = (
198
+ palette.get("Ring"), palette.get("Accent"), palette.get("Primary"),
199
+ "#60A5FA",
200
+ )
201
+ ring = next(
202
+ (candidate for candidate in ring_candidates
203
+ if (_contrast_ratio(candidate, background) or 0) >= 3),
204
+ "#60A5FA",
205
+ )
206
+ derived.update({
207
+ "Background": background,
208
+ "Foreground": "#F8FAFC",
209
+ "Card": "#111827",
210
+ "Card Foreground": "#F8FAFC",
211
+ "Muted": "#1E293B",
212
+ "Muted Foreground": "#CBD5E1",
213
+ "Border": "#334155",
214
+ "Ring": ring,
215
+ "_mode_derivation": "derived-dark",
216
+ })
217
+ return derived
218
+
219
+
220
+ def _select_palette_for_mode(palettes: list, mode: str,
221
+ category: str = None) -> dict:
222
+ """Pick the highest-ranked palette matching the resolved mode.
223
+
224
+ Only the dark case filters. Light is left on the existing "top hit wins"
225
+ behaviour so queries that never mention a mode keep their current palette.
226
+ Falls back to the top hit when the data has no matching ramp.
227
+ """
228
+ if not palettes:
229
+ return {}
230
+ category_palette = next(
231
+ (palette for palette in palettes
232
+ if palette.get("Product Type") == category),
233
+ None,
234
+ )
235
+ if category_palette:
236
+ if mode == "dark" and not _palette_is_dark(category_palette):
237
+ return _derive_dark_palette(category_palette)
238
+ return category_palette
239
+ if mode == "dark":
240
+ for palette in palettes:
241
+ if _palette_is_dark(palette):
242
+ return palette
243
+ return palettes[0]
244
+
245
+
246
+ def _filter_anti_patterns_for_mode(anti_patterns: str, mode: str) -> str:
247
+ """Drop "avoid dark mode" advice once dark mode is the resolved answer."""
248
+ if mode != "dark" or not anti_patterns:
249
+ return anti_patterns
250
+ kept = [
251
+ clause for clause in anti_patterns.split("+")
252
+ if not any(marker in clause.lower() for marker in _DARK_ANTI_PATTERN_MARKERS)
253
+ ]
254
+ return " + ".join(clause.strip() for clause in kept if clause.strip())
255
+
256
+
257
+ def _mode_support_labels(style: dict, anti_patterns: str):
258
+ """Light/dark support labels that agree with the product's anti-patterns.
259
+
260
+ A light result keeps its "avoid dark mode" clause, so a dark-capable style
261
+ must not read as a plain "Dark supported" next to it.
262
+ """
263
+ light = style.get("light_mode", "")
264
+ dark = style.get("dark_mode", "")
265
+ avoids_dark = any(
266
+ marker in (anti_patterns or "").lower() for marker in _DARK_ANTI_PATTERN_MARKERS
267
+ )
268
+ if dark and dark != "not-recommended" and avoids_dark:
269
+ dark = f"{dark}, but avoid for this product"
270
+ return light, dark
271
+
272
+
273
+ def _button_outline_text_color(colors: dict) -> str:
274
+ """Primary for outline-button text when it is readable, else the foreground."""
275
+ primary = colors.get("primary", "#2563EB")
276
+ background = colors.get("background", "#FFFFFF")
277
+ if (_contrast_ratio(primary, background) or 0) >= 4.5:
278
+ return primary
279
+ return colors.get("foreground") or primary
280
+
281
+
282
+ # ============ DESIGN SYSTEM GENERATOR ============
283
+ class DesignSystemGenerator:
284
+ """Generates design system recommendations from aggregated searches."""
285
+
286
+ def __init__(self):
287
+ self.reasoning_data = self._load_reasoning()
288
+ self.style_data = self._load_styles()
289
+ self.style_lookup = self._build_style_lookup(self.style_data)
290
+ self.landing_lookup = self._load_landing_patterns()
291
+
292
+ def _load_reasoning(self) -> list:
293
+ """Load reasoning rules from CSV."""
294
+ filepath = DATA_DIR / REASONING_FILE
295
+ if not filepath.exists():
296
+ return []
297
+ with open(filepath, 'r', encoding='utf-8') as f:
298
+ return list(csv.DictReader(f))
299
+
300
+ def _load_styles(self) -> list:
301
+ filepath = DATA_DIR / "styles.csv"
302
+ if not filepath.exists():
303
+ return []
304
+ with open(filepath, 'r', encoding='utf-8') as f:
305
+ return list(csv.DictReader(f))
306
+
307
+ def _load_landing_patterns(self) -> dict:
308
+ filepath = DATA_DIR / "landing.csv"
309
+ if not filepath.exists():
310
+ return {}
311
+ with open(filepath, 'r', encoding='utf-8') as f:
312
+ lookup = {}
313
+ for row in csv.DictReader(f):
314
+ identities = [row.get("Pattern ID", ""), row.get("Pattern Name", "")]
315
+ identities.extend(row.get("Aliases", "").split("|"))
316
+ for identity in identities:
317
+ if identity.strip():
318
+ lookup[identity.strip().casefold()] = row
319
+ return lookup
320
+
321
+ @staticmethod
322
+ def _build_style_lookup(styles: list) -> dict:
323
+ lookup = {}
324
+ for style in styles:
325
+ keys = [style.get("Style ID", ""), style.get("Style Category", "")]
326
+ keys.extend(style.get("Aliases", "").split("|"))
327
+ for key in keys:
328
+ if key.strip():
329
+ lookup[key.strip().casefold()] = style
330
+ return lookup
331
+
332
+ def _resolve_style(self, reference: str) -> dict:
333
+ style = self.style_lookup.get(str(reference or "").strip().casefold(), {})
334
+ seen = set()
335
+ while style and style.get("Status", "active") == "deprecated":
336
+ style_id = style.get("Style ID", "")
337
+ parent_id = style.get("Parent Style ID", "")
338
+ if not parent_id or style_id in seen:
339
+ return {}
340
+ seen.add(style_id)
341
+ style = self.style_lookup.get(parent_id.casefold(), {})
342
+ return style
343
+
344
+ def _multi_domain_search(self, query: str, category: str,
345
+ reasoning: dict, style_priority: list = None) -> dict:
346
+ """Execute searches across multiple domains."""
347
+ results = {}
348
+ constraints = " ".join(
349
+ item.replace("-", " ")
350
+ for item in reasoning.get("constraints", [])
351
+ )
352
+ resolved_query = " ".join(
353
+ part for part in (query, category, constraints) if part
354
+ )
355
+ for domain, config in SEARCH_CONFIG.items():
356
+ if domain == "style" and style_priority:
357
+ priority_query = " ".join(style_priority[:2])
358
+ results[domain] = search(
359
+ f"{resolved_query} {priority_query}", domain, config["max_results"])
360
+ elif domain == "color":
361
+ results[domain] = search(
362
+ f"{reasoning.get('color_mood', '')} {resolved_query}",
363
+ domain, config["max_results"])
364
+ elif domain == "landing":
365
+ # The reasoning pattern is the landing query contract. Mixing the
366
+ # product prompt into it can push token coverage below the
367
+ # abstention threshold even when the pattern names an exact row.
368
+ pattern = reasoning.get("pattern", "")
369
+ landing_query = pattern if pattern.casefold() in self.landing_lookup else (
370
+ f"{pattern} {resolved_query}"
371
+ )
372
+ results[domain] = search(
373
+ landing_query or query, domain, config["max_results"])
374
+ elif domain == "typography":
375
+ results[domain] = search(
376
+ f"{reasoning.get('typography_mood', '')} {resolved_query}",
377
+ domain, config["max_results"])
378
+ else:
379
+ results[domain] = search(query, domain, config["max_results"])
380
+ return results
381
+
382
+ def _find_reasoning_rule(self, category: str) -> dict:
383
+ """Find matching reasoning rule for a category."""
384
+ category_lower = category.strip().casefold()
385
+ for rule in self.reasoning_data:
386
+ if rule.get("UI_Category", "").strip().casefold() == category_lower:
387
+ return rule
388
+ return {}
389
+
390
+ def _apply_reasoning(self, category: str, query: str) -> dict:
391
+ """Apply reasoning rules to search results."""
392
+ rule = self._find_reasoning_rule(category)
393
+
394
+ if not rule:
395
+ return {
396
+ "pattern": "Hero + Features + CTA",
397
+ "style_priority": ["Minimalism", "Flat Design"],
398
+ "color_mood": "Professional",
399
+ "typography_mood": "Clean",
400
+ "key_effects": "Subtle hover transitions",
401
+ "anti_patterns": "",
402
+ "decision_rules": {},
403
+ "activated_rules": [],
404
+ "constraints": [],
405
+ "preferred_mode": None,
406
+ "is_default": True,
407
+ "severity": "MEDIUM"
408
+ }
409
+
410
+ decision_rules = parse_decision_rules(rule.get("Decision_Rules", "{}"))
411
+ applied = apply_decision_rules(decision_rules, query)
412
+ style_priority = [s.strip() for s in rule.get("Style_Priority", "").split("+")]
413
+ applied_style_names = [
414
+ self._resolve_style(style_id).get("Style Category", style_id)
415
+ for style_id in applied["style_ids"]
416
+ ]
417
+
418
+ return {
419
+ "pattern": applied["pattern"] or rule.get("Recommended_Pattern", ""),
420
+ "style_priority": applied_style_names + style_priority,
421
+ "color_mood": rule.get("Color_Mood", ""),
422
+ "typography_mood": rule.get("Typography_Mood", ""),
423
+ "key_effects": rule.get("Key_Effects", ""),
424
+ "anti_patterns": rule.get("Anti_Patterns", ""),
425
+ "decision_rules": decision_rules,
426
+ "activated_rules": applied["activated"],
427
+ "constraints": applied["constraints"],
428
+ "preferred_mode": applied["mode"],
429
+ "is_default": False,
430
+ "severity": rule.get("Severity", "MEDIUM")
431
+ }
432
+
433
+ def _select_best_match(self, results: list, priority_keywords: list) -> dict:
434
+ """Select best matching result based on priority keywords."""
435
+ if not results:
436
+ return {}
437
+
438
+ if not priority_keywords:
439
+ return results[0]
440
+
441
+ # Canonical reasoning has authority over lexical candidates. Returning
442
+ # the resolved row directly prevents a platform variant in BM25 top-3
443
+ # from displacing the explicit family recommendation.
444
+ for priority in priority_keywords:
445
+ resolved = self._resolve_style(priority)
446
+ if resolved and resolved.get("Status", "active") != "deprecated":
447
+ return dict(resolved)
448
+
449
+ # Second: score by keyword match in all fields
450
+ scored = []
451
+ for result in results:
452
+ result_str = str(result).lower()
453
+ score = 0
454
+ for kw in priority_keywords:
455
+ kw_tokens = set(re.findall(r"[a-z0-9]+", kw.lower()))
456
+ name_tokens = set(re.findall(
457
+ r"[a-z0-9]+", result.get("Style Category", "").lower()))
458
+ if kw_tokens and kw_tokens <= name_tokens:
459
+ score += 10
460
+ elif kw_tokens & set(re.findall(
461
+ r"[a-z0-9]+", result.get("Keywords", "").lower())):
462
+ score += 3
463
+ elif any(token in result_str for token in kw_tokens):
464
+ score += 1
465
+ scored.append((score, result))
466
+
467
+ scored.sort(key=lambda x: x[0], reverse=True)
468
+ return scored[0][1] if scored and scored[0][0] > 0 else results[0]
469
+
470
+ def _extract_results(self, search_result: dict) -> list:
471
+ """Extract results list from search result dict."""
472
+ return search_result.get("results", [])
473
+
474
+ def generate(self, query: str, project_name: str = None,
475
+ variance: int = None, motion: int = None, density: int = None) -> dict:
476
+ """Generate complete design system recommendation.
477
+
478
+ variance/motion/density are optional 1-10 dials (see DIAL_TIERS) that bias
479
+ style selection, pull in a matching motion.csv snippet, and override the
480
+ spacing scale, without changing behavior when left unset.
481
+ """
482
+ variance_info = _resolve_dial("variance", variance)
483
+ motion_info = _resolve_dial("motion", motion)
484
+ density_info = _resolve_dial("density", density)
485
+
486
+ # Step 1: First search product to get category
487
+ product_result = search(query, "product", 1)
488
+ product_results = product_result.get("results", [])
489
+ category = "General"
490
+ if product_results:
491
+ category = product_results[0].get("Product Type", "General")
492
+
493
+ # Step 2: Get reasoning rules for this category
494
+ reasoning = self._apply_reasoning(category, query)
495
+ style_priority = reasoning.get("style_priority", [])
496
+
497
+ # DESIGN_VARIANCE dial: bias style retrieval/selection toward
498
+ # centered-minimal (low) or bold-asymmetric (high) keywords.
499
+ effective_style_priority = style_priority
500
+ if variance_info:
501
+ effective_style_priority = variance_info["style_keywords"] + style_priority
502
+
503
+ # Step 3: Multi-domain search with style priority hints
504
+ search_results = self._multi_domain_search(
505
+ query, category, reasoning, effective_style_priority)
506
+ search_results["product"] = product_result # Reuse product search
507
+
508
+ # Step 4: Select best matches from each domain using priority
509
+ style_results = self._extract_results(search_results.get("style", {}))
510
+ color_results = self._extract_results(search_results.get("color", {}))
511
+ typography_results = self._extract_results(search_results.get("typography", {}))
512
+ landing_results = self._extract_results(search_results.get("landing", {}))
513
+
514
+ best_style = self._select_best_match(style_results, effective_style_priority)
515
+ # Resolve the mode from the style + query first, then pick a palette that
516
+ # agrees with it. Ranking colors independently is what let a dark-primary
517
+ # style ship with a light background.
518
+ color_mode = reasoning.get("preferred_mode") or _resolve_color_mode(query, best_style)
519
+ best_color = _select_palette_for_mode(color_results, color_mode, category)
520
+ best_typography = typography_results[0] if typography_results else {}
521
+ best_landing = next(
522
+ (row for row in landing_results
523
+ if row.get("Pattern Name") == reasoning.get("pattern")),
524
+ landing_results[0] if landing_results else {},
525
+ )
526
+
527
+ # MOTION_INTENSITY dial: pull a matching GSAP skeleton from motion.csv
528
+ # (domain key is "gsap", not "motion" - PR #296 already owns the "motion"
529
+ # domain for Emil Kowalski's motion-design principles, motion-principles.csv).
530
+ motion_snippet = {}
531
+ if motion_info:
532
+ motion_result = search(f"{query} {motion_info['tier']}", "gsap", 5)
533
+ motion_matches = motion_result.get("results", [])
534
+ tiered = [m for m in motion_matches if m.get("Intensity Tier") == motion_info["tier"]]
535
+ if tiered:
536
+ motion_snippet = tiered[0]
537
+ elif motion_matches:
538
+ motion_snippet = motion_matches[0]
539
+
540
+ # Step 5: Build final recommendation
541
+ # Combine effects from both reasoning and style search
542
+ style_effects = best_style.get("Effects & Animation", "")
543
+ reasoning_effects = reasoning.get("key_effects", "")
544
+ combined_effects = style_effects if style_effects else reasoning_effects
545
+
546
+ return {
547
+ "project_name": project_name or query.upper(),
548
+ "category": category,
549
+ "pattern": {
550
+ "name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
551
+ "sections": best_landing.get("Section Order", "Hero > Features > CTA"),
552
+ "cta_placement": best_landing.get("Primary CTA Placement", "Above fold"),
553
+ "color_strategy": best_landing.get("Color Strategy", ""),
554
+ "conversion": best_landing.get("Conversion Optimization", "")
555
+ },
556
+ "style": {
557
+ "id": best_style.get("Style ID", "minimalism-and-swiss-style"),
558
+ "name": best_style.get("Style Category", "Minimalism"),
559
+ "type": best_style.get("Type", "General"),
560
+ "effects": style_effects,
561
+ "keywords": best_style.get("Keywords", ""),
562
+ "best_for": best_style.get("Best For", ""),
563
+ "performance": best_style.get("Performance", ""),
564
+ "accessibility": best_style.get("Accessibility", ""),
565
+ "light_mode": best_style.get("Light Mode ✓", ""),
566
+ "dark_mode": best_style.get("Dark Mode ✓", ""),
567
+ },
568
+ "colors": {
569
+ "primary": best_color.get("Primary", "#2563EB"),
570
+ "on_primary": best_color.get("On Primary", ""),
571
+ "secondary": best_color.get("Secondary", "#3B82F6"),
572
+ "on_secondary": best_color.get("On Secondary", ""),
573
+ "accent": best_color.get("Accent", "#F97316"),
574
+ "on_accent": best_color.get("On Accent", ""),
575
+ "background": best_color.get("Background", "#F8FAFC"),
576
+ "foreground": best_color.get("Foreground", "#1E293B"),
577
+ "card": best_color.get("Card", ""),
578
+ "card_foreground": best_color.get("Card Foreground", ""),
579
+ "muted": best_color.get("Muted", ""),
580
+ "muted_foreground": best_color.get("Muted Foreground", ""),
581
+ "border": best_color.get("Border", ""),
582
+ "destructive": best_color.get("Destructive", ""),
583
+ "on_destructive": best_color.get("On Destructive", ""),
584
+ "ring": best_color.get("Ring", ""),
585
+ "notes": best_color.get("Notes", ""),
586
+ # Keep legacy keys for backward compat in MASTER.md
587
+ "cta": best_color.get("Accent", "#F97316"),
588
+ "text": best_color.get("Foreground", "#1E293B"),
589
+ "on_cta": best_color.get("On Accent", ""),
590
+ },
591
+ "typography": {
592
+ "heading": best_typography.get("Heading Font", "Inter"),
593
+ "body": best_typography.get("Body Font", "Inter"),
594
+ "mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
595
+ "best_for": best_typography.get("Best For", ""),
596
+ "google_fonts_url": best_typography.get("Google Fonts URL", ""),
597
+ "css_import": best_typography.get("CSS Import", "")
598
+ },
599
+ "key_effects": combined_effects,
600
+ "anti_patterns": _filter_anti_patterns_for_mode(
601
+ reasoning.get("anti_patterns", ""), color_mode
602
+ ),
603
+ "decision_rules": reasoning.get("decision_rules", {}),
604
+ "activated_rules": reasoning.get("activated_rules", []),
605
+ "constraints": reasoning.get("constraints", []),
606
+ "reasoning_default": reasoning.get("is_default", False),
607
+ "source_identities": {
608
+ "product": category if product_results else None,
609
+ "reasoning": category if not reasoning.get("is_default") else None,
610
+ "style": best_style.get("Style ID") or best_style.get("Style Category"),
611
+ "color": best_color.get("Product Type"),
612
+ "typography": best_typography.get("Font Pairing Name"),
613
+ "landing": best_landing.get("Pattern Name"),
614
+ },
615
+ "source_derivations": {
616
+ "color_mode": best_color.get("_mode_derivation"),
617
+ },
618
+ "severity": reasoning.get("severity", "MEDIUM"),
619
+ "dials": {
620
+ "variance": variance_info["value"] if variance_info else None,
621
+ "variance_label": variance_info["label"] if variance_info else None,
622
+ "motion": motion_info["value"] if motion_info else None,
623
+ "motion_label": motion_info["label"] if motion_info else None,
624
+ "density": density_info["value"] if density_info else None,
625
+ "density_label": density_info["label"] if density_info else None,
626
+ },
627
+ "motion_snippet": motion_snippet,
628
+ "spacing_scale": density_info["spacing"] if density_info else None,
629
+ }
630
+
631
+
632
+ # ============ OUTPUT FORMATTERS ============
633
+ BOX_WIDTH = 90 # Wider box for more content
634
+
635
+
636
+ def hex_to_ansi(hex_color: str) -> str:
637
+ """Convert hex color to ANSI True Color swatch (██) with fallback."""
638
+ if not hex_color or not hex_color.startswith('#'):
639
+ return ""
640
+ colorterm = os.environ.get('COLORTERM', '')
641
+ if colorterm not in ('truecolor', '24bit'):
642
+ return ""
643
+ hex_color = hex_color.lstrip('#')
644
+ if len(hex_color) != 6:
645
+ return ""
646
+ r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
647
+ return f"\033[38;2;{r};{g};{b}m██\033[0m "
648
+
649
+
650
+ def ansi_ljust(s: str, width: int) -> str:
651
+ """Like str.ljust but accounts for zero-width ANSI escape sequences."""
652
+ import re
653
+ visible_len = len(re.sub(r'\033\[[0-9;]*m', '', s))
654
+ pad = width - visible_len
655
+ return s + (" " * max(0, pad))
656
+
657
+
658
+ def section_header(name: str, width: int) -> str:
659
+ """Create a Unicode section separator: ├─── NAME ───...┤"""
660
+ label = f"─── {name} "
661
+ fill = "─" * (width - len(label) - 1)
662
+ return f"├{label}{fill}┤"
663
+
664
+
665
+ def format_ascii_box(design_system: dict) -> str:
666
+ """Format design system as Unicode box with ANSI color swatches."""
667
+ project = design_system.get("project_name", "PROJECT")
668
+ pattern = design_system.get("pattern", {})
669
+ style = design_system.get("style", {})
670
+ colors = design_system.get("colors", {})
671
+ typography = design_system.get("typography", {})
672
+ effects = design_system.get("key_effects", "")
673
+ anti_patterns = design_system.get("anti_patterns", "")
674
+ dials = design_system.get("dials", {})
675
+ motion_snippet = design_system.get("motion_snippet", {})
676
+
677
+ def wrap_text(text: str, prefix: str, width: int) -> list:
678
+ """Wrap long text into multiple lines, splitting tokens (URLs) wider than a line."""
679
+ if not text:
680
+ return []
681
+ room = width - 2 - len(prefix)
682
+ words = []
683
+ for word in text.split():
684
+ words.extend(word[i:i + room] for i in range(0, len(word), room))
685
+ lines = []
686
+ current_line = prefix
687
+ for word in words:
688
+ if len(current_line) + len(word) + 1 <= width - 2:
689
+ current_line += (" " if current_line != prefix else "") + word
690
+ else:
691
+ if current_line != prefix:
692
+ lines.append(current_line)
693
+ current_line = prefix + word
694
+ if current_line != prefix:
695
+ lines.append(current_line)
696
+ return lines
697
+
698
+ def add_wrapped(text: str, prefix: str = "│ ") -> None:
699
+ for line in wrap_text(text, prefix, BOX_WIDTH):
700
+ lines.append(line.ljust(BOX_WIDTH) + "│")
701
+
702
+ # Build sections from pattern
703
+ sections = pattern.get("sections", "").split(" > ")
704
+ sections = [s.strip() for s in sections if s.strip()]
705
+
706
+ # Build output lines
707
+ lines = []
708
+ w = BOX_WIDTH - 1
709
+
710
+ # Header with double-line box
711
+ lines.append("╔" + "═" * w + "╗")
712
+ lines.append(ansi_ljust(f"║ TARGET: {project} - RECOMMENDED DESIGN SYSTEM", BOX_WIDTH) + "║")
713
+ lines.append("╚" + "═" * w + "╝")
714
+ lines.append("┌" + "─" * w + "┐")
715
+
716
+ # Design Dials section (only if at least one dial was set)
717
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
718
+ lines.append(section_header("DESIGN DIALS", BOX_WIDTH))
719
+ if dials.get("variance") is not None:
720
+ lines.append(f"│ Variance: {dials['variance']}/10 — {dials['variance_label']}".ljust(BOX_WIDTH) + "│")
721
+ if dials.get("motion") is not None:
722
+ lines.append(f"│ Motion: {dials['motion']}/10 — {dials['motion_label']}".ljust(BOX_WIDTH) + "│")
723
+ if dials.get("density") is not None:
724
+ lines.append(f"│ Density: {dials['density']}/10 — {dials['density_label']}".ljust(BOX_WIDTH) + "│")
725
+
726
+ # Pattern section
727
+ lines.append(section_header("PATTERN", BOX_WIDTH))
728
+ add_wrapped(f"Name: {pattern.get('name', '')}", "│ ")
729
+ if pattern.get('conversion'):
730
+ add_wrapped(f"Conversion: {pattern.get('conversion', '')}")
731
+ if pattern.get('cta_placement'):
732
+ add_wrapped(f"CTA: {pattern.get('cta_placement', '')}")
733
+ lines.append("│ Sections:".ljust(BOX_WIDTH) + "│")
734
+ for i, section in enumerate(sections, 1):
735
+ add_wrapped(f"{i}. {section}", "│ ")
736
+
737
+ # Style section
738
+ lines.append(section_header("STYLE", BOX_WIDTH))
739
+ add_wrapped(f"Name: {style.get('name', '')}", "│ ")
740
+ light, dark = _mode_support_labels(style, anti_patterns)
741
+ if light or dark:
742
+ add_wrapped(f"Mode Support: Light {light} | Dark {dark}")
743
+ if style.get("keywords"):
744
+ add_wrapped(f"Keywords: {style.get('keywords', '')}")
745
+ if style.get("best_for"):
746
+ add_wrapped(f"Best For: {style.get('best_for', '')}")
747
+ if style.get("performance") or style.get("accessibility"):
748
+ add_wrapped(f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}")
749
+
750
+ # Colors section (extended palette with ANSI swatches)
751
+ lines.append(section_header("COLORS", BOX_WIDTH))
752
+ for label, key, css_var in SEMANTIC_COLOR_ENTRIES:
753
+ hex_val = colors.get(key, "")
754
+ if not hex_val:
755
+ continue
756
+ swatch = hex_to_ansi(hex_val)
757
+ content = f"│ {swatch}{label + ':':18s} {hex_val:10s} ({css_var})"
758
+ lines.append(ansi_ljust(content, BOX_WIDTH) + "│")
759
+ if colors.get("notes"):
760
+ for line in wrap_text(f"Notes: {colors.get('notes', '')}", "│ ", BOX_WIDTH):
761
+ lines.append(line.ljust(BOX_WIDTH) + "│")
762
+
763
+ # Typography section
764
+ lines.append(section_header("TYPOGRAPHY", BOX_WIDTH))
765
+ add_wrapped(f"{typography.get('heading', '')} / {typography.get('body', '')}", "│ ")
766
+ if typography.get("mood"):
767
+ add_wrapped(f"Mood: {typography.get('mood', '')}")
768
+ if typography.get("best_for"):
769
+ add_wrapped(f"Best For: {typography.get('best_for', '')}")
770
+ if typography.get("google_fonts_url"):
771
+ add_wrapped(f"Google Fonts: {typography.get('google_fonts_url', '')}")
772
+ if typography.get("css_import"):
773
+ lines.append(f"│ CSS Import: {typography.get('css_import', '')[:67]}...".ljust(BOX_WIDTH) + "│")
774
+
775
+ # Key Effects section
776
+ if effects:
777
+ lines.append(section_header("KEY EFFECTS", BOX_WIDTH))
778
+ for line in wrap_text(effects, "│ ", BOX_WIDTH):
779
+ lines.append(line.ljust(BOX_WIDTH) + "│")
780
+
781
+ # Motion section (GSAP skeleton, only if --motion dial was set)
782
+ if motion_snippet:
783
+ lines.append(section_header("MOTION", BOX_WIDTH))
784
+ add_wrapped(f"{motion_snippet.get('Category', '')} ({motion_snippet.get('Intensity Tier', '')})", "│ ")
785
+ add_wrapped(f"Trigger: {motion_snippet.get('Trigger', '')} | Duration: {motion_snippet.get('Duration', '')} | Easing: {motion_snippet.get('Easing', '')}")
786
+ for line in wrap_text(f"GSAP: {motion_snippet.get('GSAP Snippet', '')}", "│ ", BOX_WIDTH):
787
+ lines.append(line.ljust(BOX_WIDTH) + "│")
788
+ if motion_snippet.get("Framework Notes"):
789
+ for line in wrap_text(f"Framework: {motion_snippet.get('Framework Notes', '')}", "│ ", BOX_WIDTH):
790
+ lines.append(line.ljust(BOX_WIDTH) + "│")
791
+
792
+ # Anti-patterns section
793
+ if anti_patterns:
794
+ lines.append(section_header("AVOID", BOX_WIDTH))
795
+ for line in wrap_text(anti_patterns, "│ ", BOX_WIDTH):
796
+ lines.append(line.ljust(BOX_WIDTH) + "│")
797
+
798
+ # Pre-Delivery Checklist section
799
+ lines.append(section_header("PRE-DELIVERY CHECKLIST", BOX_WIDTH))
800
+ checklist_items = [
801
+ "[ ] No emojis as icons (use SVG: Heroicons/Lucide)",
802
+ "[ ] cursor-pointer on all clickable elements",
803
+ "[ ] Hover states with smooth transitions (150-300ms)",
804
+ "[ ] Light mode: text contrast 4.5:1 minimum",
805
+ "[ ] Focus states visible for keyboard nav",
806
+ "[ ] prefers-reduced-motion respected",
807
+ "[ ] Responsive: 375px, 768px, 1024px, 1440px"
808
+ ]
809
+ for item in checklist_items:
810
+ lines.append(f"│ {item}".ljust(BOX_WIDTH) + "│")
811
+
812
+ lines.append("└" + "─" * w + "┘")
813
+
814
+ return "\n".join(lines)
815
+
816
+
817
+ def format_markdown(design_system: dict) -> str:
818
+ """Format design system as markdown."""
819
+ project = design_system.get("project_name", "PROJECT")
820
+ pattern = design_system.get("pattern", {})
821
+ style = design_system.get("style", {})
822
+ colors = design_system.get("colors", {})
823
+ typography = design_system.get("typography", {})
824
+ effects = design_system.get("key_effects", "")
825
+ anti_patterns = design_system.get("anti_patterns", "")
826
+ dials = design_system.get("dials", {})
827
+ motion_snippet = design_system.get("motion_snippet", {})
828
+
829
+ lines = []
830
+ lines.append(f"## Design System: {project}")
831
+ lines.append("")
832
+
833
+ # Design Dials section (only if at least one dial was set)
834
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
835
+ lines.append("### Design Dials")
836
+ if dials.get("variance") is not None:
837
+ lines.append(f"- **Variance:** {dials['variance']}/10 — {dials['variance_label']}")
838
+ if dials.get("motion") is not None:
839
+ lines.append(f"- **Motion:** {dials['motion']}/10 — {dials['motion_label']}")
840
+ if dials.get("density") is not None:
841
+ lines.append(f"- **Density:** {dials['density']}/10 — {dials['density_label']}")
842
+ lines.append("")
843
+
844
+ # Pattern section
845
+ lines.append("### Pattern")
846
+ lines.append(f"- **Name:** {pattern.get('name', '')}")
847
+ if pattern.get('conversion'):
848
+ lines.append(f"- **Conversion Focus:** {pattern.get('conversion', '')}")
849
+ if pattern.get('cta_placement'):
850
+ lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
851
+ if pattern.get('color_strategy'):
852
+ lines.append(f"- **Color Strategy:** {pattern.get('color_strategy', '')}")
853
+ lines.append(f"- **Sections:** {pattern.get('sections', '')}")
854
+ lines.append("")
855
+
856
+ # Style section
857
+ lines.append("### Style")
858
+ lines.append(f"- **Name:** {style.get('name', '')}")
859
+ light, dark = _mode_support_labels(style, anti_patterns)
860
+ if light or dark:
861
+ lines.append(f"- **Mode Support:** Light {light} | Dark {dark}")
862
+ if style.get('keywords'):
863
+ lines.append(f"- **Keywords:** {style.get('keywords', '')}")
864
+ if style.get('best_for'):
865
+ lines.append(f"- **Best For:** {style.get('best_for', '')}")
866
+ if style.get('performance') or style.get('accessibility'):
867
+ lines.append(f"- **Performance:** {style.get('performance', '')} | **Accessibility:** {style.get('accessibility', '')}")
868
+ lines.append("")
869
+
870
+ # Colors section (extended palette)
871
+ lines.append("### Colors")
872
+ lines.append("| Role | Hex | CSS Variable |")
873
+ lines.append("|------|-----|--------------|")
874
+ for label, key, css_var in SEMANTIC_COLOR_ENTRIES:
875
+ hex_val = colors.get(key, "")
876
+ if hex_val:
877
+ lines.append(f"| {label} | `{hex_val}` | `{css_var}` |")
878
+ if colors.get("notes"):
879
+ lines.append(f"\n*Notes: {colors.get('notes', '')}*")
880
+ lines.append("")
881
+
882
+ # Typography section
883
+ lines.append("### Typography")
884
+ lines.append(f"- **Heading:** {typography.get('heading', '')}")
885
+ lines.append(f"- **Body:** {typography.get('body', '')}")
886
+ if typography.get("mood"):
887
+ lines.append(f"- **Mood:** {typography.get('mood', '')}")
888
+ if typography.get("best_for"):
889
+ lines.append(f"- **Best For:** {typography.get('best_for', '')}")
890
+ if typography.get("google_fonts_url"):
891
+ lines.append(f"- **Google Fonts:** {typography.get('google_fonts_url', '')}")
892
+ if typography.get("css_import"):
893
+ lines.append(f"- **CSS Import:**")
894
+ lines.append(f"```css")
895
+ lines.append(f"{typography.get('css_import', '')}")
896
+ lines.append(f"```")
897
+ lines.append("")
898
+
899
+ # Key Effects section
900
+ if effects:
901
+ lines.append("### Key Effects")
902
+ lines.append(f"{effects}")
903
+ lines.append("")
904
+
905
+ # Motion section (GSAP skeleton, only if --motion dial was set)
906
+ if motion_snippet:
907
+ lines.append("### Motion")
908
+ 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', '')}`")
909
+ lines.append("```js")
910
+ lines.append(motion_snippet.get("GSAP Snippet", ""))
911
+ lines.append("```")
912
+ if motion_snippet.get("Framework Notes"):
913
+ lines.append(f"*Framework notes: {motion_snippet.get('Framework Notes', '')}*")
914
+ motion_do = motion_snippet.get("Do", "")
915
+ motion_dont = motion_snippet.get("Don't", "")
916
+ if motion_do:
917
+ lines.append(f"- ✅ {motion_do}")
918
+ if motion_dont:
919
+ lines.append(f"- ❌ {motion_dont}")
920
+ lines.append("")
921
+
922
+ # Anti-patterns section
923
+ if anti_patterns:
924
+ lines.append("### Avoid (Anti-patterns)")
925
+ newline_bullet = '\n- '
926
+ lines.append(f"- {anti_patterns.replace(' + ', newline_bullet)}")
927
+ lines.append("")
928
+
929
+ # Pre-Delivery Checklist section
930
+ lines.append("### Pre-Delivery Checklist")
931
+ lines.append("- [ ] No emojis as icons (use SVG: Heroicons/Lucide)")
932
+ lines.append("- [ ] cursor-pointer on all clickable elements")
933
+ lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
934
+ lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
935
+ lines.append("- [ ] Focus states visible for keyboard nav")
936
+ lines.append("- [ ] prefers-reduced-motion respected")
937
+ lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
938
+ lines.append("")
939
+
940
+ return "\n".join(lines)
941
+
942
+
943
+ # ============ MAIN ENTRY POINT ============
944
+ def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii",
945
+ persist: bool = False, page: str = None, output_dir: str = None,
946
+ variance: int = None, motion: int = None, density: int = None,
947
+ force: bool = False) -> dict:
948
+ """
949
+ Main entry point for design system generation.
950
+
951
+ Args:
952
+ query: Search query (e.g., "SaaS dashboard", "e-commerce luxury")
953
+ project_name: Optional project name for output header
954
+ output_format: "ascii" (default) or "markdown"
955
+ persist: If True, save design system to design-system/ folder
956
+ page: Optional page name for page-specific override file
957
+ output_dir: Optional output directory (defaults to current working directory)
958
+ variance: Optional 1-10 DESIGN_VARIANCE dial (1=centered/minimal, 10=bold/asymmetric)
959
+ motion: Optional 1-10 MOTION_INTENSITY dial, pulls a matching GSAP snippet from motion.csv
960
+ density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense)
961
+ force: If True, overwrite an existing MASTER.md; otherwise persistence
962
+ is skipped (with a status message) when one already exists
963
+
964
+ Returns:
965
+ dict with keys: "text" (formatted design system string), "design_system"
966
+ (raw dict, useful for --json callers), and "persistence" (result of
967
+ persist_design_system(), or None if persist=False)
968
+ """
969
+ generator = DesignSystemGenerator()
970
+ design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density)
971
+
972
+ persistence_result = None
973
+ if persist:
974
+ persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
975
+
976
+ text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system)
977
+
978
+ return {
979
+ "text": text,
980
+ "design_system": design_system,
981
+ "persistence": persistence_result,
982
+ }
983
+
984
+
985
+ # ============ PERSISTENCE FUNCTIONS ============
986
+ def safe_slug(name, fallback: str = "default") -> str:
987
+ """Slugify a name into a single safe path segment.
988
+
989
+ Only [a-z0-9_-] survives; every other character (including '/', '\\' and
990
+ '.') collapses into '-'. This makes path traversal via project/page names
991
+ (e.g. "../../etc") impossible — the slug can never leave its parent dir.
992
+ """
993
+ slug = re.sub(r'[^a-z0-9_-]+', '-', str(name).lower()).strip('-')
994
+ return slug or fallback
995
+
996
+
997
+ def _write_persisted_file(path: Path, content: str, force: bool) -> None:
998
+ """Write fully to a temp file, then publish atomically."""
999
+ temp_name = None
1000
+ try:
1001
+ with tempfile.NamedTemporaryFile(
1002
+ mode='w', encoding='utf-8', dir=path.parent,
1003
+ prefix=f".{path.name}.", suffix=".tmp", delete=False) as handle:
1004
+ temp_name = handle.name
1005
+ handle.write(content)
1006
+ handle.flush()
1007
+ os.fsync(handle.fileno())
1008
+ if force:
1009
+ os.replace(temp_name, path)
1010
+ temp_name = None
1011
+ else:
1012
+ # A same-filesystem hard link atomically publishes only if the
1013
+ # destination is absent. Losing writers get FileExistsError.
1014
+ os.link(temp_name, path)
1015
+ finally:
1016
+ if temp_name and os.path.exists(temp_name):
1017
+ os.unlink(temp_name)
1018
+
1019
+
1020
+ def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
1021
+ page_query: str = None, force: bool = False) -> dict:
1022
+ """
1023
+ Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
1024
+
1025
+ Args:
1026
+ design_system: The generated design system dictionary
1027
+ page: Optional page name for page-specific override file
1028
+ output_dir: Optional output directory (defaults to current working directory)
1029
+ page_query: Optional query string for intelligent page override generation
1030
+ force: If True, overwrite an existing MASTER.md. If False (default) and
1031
+ MASTER.md already exists, persistence is skipped so prior design
1032
+ decisions aren't silently discarded.
1033
+
1034
+ Returns:
1035
+ dict with created file paths and status. status is "skipped_exists" if
1036
+ MASTER.md already existed and force was not set.
1037
+ """
1038
+ base_dir = Path(output_dir) if output_dir else Path.cwd()
1039
+
1040
+ # Use project name for project-specific folder. Coalesce falsy values
1041
+ # (missing key, explicit None, or "") so the .lower() below can't crash.
1042
+ project_name = design_system.get("project_name") or "default"
1043
+ project_slug = safe_slug(project_name)
1044
+
1045
+ design_system_dir = base_dir / "design-system" / project_slug
1046
+ pages_dir = design_system_dir / "pages"
1047
+
1048
+ master_file = design_system_dir / "MASTER.md"
1049
+
1050
+ created_files = []
1051
+
1052
+ # Create directories
1053
+ design_system_dir.mkdir(parents=True, exist_ok=True)
1054
+ pages_dir.mkdir(parents=True, exist_ok=True)
1055
+
1056
+ # Exclusive creation makes the default no-overwrite contract safe when
1057
+ # multiple agents persist the same project concurrently.
1058
+ master_content = format_master_md(design_system)
1059
+ try:
1060
+ _write_persisted_file(master_file, master_content, force)
1061
+ created_files.append(str(master_file))
1062
+ except FileExistsError:
1063
+ if not page:
1064
+ return {
1065
+ "status": "skipped_exists",
1066
+ "design_system_dir": str(design_system_dir),
1067
+ "master_file": str(master_file),
1068
+ "created_files": [],
1069
+ "message": (
1070
+ f"{master_file} already exists and was not modified. "
1071
+ "Read it first to check for prior design decisions, then "
1072
+ "re-run with force=True / --force to overwrite."
1073
+ ),
1074
+ }
1075
+
1076
+ # If page is specified, create page override file with intelligent content
1077
+ if page:
1078
+ page_file = pages_dir / f"{safe_slug(page, 'page')}.md"
1079
+ page_content = format_page_override_md(design_system, page, page_query)
1080
+ try:
1081
+ _write_persisted_file(page_file, page_content, force)
1082
+ created_files.append(str(page_file))
1083
+ except FileExistsError:
1084
+ if not created_files:
1085
+ return {
1086
+ "status": "skipped_exists",
1087
+ "design_system_dir": str(design_system_dir),
1088
+ "master_file": str(master_file),
1089
+ "created_files": [],
1090
+ "message": f"{page_file} already exists and was not modified.",
1091
+ }
1092
+
1093
+ return {
1094
+ "status": "success",
1095
+ "design_system_dir": str(design_system_dir),
1096
+ "master_file": str(master_file),
1097
+ "created_files": created_files
1098
+ }
1099
+
1100
+
1101
+ def format_master_md(design_system: dict) -> str:
1102
+ """Format design system as MASTER.md with hierarchical override logic."""
1103
+ project = design_system.get("project_name", "PROJECT")
1104
+ pattern = design_system.get("pattern", {})
1105
+ style = design_system.get("style", {})
1106
+ colors = design_system.get("colors", {})
1107
+ typography = design_system.get("typography", {})
1108
+ effects = design_system.get("key_effects", "")
1109
+ anti_patterns = design_system.get("anti_patterns", "")
1110
+ dials = design_system.get("dials", {})
1111
+ motion_snippet = design_system.get("motion_snippet", {})
1112
+ spacing_scale = design_system.get("spacing_scale")
1113
+
1114
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1115
+
1116
+ lines = []
1117
+
1118
+ # Logic header
1119
+ lines.append("# Design System Master File")
1120
+ lines.append("")
1121
+ lines.append("> **LOGIC:** When building a specific page, first check `design-system/pages/[page-name].md`.")
1122
+ lines.append("> If that file exists, its rules **override** this Master file.")
1123
+ lines.append("> If not, strictly follow the rules below.")
1124
+ lines.append("")
1125
+ lines.append("---")
1126
+ lines.append("")
1127
+ lines.append(f"**Project:** {project}")
1128
+ lines.append(f"**Generated:** {timestamp}")
1129
+ lines.append(f"**Category:** {design_system.get('category', 'General')}")
1130
+ if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
1131
+ dial_parts = []
1132
+ if dials.get("variance") is not None:
1133
+ dial_parts.append(f"Variance {dials['variance']}/10 ({dials['variance_label']})")
1134
+ if dials.get("motion") is not None:
1135
+ dial_parts.append(f"Motion {dials['motion']}/10 ({dials['motion_label']})")
1136
+ if dials.get("density") is not None:
1137
+ dial_parts.append(f"Density {dials['density']}/10 ({dials['density_label']})")
1138
+ lines.append(f"**Design Dials:** {' | '.join(dial_parts)}")
1139
+ lines.append("")
1140
+ lines.append("---")
1141
+ lines.append("")
1142
+
1143
+ # Global Rules section
1144
+ lines.append("## Global Rules")
1145
+ lines.append("")
1146
+
1147
+ # Color Palette
1148
+ lines.append("### Color Palette")
1149
+ lines.append("")
1150
+ lines.append("| Role | Hex | CSS Variable |")
1151
+ lines.append("|------|-----|--------------|")
1152
+ for label, key, css_var in SEMANTIC_COLOR_ENTRIES:
1153
+ hex_val = colors.get(key, "")
1154
+ if hex_val:
1155
+ lines.append(f"| {label} | `{hex_val}` | `{css_var}` |")
1156
+ lines.append("")
1157
+ if colors.get("notes"):
1158
+ lines.append(f"**Color Notes:** {colors.get('notes', '')}")
1159
+ lines.append("")
1160
+
1161
+ # Typography
1162
+ lines.append("### Typography")
1163
+ lines.append("")
1164
+ lines.append(f"- **Heading Font:** {typography.get('heading', 'Inter')}")
1165
+ lines.append(f"- **Body Font:** {typography.get('body', 'Inter')}")
1166
+ if typography.get("mood"):
1167
+ lines.append(f"- **Mood:** {typography.get('mood', '')}")
1168
+ if typography.get("google_fonts_url"):
1169
+ lines.append(f"- **Google Fonts:** [{typography.get('heading', '')} + {typography.get('body', '')}]({typography.get('google_fonts_url', '')})")
1170
+ lines.append("")
1171
+ if typography.get("css_import"):
1172
+ lines.append("**CSS Import:**")
1173
+ lines.append("```css")
1174
+ lines.append(typography.get("css_import", ""))
1175
+ lines.append("```")
1176
+ lines.append("")
1177
+
1178
+ # Spacing Variables (overridden by the VISUAL_DENSITY dial when set)
1179
+ default_spacing = DIAL_TIERS["density"][1][2]["spacing"] # mid-tier = the historical defaults
1180
+ scale = spacing_scale or default_spacing
1181
+ spacing_usage = {
1182
+ "xs": "Tight gaps", "sm": "Icon gaps, inline spacing", "md": "Standard padding",
1183
+ "lg": "Section padding", "xl": "Large gaps", "2xl": "Section margins", "3xl": "Hero padding",
1184
+ }
1185
+ lines.append("### Spacing Variables")
1186
+ lines.append("")
1187
+ if spacing_scale:
1188
+ lines.append(f"*Density: {dials.get('density')}/10 — {dials.get('density_label')}*")
1189
+ lines.append("")
1190
+ lines.append("| Token | Value | Usage |")
1191
+ lines.append("|-------|-------|-------|")
1192
+ for token in ("xs", "sm", "md", "lg", "xl", "2xl", "3xl"):
1193
+ px_value = scale[token]
1194
+ rem_value = f"{int(px_value.rstrip('px')) / 16:g}rem"
1195
+ lines.append(f"| `--space-{token}` | `{px_value}` / `{rem_value}` | {spacing_usage[token]} |")
1196
+ lines.append("")
1197
+
1198
+ # Shadow Depths
1199
+ lines.append("### Shadow Depths")
1200
+ lines.append("")
1201
+ lines.append("| Level | Value | Usage |")
1202
+ lines.append("|-------|-------|-------|")
1203
+ lines.append("| `--shadow-sm` | `0 1px 2px rgba(0,0,0,0.05)` | Subtle lift |")
1204
+ lines.append("| `--shadow-md` | `0 4px 6px rgba(0,0,0,0.1)` | Cards, buttons |")
1205
+ lines.append("| `--shadow-lg` | `0 10px 15px rgba(0,0,0,0.1)` | Modals, dropdowns |")
1206
+ lines.append("| `--shadow-xl` | `0 20px 25px rgba(0,0,0,0.15)` | Hero images, featured cards |")
1207
+ lines.append("")
1208
+
1209
+ # Component Specs section
1210
+ lines.append("---")
1211
+ lines.append("")
1212
+ lines.append("## Component Specs")
1213
+ lines.append("")
1214
+
1215
+ # Buttons
1216
+ lines.append("### Buttons")
1217
+ lines.append("")
1218
+ lines.append("```css")
1219
+ lines.append("/* Primary Button */")
1220
+ lines.append(".btn-primary {")
1221
+ lines.append(f" background: {colors.get('cta', '#F97316')};")
1222
+ lines.append(f" color: {colors.get('on_cta') or 'white'};")
1223
+ lines.append(" padding: 12px 24px;")
1224
+ lines.append(" border-radius: 8px;")
1225
+ lines.append(" font-weight: 600;")
1226
+ lines.append(" transition: all 200ms ease;")
1227
+ lines.append(" cursor: pointer;")
1228
+ lines.append("}")
1229
+ lines.append("")
1230
+ lines.append(".btn-primary:hover {")
1231
+ lines.append(" opacity: 0.9;")
1232
+ lines.append(" transform: translateY(-1px);")
1233
+ lines.append("}")
1234
+ lines.append("")
1235
+ lines.append("/* Secondary Button */")
1236
+ lines.append(".btn-secondary {")
1237
+ lines.append(f" background: transparent;")
1238
+ lines.append(f" color: {_button_outline_text_color(colors)};")
1239
+ lines.append(f" border: 2px solid {colors.get('primary', '#2563EB')};")
1240
+ lines.append(" padding: 12px 24px;")
1241
+ lines.append(" border-radius: 8px;")
1242
+ lines.append(" font-weight: 600;")
1243
+ lines.append(" transition: all 200ms ease;")
1244
+ lines.append(" cursor: pointer;")
1245
+ lines.append("}")
1246
+ lines.append("```")
1247
+ lines.append("")
1248
+
1249
+ # Cards
1250
+ lines.append("### Cards")
1251
+ lines.append("")
1252
+ lines.append("```css")
1253
+ lines.append(".card {")
1254
+ lines.append(f" background: {colors.get('background', '#FFFFFF')};")
1255
+ lines.append(" border-radius: 12px;")
1256
+ lines.append(" padding: 24px;")
1257
+ lines.append(" box-shadow: var(--shadow-md);")
1258
+ lines.append(" transition: all 200ms ease;")
1259
+ lines.append(" cursor: pointer;")
1260
+ lines.append("}")
1261
+ lines.append("")
1262
+ lines.append(".card:hover {")
1263
+ lines.append(" box-shadow: var(--shadow-lg);")
1264
+ lines.append(" transform: translateY(-2px);")
1265
+ lines.append("}")
1266
+ lines.append("```")
1267
+ lines.append("")
1268
+
1269
+ # Inputs
1270
+ lines.append("### Inputs")
1271
+ lines.append("")
1272
+ lines.append("```css")
1273
+ lines.append(".input {")
1274
+ lines.append(" padding: 12px 16px;")
1275
+ lines.append(" border: 1px solid #E2E8F0;")
1276
+ lines.append(" border-radius: 8px;")
1277
+ lines.append(" font-size: 16px;")
1278
+ lines.append(" transition: border-color 200ms ease;")
1279
+ lines.append("}")
1280
+ lines.append("")
1281
+ lines.append(".input:focus {")
1282
+ lines.append(f" border-color: {colors.get('primary', '#2563EB')};")
1283
+ lines.append(" outline: none;")
1284
+ lines.append(f" box-shadow: 0 0 0 3px {colors.get('primary', '#2563EB')}20;")
1285
+ lines.append("}")
1286
+ lines.append("```")
1287
+ lines.append("")
1288
+
1289
+ # Modals
1290
+ lines.append("### Modals")
1291
+ lines.append("")
1292
+ lines.append("```css")
1293
+ lines.append(".modal-overlay {")
1294
+ lines.append(" background: rgba(0, 0, 0, 0.5);")
1295
+ lines.append(" backdrop-filter: blur(4px);")
1296
+ lines.append("}")
1297
+ lines.append("")
1298
+ lines.append(".modal {")
1299
+ lines.append(" background: white;")
1300
+ lines.append(" border-radius: 16px;")
1301
+ lines.append(" padding: 32px;")
1302
+ lines.append(" box-shadow: var(--shadow-xl);")
1303
+ lines.append(" max-width: 500px;")
1304
+ lines.append(" width: 90%;")
1305
+ lines.append("}")
1306
+ lines.append("```")
1307
+ lines.append("")
1308
+
1309
+ # Style section
1310
+ lines.append("---")
1311
+ lines.append("")
1312
+ lines.append("## Style Guidelines")
1313
+ lines.append("")
1314
+ lines.append(f"**Style:** {style.get('name', 'Minimalism')}")
1315
+ lines.append("")
1316
+ if style.get("keywords"):
1317
+ lines.append(f"**Keywords:** {style.get('keywords', '')}")
1318
+ lines.append("")
1319
+ if style.get("best_for"):
1320
+ lines.append(f"**Best For:** {style.get('best_for', '')}")
1321
+ lines.append("")
1322
+ if effects:
1323
+ lines.append(f"**Key Effects:** {effects}")
1324
+ lines.append("")
1325
+
1326
+ # Layout Pattern
1327
+ lines.append("### Page Pattern")
1328
+ lines.append("")
1329
+ lines.append(f"**Pattern Name:** {pattern.get('name', '')}")
1330
+ lines.append("")
1331
+ if pattern.get('conversion'):
1332
+ lines.append(f"- **Conversion Strategy:** {pattern.get('conversion', '')}")
1333
+ if pattern.get('cta_placement'):
1334
+ lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
1335
+ lines.append(f"- **Section Order:** {pattern.get('sections', '')}")
1336
+ lines.append("")
1337
+
1338
+ # Motion section (GSAP skeleton, only if --motion dial was set)
1339
+ if motion_snippet:
1340
+ lines.append("---")
1341
+ lines.append("")
1342
+ lines.append("## Motion")
1343
+ lines.append("")
1344
+ 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', '')}`")
1345
+ lines.append("")
1346
+ lines.append("```js")
1347
+ lines.append(motion_snippet.get("GSAP Snippet", ""))
1348
+ lines.append("```")
1349
+ lines.append("")
1350
+ if motion_snippet.get("Framework Notes"):
1351
+ lines.append(f"**Framework notes:** {motion_snippet.get('Framework Notes', '')}")
1352
+ lines.append("")
1353
+ motion_do = motion_snippet.get("Do", "")
1354
+ motion_dont = motion_snippet.get("Don't", "")
1355
+ if motion_do:
1356
+ lines.append(f"- ✅ {motion_do}")
1357
+ if motion_dont:
1358
+ lines.append(f"- ❌ {motion_dont}")
1359
+ if motion_snippet.get("Performance Notes"):
1360
+ lines.append(f"- ⚡ {motion_snippet.get('Performance Notes', '')}")
1361
+ lines.append("")
1362
+
1363
+ # Anti-Patterns section
1364
+ lines.append("---")
1365
+ lines.append("")
1366
+ lines.append("## Anti-Patterns (Do NOT Use)")
1367
+ lines.append("")
1368
+ if anti_patterns:
1369
+ anti_list = [a.strip() for a in anti_patterns.split("+")]
1370
+ for anti in anti_list:
1371
+ if anti:
1372
+ lines.append(f"- ❌ {anti}")
1373
+ lines.append("")
1374
+ lines.append("### Additional Forbidden Patterns")
1375
+ lines.append("")
1376
+ lines.append("- ❌ **Emojis as icons** — Use SVG icons (Heroicons, Lucide, Simple Icons)")
1377
+ lines.append("- ❌ **Missing cursor:pointer** — All clickable elements must have cursor:pointer")
1378
+ lines.append("- ❌ **Layout-shifting hovers** — Avoid scale transforms that shift layout")
1379
+ lines.append("- ❌ **Low contrast text** — Maintain 4.5:1 minimum contrast ratio")
1380
+ lines.append("- ❌ **Instant state changes** — Always use transitions (150-300ms)")
1381
+ lines.append("- ❌ **Invisible focus states** — Focus states must be visible for a11y")
1382
+ lines.append("")
1383
+
1384
+ # Pre-Delivery Checklist
1385
+ lines.append("---")
1386
+ lines.append("")
1387
+ lines.append("## Pre-Delivery Checklist")
1388
+ lines.append("")
1389
+ lines.append("Before delivering any UI code, verify:")
1390
+ lines.append("")
1391
+ lines.append("- [ ] No emojis used as icons (use SVG instead)")
1392
+ lines.append("- [ ] All icons from consistent icon set (Heroicons/Lucide)")
1393
+ lines.append("- [ ] `cursor-pointer` on all clickable elements")
1394
+ lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
1395
+ lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
1396
+ lines.append("- [ ] Focus states visible for keyboard navigation")
1397
+ lines.append("- [ ] `prefers-reduced-motion` respected")
1398
+ lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
1399
+ lines.append("- [ ] No content hidden behind fixed navbars")
1400
+ lines.append("- [ ] No horizontal scroll on mobile")
1401
+ lines.append("")
1402
+
1403
+ return "\n".join(lines)
1404
+
1405
+
1406
+ def format_page_override_md(design_system: dict, page_name: str, page_query: str = None) -> str:
1407
+ """Format a page-specific override file with intelligent AI-generated content."""
1408
+ project = design_system.get("project_name", "PROJECT")
1409
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1410
+ page_title = page_name.replace("-", " ").replace("_", " ").title()
1411
+
1412
+ # Detect page type and generate intelligent overrides
1413
+ page_overrides = _generate_intelligent_overrides(page_name, page_query, design_system)
1414
+
1415
+ lines = []
1416
+
1417
+ lines.append(f"# {page_title} Page Overrides")
1418
+ lines.append("")
1419
+ lines.append(f"> **PROJECT:** {project}")
1420
+ lines.append(f"> **Generated:** {timestamp}")
1421
+ lines.append(f"> **Page Type:** {page_overrides.get('page_type', 'General')}")
1422
+ lines.append("")
1423
+ lines.append("> ⚠️ **IMPORTANT:** Rules in this file **override** the Master file (`design-system/MASTER.md`).")
1424
+ lines.append("> Only deviations from the Master are documented here. For all other rules, refer to the Master.")
1425
+ lines.append("")
1426
+ lines.append("---")
1427
+ lines.append("")
1428
+
1429
+ # Page-specific rules with actual content
1430
+ lines.append("## Page-Specific Rules")
1431
+ lines.append("")
1432
+
1433
+ # Layout Overrides
1434
+ lines.append("### Layout Overrides")
1435
+ lines.append("")
1436
+ layout = page_overrides.get("layout", {})
1437
+ if layout:
1438
+ for key, value in layout.items():
1439
+ lines.append(f"- **{key}:** {value}")
1440
+ else:
1441
+ lines.append("- No overrides — use Master layout")
1442
+ lines.append("")
1443
+
1444
+ # Spacing Overrides
1445
+ lines.append("### Spacing Overrides")
1446
+ lines.append("")
1447
+ spacing = page_overrides.get("spacing", {})
1448
+ if spacing:
1449
+ for key, value in spacing.items():
1450
+ lines.append(f"- **{key}:** {value}")
1451
+ else:
1452
+ lines.append("- No overrides — use Master spacing")
1453
+ lines.append("")
1454
+
1455
+ # Typography Overrides
1456
+ lines.append("### Typography Overrides")
1457
+ lines.append("")
1458
+ typography = page_overrides.get("typography", {})
1459
+ if typography:
1460
+ for key, value in typography.items():
1461
+ lines.append(f"- **{key}:** {value}")
1462
+ else:
1463
+ lines.append("- No overrides — use Master typography")
1464
+ lines.append("")
1465
+
1466
+ # Color Overrides
1467
+ lines.append("### Color Overrides")
1468
+ lines.append("")
1469
+ colors = page_overrides.get("colors", {})
1470
+ if colors:
1471
+ for key, value in colors.items():
1472
+ lines.append(f"- **{key}:** {value}")
1473
+ else:
1474
+ lines.append("- No overrides — use Master colors")
1475
+ lines.append("")
1476
+
1477
+ # Component Overrides
1478
+ lines.append("### Component Overrides")
1479
+ lines.append("")
1480
+ components = page_overrides.get("components", [])
1481
+ if components:
1482
+ for comp in components:
1483
+ lines.append(f"- {comp}")
1484
+ else:
1485
+ lines.append("- No overrides — use Master component specs")
1486
+ lines.append("")
1487
+
1488
+ # Page-Specific Components
1489
+ lines.append("---")
1490
+ lines.append("")
1491
+ lines.append("## Page-Specific Components")
1492
+ lines.append("")
1493
+ unique_components = page_overrides.get("unique_components", [])
1494
+ if unique_components:
1495
+ for comp in unique_components:
1496
+ lines.append(f"- {comp}")
1497
+ else:
1498
+ lines.append("- No unique components for this page")
1499
+ lines.append("")
1500
+
1501
+ # Recommendations
1502
+ lines.append("---")
1503
+ lines.append("")
1504
+ lines.append("## Recommendations")
1505
+ lines.append("")
1506
+ recommendations = page_overrides.get("recommendations", [])
1507
+ if recommendations:
1508
+ for rec in recommendations:
1509
+ lines.append(f"- {rec}")
1510
+ lines.append("")
1511
+
1512
+ return "\n".join(lines)
1513
+
1514
+
1515
+ def _generate_intelligent_overrides(page_name: str, page_query: str, design_system: dict) -> dict:
1516
+ """
1517
+ Generate intelligent overrides based on page type using layered search.
1518
+
1519
+ Uses the existing search infrastructure to find relevant style, UX, and layout
1520
+ data instead of hardcoded page types.
1521
+ """
1522
+ from core import search
1523
+
1524
+ page_lower = page_name.lower()
1525
+ query_lower = (page_query or "").lower()
1526
+ combined_context = f"{page_lower} {query_lower}"
1527
+
1528
+ # Search across multiple domains for page-specific guidance
1529
+ style_search = search(combined_context, "style", max_results=1)
1530
+ ux_search = search(combined_context, "ux", max_results=3)
1531
+ landing_search = search(combined_context, "landing", max_results=1)
1532
+
1533
+ # Extract results from search response
1534
+ style_results = style_search.get("results", [])
1535
+ ux_results = ux_search.get("results", [])
1536
+ landing_results = landing_search.get("results", [])
1537
+
1538
+ # Detect page type from search results or context
1539
+ page_type = _detect_page_type(combined_context, style_results)
1540
+
1541
+ # Build overrides from search results
1542
+ layout = {}
1543
+ spacing = {}
1544
+ typography = {}
1545
+ colors = {}
1546
+ components = []
1547
+ unique_components = []
1548
+ recommendations = []
1549
+
1550
+ # Extract style-based overrides
1551
+ if style_results:
1552
+ style = style_results[0]
1553
+ style_name = style.get("Style Category", "")
1554
+ keywords = style.get("Keywords", "")
1555
+ best_for = style.get("Best For", "")
1556
+ effects = style.get("Effects & Animation", "")
1557
+
1558
+ # Infer layout from style keywords
1559
+ if any(kw in keywords.lower() for kw in ["data", "dense", "dashboard", "grid"]):
1560
+ layout["Max Width"] = "1400px or full-width"
1561
+ layout["Grid"] = "12-column grid for data flexibility"
1562
+ spacing["Content Density"] = "High — optimize for information display"
1563
+ elif any(kw in keywords.lower() for kw in ["minimal", "simple", "clean", "single"]):
1564
+ layout["Max Width"] = "800px (narrow, focused)"
1565
+ layout["Layout"] = "Single column, centered"
1566
+ spacing["Content Density"] = "Low — focus on clarity"
1567
+ else:
1568
+ layout["Max Width"] = "1200px (standard)"
1569
+ layout["Layout"] = "Full-width sections, centered content"
1570
+
1571
+ if effects:
1572
+ recommendations.append(f"Effects: {effects}")
1573
+
1574
+ # Extract UX guidelines as recommendations
1575
+ for ux in ux_results:
1576
+ category = ux.get("Category", "")
1577
+ do_text = ux.get("Do", "")
1578
+ dont_text = ux.get("Don't", "")
1579
+ if do_text:
1580
+ recommendations.append(f"{category}: {do_text}")
1581
+ if dont_text:
1582
+ components.append(f"Avoid: {dont_text}")
1583
+
1584
+ # Extract landing pattern info for section structure
1585
+ if landing_results:
1586
+ landing = landing_results[0]
1587
+ sections = landing.get("Section Order", "")
1588
+ cta_placement = landing.get("Primary CTA Placement", "")
1589
+ color_strategy = landing.get("Color Strategy", "")
1590
+
1591
+ if sections:
1592
+ layout["Sections"] = sections
1593
+ if cta_placement:
1594
+ recommendations.append(f"CTA Placement: {cta_placement}")
1595
+ if color_strategy:
1596
+ colors["Strategy"] = color_strategy
1597
+
1598
+ # Add page-type specific defaults if no search results
1599
+ if not layout:
1600
+ layout["Max Width"] = "1200px"
1601
+ layout["Layout"] = "Responsive grid"
1602
+
1603
+ if not recommendations:
1604
+ recommendations = [
1605
+ "Refer to MASTER.md for all design rules",
1606
+ "Add specific overrides as needed for this page"
1607
+ ]
1608
+
1609
+ return {
1610
+ "page_type": page_type,
1611
+ "layout": layout,
1612
+ "spacing": spacing,
1613
+ "typography": typography,
1614
+ "colors": colors,
1615
+ "components": components,
1616
+ "unique_components": unique_components,
1617
+ "recommendations": recommendations
1618
+ }
1619
+
1620
+
1621
+ def _detect_page_type(context: str, style_results: list) -> str:
1622
+ """Detect page type from context and search results."""
1623
+ context_lower = context.lower()
1624
+
1625
+ # Check for common page type patterns
1626
+ page_patterns = [
1627
+ (["dashboard", "admin", "analytics", "data", "metrics", "stats", "monitor", "overview"], "Dashboard / Data View"),
1628
+ (["checkout", "payment", "cart", "purchase", "order", "billing"], "Checkout / Payment"),
1629
+ (["settings", "profile", "account", "preferences", "config"], "Settings / Profile"),
1630
+ (["landing", "marketing", "homepage", "hero", "home", "promo"], "Landing / Marketing"),
1631
+ (["login", "signin", "signup", "register", "auth", "password"], "Authentication"),
1632
+ (["pricing", "plans", "subscription", "tiers", "packages"], "Pricing / Plans"),
1633
+ (["blog", "article", "post", "news", "content", "story"], "Blog / Article"),
1634
+ (["product", "item", "detail", "pdp", "shop", "store"], "Product Detail"),
1635
+ (["search", "results", "browse", "filter", "catalog", "list"], "Search Results"),
1636
+ (["empty", "404", "error", "not found", "zero"], "Empty State"),
1637
+ ]
1638
+
1639
+ for keywords, page_type in page_patterns:
1640
+ if any(kw in context_lower for kw in keywords):
1641
+ return page_type
1642
+
1643
+ # Fallback: try to infer from style results
1644
+ if style_results:
1645
+ style_name = style_results[0].get("Style Category", "").lower()
1646
+ best_for = style_results[0].get("Best For", "").lower()
1647
+
1648
+ if "dashboard" in best_for or "data" in best_for:
1649
+ return "Dashboard / Data View"
1650
+ elif "landing" in best_for or "marketing" in best_for:
1651
+ return "Landing / Marketing"
1652
+
1653
+ return "General"
1654
+
1655
+
1656
+ # ============ CLI SUPPORT ============
1657
+ if __name__ == "__main__":
1658
+ import argparse
1659
+
1660
+ parser = argparse.ArgumentParser(description="Generate Design System")
1661
+ parser.add_argument("query", help="Search query (e.g., 'SaaS dashboard')")
1662
+ parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name")
1663
+ parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format")
1664
+
1665
+ args = parser.parse_args()
1666
+
1667
+ result = generate_design_system(args.query, args.project_name, args.format)
1668
+ print(result["text"])