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
fix(roundtrip): close adversarial-review defects and skip conversion of unchanged source refs
hugohe39a02227c1bee
diff --git a/skills/ppt-master/scripts/authoring_roundtrip.py b/skills/ppt-master/scripts/authoring_roundtrip.pyindex 632897b5..2b37c049 100644--- a/skills/ppt-master/scripts/authoring_roundtrip.py+++ b/skills/ppt-master/scripts/authoring_roundtrip.py@@ -44,6 +44,7 @@ from svg_authoring_view import (AUTHORING_OMITTED_SOURCE_ATTRIBUTES,AUTHORING_MANIFEST_NAME,AUTHORING_SCHEMA,+ EXTERNAL_LINKED_IMAGE_PROXY_ATTRIBUTE,SOURCE_REF_ATTRIBUTE,SOURCE_PROXY_ATTRIBUTE,SOURCE_PROXY_KIND,@@ -51,6 +52,7 @@ from svg_authoring_view import (semantic_subtree_sha256,)from svg_compatibility import normalize_single_child_group_filters+from svg_to_pptx.drawingml.utils import INHERITABLE_ATTRSSVG_NS = "http://www.w3.org/2000/svg"@@ -64,6 +66,14 @@ _PRESERVED_EFFECT_ATTRIBUTES = frozenset({"data-pptx-effect-reason","data-pptx-effect-status",})+_ROOT_AUTHORING_ATTRIBUTES = (+ "width",+ "height",+ "viewBox",+ "style",+ *INHERITABLE_ATTRS,+ "opacity",+)ET.register_namespace("", SVG_NS)ET.register_namespace("xlink", XLINK_NS)@@ -175,9 +185,15 @@ def _load_json(path: Path, *, context: str) -> dict[str, Any]:def _resolve_inside(root: Path, value: str, *, context: str) -> Path:- path = (root / value).resolve()try:- path.relative_to(root.resolve())+ resolved_root = root.resolve()+ path = (root / value).resolve()+ except ValueError as exc:+ raise AuthoringRoundtripError(+ f"{context} contains an invalid path value: {value!r}"+ ) from exc+ try:+ path.relative_to(resolved_root)except ValueError as exc:raise AuthoringRoundtripError(f"{context} resolves outside {root}: {value!r}"@@ -648,6 +664,10 @@ def _load_page_plan(raise AuthoringRoundtripError(f"{context}.svg must be a non-empty authoring SVG filename")+ if "\\" in svg_value:+ raise AuthoringRoundtripError(+ f"{context}.svg must not contain backslashes: {svg_value!r}"+ )svg_path_value = Path(svg_value)if (svg_path_value.name != svg_value@@ -1203,6 +1223,67 @@ def _referenced_definition_ids(element: ET.Element) -> set[str]:return references+def _definition_reference_ids(element: ET.Element) -> set[str]:+ """Return local definition ids referenced by attributes or style text."""+ references = _referenced_definition_ids(element)+ for item in element.iter():+ if item.text:+ references.update(+ match.group(2) for match in _URL_ID_RE.finditer(item.text)+ )+ return references+++def _prune_unreferenced_definitions(root: ET.Element) -> None:+ """Keep only the definition closure reachable by converted page content."""+ definitions = _direct_defs(root)+ if definitions is None:+ return+ owner_by_id: dict[str, ET.Element] = {}+ for child in definitions:+ for item in child.iter():+ if definition_id := item.get("id"):+ owner_by_id.setdefault(definition_id, child)++ always_kept = [+ child+ for child in definitions+ if _local_name(child.tag) == "style" or not child.get("id")+ ]+ pending = [+ reference+ for child in root+ if child is not definitions+ for reference in _definition_reference_ids(child)+ ]+ pending.extend(+ reference+ for child in always_kept+ for reference in _definition_reference_ids(child)+ )+ selected_owners: set[int] = set()+ required_ids: set[str] = set()+ while pending:+ definition_id = pending.pop()+ if definition_id in required_ids:+ continue+ required_ids.add(definition_id)+ owner = owner_by_id.get(definition_id)+ if owner is None or id(owner) in selected_owners:+ continue+ selected_owners.add(id(owner))+ pending.extend(_definition_reference_ids(owner) - required_ids)++ for child in list(definitions):+ if child in always_kept or id(child) in selected_owners:+ continue+ definitions.remove(child)+ if not list(definitions) and not (+ definitions.text and definitions.text.strip()+ ):+ root.remove(definitions)++def _merge_defs(layered_root: ET.Element,authoring_root: ET.Element,@@ -1328,6 +1409,64 @@ def _restore_preserved_effect_metadata(item.set(name, value)+def _apply_authoring_root_attributes(+ target: ET.Element,+ authoring_root: ET.Element,+) -> None:+ """Make authoring-root geometry and inherited presentation authoritative."""+ for name in _ROOT_AUTHORING_ATTRIBUTES:+ target.attrib.pop(name, None)+ value = authoring_root.get(name)+ if value is not None:+ target.set(name, value)+++def _native_restore_placeholder(+ source: ET.Element,+ source_ref: str,+) -> ET.Element:+ """Keep one natively restored source shape ordered without converting it."""+ shape_key = source_ref.split(":", 1)[1]+ placeholder = ET.Element(+ f"{{{SVG_NS}}}g",+ {+ "id": f"shape-{shape_key}",+ "data-pptx-object": "group",+ },+ )+ if shape_key.isdigit():+ placeholder.set("data-pptx-shape-id", shape_key)+ placeholder.set("data-pptx-shape-scope", "slide")+ for name in (+ "data-pptx-layer",+ "data-pptx-role",+ "data-pptx-placeholder",+ ):+ value = source.get(name)+ if value is not None:+ placeholder.set(name, value)+ transform = source.get("transform")+ if transform:+ placeholder.set("transform", transform)+ frame = (source.get("data-pptx-frame") or "").split()+ try:+ x, y, width, height = (float(value) for value in frame)+ except (TypeError, ValueError):+ x, y, width, height = 0.0, 0.0, 1.0, 1.0+ ET.SubElement(+ placeholder,+ f"{{{SVG_NS}}}rect",+ {+ "x": f"{x:.15g}",+ "y": f"{y:.15g}",+ "width": f"{max(width, 0.001):.15g}",+ "height": f"{max(height, 0.001):.15g}",+ "fill": "#000000",+ },+ )+ return placeholder++def _materialize_document(project_path: Path,document: AuthoringDocument,@@ -1447,6 +1586,20 @@ def _materialize_document("object; only a complete Slide-local proxy may be removed to ""delete that object")+ deleted_external_linked_image_refs = sorted(+ source_ref+ for source_ref in deleted_refs & manifest_proxy_refs+ if baseline_occurrences[source_ref][0].element.get(+ EXTERNAL_LINKED_IMAGE_PROXY_ATTRIBUTE+ ) == "true"+ )+ if deleted_external_linked_image_refs:+ raise AuthoringRoundtripError(+ f"{document.name} deletes externally linked image proxy object(s): "+ + ", ".join(deleted_external_linked_image_refs)+ + "; keep each proxy unchanged to restore its original external "+ "picture relationship"+ )deleted_inherited_proxy_refs = sorted(source_reffor source_ref in deleted_refs & manifest_proxy_refs@@ -1475,15 +1628,7 @@ def _materialize_document(raise AuthoringRoundtripError(f"{document.name} cannot find {source_ref!r} in layered source")- restored = copy.deepcopy(source)- _rebase_resource_references(- restored,- document.layered_source_path.parent,- output_path.parent,- project_path,- recursive=True,- )- return [restored]+ return [_native_restore_placeholder(source, source_ref)]if _local_name(element.tag) == "use":icon = (element.get("data-icon") or "").strip()@@ -1541,10 +1686,7 @@ def _materialize_document(output_root = copy.deepcopy(layered_root)for child in list(output_root):output_root.remove(child)- for name in ("width", "height", "viewBox"):- value = current_root.get(name)- if value is not None:- output_root.set(name, value)+ _apply_authoring_root_attributes(output_root, current_root)layered_defs_root = copy.deepcopy(layered_root)current_defs_root = copy.deepcopy(current_root)_rebase_resource_references(@@ -1633,6 +1775,7 @@ def _materialize_document(for replacement in replacements:output_root.append(replacement)+ _prune_unreferenced_definitions(output_root)residual_refs = sorted({source_reffor element in output_root.iter()diff --git a/skills/ppt-master/scripts/docs/confirm_ui.md b/skills/ppt-master/scripts/docs/confirm_ui.mdindex 25f9474b..84d650ea 100644--- a/skills/ppt-master/scripts/docs/confirm_ui.md+++ b/skills/ppt-master/scripts/docs/confirm_ui.md@@ -538,7 +538,7 @@ Template-mode-only Stage-2 fragment:- **Generated-image direction** appears only for current `image_usage: ai`, but all three custom project candidates already exist in `design_directions` before that toggle. Turning AI on reveals those candidates immediately without a backend rerun, followed by the 20 fixed system styles. Selecting a project candidate expands its behavior editor in that card; a fixed preset submits its id, while a project candidate submits `rendering: "custom"` + edited non-empty `behavior`. Turning AI off omits `image_strategy` from the final result without deleting the authored recommendation candidates. Catalog-based custom behavior names exact ids for optional `image_rendering_references`; a novel behavior has none. The left preview follows selection. No image palette is written; deck colors remain authoritative, and legacy `image_strategy.palette` is ignored. Illustrated icons and decorative lettering are downstream AI carrier decisions; neither adds a Confirm UI field or `result.json` key.- **`design_directions`** is the canonical Stage-2 starting set: exactly three top-down, project-fit bundles with stable ids, localized copy, custom mode/style/rendering, icons, complete language-aware typography, and HEX `background`, `secondary_bg`, `primary`, `accent`, `secondary_accent`, `body_text`. The `selected` card carries the persistent Recommended marker and is applied first. A custom direction card uses its localized style-summary note—or the required behavior fallback—instead of requesting a preset-style preview. Newly authored notes may borrow localized catalog display labels where useful or use concise natural language freely; they never force an approximate label or expose internal catalog ids. Clicking an inactive card applies every field it owns; projected custom fields can then be edited in place and all lower controls may diverge. The active card shows an adjusted state and exposes an explicit restore action for its immutable authored bundle. `result.json` stores the edited current components, never a direction id.- `recommend.generation_mode` and `refine_spec` mirror [`generate-pptx`](../../workflows/generate-pptx.md) Step 4. `split` / `true` are explicit opt-ins. Refinement adds no UI stage: after Gate 1 it stops before the lock for unrestricted chat revision until approval.-- `content_divergence` is a **free-text** Stage-1 source-treatment field. Blank means a balanced default; facts stay sourced at every level. Strategist consumes it while authoring §IX and records it in `design_spec.md §I`; it is not written to `spec_lock.md`. Beautify sends `{ "value": "keep source wording and page structure verbatim", "locked": true }`, so the UI displays it read-only and the server restores it on every staged submit. Template-fill does not use this confirmation flow and does not surface it.+- `content_divergence` is a **free-text** Stage-1 source-treatment field. Blank means a balanced default; facts stay sourced at every level. Strategist consumes it while authoring §IX and records it in `design_spec.md §I`; it is not written to `spec_lock.md`. Beautify sends `{ "value": "keep source wording and page structure verbatim", "locked": true }`, so the UI displays it read-only and the server restores it on every staged submit. Edit Native PPTX uses its source-backed round-trip plan instead of this confirmation flow and does not surface the field.- `lang` is the soft UI-language default (`zh` / `zh-TW` / `en` / `ja`); the persisted user choice wins. It never sets `primary_language`.### Output — `result.json` (written on submit, read by the AI)diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex c8833a43..3324d94f 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -62,8 +62,8 @@ staging transaction, before the editable bundle first appears:The live editor expands `data-icon` references for complete-page preview. Readan imported vector asset only when editing that decoration. An unchanged asset-restores its native source objects; editing the asset rebuilds only its owning-slide as one vector edit unit. A source proxy remains atomic: leave it unchanged+restores its native source objects; editing the asset rebuilds every slide whose+placeholder references that vector edit unit. A source proxy remains atomic: leave it unchangedto restore the original native PowerPoint object. A complete Slide-local proxymay be removed to delete that object; an inherited Master/Layout proxy mustremain because one flat page cannot delete shared structure. Editing the proxy@@ -90,9 +90,11 @@ invalid. `svg_to_pptx.py --roundtrip` always reads `authoring-svg-flat/`,restores unchanged source refs from `analysis/roundtrip-svg/`, expands importedvector edit units from `icons/imported/`, and retains edits/deletions/newcontent without rewriting the bundle. Unchanged slides and resources pass-through byte-for-byte; an edit rebuilds only its owner. Resource hrefs resolve-exactly relative to the page or extracted asset and must remain inside the-workspace.+through byte-for-byte. A page edit rebuilds that output page; a changed+materialized or derived resource rebuilds every output page that references it.+Changed materialized bytes must still match the source package part's extension+and Content-Type. Resource hrefs resolve exactly relative to the page or+extracted asset and must remain inside the workspace.### Round-trip deck page plans@@ -182,9 +184,9 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py /path/to/workspace \Successful round-trip export prints one deck receipt:`Round-trip export summary: output_pages=N passthrough=P-cloned_passthrough=C patched=M rebuilt=R`. `patched` keeps the source visible-Slide XML and applies only notes or motion overlays; `rebuilt` means the page's-visible authoring changed.+cloned_passthrough=C patched=M rebuilt=R`. `patched` keeps source shape XML+while order, notes, or motion may change; `rebuilt` means visible authoring or+one of its referenced resources changed.Without `-o`, round-trip export names the deck `<workspace-directory-name>_<timestamp>[<flavor-suffix>].pptx` under `exports/`.Before export, run `python3 scripts/svg_quality_checker.py <workspace> --roundtrip`@@ -861,7 +863,7 @@ Behavior:- `--no-merge`: each dy-stacked line becomes an independent frame with its own placement.- Detection is conservative: mixed-layout `<text>` falls back to per-line frames. Use `--reflow-text` only for resizable body copy and `--no-merge` only for independent line objects or absolute line positions.- Native release export reads `svg_output/`; `-s <directory>` selects another project-relative SVG source. `-s final` remains an explicit diagnostic comparison against post-processed SVGs and does not change artifact ownership. `--enable-dangerous-nonconforming-svg-export` is a separate, explicitly requested flat compatibility path for either the default or selected source; it forces flat structure, restores no imported source object, and cannot combine with `--roundtrip` or `--quick-generate`.-- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, and rebuilds only edited owners. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement. Optional root `page_plan.json` uses the versioned deck-plan contract above; the no-plan path remains the identity export. Explicit `-t <effect>` without `--transition-duration` on a source without transitions uses the default duration.+- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, rebuilds a page whose authoring changed, and rebuilds every output page that references a changed resource. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement. Optional root `page_plan.json` uses the versioned deck-plan contract above; the no-plan path remains the identity export. Explicit `-t <effect>` without `--transition-duration` on a source without transitions uses the default duration.- `svg_final/` may be opened directly or inserted into PowerPoint as an SVG picture. PowerPoint's manual Convert-to-Shape operation is outside the compatibility contract.- On every SVG-authoring route, each file in `svg_output/` is the complete visiblepage-design source. Templates and locks may guide authoring, but finalize/exportdiff --git a/skills/ppt-master/scripts/pptx_ooxml/ooxml.py b/skills/ppt-master/scripts/pptx_ooxml/ooxml.pyindex b37c11eb..f26d2df9 100644--- a/skills/ppt-master/scripts/pptx_ooxml/ooxml.py+++ b/skills/ppt-master/scripts/pptx_ooxml/ooxml.py@@ -108,10 +108,18 @@ def _emu_to_px(value: str | None) -> int | None:def _parse_relationships(zf: zipfile.ZipFile) -> dict[str, dict[str, str]]:- rels_root = _read_xml(zf, "ppt/_rels/presentation.xml.rels")+ rels_name = "ppt/_rels/presentation.xml.rels"+ rels_root = _read_xml(zf, rels_name)relationships: dict[str, dict[str, str]] = {}+ seen_ids: set[str] = set()for rel in rels_root.findall(_qn(REL_NS, "Relationship")):rel_id = rel.attrib.get("Id")+ if rel_id:+ if rel_id in seen_ids:+ raise RuntimeError(+ f"Duplicate relationship Id {rel_id!r} in {rels_name}"+ )+ seen_ids.add(rel_id)target = rel.attrib.get("Target")rel_type = rel.attrib.get("Type")if rel_id and target and rel_type:diff --git a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.pyindex 78eecc4b..0cebcf0a 100644--- a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py@@ -74,12 +74,17 @@ class PictureResult:# the SVG. Filename is the basename inside the package's media dir.media: dict[str, bytes] = field(default_factory=dict)diagnostics: tuple[PictureDiagnostic, ...] = ()+ external_linked: bool = Falseclass MediaResolutionError(RuntimeError):"""Raised when a PPTX media relationship cannot be reproduced as SVG."""+class LinkedImageResolutionError(MediaResolutionError):+ """Raised when an external linked image has no embedded preview."""++def convert_blip_fill(blip_fill_elem: ET.Element,xfrm: Xfrm,@@ -103,10 +108,16 @@ def convert_blip_fill(relationship_ids = blip_embed_relationship_ids(blip)linked_rid = blip.attrib.get(f"{{{NS['r']}}}link")+ linked_relationship = slide_part.rels.get(linked_rid or "", {})+ external_linked = linked_relationship.get("external") == "1"if not relationship_ids:+ if external_linked:+ raise LinkedImageResolutionError(+ "Linked image relationships are not supported; embed the image in PowerPoint first"+ )if linked_rid:raise MediaResolutionError(- "Linked image relationships are not supported; embed the image in PowerPoint first"+ "Linked image relationship cannot be resolved; embed the image in PowerPoint first")return PictureResult()@@ -130,7 +141,12 @@ def convert_blip_fill(breakif target is None or img_bytes is None:details = "; ".join(failures)- raise MediaResolutionError(+ error_type = (+ LinkedImageResolutionError+ if external_linked+ else MediaResolutionError+ )+ raise error_type(f"No embedded image relationship can be read in {slide_part.path}: {details}")@@ -196,6 +212,7 @@ def convert_blip_fill(svg=svg,media=media,diagnostics=tuple(diagnostics),+ external_linked=external_linked,)diff --git a/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.pyindex 20b411a8..2f76f668 100644--- a/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py+++ b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py@@ -251,6 +251,7 @@ def _walk_container(container: ET.Element,parent_group_xfrm: Xfrm | None,ancestor_rotation: float = 0.0,+ source_order_path: tuple[int, ...] = (),placeholder_xfrms: dict[tuple[str | None, str | None], Xfrm] | None = None,placeholder_lst_styles: dict[tuple[str | None, str | None],@@ -264,6 +265,7 @@ def _walk_container("""Walk a p:spTree or p:grpSp subtree. Children kept in document (z) order."""nodes: list[ShapeNode] = []+ source_order = 0for child in list(container):if not isinstance(child.tag, str):continue@@ -277,6 +279,8 @@ def _walk_container(kind_info = _KIND_MAP.get(local)if kind_info is None:continue+ source_order += 1+ child_order_path = (*source_order_path, source_order)kind, nv_tag = kind_info(@@ -287,6 +291,10 @@ def _walk_container(hyperlink_rid,hyperlink_action,) = _read_nv_sp_pr(child, nv_tag)+ if not spid:+ spid = "missing-" + "-".join(+ str(value) for value in child_order_path+ )xfrm = parse_xfrm(_resolve_xfrm(child, kind))effective_rotation = (ancestor_rotation + xfrm.rot) % 360.0@@ -336,6 +344,7 @@ def _walk_container(if kind == GROUP:node.children = _walk_container(child, xfrm, effective_rotation,+ source_order_path=child_order_path,placeholder_xfrms=placeholder_xfrms,placeholder_lst_styles=placeholder_lst_styles,placeholder_body_properties=placeholder_body_properties,diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.pyindex 92c2ff99..6ac3e3bf 100644--- a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py@@ -85,6 +85,7 @@ from .ooxml_loader import (inherited_shape_visibility,)from .pic_to_svg import (+ LinkedImageResolutionError,MediaResolutionError,PictureResult,convert_blip_fill,@@ -110,6 +111,12 @@ from .txbody_to_svg import (# AssemblyContext# ---------------------------------------------------------------------------+_SOURCE_PROXY_ATTRIBUTE = "data-pptx-source-proxy"+_SOURCE_PROXY_KIND = "native-restore"+_EXTERNAL_LINKED_IMAGE_PROXY_ATTRIBUTE = (+ "data-pptx-external-linked-image-proxy"+)+@dataclassclass AssemblyContext:"""Per-slide accumulator for unique IDs + media + defs."""@@ -483,6 +490,7 @@ def _fallback_node_svg(ctx: AssemblyContext,*,top_level: bool,+ source_proxy: bool = False,) -> str:"""Keep one unsupported source object visible without aborting its deck."""if node.xfrm.w <= 0 or node.xfrm.h <= 0:@@ -500,7 +508,21 @@ def _fallback_node_svg(f'y="{fmt_num(node.xfrm.y + min(18, node.xfrm.h / 2))}" 'f'font-size="12" fill="#991B1B">{label}</text>')- return _wrap_shape_group(inner, node, ctx, top_level=top_level)+ extra_attrs = (+ [+ f'{_SOURCE_PROXY_ATTRIBUTE}="{_SOURCE_PROXY_KIND}"',+ f'{_EXTERNAL_LINKED_IMAGE_PROXY_ATTRIBUTE}="true"',+ ]+ if source_proxy+ else None+ )+ return _wrap_shape_group(+ inner,+ node,+ ctx,+ top_level=top_level,+ extra_attrs=extra_attrs,+ )# ---------------------------------------------------------------------------@@ -525,6 +547,20 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->asset_name_map=ctx.asset_name_map,strict=ctx.strict,)+ except LinkedImageResolutionError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "linked-image-proxy",+ str(exc),+ "retain the complete source object as a non-editable proxy",+ )+ return _fallback_node_svg(+ node,+ ctx,+ top_level=top_level,+ source_proxy=True,+ )except (ValueError, MediaResolutionError) as exc:if ctx.strict:raise@@ -534,6 +570,18 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->"omit the image fill and retain shape geometry/text",)else:+ if blip_result.external_linked:+ ctx.diagnose(+ "linked-image-proxy",+ "Externally linked image fills are source-backed",+ "retain the complete source object as a non-editable proxy",+ )+ return _fallback_node_svg(+ node,+ ctx,+ top_level=top_level,+ source_proxy=True,+ )_diagnose_picture_result(ctx, blip_result)if blip_result.svg:blip_image = _clip_blip_image(blip_result.svg, geom, ctx)@@ -1555,6 +1603,20 @@ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool)asset_name_map=ctx.asset_name_map,strict=ctx.strict,)+ except LinkedImageResolutionError as exc:+ if ctx.strict:+ raise+ ctx.diagnose(+ "linked-image-proxy",+ str(exc),+ "retain the complete source picture as a non-editable proxy",+ )+ return _fallback_node_svg(+ node,+ ctx,+ top_level=top_level,+ source_proxy=True,+ )except MediaResolutionError as exc:if ctx.strict:raise@@ -1581,6 +1643,13 @@ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool)clipped_svg = _clip_blip_image(result.svg, geom, ctx)picture_attrs = {**_object_metadata(node, ctx), **effect_metadata}group_attrs = _metadata_group_attrs(effect_metadata)+ if result.external_linked:+ group_attrs.append(+ f'{_SOURCE_PROXY_ATTRIBUTE}="{_SOURCE_PROXY_KIND}"'+ )+ group_attrs.append(+ f'{_EXTERNAL_LINKED_IMAGE_PROXY_ATTRIBUTE}="true"'+ )if effect.filter_id is not None:filter_attr = f"url(#{effect.filter_id})"if (diff --git a/skills/ppt-master/scripts/pptx_workspace.py b/skills/ppt-master/scripts/pptx_workspace.pyindex 8ef3f672..11dc4572 100644--- a/skills/ppt-master/scripts/pptx_workspace.py+++ b/skills/ppt-master/scripts/pptx_workspace.py@@ -19,6 +19,7 @@ Dependencies:from __future__ import annotationsimport hashlib+import ioimport jsonimport posixpathimport re@@ -95,6 +96,127 @@ _TRANSITION_TAG = ("{http://schemas.openxmlformats.org/presentationml/2006/main}transition")_REL_ATTR_PREFIX = f"{{{_DOC_REL_NS}}}"+_CONTENT_TYPES_NS = (+ "http://schemas.openxmlformats.org/package/2006/content-types"+)+_FORMAT_BY_EXTENSION = {+ ".3mf": frozenset({"3mf"}),+ ".aac": frozenset({"aac"}),+ ".aif": frozenset({"aiff"}),+ ".aiff": frozenset({"aiff"}),+ ".avif": frozenset({"avif"}),+ ".avi": frozenset({"avi"}),+ ".bmp": frozenset({"bmp"}),+ ".doc": frozenset({"ole"}),+ ".docm": frozenset({"ooxml-docx"}),+ ".docx": frozenset({"ooxml-docx"}),+ ".dotm": frozenset({"ooxml-docx"}),+ ".dotx": frozenset({"ooxml-docx"}),+ ".emf": frozenset({"emf"}),+ ".eps": frozenset({"postscript"}),+ ".flac": frozenset({"flac"}),+ ".gif": frozenset({"gif"}),+ ".glb": frozenset({"glb"}),+ ".jpeg": frozenset({"jpeg"}),+ ".jpg": frozenset({"jpeg"}),+ ".ico": frozenset({"ico"}),+ ".m4a": frozenset({"iso-bmff"}),+ ".m4v": frozenset({"iso-bmff"}),+ ".mkv": frozenset({"ebml"}),+ ".mov": frozenset({"iso-bmff"}),+ ".mp3": frozenset({"mp3"}),+ ".mp4": frozenset({"iso-bmff"}),+ ".mpeg": frozenset({"mpeg"}),+ ".mpg": frozenset({"mpeg"}),+ ".oga": frozenset({"ogg"}),+ ".ogg": frozenset({"ogg"}),+ ".png": frozenset({"png"}),+ ".pdf": frozenset({"pdf"}),+ ".potm": frozenset({"ooxml-pptx"}),+ ".potx": frozenset({"ooxml-pptx"}),+ ".ppt": frozenset({"ole"}),+ ".pptm": frozenset({"ooxml-pptx"}),+ ".pptx": frozenset({"ooxml-pptx"}),+ ".svg": frozenset({"svg"}),+ ".tif": frozenset({"tiff"}),+ ".tiff": frozenset({"tiff"}),+ ".wav": frozenset({"wav"}),+ ".wdp": frozenset({"wdp"}),+ ".webm": frozenset({"ebml"}),+ ".webp": frozenset({"webp"}),+ ".wma": frozenset({"asf"}),+ ".wmf": frozenset({"wmf"}),+ ".wmv": frozenset({"asf"}),+ ".xls": frozenset({"ole"}),+ ".xlsb": frozenset({"ooxml-xlsx"}),+ ".xlsm": frozenset({"ooxml-xlsx"}),+ ".xlsx": frozenset({"ooxml-xlsx"}),+ ".xltm": frozenset({"ooxml-xlsx"}),+ ".xltx": frozenset({"ooxml-xlsx"}),+}+_FORMAT_MEDIA_KIND = {+ "aac": "audio",+ "aiff": "audio",+ "asf": "media",+ "avi": "video",+ "avif": "image",+ "bmp": "image",+ "ebml": "video",+ "emf": "image",+ "flac": "audio",+ "gif": "image",+ "ico": "image",+ "iso-bmff": "media",+ "jpeg": "image",+ "mp3": "audio",+ "mpeg": "video",+ "ogg": "media",+ "png": "image",+ "postscript": "image",+ "svg": "image",+ "tiff": "image",+ "wav": "audio",+ "wdp": "image",+ "webp": "image",+ "wmf": "image",+}+_FORMAT_BY_CONTENT_TYPE = {+ "application/pdf": frozenset({"pdf"}),+ "application/postscript": frozenset({"postscript"}),+ "application/vnd.ms-3mfdocument": frozenset({"3mf"}),+ "audio/aac": frozenset({"aac"}),+ "audio/aiff": frozenset({"aiff"}),+ "audio/flac": frozenset({"flac"}),+ "audio/mpeg": frozenset({"mp3"}),+ "audio/mp4": frozenset({"iso-bmff"}),+ "audio/ogg": frozenset({"ogg"}),+ "audio/wav": frozenset({"wav"}),+ "audio/x-aiff": frozenset({"aiff"}),+ "audio/x-ms-wma": frozenset({"asf"}),+ "audio/x-wav": frozenset({"wav"}),+ "image/avif": frozenset({"avif"}),+ "image/bmp": frozenset({"bmp"}),+ "image/gif": frozenset({"gif"}),+ "image/jpeg": frozenset({"jpeg"}),+ "image/png": frozenset({"png"}),+ "image/svg+xml": frozenset({"svg"}),+ "image/tiff": frozenset({"tiff"}),+ "image/vnd.ms-photo": frozenset({"wdp"}),+ "image/vnd.microsoft.icon": frozenset({"ico"}),+ "image/webp": frozenset({"webp"}),+ "image/x-eps": frozenset({"postscript"}),+ "image/x-emf": frozenset({"emf"}),+ "image/x-icon": frozenset({"ico"}),+ "image/x-wmf": frozenset({"wmf"}),+ "model/gltf-binary": frozenset({"glb"}),+ "video/mp4": frozenset({"iso-bmff"}),+ "video/mpeg": frozenset({"mpeg"}),+ "video/quicktime": frozenset({"iso-bmff"}),+ "video/webm": frozenset({"ebml"}),+ "video/x-matroska": frozenset({"ebml"}),+ "video/x-ms-wmv": frozenset({"asf"}),+ "video/x-msvideo": frozenset({"avi"}),+}def source_pptx_path(workspace: Path) -> Path:@@ -148,6 +270,201 @@ def _sha256(payload: bytes) -> str:return hashlib.sha256(payload).hexdigest()+def _sniff_zip_format(payload: bytes) -> str | None:+ """Return the semantic package family for one ZIP payload."""+ try:+ with zipfile.ZipFile(io.BytesIO(payload)) as package:+ names = set(package.namelist())+ except (OSError, zipfile.BadZipFile):+ return None+ if "xl/workbook.xml" in names or "xl/workbook.bin" in names:+ return "ooxml-xlsx"+ if "word/document.xml" in names:+ return "ooxml-docx"+ if "ppt/presentation.xml" in names:+ return "ooxml-pptx"+ if any(name.lower().endswith(".model") for name in names):+ return "3mf"+ return "zip"+++def _sniff_resource_format(payload: bytes) -> str | None:+ """Identify common PPTX resource formats from their bytes."""+ header = payload[:64]+ if header.startswith(b"\x89PNG\r\n\x1a\n"):+ return "png"+ if header.startswith(b"\xff\xd8\xff"):+ return "jpeg"+ if header.startswith((b"GIF87a", b"GIF89a")):+ return "gif"+ if header.startswith(b"BM"):+ return "bmp"+ if header.startswith((b"II*\x00", b"MM\x00*", b"II+\x00", b"MM\x00+")):+ return "tiff"+ if header.startswith((b"II\xbc\x01", b"MM\x01\xbc")):+ return "wdp"+ if len(header) >= 44 and header[40:44] == b" EMF":+ return "emf"+ if header.startswith(b"\xd7\xcd\xc6\x9a"):+ return "wmf"+ if (+ len(header) >= 6+ and header[:2] in {b"\x01\x00", b"\x02\x00"}+ and header[2:4] == b"\x09\x00"+ ):+ return "wmf"+ if header.startswith(b"\x00\x00\x01\x00"):+ return "ico"+ if header.startswith(b"%PDF-"):+ return "pdf"+ if header.startswith(b"%!PS-Adobe-"):+ return "postscript"+ if len(header) >= 12 and header[:4] in {b"RIFF", b"RF64"}:+ form = header[8:12]+ if form == b"WAVE":+ return "wav"+ if form == b"AVI ":+ return "avi"+ if form == b"WEBP":+ return "webp"+ if header.startswith(b"FORM") and header[8:12] in {b"AIFF", b"AIFC"}:+ return "aiff"+ if header.startswith(b"fLaC"):+ return "flac"+ if header.startswith(b"OggS"):+ return "ogg"+ if header.startswith(b"ID3") or (+ len(header) >= 2+ and header[0] == 0xFF+ and header[1] & 0xE0 == 0xE0+ and header[1] & 0x06 != 0+ ):+ return "mp3"+ if (+ len(header) >= 2+ and header[0] == 0xFF+ and header[1] & 0xF6 == 0xF0+ ):+ return "aac"+ if header.startswith(b"\x30\x26\xb2\x75\x8e\x66\xcf\x11"):+ return "asf"+ if header.startswith(b"\x1aE\xdf\xa3"):+ return "ebml"+ if header.startswith(b"glTF"):+ return "glb"+ if len(header) >= 12 and header[4:8] == b"ftyp":+ box_size = int.from_bytes(header[:4], "big")+ brands = {+ header[offset:offset + 4]+ for offset in range(8, min(len(header), box_size or len(header)), 4)+ }+ if brands & {b"avif", b"avis"}:+ return "avif"+ return "iso-bmff"+ if header.startswith((b"\x00\x00\x01\xba", b"\x00\x00\x01\xb3")):+ return "mpeg"+ if header.startswith(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"):+ return "ole"+ if header.startswith(b"PK"):+ return _sniff_zip_format(payload)+ try:+ root = ET.fromstring(payload)+ except ET.ParseError:+ return None+ if root.tag == "svg" or root.tag.endswith("}svg"):+ return "svg"+ return None+++def _package_content_types(+ package: zipfile.ZipFile,+) -> tuple[dict[str, str], dict[str, str]]:+ """Read Default and Override declarations from a PPTX package."""+ try:+ root = ET.fromstring(package.read("[Content_Types].xml"))+ except (KeyError, ET.ParseError) as exc:+ raise RuntimeError(+ "Round-trip source PPTX has an invalid [Content_Types].xml"+ ) from exc+ defaults = {+ str(item.get("Extension", "")).lower(): str(item.get("ContentType", ""))+ for item in root.findall(f"{{{_CONTENT_TYPES_NS}}}Default")+ if item.get("Extension") and item.get("ContentType")+ }+ overrides = {+ str(item.get("PartName", "")).lstrip("/"): str(+ item.get("ContentType", "")+ )+ for item in root.findall(f"{{{_CONTENT_TYPES_NS}}}Override")+ if item.get("PartName") and item.get("ContentType")+ }+ return defaults, overrides+++def _expected_content_type_formats(content_type: str) -> frozenset[str]:+ normalized = content_type.partition(";")[0].strip().lower()+ known = _FORMAT_BY_CONTENT_TYPE.get(normalized)+ if known is not None:+ return known+ if "spreadsheetml" in normalized:+ return frozenset({"ooxml-xlsx"})+ if "wordprocessingml" in normalized:+ return frozenset({"ooxml-docx"})+ if "presentationml" in normalized:+ return frozenset({"ooxml-pptx"})+ return frozenset()+++def _validate_changed_resource_format(+ *,+ spec: WorkspaceResourceSpec,+ payload: bytes,+ source_payload: bytes,+ content_type: str,+) -> None:+ """Refuse changed bytes that no longer fit their source package part."""+ suffix = PurePosixPath(spec.package_part).suffix.lower()+ actual_format = _sniff_resource_format(payload)+ source_format = _sniff_resource_format(source_payload)+ expected_by_extension = _FORMAT_BY_EXTENSION.get(suffix, frozenset())+ expected_by_content_type = _expected_content_type_formats(content_type)+ declared_media_kind = content_type.partition("/")[0].lower()+ actual_media_kind = _FORMAT_MEDIA_KIND.get(actual_format or "")+ has_declared_expectation = bool(+ source_format+ or expected_by_extension+ or expected_by_content_type+ or declared_media_kind in {"audio", "image", "video"}+ )+ mismatch = actual_format is None or not has_declared_expectation or (+ actual_format is not None+ and (+ (source_format is not None and actual_format != source_format)+ or (+ bool(expected_by_extension)+ and actual_format not in expected_by_extension+ )+ or (+ bool(expected_by_content_type)+ and actual_format not in expected_by_content_type+ )+ or (+ declared_media_kind in {"audio", "image", "video"}+ and actual_media_kind not in {declared_media_kind, "media"}+ )+ )+ )+ if not mismatch:+ return+ detected = actual_format or "unrecognized"+ raise RuntimeError(+ "Changed round-trip resource format does not match its source part: "+ f"{spec.workspace_path.as_posix()} is {detected}, but "+ f"{spec.package_part} uses extension {suffix or '<none>'} and "+ f"Content-Type {content_type!r}"+ )++def _source_part_for_relationships(rels_path: str) -> str | None:if rels_path == "_rels/.rels":return None@@ -258,6 +575,18 @@ class WorkspaceResourceSpec:kind: strworkspace_path: Pathmaterialized: bool+ source_sha256: str+ current_sha256: str | None+ owner_parts: tuple[str, ...]++ @property+ def changed(self) -> bool:+ """Return whether materialized workspace bytes differ from import."""+ return (+ self.materialized+ and self.current_sha256 is not None+ and self.current_sha256 != self.source_sha256+ )def workspace_resource_specs(@@ -279,6 +608,7 @@ def workspace_resource_specs(workspace_root = workspace.resolve()specs: list[WorkspaceResourceSpec] = []+ changed_payloads: list[tuple[WorkspaceResourceSpec, bytes]] = []seen_package_parts: set[str] = set()for index, raw in enumerate(items):context = f"round-trip resources.items[{index}]"@@ -288,6 +618,8 @@ def workspace_resource_specs(kind = raw.get("kind")workspace_path = raw.get("workspacePath")materialized = raw.get("materialized")+ source_sha256 = raw.get("sha256")+ raw_owner_parts = raw.get("ownerParts")if not isinstance(package_part, str) or not package_part:raise RuntimeError(f"{context}.packagePart must be a non-empty string")package_path = PurePosixPath(package_part)@@ -334,13 +666,70 @@ def workspace_resource_specs(raise RuntimeError(f"Materialized round-trip resource is missing: {workspace_path}")- specs.append(WorkspaceResourceSpec(+ if (+ not isinstance(source_sha256, str)+ or re.fullmatch(r"[0-9a-f]{64}", source_sha256) is None+ ):+ raise RuntimeError(f"{context}.sha256 must be a lowercase SHA-256")+ if not isinstance(raw_owner_parts, list) or not all(+ isinstance(value, str) and value+ for value in raw_owner_parts+ ):+ raise RuntimeError(f"{context}.ownerParts must be an array of parts")+ payload = resolved.read_bytes() if materialized else None+ current_sha256 = _sha256(payload) if payload is not None else None+ spec = WorkspaceResourceSpec(package_part=package_part,kind=kind,workspace_path=relative,materialized=materialized,- ))+ source_sha256=source_sha256,+ current_sha256=current_sha256,+ owner_parts=tuple(raw_owner_parts),+ )+ specs.append(spec)+ if payload is not None and spec.changed:+ changed_payloads.append((spec, payload))seen_package_parts.add(package_part)++ if changed_payloads:+ source_path = source_pptx_path(workspace_root)+ if not source_path.is_file():+ raise RuntimeError(+ "Changed round-trip resources require the preserved source PPTX: "+ f"{source_path}"+ )+ try:+ with zipfile.ZipFile(source_path) as package:+ defaults, overrides = _package_content_types(package)+ names = set(package.namelist())+ for spec, payload in changed_payloads:+ if spec.package_part not in names:+ raise RuntimeError(+ "Round-trip source package part is missing: "+ f"{spec.package_part}"+ )+ suffix = (+ PurePosixPath(spec.package_part).suffix.lstrip(".").lower()+ )+ content_type = overrides.get(spec.package_part) or defaults.get(+ suffix,+ )+ if not content_type:+ raise RuntimeError(+ "Round-trip source package part has no Content-Type: "+ f"{spec.package_part}"+ )+ _validate_changed_resource_format(+ spec=spec,+ payload=payload,+ source_payload=package.read(spec.package_part),+ content_type=content_type,+ )+ except zipfile.BadZipFile as exc:+ raise RuntimeError(+ f"Round-trip source PPTX is not a valid ZIP package: {source_path}"+ ) from excreturn tuple(specs)diff --git a/skills/ppt-master/scripts/svg_authoring_view.py b/skills/ppt-master/scripts/svg_authoring_view.pyindex 46399057..79341130 100644--- a/skills/ppt-master/scripts/svg_authoring_view.py+++ b/skills/ppt-master/scripts/svg_authoring_view.py@@ -69,6 +69,14 @@ from svg_authoring_contract import (canonical_authoring_errors,normalize_compact_authoring_tree,)+from svg_to_pptx.drawingml.context import IDENTITY_MATRIX+from svg_to_pptx.drawingml.utils import (+ INHERITABLE_ATTRS,+ matrix_multiply,+ parse_inline_style,+ parse_opacity,+ parse_transform_matrix,+)configure_utf8_stdio()@@ -81,6 +89,9 @@ AUTHORING_SUMMARY_SCHEMA = "ppt-master.svg-authoring-summary.v1"SOURCE_REF_ATTRIBUTE = "data-pptx-source-ref"SOURCE_PROXY_ATTRIBUTE = "data-pptx-source-proxy"SOURCE_PROXY_KIND = "native-restore"+EXTERNAL_LINKED_IMAGE_PROXY_ATTRIBUTE = (+ "data-pptx-external-linked-image-proxy"+)SEMANTIC_OBJECT_ATTRIBUTE = "data-pptx-semantic-object"SEMANTIC_SHAPE_KIND = "shape"SEMANTIC_TABLE_KIND = "table"@@ -177,6 +188,7 @@ _TSPAN_INHERITED_ATTRIBUTES = frozenset({"text-anchor","text-decoration",})+_ADOPT_INHERITED_ATTRIBUTES = tuple(INHERITABLE_ATTRS)# Compact native-shape intent is intentionally not in the removal set:# data-pptx-object, data-pptx-prst, and data-pptx-frame remain useful while@@ -1159,6 +1171,7 @@ def _source_proxy_element("id","data-pptx-object","data-pptx-frame",+ EXTERNAL_LINKED_IMAGE_PROXY_ATTRIBUTE,"data-pptx-prst","data-pptx-av-adj","data-pptx-av-adj1",@@ -1315,10 +1328,16 @@ def _externalize_large_source_objects(}:continueoriginal_bytes = len(_serialize_svg(element))+ forced_source_proxy = (+ element.get(SOURCE_PROXY_ATTRIBUTE) == SOURCE_PROXY_KIND+ )if (- original_bytes < SOURCE_PROXY_MIN_BYTES- or _contains_authoring_semantics(element)- or _prefer_editable_vector_asset(element)+ not forced_source_proxy+ and (+ original_bytes < SOURCE_PROXY_MIN_BYTES+ or _contains_authoring_semantics(element)+ or _prefer_editable_vector_asset(element)+ )):continuesource_ref = element.get(SOURCE_REF_ATTRIBUTE)@@ -1843,6 +1862,150 @@ def _parse_authoring_svg(path: Path) -> ET.Element:return root+def _element_chain(+ root: ET.Element,+ element: ET.Element,+) -> tuple[ET.Element, ...]:+ """Return the root-to-element ancestry chain."""+ parent_by_child = {+ child: parent+ for parent in root.iter()+ for child in parent+ }+ chain = [element]+ while chain[-1] is not root:+ parent = parent_by_child.get(chain[-1])+ if parent is None:+ raise ValueError("Adopted element is detached from its source SVG")+ chain.append(parent)+ return tuple(reversed(chain))+++def _local_inherited_presentation(element: ET.Element) -> dict[str, str]:+ """Resolve supported local presentation attributes with CSS precedence."""+ values = {+ name: value+ for name in _ADOPT_INHERITED_ATTRIBUTES+ if (value := element.get(name)) is not None+ }+ values.update({+ name: value+ for name, value in parse_inline_style(element.get("style")).items()+ if name in _ADOPT_INHERITED_ATTRIBUTES+ })+ return values+++def _local_opacity(element: ET.Element) -> str | None:+ inline = parse_inline_style(element.get("style"))+ return inline.get("opacity") or element.get("opacity")+++def _set_explicit_presentation(+ element: ET.Element,+ name: str,+ value: str,+) -> None:+ """Write one resolved style as an attribute, removing its inline shadow."""+ inline = parse_inline_style(element.get("style"))+ if name in inline:+ inline.pop(name)+ if inline:+ element.set(+ "style",+ "; ".join(+ f"{property_name}: {property_value}"+ for property_name, property_value in inline.items()+ ),+ )+ else:+ element.attrib.pop("style", None)+ element.set(name, value)+++def _format_transform_number(value: float) -> str:+ if math.isclose(value, 0.0, abs_tol=1e-12):+ value = 0.0+ return f"{value:.12g}"+++def _materialize_adopted_context(+ source_root: ET.Element,+ source_element: ET.Element,+ target_root: ET.Element,+ adopted: ET.Element,+) -> tuple[tuple[str, ...], bool]:+ """Carry source ancestry style and transforms onto an adopted object."""+ chain = _element_chain(source_root, source_element)+ effective: dict[str, str] = {}+ for ancestor in chain:+ effective.update(_local_inherited_presentation(ancestor))+ target_defaults = _local_inherited_presentation(target_root)+ materialized: list[str] = []+ for name, value in effective.items():+ if target_defaults.get(name) == value:+ continue+ _set_explicit_presentation(adopted, name, value)+ materialized.append(name)++ source_opacity = 1.0+ source_has_opacity = False+ try:+ for ancestor in chain:+ raw_opacity = _local_opacity(ancestor)+ if raw_opacity is None:+ continue+ source_has_opacity = True+ source_opacity *= parse_opacity(+ raw_opacity,+ allow_percentage=True,+ )+ target_raw_opacity = _local_opacity(target_root)+ target_opacity = parse_opacity(+ target_raw_opacity,+ allow_percentage=True,+ )+ except ValueError as exc:+ raise ValueError(f"Cannot resolve adopted object opacity: {exc}") from exc+ if (+ (source_has_opacity or target_raw_opacity is not None)+ and not math.isclose(source_opacity, target_opacity, abs_tol=1e-12)+ ):+ _set_explicit_presentation(+ adopted,+ "opacity",+ _format_transform_number(source_opacity),+ )+ materialized.append("opacity")++ ancestor_transform_composed = any(+ (ancestor.get("transform") or "").strip()+ for ancestor in chain[:-1]+ )+ if ancestor_transform_composed:+ matrix = IDENTITY_MATRIX+ try:+ for ancestor in chain:+ raw_transform = ancestor.get("transform")+ if raw_transform:+ matrix = matrix_multiply(+ matrix,+ parse_transform_matrix(raw_transform),+ )+ except ValueError as exc:+ raise ValueError(+ f"Cannot compose adopted object ancestor transform: {exc}"+ ) from exc+ adopted.set(+ "transform",+ "matrix(" + " ".join(+ _format_transform_number(value)+ for value in matrix+ ) + ")",+ )+ return tuple(sorted(materialized)), ancestor_transform_composed++def _rewrite_adopted_fragment_ids(element: ET.Element,target_ids: set[str],@@ -1902,9 +2065,17 @@ def _adopted_definition_clones(source_element: ET.Element,) -> list[ET.Element]:"""Copy the transitive source definitions referenced by one adopted object."""+ context_elements = [source_element]+ for ancestor in _element_chain(source_root, source_element)[:-1]:+ context = ET.Element(ancestor.tag)+ for name in (*_ADOPT_INHERITED_ATTRIBUTES, "opacity", "style"):+ value = ancestor.get(name)+ if value is not None:+ context.set(name, value)+ context_elements.append(context)definitions, selected_owners = _definition_closure(source_root,- [source_element],+ context_elements,)return [copy.deepcopy(child)@@ -2124,6 +2295,14 @@ def adopt_authoring_object(+ ", ".join(residual_imports))+ inherited_attributes, ancestor_transform_composed = (+ _materialize_adopted_context(+ source_root,+ source_element,+ target_root,+ adopted,+ )+ )stripped, removed_metadata = _strip_adopted_transport(adopted)target_ids = {item_id@@ -2177,6 +2356,8 @@ def adopt_authoring_object("renamed_ids": dict(sorted(replacements.items())),"copied_definitions": len(adopted_definitions),"inlined_imported_vectors": inlined_icons,+ "inherited_attributes": list(inherited_attributes),+ "ancestor_transform_composed": ancestor_transform_composed,"stripped_attributes": sorted(stripped),"removed_native_metadata": removed_metadata,"summary": str(summary_path),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 2be15990..27071695 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@@ -223,6 +223,7 @@ class RoundtripSlidePatch:edited_ref_ids: frozenset[str]deleted_ref_ids: frozenset[str]visual_changed: bool+ authoring_visual_changed: boolmotion_changed: booltransition_changed: booltransition_replaced: bool@@ -230,6 +231,14 @@ class RoundtripSlidePatch:notes_changed: bool+@dataclass(frozen=True)+class _NotesMasterReference:+ """Notes master selected for one generated notes slide."""++ package_part: str+ created_theme_part: str | None = None++@dataclassclass _TemplateRuntimeSlide:"""Parsed slide package state used by explicit Layout structure export."""@@ -883,15 +892,205 @@ def _write_xml_tree(path: Path, tree: ET.ElementTree) -> None:def _slide_ref_shape_ids(values: frozenset[str]) -> set[str]:- """Return numeric Slide-local ids from authoring source references."""+ """Return Slide-local ids from authoring source references."""result: set[str] = set()for value in values:- match = re.fullmatch(r"slide:(\d+)", value)- if match is not None:- result.add(match.group(1))+ if value.startswith("slide:") and len(value) > len("slide:"):+ result.add(value.split(":", 1)[1])return result+def _roundtrip_synthetic_shape_id(source_order: tuple[int, ...]) -> str:+ """Return the importer's stable identity for a shape with no native id."""+ return "missing-" + "-".join(str(value) for value in source_order)+++def _direct_shape_id(element: ET.Element) -> str | None:+ """Return one shape's own cNvPr id without descending into child shapes."""+ if element.tag == f"{{{MC_NS}}}AlternateContent":+ return _shape_id(element)+ for child in element:+ c_nv_pr = child.find(f"{{{PML_NS}}}cNvPr")+ if c_nv_pr is not None:+ return c_nv_pr.get("id")+ return None+++def _roundtrip_shape_id_closure(+ element: ET.Element,+ source_order: tuple[int, ...],+) -> set[str]:+ """Return native and synthetic identities in one source shape subtree."""+ identity = _direct_shape_id(element) or _roundtrip_synthetic_shape_id(+ source_order+ )+ identities = _shape_ids_in_element(element) | {identity}+ if element.tag != f"{{{PML_NS}}}grpSp":+ return identities+ child_order = 0+ for child in element:+ if child.tag not in _TOP_LEVEL_SHAPE_TAGS:+ continue+ child_order += 1+ identities.update(+ _roundtrip_shape_id_closure(+ child,+ (*source_order, child_order),+ )+ )+ return identities+++def _index_roundtrip_source_shape(+ element: ET.Element,+ source_order: tuple[int, ...],+ shapes: dict[str, ET.Element],+ key_by_element: dict[int, str],+) -> None:+ """Index one native source shape subtree by stable round-trip identity."""+ shape_id = _direct_shape_id(element) or _roundtrip_synthetic_shape_id(+ source_order+ )+ if shape_id in shapes:+ raise TemplateStructureError(+ f"Round-trip source slide repeats shape id {shape_id}"+ )+ shapes[shape_id] = element+ key_by_element[id(element)] = shape_id+ if element.tag != f"{{{PML_NS}}}grpSp":+ return+ child_order = 0+ for child in element:+ if child.tag not in _TOP_LEVEL_SHAPE_TAGS:+ continue+ child_order += 1+ _index_roundtrip_source_shape(+ child,+ (*source_order, child_order),+ shapes,+ key_by_element,+ )+++def _roundtrip_source_shape_roster(+ source_tree: ET.Element,+) -> tuple[+ dict[str, ET.Element],+ dict[str, set[str]],+ dict[int, str],+ dict[str, ET.Element],+]:+ """Index source top-level shapes without mutating missing native ids."""+ shapes: dict[str, ET.Element] = {}+ descendant_ids: dict[str, set[str]] = {}+ key_by_element: dict[int, str] = {}+ all_shapes: dict[str, ET.Element] = {}+ source_order = 0+ for child in source_tree:+ if child.tag not in _TOP_LEVEL_SHAPE_TAGS:+ continue+ source_order += 1+ order_path = (source_order,)+ _index_roundtrip_source_shape(+ child,+ order_path,+ all_shapes,+ key_by_element,+ )+ shape_id = key_by_element[id(child)]+ shapes[shape_id] = child+ descendant_ids[shape_id] = _roundtrip_shape_id_closure(+ child,+ order_path,+ )+ return shapes, descendant_ids, key_by_element, all_shapes+++def _roundtrip_nested_restore_ids(+ source_shapes: dict[str, ET.Element],+ source_key_by_element: dict[int, str],+ affected_top_ids: set[str],+ unchanged_ids: set[str],+ deleted_ids: set[str],+) -> set[str]:+ """Return outermost unchanged source shapes inside rebuilt top-level groups."""+ restore_ids: set[str] = set()++ def visit(element: ET.Element) -> None:+ shape_id = source_key_by_element[id(element)]+ if shape_id in unchanged_ids:+ restore_ids.add(shape_id)+ return+ if shape_id in deleted_ids or element.tag != f"{{{PML_NS}}}grpSp":+ return+ for child in element:+ if child.tag in _TOP_LEVEL_SHAPE_TAGS:+ visit(child)++ for shape_id in affected_top_ids:+ visit(source_shapes[shape_id])+ return restore_ids+++def _restore_roundtrip_nested_source_shapes(+ generated_nodes: list[ET.Element],+ source_shapes: dict[str, ET.Element],+ restore_ids: set[str],+ traced_ids: dict[str, list[str]],+) -> None:+ """Replace converter-safe nested placeholders with exact source shapes."""+ locations: dict[str, tuple[ET.Element, ET.Element]] = {}++ def index_children(parent: ET.Element) -> None:+ for child in parent:+ if child.tag not in _TOP_LEVEL_SHAPE_TAGS:+ continue+ shape_id = _direct_shape_id(child)+ if shape_id is not None:+ previous = locations.setdefault(shape_id, (parent, child))+ if previous[1] is not child:+ raise TemplateStructureError(+ "Generated round-trip slide repeats nested shape id "+ f"{shape_id}"+ )+ if child.tag == f"{{{PML_NS}}}grpSp":+ index_children(child)++ for node in generated_nodes:+ if node.tag == f"{{{PML_NS}}}grpSp":+ index_children(node)++ for source_id in sorted(restore_ids, key=_roundtrip_shape_sort_key):+ candidate_ids = {source_id}+ candidate_ids.update(traced_ids.get(f"shape-{source_id}", []))+ matches = {+ candidate_id: locations[candidate_id]+ for candidate_id in candidate_ids+ if candidate_id in locations+ }+ if len(matches) != 1:+ raise TemplateStructureError(+ "Unchanged nested round-trip source object did not produce "+ f"exactly one restore placeholder: {source_id}"+ )+ parent, placeholder = next(iter(matches.values()))+ source = source_shapes.get(source_id)+ if source is None:+ raise TemplateStructureError(+ f"Round-trip source shape is missing for nested ref {source_id}"+ )+ clone = ET.fromstring(ET.tostring(source, encoding="utf-8"))+ clone.tail = placeholder.tail+ position = list(parent).index(placeholder)+ parent.remove(placeholder)+ parent.insert(position, clone)+++def _roundtrip_shape_sort_key(value: str) -> tuple[int, int | str]:+ """Sort native numeric ids before stable synthetic ids."""+ return (0, int(value)) if value.isdigit() else (1, value)++def _relationship_key(attrs: dict[str, str]) -> tuple[str, str, str | None]:"""Return the identity used to reuse one source relationship."""return (@@ -1376,22 +1575,12 @@ def _apply_roundtrip_slide_overlay("Round-trip slide overlay requires source and generated p:spTree")- source_shapes: dict[str, ET.Element] = {}- source_descendant_ids: dict[str, set[str]] = {}- for child in source_tree:- if child.tag not in _TOP_LEVEL_SHAPE_TAGS:- continue- shape_id = _shape_id(child)- if not shape_id:- raise TemplateStructureError(- "Round-trip source slide contains a top-level shape without id"- )- if shape_id in source_shapes:- raise TemplateStructureError(- f"Round-trip source slide repeats top-level shape id {shape_id}"- )- source_shapes[shape_id] = child- source_descendant_ids[shape_id] = _shape_ids_in_element(child)+ (+ source_shapes,+ source_descendant_ids,+ source_key_by_element,+ all_source_shapes,+ ) = _roundtrip_source_shape_roster(source_tree)generated_order: list[str] = []generated_shapes: dict[str, ET.Element] = {}@@ -1424,11 +1613,19 @@ def _apply_roundtrip_slide_overlay(source_ref_ids = _slide_ref_shape_ids(patch.source_ref_ids)edited_ids = _slide_ref_shape_ids(patch.edited_ref_ids)deleted_ids = _slide_ref_shape_ids(patch.deleted_ref_ids)+ unchanged_ids = source_ref_ids - edited_ids - deleted_idsaffected_top_ids = {shape_idfor shape_id, descendant_ids in source_descendant_ids.items()if descendant_ids & (edited_ids | deleted_ids)}+ nested_restore_ids = _roundtrip_nested_restore_ids(+ source_shapes,+ source_key_by_element,+ affected_top_ids,+ unchanged_ids,+ deleted_ids,+ )authored_top_ids = {shape_idfor shape_id in source_shapes@@ -1480,7 +1677,7 @@ def _apply_roundtrip_slide_overlay(if missing_authored:raise TemplateStructureError("Edited round-trip source object did not produce a DrawingML shape: "- + ", ".join(sorted(missing_authored, key=int))+ + ", ".join(sorted(missing_authored, key=_roundtrip_shape_sort_key)))selected_by_id: dict[str, tuple[ET.Element, bool]] = {}@@ -1502,7 +1699,11 @@ def _apply_roundtrip_slide_overlay(merged_children: list[tuple[ET.Element, bool]] = []final_authored_slot = 0for child in list(source_tree):- shape_id = _shape_id(child) if child.tag in _TOP_LEVEL_SHAPE_TAGS else None+ shape_id = (+ source_key_by_element.get(id(child))+ if child.tag in _TOP_LEVEL_SHAPE_TAGS+ else None+ )if shape_id not in authored_top_ids:merged_children.append((child, False))continue@@ -1556,6 +1757,12 @@ def _apply_roundtrip_slide_overlay(generated_root,required_generated_relationship_ids,)+ _restore_roundtrip_nested_source_shapes(+ generated_nodes,+ all_source_shapes,+ nested_restore_ids,+ traced_ids,+ )if patch.transition_changed or patch.animation_changed:_replace_roundtrip_motion(source_root,@@ -1646,16 +1853,16 @@ def _apply_slide_notes(primary_language: str | None,*,enable_notes: bool,-) -> bool:- """Replace one slide's notes relationship and return whether notes were added."""+) -> _NotesMasterReference | None:+ """Replace one slide's notes relationship and return its notes master."""_remove_relationships_by_type(rels_path, NOTES_SLIDE_REL_TYPE)if not enable_notes:- return False+ return Nonenotes_text = markdown_to_plain_text(notes_content) if notes_content else ''if not notes_text:- return False+ return None- _ensure_notes_master(extract_dir, primary_language)+ notes_master = _ensure_notes_master(extract_dir, primary_language)notes_slides_dir = extract_dir / 'ppt' / 'notesSlides'notes_slides_dir.mkdir(exist_ok=True)notes_xml_path = notes_slides_dir / f'notesSlide{slide_num}.xml'@@ -1667,7 +1874,10 @@ def _apply_slide_notes(notes_rels_dir.mkdir(exist_ok=True)notes_rels_path = notes_rels_dir / f'notesSlide{slide_num}.xml.rels'notes_rels_path.write_text(- create_notes_slide_rels_xml(slide_num),+ create_notes_slide_rels_xml(+ slide_num,+ posixpath.relpath(notes_master.package_part, 'ppt/notesSlides'),+ ),encoding='utf-8',)_ensure_relationship(@@ -1675,16 +1885,16 @@ def _apply_slide_notes(NOTES_SLIDE_REL_TYPE,f'../notesSlides/notesSlide{slide_num}.xml',)- return True+ return notes_masterdef _roundtrip_resource_payloads(resource_root: Path | None,resources: tuple[WorkspaceResourceSpec, ...],) -> dict[str, bytes]:- """Read validated materialized round-trip resources by package part."""- materialized = [resource for resource in resources if resource.materialized]- if not materialized:+ """Read changed, validated round-trip resources by package part."""+ changed = [resource for resource in resources if resource.changed]+ if not changed:return {}if resource_root is None:raise TemplateStructureError(@@ -1692,7 +1902,7 @@ def _roundtrip_resource_payloads()workspace = resource_root.resolve()payloads: dict[str, bytes] = {}- for resource in materialized:+ for resource in changed:source = (workspace / resource.workspace_path).resolve()try:source.relative_to(workspace)@@ -1706,7 +1916,14 @@ def _roundtrip_resource_payloads("Materialized round-trip resource is missing: "f"{resource.workspace_path.as_posix()}")- payloads[resource.package_part] = source.read_bytes()+ payload = source.read_bytes()+ current_sha256 = hashlib.sha256(payload).hexdigest()+ if current_sha256 != resource.current_sha256:+ raise TemplateStructureError(+ "Round-trip resource changed after validation: "+ f"{resource.workspace_path.as_posix()}"+ )+ payloads[resource.package_part] = payloadreturn payloads@@ -1715,7 +1932,7 @@ def _reinject_roundtrip_resources(resource_root: Path | None,resources: tuple[WorkspaceResourceSpec, ...],) -> int:- """Write semantic resource bytes back to their exact source package parts."""+ """Write changed resource bytes back to their exact source package parts."""payloads = _roundtrip_resource_payloads(resource_root, resources)written = 0for package_part, payload in payloads.items():@@ -4917,72 +5134,246 @@ def _relax_output_permissions(output_path: Path) -> list[str]:_NOTES_MASTER_REL_TYPE = ('http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster')+_NOTES_MASTER_CONTENT_TYPE = (+ 'application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml'+)+++def _content_type_overrides(extract_dir: Path) -> dict[str, str]:+ """Return package part content-type overrides keyed without a leading slash."""+ content_types_path = extract_dir / '[Content_Types].xml'+ try:+ root = ET.parse(content_types_path).getroot()+ except (OSError, ET.ParseError) as exc:+ raise RuntimeError(+ f'Cannot read package content types: {content_types_path}'+ ) from exc+ overrides: dict[str, str] = {}+ for child in root:+ if child.tag.rsplit('}', 1)[-1] != 'Override':+ continue+ part_name = child.get('PartName', '').lstrip('/')+ content_type = child.get('ContentType', '')+ if part_name:+ overrides[part_name] = content_type+ return overrides+++def _notes_master_part_from_target(target: str) -> str | None:+ """Resolve one presentation relationship target to a notes-master part."""+ part_name = _resolve_package_target(+ 'ppt/presentation.xml',+ target,+ ).lstrip('/')+ prefix = 'ppt/notesMasters/'+ if not part_name.startswith(prefix) or part_name == prefix:+ return None+ return part_name+++def _validate_notes_master_part(+ extract_dir: Path,+ part_name: str,+ content_types: dict[str, str],+) -> str:+ """Validate one existing notes-master package part and return its name."""+ normalized = posixpath.normpath(part_name.lstrip('/'))+ if not normalized.startswith('ppt/notesMasters/'):+ raise RuntimeError(+ f'Notes master resolves outside ppt/notesMasters: {part_name}'+ )+ part_path = extract_dir / PurePosixPath(normalized)+ if not part_path.is_file():+ raise RuntimeError(f'Notes master part is missing: {normalized}')+ try:+ root = ET.parse(part_path).getroot()+ except (OSError, ET.ParseError) as exc:+ raise RuntimeError(f'Cannot parse notes master part: {normalized}') from exc+ if root.tag != f'{{{PML_NS}}}notesMaster':+ raise RuntimeError(f'Notes master part has an invalid root: {normalized}')+ declared_type = content_types.get(normalized)+ if declared_type is not None and declared_type != _NOTES_MASTER_CONTENT_TYPE:+ raise RuntimeError(+ 'Notes master content type mismatch for '+ f'{normalized}: {declared_type}'+ )+ return normalized+++def _register_notes_master_id(+ presentation_path: Path,+ relationship_id: str,+) -> None:+ """Register a notes-master relationship in presentation.xml by XML identity."""+ try:+ tree = ET.parse(presentation_path)+ except (OSError, ET.ParseError) as exc:+ raise RuntimeError(+ f'Cannot parse presentation package part: {presentation_path}'+ ) from exc+ root = tree.getroot()+ list_tag = f'{{{PML_NS}}}notesMasterIdLst'+ id_tag = f'{{{PML_NS}}}notesMasterId'+ relationship_attr = f'{{{REL_NS}}}id'+ notes_master_list = root.find(list_tag)+ if notes_master_list is not None:+ if any(+ child.tag == id_tag+ and child.get(relationship_attr) == relationship_id+ for child in notes_master_list+ ):+ return+ else:+ slide_master_list = root.find(f'{{{PML_NS}}}sldMasterIdLst')+ if slide_master_list is None:+ raise RuntimeError(+ 'presentation.xml is missing p:sldMasterIdLst'+ )+ notes_master_list = ET.Element(list_tag)+ insert_at = list(root).index(slide_master_list) + 1+ root.insert(insert_at, notes_master_list)+ ET.SubElement(+ notes_master_list,+ id_tag,+ {relationship_attr: relationship_id},+ )+ _write_xml_tree(presentation_path, tree)def _ensure_notes_master(extract_dir: Path,primary_language: str | None = None,-) -> None:- """Create notesMaster parts and wire them into the presentation package."""+) -> _NotesMasterReference:+ """Reuse or create a notes master and wire it into the presentation package."""ppt_dir = extract_dir / 'ppt'notes_masters_dir = ppt_dir / 'notesMasters'notes_masters_dir.mkdir(exist_ok=True)+ presentation_rels_path = ppt_dir / '_rels' / 'presentation.xml.rels'+ presentation_path = ppt_dir / 'presentation.xml'+ content_types = _content_type_overrides(extract_dir)+ relationships = _read_relationships(presentation_rels_path)- notes_master_path = notes_masters_dir / 'notesMaster1.xml'- if not notes_master_path.exists():+ try:+ presentation_root = ET.parse(presentation_path).getroot()+ except (OSError, ET.ParseError) as exc:+ raise RuntimeError(+ f'Cannot parse presentation package part: {presentation_path}'+ ) from exc+ relationship_attr = f'{{{REL_NS}}}id'+ referenced_ids = [+ elem.get(relationship_attr, '')+ for elem in presentation_root.findall(+ f'./{{{PML_NS}}}notesMasterIdLst/{{{PML_NS}}}notesMasterId'+ )+ ]+ notes_relationship_ids = [+ rel_id+ for rel_id, attrs in relationships.items()+ if attrs.get('Type') == _NOTES_MASTER_REL_TYPE+ and attrs.get('TargetMode') != 'External'+ ]+ ordered_relationship_ids = list(+ dict.fromkeys(referenced_ids + notes_relationship_ids)+ )+ relationship_id_by_part: dict[str, str] = {}+ selected_part: str | None = None+ selected_rid: str | None = None+ for rel_id in ordered_relationship_ids:+ attrs = relationships.get(rel_id)+ if (+ not attrs+ or attrs.get('Type') != _NOTES_MASTER_REL_TYPE+ or attrs.get('TargetMode') == 'External'+ ):+ continue+ target = attrs.get('Target', '')+ part_name = _notes_master_part_from_target(target)+ if part_name is None:+ raise RuntimeError(+ f'Notes master relationship {rel_id} has an invalid target: {target}'+ )+ part_name = _validate_notes_master_part(+ extract_dir,+ part_name,+ content_types,+ )+ relationship_id_by_part.setdefault(part_name, rel_id)+ if selected_part is None:+ selected_part = part_name+ selected_rid = rel_id++ if selected_part is None:+ for part_name, content_type in sorted(content_types.items()):+ if content_type != _NOTES_MASTER_CONTENT_TYPE:+ continue+ selected_part = _validate_notes_master_part(+ extract_dir,+ part_name,+ content_types,+ )+ selected_rid = relationship_id_by_part.get(selected_part)+ break++ created_theme_part: str | None = None+ if selected_part is None:+ occupied_parts = set(content_types)+ occupied_parts.update(+ part_name+ for attrs in relationships.values()+ if attrs.get('Type') == _NOTES_MASTER_REL_TYPE+ and (part_name := _notes_master_part_from_target(+ attrs.get('Target', '')+ )) is not None+ )+ index = 1+ while True:+ selected_part = f'ppt/notesMasters/notesMaster{index}.xml'+ if (+ selected_part not in occupied_parts+ and not (extract_dir / selected_part).exists()+ ):+ break+ index += 1+ notes_master_path = extract_dir / selected_partnotes_master_path.write_text(create_notes_master_xml(primary_language),encoding='utf-8',)- theme_dir = ppt_dir / 'theme'- theme_dir.mkdir(exist_ok=True)- theme1_path = theme_dir / 'theme1.xml'- theme2_path = theme_dir / 'theme2.xml'- if not theme2_path.exists():- if theme1_path.exists():- shutil.copy2(theme1_path, theme2_path)- else:- raise RuntimeError('Cannot create notes theme: ppt/theme/theme1.xml is missing')+ theme_dir = ppt_dir / 'theme'+ theme_dir.mkdir(exist_ok=True)+ theme1_path = theme_dir / 'theme1.xml'+ theme2_path = theme_dir / 'theme2.xml'+ if not theme2_path.exists():+ if theme1_path.exists():+ shutil.copy2(theme1_path, theme2_path)+ else:+ raise RuntimeError(+ 'Cannot create notes theme: ppt/theme/theme1.xml is missing'+ )+ created_theme_part = 'ppt/theme/theme2.xml'- notes_master_rels_dir = notes_masters_dir / '_rels'- notes_master_rels_dir.mkdir(exist_ok=True)- notes_master_rels_path = notes_master_rels_dir / 'notesMaster1.xml.rels'- if not notes_master_rels_path.exists():+ notes_master_rels_path = _relationships_path_for_part(+ extract_dir,+ selected_part,+ )+ notes_master_rels_path.parent.mkdir(parents=True, exist_ok=True)notes_master_rels_path.write_text(create_notes_master_rels_xml(),encoding='utf-8',)- presentation_rels_path = ppt_dir / '_rels' / 'presentation.xml.rels'- notes_master_rid = _find_relationship_id(- presentation_rels_path,- _NOTES_MASTER_REL_TYPE,- 'notesMasters/notesMaster1.xml',- )- if notes_master_rid is None:- notes_master_rid = _append_relationship(+ if selected_rid is None:+ selected_rid = _append_relationship(presentation_rels_path,_NOTES_MASTER_REL_TYPE,- 'notesMasters/notesMaster1.xml',+ posixpath.relpath(selected_part, 'ppt'),)-- presentation_path = ppt_dir / 'presentation.xml'- presentation_xml = presentation_path.read_text(encoding='utf-8')- if '<p:notesMasterIdLst>' in presentation_xml:- return- notes_master_lst = (- f'<p:notesMasterIdLst><p:notesMasterId r:id="{notes_master_rid}"/>'- '</p:notesMasterIdLst>'+ _register_notes_master_id(presentation_path, selected_rid)+ return _NotesMasterReference(+ package_part=selected_part,+ created_theme_part=created_theme_part,)- if '</p:sldMasterIdLst>' not in presentation_xml:- raise RuntimeError('presentation.xml is missing p:sldMasterIdLst')- presentation_xml = presentation_xml.replace(- '</p:sldMasterIdLst>',- '</p:sldMasterIdLst>' + notes_master_lst,- 1,- )- presentation_path.write_text(presentation_xml, encoding='utf-8')def _slide_config(animation_config: dict[str, Any] | None, svg_stem: str) -> dict[str, Any]:@@ -6538,6 +6929,8 @@ def create_pptx_with_native_svg(package_exts_used: set[str] = set()package_content_overrides: dict[str, str] = {}notes_slides_created: set[int] = set()+ notes_master_parts_used: set[str] = set()+ notes_master_theme_parts_created: set[str] = set()narration_slides_created: set[int] = set()audio_exts_used: set[str] = set()package_uses_timings = False@@ -6704,15 +7097,23 @@ def create_pptx_with_native_svg(notes_content = (notes.get(svg_path.stem, '') if notes else '')- if _apply_slide_notes(+ notes_master = _apply_slide_notes(extract_dir,rels_path,slide_num,notes_content,primary_language,enable_notes=enable_notes,- ):+ )+ if notes_master is not None:notes_slides_created.add(slide_num)+ notes_master_parts_used.add(+ notes_master.package_part+ )+ if notes_master.created_theme_part is not None:+ notes_master_theme_parts_created.add(+ notes_master.created_theme_part+ )if verbose:print(f" {progress_label} {svg_path.name} "@@ -6729,7 +7130,7 @@ def create_pptx_with_native_svg(notes_content = (notes.get(svg_path.stem, '') if notes else '')- notes_added = _apply_slide_notes(+ notes_master = _apply_slide_notes(extract_dir,rels_path,slide_num,@@ -6737,8 +7138,13 @@ def create_pptx_with_native_svg(primary_language,enable_notes=enable_notes,)- if notes_added:+ if notes_master is not None:notes_slides_created.add(slide_num)+ notes_master_parts_used.add(notes_master.package_part)+ if notes_master.created_theme_part is not None:+ notes_master_theme_parts_created.add(+ notes_master.created_theme_part+ )if verbose:print(f" {progress_label} {svg_path.name} "@@ -7235,15 +7641,21 @@ def create_pptx_with_native_svg(notes_content = (notes.get(svg_path.stem, '') if notes else '')- if _apply_slide_notes(+ notes_master = _apply_slide_notes(extract_dir,rels_path,slide_num,notes_content,primary_language,enable_notes=enable_notes,- ):+ )+ if notes_master is not None:notes_slides_created.add(slide_num)+ notes_master_parts_used.add(notes_master.package_part)+ if notes_master.created_theme_part is not None:+ notes_master_theme_parts_created.add(+ notes_master.created_theme_part+ )# --- Process narration audio (shared between native and legacy mode) ---svg_stem = svg_path.stem@@ -7650,17 +8062,18 @@ def create_pptx_with_native_svg(# Add notes master / slides content typesif enable_notes and notes_slides_created:- content_types = _add_content_type_override(- content_types,- '/ppt/theme/theme2.xml',- 'application/vnd.openxmlformats-officedocument.theme+xml',- )- content_types = _add_content_type_override(- content_types,- '/ppt/notesMasters/notesMaster1.xml',- 'application/vnd.openxmlformats-officedocument.presentationml.'- 'notesMaster+xml',- )+ for part_name in sorted(notes_master_theme_parts_created):+ content_types = _add_content_type_override(+ content_types,+ part_name,+ THEME_CONTENT_TYPE,+ )+ for part_name in sorted(notes_master_parts_used):+ content_types = _add_content_type_override(+ content_types,+ part_name,+ _NOTES_MASTER_CONTENT_TYPE,+ )for i in sorted(notes_slides_created):content_types = _add_content_type_override(content_types,diff --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 b1abf436..f660b462 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@@ -194,6 +194,43 @@ def _resource_slide_indices(}+def _changed_roundtrip_resource_pages(+ resources: tuple[WorkspaceResourceSpec, ...],+ manifest: dict[str, object],+ pages: tuple[RoundtripPage, ...],+) -> dict[int, frozenset[str]]:+ """Map changed materialized resources to every referencing output page."""+ raw_slides = manifest.get("slides")+ if not isinstance(raw_slides, list):+ raise RuntimeError("Round-trip manifest slides must be an array")+ slide_rows = {+ int(row["index"]): row+ for row in raw_slides+ if isinstance(row, dict) and isinstance(row.get("index"), int)+ }+ affected: dict[int, set[str]] = {}+ for resource in resources:+ if not resource.changed:+ continue+ source_slides = {+ index+ for index, row in slide_rows.items()+ if set(resource.owner_parts) & _roundtrip_slide_parts(+ row,+ include_structure=True,+ )+ }+ for page in pages:+ if page.source_slide in source_slides:+ affected.setdefault(page.output_index, set()).add(+ resource.workspace_path.as_posix()+ )+ return {+ index: frozenset(paths)+ for index, paths in affected.items()+ }++def _roundtrip_animation_config_for_pages(config: dict[str, object],pages: tuple[RoundtripPage, ...],@@ -305,6 +342,7 @@ def _roundtrip_passthrough_candidates(*,source_dir: str,authoring_report: dict[str, object] | None,+ changed_resource_pages: frozenset[int],) -> set[int]:"""Return source slides whose visual and editable sidecars are unchanged."""manifest = load_roundtrip_manifest(project_path)@@ -446,6 +484,7 @@ def _roundtrip_passthrough_candidates(if not path.is_file() or _path_sha256(path) != expected_sha:candidates.discard(index)break+ candidates.difference_update(changed_resource_pages)return candidates@@ -455,6 +494,7 @@ def _roundtrip_slide_patches(passthrough_slides: set[int],pages: tuple[RoundtripPage, ...],*,+ changed_resource_pages: frozenset[int],force_visual_changed: bool,force_motion_changed: bool,force_transition_changed: bool,@@ -588,17 +628,22 @@ def _roundtrip_slide_patches()return frozenset(value)+ authoring_visual_changed = (+ force_visual_changed+ or int(raw.get("edited_refs") or 0) > 0+ or int(raw.get("deleted_refs") or 0) > 0+ or int(raw.get("authored_unreferenced") or 0) > 0+ or raw.get("defs_changed") is True+ )patches[index] = RoundtripSlidePatch(source_ref_ids=_ref_set("source_ref_ids"),edited_ref_ids=_ref_set("edited_ref_ids"),deleted_ref_ids=_ref_set("deleted_ref_ids"),visual_changed=(- force_visual_changed- or int(raw.get("edited_refs") or 0) > 0- or int(raw.get("deleted_refs") or 0) > 0- or int(raw.get("authored_unreferenced") or 0) > 0- or raw.get("defs_changed") is True+ authoring_visual_changed+ or index in changed_resource_pages),+ authoring_visual_changed=authoring_visual_changed,motion_changed=motion_changed,transition_changed=transition_changed,transition_replaced=transition_replaced,@@ -611,6 +656,71 @@ def _roundtrip_slide_patches(return patches+def _report_roundtrip_omitted_opaque_payloads(+ project_path: Path,+ pages: tuple[RoundtripPage, ...],+) -> None:+ """Report omitted source slides whose private payloads drop with the page."""+ manifest = load_roundtrip_manifest(project_path)+ if manifest is None:+ return+ resources = manifest.get("resources")+ items = resources.get("items") if isinstance(resources, dict) else None+ raw_slides = manifest.get("slides")+ if not isinstance(items, list) or not isinstance(raw_slides, list):+ return+ slide_rows = {+ int(row["index"]): row+ for row in raw_slides+ if isinstance(row, dict) and isinstance(row.get("index"), int)+ }+ kept_source_slides = {page.source_slide for page in pages}+ omitted_payloads: dict[int, set[str]] = {}+ for item in items:+ if not isinstance(item, dict):+ continue+ kind = item.get("kind")+ source_parts = item.get("sourceParts")+ chart_native_payload = (+ kind == "native-payload"+ and isinstance(source_parts, list)+ and bool(source_parts)+ and all(+ isinstance(source_part, str)+ and source_part.startswith("ppt/charts/")+ for source_part in source_parts+ )+ )+ if chart_native_payload:+ continue+ payload_kind = {+ "audio": "audio",+ "sound": "audio",+ "video": "video",+ "native-payload": "opaque native payload",+ }.get(kind)+ if payload_kind is None:+ continue+ for index in _resource_slide_indices(+ item,+ slide_rows,+ include_structure=False,+ ):+ if index not in kept_source_slides:+ omitted_payloads.setdefault(index, set()).add(payload_kind)+ if not omitted_payloads:+ return+ details = "; ".join(+ f"source slide {index}: {', '.join(sorted(kinds))}"+ for index, kinds in sorted(omitted_payloads.items())+ )+ print(+ "Note: page_plan.json omits source slide(s) whose private payloads "+ "are dropped with the page: " + details,+ file=sys.stderr,+ )++def _opaque_roundtrip_slide_dependencies(project_path: Path,) -> dict[int, list[str]]:@@ -2218,6 +2328,7 @@ Recorded narration:structure_lock = Nonenative_structure_contract = None+ roundtrip_manifest: dict[str, object] | None = Noneroundtrip_resources: tuple[WorkspaceResourceSpec, ...] = ()pptx_structure = args.pptx_structurelock_path = project_path / 'spec_lock.md'@@ -2590,6 +2701,22 @@ Recorded narration:f"{len(set(roundtrip_page_sources or ()))} source slide(s)")+ changed_resources_by_page: dict[int, frozenset[str]] = {}+ if args.roundtrip:+ if roundtrip_manifest is None:+ print("Error: Round-trip manifest is missing", file=sys.stderr)+ return 1+ try:+ changed_resources_by_page = _changed_roundtrip_resource_pages(+ roundtrip_resources,+ roundtrip_manifest,+ roundtrip_pages,+ )+ except RuntimeError as exc:+ print(f"Error: {exc}", file=sys.stderr)+ return 1+ changed_resource_pages = frozenset(changed_resources_by_page)+roundtrip_passthrough_slides: set[int] = set()roundtrip_slide_patches: dict[int, RoundtripSlidePatch] = {}roundtrip_passthrough_overridden = any((@@ -2618,6 +2745,7 @@ Recorded narration:roundtrip_pages,source_dir=args.source or native_source_dir,authoring_report=authoring_roundtrip_report,+ changed_resource_pages=changed_resource_pages,)except RuntimeError as exc:print(f"Error: {exc}", file=sys.stderr)@@ -2691,6 +2819,7 @@ Recorded narration:authoring_roundtrip_report,roundtrip_passthrough_slides,roundtrip_pages,+ changed_resource_pages=changed_resource_pages,force_visual_changed=(args.image_sizing == 'display'or args.text_flow != TEXT_FLOW_PRESERVE@@ -2705,6 +2834,11 @@ Recorded narration:print(f"Error: {exc}", file=sys.stderr)return 1try:+ if roundtrip_page_plan_present:+ _report_roundtrip_omitted_opaque_payloads(+ project_path.resolve(),+ roundtrip_pages,+ )opaque_dependencies = _opaque_roundtrip_slide_dependencies(project_path.resolve())@@ -2744,7 +2878,7 @@ Recorded narration:for paths in owner_refs.values()for path in paths}- if patch.visual_changed:+ if patch.authoring_visual_changed:affected_paths.update(set(dependencies) - mapped_paths)if affected_paths:blocked_dependencies[page.output_index] = (diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/notes.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/notes.pyindex ef487089..fd334dff 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/notes.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/notes.py@@ -3,6 +3,7 @@from __future__ import annotationsimport re+from xml.sax.saxutils import quoteattrfrom language_tags import normalize_language_tag@@ -181,18 +182,22 @@ def create_notes_slide_xml(</p:notes>'''-def create_notes_slide_rels_xml(slide_num: int) -> str:+def create_notes_slide_rels_xml(+ slide_num: int,+ notes_master_target: str,+) -> str:"""Create notes slide relationship file XML.Args:slide_num: Slide number.+ notes_master_target: Package-relative target of the notes master.Returns:Relationship file XML string."""return f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target="../notesMasters/notesMaster1.xml"/>+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster" Target={quoteattr(notes_master_target)}/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="../slides/slide{slide_num}.xml"/></Relationships>'''diff --git a/skills/ppt-master/workflows/edit-native-pptx.md b/skills/ppt-master/workflows/edit-native-pptx.mdindex 03b58d21..f149705e 100644--- a/skills/ppt-master/workflows/edit-native-pptx.md+++ b/skills/ppt-master/workflows/edit-native-pptx.md@@ -67,7 +67,7 @@ python3 skills/ppt-master/scripts/pptx_to_svg.py "<source.pptx>" \|---|---|---|| `authoring-svg-flat/slide_NN.svg` | One compact editable SVG per source slide, in source order | Open only the pages you will edit or need to judge for reuse || `authoring-svg-flat/authoring_summary.json` | Roster plus per-page canvas, text, image, vector, placeholder, source-ref, and source-proxy counts | Read first; plan from it before opening any SVG |-| `images/`, `icons/imported/`, `audio/`, `video/`, `sounds/` | Source media and imported decorative vectors | Reference from pages; keep names — export resolves hrefs relative to the page and fails on a missing resource |+| `images/`, `icons/imported/`, `audio/`, `video/`, `sounds/` | Source media and imported decorative vectors | Keep names. Export hashes materialized files; changed bytes rebuild every output page whose source Slide/Layout/Master/notes graph references that package part, and a format mismatch fails export || `notes/slide_NN.md` | Source speaker notes when present | Edit, delete, or add per output page (§6) || `native-payloads/`, `analysis/` | Immutable native backing and tool-owned contracts | Tool-owned; opening them costs context and changes nothing — do not read, edit, or quote || `sources/source.pptx` | Exact source package | Read only through `ppt_to_md.py "<workspace>/sources/source.pptx" -o "<workspace>/validation/source_readback.md"` when you need page text without opening every SVG (notes on unchanged pages, content mapping) |@@ -111,11 +111,12 @@ Write `page_plan.json` at the workspace root only when the output differs from tOnly `schema` and `pages` at the root and `source_slide` / `svg` per page are accepted; the exporter rejects any other field.**Forbidden — plans the exporter refuses** (fail-closed, fix the plan instead of forcing):-- Omitting a source slide that owns audio, video, or another opaque native payload- A same-deck slide jump whose destination is omitted or repeated (include the target exactly once, or remove the link from the page)- Unknown, duplicated, or cross-owned `svg` filenames; `source_slide` out of range-**Combining pages**: One output page always has exactly one skeleton — its `source_slide`. To merge several source pages, pick the page whose layout carries the result as the skeleton, then copy the needed elements from the other pages' SVGs into it and delete what the merged page no longer needs. Bring an object across pages only through the adopt command below — never by pasting raw SVG, because source refs are page-local and a pasted object would be mistaken for one of the skeleton's own. The adopted object keeps its visual form but loses its native identity and is rebuilt from SVG, so the combined page counts as `rebuilt`. A source proxy (§3) cannot leave its own page; a merge that needs one keeps that page as the skeleton instead.+Omitting a source slide deliberately drops the audio, video, or undecodable payloads only that slide owns; export prints a note listing them.++**Combining pages**: One output page always has exactly one skeleton — its `source_slide`. To merge several source pages, pick the page whose layout carries the result as the skeleton, then copy the needed elements from the other pages' SVGs into it and delete what the merged page no longer needs. Bring an object across pages only through the adopt command below — never by pasting raw SVG, because source refs are page-local and a pasted object would be mistaken for one of the skeleton's own. The adopted object keeps its visual form by materializing effective inherited presentation attributes (including `font-family`, `fill`, `opacity`, and CSS-resolved values) and composing ancestor transforms onto the copy. It loses its native identity and is rebuilt from SVG, so the combined page counts as `rebuilt`. A source proxy (§3) cannot leave its own page; a merge that needs one keeps that page as the skeleton instead.```bashpython3 skills/ppt-master/scripts/svg_authoring_view.py \@@ -234,8 +235,8 @@ Round-trip export summary: output_pages=N passthrough=P cloned_passthrough=C pat|---|---|---|| `passthrough` | Identity page, original XML and relationships | Referenced pages without a plan and without any notes/motion overlay || `cloned_passthrough` | Planned page, original XML on a cloned part | Referenced pages with a plan and without any overlay |-| `patched` | Visible XML kept; only notes or motion overlaid | Referenced pages once notes, transitions, animation, or narration flags apply |-| `rebuilt` | Visible authoring changed | Exactly the pages marked edited in §4.3 — a delivery-only job must show `rebuilt=0` |+| `patched` | Source shape XML is kept while shape order, notes, transitions, animation, or narration timing may change | Pages with z-order-only edits or package overlays that do not rebuild a source shape |+| `rebuilt` | Visible authoring or a referenced materialized resource changed | Exactly the pages marked edited in §4.3 plus every output page that references a changed resource — a delivery-only job must show `rebuilt=0` |**Validation**:diff --git a/skills/ppt-master/workflows/generate-pptx.md b/skills/ppt-master/workflows/generate-pptx.mdindex f3172078..21e1b729 100644--- a/skills/ppt-master/workflows/generate-pptx.md+++ b/skills/ppt-master/workflows/generate-pptx.md@@ -308,7 +308,7 @@ is confirmed; a bare template/style name does not.**Artifact ownership**: fact-channel and source/derived artifact boundaries are defined in [`references/artifact-ownership.md`](../references/artifact-ownership.md). This Step uses those ownership rules; it does not redefine them.-**`<project_path>/analysis/` is the project's intermediate-analysis folder: the canonical home for machine-extracted source/asset facts — the PPTX intake bundle (`source_profile.json` index + per-deck `<stem>.identity.json` / `<stem>.slide_library.json`) and `image_analysis.csv`. It holds facts, not design contracts — `design_spec.md` / `spec_lock.md` stay at the project root.** The MUST-read contract covers only the **compact structured data files (`.json` / `.csv`)**; other artifacts that may live under `analysis/` (e.g. a beautify `source_svg_import/` vector reference package) are NOT bulk-read — they are read selectively only when a specific workflow step calls for them. Before the Strategist confirmation stage, Strategist MUST read the auto-extracted fact files already in `analysis/` — currently `source_profile.json` (PPTX intake), when present. This file is the multi-deck index: read it once for the `decks[]` digests (canvas / chart / table / SmartArt entries per source deck), then open a specific deck's `<stem>.identity.json` / `<stem>.slide_library.json` only if you need its full raw facts. Use these entries as **factual source context** (format default + content facts); when several decks are present, synthesize across all of them. The source's **palette / typography / visual identity are a reference, not a constraint**: the main pipeline may inherit them where they fit the content and the confirmed style, or design fresh where they don't — the Strategist's judgment, never an obligation to either keep or discard. (Template-fill preserves the native source design by editing cloned slides directly; beautify defaults to the source identity but still follows the confirmed values; the main pipeline treats source identity as reference only and defaults to fresh design.) (`image_analysis.csv` lands later, at the image-analysis step below, and is the authoritative regenerated image-fact view there — re-derived from the live `images/` folder, not a durable store.)+**`<project_path>/analysis/` is the project's intermediate-analysis folder: the canonical home for machine-extracted source/asset facts — the PPTX intake bundle (`source_profile.json` index + per-deck `<stem>.identity.json` / `<stem>.slide_library.json`) and `image_analysis.csv`. It holds facts, not design contracts — `design_spec.md` / `spec_lock.md` stay at the project root.** The MUST-read contract covers only the **compact structured data files (`.json` / `.csv`)**; other artifacts that may live under `analysis/` (e.g. a beautify `source_svg_import/` vector reference package) are NOT bulk-read — they are read selectively only when a specific workflow step calls for them. Before the Strategist confirmation stage, Strategist MUST read the auto-extracted fact files already in `analysis/` — currently `source_profile.json` (PPTX intake), when present. This file is the multi-deck index: read it once for the `decks[]` digests (canvas / chart / table / SmartArt entries per source deck), then open a specific deck's `<stem>.identity.json` / `<stem>.slide_library.json` only if you need its full raw facts. Use these entries as **factual source context** (format default + content facts); when several decks are present, synthesize across all of them. The source's **palette / typography / visual identity are a reference, not a constraint**: the main pipeline may inherit them where they fit the content and the confirmed style, or design fresh where they don't — the Strategist's judgment, never an obligation to either keep or discard. (Edit Native PPTX preserves source-native objects through its source-backed round trip; beautify defaults to the source identity but still follows the confirmed values; the main pipeline treats source identity as reference only and defaults to fresh design.) (`image_analysis.csv` lands later, at the image-analysis step below, and is the authoritative regenerated image-fact view there — re-derived from the live `images/` folder, not a durable store.)**Channel ownership — read each fact once from its owning channel.** In the main pipeline the **content contract is the content-type files in `sources/`** — primarily `<stem>.md`, but also any user-supplied content the import archived there: `.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml` (a `metrics.json` or `data.csv` may carry core content — judge by what the file holds). Text, tables, chart data values, and SmartArt node wording come from these (`ppt_to_md` transcribes native charts as Markdown tables and SmartArt nodes as hierarchical bullets). **Do NOT read pipeline sidecars in `sources/` as content**: `*.conversion_profile.json` (conversion audit) and `*_files/image_manifest.json` (asset index) are process metadata — open them only to audit a conversion or resolve assets, never as slide content. Converted-source originals archived in `sources/` (`.pdf` / `.pptx` / `.docx` / `.xlsx` / `.html` / `.epub` / `.tex` / `.rst` / `.ipynb` / `.typ`, etc.) are read via their converted `<stem>.md`, not scanned directly in the main pipeline. The `analysis/` chart / table / diagram entries are a **structural digest** for outline decisions (which slides carried charts, tables, or SmartArt; chart types / series names; SmartArt layout and hierarchy) — not a second copy of the content values; do NOT also pull chart values or SmartArt wording from `<stem>.slide_library.json` in the main pipeline. The `<stem>.slide_library.json` full structured data is owned by beautify for native chart / table data and SmartArt relationships while keeping all wording from the Markdown.