@diffra-ai/cli 0.2.0 → 0.2.2

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