AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
feat(templates): compose project-scoped template kinds
hugohe38eaa534b0556
diff --git a/skills/ppt-master/scripts/confirm_ui/server.py b/skills/ppt-master/scripts/confirm_ui/server.pyindex 1732ffe6..b39a7237 100644--- a/skills/ppt-master/scripts/confirm_ui/server.py+++ b/skills/ppt-master/scripts/confirm_ui/server.py@@ -198,22 +198,74 @@ def _safe_template_id(template_id: object) -> bool:)-def _template_design_spec_path(workspace_root: Path) -> Path:- """Return the current or legacy Design Spec for one workspace root."""- current = workspace_root / 'templates' / 'design_spec.md'+_TEMPLATE_SPEC_NAME_RE = re.compile(+ r'design_spec\.(?P<kind>brand|style|layout|deck)\.(?P<id>[^/\\]+)\.md'+)+++def _template_design_specs(workspace_root: Path) -> list[Path]:+ """Return every Design Spec one template workspace root exposes.++ A single-kind workspace keeps the exact ``templates/design_spec.md``, and a+ compatible legacy-flat root keeps ``design_spec.md`` beside its pages. A+ multi-kind workspace keeps one ``templates/design_spec.<kind>.<id>.md`` per+ kind — the same shape the apply stage installs into a consuming project — so+ one root can carry, for example, a Brand plus a Style. Order is stable so+ candidate keys and the options digest do not depend on directory listing+ order.+ """+ templates_dir = workspace_root / 'templates'+ current = templates_dir / 'design_spec.md'+ multi = sorted(+ path+ for path in templates_dir.glob('design_spec.*.md')+ if _TEMPLATE_SPEC_NAME_RE.fullmatch(path.name)+ ) if templates_dir.is_dir() else []+ if current.is_file() and multi:+ raise ValueError(+ 'template workspace mixes design_spec.md with kind-qualified specs '+ f'({", ".join(path.name for path in multi)}): {workspace_root}; '+ 'rename the bare spec to design_spec.<kind>.<id>.md'+ )if current.is_file():- return current+ return [current]+ if multi:+ return multilegacy = workspace_root / 'design_spec.md'if legacy.is_file():- return legacy+ return [legacy]raise ValueError(- 'template workspace is missing templates/design_spec.md '- f'or legacy design_spec.md: {workspace_root}'+ 'template workspace is missing templates/design_spec.md, '+ 'templates/design_spec.<kind>.<id>.md, or legacy design_spec.md: '+ f'{workspace_root}')def _template_kind_from_spec(spec_path: Path) -> str:- """Read one supported top-level ``kind`` from Design Spec frontmatter."""+ """Read one supported top-level ``kind`` from Design Spec frontmatter.++ Frontmatter stays the single truth. When the filename also carries a kind,+ both its kind and id must agree; a mismatch is a corrupt workspace rather+ than a precedence question.+ """+ name_match = _TEMPLATE_SPEC_NAME_RE.fullmatch(spec_path.name)+ if name_match is not None:+ try:+ from register_template import (+ SpecParseError,+ validate_qualified_spec_identity,+ )+ declared_kind, _filename_id, _frontmatter, _body = (+ validate_qualified_spec_identity(spec_path)+ )+ except ImportError as exc:+ raise ValueError(+ f'Qualified Design Spec validator could not be imported: {exc}'+ ) from exc+ except (OSError, SpecParseError) as exc:+ raise ValueError(str(exc)) from exc+ return declared_kind+try:lines = spec_path.read_text(encoding='utf-8-sig').splitlines()except OSError as exc:@@ -313,7 +365,7 @@ def _read_template_options_input(confirm_dir: Path) -> tuple[dict, list[Path]]:)if not root.is_dir():raise ValueError(f'explicit workspace root is not a directory: {canonical}')- _template_design_spec_path(root)+ _template_design_specs(root)seen.add(canonical)roots.append(root)return data, roots@@ -404,25 +456,39 @@ def _build_template_options(confirm_dir: Path) -> tuple[dict, dict[str, dict]]:suggested_keys.append(registered['key'])continuedigest = hashlib.sha256(canonical_root.encode('utf-8')).hexdigest()- key = f'explicit:{digest}'- if key in candidates:- raise ValueError(f'duplicate template candidate key: {key}')- kind = _template_kind_from_spec(_template_design_spec_path(root))- candidate = {- 'key': key,- 'source': 'explicit',- 'kind': kind,- 'label': root.name or canonical_root,- 'workspace_root': canonical_root,- }- explicit.append(candidate)- candidates[key] = candidate- suggested_keys.append(key)-- # One supplied exact root is an unambiguous convenience default. Multiple- # roots are candidates for the single-select controls, not an instruction- # to select all of them.- preselected_keys = suggested_keys if len(suggested_keys) == 1 else []+ root_specs = [+ (spec, _template_kind_from_spec(spec))+ for spec in _template_design_specs(root)+ ]+ root_kinds = [kind for _spec, kind in root_specs]+ duplicate_kinds = sorted({+ kind for kind in root_kinds if root_kinds.count(kind) > 1+ })+ if duplicate_kinds:+ raise ValueError(+ 'workspace root exposes the same kind more than once '+ f'({", ".join(duplicate_kinds)}): {canonical_root}'+ )+ for spec, kind in root_specs:+ key = f'explicit:{digest}:{kind}'+ if key in candidates:+ raise ValueError(f'duplicate template candidate key: {key}')+ candidate = {+ 'key': key,+ 'source': 'explicit',+ 'kind': kind,+ 'label': root.name or canonical_root,+ 'workspace_root': canonical_root,+ }+ explicit.append(candidate)+ candidates[key] = candidate+ suggested_keys.append(key)++ # One supplied exact root is an unambiguous convenience default, including+ # a multi-kind root whose kinds compose rather than compete. Several roots+ # are candidates for the single-select controls, not an instruction to+ # select all of them.+ preselected_keys = suggested_keys if len(explicit_roots) == 1 else []response = {'schema_version': TEMPLATE_SCHEMA_VERSION,@@ -515,9 +581,9 @@ def _validate_template_selection(data: dict) -> None:if not isinstance(selection_sha256, str) or not re.fullmatch(r'[0-9a-f]{64}', selection_sha256):raise ValueError(f'{TEMPLATE_SELECTION_NAME} selection_sha256 is invalid')- seen_roots = set()- seen_library_kinds = set()- explicit_count = 0+ seen_root_kinds = set()+ seen_kinds: set[str] = set()+ explicit_roots_seen: dict[str, set[str]] = {}for index, selection in enumerate(selections):if not isinstance(selection, dict):raise ValueError(@@ -536,22 +602,16 @@ def _validate_template_selection(data: dict) -> None:expected_keys = {'source', 'kind', 'workspace_root'}if source == 'library':expected_keys.add('id')- if kind in seen_library_kinds:- raise ValueError(- 'template selection allows at most one library workspace '- f'for kind {kind!r}'- )- seen_library_kinds.add(kind)if not _safe_template_id(selection.get('id')):raise ValueError(f'{TEMPLATE_SELECTION_NAME} selections[{index}] has invalid id')- else:- explicit_count += 1- if explicit_count > 1:- raise ValueError(- 'template selection allows at most one explicit workspace'- )+ if kind in seen_kinds:+ raise ValueError(+ 'template selection allows at most one workspace for kind '+ f'{kind!r}'+ )+ seen_kinds.add(kind)if set(selection) != expected_keys:raise ValueError(f'{TEMPLATE_SELECTION_NAME} selections[{index}] has invalid fields'@@ -568,12 +628,20 @@ def _validate_template_selection(data: dict) -> None:f'{TEMPLATE_SELECTION_NAME} selections[{index}] ''workspace_root must be a canonical absolute path')- if workspace_root in seen_roots:+ if source == 'explicit':+ # One explicit workspace root may contribute several kinds, so the+ # cap counts roots rather than selections.+ explicit_roots_seen.setdefault(workspace_root, set()).add(kind)+ if len(explicit_roots_seen) > 1:+ raise ValueError(+ 'template selection allows at most one explicit workspace'+ )+ if (workspace_root, kind) in seen_root_kinds:raise ValueError(- f'{TEMPLATE_SELECTION_NAME} contains duplicate workspace root: '- f'{workspace_root}'+ f'{TEMPLATE_SELECTION_NAME} contains duplicate workspace root '+ f'for kind {kind!r}: {workspace_root}')- seen_roots.add(workspace_root)+ seen_root_kinds.add((workspace_root, kind))if not isinstance(data.get('confirmed_at'), str) or not data['confirmed_at']:raise ValueError(f'{TEMPLATE_SELECTION_NAME} confirmed_at must be a non-empty string'@@ -587,6 +655,32 @@ def _validate_template_selection(data: dict) -> None:raise ValueError(f'{TEMPLATE_SELECTION_NAME} selection_sha256 does not match')+def _validate_explicit_root_closure(+ selections: list[dict],+ candidates: dict[str, dict],+) -> None:+ """Require every selected explicit root to contribute all exposed kinds."""+ exposed: dict[str, set[str]] = {}+ for candidate in candidates.values():+ if candidate['source'] == 'explicit':+ exposed.setdefault(candidate['workspace_root'], set()).add(+ candidate['kind']+ )+ chosen: dict[str, set[str]] = {}+ for selection in selections:+ if selection['source'] == 'explicit':+ chosen.setdefault(selection['workspace_root'], set()).add(+ selection['kind']+ )+ for root, kinds in chosen.items():+ missing = sorted(exposed.get(root, set()) - kinds)+ if missing:+ raise ValueError(+ f'{TEMPLATE_SELECTION_NAME} selects workspace root {root} '+ f'without every kind it exposes; missing: {", ".join(missing)}'+ )++def _read_template_selection(selection_file: Path) -> dict:"""Read a selection and revalidate it against current indexed options."""data = _read_json_object(selection_file)@@ -611,6 +705,8 @@ def _read_template_selection(selection_file: Path) -> dict:raise ValueError(f'{TEMPLATE_SELECTION_NAME} references an unavailable candidate')++ _validate_explicit_root_closure(data['selections'], candidates)return data@@ -685,7 +781,7 @@ def _installed_template_specs(project_path: Path) -> list[Path]:return sorted(pathfor path in (project_path / 'templates').glob('design_spec.*.md')- if path.is_file()+ if path.is_file() and _TEMPLATE_SPEC_NAME_RE.fullmatch(path.name))@@ -890,6 +986,7 @@ def _resolve_template_confirmation('confirmed_at': time.strftime('%Y-%m-%dT%H:%M:%S'),}_validate_template_selection(receipt)+ _validate_explicit_root_closure(selections, candidates)return receiptdiff --git a/skills/ppt-master/scripts/confirm_ui/static/app.js b/skills/ppt-master/scripts/confirm_ui/static/app.jsindex 23b3519e..a05d51c5 100644--- a/skills/ppt-master/scripts/confirm_ui/static/app.js+++ b/skills/ppt-master/scripts/confirm_ui/static/app.js@@ -24,6 +24,7 @@btn_confirm_final_plan: "Confirm final plan →",deriving: "Generating the downstream options from your choices…",template_selection_required: "Choose free design or use templates. When using templates, select at least one workspace.",+ template_selection_conflict: "Choose at most one workspace per kind.",connection_lost: "Connection to the confirm server was interrupted; retrying. If this keeps failing, return to the chat for confirmation.",confirmed_title: "✓ Confirmed",confirmed_hint: "Your choices are saved. You can close this page and return to the chat.",@@ -35,9 +36,9 @@template_use_title: "Use templates",template_use_desc: "Select one or more reusable Brand, Style, Layout, Deck, or specified workspaces.",sec_template_library: "Template combination",- template_library_hint: "Choose at most one registered template for each type. Brand, Style, Layout, and Deck can be combined.",+ template_library_hint: "Choose at most one workspace per kind. All four kinds can combine; Layout takes structural precedence over Deck.",sec_template_explicit: "Specified templates",- template_explicit_hint: "Choose at most one exact workspace supplied for this run. Its source path is shown for verification.",+ template_explicit_hint: "Choose at most one exact workspace supplied for this run; every kind it contains is applied. Its source path is shown for verification.",template_kind_brand: "Brand",template_kind_style: "Style",template_kind_layout: "Layout",@@ -206,6 +207,7 @@btn_confirm_final_plan: "最終プランを確定 →",deriving: "選択内容をもとに後続の選択肢を生成しています…",template_selection_required: "自由デザインまたはテンプレート利用を選んでください。テンプレート利用時は、1つ以上のワークスペースを選択してください。",+ template_selection_conflict: "種類ごとにワークスペースを1件まで選択してください。",connection_lost: "確認ページのサーバー接続が中断されました。再試行しています。失敗が続く場合はチャットで確認してください。",confirmed_title: "✓ 確定しました",confirmed_hint: "選択内容を保存しました。このページを閉じてチャットに戻ってください。",@@ -217,9 +219,9 @@template_use_title: "テンプレートを使用",template_use_desc: "Brand、Style、Layout、Deck、または指定ワークスペースから1つ以上選択します。",sec_template_library: "テンプレートの組み合わせ",- template_library_hint: "登録済みテンプレートは種類ごとに1件まで選択でき、Brand、Style、Layout、Deck を組み合わせられます。",+ template_library_hint: "種類ごとにワークスペースを1件まで選択できます。4種類はすべて組み合わせ可能で、構造は Layout が Deck より優先されます。",sec_template_explicit: "指定テンプレート",- template_explicit_hint: "この実行で指定された正確なワークスペースを1件まで選択できます。確認用に参照元パスを表示します。",+ template_explicit_hint: "この実行で指定された正確なワークスペースを1件まで選択でき、そこに含まれる種別はすべて適用されます。確認用に参照元パスを表示します。",template_kind_brand: "Brand",template_kind_style: "Style",template_kind_layout: "Layout",@@ -388,6 +390,7 @@btn_confirm_final_plan: "确认最终方案 →",deriving: "正在根据你的选择生成下游选项…",template_selection_required: "请选择自由设计或使用模板;选择使用模板时,至少选择一个工作区。",+ template_selection_conflict: "每种模板最多选择一个工作区。",connection_lost: "确认页服务连接中断,正在重试;如果持续失败,请回到聊天窗口走聊天确认。",confirmed_title: "✓ 已确认",confirmed_hint: "选择已保存,可关闭此页并回到聊天窗口。",@@ -399,9 +402,9 @@template_use_title: "使用模板",template_use_desc: "选择一个或多个 Brand、Style、Layout、Deck 或指定工作区。",sec_template_library: "模板组合",- template_library_hint: "每种已注册模板最多选择一个;Brand、Style、Layout、Deck 可以组合使用。",+ template_library_hint: "每种模板最多选择一个工作区;四种模板均可组合,结构由 Layout 优先于 Deck。",sec_template_explicit: "指定模板",- template_explicit_hint: "本次运行明确提供的精确工作区最多选择一个;显示来源路径供你核对。",+ template_explicit_hint: "本次运行明确提供的精确工作区最多选择一个,它包含的每一类都会被采用;显示来源路径供你核对。",template_kind_brand: "Brand",template_kind_style: "Style",template_kind_layout: "Layout",@@ -570,6 +573,7 @@btn_confirm_final_plan: "確認最終方案 →",deriving: "正在根據你的選擇生成下游選項…",template_selection_required: "請選擇自由設計或使用範本;選擇使用範本時,至少選擇一個工作區。",+ template_selection_conflict: "每種範本最多選擇一個工作區。",connection_lost: "確認頁服務連線中斷,正在重試;如果持續失敗,請回到聊天視窗走聊天確認。",confirmed_title: "✓ 已確認",confirmed_hint: "選擇已儲存,可關閉此頁並回到聊天視窗。",@@ -581,9 +585,9 @@template_use_title: "使用範本",template_use_desc: "選擇一個或多個 Brand、Style、Layout、Deck 或指定工作區。",sec_template_library: "範本組合",- template_library_hint: "每種已註冊範本最多選擇一個;Brand、Style、Layout、Deck 可以組合使用。",+ template_library_hint: "每種範本最多選擇一個工作區;四種範本均可組合,結構由 Layout 優先於 Deck。",sec_template_explicit: "指定範本",- template_explicit_hint: "本次執行明確提供的精確工作區最多選擇一個;顯示來源路徑供你核對。",+ template_explicit_hint: "本次執行明確提供的精確工作區最多選擇一個,它包含的每一類都會被採用;顯示來源路徑供你核對。",template_kind_brand: "Brand",template_kind_style: "Style",template_kind_layout: "Layout",@@ -1115,14 +1119,18 @@if (!candidate || !slot) {throw new Error("Invalid preselected template key: " + key);}- if (TEMPLATE_SELECTIONS[slot]) {+ var value = slot === "explicit" ? (candidate.workspace_root || "") : key;+ if (TEMPLATE_SELECTIONS[slot] && TEMPLATE_SELECTIONS[slot] !== value) {throw new Error("Multiple preselected templates for slot: " + slot);}- TEMPLATE_SELECTIONS[slot] = key;+ TEMPLATE_SELECTIONS[slot] = value;});+ // Publish options before syncing: expanding an explicit root into its+ // kinds reads TEMPLATE_OPTIONS, so a preselected root would otherwise+ // resolve to zero keys on first load.+ TEMPLATE_OPTIONS = normalized;syncTemplateSelectionState();TEMPLATE_MODE = normalized.default_mode;- TEMPLATE_OPTIONS = normalized;}function emptyTemplateSelections() {@@ -1146,11 +1154,42 @@return null;}+ function explicitCandidatesForRoot(workspaceRoot) {+ var root = String(workspaceRoot || "");+ if (!root) return [];+ return ((TEMPLATE_OPTIONS && TEMPLATE_OPTIONS.explicit) || [])+ .filter(function (candidate) { return candidate.workspace_root === root; });+ }++ // One supplied path is one workspace, and its kinds compose rather than+ // compete. Selecting that root therefore takes every kind it exposes.+ function explicitRootOptions() {+ var roots = [];+ var seen = Object.create(null);+ ((TEMPLATE_OPTIONS && TEMPLATE_OPTIONS.explicit) || []).forEach(function (candidate) {+ var root = candidate.workspace_root || "";+ if (!root || seen[root]) return;+ seen[root] = true;+ var kinds = explicitCandidatesForRoot(root).map(function (item) {+ return templateKindLabel(item.kind);+ });+ roots.push({+ key: root,+ label: candidate.label || root,+ summary: kinds.join(" + "),+ workspace_root: root+ });+ });+ return roots;+ }+function syncTemplateSelectionState() {TEMPLATE_SELECTED_KEYS = TEMPLATE_KINDS.map(function (kind) {return TEMPLATE_SELECTIONS[kind];});- TEMPLATE_SELECTED_KEYS.push(TEMPLATE_SELECTIONS.explicit);+ explicitCandidatesForRoot(TEMPLATE_SELECTIONS.explicit).forEach(function (candidate) {+ TEMPLATE_SELECTED_KEYS.push(candidate.key);+ });TEMPLATE_SELECTED_KEYS = TEMPLATE_SELECTED_KEYS.filter(Boolean);}@@ -1279,7 +1318,7 @@grid.appendChild(renderTemplateSelectField("explicit",t("template_source_explicit"),- TEMPLATE_OPTIONS.explicit || []+ explicitRootOptions()));panel.appendChild(grid);sec.appendChild(panel);@@ -1291,8 +1330,7 @@var path = document.getElementById("template-explicit-path");var value = document.getElementById("template-explicit-path-value");if (!path || !value) return;- var candidate = templateCandidateByKey(TEMPLATE_SELECTIONS.explicit);- var workspaceRoot = candidate && candidate.workspace_root ? candidate.workspace_root : "";+ var workspaceRoot = TEMPLATE_SELECTIONS.explicit || "";path.hidden = !workspaceRoot;value.textContent = workspaceRoot;value.title = workspaceRoot;@@ -4231,8 +4269,22 @@if (!valid) {document.getElementById("confirm-status").textContent =t("template_selection_required");+ return false;+ }+ if (TEMPLATE_MODE === "templates") {+ var seenKinds = Object.create(null);+ for (var i = 0; i < TEMPLATE_SELECTED_KEYS.length; i += 1) {+ var candidate = templateCandidateByKey(TEMPLATE_SELECTED_KEYS[i]);+ if (!candidate) continue;+ if (seenKinds[candidate.kind]) {+ document.getElementById("confirm-status").textContent =+ t("template_selection_conflict");+ return false;+ }+ seenKinds[candidate.kind] = true;+ }}- return valid;+ return true;}function submitStage1() {diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.pyindex 240508f9..16c5004c 100644--- a/skills/ppt-master/scripts/mirror_template_materialize.py+++ b/skills/ppt-master/scripts/mirror_template_materialize.py@@ -2515,11 +2515,36 @@ def _preflight_output(raise MirrorMaterializationError(f"Template output is not a directory: {templates_root}")- existing = sorted(path for path in templates_root.iterdir())- if existing:+ # Brand/Style specs own no roster. During a Layout transition, one Deck+ # spec may also remain after its lower-priority roster was withheld by+ # the parent workflow. Any other payload would contend with this run.+ existing = sorted(templates_root.iterdir())+ coexisting_specs = [+ path+ for path in existing+ if path.is_file()+ and _MIRROR_COEXISTING_SPEC_NAME_RE.fullmatch(path.name)+ ]+ blocking = [path for path in existing if path not in coexisting_specs]+ if blocking:+ raise MirrorMaterializationError(+ "Template output must hold no roster before mirror "+ f"materialization: {templates_root}; blocking entry: "+ f"{blocking[0].name}"+ )+ coexisting_kinds = [+ _MIRROR_COEXISTING_SPEC_NAME_RE.fullmatch(path.name).group("kind")+ for path in coexisting_specs+ ]+ duplicate_kinds = sorted({+ kind+ for kind in coexisting_kinds+ if coexisting_kinds.count(kind) > 1+ })+ if duplicate_kinds:raise MirrorMaterializationError(- f"Template output must be empty before mirror materialization: "- f"{templates_root}; first entry: {existing[0].name}"+ f"Template output declares the same kind more than once: "+ + ", ".join(duplicate_kinds))collisions = [template_workspace / relative@@ -2532,6 +2557,11 @@ def _preflight_output()+_MIRROR_COEXISTING_SPEC_NAME_RE = re.compile(+ r"design_spec\.(?P<kind>brand|style|deck)\.[^/\\]+\.md"+)++def _nearest_existing_directory(path: Path) -> Path:candidate = pathwhile not candidate.exists():@@ -2910,7 +2940,11 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("template_workspace",type=Path,- help="Empty template workspace destination (templates/ must be absent or empty)",+ help=(+ "Template workspace destination (templates/ must own no roster; "+ "qualified Brand/Style specs or one Deck spec staged for Layout "+ "supersession may remain)"+ ),)return parserdiff --git a/skills/ppt-master/scripts/register_template.py b/skills/ppt-master/scripts/register_template.pyindex b6d3ed1a..f9df58aa 100644--- a/skills/ppt-master/scripts/register_template.py+++ b/skills/ppt-master/scripts/register_template.py@@ -336,15 +336,113 @@ def _summary_from_use_cases(use_cases: str | None) -> str | None:return f"{cleaned}."+_SPEC_NAME_RE = re.compile(+ r"design_spec\.(?P<kind>brand|style|layout|deck)\.(?P<id>[^/\\]+)\.md"+)+++def _has_kind_qualified_spec(directory: Path) -> bool:+ """Report whether a directory holds any ``design_spec.<kind>.<id>.md``."""+ if not directory.is_dir():+ return False+ return any(+ _SPEC_NAME_RE.fullmatch(path.name)+ for path in directory.glob("design_spec.*.md")+ )+++def _qualified_template_specs(directory: Path) -> list[tuple[Path, str]]:+ """Return kind-qualified specs and their filename-declared kinds."""+ if not directory.is_dir():+ return []+ specs = []+ for path in sorted(directory.glob("design_spec.*.md")):+ match = _SPEC_NAME_RE.fullmatch(path.name)+ if match is not None:+ specs.append((path, match.group("kind")))+ return specs+++def validate_qualified_spec_identity(+ spec_path: str | Path,+) -> tuple[str, str, dict, str]:+ """Match one qualified filename's kind and id to its frontmatter."""+ path = Path(spec_path)+ match = _SPEC_NAME_RE.fullmatch(path.name)+ if match is None:+ raise SpecParseError(+ "qualified Design Spec must be named "+ "design_spec.<kind>.<id>.md: "+ f"{path.name}"+ )++ filename_kind = match.group("kind")+ filename_id = match.group("id")+ frontmatter, body = _read_spec(path)+ fm = frontmatter or {}+ declared_kind = str(fm.get("kind") or "").strip()+ id_key = KIND_CONFIG[filename_kind]["id_key"]+ declared_id = str(fm.get(id_key) or "").strip()+ errors: list[str] = []+ if declared_kind != filename_kind:+ errors.append(+ f"filename kind {filename_kind!r} must match frontmatter kind "+ f"{declared_kind!r}"+ )+ if declared_id != filename_id:+ errors.append(+ f"filename id {filename_id!r} must match frontmatter {id_key} "+ f"{declared_id!r}"+ )+ if errors:+ details = "\n".join(f" - {error}" for error in errors)+ raise SpecParseError(+ f"invalid qualified Design Spec identity ({path.name}):\n{details}"+ )+ return filename_kind, filename_id, fm, body+++def _validate_spec_shape(template_dir: Path) -> list[tuple[Path, str]]:+ """Reject ambiguous project-spec naming and duplicate kind ownership."""+ exact = template_dir / "design_spec.md"+ qualified = _qualified_template_specs(template_dir)+ if exact.is_file() and qualified:+ raise SpecParseError(+ "design_spec.md and design_spec.<kind>.<id>.md cannot share "+ f"{template_dir}; rename the bare spec to its kind-qualified name"+ )+ kinds = [kind for _path, kind in qualified]+ duplicate_kinds = sorted({+ kind for kind in kinds if kinds.count(kind) > 1+ })+ if duplicate_kinds:+ raise SpecParseError(+ f"{template_dir} declares the same kind more than once: "+ + ", ".join(duplicate_kinds)+ )+ for path, _kind in qualified:+ validate_qualified_spec_identity(path)+ return qualified+++def _has_qualified_roster_spec(template_dir: Path) -> bool:+ """Return whether a project directory declares a structural kind."""+ return any(+ kind in {"layout", "deck"}+ for _path, kind in _qualified_template_specs(template_dir)+ )++def _template_content_dir(template_root: Path) -> Path:"""Resolve the canonical source directory, with legacy-flat compatibility."""nested = template_root / "templates"- if (nested / "design_spec.md").is_file():+ if (nested / "design_spec.md").is_file() or _has_kind_qualified_spec(nested):return nestedif (template_root / "design_spec.md").is_file():return template_rootraise SpecParseError(- f"missing templates/design_spec.md or legacy design_spec.md in {template_root}"+ "missing templates/design_spec.md, templates/design_spec.<kind>.<id>.md, "+ f"or legacy design_spec.md in {template_root}")@@ -472,7 +570,8 @@ def _validate_brand_spec(+ ", ".join(unexpected_fields))- if pages:+ # Project pages are valid only when one sibling Layout or Deck owns them.+ if pages and not _has_qualified_roster_spec(template_dir):errors.append("brand workspaces must not contain page SVGs under templates/: "+ ", ".join(f"{page}.svg" for page in pages)@@ -563,6 +662,7 @@ def _validate_style_spec(template_dir: Path,frontmatter: dict,body: str,+ pages: list[str],) -> None:"""Reject Style workspaces outside the roster-free method contract."""errors: list[str] = []@@ -632,19 +732,30 @@ def _validate_style_spec(elif len({item.strip().casefold() for item in keywords}) != len(keywords):errors.append("frontmatter keywords must be unique")- unexpected_source_entries = sorted(- path.relative_to(template_dir).as_posix()- + ("/" if path.is_dir() else "")- for path in template_dir.rglob("*")- if path.relative_to(template_dir).as_posix() != "design_spec.md"- )- if unexpected_source_entries:+ if pages and not _has_qualified_roster_spec(template_dir):errors.append(- "style workspaces must contain only templates/design_spec.md; "- "unexpected template entry(s): "- + ", ".join(unexpected_source_entries)+ "style workspaces must not contain page SVGs without a sibling "+ "Layout or Deck owner: "+ + ", ".join(f"{page}.svg" for page in pages))+ # The one-file packaging rule describes a workspace whose templates/ Style+ # owns alone. A project root shares that directory with other kinds, so the+ # rule there is only that Style itself contributes nothing but its spec.+ if (template_dir / "design_spec.md").is_file():+ unexpected_source_entries = sorted(+ path.relative_to(template_dir).as_posix()+ + ("/" if path.is_dir() else "")+ for path in template_dir.rglob("*")+ if path.relative_to(template_dir).as_posix() != "design_spec.md"+ )+ if unexpected_source_entries:+ errors.append(+ "style workspaces must contain only templates/design_spec.md; "+ "unexpected template entry(s): "+ + ", ".join(unexpected_source_entries)+ )+if expected_template_id is not None:unexpected_workspace_entries = sorted(path.relative_to(template_root).as_posix()@@ -884,8 +995,10 @@ def _validate_svg_template_spec(template_dir: Path,frontmatter: dict,pages: list[str],+ *,+ validate_payload: bool = True,) -> None:- """Reject Layout/Deck workspaces whose registry facts drift from SVGs."""+ """Validate Layout/Deck metadata and, when active, its SVG payload."""errors: list[str] = []id_key = KIND_CONFIG[kind]["id_key"]declared_id = str(frontmatter.get(id_key) or "").strip()@@ -969,7 +1082,7 @@ def _validate_svg_template_spec()svg_paths = [template_dir / f"{page}.svg" for page in pages]- if canvas is not None:+ if validate_payload and canvas is not None:expected_viewbox = str(canvas["viewbox"])for svg_path in svg_paths:try:@@ -993,7 +1106,7 @@ def _validate_svg_template_spec(f"{expected_canvas!r}")- if svg_paths:+ if validate_payload and svg_paths:try:from svg_to_pptx.pptx_package.template_structure import (TemplateStructureError,@@ -1012,6 +1125,30 @@ def _validate_svg_template_spec(raise SpecParseError(f"invalid {kind} specification:\n{details}")+def validate_shadowed_deck_spec(+ spec_path: str | Path,+ declared_pages: list[str],+) -> None:+ """Validate a Deck spec whose SVG roster is overridden by Layout."""+ path = Path(spec_path)+ match = _SPEC_NAME_RE.fullmatch(path.name)+ if match is None or match.group("kind") != "deck":+ raise SpecParseError(+ "shadowed Deck validation requires design_spec.deck.<id>.md"+ )+ _kind, filename_id, frontmatter, _body = validate_qualified_spec_identity(+ path+ )+ _validate_svg_template_spec(+ "deck",+ filename_id,+ path.parent,+ frontmatter,+ declared_pages,+ validate_payload=False,+ )++# ---------------------------------------------------------------------------# Per-kind extraction# ---------------------------------------------------------------------------@@ -1029,7 +1166,14 @@ def _extract_entry("Style workspaces require templates/design_spec.md; ""legacy-flat design_spec.md is not supported")- spec_path = template_dir / "design_spec.md"+ if template_id is not None and template_dir != template_root:+ exact_spec = template_dir / "design_spec.md"+ if not exact_spec.is_file():+ raise SpecParseError(+ "library workspaces require templates/design_spec.md; "+ "kind-qualified specs belong only to shared project roots"+ )+ spec_path = _resolve_spec_path(template_dir, kind)frontmatter, body = _read_spec(spec_path)fm = frontmatter or {}@@ -1079,6 +1223,7 @@ def _extract_entry(template_dir,fm,body,+ pages,)entry = OrderedDict(summary=summary,@@ -1137,6 +1282,33 @@ def _extract_entry(return {"entry": entry, "extras": extras}+def _resolve_spec_path(template_dir: Path, kind: str) -> Path:+ """Return the Design Spec one kind owns inside a template source directory.++ A library workspace keeps the exact ``design_spec.md`` because+ ``<kind_dir>/<template_id>/`` already names its kind and id. A project+ workspace root has no such parent, so it keeps+ ``design_spec.<kind>.<id>.md`` and may hold one spec per kind side by side.+ """+ qualified = _validate_spec_shape(template_dir)+ exact = template_dir / "design_spec.md"+ if exact.is_file():+ return exact+ matches = sorted(+ path for path, declared_kind in qualified if declared_kind == kind+ )+ if len(matches) == 1:+ return matches[0]+ if not matches:+ raise SpecParseError(+ f"missing design_spec.md or design_spec.{kind}.<id>.md in {template_dir}"+ )+ raise SpecParseError(+ f"{template_dir} declares kind {kind!r} more than once: "+ + ", ".join(path.name for path in matches)+ )++def validate_brand_workspace(template_root: str | Path) -> dict:"""Validate a portable Brand workspace without registering it.diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.pyindex 3725e599..66fcfc4e 100644--- a/skills/ppt-master/scripts/svg_quality/checker.py+++ b/skills/ppt-master/scripts/svg_quality/checker.py@@ -792,13 +792,77 @@ SPARSE_UNDECLARED_FONT_SIZE_MAX_OCCURRENCES = 2IMAGE_DOWNSIZE_WARN_RATIO = 4.0IMAGE_DOWNSIZE_WARN_MIN_BYTES = 1024 * 1024+_TEMPLATE_SPEC_NAME_RE = re.compile(+ r'design_spec\.(?P<kind>brand|style|layout|deck)\.(?P<id>[^/\\]+)\.md'+)+++def _template_spec_paths(directory: Path) -> list[Path]:+ """Return every template Design Spec directly inside one directory.++ A library workspace keeps the exact ``design_spec.md`` because its parent+ directory already names the kind and id. A project workspace root shares one+ ``templates/`` across kinds, so it keeps ``design_spec.<kind>.<id>.md`` and+ may hold one spec per kind side by side.+ """+ if not directory.is_dir():+ return []+ exact = directory / 'design_spec.md'+ qualified = sorted(+ path+ for path in directory.glob('design_spec.*.md')+ if _TEMPLATE_SPEC_NAME_RE.fullmatch(path.name)+ )+ if exact.is_file():+ # Mixing both shapes hides one of them from every reader that stops at+ # the first match, so it is reported rather than silently resolved.+ return [exact] + qualified+ return qualified+++def _spec_declared_kind(spec_path: Path) -> str | None:+ """Return one spec's kind, from its filename when it carries one."""+ match = _TEMPLATE_SPEC_NAME_RE.fullmatch(spec_path.name)+ if match is not None:+ return match.group('kind')+ return _design_spec_kind(spec_path)+++def _roster_spec_paths(directory: Path) -> list[Path]:+ """Return every spec in one directory that owns an SVG roster."""+ roster = []+ for spec in _template_spec_paths(directory):+ match = _TEMPLATE_SPEC_NAME_RE.fullmatch(spec.name)+ if match is not None:+ if match.group('kind') in {'layout', 'deck'}:+ roster.append(spec)+ elif _design_spec_kind(spec) not in {'brand', 'style'}:+ roster.append(spec)+ return roster+++def _roster_spec_path(directory: Path) -> Path | None:+ """Return the effective spec that owns this directory's SVG roster.++ A project root may carry both Layout and Deck. Layout owns reusable+ structure when present; Deck owns it only when no Layout is installed.+ """+ roster = _roster_spec_paths(directory)+ for spec in roster:+ if spec.name == 'design_spec.md':+ return spec+ for kind in ('layout', 'deck'):+ for spec in roster:+ if _spec_declared_kind(spec) == kind:+ return spec+ return None++def _design_spec_kind(spec_path: Path) -> str | None:- """Return a roster-free ``kind`` declared in design_spec.md frontmatter.+ """Return ``kind`` declared in Design Spec frontmatter.Lightweight detector that does not require PyYAML — scans only the- frontmatter block (``---`` delimited). Used by ``check_directory`` to- select schema-only validation for Brand and Style workspaces instead of- SVG-roster validation.+ frontmatter block (``---`` delimited)."""try:text = spec_path.read_text(encoding='utf-8')@@ -813,7 +877,8 @@ def _design_spec_kind(spec_path: Path) -> str | None:for line in fm_block.splitlines():stripped = line.strip()match = re.fullmatch(- r'''kind\s*:\s*(?:(['"])(brand|style)\1|(brand|style))'''+ r'''kind\s*:\s*(?:(['"])(brand|style|layout|deck)\1|'''+ r'''(brand|style|layout|deck))'''r'''(?:\s+#.*)?\s*''',stripped,)@@ -825,7 +890,9 @@ def _design_spec_kind(spec_path: Path) -> str | None:def _declared_template_structure_mode(target_path: Path) -> str | None:"""Return a template directory's explicit native structure mode."""directory = target_path.parent if target_path.is_file() else target_path- spec_path = directory / 'design_spec.md'+ spec_path = _roster_spec_path(directory)+ if spec_path is None:+ return Nonetry:text = spec_path.read_text(encoding='utf-8')except OSError:@@ -846,7 +913,9 @@ def _declared_template_structure_mode(target_path: Path) -> str | None:def _declared_template_canvas_viewbox(target_path: Path) -> str | None:"""Return a template design spec's locked root-canvas value."""directory = target_path.parent if target_path.is_file() else target_path- spec_path = directory / 'design_spec.md'+ spec_path = _roster_spec_path(directory)+ if spec_path is None:+ return Nonetry:text = spec_path.read_text(encoding='utf-8')except OSError:@@ -5258,17 +5327,103 @@ class SVGQualityChecker:# registration, while keeping project scope independent of global# indexes and directory names.if self.template_mode and dir_path.is_dir():- nested_spec = dir_path / 'templates' / 'design_spec.md'- spec = nested_spec if nested_spec.is_file() else dir_path / 'design_spec.md'- spec_kind = _design_spec_kind(spec) if spec.exists() else None- if spec_kind in {'brand', 'style'}:+ nested = dir_path / 'templates'+ spec_dir = nested if _template_spec_paths(nested) else dir_path+ specs = _template_spec_paths(spec_dir)+ bare = [spec for spec in specs if spec.name == 'design_spec.md']+ qualified = [spec for spec in specs if spec.name != 'design_spec.md']+ if bare and qualified:+ self._template_issues.append((+ 'error',+ 'spec_naming',+ 'design_spec.md and design_spec.<kind>.<id>.md cannot share '+ f'{spec_dir}; rename the bare spec to its kind-qualified name',+ ))+ return self.results+ try:+ from register_template import (+ SpecParseError,+ validate_qualified_spec_identity,+ )+ for spec in qualified:+ validate_qualified_spec_identity(spec)+ except ImportError as exc:+ self._template_issues.append((+ 'error',+ 'spec_naming',+ f'Qualified Design Spec validator could not be imported: {exc}',+ ))+ return self.results+ except (OSError, SpecParseError) as exc:+ self._template_issues.append((+ 'error',+ 'spec_naming',+ str(exc),+ ))+ return self.results+ declared_kinds = [+ kind+ for spec in qualified+ for kind in [_spec_declared_kind(spec)]+ if kind is not None+ ]+ duplicate_kinds = sorted({+ kind for kind in declared_kinds+ if declared_kinds.count(kind) > 1+ })+ if duplicate_kinds:+ self._template_issues.append((+ 'error',+ 'spec_naming',+ f'{spec_dir} declares the same kind more than once: '+ + ', '.join(duplicate_kinds),+ ))+ return self.results+ active_roster_spec = _roster_spec_path(spec_dir)+ shadowed_deck_specs = [+ spec+ for spec in _roster_spec_paths(spec_dir)+ if spec != active_roster_spec+ and _spec_declared_kind(spec) == 'deck'+ ]+ for spec in shadowed_deck_specs:+ try:+ from register_template import (+ SpecParseError,+ validate_shadowed_deck_spec,+ )+ declared_pages = self._extract_spec_roster(+ spec.read_text(encoding='utf-8')+ )+ validate_shadowed_deck_spec(spec, declared_pages)+ except ImportError as exc:+ self._template_issues.append((+ 'error',+ 'deck_contract',+ f'Shadowed Deck validator could not be imported: {exc}',+ ))+ return self.results+ except (OSError, SpecParseError) as exc:+ self._template_issues.append((+ 'error',+ 'deck_contract',+ str(exc),+ ))+ return self.results+ roster_free = [+ (spec, kind)+ for spec in _template_spec_paths(spec_dir)+ for kind in [_spec_declared_kind(spec)]+ if kind in {'brand', 'style'}+ ]+ for spec, spec_kind in roster_free:self._spec_only_template_kind = spec_kindself.summary['total'] += 1spec_valid = Truepretty_kind = spec_kind.title()print(- f"[INFO] {pretty_kind} directory detected "- f"(kind: {spec_kind}) — "+ f"[INFO] {pretty_kind} spec detected "+ f"({spec.name}) — "f"validating its portable workspace contract.")workspace_root = (@@ -5303,6 +5458,9 @@ class SVGQualityChecker:))if spec_valid:self.summary['passed'] += 1+ # A roster-bearing Layout/Deck spec may sit beside those in one+ # project workspace; only then does SVG validation still apply.+ if roster_free and _roster_spec_path(spec_dir) is None:return self.results# Find all SVG files@@ -6791,8 +6949,12 @@ class SVGQualityChecker:Issues are aggregated and printed in :py:meth:`print_summary` so theper-file report stays focused on intrinsic SVG validity."""- spec_path = dir_path / 'design_spec.md'- spec_text = spec_path.read_text(encoding='utf-8') if spec_path.exists() else ""+ spec_path = _roster_spec_path(dir_path)+ spec_text = (+ spec_path.read_text(encoding='utf-8')+ if spec_path is not None and spec_path.exists()+ else ""+ )declared_structure_mode = _declared_template_structure_mode(dir_path)mode_error_recorded = Falseif declared_structure_mode != 'structured':@@ -6920,7 +7082,7 @@ class SVGQualityChecker:'roster_missing',f"design_spec.md Page Roster lists {page} but {page}.svg is missing on disk",))- elif spec_path.exists():+ elif spec_path is not None and spec_path.exists():# design_spec.md is present but the roster parser found nothing —# reusable template workspaces always fail closed.self._template_issues.append((@@ -6933,7 +7095,7 @@ class SVGQualityChecker:self._template_issues.append(('error','spec_missing',- f"{spec_path.name} not found — required for every library template",+ "one Layout or Deck Design Spec is required for every SVG roster",))# Per-file placeholder coverage. Variants reuse the parent type's setdiff --git a/skills/ppt-master/scripts/template_preview_pptx.py b/skills/ppt-master/scripts/template_preview_pptx.pyindex 693ac02e..8587bae3 100644--- a/skills/ppt-master/scripts/template_preview_pptx.py+++ b/skills/ppt-master/scripts/template_preview_pptx.py@@ -160,22 +160,77 @@ def _partition_svg_prototypes(return public_files, definition_files+_TEMPLATE_SPEC_NAME_RE = re.compile(+ r"design_spec\.(?P<kind>brand|style|layout|deck)\.[^/\\]+\.md"+)+++def _roster_spec(directory: Path) -> Path | None:+ """Return the effective spec that owns this directory's SVG roster.++ A library workspace keeps the exact ``design_spec.md``. A project workspace+ shares one ``templates/`` across kinds. Layout owns structure when both+ Layout and Deck are present; otherwise Deck owns it.+ """+ if not directory.is_dir():+ return None+ exact = directory / "design_spec.md"+ qualified = []+ for item in sorted(directory.glob("design_spec.*.md")):+ match = _TEMPLATE_SPEC_NAME_RE.fullmatch(item.name)+ if match is not None:+ qualified.append((item, match.group("kind")))+ if exact.is_file() and qualified:+ raise ValueError(+ "design_spec.md and design_spec.<kind>.<id>.md cannot share "+ f"{directory}; rename the bare spec to its kind-qualified name"+ )+ kinds = [kind for _item, kind in qualified]+ duplicate_kinds = sorted({+ kind for kind in kinds if kinds.count(kind) > 1+ })+ if duplicate_kinds:+ raise ValueError(+ f"{directory} declares the same kind more than once: "+ + ", ".join(duplicate_kinds)+ )+ try:+ from register_template import (+ SpecParseError,+ validate_qualified_spec_identity,+ )+ for item, _kind in qualified:+ validate_qualified_spec_identity(item)+ except ImportError as exc:+ raise ValueError(+ f"Qualified Design Spec validator could not be imported: {exc}"+ ) from exc+ except (OSError, SpecParseError) as exc:+ raise ValueError(str(exc)) from exc+ if exact.is_file():+ return exact+ for preferred_kind in ("layout", "deck"):+ for item, kind in qualified:+ if kind == preferred_kind:+ return item+ return None++def _resolve_workspace(path: Path) -> tuple[Path, Path]:"""Resolve one workspace root and its canonical template-source directory."""candidate = path.expanduser().resolve()- nested_spec = candidate / "templates" / "design_spec.md"- if nested_spec.is_file():+ if _roster_spec(candidate / "templates") is not None:return candidate, candidate / "templates"- direct_spec = candidate / "design_spec.md"- if direct_spec.is_file():+ if _roster_spec(candidate) is not None:if candidate.name == "templates" and (candidate.parent / "exports").is_dir():return candidate.parent, candidatereturn candidate, candidateraise ValueError(- "template workspace must contain templates/design_spec.md "- "(current structure) or design_spec.md (legacy flat package)"+ "template workspace must contain templates/design_spec.md, "+ "templates/design_spec.<layout|deck>.<id>.md, or a legacy flat "+ "design_spec.md")@@ -382,7 +437,7 @@ def main(argv: list[str] | None = None) -> int:f"SVG prototypes: {template_dir}")- spec_path = template_dir / "design_spec.md"+ spec_path = _roster_spec(template_dir)template_id = _template_id(spec_path, workspace)replication_mode = _replication_mode(spec_path)locked_canvas = _canvas_viewbox(spec_path)