dknowc-dsh 1.0.3 → 1.1.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 (173) hide show
  1. package/README.md +9 -4
  2. package/package.json +2 -2
  3. package/skills/dknowc-official-doc-writer/SKILL.md +17 -8
  4. package/skills/dknowc-official-doc-writer/reference/sample_search_result.md +48 -0
  5. package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +75 -0
  6. package/skills/dknowc-official-doc-writer/reference/search_intro.md +72 -8
  7. package/skills/dknowc-official-doc-writer/scripts/register.mjs +1 -1
  8. package/skills/dknowc-ppt-assistant/README.md +54 -0
  9. package/skills/dknowc-ppt-assistant/SKILL.md +151 -0
  10. package/skills/dknowc-ppt-assistant/THIRD_PARTY_NOTICES.md +36 -0
  11. package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
  12. package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
  13. package/skills/dknowc-ppt-assistant/projects/.gitkeep +0 -0
  14. package/skills/dknowc-ppt-assistant/references/content-pack.md +55 -0
  15. package/skills/dknowc-ppt-assistant/references/material_usage.md +51 -0
  16. package/skills/dknowc-ppt-assistant/references/sample_effect.html +89 -0
  17. package/skills/dknowc-ppt-assistant/references/sample_search_result.md +48 -0
  18. package/skills/dknowc-ppt-assistant/references/search_intro.md +79 -0
  19. package/skills/dknowc-ppt-assistant/references/style-presets.md +126 -0
  20. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +81 -0
  21. package/skills/dknowc-ppt-assistant/references/upstream-docs/svg-pipeline.md +842 -0
  22. package/skills/dknowc-ppt-assistant/references/upstream-example/01_cover.svg +28 -0
  23. package/skills/dknowc-ppt-assistant/references/upstream-example/02_quote.svg +38 -0
  24. package/skills/dknowc-ppt-assistant/references/upstream-example/03_origin.svg +96 -0
  25. package/skills/dknowc-ppt-assistant/references/upstream-example/README.md +15 -0
  26. package/skills/dknowc-ppt-assistant/references/upstream-example/design_spec.md +408 -0
  27. package/skills/dknowc-ppt-assistant/references/upstream-example/spec_lock.md +78 -0
  28. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +279 -0
  29. package/skills/dknowc-ppt-assistant/scripts/check_release.py +106 -0
  30. package/skills/dknowc-ppt-assistant/scripts/compact_svg_coordinates.py +345 -0
  31. package/skills/dknowc-ppt-assistant/scripts/config.py +707 -0
  32. package/skills/dknowc-ppt-assistant/scripts/console_encoding.py +33 -0
  33. package/skills/dknowc-ppt-assistant/scripts/error_helper.py +434 -0
  34. package/skills/dknowc-ppt-assistant/scripts/finalize_svg.py +507 -0
  35. package/skills/dknowc-ppt-assistant/scripts/hyperlink_contract.py +399 -0
  36. package/skills/dknowc-ppt-assistant/scripts/initialize.py +182 -0
  37. package/skills/dknowc-ppt-assistant/scripts/language_tags.py +283 -0
  38. package/skills/dknowc-ppt-assistant/scripts/mcp_direct.py +158 -0
  39. package/skills/dknowc-ppt-assistant/scripts/native_payloads.py +655 -0
  40. package/skills/dknowc-ppt-assistant/scripts/pptx_animation_presets.json +3440 -0
  41. package/skills/dknowc-ppt-assistant/scripts/pptx_animations.py +3965 -0
  42. package/skills/dknowc-ppt-assistant/scripts/pptx_effects.py +143 -0
  43. package/skills/dknowc-ppt-assistant/scripts/pptx_opc_validation.py +346 -0
  44. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/__init__.py +130 -0
  45. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-APACHE-2.0.txt +202 -0
  46. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/LICENSE-OPEN-XML-SDK-MIT.txt +23 -0
  47. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/NOTICE.md +54 -0
  48. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeDefinitions.xml +19898 -0
  49. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/presetShapeSemantics.json +1217 -0
  50. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/data/shape_type_values.txt +187 -0
  51. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/errors.py +39 -0
  52. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/formula.py +336 -0
  53. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/loader.py +364 -0
  54. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/models.py +201 -0
  55. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/registry.py +270 -0
  56. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantic_hash.py +456 -0
  57. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/semantics.py +543 -0
  58. package/skills/dknowc-ppt-assistant/scripts/pptx_shapes/xml_safety.py +21 -0
  59. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/__init__.py +21 -0
  60. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/animation_import.py +287 -0
  61. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chart_to_svg.py +2377 -0
  62. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/chartex_to_svg.py +422 -0
  63. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/color_resolver.py +894 -0
  64. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/converter.py +1143 -0
  65. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/custgeom_to_svg.py +165 -0
  66. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/effect_to_svg.py +410 -0
  67. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/emu_units.py +258 -0
  68. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/fill_to_svg.py +816 -0
  69. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/formula_import.py +611 -0
  70. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/hyperlinks.py +93 -0
  71. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/import_diagnostics.py +37 -0
  72. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ln_to_svg.py +362 -0
  73. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/normalized_chart_svg.py +1217 -0
  74. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/ooxml_loader.py +506 -0
  75. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/pic_to_svg.py +653 -0
  76. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_authoring.py +894 -0
  77. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_registry_to_svg.py +216 -0
  78. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/preset_svg_markup.py +198 -0
  79. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/prstgeom_to_svg.py +162 -0
  80. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/shape_walker.py +556 -0
  81. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/slide_to_svg.py +2002 -0
  82. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/tbl_to_svg.py +1841 -0
  83. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/transition_import.py +201 -0
  84. package/skills/dknowc-ppt-assistant/scripts/pptx_to_svg/txbody_to_svg.py +1433 -0
  85. package/skills/dknowc-ppt-assistant/scripts/pptx_transitions.py +3153 -0
  86. package/skills/dknowc-ppt-assistant/scripts/preset_shape_svg.py +450 -0
  87. package/skills/dknowc-ppt-assistant/scripts/project_utils.py +645 -0
  88. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +183 -0
  89. package/skills/dknowc-ppt-assistant/scripts/register_template.py +1327 -0
  90. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1048 -0
  91. package/skills/dknowc-ppt-assistant/scripts/resource_paths.py +282 -0
  92. package/skills/dknowc-ppt-assistant/scripts/shape_boolean_svg.py +189 -0
  93. package/skills/dknowc-ppt-assistant/scripts/slide_roster.py +44 -0
  94. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/__init__.py +12 -0
  95. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/align_embed_images.py +672 -0
  96. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/crop_images.py +370 -0
  97. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_icons.py +564 -0
  98. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/embed_images.py +288 -0
  99. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/fix_image_aspect.py +389 -0
  100. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/flatten_tspan.py +948 -0
  101. package/skills/dknowc-ppt-assistant/scripts/svg_finalize/svg_rect_to_path.py +346 -0
  102. package/skills/dknowc-ppt-assistant/scripts/svg_quality/__init__.py +15 -0
  103. package/skills/dknowc-ppt-assistant/scripts/svg_quality/checker.py +7791 -0
  104. package/skills/dknowc-ppt-assistant/scripts/svg_quality/cli.py +193 -0
  105. package/skills/dknowc-ppt-assistant/scripts/svg_quality/svg_contracts.py +1121 -0
  106. package/skills/dknowc-ppt-assistant/scripts/svg_quality/xml_support.py +35 -0
  107. package/skills/dknowc-ppt-assistant/scripts/svg_quality_checker.py +59 -0
  108. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/__init__.py +37 -0
  109. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/animation_config.py +1622 -0
  110. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/canvas_contract.py +226 -0
  111. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/__init__.py +1 -0
  112. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/context.py +291 -0
  113. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/converter.py +1980 -0
  114. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/elements.py +5272 -0
  115. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/hyperlinks.py +162 -0
  116. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/paths.py +847 -0
  117. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/styles.py +752 -0
  118. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/text_properties.py +796 -0
  119. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_colors.py +283 -0
  120. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/theme_fonts.py +330 -0
  121. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/drawingml/utils.py +3555 -0
  122. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/geometry_properties.py +140 -0
  123. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/__init__.py +356 -0
  124. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_data.py +1449 -0
  125. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_style.py +886 -0
  126. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chart_xml.py +1495 -0
  127. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/chartex.py +272 -0
  128. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/fallback_hash.py +161 -0
  129. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula.py +243 -0
  130. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_ast.py +592 -0
  131. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_compiler.py +96 -0
  132. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_omml.py +1049 -0
  133. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_parser.py +2181 -0
  134. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_profile.py +739 -0
  135. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/formula_run_properties.py +234 -0
  136. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/inline_formula.py +311 -0
  137. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_attributes.py +182 -0
  138. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_common.py +806 -0
  139. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/marker_status.py +190 -0
  140. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/table.py +1113 -0
  141. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/native_objects/workbook.py +216 -0
  142. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/__init__.py +1 -0
  143. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/builder.py +6273 -0
  144. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/cli.py +2059 -0
  145. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/dimensions.py +189 -0
  146. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/discovery.py +120 -0
  147. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/media.py +160 -0
  148. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/narration.py +696 -0
  149. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/notes.py +336 -0
  150. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/slide_xml.py +138 -0
  151. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_structure.py +3457 -0
  152. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/pptx_package/template_validation.py +1536 -0
  153. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/semantic_markers.py +240 -0
  154. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/shape_boolean.py +1355 -0
  155. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/text_outline.py +1121 -0
  156. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/tspan_flattener.py +64 -0
  157. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx/use_expander.py +577 -0
  158. package/skills/dknowc-ppt-assistant/scripts/svg_to_pptx.py +21 -0
  159. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +336 -0
  160. package/skills/dknowc-ppt-assistant/scripts/update_spec.py +404 -0
  161. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +142 -0
  162. package/skills/dknowc-ppt-assistant/workflows/routing.md +38 -0
  163. package/skills/dknowc-trusted-consulting/SKILL.md +21 -5
  164. package/skills/dknowc-trusted-consulting/reference/consult_intro.md +79 -0
  165. package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +31 -0
  166. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +76 -0
  167. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +1 -0
  168. package/skills/dknowc-trusted-search/SKILL.md +30 -2
  169. package/skills/dknowc-trusted-search/reference/sample_search_result.md +33 -0
  170. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +450 -0
  171. package/skills/dknowc-trusted-search/reference/search_intro.md +79 -0
  172. package/skills/dknowc-trusted-search/scripts/register_key.mjs +1 -0
  173. package/src/index.js +7 -2
@@ -0,0 +1,1327 @@
1
+ #!/usr/bin/env python3
2
+ """Register a brand / style / layout / deck template in the global index.
3
+
4
+ Four kinds, four workspace roots, four index files. The shared model lives
5
+ in ``templates/README.md``; each kind's schema lives in its directory README:
6
+
7
+ | --kind | Workspace roots | Index file |
8
+ |---------|-------------------------|-------------------------------|
9
+ | brand | ``templates/brands/`` | ``brands_index.json`` |
10
+ | style | ``templates/styles/`` | ``styles_index.json`` |
11
+ | layout | ``templates/layouts/`` | ``layouts_index.json`` |
12
+ | deck | ``templates/decks/`` | ``decks_index.json`` |
13
+
14
+ Current workspaces keep ``design_spec.md`` and any SVG roster under
15
+ ``<workspace>/templates/``. Assets live in optional ``images/`` / ``icons/``
16
+ directories. Explicitly generated review artifacts go to the optional, ignored
17
+ ``exports/`` directory. Legacy flat roots remain readable for Brand/Layout/Deck;
18
+ Style uses only the current nested one-file contract.
19
+
20
+ Index entry schemas (the JSON file is the single source of truth — README
21
+ files describe the kind and usage in prose but do **not** enumerate templates;
22
+ discovery happens exclusively against the index file):
23
+
24
+ - brand: ``{ summary, primary_color }``
25
+ - style: ``{ summary, keywords[] }``
26
+ - layout: ``{ summary, canvas_format, page_count, page_types[] }``
27
+ - deck: ``{ summary, canvas_format, page_count, primary_color }``
28
+
29
+ Usage::
30
+
31
+ python3 scripts/register_template.py <id> --kind deck # default kind=deck
32
+ python3 scripts/register_template.py <id> --kind layout
33
+ python3 scripts/register_template.py <id> --kind brand
34
+ python3 scripts/register_template.py <id> --kind style
35
+ python3 scripts/register_template.py --rebuild-all --kind deck
36
+ python3 scripts/register_template.py <id> --dry-run
37
+
38
+ ``--rebuild-all`` rebuilds every entry from scratch within the chosen kind;
39
+ recommended for repairing index drift across many templates at once.
40
+
41
+ Project-scoped Brand and Style workspaces are validated, not registered,
42
+ through ``svg_quality_checker.py <workspace>/templates --template-mode``. That
43
+ entry reuses :func:`validate_brand_workspace` or
44
+ :func:`validate_style_workspace`, so each schema has one authority.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import argparse
50
+ import json
51
+ import re
52
+ import sys
53
+ from collections import OrderedDict
54
+ from pathlib import Path
55
+ from xml.etree import ElementTree as ET
56
+
57
+ from console_encoding import configure_utf8_stdio
58
+ from config import CANVAS_FORMATS
59
+
60
+ try:
61
+ import yaml # type: ignore
62
+ except ImportError:
63
+ yaml = None
64
+
65
+
66
+ configure_utf8_stdio()
67
+
68
+
69
+ SCRIPT_DIR = Path(__file__).resolve().parent
70
+ SKILL_DIR = SCRIPT_DIR.parent
71
+ TEMPLATES_DIR = SKILL_DIR / "templates"
72
+
73
+ KIND_CONFIG = {
74
+ "brand": {
75
+ "dir": TEMPLATES_DIR / "brands",
76
+ "index": TEMPLATES_DIR / "brands" / "brands_index.json",
77
+ "id_key": "brand_id",
78
+ "needs_svg_roster": False,
79
+ },
80
+ "style": {
81
+ "dir": TEMPLATES_DIR / "styles",
82
+ "index": TEMPLATES_DIR / "styles" / "styles_index.json",
83
+ "id_key": "style_id",
84
+ "needs_svg_roster": False,
85
+ },
86
+ "layout": {
87
+ "dir": TEMPLATES_DIR / "layouts",
88
+ "index": TEMPLATES_DIR / "layouts" / "layouts_index.json",
89
+ "id_key": "layout_id",
90
+ "needs_svg_roster": True,
91
+ },
92
+ "deck": {
93
+ "dir": TEMPLATES_DIR / "decks",
94
+ "index": TEMPLATES_DIR / "decks" / "decks_index.json",
95
+ "id_key": "deck_id",
96
+ "needs_svg_roster": True,
97
+ },
98
+ }
99
+
100
+ _BRAND_REQUIRED_SECTIONS = (
101
+ ("I", "Brand Overview"),
102
+ ("II", "Color Scheme"),
103
+ ("III", "Typography"),
104
+ ("IV", "Logo"),
105
+ ("V", "Voice & Tone"),
106
+ ("VI", "Icon Style"),
107
+ )
108
+ _BRAND_FORBIDDEN_SECTIONS = (
109
+ "Page Roster",
110
+ "Signature Design Elements",
111
+ )
112
+ _BRAND_ALLOWED_FRONTMATTER_FIELDS = frozenset({
113
+ "brand_id",
114
+ "kind",
115
+ "summary",
116
+ "primary_color",
117
+ })
118
+ _BRAND_PROVENANCE_VALUES = {"fact", "approx", "user"}
119
+ _BRAND_ASSET_REF_RE = re.compile(
120
+ r"`((?:\.\./)+(?:images|icons)/[^`]+)`"
121
+ )
122
+ _STYLE_REQUIRED_SECTIONS = (
123
+ ("I", "Style Overview"),
124
+ ("II", "Communication Method"),
125
+ ("III", "Page Role Vocabulary"),
126
+ ("IV", "Evidence & Data Expression"),
127
+ ("V", "Visual System Defaults"),
128
+ ("VI", "Image & Icon Direction"),
129
+ ("VII", "Review Focus"),
130
+ )
131
+ _STYLE_FORBIDDEN_SECTIONS = (
132
+ "Brand Overview",
133
+ "Template Overview",
134
+ "Color Scheme",
135
+ "Typography",
136
+ "Logo",
137
+ "Voice & Tone",
138
+ "Icon Style",
139
+ "Assets",
140
+ "Signature Design Elements",
141
+ "Page Roster",
142
+ "Placeholder Overrides",
143
+ )
144
+ _STYLE_REQUIRED_FIELDS = {
145
+ "I. Style Overview": (
146
+ "Style Name",
147
+ "Best Fit",
148
+ "Reusable Intent",
149
+ "Sources",
150
+ ),
151
+ "II. Communication Method": (
152
+ "Argument Flow",
153
+ "Page Message Discipline",
154
+ "Claim Discipline",
155
+ ),
156
+ "IV. Evidence & Data Expression": (
157
+ "Argument Trace",
158
+ "Charts",
159
+ "Tables",
160
+ "Sources",
161
+ "Native Editability",
162
+ ),
163
+ "V. Visual System Defaults": (
164
+ "Composition",
165
+ "Density",
166
+ "Decoration",
167
+ "Color Behavior",
168
+ "Typography Character",
169
+ ),
170
+ "VI. Image & Icon Direction": (
171
+ "Image Usage",
172
+ "Image Treatment",
173
+ "Icon Treatment",
174
+ ),
175
+ }
176
+ _STYLE_CUSTOM_FIELDS = (
177
+ (
178
+ "II. Communication Method",
179
+ "Preferred Mode",
180
+ "Mode Behavior",
181
+ "Mode References",
182
+ SKILL_DIR / "references" / "modes",
183
+ ),
184
+ (
185
+ "V. Visual System Defaults",
186
+ "Preferred Visual Style",
187
+ "Visual Style Behavior",
188
+ "Visual Style References",
189
+ SKILL_DIR / "references" / "visual-styles",
190
+ ),
191
+ (
192
+ "VI. Image & Icon Direction",
193
+ "Preferred Image Rendering",
194
+ "Image Rendering Behavior",
195
+ "Image Rendering References",
196
+ SKILL_DIR / "references" / "image-renderings",
197
+ ),
198
+ )
199
+ _STYLE_FORBIDDEN_FIELDS = (
200
+ "Brand Overview",
201
+ "Template Overview",
202
+ "Color Scheme",
203
+ "Typography",
204
+ "Signature Design Elements",
205
+ "Page Roster",
206
+ "Placeholder Overrides",
207
+ "Target Audience",
208
+ "Communication Objective",
209
+ "Desired Outcome",
210
+ "Core Message",
211
+ "Delivery Context",
212
+ "Artifact Afterlife",
213
+ "Application Context",
214
+ "Content Outline",
215
+ "Page Count",
216
+ "Page Types",
217
+ "Page Order",
218
+ "Page Sequence",
219
+ "Canvas Format",
220
+ "Canvas Width",
221
+ "Canvas Height",
222
+ "Canvas ViewBox",
223
+ "Replication Mode",
224
+ "Native Structure Mode",
225
+ "Master",
226
+ "Layout",
227
+ "Placeholders",
228
+ "Page Assignment",
229
+ "Icon Inventory",
230
+ "Image Resources",
231
+ "Primary Color",
232
+ "Logo",
233
+ "Voice & Tone",
234
+ "Icon Style",
235
+ "Assets",
236
+ )
237
+ _STYLE_ALLOWED_FRONTMATTER_FIELDS = frozenset({
238
+ "style_id",
239
+ "kind",
240
+ "summary",
241
+ "keywords",
242
+ })
243
+ _STYLE_REVIEW_TRIGGER_MARKER = "<!-- visual-review-trigger: explicit-user-only -->"
244
+ _HEX_COLOR_RE = re.compile(r"#[0-9A-Fa-f]{6}")
245
+ _PORTABLE_STYLE_ID_RE = re.compile(r"^\w[\w.-]*$")
246
+
247
+
248
+ # ---------------------------------------------------------------------------
249
+ # design_spec.md parsing
250
+ # ---------------------------------------------------------------------------
251
+
252
+ class SpecParseError(RuntimeError):
253
+ """Raised when a design_spec.md cannot be turned into an index entry."""
254
+
255
+
256
+ def _read_spec(spec_path: Path) -> tuple[dict | None, str]:
257
+ """Split YAML frontmatter from the body. Returns ``(frontmatter, body)``."""
258
+ text = spec_path.read_text(encoding="utf-8")
259
+ if not text.startswith("---\n"):
260
+ return None, text
261
+ end = text.find("\n---\n", 4)
262
+ if end == -1:
263
+ return None, text
264
+ fm_block = text[4:end]
265
+ body = text[end + 5:]
266
+ if yaml is None:
267
+ raise SpecParseError(
268
+ "design_spec.md has YAML frontmatter but PyYAML is not installed; "
269
+ "install pyyaml or remove the frontmatter."
270
+ )
271
+ try:
272
+ data = yaml.safe_load(fm_block) or {}
273
+ except yaml.YAMLError as exc:
274
+ raise SpecParseError(f"invalid YAML frontmatter: {exc}") from exc
275
+ if not isinstance(data, dict):
276
+ raise SpecParseError("YAML frontmatter must be a mapping")
277
+ return data, body
278
+
279
+
280
+ def _extract_section_field(body: str, section_title: str, labels: list[str]) -> str | None:
281
+ section_re = re.compile(
282
+ rf"^##\s+{re.escape(section_title)}\b.*?(?=^##\s+|\Z)",
283
+ re.MULTILINE | re.DOTALL,
284
+ )
285
+ section_match = section_re.search(body)
286
+ if section_match is None:
287
+ return None
288
+ section = section_match.group(0)
289
+
290
+ for label in labels:
291
+ row = re.search(
292
+ rf"^\|\s*\*?\*?{re.escape(label)}\*?\*?\s*\|\s*(.+?)\s*\|",
293
+ section, re.MULTILINE | re.IGNORECASE,
294
+ )
295
+ if row:
296
+ return _clean_field_value(row.group(1))
297
+
298
+ bullet = re.search(
299
+ rf"^[-*]\s*\*?\*?{re.escape(label)}\*?\*?\s*[::]\s*(.+?)\s*$",
300
+ section, re.MULTILINE | re.IGNORECASE,
301
+ )
302
+ if bullet:
303
+ return _clean_field_value(bullet.group(1))
304
+ return None
305
+
306
+
307
+ def _clean_field_value(value: str) -> str:
308
+ value = value.strip()
309
+ value = re.sub(r"^[`*_]+", "", value)
310
+ value = re.sub(r"[`*_]+$", "", value)
311
+ return value.strip()
312
+
313
+
314
+ def _find_first_color(section: str) -> str | None:
315
+ match = re.search(r"`(#[0-9A-Fa-f]{3,8})`", section)
316
+ return match.group(1).upper() if match else None
317
+
318
+
319
+ def _extract_primary_color(body: str) -> str | None:
320
+ section_match = re.search(
321
+ r"^##\s+[IVX]+\.\s+Color Scheme\b.*?(?=^##\s+|\Z)",
322
+ body, re.MULTILINE | re.DOTALL,
323
+ )
324
+ if section_match is None:
325
+ return None
326
+ return _find_first_color(section_match.group(0))
327
+
328
+
329
+ def _summary_from_use_cases(use_cases: str | None) -> str | None:
330
+ if not use_cases:
331
+ return None
332
+ cleaned = use_cases.strip().rstrip(".")
333
+ if not cleaned:
334
+ return None
335
+ return f"{cleaned}."
336
+
337
+
338
+ def _template_content_dir(template_root: Path) -> Path:
339
+ """Resolve the canonical source directory, with legacy-flat compatibility."""
340
+ nested = template_root / "templates"
341
+ if (nested / "design_spec.md").is_file():
342
+ return nested
343
+ if (template_root / "design_spec.md").is_file():
344
+ return template_root
345
+ raise SpecParseError(
346
+ f"missing templates/design_spec.md or legacy design_spec.md in {template_root}"
347
+ )
348
+
349
+
350
+ def _list_pages(template_dir: Path) -> list[str]:
351
+ return sorted(p.stem for p in template_dir.glob("*.svg"))
352
+
353
+
354
+ def _derive_page_types(pages: list[str]) -> list[str]:
355
+ """Derive canonical page-type list from SVG filenames (strips leading 'NN_')."""
356
+ types: list[str] = []
357
+ seen: set[str] = set()
358
+ for p in pages:
359
+ m = re.match(r"^\d+[a-z]?_(.+)$", p)
360
+ role = m.group(1) if m else p
361
+ if role not in seen:
362
+ seen.add(role)
363
+ types.append(role)
364
+ return types
365
+
366
+
367
+ def _numbered_section(body: str, title: str) -> str | None:
368
+ match = re.search(
369
+ rf"^##\s+[IVX]+\.\s+{re.escape(title)}\s*$.*?(?=^##\s+|\Z)",
370
+ body,
371
+ re.MULTILINE | re.DOTALL,
372
+ )
373
+ return match.group(0) if match else None
374
+
375
+
376
+ def _markdown_subsection(body: str, title: str) -> str | None:
377
+ match = re.search(
378
+ rf"^###\s+{re.escape(title)}\s*$.*?(?=^#{{2,3}}\s+|\Z)",
379
+ body,
380
+ re.MULTILINE | re.DOTALL,
381
+ )
382
+ return match.group(0) if match else None
383
+
384
+
385
+ def _markdown_table_rows(section: str) -> list[list[str]]:
386
+ rows: list[list[str]] = []
387
+ for line in section.splitlines():
388
+ if not line.lstrip().startswith("|"):
389
+ continue
390
+ cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
391
+ if not cells or all(re.fullmatch(r":?-{3,}:?", cell) for cell in cells):
392
+ continue
393
+ rows.append(cells)
394
+ return rows
395
+
396
+
397
+ def _style_value_is_substantive(value: str | None) -> bool:
398
+ if value is None:
399
+ return False
400
+ cleaned = _clean_field_value(value)
401
+ if not cleaned or re.fullmatch(r"<[^>]+>", cleaned):
402
+ return False
403
+ return cleaned.casefold() not in {"tbd", "todo", "n/a", "none", "-", "—"}
404
+
405
+
406
+ def _style_field_is_declared(body: str, label: str) -> bool:
407
+ escaped = re.escape(label)
408
+ return bool(
409
+ re.search(
410
+ rf"^\s*(?:>\s*)?(?:[-*]\s*)?"
411
+ rf"\*{{0,2}}{escaped}\*{{0,2}}\s*[::]",
412
+ body,
413
+ re.MULTILINE | re.IGNORECASE,
414
+ )
415
+ or re.search(
416
+ rf"^\|\s*\*{{0,2}}{escaped}\*{{0,2}}\s*\|",
417
+ body,
418
+ re.MULTILINE | re.IGNORECASE,
419
+ )
420
+ )
421
+
422
+
423
+ def _validate_brand_spec(
424
+ expected_template_id: str | None,
425
+ template_root: Path,
426
+ template_dir: Path,
427
+ frontmatter: dict,
428
+ body: str,
429
+ pages: list[str],
430
+ ) -> None:
431
+ """Reject brand workspaces that cannot be locked as portable identity truth.
432
+
433
+ Args:
434
+ expected_template_id: Registry key to match in library scope. Project
435
+ workspaces pass ``None`` because their root name is the project id,
436
+ not the portable brand id.
437
+ template_root: Brand workspace root containing assets and templates.
438
+ template_dir: Directory containing ``design_spec.md`` and any page SVGs.
439
+ frontmatter: Parsed design-spec frontmatter.
440
+ body: Markdown content after the frontmatter block.
441
+ pages: SVG page stems discovered beside the design spec.
442
+ """
443
+ errors: list[str] = []
444
+
445
+ declared_id = str(frontmatter.get("brand_id") or "").strip()
446
+ if not declared_id:
447
+ errors.append("frontmatter brand_id must be non-empty")
448
+ elif expected_template_id is not None and declared_id != expected_template_id:
449
+ errors.append(
450
+ "frontmatter brand_id must match directory "
451
+ f"{expected_template_id!r}, "
452
+ f"got {declared_id!r}"
453
+ )
454
+
455
+ declared_kind = str(frontmatter.get("kind") or "").strip()
456
+ if declared_kind != "brand":
457
+ errors.append(
458
+ "frontmatter kind must be 'brand', "
459
+ f"got {declared_kind!r}"
460
+ )
461
+
462
+ if not str(frontmatter.get("summary") or "").strip():
463
+ errors.append("frontmatter summary must be non-empty")
464
+
465
+ unexpected_fields = sorted(
466
+ set(frontmatter) - _BRAND_ALLOWED_FRONTMATTER_FIELDS
467
+ )
468
+ if unexpected_fields:
469
+ errors.append(
470
+ "brand frontmatter contains non-identity field(s): "
471
+ + ", ".join(unexpected_fields)
472
+ )
473
+
474
+ if pages:
475
+ errors.append(
476
+ "brand workspaces must not contain page SVGs under templates/: "
477
+ + ", ".join(f"{page}.svg" for page in pages)
478
+ )
479
+
480
+ for numeral, title in _BRAND_REQUIRED_SECTIONS:
481
+ if re.search(
482
+ rf"^##\s+{numeral}\.\s+{re.escape(title)}\s*$",
483
+ body,
484
+ re.MULTILINE,
485
+ ) is None:
486
+ errors.append(f"missing required section: {numeral}. {title}")
487
+
488
+ for title in _BRAND_FORBIDDEN_SECTIONS:
489
+ if re.search(
490
+ rf"^##\s+(?:[IVX]+\.\s+)?{re.escape(title)}\s*$",
491
+ body,
492
+ re.MULTILINE,
493
+ ):
494
+ errors.append(f"brand scope must not declare section: {title}")
495
+
496
+ declared_primary = str(frontmatter.get("primary_color") or "").strip()
497
+ if _HEX_COLOR_RE.fullmatch(declared_primary) is None:
498
+ errors.append(
499
+ "frontmatter primary_color must use #RRGGBB, "
500
+ f"got {declared_primary!r}"
501
+ )
502
+
503
+ color_section = _numbered_section(body, "Color Scheme") or ""
504
+ primary_rows: list[str] = []
505
+ for line in color_section.splitlines():
506
+ if not line.lstrip().startswith("|"):
507
+ continue
508
+ cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
509
+ if len(cells) < 3:
510
+ continue
511
+ role = cells[0].strip("` ")
512
+ raw_color = cells[1].strip("` ")
513
+ if role.lower() == "role" or re.fullmatch(r":?-+:?", role):
514
+ continue
515
+ if _HEX_COLOR_RE.fullmatch(raw_color) is None:
516
+ errors.append(
517
+ f"color row {role!r} must use #RRGGBB, "
518
+ f"got {raw_color!r}"
519
+ )
520
+ continue
521
+ if role.lower() == "primary":
522
+ primary_rows.append(raw_color.upper())
523
+ provenance = cells[2].strip("` ").lower()
524
+ if provenance not in _BRAND_PROVENANCE_VALUES:
525
+ errors.append(
526
+ f"color {raw_color} must declare provenance as "
527
+ "fact, approx, or user"
528
+ )
529
+
530
+ if not primary_rows:
531
+ errors.append("Color Scheme must declare one primary color row")
532
+ elif len(primary_rows) > 1:
533
+ errors.append("Color Scheme must declare only one primary color row")
534
+ elif (
535
+ _HEX_COLOR_RE.fullmatch(declared_primary)
536
+ and primary_rows[0] != declared_primary.upper()
537
+ ):
538
+ errors.append(
539
+ "Color Scheme primary must match frontmatter primary_color: "
540
+ f"{primary_rows[0]} != {declared_primary.upper()}"
541
+ )
542
+
543
+ root = template_root.resolve()
544
+ for raw_ref in sorted(set(_BRAND_ASSET_REF_RE.findall(body))):
545
+ asset = (template_dir / raw_ref).resolve()
546
+ try:
547
+ asset.relative_to(root)
548
+ except ValueError:
549
+ errors.append(f"asset reference escapes brand workspace: {raw_ref}")
550
+ continue
551
+ if not asset.is_file():
552
+ errors.append(f"referenced brand asset does not exist: {raw_ref}")
553
+
554
+ if errors:
555
+ details = "\n".join(f" - {error}" for error in errors)
556
+ raise SpecParseError(f"invalid brand specification:\n{details}")
557
+
558
+
559
+ def _validate_style_spec(
560
+ expected_template_id: str | None,
561
+ template_root: Path,
562
+ template_dir: Path,
563
+ frontmatter: dict,
564
+ body: str,
565
+ ) -> None:
566
+ """Reject Style workspaces outside the roster-free method contract."""
567
+ errors: list[str] = []
568
+
569
+ raw_style_id = frontmatter.get("style_id")
570
+ declared_id = raw_style_id.strip() if isinstance(raw_style_id, str) else ""
571
+ if not declared_id:
572
+ errors.append("frontmatter style_id must be a non-empty string")
573
+ else:
574
+ if (
575
+ _PORTABLE_STYLE_ID_RE.fullmatch(declared_id) is None
576
+ or declared_id in {".", ".."}
577
+ or declared_id.endswith(".")
578
+ ):
579
+ errors.append(
580
+ "frontmatter style_id must be a filesystem-safe portable slug"
581
+ )
582
+ if (
583
+ expected_template_id is not None
584
+ and declared_id != expected_template_id
585
+ ):
586
+ errors.append(
587
+ "frontmatter style_id must match directory "
588
+ f"{expected_template_id!r}, got {declared_id!r}"
589
+ )
590
+
591
+ raw_kind = frontmatter.get("kind")
592
+ declared_kind = raw_kind.strip() if isinstance(raw_kind, str) else ""
593
+ if declared_kind != "style":
594
+ errors.append(
595
+ "frontmatter kind must be 'style', "
596
+ f"got {declared_kind!r}"
597
+ )
598
+
599
+ raw_summary = frontmatter.get("summary")
600
+ if not isinstance(raw_summary, str) or not _style_value_is_substantive(
601
+ raw_summary
602
+ ):
603
+ errors.append("frontmatter summary must be a non-empty string")
604
+
605
+ non_string_fields = [key for key in frontmatter if not isinstance(key, str)]
606
+ if non_string_fields:
607
+ errors.append("style frontmatter field names must be strings")
608
+ unexpected_fields = sorted(
609
+ key
610
+ for key in frontmatter
611
+ if isinstance(key, str) and key not in _STYLE_ALLOWED_FRONTMATTER_FIELDS
612
+ )
613
+ if unexpected_fields:
614
+ errors.append(
615
+ "style frontmatter contains unsupported field(s): "
616
+ + ", ".join(unexpected_fields)
617
+ )
618
+
619
+ keywords = frontmatter.get("keywords")
620
+ if (
621
+ not isinstance(keywords, list)
622
+ or not 3 <= len(keywords) <= 5
623
+ or not all(
624
+ isinstance(item, str) and _style_value_is_substantive(item)
625
+ for item in keywords
626
+ )
627
+ ):
628
+ errors.append(
629
+ "frontmatter keywords must contain 3-5 non-empty strings"
630
+ )
631
+ elif len({item.strip().casefold() for item in keywords}) != len(keywords):
632
+ errors.append("frontmatter keywords must be unique")
633
+
634
+ unexpected_source_entries = sorted(
635
+ path.relative_to(template_dir).as_posix()
636
+ + ("/" if path.is_dir() else "")
637
+ for path in template_dir.rglob("*")
638
+ if path.relative_to(template_dir).as_posix() != "design_spec.md"
639
+ )
640
+ if unexpected_source_entries:
641
+ errors.append(
642
+ "style workspaces must contain only templates/design_spec.md; "
643
+ "unexpected template entry(s): "
644
+ + ", ".join(unexpected_source_entries)
645
+ )
646
+
647
+ if expected_template_id is not None:
648
+ unexpected_workspace_entries = sorted(
649
+ path.relative_to(template_root).as_posix()
650
+ + ("/" if path.is_dir() else "")
651
+ for path in template_root.rglob("*")
652
+ if path.relative_to(template_root).as_posix()
653
+ not in {"templates", "templates/design_spec.md"}
654
+ )
655
+ if unexpected_workspace_entries:
656
+ errors.append(
657
+ "library Style workspaces must contain only "
658
+ "templates/design_spec.md; unexpected workspace entry(s): "
659
+ + ", ".join(unexpected_workspace_entries)
660
+ )
661
+
662
+ h1_headings = re.findall(r"^#\s+(.+?)\s*$", body, re.MULTILINE)
663
+ if len(h1_headings) != 1:
664
+ errors.append(
665
+ "style body must contain exactly one document-title H1; got "
666
+ f"{len(h1_headings)}"
667
+ )
668
+
669
+ expected_headings = [
670
+ f"{numeral}. {title}" for numeral, title in _STYLE_REQUIRED_SECTIONS
671
+ ]
672
+ actual_headings = re.findall(r"^##\s+(.+?)\s*$", body, re.MULTILINE)
673
+ if actual_headings != expected_headings:
674
+ errors.append(
675
+ "style body must contain exactly the required I-VII sections in "
676
+ "order; got: " + (", ".join(actual_headings) or "none")
677
+ )
678
+
679
+ nested_headings = re.findall(
680
+ r"^(#{3,6})\s+(.+?)\s*$",
681
+ body,
682
+ re.MULTILINE,
683
+ )
684
+ unexpected_nested_headings = [
685
+ f"{marks} {title}"
686
+ for marks, title in nested_headings
687
+ if len(marks) != 3
688
+ or title not in {"Fallback Color Scheme", "Fallback Typography"}
689
+ ]
690
+ if unexpected_nested_headings:
691
+ errors.append(
692
+ "style body contains unsupported nested heading(s): "
693
+ + ", ".join(unexpected_nested_headings)
694
+ )
695
+ allowed_h3 = [title for marks, title in nested_headings if len(marks) == 3]
696
+ if len(allowed_h3) != len(set(allowed_h3)):
697
+ errors.append("style fallback subsections must not be repeated")
698
+
699
+ for title in _STYLE_FORBIDDEN_SECTIONS:
700
+ if re.search(
701
+ rf"^#{{1,6}}\s+(?:[IVX]+\.\s+)?{re.escape(title)}\s*$",
702
+ body,
703
+ re.MULTILINE,
704
+ ):
705
+ errors.append(f"style scope must not declare section: {title}")
706
+
707
+ for section_title, labels in _STYLE_REQUIRED_FIELDS.items():
708
+ section_name = section_title.split(". ", 1)[1]
709
+ if _numbered_section(body, section_name) is None:
710
+ continue
711
+ for label in labels:
712
+ value = _extract_section_field(body, section_title, [label])
713
+ if not _style_value_is_substantive(value):
714
+ errors.append(
715
+ f"{section_title} must declare a non-empty {label} field"
716
+ )
717
+
718
+ role_section = _numbered_section(body, "Page Role Vocabulary") or ""
719
+ role_rows = [
720
+ row
721
+ for row in _markdown_table_rows(role_section)
722
+ if row and row[0].casefold() != "role"
723
+ ]
724
+ if not any(
725
+ len(row) >= 4
726
+ and all(_style_value_is_substantive(cell) for cell in row[:4])
727
+ for row in role_rows
728
+ ):
729
+ errors.append(
730
+ "III. Page Role Vocabulary must contain at least one complete "
731
+ "four-column role row"
732
+ )
733
+
734
+ for (
735
+ section_title,
736
+ preferred_label,
737
+ behavior_label,
738
+ references_label,
739
+ catalog_dir,
740
+ ) in _STYLE_CUSTOM_FIELDS:
741
+ preferred = _extract_section_field(
742
+ body,
743
+ section_title,
744
+ [preferred_label],
745
+ )
746
+ behavior = _extract_section_field(
747
+ body,
748
+ section_title,
749
+ [behavior_label],
750
+ )
751
+ references = _extract_section_field(
752
+ body,
753
+ section_title,
754
+ [references_label],
755
+ )
756
+ preferred_text = _clean_field_value(preferred or "")
757
+ catalog_ids = {
758
+ path.stem
759
+ for path in catalog_dir.glob("*.md")
760
+ if not path.stem.startswith("_")
761
+ }
762
+ is_custom = bool(
763
+ re.match(r"^custom(?:\b|\s*[:—-])", preferred_text, re.IGNORECASE)
764
+ )
765
+ if is_custom and not _style_value_is_substantive(behavior):
766
+ errors.append(
767
+ f"{behavior_label} is required when {preferred_label} is custom"
768
+ )
769
+ if not is_custom and _style_value_is_substantive(behavior):
770
+ errors.append(
771
+ f"{behavior_label} is allowed only when {preferred_label} is custom"
772
+ )
773
+ if not is_custom and _style_value_is_substantive(references):
774
+ errors.append(
775
+ f"{references_label} is allowed only when "
776
+ f"{preferred_label} is custom"
777
+ )
778
+ if (
779
+ _style_value_is_substantive(preferred)
780
+ and not is_custom
781
+ and preferred_text not in catalog_ids
782
+ ):
783
+ errors.append(
784
+ f"{preferred_label} references unknown catalog id "
785
+ f"{preferred_text!r}"
786
+ )
787
+ if is_custom and _style_value_is_substantive(references):
788
+ catalog_references = [
789
+ _clean_field_value(item)
790
+ for item in (references or "").split(",")
791
+ ]
792
+ if any(not item for item in catalog_references):
793
+ errors.append(
794
+ f"{references_label} must be a comma-separated list of "
795
+ "catalog ids"
796
+ )
797
+ duplicates = sorted(
798
+ item
799
+ for item in set(catalog_references)
800
+ if catalog_references.count(item) > 1
801
+ )
802
+ if duplicates:
803
+ errors.append(
804
+ f"{references_label} repeats catalog id(s): "
805
+ + ", ".join(duplicates)
806
+ )
807
+ unknown_references = sorted(
808
+ item
809
+ for item in set(catalog_references)
810
+ if item == "custom" or item not in catalog_ids
811
+ )
812
+ if unknown_references:
813
+ errors.append(
814
+ f"{references_label} references unknown catalog id(s): "
815
+ + ", ".join(unknown_references)
816
+ )
817
+
818
+ visual_section = _numbered_section(body, "Visual System Defaults") or ""
819
+ fallback_colors = _markdown_subsection(body, "Fallback Color Scheme")
820
+ if fallback_colors is not None:
821
+ if "### Fallback Color Scheme" not in visual_section:
822
+ errors.append("Fallback Color Scheme must appear under section V")
823
+ color_rows = [
824
+ row
825
+ for row in _markdown_table_rows(fallback_colors)
826
+ if row and row[0].casefold() != "role"
827
+ ]
828
+ if not color_rows:
829
+ errors.append("Fallback Color Scheme must contain at least one row")
830
+ for row in color_rows:
831
+ if (
832
+ len(row) < 3
833
+ or not _style_value_is_substantive(row[0])
834
+ or _HEX_COLOR_RE.fullmatch(row[1].strip("` ")) is None
835
+ or not _style_value_is_substantive(row[2])
836
+ ):
837
+ errors.append(
838
+ "Fallback Color Scheme rows must be Role | #RRGGBB | Purpose"
839
+ )
840
+ break
841
+
842
+ fallback_typography = _markdown_subsection(body, "Fallback Typography")
843
+ if fallback_typography is not None:
844
+ if "### Fallback Typography" not in visual_section:
845
+ errors.append("Fallback Typography must appear under section V")
846
+ typography_rows = [
847
+ row
848
+ for row in _markdown_table_rows(fallback_typography)
849
+ if row and row[0].casefold() != "role"
850
+ ]
851
+ if not any(
852
+ len(row) >= 4
853
+ and all(_style_value_is_substantive(cell) for cell in row[:4])
854
+ for row in typography_rows
855
+ ):
856
+ errors.append(
857
+ "Fallback Typography must contain at least one complete "
858
+ "four-column row"
859
+ )
860
+
861
+ review_section = _numbered_section(body, "Review Focus") or ""
862
+ if review_section.count(_STYLE_REVIEW_TRIGGER_MARKER) != 1:
863
+ errors.append(
864
+ "VII. Review Focus must contain exactly one "
865
+ f"{_STYLE_REVIEW_TRIGGER_MARKER} marker"
866
+ )
867
+ review_items = re.findall(r"^[-*]\s+(.+?)\s*$", review_section, re.MULTILINE)
868
+ if not any(_style_value_is_substantive(item) for item in review_items):
869
+ errors.append("VII. Review Focus must contain at least one check")
870
+
871
+ for label in _STYLE_FORBIDDEN_FIELDS:
872
+ if _style_field_is_declared(body, label):
873
+ errors.append(f"style scope must not declare field: {label}")
874
+
875
+ if errors:
876
+ details = "\n".join(f" - {error}" for error in errors)
877
+ raise SpecParseError(f"invalid style specification:\n{details}")
878
+
879
+
880
+ def _validate_svg_template_spec(
881
+ kind: str,
882
+ template_id: str,
883
+ template_dir: Path,
884
+ frontmatter: dict,
885
+ pages: list[str],
886
+ ) -> None:
887
+ """Reject Layout/Deck workspaces whose registry facts drift from SVGs."""
888
+ errors: list[str] = []
889
+ id_key = KIND_CONFIG[kind]["id_key"]
890
+ declared_id = str(frontmatter.get(id_key) or "").strip()
891
+ if declared_id != template_id:
892
+ errors.append(
893
+ f"frontmatter {id_key} must match directory {template_id!r}, "
894
+ f"got {declared_id!r}"
895
+ )
896
+ declared_kind = str(frontmatter.get("kind") or "").strip()
897
+ if declared_kind != kind:
898
+ errors.append(
899
+ f"frontmatter kind must be {kind!r}, got {declared_kind!r}"
900
+ )
901
+ if not str(frontmatter.get("summary") or "").strip():
902
+ errors.append("frontmatter summary must be non-empty")
903
+ if not pages:
904
+ errors.append(f"{kind} workspace must contain at least one template SVG")
905
+
906
+ raw_page_count = frontmatter.get("page_count")
907
+ if isinstance(raw_page_count, bool) or not isinstance(raw_page_count, int):
908
+ errors.append("frontmatter page_count must be an integer")
909
+ elif raw_page_count != len(pages):
910
+ errors.append(
911
+ f"frontmatter page_count is {raw_page_count}, but templates/ "
912
+ f"contains {len(pages)} SVG files"
913
+ )
914
+
915
+ canvas_format = str(frontmatter.get("canvas_format") or "").strip()
916
+ canvas = CANVAS_FORMATS.get(canvas_format)
917
+ if canvas is None:
918
+ errors.append(
919
+ "frontmatter canvas_format must be one of: "
920
+ + ", ".join(sorted(CANVAS_FORMATS))
921
+ )
922
+ else:
923
+ expected_canvas_fields = {
924
+ "canvas_width": canvas["width"],
925
+ "canvas_height": canvas["height"],
926
+ "canvas_viewbox": canvas["viewbox"],
927
+ }
928
+ for field, expected in expected_canvas_fields.items():
929
+ actual = frontmatter.get(field)
930
+ if str(actual) != str(expected):
931
+ errors.append(
932
+ f"frontmatter {field} must be {expected!r} for "
933
+ f"{canvas_format}, got {actual!r}"
934
+ )
935
+
936
+ if frontmatter.get("native_structure_mode") != "structured":
937
+ errors.append(
938
+ "frontmatter native_structure_mode must be 'structured'"
939
+ )
940
+ if frontmatter.get("replication_mode") not in {
941
+ "standard",
942
+ "fidelity",
943
+ "mirror",
944
+ }:
945
+ errors.append(
946
+ "frontmatter replication_mode must be standard, fidelity, or mirror"
947
+ )
948
+
949
+ if kind == "layout":
950
+ raw_page_types = frontmatter.get("page_types")
951
+ expected_page_types = _derive_page_types(pages)
952
+ if not isinstance(raw_page_types, list) or not all(
953
+ isinstance(item, str) and item.strip()
954
+ for item in raw_page_types
955
+ ):
956
+ errors.append("frontmatter page_types must be a non-empty string list")
957
+ elif raw_page_types != expected_page_types:
958
+ errors.append(
959
+ "frontmatter page_types must exactly match the SVG filename "
960
+ f"roster: expected {expected_page_types!r}, got {raw_page_types!r}"
961
+ )
962
+ else:
963
+ primary_color = str(frontmatter.get("primary_color") or "").strip()
964
+ if _HEX_COLOR_RE.fullmatch(primary_color) is None:
965
+ errors.append(
966
+ "frontmatter primary_color must use #RRGGBB, "
967
+ f"got {primary_color!r}"
968
+ )
969
+
970
+ svg_paths = [template_dir / f"{page}.svg" for page in pages]
971
+ if canvas is not None:
972
+ expected_viewbox = str(canvas["viewbox"])
973
+ for svg_path in svg_paths:
974
+ try:
975
+ root = ET.parse(svg_path).getroot()
976
+ except (OSError, ET.ParseError) as exc:
977
+ errors.append(f"{svg_path.name} is not valid SVG XML: {exc}")
978
+ continue
979
+ actual_canvas = (
980
+ root.get("width"),
981
+ root.get("height"),
982
+ root.get("viewBox"),
983
+ )
984
+ expected_canvas = (
985
+ str(canvas["width"]),
986
+ str(canvas["height"]),
987
+ expected_viewbox,
988
+ )
989
+ if actual_canvas != expected_canvas:
990
+ errors.append(
991
+ f"{svg_path.name} canvas is {actual_canvas!r}, expected "
992
+ f"{expected_canvas!r}"
993
+ )
994
+
995
+ if svg_paths:
996
+ try:
997
+ from svg_to_pptx.pptx_package.template_structure import (
998
+ TemplateStructureError,
999
+ parse_template_slides,
1000
+ )
1001
+ except ImportError as exc:
1002
+ errors.append(f"structured SVG roster is invalid: {exc}")
1003
+ else:
1004
+ try:
1005
+ parse_template_slides(svg_paths)
1006
+ except TemplateStructureError as exc:
1007
+ errors.append(f"structured SVG roster is invalid: {exc}")
1008
+
1009
+ if errors:
1010
+ details = "\n".join(f" - {error}" for error in errors)
1011
+ raise SpecParseError(f"invalid {kind} specification:\n{details}")
1012
+
1013
+
1014
+ # ---------------------------------------------------------------------------
1015
+ # Per-kind extraction
1016
+ # ---------------------------------------------------------------------------
1017
+
1018
+ def _extract_entry(
1019
+ kind: str,
1020
+ template_id: str | None,
1021
+ template_dir: Path,
1022
+ ) -> dict:
1023
+ """Build the index entry + extras for a single template."""
1024
+ template_root = template_dir
1025
+ template_dir = _template_content_dir(template_root)
1026
+ if kind == "style" and template_dir == template_root:
1027
+ raise SpecParseError(
1028
+ "Style workspaces require templates/design_spec.md; "
1029
+ "legacy-flat design_spec.md is not supported"
1030
+ )
1031
+ spec_path = template_dir / "design_spec.md"
1032
+
1033
+ frontmatter, body = _read_spec(spec_path)
1034
+ fm = frontmatter or {}
1035
+
1036
+ declared_kind = fm.get("kind")
1037
+ if declared_kind not in (None, kind):
1038
+ raise SpecParseError(
1039
+ f"design_spec.md frontmatter declares kind={declared_kind!r}; "
1040
+ f"expected kind={kind!r} — use --kind {declared_kind} instead"
1041
+ )
1042
+
1043
+ raw_summary = fm.get("summary")
1044
+ summary = raw_summary.strip() if isinstance(raw_summary, str) else ""
1045
+ if not summary:
1046
+ section_title = (
1047
+ "I. Brand Overview" if kind == "brand" else "I. Template Overview"
1048
+ )
1049
+ summary = (_summary_from_use_cases(
1050
+ _extract_section_field(body, section_title, ["Use Cases", "Use cases"])
1051
+ ) or "").strip()
1052
+
1053
+ pages = _list_pages(template_dir)
1054
+ primary_color = fm.get("primary_color") or _extract_primary_color(body) or ""
1055
+ resolved_template_id = (
1056
+ template_id
1057
+ or str(fm.get(KIND_CONFIG[kind]["id_key"]) or "").strip()
1058
+ or template_root.name
1059
+ )
1060
+
1061
+ if kind == "brand":
1062
+ _validate_brand_spec(
1063
+ template_id,
1064
+ template_root,
1065
+ template_dir,
1066
+ fm,
1067
+ body,
1068
+ pages,
1069
+ )
1070
+ entry = OrderedDict(
1071
+ summary=summary,
1072
+ primary_color=str(primary_color),
1073
+ )
1074
+ elif kind == "style":
1075
+ _validate_style_spec(
1076
+ template_id,
1077
+ template_root,
1078
+ template_dir,
1079
+ fm,
1080
+ body,
1081
+ )
1082
+ entry = OrderedDict(
1083
+ summary=summary,
1084
+ keywords=[item.strip() for item in fm["keywords"]],
1085
+ )
1086
+ elif kind == "layout":
1087
+ if template_id is None:
1088
+ raise SpecParseError("layout validation requires an expected layout_id")
1089
+ _validate_svg_template_spec(
1090
+ kind,
1091
+ template_id,
1092
+ template_dir,
1093
+ fm,
1094
+ pages,
1095
+ )
1096
+ page_types = fm["page_types"]
1097
+ entry = OrderedDict(
1098
+ summary=summary,
1099
+ canvas_format=str(fm["canvas_format"]),
1100
+ page_count=int(fm["page_count"]),
1101
+ page_types=list(page_types),
1102
+ )
1103
+ elif kind == "deck":
1104
+ if template_id is None:
1105
+ raise SpecParseError("deck validation requires an expected deck_id")
1106
+ _validate_svg_template_spec(
1107
+ kind,
1108
+ template_id,
1109
+ template_dir,
1110
+ fm,
1111
+ pages,
1112
+ )
1113
+ entry = OrderedDict(
1114
+ summary=summary,
1115
+ canvas_format=str(fm["canvas_format"]),
1116
+ page_count=int(fm["page_count"]),
1117
+ primary_color=str(primary_color),
1118
+ )
1119
+ else:
1120
+ raise SpecParseError(f"unknown kind {kind!r}")
1121
+
1122
+ extras = OrderedDict(
1123
+ pages=pages,
1124
+ primary_color=str(primary_color),
1125
+ page_prefix="templates/" if template_dir != template_root else "",
1126
+ preview=(
1127
+ f"exports/{resolved_template_id}_template_preview.pptx"
1128
+ if (
1129
+ template_root
1130
+ / "exports"
1131
+ / f"{resolved_template_id}_template_preview.pptx"
1132
+ ).is_file()
1133
+ else ""
1134
+ ),
1135
+ )
1136
+ return {"entry": entry, "extras": extras}
1137
+
1138
+
1139
+ def validate_brand_workspace(template_root: str | Path) -> dict:
1140
+ """Validate a portable Brand workspace without registering it.
1141
+
1142
+ This is the project-scope entry used by ``svg_quality_checker.py
1143
+ --template-mode``. Library registration calls the same extraction path with
1144
+ an expected directory id, so both scopes share one Brand schema authority.
1145
+ """
1146
+ return _extract_entry("brand", None, Path(template_root))
1147
+
1148
+
1149
+ def validate_style_workspace(template_root: str | Path) -> dict:
1150
+ """Validate a portable Style workspace without registering it.
1151
+
1152
+ Global library roots also enforce directory identity and the one-file
1153
+ package boundary. Project roots keep their unrelated initialized-project
1154
+ scaffolding out of the Style contract.
1155
+ """
1156
+ root = Path(template_root)
1157
+ expected_id = (
1158
+ root.name
1159
+ if root.resolve().parent == KIND_CONFIG["style"]["dir"].resolve()
1160
+ else None
1161
+ )
1162
+ return _extract_entry("style", expected_id, root)
1163
+
1164
+
1165
+ # ---------------------------------------------------------------------------
1166
+ # Index / README writers
1167
+ # ---------------------------------------------------------------------------
1168
+
1169
+ def _load_index(path: Path) -> "OrderedDict[str, dict]":
1170
+ if not path.exists():
1171
+ return OrderedDict()
1172
+ raw_text = path.read_text(encoding="utf-8").strip() or "{}"
1173
+ raw = json.loads(raw_text)
1174
+ return OrderedDict(sorted(raw.items()))
1175
+
1176
+
1177
+ def _write_index(path: Path, data: "OrderedDict[str, dict]", *, dry_run: bool) -> None:
1178
+ payload = json.dumps(data, ensure_ascii=False, indent=2) + "\n"
1179
+ if dry_run:
1180
+ print(f"--- {path.name} (dry-run) ---")
1181
+ print(payload)
1182
+ return
1183
+ path.parent.mkdir(parents=True, exist_ok=True)
1184
+ path.write_text(payload, encoding="utf-8")
1185
+
1186
+
1187
+ def _enumerate_ids(kind: str) -> list[str]:
1188
+ base = KIND_CONFIG[kind]["dir"]
1189
+ if not base.exists():
1190
+ return []
1191
+ return sorted(
1192
+ p.name for p in base.iterdir()
1193
+ if p.is_dir()
1194
+ and (
1195
+ (p / "templates" / "design_spec.md").is_file()
1196
+ or (p / "design_spec.md").is_file()
1197
+ )
1198
+ )
1199
+
1200
+
1201
+ def _print_completion_card(kind: str, template_id: str, entry: dict, extras: dict) -> None:
1202
+ pretty_kind = {
1203
+ "layout": "Layout",
1204
+ "deck": "Deck",
1205
+ "brand": "Brand",
1206
+ "style": "Style",
1207
+ }[kind]
1208
+ dir_name = {
1209
+ "layout": "layouts",
1210
+ "deck": "decks",
1211
+ "brand": "brands",
1212
+ "style": "styles",
1213
+ }[kind]
1214
+ print()
1215
+ print(f"## {pretty_kind} Registration Complete")
1216
+ print()
1217
+ print(f"**{pretty_kind} ID**: {template_id}")
1218
+ print(f"**Path**: `templates/{dir_name}/{template_id}/`")
1219
+ if kind in ("brand", "deck"):
1220
+ primary = entry.get("primary_color") or "—"
1221
+ print(f"**Primary Color**: {primary}")
1222
+ if kind in ("layout", "deck"):
1223
+ canvas = entry.get("canvas_format") or "—"
1224
+ pc = entry.get("page_count") or "—"
1225
+ print(f"**Canvas**: {canvas}")
1226
+ print(f"**Pages**: {pc}")
1227
+ print(f"**Summary**: {entry.get('summary') or '—'}")
1228
+ print("**Index Registration**: Done")
1229
+ print()
1230
+ if KIND_CONFIG[kind]["needs_svg_roster"]:
1231
+ pages = extras.get("pages") or []
1232
+ page_prefix = extras.get("page_prefix") or ""
1233
+ preview = extras.get("preview") or ""
1234
+ if preview:
1235
+ print(f"**Review PPTX**: `{preview}`")
1236
+ print()
1237
+ if pages:
1238
+ print("### Files Included")
1239
+ print()
1240
+ print("| File | Status |")
1241
+ print("|------|--------|")
1242
+ for page in pages:
1243
+ print(f"| `{page_prefix}{page}.svg` | Done |")
1244
+ if preview:
1245
+ print(f"| `{preview}` | Verified |")
1246
+ print()
1247
+
1248
+
1249
+ # ---------------------------------------------------------------------------
1250
+ # Main
1251
+ # ---------------------------------------------------------------------------
1252
+
1253
+ def main() -> int:
1254
+ parser = argparse.ArgumentParser(
1255
+ description=(
1256
+ "Register / refresh templates (brand / style / layout / deck) "
1257
+ "in the index."
1258
+ )
1259
+ )
1260
+ parser.add_argument(
1261
+ "template_id", nargs="?",
1262
+ help="Template directory id (under templates/<kind_dir>/). Omit with --rebuild-all.",
1263
+ )
1264
+ parser.add_argument(
1265
+ "--kind", choices=list(KIND_CONFIG.keys()), default="deck",
1266
+ help="Template kind (default: deck).",
1267
+ )
1268
+ parser.add_argument("--rebuild-all", action="store_true",
1269
+ help="Rebuild every index entry within the chosen kind.")
1270
+ parser.add_argument("--dry-run", action="store_true",
1271
+ help="Show what would be written without modifying any files.")
1272
+ args = parser.parse_args()
1273
+
1274
+ if not args.template_id and not args.rebuild_all:
1275
+ parser.error("provide a template_id or use --rebuild-all")
1276
+
1277
+ cfg = KIND_CONFIG[args.kind]
1278
+ base = cfg["dir"]
1279
+
1280
+ if args.rebuild_all:
1281
+ ids = _enumerate_ids(args.kind)
1282
+ if not ids:
1283
+ print(f"[OK] No {args.kind} directories found; index left empty.")
1284
+ _write_index(cfg["index"], OrderedDict(), dry_run=args.dry_run)
1285
+ return 0
1286
+ else:
1287
+ ids = [args.template_id]
1288
+ spec_dir = base / args.template_id
1289
+ if not spec_dir.is_dir():
1290
+ print(f"Error: {args.kind} directory not found: {spec_dir}", file=sys.stderr)
1291
+ return 1
1292
+
1293
+ extracted: dict[str, dict] = {}
1294
+ for tid in ids:
1295
+ try:
1296
+ extracted[tid] = _extract_entry(args.kind, tid, base / tid)
1297
+ except SpecParseError as exc:
1298
+ print(f"Error: {tid}: {exc}", file=sys.stderr)
1299
+ return 1
1300
+
1301
+ if args.rebuild_all:
1302
+ index = OrderedDict((tid, extracted[tid]["entry"]) for tid in sorted(extracted))
1303
+ else:
1304
+ index = _load_index(cfg["index"])
1305
+ for tid, payload in extracted.items():
1306
+ index[tid] = payload["entry"]
1307
+ index = OrderedDict(sorted(index.items()))
1308
+
1309
+ _write_index(cfg["index"], index, dry_run=args.dry_run)
1310
+
1311
+ if not args.dry_run and not args.rebuild_all:
1312
+ tid = args.template_id
1313
+ _print_completion_card(
1314
+ args.kind, tid, extracted[tid]["entry"], extracted[tid]["extras"]
1315
+ )
1316
+ return 0
1317
+
1318
+ print()
1319
+ print(
1320
+ f"[OK] {'Dry-run preview' if args.dry_run else 'Updated'}: "
1321
+ f"{len(extracted)} {args.kind}(s) processed; index now lists {len(index)} entries."
1322
+ )
1323
+ return 0
1324
+
1325
+
1326
+ if __name__ == "__main__":
1327
+ sys.exit(main())