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(template-reuse): add explicit reuse scopes and export audits
hugohe3d6e0bedc69d1
diff --git a/skills/ppt-master/scripts/confirm_ui/server.py b/skills/ppt-master/scripts/confirm_ui/server.pyindex 26bbe44e..d03ee8c4 100644--- a/skills/ppt-master/scripts/confirm_ui/server.py+++ b/skills/ppt-master/scripts/confirm_ui/server.py@@ -514,29 +514,48 @@ _ANCHOR_RECOMMEND_KEYS = ('mode','visual_style','delivery_purpose',+ 'template_reuse_scope','template_adherence',)_ANCHOR_VALUE_KEYS = ('audience', 'content_divergence')_DESIGN_RECOMMEND_KEYS = ('icons', 'formula_policy')+_TEMPLATE_REUSE_SCOPES = frozenset({'mirror', 'layout', 'style'})+_TEMPLATE_ADHERENCE_MODES = frozenset({'strict', 'adaptive'})-def _template_adherence_enabled(project_path: Path) -> bool:- """Return whether Step 3 loaded a deck/layout template into the project."""+def _template_context(project_path: Path) -> dict[str, object]:+ """Return the loaded template kind and replication contract."""spec_path = project_path / 'templates' / 'design_spec.md'try:lines = spec_path.read_text(encoding='utf-8').splitlines()except OSError:- return False+ return {'enabled': False, 'kind': None, 'replication_mode': None}if not lines or lines[0].strip() != '---':- return False+ return {'enabled': False, 'kind': None, 'replication_mode': None}+ kind = None+ replication_mode = Nonefor line in lines[1:]:stripped = line.strip()if stripped == '---':- return False- match = re.fullmatch(r'kind\s*:\s*["\']?(brand|layout|deck)["\']?', stripped)- if match:- return match.group(1) in {'layout', 'deck'}- return False+ break+ kind_match = re.fullmatch(+ r'kind\s*:\s*["\']?(brand|layout|deck)["\']?',+ stripped,+ )+ if kind_match:+ kind = kind_match.group(1)+ continue+ replication_match = re.fullmatch(+ r'replication_mode\s*:\s*["\']?(standard|fidelity|mirror)["\']?',+ stripped,+ )+ if replication_match:+ replication_mode = replication_match.group(1)+ return {+ 'enabled': kind in {'layout', 'deck'},+ 'kind': kind,+ 'replication_mode': replication_mode,+ }def _merge_confirmed_choices(data: dict, result_file: Path) -> None:@@ -897,16 +916,31 @@ def create_app(# the user's choices instead of catalog defaults.if _recommendation_stage(data) >= 2 and result_file.exists():_merge_confirmed_choices(data, result_file)- template_adherence_enabled = _template_adherence_enabled(project_path)+ template_context = _template_context(project_path)+ template_adherence_enabled = bool(template_context['enabled'])data['_template_adherence_enabled'] = template_adherence_enabled+ data['_template_reuse_scope_enabled'] = template_adherence_enabled+ data['_template_replication_mode'] = template_context['replication_mode']recommend = data.get('recommend')if template_adherence_enabled:if not isinstance(recommend, dict):recommend = data['recommend'] = {}- recommend.setdefault('template_adherence', 'adaptive')+ recommend.setdefault('template_reuse_scope', 'layout')+ if (+ recommend.get('template_reuse_scope') == 'mirror'+ and template_context['replication_mode'] != 'mirror'+ ):+ recommend['template_reuse_scope'] = 'layout'+ if recommend.get('template_reuse_scope') == 'style':+ recommend.pop('template_adherence', None)+ data.pop('template_adherence', None)+ else:+ recommend.setdefault('template_adherence', 'adaptive')else:if isinstance(recommend, dict):+ recommend.pop('template_reuse_scope', None)recommend.pop('template_adherence', None)+ data.pop('template_reuse_scope', None)data.pop('template_adherence', None)# The page polls this endpoint after a stage-1 confirm until the AI# overwrites the file with the re-derived stage-2 recommendations, so it@@ -923,6 +957,29 @@ def create_app(return jsonify({'error': 'invalid payload'}), 400confirm_dir.mkdir(parents=True, exist_ok=True)result = dict(payload)+ template_context = _template_context(project_path)+ if template_context['enabled']:+ reuse_scope = result.get('template_reuse_scope')+ if reuse_scope not in _TEMPLATE_REUSE_SCOPES:+ return jsonify({+ 'error': 'template_reuse_scope must be mirror, layout, or style',+ }), 400+ if (+ reuse_scope == 'mirror'+ and template_context['replication_mode'] != 'mirror'+ ):+ return jsonify({+ 'error': 'mirror reuse requires replication_mode: mirror',+ }), 400+ if reuse_scope == 'style':+ result.pop('template_adherence', None)+ elif result.get('template_adherence') not in _TEMPLATE_ADHERENCE_MODES:+ return jsonify({+ 'error': 'template_adherence must be strict or adaptive',+ }), 400+ else:+ result.pop('template_reuse_scope', None)+ result.pop('template_adherence', None)# Staged flow: stage-1 / stage-2 submits record intermediate choices but do# NOT close the page. Only a final submit is a full confirmation. A# payload with no stage is a single-pass confirmation (chat-opt-out parity).diff --git a/skills/ppt-master/scripts/confirm_ui/static/app.js b/skills/ppt-master/scripts/confirm_ui/static/app.jsindex 11c224dd..81036ac4 100644--- a/skills/ppt-master/scripts/confirm_ui/static/app.js+++ b/skills/ppt-master/scripts/confirm_ui/static/app.js@@ -1,5 +1,6 @@/* PPT Master - Strategist confirmation stage UI- * Finite/enumerable fields (canvas, mode, visual style, template adherence,+ * Finite/enumerable fields (canvas, mode, visual style, template reuse scope,+ * template adherence,* icons, image usage, AI source, formula policy, generation mode) list ALL options from* /static/catalogs.json with the AI's recommendation marked. Open/generative* fields (color, typography, generated-image style) show >=3 AI candidates. Open fields also expose@@ -38,6 +39,7 @@sec_refine: "Refine spec first",sub_mode: "Narrative mode",sub_visual: "Visual style",+ sub_template_reuse_scope: "Template reuse scope",sub_template_adherence: "Template adherence",sub_divergence: "Material divergence (how freely to reshape vs. stay close to the source)",placeholder_divergence: "In your words — e.g. \"stick closely to the document\" / \"freely restructure and expand within the source\". Leave blank for a balanced default.",@@ -150,6 +152,7 @@sec_refine: "先に設計仕様を精査",sub_mode: "ナラティブモード",sub_visual: "ビジュアルスタイル",+ sub_template_reuse_scope: "テンプレートの再利用範囲",sub_template_adherence: "テンプレートの適用方法",sub_divergence: "素材からの発散度(どこまで自由に再構成するか、原文に忠実か)",placeholder_divergence: "自分の言葉でどうぞ — 例:「文書に忠実に」「元素材の範囲内で自由に再構成・展開」。空欄ならバランス型になります。",@@ -262,6 +265,7 @@sec_refine: "先精修设计规范",sub_mode: "叙事模式",sub_visual: "视觉风格",+ sub_template_reuse_scope: "模板复用范围",sub_template_adherence: "模板遵循方式",sub_divergence: "材料发散度(多大程度重塑,还是贴近源材料)",placeholder_divergence: "用你自己的话写,例如「严格贴着文档来」/「在源材料范围内自由重组并展开」。留空则按平衡处理。",@@ -723,7 +727,30 @@return (REC && REC.recommend && REC.recommend[field]) || legacyRecId(field);}+ function hasTemplateReuseScope() {+ if (!REC) return false;+ if (typeof REC._template_reuse_scope_enabled === "boolean") {+ return REC._template_reuse_scope_enabled;+ }+ if (REC.recommend && REC.recommend.template_reuse_scope != null) return true;+ return REC.template_reuse_scope != null;+ }++ function templateReuseScopeOptions() {+ var options = (CAT && CAT.template_reuse_scope) || [];+ if (REC && REC._template_replication_mode === "mirror") return options;+ return options.filter(function (option) { return option.id !== "mirror"; });+ }++ function pickTemplateReuseScope() {+ var options = templateReuseScopeOptions();+ var recommended = recId("template_reuse_scope");+ var ids = options.map(function (option) { return option.id; });+ return ids.indexOf(recommended) >= 0 ? recommended : firstId(options);+ }+function hasTemplateAdherence() {+ if (STATE.template_reuse_scope === "style") return false;if (!REC) return false;if (typeof REC._template_adherence_enabled === "boolean") {return REC._template_adherence_enabled;@@ -1066,6 +1093,24 @@function () { return STATE.visual_style; }, function (v) { STATE.visual_style = v; refreshDirectionPreview(); },{ allowCustom: true, spectrum: REC && REC.visual_style_spectrum });sec.appendChild(sub2);+ if (hasTemplateReuseScope()) {+ var reuseField = el("div", "subfield");+ var reuseOptions = templateReuseScopeOptions();+ reuseField.appendChild(el("div", "subfield-label", t("sub_template_reuse_scope")));+ enumField(reuseField, reuseOptions,+ pickTemplateReuseScope(),+ function () { return STATE.template_reuse_scope; },+ function (v) {+ STATE.template_reuse_scope = v;+ if (v === "style") {+ delete STATE.template_adherence;+ } else if (!STATE.template_adherence) {+ STATE.template_adherence = pick("template_adherence", CAT.template_adherence);+ }+ setTimeout(renderAll, 0);+ });+ sec.appendChild(reuseField);+ }if (hasTemplateAdherence()) {var templateField = el("div", "subfield");templateField.appendChild(el("div", "subfield-label", t("sub_template_adherence")));@@ -2095,6 +2140,11 @@STATE.content_divergence = (REC.content_divergence && REC.content_divergence.value) || ""; // free text; blank = balanced defaultSTATE.mode = pick("mode", CAT.modes);STATE.visual_style = pick("visual_style", CAT.visual_styles);+ if (hasTemplateReuseScope()) {+ STATE.template_reuse_scope = pickTemplateReuseScope();+ } else {+ delete STATE.template_reuse_scope;+ }if (hasTemplateAdherence()) {STATE.template_adherence = pick("template_adherence", CAT.template_adherence);} else {@@ -2176,7 +2226,10 @@mode: STATE.mode,visual_style: STATE.visual_style};- if (STATE.template_adherence) payload.template_adherence = STATE.template_adherence;+ if (STATE.template_reuse_scope) payload.template_reuse_scope = STATE.template_reuse_scope;+ if (STATE.template_reuse_scope !== "style" && STATE.template_adherence) {+ payload.template_adherence = STATE.template_adherence;+ }// Delivery purpose is PPT-only and rendered only on PPT canvases (§c).if (isPptCanvas(STATE.canvas)) payload.delivery_purpose = STATE.delivery_purpose;return payload;@@ -2196,7 +2249,10 @@typography: STATE.typography,formula_policy: STATE.formula_policy};- if (STATE.template_adherence) payload.template_adherence = STATE.template_adherence;+ if (STATE.template_reuse_scope) payload.template_reuse_scope = STATE.template_reuse_scope;+ if (STATE.template_reuse_scope !== "style" && STATE.template_adherence) {+ payload.template_adherence = STATE.template_adherence;+ }if (isPptCanvas(STATE.canvas)) payload.delivery_purpose = STATE.delivery_purpose;normalizeTypographyForSubmit(payload);return payload;@@ -2274,6 +2330,7 @@var payload = JSON.parse(JSON.stringify(STATE));normalizeTypographyForSubmit(payload);payload.stage = "final";+ if (payload.template_reuse_scope === "style") delete payload.template_adherence;payload.image_usage = selectedImageUsageIds(payload.image_usage);if (!payload.image_usage.length) {document.getElementById("confirm-status").textContent = t("image_usage_required");diff --git a/skills/ppt-master/scripts/confirm_ui/static/catalogs.json b/skills/ppt-master/scripts/confirm_ui/static/catalogs.jsonindex 3acbb5ab..b5036a7d 100644--- a/skills/ppt-master/scripts/confirm_ui/static/catalogs.json+++ b/skills/ppt-master/scripts/confirm_ui/static/catalogs.json@@ -555,6 +555,38 @@"label_ja": "分割モード"}],+ "template_reuse_scope": [+ {+ "id": "layout",+ "label": "layout",+ "label_zh": "复用布局体系",+ "label_en": "reuse layout system",+ "label_ja": "レイアウト体系を再利用",+ "desc_zh": "保留模板的 Master、布局语法和结构身份,可按内容重排,并在需要时创建新 Layout。",+ "desc_en": "Keep the template Master and layout grammar, but allow content-driven reflow and new explicit Layouts.",+ "desc_ja": "テンプレートのMasterとレイアウト体系を保ち、内容に応じた再配置や新しいLayoutの作成を許可する。"+ },+ {+ "id": "style",+ "label": "style",+ "label_zh": "只参考视觉风格",+ "label_en": "style reference only",+ "label_ja": "ビジュアルスタイルのみ参照",+ "desc_zh": "只采用颜色、字体、装饰语言和视觉节奏;页面走自由设计,不继承模板 Master/Layout。",+ "desc_en": "Use only color, typography, decoration, and rhythm; author free-design pages without inheriting template Master/Layout structure.",+ "desc_ja": "色、書体、装飾、リズムのみを参照し、テンプレートのMaster/Layoutを継承せず自由設計する。"+ },+ {+ "id": "mirror",+ "label": "mirror",+ "label_zh": "镜像页面替换",+ "label_en": "mirror page replacement",+ "label_ja": "ミラーページ置換",+ "desc_zh": "仅镜像模板可用;复制完整原型,只替换允许变化的可见文字,保持视觉和文本节点拓扑。",+ "desc_en": "Mirror workspaces only: copy the complete prototype, replace allowed visible text, and preserve visual and text-node topology.",+ "desc_ja": "mirrorワークスペース専用。完全な原型を複製し、許可された表示テキストだけを置換して視覚とテキストノード構造を維持する。"+ }+ ],"template_adherence": [{"id": "adaptive",diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.pyindex 7211a07c..7badc511 100644--- a/skills/ppt-master/scripts/mirror_template_materialize.py+++ b/skills/ppt-master/scripts/mirror_template_materialize.py@@ -27,6 +27,7 @@ import osimport reimport sysimport tempfile+from collections import Counterfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable@@ -66,6 +67,10 @@ XLINK_NS = "http://www.w3.org/1999/xlink"XML_NS = "http://www.w3.org/XML/1998/namespace"NATIVE_STRUCTURE_SCHEMA = "ppt-master.native-structure.v1"VECTOR_INVENTORY_SCHEMA = "vector_asset_inventory.v1"+TEMPLATE_EXECUTION_MANIFEST_NAME = "template_execution_manifest.json"+TEMPLATE_EXECUTION_MANIFEST_SCHEMA = "ppt-master.template-execution-manifest.v1"+TEMPLATE_TEXT_SLOTS_DIR = "template_execution"+TEMPLATE_TEXT_SLOTS_SCHEMA = "ppt-master.template-text-slots.v1"IMPORTED_ICON_NAMESPACE = "imported"TRANSPARENT_PIXEL_DATA_URI = ("data:image/png;base64,"@@ -201,6 +206,244 @@ class MaterializedFile:payload: bytes+def _ancestor_chain(+ element: ET.Element,+ parent_by_child: dict[ET.Element, ET.Element],+) -> list[ET.Element]:+ """Return one element followed by its ancestors up to the SVG root."""+ chain = [element]+ while chain[-1] in parent_by_child:+ chain.append(parent_by_child[chain[-1]])+ return chain+++def _stable_text_selector(+ element: ET.Element,+ parent_by_child: dict[ET.Element, ET.Element],+) -> str:+ """Build a stable, human-readable selector for one materialized text node."""+ segments: list[str] = []+ current = element+ while True:+ element_id = (current.get("id") or "").strip()+ if element_id:+ segments.append(f"#{element_id}")+ break+ parent = parent_by_child.get(current)+ tag = _local_name(current.tag)+ if parent is None:+ segments.append(tag)+ break+ same_tag = [+ child+ for child in parent+ if _local_name(child.tag) == tag+ ]+ position = same_tag.index(current) + 1+ segments.append(f"{tag}:nth-of-type({position})")+ current = parent+ return " > ".join(reversed(segments))+++def _nearest_attribute(+ chain: list[ET.Element],+ name: str,+) -> str | None:+ for element in chain:+ value = element.get(name)+ if value is not None:+ return value+ return None+++def _text_slot_bounds(chain: list[ET.Element]) -> dict[str, float | None]:+ """Read the nearest four-value placeholder/native frame when available."""+ for name in ("data-pptx-placeholder-bounds", "data-pptx-frame"):+ raw = _nearest_attribute(chain, name)+ if raw is None:+ continue+ try:+ values = [float(value) for value in raw.replace(",", " ").split()]+ except ValueError:+ continue+ if len(values) == 4 and all(math.isfinite(value) for value in values):+ return dict(zip(("x", "y", "width", "height"), values))+ return {"x": None, "y": None, "width": None, "height": None}+++def _text_topology_sha256(element: ET.Element) -> str:+ """Hash text/tspan topology and attributes while excluding visible values."""+ digest = hashlib.sha256()++ def visit(node: ET.Element) -> None:+ digest.update(_local_name(node.tag).encode("utf-8"))+ for name, value in sorted(node.attrib.items()):+ digest.update(b"\0a")+ digest.update(name.encode("utf-8"))+ digest.update(b"\0")+ digest.update(value.encode("utf-8"))+ for child in node:+ digest.update(b"\0c")+ visit(child)+ digest.update(b"\0e")++ visit(element)+ return digest.hexdigest()+++def _template_text_slots(root: ET.Element) -> list[dict[str, object]]:+ """Describe exact mirror-safe text replacement slots for one template."""+ parent_by_child = {+ child: parent+ for parent in root.iter()+ for child in parent+ }+ slots: list[dict[str, object]] = []+ for text_element in root.iter():+ if _local_name(text_element.tag) != "text":+ continue+ chain = _ancestor_chain(text_element, parent_by_child)+ placeholder = _nearest_attribute(chain, "data-pptx-placeholder")+ editable_value = _nearest_attribute(chain, "data-pptx-editable")+ inherited_layer = _nearest_attribute(chain, "data-pptx-layer")+ tspans = [+ child+ for child in text_element.iter()+ if child is not text_element and _local_name(child.tag) == "tspan"+ ]+ segments = [+ text_element.text or "",+ *[(tspan.text or "") for tspan in tspans],+ ]+ if tspans and not segments[0].strip():+ segments = segments[1:]+ slots.append({+ "selector": _stable_text_selector(text_element, parent_by_child),+ "role": placeholder or "text",+ "editable": editable_value != "false" and inherited_layer is None,+ "current_text": "".join(text_element.itertext()),+ "text_segments": segments,+ "text_attributes": dict(sorted(text_element.attrib.items())),+ "tspan_count": len(tspans),+ "tspan_attributes": [+ dict(sorted(tspan.attrib.items()))+ for tspan in tspans+ ],+ "topology_sha256": _text_topology_sha256(text_element),+ "bbox": _text_slot_bounds(chain),+ "font_stack": _nearest_attribute(chain, "font-family"),+ })+ return slots+++def _json_bytes(payload: dict[str, object]) -> bytes:+ return (+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n"+ ).encode("utf-8")+++def _template_execution_manifest_files(+ materialized_roots: list[tuple[Path, ET.Element]],+ source_import: dict[str, object] | None,+) -> list[MaterializedFile]:+ """Serialize one compact roster plus per-prototype text-slot sidecars."""+ templates: list[dict[str, object]] = []+ files: list[MaterializedFile] = []+ for relative_path, root in sorted(+ materialized_roots,+ key=lambda item: item[0].as_posix(),+ ):+ prototype = relative_path.name+ text_slots = _template_text_slots(root)+ text_slots_path = (+ Path("templates")+ / TEMPLATE_TEXT_SLOTS_DIR+ / f"{relative_path.stem}.text-slots.json"+ )+ files.append(MaterializedFile(+ text_slots_path,+ _json_bytes({+ "schema": TEMPLATE_TEXT_SLOTS_SCHEMA,+ "prototype": prototype,+ "text_slot_count": len(text_slots),+ "text_slots": text_slots,+ }),+ ))+ templates.append({+ "prototype": prototype,+ "page_type": relative_path.stem.split("_", 1)[-1],+ "viewBox": root.get("viewBox"),+ "master": root.get("data-pptx-master"),+ "layout": root.get("data-pptx-layout"),+ "layout_name": root.get("data-pptx-layout-name"),+ "text_slot_count": len(text_slots),+ "editable_text_slot_count": sum(+ 1 for slot in text_slots if slot["editable"]+ ),+ "text_slots_path": text_slots_path.relative_to(+ Path("templates")+ ).as_posix(),+ })+ payload = {+ "schema": TEMPLATE_EXECUTION_MANIFEST_SCHEMA,+ "replication_mode": "mirror",+ "template_root": ".",+ "template_count": len(templates),+ "execution_policy": (+ "Read this compact roster once. Before authoring each page, read the "+ "selected template's text_slots_path and complete prototype SVG. "+ "Replace visible text values only; preserve every text/tspan node, "+ "order, nesting level, and attribute."+ ),+ "source_import": source_import or {+ "warning_count": 0,+ "by_code": {},+ },+ "templates": templates,+ }+ files.append(MaterializedFile(+ Path("templates") / TEMPLATE_EXECUTION_MANIFEST_NAME,+ _json_bytes(payload),+ ))+ return files+++def _source_import_summary(import_workspace: Path) -> dict[str, object] | None:+ """Summarize source-owned tolerant-import diagnostics by stable code."""+ report_path = import_workspace / "conversion-report.json"+ try:+ report = json.loads(report_path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, json.JSONDecodeError) as exc:+ raise MirrorMaterializationError(+ f"Cannot read source conversion report {report_path}: {exc}"+ ) from exc+ diagnostics = report.get("diagnostics")+ if not isinstance(diagnostics, list):+ raise MirrorMaterializationError(+ f"Source conversion report has no diagnostics array: {report_path}"+ )+ by_code: Counter[str] = Counter()+ samples: dict[str, str] = {}+ for item in diagnostics:+ if not isinstance(item, dict):+ continue+ severity = str(item.get("severity") or "warning").lower()+ if severity != "warning":+ continue+ code = str(item.get("code") or "unknown")+ by_code[code] += 1+ message = item.get("message")+ if code not in samples and isinstance(message, str) and message:+ samples[code] = message+ return {+ "warning_count": sum(by_code.values()),+ "by_code": dict(sorted(by_code.items())),+ "samples": dict(sorted(samples.items())),+ }++def _local_name(name: object) -> str:return name.rsplit("}", 1)[-1] if isinstance(name, str) else ""@@ -2659,6 +2902,13 @@ def materialize_mirror_template(for relative_path, root in output_roots:files.append(MaterializedFile(relative_path, _serialize_svg(root)))+ execution_manifest_path = Path("templates") / TEMPLATE_EXECUTION_MANIFEST_NAME+ files.extend(+ _template_execution_manifest_files(+ materialized_roots,+ _source_import_summary(import_workspace),+ )+ )for relative_target, source in sorted(asset_sources.items()):files.append(MaterializedFile(relative_target, source.read_bytes()))@@ -2729,6 +2979,8 @@ def materialize_mirror_template("layout_count": len(layouts),"unused_layout_count": len(unused_layouts),"template_svg_count": len(materialized_roots),+ "template_execution_manifest": execution_manifest_path.as_posix(),+ "template_text_slot_manifest_count": len(materialized_roots),"imported_vector_count": len(referenced_icons),"packaged_asset_count": len(asset_sources),"restoration": total_stats.as_dict(),diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 38d66cce..5a09b707 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -16,6 +16,7 @@ import reimport jsonimport htmlimport math+import hashlibfrom pathlib import Pathfrom typing import List, Dict, Tuplefrom collections import Counter, defaultdict@@ -1157,8 +1158,47 @@ class SVGQualityChecker:self._animation_issues: List[Tuple[str, str]] = []self._illustration_issues: List[Tuple[str, str, str]] = []self._pptx_structure_issues: List[Tuple[str, str]] = []+ self._has_incomplete_page_roster = False+ self._prototype_by_output: Dict[Path, Path] = {}+ self._active_prototype_path: Path | None = None+ self._active_template_reuse_scope: str | None = None+ self._prototype_root_cache: Dict[Path, ET.Element | None] = {}+ self._source_import_summary: Dict[str, object] = {+ 'warning_count': 0,+ 'by_code': {},+ }self._aggregate_counts_applied = False+ @staticmethod+ def _append_inherited_info(+ result: Dict,+ kind: str,+ message: str,+ ) -> None:+ """Record prototype-owned diagnostics outside the warning channel."""+ result['info'].setdefault('inherited', []).append({+ 'kind': kind,+ 'message': message,+ })++ def _active_prototype_root(self) -> ET.Element | None:+ """Parse the selected mirror prototype once for inherited checks."""+ if (+ self._active_template_reuse_scope != 'mirror'+ or self._active_prototype_path is None+ ):+ return None+ path = self._active_prototype_path.resolve()+ if path in self._prototype_root_cache:+ return self._prototype_root_cache[path]+ try:+ root = ET.parse(path).getroot()+ hydrate_native_payload_refs(root, path)+ except (OSError, ET.ParseError, NativePayloadError):+ root = None+ self._prototype_root_cache[path] = root+ return root+def check_file(self,svg_file: str,@@ -1199,8 +1239,9 @@ class SVGQualityChecker:}try:- with open(svg_path, 'r', encoding='utf-8') as f:- content = f.read()+ source_bytes = svg_path.read_bytes()+ result['source_sha256'] = hashlib.sha256(source_bytes).hexdigest()+ content = source_bytes.decode('utf-8')# 0. Parse XML once — every other check assumes the file is valid# XML. Bail early on failure so the regex-based checks below don't@@ -3468,6 +3509,7 @@ class SVGQualityChecker:non_visual = {'defs', 'title', 'desc', 'metadata', 'style'}group_indexes: Dict[str, List[int]] = defaultdict(list)ungrouped: List[str] = []+ ungrouped_signatures: List[Tuple[object, ...]] = []visual_index = 0for child in root:@@ -3507,6 +3549,9 @@ class SVGQualityChecker:f'<{tag} id="{child_id}">'if child_id else f'<{tag}> #{visual_index}')+ ungrouped_signatures.append(+ self._prototype_element_signature(child)+ )for group_id, indexes in sorted(group_indexes.items()):if len(indexes) > 1:@@ -3520,11 +3565,77 @@ class SVGQualityChecker:samples = ', '.join(ungrouped[:3])if len(ungrouped) > 3:samples += ', ...'- result['warnings'].append(+ message = (f'{len(ungrouped)} ungrouped top-level Slide-local element(s) 'f'in svg_output ({samples}); wrap each logical content unit ''in a top-level <g id="...">')+ prototype_root = self._active_prototype_root()+ prototype_ungrouped = (+ self._ungrouped_slide_local_facts(prototype_root)+ if prototype_root is not None+ else ([], [])+ )+ if (+ prototype_root is not None+ and ungrouped == prototype_ungrouped[0]+ and ungrouped_signatures == prototype_ungrouped[1]+ ):+ self._append_inherited_info(+ result,+ 'animation_anchor',+ message,+ )+ else:+ result['warnings'].append(message)++ @staticmethod+ def _prototype_element_signature(+ element: ET.Element,+ ) -> Tuple[object, ...]:+ """Compare warning-owned topology/style while ignoring visible text."""+ return (+ _local_name(element),+ tuple(sorted(element.attrib.items())),+ tuple(+ SVGQualityChecker._prototype_element_signature(child)+ for child in element+ ),+ )++ def _ungrouped_slide_local_facts(+ self,+ root: ET.Element,+ ) -> Tuple[List[str], List[Tuple[object, ...]]]:+ """Describe and fingerprint top-level non-group Slide-local atoms."""+ non_visual = {'defs', 'title', 'desc', 'metadata', 'style'}+ descriptors: List[str] = []+ signatures: List[Tuple[object, ...]] = []+ visual_index = 0+ for child in root:+ tag = _local_name(child)+ if tag in non_visual:+ continue+ visual_index += 1+ if tag == 'g' or child.get('data-pptx-layer') is not None:+ continue+ if (+ _is_static_page_frame is not None+ and _is_static_page_frame(+ child.get('data-pptx-role'),+ child.get('data-pptx-placeholder'),+ )+ ):+ continue+ if visual_index == 1 and self._is_full_canvas_root_rect(root, child):+ continue+ child_id = (child.get('id') or '').strip()+ descriptors.append(+ f'<{tag} id="{child_id}">'+ if child_id else f'<{tag}> #{visual_index}'+ )+ signatures.append(self._prototype_element_signature(child))+ return descriptors, signatures# OOXML ST_PresetPatternVal enum — anything outside this set produces a# PPTX schema violation ("PowerPoint found a problem with the content").@@ -3913,8 +4024,8 @@ class SVGQualityChecker:"frame, or move independently positioned lines outside the slot")- @staticmethoddef _append_structure_coverage_warnings(+ self,root: ET.Element,result: Dict,) -> None:@@ -3924,8 +4035,29 @@ class SVGQualityChecker:advisory warnings. They neither fail the workflow gate nor require aper-warning disposition."""- if not (root.get('data-pptx-layout') or '').strip():+ messages = self._structure_coverage_messages(root)+ if not messages:return+ prototype_root = self._active_prototype_root()+ if (+ prototype_root is not None+ and messages == self._structure_coverage_messages(prototype_root)+ ):+ for message in messages:+ self._append_inherited_info(+ result,+ 'structure_coverage',+ message,+ )+ return+ result['warnings'].extend(messages)++ @staticmethod+ def _structure_coverage_messages(root: ET.Element) -> List[str]:+ """Return advisory coverage messages for one structured page."""+ if not (root.get('data-pptx-layout') or '').strip():+ return []+ messages: List[str] = []has_layer_mark = any(elem.get('data-pptx-layer') is not Nonefor elem in root.iter()@@ -3939,7 +4071,7 @@ class SVGQualityChecker:for elem in root.iter())if not has_layer_mark:- result['warnings'].append(+ messages.append('Mapped page declares data-pptx-layout but no data-pptx-layer ''mark; the exported Master gets no shared background/chrome ''and the Layout gets no static framing. Generated templates '@@ -3949,7 +4081,7 @@ class SVGQualityChecker:'is required.')if not has_placeholder and not has_layout_atom:- result['warnings'].append(+ messages.append('Mapped page has no placeholder slot and no ''data-pptx-layer="layout" atom; its Layout exports empty. ''Generated templates should declare the slots the page actually '@@ -3959,13 +4091,14 @@ class SVGQualityChecker:'zero-slot composition. No change or disposition is required.')elif not has_placeholder:- result['warnings'].append(+ messages.append('Mapped Layout has static framing but no insertable ''placeholder slot. Generated templates should declare the ''slots the page actually has (title / subtitle / body / ''picture / slide-number / footer) unless zero-slot is the ''intended reusable contract. No change or disposition is required.')+ return messagesdef _check_semantic_markers(self,@@ -4023,6 +4156,43 @@ class SVGQualityChecker:return datareturn None+ def _prototype_drift_allowances(+ self,+ ) -> Tuple[set[str], set[str], set[str]]:+ """Return color/font/size values owned by the selected mirror page."""+ if self._active_prototype_root() is None:+ return set(), set(), set()+ try:+ content = self._active_prototype_path.read_text(encoding='utf-8')+ except (AttributeError, OSError):+ return set(), set(), set()++ colors: set[str] = set()+ for attribute in _PAINT_PROPERTIES or ():+ for raw_value in self._svg_property_values(content, attribute):+ normalized = raw_value.strip()+ if normalized.lower() in {'none', 'transparent'} or re.fullmatch(+ r'url\(#[^)]+\)', normalized+ ):+ continue+ if _parse_export_color is not None:+ color, _alpha = _parse_export_color(normalized)+ else:+ color = _normalize_hex_rgb(normalized)+ if color:+ colors.add(color)+ fonts = {+ self._normalize_font_stack(value)+ for value in self._font_family_values(content)+ if self._normalize_font_stack(value)+ }+ sizes = {+ self._normalize_size(value)+ for value in self._svg_property_values(content, 'font-size')+ if self._normalize_size(value)+ }+ return colors, fonts, sizes+def _check_spec_lock_drift(self,content: str,@@ -4043,6 +4213,9 @@ class SVGQualityChecker:lock = self._get_spec_lock(svg_path)if lock is None:return+ prototype_colors, prototype_fonts, prototype_sizes = (+ self._prototype_drift_allowances()+ )# Build allow-sets from the lockallowed_colors = set()@@ -4080,6 +4253,8 @@ class SVGQualityChecker:color = _normalize_hex_rgb(raw_value)if color:allowed_colors.add(color)+ locked_colors = set(allowed_colors)+ allowed_colors.update(prototype_colors)typo = lock.get('typography', {})numeric_size_re = re.compile(r'^(?:\d+(?:\.\d+)?|\.\d+)$')@@ -4115,6 +4290,8 @@ class SVGQualityChecker:if not v_clean or v_clean.lower().startswith('same as'):continueallowed_fonts.add(self._normalize_font_stack(v_clean))+ locked_fonts = set(allowed_fonts)+ allowed_fonts.update(prototype_fonts)# Sizes: declared slots are anchors; body is the ramp baseline.allowed_sizes = set()@@ -4128,9 +4305,12 @@ class SVGQualityChecker:body_px = float(self._normalize_size(v))except (ValueError, TypeError):body_px = None+ locked_sizes = set(allowed_sizes)+ allowed_sizes.update(prototype_sizes)# Scan SVG for used valuescolor_drifts = set()+ inherited_colors = set()for attr in _PAINT_PROPERTIES or ():for raw_value in self._svg_property_values(content, attr):normalized = raw_value.strip()@@ -4150,11 +4330,20 @@ class SVGQualityChecker:continueif val not in allowed_colors:color_drifts.add(f'#{val}')+ elif val in prototype_colors and val not in locked_colors:+ inherited_colors.add(f'#{val}')font_drifts = set()+ inherited_fonts = set()for val in self._font_family_values(content):- if allowed_fonts and self._normalize_font_stack(val) not in allowed_fonts:+ normalized_font = self._normalize_font_stack(val)+ if allowed_fonts and normalized_font not in allowed_fonts:font_drifts.add(val)+ elif (+ normalized_font in prototype_fonts+ and normalized_font not in locked_fonts+ ):+ inherited_fonts.add(val)# Poster / showcase contexts use unbounded hero type — drop the ceiling.mode = (lock.get('mode', {}).get('mode') or '').strip().lower()@@ -4163,10 +4352,14 @@ class SVGQualityChecker:else RAMP_MAX_RATIO)size_drifts = set()+ inherited_sizes = set()used_sizes = []for raw_value in self._svg_property_values(content, 'font-size'):val = self._normalize_size(raw_value)used_sizes.append(val)+ if val in prototype_sizes and val not in locked_sizes:+ inherited_sizes.add(val)+ continueif not allowed_sizes or val in allowed_sizes:continue# Intermediate values are allowed when they sit inside the ramp@@ -4206,6 +4399,20 @@ class SVGQualityChecker:f"spec_lock drift: {', '.join(parts)} not in spec_lock.md ""(see drift summary for details)")+ inherited_parts = []+ if inherited_colors:+ inherited_parts.append(f"{len(inherited_colors)} color(s)")+ if inherited_fonts:+ inherited_parts.append(f"{len(inherited_fonts)} font-family value(s)")+ if inherited_sizes:+ inherited_parts.append(f"{len(inherited_sizes)} font-size value(s)")+ if inherited_parts:+ self._append_inherited_info(+ result,+ 'spec_lock_drift',+ f"{', '.join(inherited_parts)} come unchanged from mirror "+ "prototype and are accepted without expanding spec_lock.md",+ )if template_size_drift:result['warnings'].append(template_size_drift)@@ -4374,6 +4581,74 @@ class SVGQualityChecker:else:return 'Other'+ def _configure_prototype_context(+ self,+ target_path: Path,+ svg_files: List[Path],+ ) -> None:+ """Map generated pages to selected prototypes for inherited diagnostics."""+ self._prototype_by_output = {}+ self._active_prototype_path = None+ self._active_template_reuse_scope = None+ self._source_import_summary = {+ 'warning_count': 0,+ 'by_code': {},+ }+ if self.template_mode or _load_pptx_structure_lock is None:+ return+ project_path = self._resolve_project_path(target_path)+ try:+ structure_lock = _load_pptx_structure_lock(project_path)+ except (_TemplateStructureError, OSError):+ # The project-level structure gate reports the actionable parser+ # error. Inherited classification is optional and stays silent.+ return+ if structure_lock is None:+ return+ self._active_template_reuse_scope = getattr(+ structure_lock,+ 'template_reuse_scope',+ None,+ )+ references = {+ reference.slide_num: reference.svg_path+ for reference in structure_lock.prototypes+ }+ if target_path.is_file():+ sibling_files = sorted(target_path.parent.glob('*.svg'))+ resolved_target = target_path.resolve()+ slide_num = next(+ (+ index+ for index, sibling in enumerate(sibling_files, start=1)+ if sibling.resolve() == resolved_target+ ),+ 1,+ )+ prototype = references.get(slide_num)+ if prototype is not None:+ self._prototype_by_output[resolved_target] = prototype.resolve()+ else:+ for slide_num, svg_path in enumerate(svg_files, start=1):+ prototype = references.get(slide_num)+ if prototype is not None:+ self._prototype_by_output[svg_path.resolve()] = prototype.resolve()++ if self._active_template_reuse_scope not in {'mirror', 'layout'}:+ return+ manifest_path = (+ project_path / 'templates' / 'template_execution_manifest.json'+ )+ try:+ manifest = json.loads(manifest_path.read_text(encoding='utf-8'))+ except (FileNotFoundError, OSError, json.JSONDecodeError):+ return+ if manifest.get('schema') != 'ppt-master.template-execution-manifest.v1':+ return+ source_import = manifest.get('source_import')+ if isinstance(source_import, dict):+ self._source_import_summary = source_import+def check_directory(self, directory: str, expected_format: str = None) -> List[Dict]:"""Check all SVG files in a directory@@ -4386,6 +4661,7 @@ class SVGQualityChecker:List of check results"""dir_path = Path(directory)+ self._has_incomplete_page_roster = Falseif not dir_path.exists():print(f"[ERROR] Directory does not exist: {directory}")@@ -4456,6 +4732,8 @@ class SVGQualityChecker:self.issue_types['Input issues'] += 1return []+ self._configure_prototype_context(dir_path, svg_files)+directory_expected_viewbox: str | None = Nonedirectory_expected_label = "the first SVG canvas"directory_lock_has_canvas = False@@ -4503,6 +4781,9 @@ class SVGQualityChecker:print(f"\n[SCAN] Checking {len(svg_files)} SVG file(s)...\n")for svg_file in svg_files:+ self._active_prototype_path = self._prototype_by_output.get(+ svg_file.resolve()+ )result = self.check_file(str(svg_file),expected_format,@@ -4671,6 +4952,18 @@ class SVGQualityChecker:returnif complete_roster:+ actual_slides = {spec.slide_num for spec in specs}+ expected_slides = {+ reference.slide_num+ for reference in structure_lock.layouts+ }+ expected_slides.update(+ reference.slide_num+ for reference in structure_lock.prototypes+ )+ self._has_incomplete_page_roster = bool(+ expected_slides - actual_slides+ )self._pptx_structure_issues.extend(('error', message)for message in _template_lock_errors(specs, structure_lock)@@ -5766,6 +6059,9 @@ class SVGQualityChecker:# Explicit PowerPoint master/layout structure aggregation.self._print_pptx_structure_summary()+ # Source-owned import recovery belongs to the template, not this run.+ self._print_source_import_summary()+# Fix suggestionsif self.summary['errors'] > 0 or self.summary['warnings'] > 0:print(f"\n[TIP] Common fixes:")@@ -5819,6 +6115,23 @@ class SVGQualityChecker:for severity, message in self._pptx_structure_issues:print(f" [{severity.upper()}] {message}")+ def _print_source_import_summary(self):+ """Print source-owned tolerant-import diagnostics as information."""+ warning_count = _source_import_warning_count(+ self._source_import_summary+ )+ if warning_count <= 0:+ return+ print("\n[SOURCE IMPORT] Template-owned compatibility diagnostics")+ print(+ f" [INFO] {warning_count} source-import warning(s); unchanged "+ "template recovery is not attributed to generated content."+ )+ by_code = self._source_import_summary.get('by_code')+ if isinstance(by_code, dict):+ for code, count in sorted(by_code.items()):+ print(f" {code}: {count}")+def _print_template_summary(self):"""Aggregate template-mode roster / placeholder issues at the bottom.@@ -5962,6 +6275,187 @@ class SVGQualityChecker:print(f"\n[REPORT] Check report exported: {output_file}")+ def export_json_report(+ self,+ output_file: str,+ *,+ target: str,+ stage: str,+ ) -> None:+ """Write a machine-readable quality report with provenance classes."""+ self._apply_aggregated_issue_counts()+ introduced: List[Dict[str, str]] = []+ blocking: List[Dict[str, str]] = []+ inherited: List[Dict[str, str]] = []+ for result in self.results:+ filename = str(result.get('file') or '')+ introduced.extend({+ 'file': filename,+ 'message': warning,+ } for warning in result.get('warnings', []))+ blocking.extend({+ 'file': filename,+ 'message': error,+ } for error in result.get('errors', []))+ info = result.get('info') or {}+ for item in info.get('inherited', []):+ if isinstance(item, dict):+ inherited.append({+ 'file': filename,+ 'kind': str(item.get('kind') or 'prototype'),+ 'message': str(item.get('message') or ''),+ })++ project_issues = {+ 'template': [+ {'severity': severity, 'kind': kind, 'message': message}+ for severity, kind, message in self._template_issues+ ],+ 'animation': [+ {'severity': severity, 'message': message}+ for severity, message in self._animation_issues+ ],+ 'illustration': [+ {'severity': severity, 'kind': kind, 'message': message}+ for severity, kind, message in self._illustration_issues+ ],+ 'pptx_structure': [+ {'severity': severity, 'message': message}+ for severity, message in self._pptx_structure_issues+ ],+ }+ for group, issues in project_issues.items():+ for issue in issues:+ item = {+ 'scope': group,+ 'message': issue['message'],+ }+ if issue['severity'] == 'error':+ blocking.append(item)+ else:+ introduced.append(item)++ drift = {+ category: {+ value: sorted(files)+ for value, files in sorted(values.items())+ }+ for category, values in self._drift_summary.items()+ }+ source_import = dict(self._source_import_summary)+ payload = {+ 'schema': 'ppt-master.svg-quality-report.v1',+ 'stage': stage,+ 'target': str(Path(target).resolve()),+ 'source_fingerprint': _quality_source_fingerprint(self.results),+ 'summary': dict(self.summary),+ 'issue_types': dict(sorted(self.issue_types.items())),+ 'categories': {+ 'blocking': {+ 'count': len(blocking),+ 'issues': blocking,+ },+ 'introduced': {+ 'count': len(introduced),+ 'issues': introduced,+ },+ 'inherited': {+ 'count': len(inherited),+ 'issues': inherited,+ },+ 'source-import': {+ 'count': _source_import_warning_count(source_import),+ 'summary': source_import,+ },+ },+ 'drift': drift,+ 'project_issues': project_issues,+ 'files': self.results,+ }+ report_path = Path(output_file)+ report_path.parent.mkdir(parents=True, exist_ok=True)+ report_path.write_text(+ json.dumps(payload, ensure_ascii=False, indent=2) + '\n',+ encoding='utf-8',+ )+ print(f"\n[REPORT] JSON quality report exported: {report_path}")+++def _source_import_warning_count(summary: Dict[str, object]) -> int:+ """Return only a schema-compatible non-negative warning count."""+ value = summary.get('warning_count')+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return 0+ return value+++def _quality_source_fingerprint(results: List[Dict]) -> Dict[str, object]:+ """Bind a quality report to the exact SVG bytes that were checked."""+ files: List[Dict[str, object]] = []+ aggregate = hashlib.sha256()+ candidates = sorted(+ (+ result+ for result in results+ if result.get('exists') and result.get('path')+ ),+ key=lambda result: Path(str(result['path'])).name,+ )+ for result in candidates:+ path = Path(str(result['path']))+ file_sha256 = result.get('source_sha256')+ if not isinstance(file_sha256, str):+ files.append({+ 'file': path.name,+ 'sha256': None,+ 'error': 'source bytes were not available during validation',+ })+ file_sha256 = 'unreadable'+ else:+ files.append({'file': path.name, 'sha256': file_sha256})+ aggregate.update(path.name.encode('utf-8'))+ aggregate.update(b'\0')+ aggregate.update(file_sha256.encode('ascii'))+ aggregate.update(b'\n')+ return {+ 'algorithm': 'sha256',+ 'digest': aggregate.hexdigest(),+ 'file_count': len(files),+ 'files': files,+ }+++def _first_page_target(target: str) -> str:+ """Resolve a project/directory target to its first authored SVG page."""+ path = Path(target)+ if path.is_file():+ return str(path)+ svg_root = path / 'svg_output' if (path / 'svg_output').is_dir() else path+ svg_files = sorted(svg_root.glob('*.svg')) if svg_root.is_dir() else []+ return str(svg_files[0]) if svg_files else target+++def _default_json_report_path(+ checker: SVGQualityChecker,+ target: str,+ stage: str,+) -> Path:+ """Choose a stage-specific report path without overwriting the final gate."""+ target_path = Path(target)+ project_path = checker._resolve_project_path(target_path)+ report_name = (+ 'svg_quality_report.json'+ if stage == 'final'+ else 'svg_quality_first_page_report.json'+ )+ if (+ (project_path / 'svg_output').is_dir()+ or (project_path / 'design_spec.md').is_file()+ ):+ return project_path / 'exports' / report_name+ base = target_path if target_path.is_dir() else target_path.parent+ return base / report_name+def print_usage() -> None:"""Print CLI usage information."""@@ -5979,6 +6473,11 @@ def print_usage() -> None:print(" python3 scripts/svg_quality_checker.py templates/decks/中国电信/templates --template-mode")print("\nOptions:")print(" --format <ppt169|ppt43|...> Expected canvas format")+ print(" --stage <first-page|final> first-page checks only the first authored SVG")+ print(" with a partial structure roster; final (default)")+ print(" requires the complete declared page roster.")+ print(" --json Write a machine-readable quality report")+ print(" --json-output <path> Override the JSON report path")print(" --template-mode Validate a template workspace's templates/ directory:")print(" Brand validates design_spec.md and referenced assets;")print(" Layout/Deck glob *.svg directly, skip spec_lock checks,")@@ -6012,14 +6511,27 @@ def main() -> None:# Parse argumentstarget = sys.argv[1]expected_format = None+ stage = 'final'if '--format' in sys.argv:idx = sys.argv.index('--format')if idx + 1 < len(sys.argv):expected_format = sys.argv[idx + 1]+ if '--stage' in sys.argv:+ idx = sys.argv.index('--stage')+ if idx + 1 >= len(sys.argv):+ print("[ERROR] --stage requires first-page or final")+ sys.exit(1)+ stage = sys.argv[idx + 1]+ if stage not in {'first-page', 'final'}:+ print(f"[ERROR] Unsupported quality-check stage: {stage}")+ sys.exit(1)# Execute checkif target == '--all':+ if stage != 'final':+ print("[ERROR] --stage first-page does not support --all")+ sys.exit(1)# Check all example projectsbase_dir = sys.argv[2] if len(sys.argv) > 2 else 'examples'from project_utils import find_all_projects@@ -6031,7 +6543,16 @@ def main() -> None:print('=' * 80)checker.check_directory(str(project))else:- checker.check_directory(target, expected_format)+ check_target = _first_page_target(target) if stage == 'first-page' else target+ checker.check_directory(check_target, expected_format)++ if stage == 'final' and Path(target).is_dir():+ if checker._has_incomplete_page_roster:+ print(+ "[TIP] This final-stage run found an incomplete page roster. "+ "During serial authoring, use --stage first-page for the first-page "+ "gate; keep --stage final for the complete deck."+ )# Print summarychecker.print_summary()@@ -6045,6 +6566,21 @@ def main() -> None:output_file = sys.argv[idx + 1]checker.export_report(output_file)+ if '--json' in sys.argv or '--json-output' in sys.argv:+ if '--json-output' in sys.argv:+ idx = sys.argv.index('--json-output')+ if idx + 1 >= len(sys.argv):+ print("[ERROR] --json-output requires a path")+ sys.exit(1)+ json_output = Path(sys.argv[idx + 1])+ else:+ json_output = _default_json_report_path(checker, target, stage)+ checker.export_json_report(+ str(json_output),+ target=target,+ stage=stage,+ )+# Return exit codeif checker.summary['errors'] > 0:sys.exit(1)diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.pyindex 12be4729..65a01fd8 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py@@ -4821,6 +4821,12 @@ def create_pptx_with_native_svg(for i, svg_path in enumerate(svg_files, 1):slide_num = iis_layout_definition = slide_num > public_slide_count+ progress_label = (+ f"[Layout definition {slide_num - public_slide_count}/"+ f"{len(definition_svg_files)}]"+ if is_layout_definition+ else f"[Slide {slide_num}/{public_slide_count}]"+ )expected_animation_targets: list[tuple[int, int, str, float]] = []expected_animation_duration = animation_durationexpected_animation_trigger = normalize_animation_trigger(animation_trigger)@@ -5251,19 +5257,18 @@ def create_pptx_with_native_svg(has_notes = slide_num in notes_slides_creatednotes_str = " +notes" if has_notes else ""narration_str = " +narration" if slide_num in narration_slides_created else ""- definition_str = (- " [Layout definition]" if is_layout_definition else ""- )print(- f" [{i}/{len(svg_files)}] {svg_path.name}{mode_str}"- f"{notes_str}{narration_str}{definition_str}"+ f" {progress_label} {svg_path.name}{mode_str}"+ f"{notes_str}{narration_str}")success_count += 1except Exception as e:if verbose:- print(f" [{i}/{len(svg_files)}] {svg_path.name} - Error: {e}")+ print(+ f" {progress_label} {svg_path.name} - Error: {e}"+ )if use_native_shapes:raisediff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.pyindex a0a05c40..89520803 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py@@ -2,12 +2,14 @@from __future__ import annotations-import sys+import argparse+import hashlibimport jsonimport mathimport reimport shutil-import argparse+import sys+import zipfilefrom datetime import datetimefrom pathlib import Pathfrom xml.etree import ElementTree as ET@@ -86,6 +88,305 @@ _LEGACY_PPTX_STRUCTURE_MODES = frozenset({'template',})_RELEASE_PPTX_STRUCTURE_MODES = frozenset({'flat', 'structured'})+_CSS_GENERIC_FONT_FAMILIES = frozenset({+ 'cursive',+ 'emoji',+ 'fangsong',+ 'fantasy',+ 'math',+ 'monospace',+ 'sans-serif',+ 'serif',+ 'system-ui',+ 'ui-monospace',+ 'ui-rounded',+ 'ui-sans-serif',+ 'ui-serif',+})+++class PptxPostflightValidationError(RuntimeError):+ """Reject a generated PPTX that fails package postflight validation."""+++def _font_stack_is_generic_only(stack: str) -> bool:+ """Return whether a CSS font stack contains no concrete family name."""+ families = [+ family.strip().strip('"\'').strip().lower()+ for family in stack.split(',')+ if family.strip().strip('"\'').strip()+ ]+ return bool(families) and all(+ family in _CSS_GENERIC_FONT_FAMILIES+ for family in families+ )+++def _package_part_counts(pptx_path: Path) -> dict[str, object]:+ """Count public and structural OOXML parts in a completed PPTX package."""+ with zipfile.ZipFile(pptx_path) as archive:+ bad_member = archive.testzip()+ names = archive.namelist()++ def count(pattern: str) -> int:+ matcher = re.compile(pattern)+ return sum(bool(matcher.fullmatch(name)) for name in names)++ return {+ 'zip_integrity': 'passed' if bad_member is None else 'failed',+ 'corrupt_member': bad_member,+ 'slides': count(r'ppt/slides/slide\d+\.xml'),+ 'notes': count(r'ppt/notesSlides/notesSlide\d+\.xml'),+ 'masters': count(r'ppt/slideMasters/slideMaster\d+\.xml'),+ 'layouts': count(r'ppt/slideLayouts/slideLayout\d+\.xml'),+ }+++def _source_resource_audit(svg_files: list[Path]) -> dict[str, object]:+ """Collect unresolved tokens and portability-oriented source inventories."""+ placeholder_re = re.compile(r'\{\{[^{}]+\}\}')+ placeholders: list[dict[str, str]] = []+ font_stacks: set[str] = set()+ image_counts = {+ 'data_uri': 0,+ 'local': 0,+ 'external': 0,+ }+ external_images: list[dict[str, str]] = []+ for svg_path in svg_files:+ try:+ content = svg_path.read_text(encoding='utf-8')+ root = ET.fromstring(content)+ except (OSError, ET.ParseError):+ continue+ for token in sorted(set(placeholder_re.findall(content))):+ placeholders.append({'file': svg_path.name, 'token': token})+ for element in root.iter():+ font_family = element.get('font-family')+ if font_family:+ font_stacks.add(font_family.strip())+ style = element.get('style') or ''+ for declaration in style.split(';'):+ if ':' not in declaration:+ continue+ name, value = declaration.split(':', 1)+ if name.strip().lower() == 'font-family' and value.strip():+ font_stacks.add(value.strip())+ if element.tag.rsplit('}', 1)[-1] != 'image':+ continue+ href = (+ element.get('href')+ or element.get('{http://www.w3.org/1999/xlink}href')+ or ''+ ).strip()+ if href.startswith('data:'):+ image_counts['data_uri'] += 1+ elif re.match(r'^[a-z][a-z0-9+.-]*://', href, re.IGNORECASE):+ image_counts['external'] += 1+ external_images.append({+ 'file': svg_path.name,+ 'href': href,+ })+ elif href:+ image_counts['local'] += 1+ generic_only_font_stacks = sorted({+ stack+ for stack in font_stacks+ if _font_stack_is_generic_only(stack)+ })+ return {+ 'unresolved_template_tokens': placeholders,+ 'fonts': {+ 'stacks': sorted(font_stacks),+ 'generic_only_stacks': generic_only_font_stacks,+ },+ 'images': {+ **image_counts,+ 'external_references': external_images,+ },+ }+++def _svg_source_fingerprint(svg_files: list[Path]) -> dict[str, object]:+ """Return one deterministic digest for the exact SVG export inputs."""+ files: list[dict[str, object]] = []+ aggregate = hashlib.sha256()+ for path in sorted(svg_files, key=lambda item: item.name):+ file_sha256 = hashlib.sha256(path.read_bytes()).hexdigest()+ files.append({'file': path.name, 'sha256': file_sha256})+ aggregate.update(path.name.encode('utf-8'))+ aggregate.update(b'\0')+ aggregate.update(file_sha256.encode('ascii'))+ aggregate.update(b'\n')+ return {+ 'algorithm': 'sha256',+ 'digest': aggregate.hexdigest(),+ 'file_count': len(files),+ 'files': files,+ }+++def _quality_report_context(+ project_path: Path,+ source_fingerprint: dict[str, object],+) -> dict[str, object]:+ """Load the final SVG quality report when the preceding gate wrote one."""+ quality_path = project_path / 'exports' / 'svg_quality_report.json'+ try:+ quality = json.loads(quality_path.read_text(encoding='utf-8'))+ except FileNotFoundError:+ return {'status': 'not-provided', 'path': str(quality_path)}+ except (OSError, json.JSONDecodeError) as exc:+ return {+ 'status': 'unreadable',+ 'path': str(quality_path),+ 'error': str(exc),+ }+ schema = quality.get('schema')+ if schema != 'ppt-master.svg-quality-report.v1':+ return {+ 'status': 'unsupported-schema',+ 'path': str(quality_path),+ 'schema': schema,+ }+ categories = quality.get('categories')+ quality_fingerprint = quality.get('source_fingerprint')+ if not isinstance(quality_fingerprint, dict):+ source_match = 'unavailable'+ elif (+ quality_fingerprint.get('algorithm') == 'sha256'+ and quality_fingerprint.get('digest') == source_fingerprint.get('digest')+ and quality_fingerprint.get('file_count')+ == source_fingerprint.get('file_count')+ ):+ source_match = 'passed'+ else:+ source_match = 'mismatch'+ return {+ 'status': 'loaded',+ 'path': str(quality_path),+ 'schema': schema,+ 'stage': quality.get('stage'),+ 'source_match': source_match,+ 'source_fingerprint': quality_fingerprint,+ 'summary': quality.get('summary'),+ 'categories': categories if isinstance(categories, dict) else {},+ }+++def _write_postflight_report(+ *,+ output_path: Path,+ project_path: Path,+ svg_files: list[Path],+ layout_definition_files: list[Path],+ pptx_structure: str,+ backup_path: Path | None,+ conversion_trace_path: Path | None,+) -> Path:+ """Write the unified package/resource audit beside a successful PPTX."""+ try:+ package = _package_part_counts(output_path)+ except (OSError, zipfile.BadZipFile) as exc:+ raise PptxPostflightValidationError(+ f"generated PPTX is not a readable ZIP package: {exc}"+ ) from exc+ if package['zip_integrity'] != 'passed':+ raise PptxPostflightValidationError(+ f"PPTX ZIP integrity failed at {package['corrupt_member']}"+ )+ if package['slides'] != len(svg_files):+ raise PptxPostflightValidationError(+ "Published Slide count does not match authored SVG count: "+ f"{package['slides']} != {len(svg_files)}"+ )+ source_audit = _source_resource_audit(svg_files)+ source_fingerprint = _svg_source_fingerprint(svg_files)+ quality = _quality_report_context(project_path, source_fingerprint)+ quality_categories = quality.get('categories')+ blocking_count = None+ if isinstance(quality_categories, dict):+ blocking = quality_categories.get('blocking')+ if isinstance(blocking, dict):+ blocking_count = blocking.get('count')+ if quality.get('status') != 'loaded':+ quality_gate = str(quality.get('status') or 'not-provided')+ elif quality.get('stage') != 'final':+ quality_gate = 'non-final'+ elif not isinstance(blocking_count, int):+ quality_gate = 'unverified'+ elif blocking_count > 0:+ quality_gate = 'failed'+ elif quality.get('source_match') == 'mismatch':+ quality_gate = 'stale'+ elif quality.get('source_match') != 'passed':+ quality_gate = 'unverified'+ else:+ quality_gate = 'passed'+ unresolved_tokens = source_audit['unresolved_template_tokens']+ external_image_count = source_audit['images']['external']+ generic_only_font_stacks = source_audit['fonts']['generic_only_stacks']+ if quality_gate == 'failed':+ report_status = 'failed'+ elif (+ not unresolved_tokens+ and not external_image_count+ and not generic_only_font_stacks+ and quality_gate == 'passed'+ ):+ report_status = 'passed'+ else:+ report_status = 'passed-with-warnings'+ report_path = output_path.with_suffix('.report.json')+ report = {+ 'schema': 'ppt-master.pptx-postflight-report.v1',+ 'status': report_status,+ 'output': {+ 'path': str(output_path.resolve()),+ 'bytes': output_path.stat().st_size,+ },+ 'source': {+ 'svg_slide_count': len(svg_files),+ 'layout_definition_count': len(layout_definition_files),+ 'fingerprint': source_fingerprint,+ },+ 'package': package,+ 'checks': {+ 'zip_integrity': 'passed',+ 'slide_count': 'passed',+ 'internal_relationships': 'enforced-at-build',+ 'structured_package': (+ 'enforced-at-build'+ if pptx_structure == 'structured'+ else 'not-applicable'+ ),+ 'transitions': 'enforced-at-build',+ 'animations': 'enforced-at-build',+ 'quality_gate': quality_gate,+ 'template_tokens': (+ 'passed' if not unresolved_tokens else 'warning'+ ),+ 'external_images': (+ 'passed' if not external_image_count else 'warning'+ ),+ 'font_portability': (+ 'passed' if not generic_only_font_stacks else 'warning'+ ),+ },+ 'quality': quality,+ 'resources': source_audit,+ 'backup_path': str(backup_path.resolve()) if backup_path else None,+ 'conversion_trace_path': (+ str(conversion_trace_path.resolve())+ if conversion_trace_path and conversion_trace_path.is_file()+ else None+ ),+ }+ report_path.write_text(+ json.dumps(report, ensure_ascii=False, indent=2) + '\n',+ encoding='utf-8',+ )+ return report_pathdef _declared_pptx_structure_mode(project_path: Path) -> str | None:@@ -121,15 +422,17 @@ def _print_structure_contract_error(mode: str | None) -> None:label = repr(mode) if mode else 'missing (legacy implicit baseline)'print("Error: release SVG export requires an explicit spec_lock.md "- "pptx_structure.mode: flat (free design / brand-only) or structured "- "(deck/layout template); found " + label + ".",+ "pptx_structure.mode: flat (style reference / free design / brand-only) "+ "or structured (mirror/layout reuse); found " + label + ".",file=sys.stderr,)print(- " New free-design and brand-only projects use mode: flat. Create a "- "new template workspace through skills/ppt-master/workflows/"- "create-template.md, then generate new structured SVG pages before "- "export. Existing PPTX/SVG files are not upgraded in place.",+ " Style-reference, free-design, and brand-only projects must write a "+ "new mode: flat lock and regenerate project-canonical flat SVG pages. "+ "Mirror/layout reuse must first create a current template workspace "+ "through skills/ppt-master/workflows/create-template.md, then generate "+ "new structured SVG pages. Existing PPTX/SVG files are not upgraded "+ "in place.",file=sys.stderr,)@@ -356,9 +659,10 @@ Recorded narration:default=None,help=('PPTX structure strategy for native export. Omitting this flag reads '- 'spec_lock.md: flat is the free-design/brand-only release mode and '+ 'spec_lock.md: flat is the style-reference/free-design/brand-only '+ 'release mode and ''builds one clean project-owned Master plus Blank Layout while keeping '- 'all SVG objects slide-local; structured is the deck/layout-template '+ 'all SVG objects slide-local; structured is the mirror/layout reuse ''mode and requires complete explicit metadata. baseline, template, ''preserve, and generated are accepted only to report a migration error.'),@@ -954,15 +1258,16 @@ Recorded narration:print(f" Output file: {native_path}")print()+ conversion_trace_path = (+ native_path.with_name(native_path.name + '.trace.json')+ if args.conversion_trace else None+ )try:success = create_pptx_with_native_svg(output_path=native_path,use_native_shapes=True,svg_files=native_files,- conversion_trace_path=(- native_path.with_name(native_path.name + '.trace.json')- if args.conversion_trace else None- ),+ conversion_trace_path=conversion_trace_path,**shared_kwargs,)except (TemplateStructureError, ValueError) as exc:@@ -972,6 +1277,7 @@ Recorded narration:# Archive svg_output/ once per default-flow export. This preserves the# authored SVG sources under backup/<ts>/svg_output/ for inspection and# deterministic re-export.+ backup_path: Path | None = Noneif success and backup_dir is not None:svg_output_src = project_path / "svg_output"if svg_output_src.is_dir():@@ -983,6 +1289,7 @@ Recorded narration:if verbose:print(f" [warn] svg_output backup skipped: {exc}")else:+ backup_path = svg_output_dstif verbose:print(f" svg_output backup: {svg_output_dst}")payload_store_src = project_path / PAYLOAD_STORE_RELATIVE_PATH@@ -999,6 +1306,39 @@ Recorded narration:elif verbose:print(f" [info] svg_output/ not found, backup skipped")+ if success:+ try:+ report_path = _write_postflight_report(+ output_path=native_path,+ project_path=project_path,+ svg_files=native_files,+ layout_definition_files=layout_definition_files,+ pptx_structure=pptx_structure,+ backup_path=backup_path,+ conversion_trace_path=conversion_trace_path,+ )+ except PptxPostflightValidationError as exc:+ print(+ "Error: generated PPTX failed postflight validation and must "+ f"not be used: {exc}",+ file=sys.stderr,+ )+ print(+ f" Invalid output remains at: {native_path}",+ file=sys.stderr,+ )+ return 1+ except OSError as exc:+ print(+ "Error: PPTX generation succeeded, but its postflight report "+ f"could not be written: {exc}",+ file=sys.stderr,+ )+ print(f" PPTX output remains at: {native_path}", file=sys.stderr)+ return 1+ if verbose:+ print(f" Postflight report: {report_path}")+return 0 if success else 1diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.pyindex 390c0b01..9e66d044 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py@@ -120,6 +120,7 @@ _LOCK_ROW_RE = re.compile(r"^-\s+([^:]+?)\s*:\s*(.*?)\s*$")_LOCK_PAGE_RE = re.compile(r"^P(\d+)$")PPTX_STRUCTURE_MODES = frozenset({"structured", "preserve", "flat"})TEMPLATE_ADHERENCE_MODES = frozenset({"strict", "adaptive"})+TEMPLATE_REUSE_SCOPES = frozenset({"mirror", "layout", "style"})PLACEHOLDER_BINDING_MODES = frozenset({"carrier", "proxy"})_TEMPLATE_SKIN_ATTRS = frozenset({"color",@@ -209,6 +210,7 @@ class PptxStructureLock:"""Optional project-level PPTX structure export policy."""mode: str+ template_reuse_scope: str | None = Nonetemplate_adherence: str | None = Nonemasters: tuple[PptxMasterReference, ...] = ()layout_definitions: tuple[PptxLayoutDefinition, ...] = ()@@ -653,6 +655,41 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:"spec_lock.md template_adherence is allowed only in structured or ""preserve mode")++ reuse_scope_rows = [+ value.strip().lower()+ for key, value in structure_rows+ if key == "template_reuse_scope"+ ]+ if len(reuse_scope_rows) > 1:+ raise TemplateStructureError(+ "spec_lock.md pptx_structure allows at most one "+ "'- template_reuse_scope:' row"+ )+ template_reuse_scope = reuse_scope_rows[0] if reuse_scope_rows else None+ if (+ template_reuse_scope+ and template_reuse_scope not in TEMPLATE_REUSE_SCOPES+ ):+ allowed = ", ".join(sorted(TEMPLATE_REUSE_SCOPES))+ raise TemplateStructureError(+ "spec_lock.md pptx_structure.template_reuse_scope must be one of: "+ f"{allowed}"+ )+ if mode == "preserve" and template_reuse_scope:+ raise TemplateStructureError(+ "spec_lock.md preserve mode does not use template_reuse_scope; "+ "the source PPTX structure is already authoritative"+ )+ if mode == "flat" and template_reuse_scope not in {None, "style"}:+ raise TemplateStructureError(+ "spec_lock.md flat mode permits only template_reuse_scope: style"+ )+ if mode == "structured" and template_reuse_scope == "style":+ raise TemplateStructureError(+ "spec_lock.md template_reuse_scope: style requires mode: flat and "+ "must omit structured template mappings"+ )if any(key == "layout_strategy" for key, _value in structure_rows):raise TemplateStructureError("spec_lock.md pptx_structure.layout_strategy is obsolete; SVG pages "@@ -765,6 +802,39 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:raise TemplateStructureError("spec_lock.md page_layouts requires template_adherence: strict or adaptive")+ if template_reuse_scope in {"mirror", "layout"} and not prototypes:+ raise TemplateStructureError(+ "spec_lock.md template_reuse_scope mirror/layout requires one "+ "page_layouts row per page"+ )+ if template_reuse_scope == "style" and prototypes:+ raise TemplateStructureError(+ "spec_lock.md template_reuse_scope: style must omit page_layouts"+ )+ if template_reuse_scope == "mirror":+ non_mirror = sorted({+ reference.template_basename+ for reference in prototypes+ if reference.replication_mode != "mirror"+ })+ if non_mirror:+ raise TemplateStructureError(+ "spec_lock.md template_reuse_scope: mirror requires a mirror "+ "template workspace; non-mirror prototype(s): "+ + ", ".join(non_mirror)+ )+ if mode == "structured" and template_reuse_scope is None and prototypes:+ # Backward compatibility: projects created before the explicit reuse+ # axis inherit their former behavior. Mirror workspaces stay literal;+ # standard/fidelity workspaces remain structural layout references.+ template_reuse_scope = (+ "mirror"+ if all(+ reference.replication_mode == "mirror"+ for reference in prototypes+ )+ else "layout"+ )layout_definitions: list[PptxLayoutDefinition] = []references: list[PptxLayoutReference] = []@@ -922,6 +992,7 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:)return PptxStructureLock(mode=mode,+ template_reuse_scope=template_reuse_scope,template_adherence=template_adherence,masters=tuple(masters),layout_definitions=tuple(layout_definitions),@@ -2515,6 +2586,205 @@ def _layout_contract_difference(return "; ".join(details)+def _mirror_comparable_attributes(+ element: ET.Element,+ svg_path: Path,+ *,+ ignore_structure_attrs: bool,+) -> dict[str, str]:+ """Return literal mirror attributes using the validator's normalization."""+ return {+ name: _signature_attr_value(+ name,+ value,+ svg_path=svg_path,+ asset_identity=True,+ )+ for name, value in element.attrib.items()+ if not (+ ignore_structure_attrs+ and name.rsplit("}", 1)[-1] in _STRUCTURE_ATTRS+ )+ }+++def _mirror_node_label(element: ET.Element, index: int) -> str:+ """Return a compact stable-enough path segment for one SVG node."""+ tag = _local_tag(element)+ element_id = (element.get("id") or "").strip()+ return f"{tag}#{element_id}" if element_id else f"{tag}[{index}]"+++def _mirror_element_difference(+ expected: ET.Element,+ actual: ET.Element,+ *,+ expected_svg: Path,+ actual_svg: Path,+ path: str,+ ignore_structure_attrs: bool,+) -> str | None:+ """Describe the first literal mirror subtree difference."""+ expected_tag = _local_tag(expected)+ actual_tag = _local_tag(actual)+ if expected_tag != actual_tag:+ return f"{path}: expected <{expected_tag}>, found <{actual_tag}>"++ expected_attrs = _mirror_comparable_attributes(+ expected,+ expected_svg,+ ignore_structure_attrs=ignore_structure_attrs,+ )+ actual_attrs = _mirror_comparable_attributes(+ actual,+ actual_svg,+ ignore_structure_attrs=ignore_structure_attrs,+ )+ if expected_attrs != actual_attrs:+ for name in sorted(set(expected_attrs) | set(actual_attrs)):+ expected_value = expected_attrs.get(name)+ actual_value = actual_attrs.get(name)+ if expected_value != actual_value:+ return (+ f"{path}: attribute {name.rsplit('}', 1)[-1]!r} expected "+ f"{expected_value!r}, found {actual_value!r}"+ )++ expected_children = list(expected)+ actual_children = list(actual)+ if len(expected_children) != len(actual_children):+ expected_tspans = sum(+ _local_tag(child) == "tspan" for child in expected_children+ )+ actual_tspans = sum(+ _local_tag(child) == "tspan" for child in actual_children+ )+ if expected_tspans != actual_tspans:+ return (+ f"{path}: expected {expected_tspans} direct <tspan> child(ren), "+ f"found {actual_tspans}; mirror text node count/order must stay "+ "unchanged"+ )+ return (+ f"{path}: expected {len(expected_children)} child node(s), found "+ f"{len(actual_children)}"+ )++ for index, (expected_child, actual_child) in enumerate(+ zip(expected_children, actual_children),+ start=1,+ ):+ child_path = f"{path}/{_mirror_node_label(expected_child, index)}"+ difference = _mirror_element_difference(+ expected_child,+ actual_child,+ expected_svg=expected_svg,+ actual_svg=actual_svg,+ path=child_path,+ ignore_structure_attrs=ignore_structure_attrs,+ )+ if difference:+ return difference+ return None+++def _mirror_slide_local_difference(+ expected_spec: TemplateSlideSpec,+ actual_spec: TemplateSlideSpec,+ protected_ids: set[str],+) -> str | None:+ """Describe the first Slide-local mirror difference."""+ expected_root = _parse_svg_root(expected_spec.svg_path)+ actual_root = _parse_svg_root(actual_spec.svg_path)+ materialize_inline_geometry_properties(expected_root)+ materialize_inline_geometry_properties(actual_root)++ def selected(root: ET.Element) -> list[ET.Element]:+ output: list[ET.Element] = []+ for child in root:+ if _local_tag(child) in _NON_VISUAL_TAGS:+ continue+ element_id = (child.get("id") or "").strip()+ if element_id and element_id not in protected_ids:+ continue+ output.append(child)+ return output++ expected_children = selected(expected_root)+ actual_children = selected(actual_root)+ if len(expected_children) != len(actual_children):+ return (+ f"svg: expected {len(expected_children)} Slide-local top-level "+ f"element(s), found {len(actual_children)}"+ )+ for index, (expected, actual) in enumerate(+ zip(expected_children, actual_children),+ start=1,+ ):+ difference = _mirror_element_difference(+ expected,+ actual,+ expected_svg=expected_spec.svg_path,+ actual_svg=actual_spec.svg_path,+ path=f"svg/{_mirror_node_label(expected, index)}",+ ignore_structure_attrs=True,+ )+ if difference:+ return difference+ if _scope_visual_resources_signature(+ expected_root,+ tuple(expected_children),+ expected_spec.svg_path,+ ) != _scope_visual_resources_signature(+ actual_root,+ tuple(actual_children),+ actual_spec.svg_path,+ ):+ return "svg: referenced defs, CSS, root styling, or asset identity differs"+ return None+++def _mirror_structure_difference(+ expected_spec: TemplateSlideSpec,+ actual_spec: TemplateSlideSpec,+ elements: tuple[TemplateElementSpec, ...],+) -> str | None:+ """Describe the first mirror difference in named structural elements."""+ expected_root = _parse_svg_root(expected_spec.svg_path)+ actual_root = _parse_svg_root(actual_spec.svg_path)+ materialize_inline_geometry_properties(expected_root)+ materialize_inline_geometry_properties(actual_root)+ expected_by_id = {+ (child.get("id") or "").strip(): child+ for child in expected_root+ if (child.get("id") or "").strip()+ }+ actual_by_id = {+ (child.get("id") or "").strip(): child+ for child in actual_root+ if (child.get("id") or "").strip()+ }+ for item in elements:+ expected = expected_by_id.get(item.element_id)+ actual = actual_by_id.get(item.element_id)+ if expected is None or actual is None:+ return (+ f"svg/{item.element_id}: expected direct structural element is "+ "missing from one side"+ )+ difference = _mirror_element_difference(+ expected,+ actual,+ expected_svg=expected_spec.svg_path,+ actual_svg=actual_spec.svg_path,+ path=f"svg/{_mirror_node_label(expected, 1)}",+ ignore_structure_attrs=False,+ )+ if difference:+ return difference+ return None++def template_prototype_errors(specs: list[TemplateSlideSpec],structure_lock: PptxStructureLock,@@ -2559,7 +2829,11 @@ def template_prototype_errors(continuetry:- literal_visual = reference.replication_mode == "mirror"+ literal_visual = (+ structure_lock.template_reuse_scope == "mirror"+ if structure_lock.template_reuse_scope is not None+ else reference.replication_mode == "mirror"+ )expected_master_structure = _structure_subtree_signature(prototype.svg_path,prototype.master_elements,@@ -2584,11 +2858,24 @@ def template_prototype_errors()or actual_master_structure != expected_master_structure):+ master_difference = (+ _mirror_structure_difference(+ prototype,+ spec,+ prototype.master_elements,+ )+ if literal_visual+ else None+ )errors.append(f"{spec.svg_path.name}: template Master structure differs "f"from prototype {reference.svg_path.name}; strict and adaptive ""routes must retain its ids, topology, geometry, and content"+ (" including mirror visual styling" if literal_visual else "")+ + (+ f"; first difference: {master_difference}"+ if master_difference else ""+ ))if literal_visual:@@ -2609,11 +2896,17 @@ def template_prototype_errors(errors.append(str(exc))continueif actual_slide_visual != expected_slide_visual:+ difference = _mirror_slide_local_difference(+ prototype,+ spec,+ protected_slide_ids,+ )errors.append(f"{spec.svg_path.name}: mirror Slide-local non-text visuals "f"differ from prototype {reference.svg_path.name}; preserve ""grouping, geometry, paint, effects, and referenced asset ""identity, changing only visible text content"+ + (f"; first difference: {difference}" if difference else ""))try:@@ -2756,10 +3049,16 @@ def template_prototype_errors("contract; assign a new key and name")if literal_visual and not placeholder_visual_same:+ difference = _mirror_structure_difference(+ prototype,+ spec,+ prototype.placeholders,+ )errors.append(f"{spec.svg_path.name}: mirror placeholder geometry or visual "f"styling differs from prototype {reference.svg_path.name}; ""only visible text content may change under the reused Layout"+ + (f"; first difference: {difference}" if difference else ""))if not layout_contract_same:qualifier = "mirror visual/structural" if literal_visual else "structural"@@ -2767,6 +3066,14 @@ def template_prototype_errors(spec.layout_elements,prototype.layout_elements,)+ if literal_visual:+ literal_difference = _mirror_structure_difference(+ prototype,+ spec,+ prototype.layout_elements,+ )+ if literal_difference:+ difference += f"; first difference: {literal_difference}"if adherence == "strict":errors.append(f"{spec.svg_path.name}: strict Layout {qualifier} contract "