Skip to content

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(roundtrip): materialize compact semantic authoring workspaces

hugohe3be01dfcd153a
diff --git a/AGENTS.md b/AGENTS.md
index 44cca50c..ab580665 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -92,6 +92,7 @@ python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live --d
python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>
# Shared create-template coordinate compaction before template validation
python3 skills/ppt-master/scripts/compact_svg_coordinates.py "<template_workspace>/templates" --inplace --keep-native-frames
+python3 skills/ppt-master/scripts/compact_svg_styles.py "<template_workspace>/templates" --inplace
# Explicit create-template normalization: selected complex <g> -> one SVG picture asset / <image>
python3 skills/ppt-master/scripts/extract_svg_pictures.py "<svg_file>" --select "<group_id>" --resource-root "<workspace>" --images-dir "<workspace>/picture-assets" --inplace
# Type A create-template mirror: validated authoring IR -> deterministic structured template workspace
diff --git a/docs/faq.md b/docs/faq.md
index 7c68d448..0c4b1e9d 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -465,7 +465,7 @@ Want to turn a PPT you love into a reusable template for PPT Master? Here's how:
**Step 1 — Prepare Reference Material**
-The recommended input is the original `.pptx`. PPT Master extracts theme identity, declared Master/Layout topology, placeholder metadata, native-shape evidence, and reusable assets that are actually present and supported. `standard` and `fidelity` use the source as visual reference and author a new SVG roster plus a new Master/Layout/slot system; they neither preserve nor distill source topology. `mirror` instead materializes those validated source facts into a new workspace without semantic synthesis or gap filling. Fixed Master/Layout group wrappers are mechanically expanded into direct atoms because structural layers cannot be `<g>`.
+The recommended input is the original `.pptx`. PPT Master extracts theme identity, declared Master/Layout topology, placeholder metadata, native-shape evidence, and reusable assets that are actually present and supported. `standard` and `fidelity` inspect the complete source inventory as evidence and author a new SVG roster plus a new Master/Layout/slot system; they neither preserve nor distill source topology. `mirror` instead materializes one prototype per source Slide together with only that Slide roster's reachable Layout/Master facts, without semantic synthesis or gap filling. Unreferenced source Layouts/Masters remain analysis evidence rather than mirror output. Fixed Master/Layout group wrappers are mechanically expanded into direct atoms because structural layers cannot be `<g>`.
Large imported SVGs may contain native-shape metadata, hidden carriers, and preview fingerprints. That lossless representation stays immutable in the temporary analysis workspace as payload backing. Template creation uses a lightweight editable IR with document-local source refs and a compact path/hash manifest. `standard` / `fidelity` author project-canonical SVG and use compact authored-preset groups only for exact registered preset matches. Mirror materializes final templates from the IR, reuses converter-supported payload only for unchanged Slide-local/slot refs, and keeps an SVG fallback for unsupported or edited objects.
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.md
index c9acc9d5..6af86cfe 100644
--- a/docs/powerpoint-svg-mapping.md
+++ b/docs/powerpoint-svg-mapping.md
@@ -184,7 +184,7 @@ preset selection and authoring behavior are documented in
| PowerPoint feature | Project representation | PPTX result | Import and fidelity | Validation boundary |
|---|---|---|---|---|
| Visually drawn table | Ordinary SVG shapes, lines, and text | Independent editable PowerPoint shapes | Fidelity follows each component row | It is not a native table and has no PowerPoint table editing model |
-| PowerPoint-native table | One `<g data-pptx-replace-with="table">` with child `<metadata type="application/json">` and a visible fallback | `p:graphicFrame` containing `a:tbl` when native Chart/Table replacement is enabled | Imported supported tables reconstruct a fallback plus replacement metadata | Metadata must form the registered rectangular schema; requires `--native-charts-and-tables` |
+| PowerPoint-native table | One `<g data-pptx-replace-with="table">` with child `ppt-master.semantic-table.v2` JSON metadata and a visible fallback | `p:graphicFrame` containing `a:tbl` when native Chart/Table replacement is enabled | Imported supported tables factor repeated cell/paragraph/run formatting into defaults and named cell styles; export expands it in memory | Metadata must form the registered rectangular schema; unversioned payloads fail; requires `--native-charts-and-tables` |
| Merged table cells | Canonical native-table merge metadata | Native horizontal/vertical merge semantics | `Native-stable` within the closed schema | Overlapping, ambiguous, or non-rectangular merges are rejected |
| Table cell formatting | Registered native-table cell formatting fields | Native cell fill, border, text, and alignment | `Native-normalized` | Fields outside the closed schema are not guessed; imported non-empty run effects block instead of normalizing into an effect-free cell |
| Unsupported native table feature | SVG fallback or direct source preservation | Visible fallback remains, or source OOXML stays on a direct route | Explicit fallback / `Direct preservation` | Do not extend JSON ad hoc |
diff --git a/docs/roadmap.md b/docs/roadmap.md
index ee4ffd2e..fb85aa05 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -141,7 +141,7 @@ The directions below come up repeatedly and have been evaluated as **not on the
**Issues**: [#53](https://github.com/hugohe3/ppt-master/issues/53), [#118](https://github.com/hugohe3/ppt-master/issues/118)
-The Generate PPTX route is built around full control of newly authored shapes, text, and layout. A structured PPTX can inform a reviewed reusable package in two explicit ways: `standard` / `fidelity` author a new SVG and Master/Layout system from visual evidence, while `mirror` materializes a new workspace from the complete set of supported source facts actually present, including unused Layout definitions. Neither path modifies the source PPTX or recovers absent design intent. Generic "open any PPTX and blindly refill every placeholder" remains a different product shape.
+The Generate PPTX route is built around full control of newly authored shapes, text, and layout. A structured PPTX can inform a reviewed reusable package in two explicit ways: `standard` / `fidelity` author new complete Slide SVG prototypes and a Master/Layout system from the full source evidence, while `mirror` materializes source Slides with only their reachable Layout/Master chains. Neither path modifies the source PPTX or recovers absent design intent. Generic "open any PPTX and blindly refill every placeholder" remains a different product shape.
**The basic need is actually simple**: if you just need "replace Excel data into fixed positions in a PPT template", have the AI write a few lines of `python-pptx`. You don't need this pipeline.
diff --git a/docs/technical-design.md b/docs/technical-design.md
index 7f1bd455..71c0bdc9 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -460,7 +460,9 @@ project. Moving one contribution into the library preserves its spec schema and
assets but changes its qualified filename to the bare single-kind library path;
global index registration then controls whether it appears as a library choice.
-For Create Layout / Create Deck, `standard` and `fidelity` write new SVG documents and a new Master/Layout/slot system; source topology is visual evidence only and is neither preserved nor distilled. `mirror` materializes a new workspace from the source page order, Master/Layout identities and parentage, placeholder facts, and supported visuals that are actually present and validated, without semantic synthesis or gap filling. Layout mirror is legal only when that preserved source is already brand-neutral and application-neutral; otherwise author a new Layout or retain the facts as Deck. Because structural layers cannot be `<g>`, fixed-layer source group wrappers are mechanically expanded into direct atoms while preserving ownership, paint order, and appearance. Create Brand analyzes identity fragments only; Create Style extracts portable method/direction only. Neither enters structural replication strategies or produces an SVG roster.
+For Create Layout / Create Deck, `standard` and `fidelity` inspect the complete source Master/Layout inventory as structural and visual evidence, then author complete Slide SVG prototypes and a new Master/Layout/slot system. `standard` stays compact; `fidelity` covers a broader set of useful source-aligned families. Every retained authored Layout is represented by at least one Slide prototype. `mirror` emits only source Slide prototypes and preserves each Slide's reachable Layout/Master chain; each standalone SVG resolves Master + Layout + Slide context while retaining explicit ownership markers. Source structures unused by every Slide remain evidence only. Layout mirror is legal only when the retained source is already brand-neutral and application-neutral; otherwise author a new Layout or retain the facts as Deck. Fixed-layer source groups are mechanically expanded into direct atoms while preserving ownership, paint order, and appearance. Create Brand analyzes identity fragments only; Create Style extracts portable method/direction only. Neither enters structural replication strategies or produces an SVG roster.
+
+Slide-only is an SVG-roster boundary, not a ban on deterministic support data. A PPTX-backed mirror may carry per-Master source Theme and native-payload sidecars; tools validate and consume them without exposing them as prototypes or page-authoring context.
The four template kinds own different segments of the design contract:
@@ -808,12 +810,15 @@ These direct routes share some analysis primitives with the main pipeline, but a
**Why PPTX round-trip uses a semantic workspace rather than a ZIP-shaped tree.** The editable page source is `authoring-svg-flat/`; PowerPoint image media, imported reusable vectors, cues, audio, video, notes, and opaque payloads live under `images/`, `icons/imported/`, `sounds/`, `audio/`, `video/`, `notes/`, and `native-payloads/`. The exact backing package stays at `sources/source.pptx`, structural and ownership contracts stay under `analysis/`, diagnostics stay under `validation/`, and published decks stay under `exports/`. This keeps authoring paths aligned with normal projects while `analysis/roundtrip_manifest.json` maps semantic files back to package ownership. Import and export use this one contract: root `source_template.pptx`, `native_structure.json`, `conversion-report.json`, and `assets/` are invalid rather than compatibility inputs.
-Large imported tables and complex groups are source-backed atoms rather than
-thousands of model-facing SVG nodes. Their exact browser previews are hashed
-under `images/source-object-previews/`, and `authoring-svg-flat/` keeps one
-compact `native-restore` image proxy plus the outer source reference. An
-unchanged proxy rehydrates the complete native OOXML object, including a native
-PowerPoint table; deleting a Slide-local proxy deletes that object. Inherited
+Supported imported native tables remain one semantic marker rather than
+thousands of model-facing SVG nodes. Their `ppt-master.semantic-table.v2`
+payload factors repeated cell, paragraph, and run formatting into defaults and
+named cell styles; native export expands those values in memory. Exact browser
+previews are hashed under `images/source-object-previews/`. Complex groups and
+tables outside the closed semantic schema instead stay source-backed:
+`authoring-svg-flat/` keeps one compact `native-restore` image proxy plus the
+outer source reference. An unchanged proxy rehydrates the complete source
+OOXML object; deleting a Slide-local proxy deletes that object. Inherited
Master/Layout proxies must remain because one flat page cannot delete shared
structure. Editing either the proxy or its preview fails closed because
silently compiling it as a picture or SVG-derived shapes would violate
@@ -835,13 +840,13 @@ round-trip intent.
**Why structured output is read back before publication.** Metadata preflight cannot prove package serialization preserved every relationship and registration. Export therefore reopens the temporary PPTX and validates published Slides separately from the complete Master/Layout roster, including definitions unused by all Slides. It checks Presentation → Master → Layout → Slide registration, physical part/content-type rosters, picker identities, exact static-object order, placeholder type/effective index/bounds, carrier bindings, hidden proxies, and zero-slot Layouts before publishing the file.
-**Why Create Layout / Create Deck have authored and preservation modes.** `pptx_template_import.py` emits layered Master/Layout/Slide references plus native structure facts. `standard` / `fidelity` use those assets and visuals as references, then author a new topology from the confirmed reusable behavior. Mirror instead materializes a new workspace from the validated source roster and topology one-to-one, allowing only mechanical normalization required by the explicit structured contract and never inventing absent facts. The original PPTX remains immutable analysis evidence, not a packaged export dependency. Create Brand has no structural replication strategy.
+**Why Create Layout / Create Deck have authored and preservation modes.** `pptx_template_import.py` emits layered Master/Layout/Slide references plus native structure facts. `standard` / `fidelity` inspect the complete source Master/Layout and visual evidence, then author compact or broader useful Slide prototypes and topology from the confirmed reusable behavior. Mirror instead materializes each source Slide and only its reachable Layout/Master chain one-to-one, allowing mechanical context completion required by the explicit structured contract. Unreferenced source structures are not mirror output; authored modes may realize useful ones through new complete Slide prototypes. The original PPTX remains immutable analysis evidence, not a packaged export dependency. Create Brand has no structural replication strategy.
**Why create-template uses one workspace route in both scopes.** `create-template` keeps `library` as its default indexed output and may instead write under an initialized project. Both roots require `templates/`; `images/`, `icons/`, and on-demand `exports/` appear only when they contain real files, and existing SVG asset references follow the same rules. Library uses one bare spec inside a single-kind directory; project uses qualified specs in one shared root. The schema and asset routes remain portable, while spec placement and global index registration are scope-specific. Only Layout / Deck own a structured SVG contract; Brand and Style remain roster-free.
**Why each template SVG stays complete while still compiling to native structure.** A template SVG repeats the inherited Master/Layout visuals together with sample Slide content so it opens as a complete standalone page. During generation, `page_layouts` selects that prototype and the output SVG remains complete. Export removes repeated inherited atoms, emits real Master/Layout parts, and leaves actual slot carriers and Slide-local content on the Slide.
-**Why PowerPoint-native Chart/Table reconstruction uses explicit replacement markers, not automatic object replacement.** The standalone `pptx_to_svg.py` importer emits a visible SVG fallback plus `data-pptx-replace-with` and `<metadata type="application/json">` only for validated table/chart subsets. Generated decks prepare that pair only for semantic object keys recorded as `<object-key>=yes` in the §IX `Native-ready` map; §VII remains a positive catalog-reference inventory, and a catalog marker is a capability example rather than an execution decision. The parent marker determines the payload schema; ordinary shapes and connectors never use this contract. Table import covers exact physical row/grid topology, canonical rectangular merges with empty slaves, safe solid/no-fill per-side borders, plain multi-paragraph cells, and a closed run-rich paragraph form. A rich paragraph contains non-empty `runs`; every run requires `text` and may use only `bold`, `italic`, `underline`, `strike`, `color`, `font_size`, one `font_family`, `lang`, and `alt_lang`. Unknown source presentation-only run XML without a non-empty `effectLst` / `effectDag` normalizes into that schema; a table-cell run effect instead disables native replacement and adds a blocking effect diagnostic. Relationship-bearing text, extensions, line breaks, fields, tabs, bullets, malformed text topology, noncanonical merges, unsafe borders, and non-solid fills remain fallback-only. The normalized fallback for table style `{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}` resolves `wholeTbl`, `firstRow`, horizontal banding, theme colors/fonts, and direct overrides; this is not a full built-in/custom style registry.
+**Why PowerPoint-native Chart/Table reconstruction uses explicit replacement markers, not automatic object replacement.** The standalone `pptx_to_svg.py` importer emits a visible SVG fallback plus `data-pptx-replace-with` and `<metadata type="application/json">` only for validated table/chart subsets. Generated decks prepare that pair only for semantic object keys recorded as `<object-key>=yes` in the §IX `Native-ready` map; §VII remains a positive catalog-reference inventory, and a catalog marker is a capability example rather than an execution decision. The parent marker determines the payload schema; ordinary shapes and connectors never use this contract. Table markers require `ppt-master.semantic-table.v2`: import factors exact repeated cell/paragraph/run values into defaults and named cell styles, while export expands them before native validation. Table import covers exact physical row/grid topology, canonical rectangular merges with empty slaves, safe solid/no-fill per-side borders, plain multi-paragraph cells, and a closed run-rich paragraph form. A rich paragraph contains non-empty `runs`; every run requires `text` and may use only `bold`, `italic`, `underline`, `strike`, `color`, `font_size`, one `font_family`, `lang`, and `alt_lang`. Unknown source presentation-only run XML without a non-empty `effectLst` / `effectDag` normalizes into that schema; a table-cell run effect instead disables native replacement and adds a blocking effect diagnostic. Relationship-bearing text, extensions, line breaks, fields, tabs, bullets, malformed text topology, noncanonical merges, unsafe borders, and non-solid fills remain fallback-only. The normalized fallback for table style `{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}` resolves `wholeTbl`, `firstRow`, horizontal banding, theme colors/fonts, and direct overrides; this is not a full built-in/custom style registry.
For supported parsed column/bar/line/area, pie/doughnut, scatter, and bubble charts, a missing baked preview is replaced by a deterministic readable SVG fallback marked `data-pptx-fallback-kind="normalized"`. The importer also covers the verified column/line/area combo subset, canonical four-series OHLC stock, area charts with numeric date axes, verified scatter/bubble charts with the closed `axes.x` / `axes.y` contract, radar, safe `of_pie` `serLines`, axis/title/legend normalization, and bounded bar/column gap/overlap cases. `gapWidth` is accepted only as one integer in `0..500`, and `overlap` only as one integer in `-100..100`; these presentation values intentionally normalize in native output, while malformed, duplicate, or out-of-range input fails closed. Combo plots may retain independent primary/secondary category caches and workbook ranges. XY import derives `scatter_style` from uniform effective series line/marker/smooth state. The closed category/value and XY axis contracts retain kind, position, visibility, label position, number format, min/max/major unit, reversal, and major gridlines for native read-back; the normalized XY fallback consumes only the two `major_gridlines` flags.
diff --git a/docs/templates-architecture.md b/docs/templates-architecture.md
index 1c47a345..26afc931 100644
--- a/docs/templates-architecture.md
+++ b/docs/templates-architecture.md
@@ -135,10 +135,14 @@ serves, the audience outcomes it supports, and representative narrative/page
roles. Identity and structure are integrated around that context, while the
current Strategist decides which prototypes and content to use.
-`standard` / `fidelity` author a new complete system from confirmed evidence;
-mirror maps validated source identities and parentage one-to-one into a new
-workspace. Mirror preserves source facts but does not prove that the source is
-a reusable Deck: creation still has to identify the stable application rules.
+`standard` / `fidelity` inspect the full confirmed source inventory and author a
+new complete system. Mirror emits one complete prototype per source Slide and
+preserves only that Slide roster plus each Slide's reachable Layout/Master
+parentage; source Layouts or Masters that no source Slide reaches are outside
+the mirror contract. Authored modes may re-author useful unreferenced source
+structures as new complete Slide prototypes. Mirror preserves those in-scope
+source facts but does not prove that the source is a reusable Deck: creation
+still has to identify the stable application rules.
A source that yields only identity becomes Brand; reusable method and visual
direction without prototypes becomes Style; a brand-neutral reusable structure
becomes Layout; a branded structural system or scenario-bearing content grammar
diff --git a/docs/templates-guide.md b/docs/templates-guide.md
index 20313c66..26dd4788 100644
--- a/docs/templates-guide.md
+++ b/docs/templates-guide.md
@@ -259,14 +259,20 @@ python3 skills/ppt-master/scripts/mirror_template_materialize.py \
"<import_workspace>" "<template_workspace>"
```
-It validates the IR manifest, immutable source hashes, complete native graph,
-visibility facts, and imported-vector closure before atomically publishing the
+It validates the IR manifest, immutable hashes for source Slides, their reachable
+native graph and visibility facts, and the corresponding imported-vector closure before atomically publishing the
source-ordered SVG roster and its `icons/imported/` / `images/` assets. It never
requires or uses the opt-in `svg-flat/` verification tree as the template source
and never generates a Design Spec; the designer writes the resolved spec
against the published roster.
-**Mirror graph boundary**: mirror preserves the complete supported source Master/Layout graph. It emits one complete prototype per source slide and one definition-only `layout_<layout_key>.svg` prototype for every source Layout unused by those slides. The latter registers in PowerPoint through the independent Layout roster without becoming a published page; its parent Master is retained with it. Preflight stops only when required source facts or supported geometry are missing, never merely because a Layout is unused.
+**Mirror graph boundary**: mirror emits one complete prototype per source Slide and preserves only each Slide's referenced Layout and parent Master. The SVG resolves Master + Layout + Slide context while keeping layer ownership explicit. Source Master/Layout identities unused by every Slide are not materialized by mirror; `standard` / `fidelity` may use the complete source inventory to author useful new Slide prototypes.
+
+The Design Spec gives every emitted Slide prototype its normal roster row. When the source contains unreferenced Master/Layout identities, one scope sentence may note that they exist but were not materialized by mirror; it does not invent per-identity usage analysis.
+
+Template use is Slide-first: each generated-page SVG already resolves its Master and Layout visuals, so normal authoring selects that complete Slide prototype. The workspace contains no standalone Master/Layout definition SVGs.
+
+“Slide-only” describes the editable SVG roster. A PPTX-backed mirror may also carry tool-only structural sidecars such as `source_themes.json` and `native_payloads.json.gz`; they preserve exact reachable Theme/native data during export and are not page prototypes or AI authoring inputs.
**How a mirror-authored workspace is consumed**: source-to-workspace `replication_mode: mirror` is a capability, not a project choice. Strategist inspects the actual prototypes, current content, and any explicit instruction, then decides which pages to select, repeat, skip, or reorder and whether literal, structural, or visual-only reuse is appropriate. Literal reuse copies a complete prototype and edits only allowed visible text values while preserving decoration, sprite crops, geometry, and normalized structured declarations. This never requires the source page count or order.
@@ -299,7 +305,7 @@ Brand/Style use is intentionally different: both keep authored content Slide-loc
`exports/<id>_template_preview.pptx` is review evidence created by Create Template when requested or required. It is not the template input; generation always consumes the workspace root.
-Microsoft PowerPoint is the acceptance target for Master/Layout behavior. Keynote, WPS, and LibreOffice can open PPTX files but may normalize template structure or load a large mirror roster of unused Layouts more slowly.
+Microsoft PowerPoint is the acceptance target for Master/Layout behavior. Keynote, WPS, and LibreOffice can open PPTX files but may normalize template structure.
### What a derived template workspace looks like
@@ -360,7 +366,7 @@ Common misconceptions to avoid:
- **A template is not one undifferentiated "style skin".** Brand, Style, Layout, and Deck deliberately separate identity, direction/method, structure, and application so each segment can be reused or combined under an explicit ownership rule
- **A template does not make content decisions for you.** The Strategist still decides per-page which layout to use and whether to extend a variant. Templates offer candidates, not predetermined results
- **`fidelity` mode is not pixel-perfect copying.** Even with `literal` fidelity, the AI still strips noise and unnecessary repetition — geometry stays, redundancy goes
-- **`mirror` targets literal supported appearance and source topology, not byte-identical OOXML.** It inherits source import limitations and permits only mechanical normalization such as fixed-layer group expansion. Unsupported native objects keep their available SVG fallback or are reported; mirror never synthesizes replacement ownership.
+- **`mirror` targets literal supported appearance and each source Slide's reachable topology, not byte-identical OOXML.** It inherits source import limitations and permits only mechanical normalization such as inheritance completion and fixed-layer group expansion. Unsupported native objects keep their available SVG fallback or are reported; mirror never synthesizes replacement ownership.
---
diff --git a/docs/zh/faq.md b/docs/zh/faq.md
index f20642f3..b9771373 100644
--- a/docs/zh/faq.md
+++ b/docs/zh/faq.md
@@ -414,7 +414,7 @@ Create Template 会先确认简报,再写入已注册、可发现的 `library`
**第一步 — 准备参考材料**
-**最推荐的方式是直接给原始 `.pptx` 文件**。PPT Master 会提取包内实际存在且受支持的主题色、字体、Master/Layout、placeholder type/idx、原生形状信息和可复用图片资源。`standard` 与 `fidelity` 把来源当作视觉参考,重新设计 SVG roster 和新的 Master/Layout/slot 系统,不保留、也不蒸馏来源拓扑。`mirror` 则把这些已验证的来源事实物化到新工作区,不做语义归纳或缺口补造。由于结构层禁止 `<g>`,来源 Master/Layout 的 group wrapper 只允许机械展开成直接原子。
+**最推荐的方式是直接给原始 `.pptx` 文件**。PPT Master 会提取包内实际存在且受支持的主题色、字体、Master/Layout、placeholder type/idx、原生形状信息和可复用图片资源。`standard` 与 `fidelity` 把完整来源清单作为证据,重新设计 SVG roster 和新的 Master/Layout/slot 系统,不保留、也不蒸馏来源拓扑。`mirror` 则为每张来源 Slide 输出一个原型,并只把这组 Slide 可达的 Layout/Master 事实物化到新工作区,不做语义归纳或缺口补造;未引用的来源 Layout/Master 只保留为分析证据,不进入 mirror 输出。由于结构层禁止 `<g>`,来源 Master/Layout 的 group wrapper 只允许机械展开成直接原子。
完整导入 SVG 可以保留高级 PowerPoint 形状所需的 metadata、隐藏 carrier 和预览指纹,并作为载荷后备留在临时分析工作区且保持不可变。模板创建使用带文档内 source ref 和紧凑路径/hash manifest 的轻量可编辑 IR。`standard` / `fidelity` 创作项目规范化 SVG,只有精确匹配已登记 preset 时才使用 compact authored-preset 组。Mirror 从 IR 物化最终模板,只为未改且 hash 匹配的 Slide-local/slot ref 重新接入转换器已经支持的载荷;不支持或已修改的对象保留当前 SVG fallback。
diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.md
index 9403f892..2805fec7 100644
--- a/docs/zh/powerpoint-svg-mapping.md
+++ b/docs/zh/powerpoint-svg-mapping.md
@@ -179,7 +179,7 @@ PowerPoint 意图
| PowerPoint 功能 | 项目表达 | PPTX 结果 | 回导与保真度 | 校验边界 |
|---|---|---|---|---|
| 视觉绘制表格 | 普通 SVG shape、line 与 text | 相互独立的可编辑 PowerPoint shape | 保真度遵循各组件对应行 | 它不是原生表格,也没有 PowerPoint 表格编辑模型 |
-| PowerPoint 原生表格 | 一个带 `<metadata type="application/json">` 和可见 fallback 的 `<g data-pptx-replace-with="table">` | 启用原生 Chart/Table 替换时产生含 `a:tbl` 的 `p:graphicFrame` | 导入受支持表格重建 fallback 加替换 metadata | metadata 必须形成已登记矩形 schema;需要 `--native-charts-and-tables` |
+| PowerPoint 原生表格 | 一个带 `ppt-master.semantic-table.v2` JSON metadata 和可见 fallback 的 `<g data-pptx-replace-with="table">` | 启用原生 Chart/Table 替换时产生含 `a:tbl` 的 `p:graphicFrame` | 导入时把重复的单元格、段落和 run 格式归纳为默认值及命名单元格样式;导出时在内存中展开 | metadata 必须形成已登记矩形 schema;拒绝无版本 payload;需要 `--native-charts-and-tables` |
| 合并表格单元格 | 规范原生表格 merge metadata | 原生水平/垂直合并语义 | 封闭 schema 内为 `Native-stable` | 拒绝重叠、歧义或非矩形合并 |
| 表格单元格格式 | 已登记原生表格单元格格式字段 | 原生单元格 fill、border、text 与 alignment | `Native-normalized` | 不猜测封闭 schema 以外的字段;导入的非空 run 效果会阻断,而不是归一化成无效果单元格 |
| 不受支持的原生表格功能 | SVG fallback 或直接源保留 | 保留可见 fallback,或在直接路线保留源 OOXML | 显式 fallback / `Direct preservation` | 不得临时扩展 JSON |
diff --git a/docs/zh/roadmap.md b/docs/zh/roadmap.md
index d861d92d..6035a08d 100644
--- a/docs/zh/roadmap.md
+++ b/docs/zh/roadmap.md
@@ -141,7 +141,7 @@
**对应 Issue**:[#53](https://github.com/hugohe3/ppt-master/issues/53)、[#118](https://github.com/hugohe3/ppt-master/issues/118)
-Generate PPTX 路线围绕完全可控的新形状、文字与版式创作。结构完整的 PPTX 可以通过两种显式方式为经过确认的可复用模板包提供依据:`standard` / `fidelity` 以视觉证据为参考,创作新的 SVG 与 Master/Layout 系统;`mirror` 把来源包内实际存在的全部受支持事实物化到新工作区,包括未使用的 Layout 定义。两者都不修改来源 PPTX,也不补造缺失的设计意图。但「打开任意 PPTX 后不经规范化就盲填所有占位框」仍是另一种产品形态。
+Generate PPTX 路线围绕完全可控的新形状、文字与版式创作。结构完整的 PPTX 可以通过两种显式方式为经过确认的可复用模板包提供依据:`standard` / `fidelity` 读取完整来源证据,创作新的完整 Slide SVG 原型和 Master/Layout 系统;`mirror` 只物化来源 Slide 及其可达的 Layout/Master 链。两者都不修改来源 PPTX,也不补造缺失的设计意图。但「打开任意 PPTX 后不经规范化就盲填所有占位框」仍是另一种产品形态。
**基础诉求其实很简单**:如果只是「固定位置替换 Excel 数据到 PPT 模板」,直接让 AI 写一段 `python-pptx` 脚本即可,几行代码搞定,不需要本项目这套管线。
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index 14033306..14cd9b82 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -391,7 +391,9 @@ Strategist 及后续角色只读该项目本地副本。Project root 可直接
复用;把其中一项迁入 library 时保留 spec schema 与素材,但要把限定名改为
单 kind 库路径下的裸 spec,再由全局索引注册决定它是否作为 library 选项出现。
-对 Create Layout / Create Deck,`standard` 与 `fidelity` 会重新创作 SVG 和新的 Master/Layout/slot 系统;来源拓扑只作为视觉证据,不保留、也不蒸馏。`mirror` 把来源包内实际存在且已验证的页序、Master/Layout 身份与父子关系、placeholder 事实和受支持视觉物化到新工作区,不做语义归纳或缺口补造。只有被保留的来源本身已经品牌中立且应用中立时,Layout mirror 才合法;否则应重新创作 Layout,或把这些事实保留为 Deck。由于结构层不能是 `<g>`,固定结构层的来源 group wrapper 只允许机械展开成直接原子,同时保持归属、paint order 和视觉一致。Create Brand 只提取身份片段,Create Style 只提取可移植方法/方向;两者都不进入结构复制策略,也不生成 SVG roster。
+对 Create Layout / Create Deck,`standard` 与 `fidelity` 会先把完整来源 Master/Layout 清单作为结构与视觉证据,再创作完整 Slide SVG 原型和新的 Master/Layout/slot 系统。`standard` 保持紧凑,`fidelity` 覆盖更广的有用来源对齐家族;每个被保留的创作型 Layout 至少由一个 Slide 原型表达。`mirror` 只输出来源 Slide 原型,并保留每张 Slide 可达的 Layout/Master 链;每个独立 SVG 会补齐 Master + Layout + Slide 上下文,同时保留显式归属标记。未被任何 Slide 引用的来源结构只作为证据。只有被保留的来源已经品牌中立且应用中立时,Layout mirror 才合法;否则应重新创作 Layout,或把这些事实保留为 Deck。固定结构层的来源 group 只允许机械展开成直接原子,同时保持归属、paint order 和视觉一致。Create Brand 只提取身份片段,Create Style 只提取可移植方法/方向;两者都不进入结构复制策略,也不生成 SVG roster。
+
+“只生成 Slide”是 SVG roster 边界,不代表禁止确定性辅助数据。PPTX 来源的 mirror 可携带逐 Master 的来源 Theme 与原生载荷 sidecar;工具会校验并消费它们,但不会把它们暴露为原型或页面创作上下文。
四类模板拥有不同的设计契约片段:
@@ -691,7 +693,7 @@ SVG 与 DrawingML 的表达模型并不等价,因此主编译路径不把“
**为什么 PPTX 往返使用语义工作区,而不是照搬 ZIP 目录。** 可编辑页面源是 `authoring-svg-flat/`;PowerPoint 图片媒体、导入的可复用矢量、提示音、音频、视频、备注和不透明载荷分别位于 `images/`、`icons/imported/`、`sounds/`、`audio/`、`video/`、`notes/` 和 `native-payloads/`。精确来源包保存在 `sources/source.pptx`,结构与归属契约保存在 `analysis/`,诊断保存在 `validation/`,发布文件保存在 `exports/`。这样既让作者路径与普通项目一致,又由 `analysis/roundtrip_manifest.json` 把语义文件映射回 package 归属。导入与导出只接受这一份契约;根目录下的 `source_template.pptx`、`native_structure.json`、`conversion-report.json` 与 `assets/` 都不是兼容输入。
-大型导入表格和复杂组合被视为来源支撑的原子对象,而不是在模型可见 SVG 中展开成数千个节点。它们的精确浏览器预览以 hash 命名存放在 `images/source-object-previews/`,`authoring-svg-flat/` 只保留一个紧凑的 `native-restore` 图片代理和外层 source ref。未修改的代理会恢复完整原生 OOXML 对象,包括 PowerPoint 原生表格;删除 Slide-local 代理会删除该对象。继承自 Master/Layout 的代理必须保留,因为单个 flat 页面不能删除共享结构。修改代理或预览会直接阻止导出,因为静默编译为图片或 SVG 派生形状会违背往返意图。
+受支持的导入原生表格保持为一个语义 marker,而不是在模型可见 SVG 中展开成数千个节点。其 `ppt-master.semantic-table.v2` payload 会把重复的单元格、段落和 run 格式归纳成默认值及命名单元格样式,原生导出时再在内存中展开。精确浏览器预览以 hash 命名存放在 `images/source-object-previews/`。复杂组合及封闭语义 schema 以外的表格则继续由来源支撑:`authoring-svg-flat/` 只保留一个紧凑的 `native-restore` 图片代理和外层 source ref。未修改的代理会恢复完整来源 OOXML 对象;删除 Slide-local 代理会删除该对象。继承自 Master/Layout 的代理必须保留,因为单个 flat 页面不能删除共享结构。修改代理或预览会直接阻止导出,因为静默编译为图片或 SVG 派生形状会违背往返意图。
**为什么只有一条 PPTX 编译路线。** Native 导出把作者 SVG 中受支持的元素逐个翻译成 DrawingML 形状。常规 deck 路线读取 `svg_output/`;用户需要时,create-template 对通过校验的模板原型调用同一 structured 编译器,生成 `exports/<id>_template_preview.pptx` 作为审阅证据。项目不会把整页 SVG 媒体或另一套位图渲染打包成第二类 PPTX。`svg_final/` 仍由常规 deck 的强制后处理生成,但只承担派生视觉预览和 SVG 图片插入,不为 PowerPoint 手工“转换为形状”提供兼容兜底。
@@ -709,13 +711,13 @@ SVG 与 DrawingML 的表达模型并不等价,因此主编译路径不把“
**为什么 structured 输出要在发布前回读。** 元数据预检不能证明 package 序列化保留了所有 relationship 与注册信息。导出器会重新打开临时 PPTX,把已发布 Slide 与完整 Master/Layout roster 分开校验,包括没有任何 Slide 使用的定义;同时核对 Presentation → Master → Layout → Slide 注册链、物理 part/content-type roster、选择器身份、固定对象顺序、placeholder 类型/有效索引/bounds、carrier 绑定、隐藏 proxy 与零槽 Layout,只有通过后才发布。
-**为什么 Create Layout / Create Deck 分为创作模式和保留模式。** `pptx_template_import.py` 输出分层 Master/Layout/Slide 参考和 native 结构事实。`standard` / `fidelity` 把这些素材和视觉当参考,再按照确认后的可复用行为创作新拓扑。Mirror 则把已验证的来源 roster 与拓扑一对一物化到新工作区,只允许显式 structured 合同要求的机械归一化,不补造缺失事实。原始 PPTX 保持为不可变分析证据,不成为最终模板依赖。Create Brand 没有结构复制策略。
+**为什么 Create Layout / Create Deck 分为创作模式和保留模式。** `pptx_template_import.py` 输出分层 Master/Layout/Slide 参考和 native 结构事实。`standard` / `fidelity` 会检查完整来源 Master/Layout 与视觉证据,再按照确认后的可复用行为创作紧凑或覆盖更广的完整 Slide 原型和新拓扑。Mirror 则一对一物化每张来源 Slide 及其可达的 Layout/Master 链,只做显式 structured 合同要求的上下文补全和机械归一化。未被来源 Slide 引用的结构不进入 mirror 输出;创作模式可按需要把其中有用的结构重新表达为完整 Slide 原型。原始 PPTX 保持为不可变分析证据,不成为最终模板依赖。Create Brand 没有结构复制策略。
**为什么 create-template 在两种范围都使用同一工作区路由。** `create-template` 仍以写入索引的 `library` 为默认,也可写入已初始化项目。两种根目录都要求 `templates/`;`images/`、`icons/` 和按需生成的 `exports/` 只有存在真实内容时才出现,已有 SVG 素材的引用规则也一致。Library 在单 kind 目录使用一份裸 spec,project 在共享 root 使用限定名 spec;schema 与素材路由保持一致,spec 落点及全局索引注册随范围变化。只有 Layout / Deck 拥有 structured SVG 合同,Brand 与 Style 保持 roster-free。
**为什么模板 SVG 保持完整却仍能编译成原生结构。** 模板 SVG 会重复携带继承的 Master/Layout 视觉和示例 Slide 内容,因此可独立打开。生成时由 `page_layouts` 选择该原型,输出 SVG 仍保持视觉闭包。导出器移除重复继承原子、生成真实 Master/Layout part,并把槽位 carrier 与 Slide-local 内容留在 Slide。
-**为什么 PowerPoint 原生 Chart/Table 重建使用显式替换 marker,而不是自动替换对象。** 独立的 `pptx_to_svg.py` 导入器只为已验证的表格 / 图表子集输出可见 SVG fallback、`data-pptx-replace-with` 与 `<metadata type="application/json">`。生成型 deck 只为 §IX `Native-ready` 映射中以 `<object-key>=yes` 点名的语义对象准备这组内容;§VII 只保存正向 catalog reference,catalog marker 只是能力示例,不替项目做决策。父组 marker 决定 payload schema;普通 shape 与 connector 不使用该合同。表格导入覆盖精确的物理行列 topology、slave 为空的规范矩形 merge、安全的 solid/no-fill 逐边 border、纯文本多段落,以及封闭的 run 级富文本段落。富文本段落包含非空 `runs`;每个 run 必须有 `text`,并且只能使用 `bold`、`italic`、`underline`、`strike`、`color`、`font_size`、单一 `font_family`、`lang` 和 `alt_lang`。不含非空 `effectLst` / `effectDag` 的来源展示型 run XML 会归一化到该 schema;表格单元格 run 效果则会禁用原生替换,并添加阻塞效果诊断。带 relationship 的文本、扩展节点、换行、字段、tab、项目符号、破损文本 topology、非规范 merge、不安全 border 与非纯色填充仍保持 fallback-only。表格样式 `{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}` 的规范化 fallback 会解析 `wholeTbl`、`firstRow`、横向带状行、主题颜色 / 字体和直接格式覆盖;这不代表完整 built-in/custom style registry。
+**为什么 PowerPoint 原生 Chart/Table 重建使用显式替换 marker,而不是自动替换对象。** 独立的 `pptx_to_svg.py` 导入器只为已验证的表格 / 图表子集输出可见 SVG fallback、`data-pptx-replace-with` 与 `<metadata type="application/json">`。生成型 deck 只为 §IX `Native-ready` 映射中以 `<object-key>=yes` 点名的语义对象准备这组内容;§VII 只保存正向 catalog reference,catalog marker 只是能力示例,不替项目做决策。父组 marker 决定 payload schema;普通 shape 与 connector 不使用该合同。表格 marker 必须使用 `ppt-master.semantic-table.v2`:导入时把完全相同的单元格、段落及 run 值归纳为默认值和命名样式,导出时在原生校验前展开。表格导入覆盖精确的物理行列 topology、slave 为空的规范矩形 merge、安全的 solid/no-fill 逐边 border、纯文本多段落,以及封闭的 run 级富文本段落。富文本段落包含非空 `runs`;每个 run 必须有 `text`,并且只能使用 `bold`、`italic`、`underline`、`strike`、`color`、`font_size`、单一 `font_family`、`lang` 和 `alt_lang`。不含非空 `effectLst` / `effectDag` 的来源展示型 run XML 会归一化到该 schema;表格单元格 run 效果则会禁用原生替换,并添加阻塞效果诊断。带 relationship 的文本、扩展节点、换行、字段、tab、项目符号、破损文本 topology、非规范 merge、不安全 border 与非纯色填充仍保持 fallback-only。表格样式 `{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}` 的规范化 fallback 会解析 `wholeTbl`、`firstRow`、横向带状行、主题颜色 / 字体和直接格式覆盖;这不代表完整 built-in/custom style registry。
受支持的柱 / 条 / 折线 / 面积、饼 / 圆环、散点 / 气泡图在没有 baked preview 时会生成确定性、可读的 SVG fallback,并标记 `data-pptx-fallback-kind="normalized"`。导入器还覆盖已验证的柱 / 折线 / 面积组合图、规范四系列 OHLC stock、数值日期轴面积图、采用封闭 `axes.x` / `axes.y` 合同的散点 / 气泡图、radar、安全的 `of_pie` `serLines`、坐标轴 / 标题 / 图例归一化,以及有界的柱 / 条图 gap/overlap 场景。`gapWidth` 只接受 `0..500` 内的单个整数,`overlap` 只接受 `-100..100` 内的单个整数;这两个表现字段在 native 输出中有意归一化,非法、重复或越界输入 fail closed。组合图可保留主 / 次 plot 各自的 category cache 与 workbook range。XY 导入根据各系列一致的有效 line/marker/smooth 状态推导 `scatter_style`。封闭的 category/value 与 XY 轴合同为 native read-back 保留 kind、position、visibility、label position、number format、min/max/major unit、reverse 和 major gridlines;规范化 XY fallback 只消费两个 `major_gridlines` 开关。
diff --git a/docs/zh/templates-architecture.md b/docs/zh/templates-architecture.md
index 10323413..ef5f18c1 100644
--- a/docs/zh/templates-architecture.md
+++ b/docs/zh/templates-architecture.md
@@ -118,7 +118,7 @@ native_structure_mode: structured
Deck 编码的是**一类可重复演示**,而不只是预先组合好的 Brand 和 Layout。它描述模板服务哪些沟通场景、支持哪些受众结果,以及常见的叙事或页面角色。身份与结构围绕这份语境形成一个整体;具体选哪些原型、如何处理内容,由当前 Strategist 决定。
-`standard` / `fidelity` 根据已确认的证据创作新完整系统;mirror 把已验证的来源身份与父子关系一对一映射进新工作区。Mirror 能保留来源事实,但不能单独证明来源就是可复用 Deck:创建时仍要识别稳定的应用规则。只得到身份时创建 Brand;方法与视觉方向需要脱离原型复用时创建 Style;得到品牌中立的可复用结构时创建 Layout;结构带品牌身份,或者包含场景叙事与内容语法时创建 Deck。
+`standard` / `fidelity` 检查完整的已确认来源清单并创作新完整系统。Mirror 为每张来源 Slide 输出一个完整原型,只保留这组 Slide 及每张 Slide 可达的 Layout/Master 父子关系;没有被任何来源 Slide 引用的 Layout 或 Master 不属于 mirror 合同。创作模式可以把其中有用的未引用来源结构重著为新的完整 Slide 原型。Mirror 能保留这部分范围内的来源事实,但不能单独证明来源就是可复用 Deck:创建时仍要识别稳定的应用规则。只得到身份时创建 Brand;方法与视觉方向需要脱离原型复用时创建 Style;得到品牌中立的可复用结构时创建 Layout;结构带品牌身份,或者包含场景叙事与内容语法时创建 Deck。
这也约束创建模式:只有来源合同本身已经品牌中立且应用中立时,Layout mirror 才成立。删除品牌色、字体、Logo、固定身份对象或可复用应用规则都属于重新创作;越过这条边界的来源要么使用 `standard` / `fidelity` 创作新的 Layout,要么保留这些事实并创建 Deck mirror。
diff --git a/docs/zh/templates-guide.md b/docs/zh/templates-guide.md
index 36674f0c..346d9b51 100644
--- a/docs/zh/templates-guide.md
+++ b/docs/zh/templates-guide.md
@@ -237,12 +237,18 @@ python3 skills/ppt-master/scripts/mirror_template_materialize.py \
"<import_workspace>" "<template_workspace>"
```
-它会先校验 IR manifest、不可变来源 hash、完整原生图谱、可见性事实和
-导入向量闭包,再原子发布按源顺序排列的 SVG roster 及
+它会先校验来源 Slide 的 IR manifest 与不可变 hash、可达原生图谱、
+可见性事实和对应的导入向量闭包,再原子发布按源顺序排列的 SVG roster 及
`icons/imported/`、`images/` 素材。它不要求、也不会把按需生成的
`svg-flat/` 校验视图当成模板来源,并且不会生成 Design Spec;设计角色必须针对物化后的 roster 写入已解析的 spec 路径。
-**Mirror 图谱边界**:mirror 保留完整且受支持的来源 Master/Layout 图谱。它为每张来源 Slide 输出一个完整原型,并为未被任何来源 Slide 使用的 Layout 额外输出一个定义专用的 `layout_<layout_key>.svg`。后者通过独立 Layout roster 注册进 PowerPoint,不会变成发布页面;其父 Master 也随之保留。预检只在必要来源事实或受支持几何缺失时停止,不会仅因 Layout 未使用而停止。
+**Mirror 图谱边界**:mirror 为每张来源 Slide 输出一个完整原型,并只保留该 Slide 引用的 Layout 及其父 Master。SVG 会补齐 Master + Layout + Slide 上下文,同时保留显式层归属。未被任何 Slide 引用的来源 Master/Layout 不由 mirror 物化;`standard` / `fidelity` 可读取完整来源清单,并把有用结构重新创作为 Slide 原型。
+
+Design Spec 对每个输出 Slide 原型按正常 roster 说明。若来源还存在未被引用的 Master/Layout,可用一句范围说明指出它们存在、但未由 mirror 物化,不逐个推断用途。
+
+模板使用以 Slide 为主:生成页面 SVG 已经补齐 Master 与 Layout 视觉,正常创作直接选择完整 Slide 原型;工作区不再存放独立 Master/Layout 定义 SVG。
+
+“只生成 Slide”描述的是可编辑 SVG roster。PPTX 来源的 mirror 仍可携带 `source_themes.json`、`native_payloads.json.gz` 等仅供工具使用的结构 sidecar,用于导出时恢复可达结构的精确 Theme/原生数据;它们不是页面原型,也不进入 AI 创作上下文。
**按 mirror 创建的工作区怎么消费**:从来源到工作区的 `replication_mode: mirror` 是一种能力,不是项目选择。Strategist 会读取真实原型、当前内容和用户明确要求,自动决定选哪些页、哪些重复/跳过/重排,以及采用字面、结构还是仅视觉参考。字面复用时,Executor 复制完整 SVG,只修改允许变更的可见文字,同时保留装饰、精灵图裁剪、几何坐标和规范化结构声明;仍不要求沿用来源页数或页序。
@@ -275,7 +281,7 @@ Brand/Style 的目标不同:两者都让创作内容保持 Slide 本地,因
`exports/<id>_template_preview.pptx` 是 Create Template 按需或按规则生成的审阅证据,不是模板输入;真正生成时始终传工作区根目录。
-Master/Layout 行为以 Microsoft PowerPoint 为验收目标。Keynote、WPS 与 LibreOffice 可以打开 PPTX,但可能归一化模板结构,或在加载包含大量未使用 Layout 的 mirror roster 时明显更慢。
+Master/Layout 行为以 Microsoft PowerPoint 为验收目标。Keynote、WPS 与 LibreOffice 可以打开 PPTX,但可能归一化模板结构。
### 派生后的模板工作区长什么样
@@ -329,7 +335,7 @@ Brand 与 Style 只写 `templates/design_spec.md`(Brand 可带真实身份资
- **模板不是一张不可拆分的“风格皮肤”。** Brand、Style、Layout 与 Deck 有意拆开身份、方向/方法、结构和应用,使每个片段都能单独复用;同时安装多个工作区时,各片段按明确的所有权规则生效
- **模板不会替你做内容决策**。策略师仍然会按内容判断每页用哪个版式、要不要扩展为变体,模板提供候选,不预设结果
- **`fidelity` 模式不等于像素级搬运**。即便是 `literal` 保真,AI 仍会把杂质和不必要的重复结构清理掉——载体保留几何,但不照抄冗余
-- **`mirror` 的目标是受支持范围内的视觉与来源拓扑忠实,不是字节级 OOXML**。它继承源 PPT 的导入限制,只允许固定结构层 group 展开等机械归一化。不支持的原生对象保留可用 SVG fallback 或明确报告;mirror 不归纳替代 ownership。
+- **`mirror` 的目标是受支持范围内的视觉及每张来源 Slide 的可达拓扑忠实,不是字节级 OOXML**。它继承源 PPT 的导入限制,只允许继承补全、固定结构层 group 展开等机械归一化。不支持的原生对象保留可用 SVG fallback 或明确报告;mirror 不归纳替代 ownership。
---
diff --git a/skills/ppt-master/references/executor-structured.md b/skills/ppt-master/references/executor-structured.md
index 182c1608..b5ebb858 100644
--- a/skills/ppt-master/references/executor-structured.md
+++ b/skills/ppt-master/references/executor-structured.md
@@ -18,7 +18,7 @@ Conditional Executor authority for `template_reuse_scope: mirror|layout` with `p
| Current page mapping | Read the retained `spec_lock.md page_layouts` row; a page change does not require another file load |
| Selected prototype SVG | Read the complete `templates/<basename>.svg` once per valid context and reuse it until a known change or context invalidation |
-**Hard rule**: The complete prototype SVG is authoritative. An on-demand page-context result may fingerprint it but carries no prototype payload; never author from a roster, manifest, sidecar, filename, or summary alone.
+**Hard rule**: The complete Slide prototype SVG is authoritative and already resolves its Master + Layout context. Standalone Master/Layout definition SVGs are invalid. An on-demand page-context result may fingerprint the selected Slide prototype but carries no payload; never author from a roster, manifest, sidecar, filename, or summary alone.
Manifest/text-slot files are derived tool metadata, not model inputs. Missing metadata neither invalidates a legacy workspace nor permits text-topology changes.
diff --git a/skills/ppt-master/references/native-data-interface.md b/skills/ppt-master/references/native-data-interface.md
index 271b0b4c..aeeafb4a 100644
--- a/skills/ppt-master/references/native-data-interface.md
+++ b/skills/ppt-master/references/native-data-interface.md
@@ -152,18 +152,29 @@ objects have no marker. Finding one marker somewhere on a page is insufficient.
rg -n 'data-pptx-replace-with="(chart|table)"|<metadata type="application/json">' <project_path>/svg_output/<current_page>.svg
```
-**Table schema**: Native tables are rectangular DrawingML grids. Use `columns`
-for the optional header row and `rows` for body rows; shorter rows are padded
-with blank cells unless `strict_grid: true` is set. Tables may contain at most
-1000 resolved rows and 1000 resolved columns. Use `column_widths` and
-`row_heights` as relative weights. Weight lists must match the resolved grid,
-contain finite non-negative numbers, and include at least one positive value.
-If present, `header_rows` must be an integer from `0` through the resolved row
-count. Write `strict_grid`, `style.band_row`, and cell `bold` as JSON booleans.
-Cell objects accept `text`, `fill`, `color`,
-`align`, `valign`, `bold`, `font_size`, `padding`, `border_color`, and
-`border_width`, plus optional `lang`; the same `padding`, `border_color`,
-`border_width`, and `lang` keys may also live under `style` as table defaults.
+**Table schema — `ppt-master.semantic-table.v2` only**: Every payload requires
+that exact `schema`; unversioned payloads and alternate field spellings fail.
+Native tables are rectangular DrawingML grids. Use `columns` for the optional
+header row and `rows` for body rows; shorter rows are padded unless
+`strict_grid: true`. Tables support at most 1000 resolved rows and columns.
+`column_widths` / `row_heights` are finite non-negative relative weights that
+match the grid and include one positive value. `header_rows` is an integer in
+the resolved row range. `strict_grid`, `style.band_row`, and `bold` are JSON
+booleans.
+
+PPTX import factors exact repetition into `defaults.cell`,
+`defaults.paragraph`, `defaults.run`, and lower-case kebab-case `cell_styles`;
+cells select a style with `cell_style`. Precedence is cell defaults → named
+style → cell fields. Only object-valued `padding` merges by member; `borders`
+and other values replace. Content/topology stays cell-local. This is JSON
+inheritance, not SVG CSS: `<style>` and `class` are forbidden. Export expands
+the payload in memory before validation and DrawingML construction.
+
+Cells accept `text`, `fill`, `fill_opacity`, `color`, `align`, `valign`, `bold`,
+`font_size`, `padding`, canonical side-specific `padding_*`, `border_color`,
+`border_width`, `borders`, `lang`, `anchor_center`, and
+`horizontal_overflow`. Table-wide font/palette/banding/uniform-border policy
+lives under `style`; exact imported defaults live under `defaults.cell`.
For multi-paragraph text, replace cell `text` with a non-empty `paragraphs`
list. Each entry is either a string or an object containing optional
`align: "l|ctr|r"` and exactly one of `text` or non-empty `runs`; empty
@@ -180,11 +191,12 @@ instead of entering either the native payload or an effect-free fallback.
Relationship-bearing text, extensions, structural line breaks, fields, tabs,
bullets, malformed run topology, and unsupported text-body structure remain
fallback-only.
-Per-side cell borders use `borders.left|right|top|bottom`, where each value is
+Per-side cell borders use
+`borders.left|right|top|bottom|diagonal_down|diagonal_up`, where each value is
either `{ "style": "none" }` or
`{ "style": "solid", "color": "#RRGGBB", "width": <positive-px> }`.
-Per-side borders are cell-only; legacy uniform `border_color` / `border_width`
-remain supported as defaults that an individual side may override.
+Per-side borders are cell-only. Uniform `border_color` / `border_width` may live
+on the table style or cell; an explicit side overrides the uniform value.
When `lang` is absent, export derives `zh-CN` for CJK text and `en-US`
otherwise. `style.band_row: false` disables both `<a:tblPr bandRow>` and
materialized alternating row fills. Native table typography mirrors the
diff --git a/skills/ppt-master/references/pptx-structure-interface.md b/skills/ppt-master/references/pptx-structure-interface.md
index 6a474c71..ff39d06f 100644
--- a/skills/ppt-master/references/pptx-structure-interface.md
+++ b/skills/ppt-master/references/pptx-structure-interface.md
@@ -81,6 +81,15 @@ prototype size remain unchanged.
**Hard rule — explicit only**: On a structured `template_reuse_scope: mirror|layout` route, every SVG requires the four root Master/Layout identity attributes. Optional inherited-shape visibility uses only exact lowercase `true` / `false`; other spellings fail, and omission means `true`. Every Master/Layout atom and slot requires a unique stable `id` and is a direct root child. Layouts with zero slots are valid. `data-pptx-layout-kind`, `distilled`, and `utility` are legacy metadata and fail the structured contract. Flat `template_reuse_scope: style`, free-design, and brand-only pages omit the structural markers and visibility attributes; ordinary groups still use the shared `data-pptx-bounds` module contract.
+**Identity is not layer membership**: An SVG `id` identifies one element and
+must be unique inside that SVG document. Any number of direct atoms may repeat
+the same `data-pptx-layer="master"` or `data-pptx-layer="layout"` value; the
+layer attribute, never the `id`, determines ownership. Separate standalone SVG
+pages may repeat the same stable fixed-atom `id` when they declare the same
+Master/Layout contract. Unmarked visual content is Slide-local, except that the
+optional direct solid Slide-background marker below makes one-page background
+ownership explicit.
+
**Layer order**: Author the SVG in PowerPoint paint order: Master background,
Layout background, optional Slide background, remaining Master atoms, remaining Layout atoms,
then slot groups and Slide-local content groups. Backgrounds are a special inheritance
diff --git a/skills/ppt-master/references/shared-standards-core.md b/skills/ppt-master/references/shared-standards-core.md
index 58932b18..cc1e3cc9 100644
--- a/skills/ppt-master/references/shared-standards-core.md
+++ b/skills/ppt-master/references/shared-standards-core.md
@@ -140,6 +140,18 @@ text uses a non-empty `font-family`, a finite positive unitless-px `font-size`,
underline/strike, text outline/alpha, gradient text, or text filter effects.
Unknown or unmapped declarations fail Checker preflight and native export.
+**Hard rule — compact inherited authoring**: Generated SVG expresses shared
+presentation values once at the nearest useful common scope. Put the page's
+common `font-family` on the root `<svg>`; a meaningful `<g>` may override a
+shared value for its subtree. Descendant `<text>` / `<tspan>` and drawing
+elements write only values that differ from their inherited effective value.
+Do not repeat the same font, size, weight, paint, stroke, anchor, or spacing on
+every child for self-containment: root/group inheritance is part of the native
+export contract. Keep true exceptions explicit. Run `compact_svg_styles.py`
+on generated or materialized SVG before its quality gate; this normalization
+does not authorize CSS classes, embedded stylesheets, or any otherwise
+unsupported property.
+
> **`marker-start` / `marker-end` is conditional** — see §1.1.
>
> **`clipPath` on `<image>` is conditional** — see §1.2.
diff --git a/skills/ppt-master/references/strategist-template.md b/skills/ppt-master/references/strategist-template.md
index b65da7d0..d1c8fff5 100644
--- a/skills/ppt-master/references/strategist-template.md
+++ b/skills/ppt-master/references/strategist-template.md
@@ -21,7 +21,7 @@ Conditional extension for applying an installed Brand/Style/Layout/Deck workspac
Immediately before authoring the Stage-2 solution, load each relevant template
resource once per path + SHA and inspect:
-- every installed `design_spec.<kind>.<id>.md`; inspect the actual Page Roster and relevant SVG prototypes from Layout when present, otherwise from Deck;
+- every installed `design_spec.<kind>.<id>.md`; inspect the actual Page Roster and relevant complete Slide prototypes from Layout when present, otherwise from Deck; a mirror scope note about omitted source identities is evidence, not a page-candidate list;
- the Identity, Structure, Reusable Application Context, and Direction / method segment owners, resolved here from the installed set under [`apply-template-workspace`](../workflows/stages/apply-template-workspace.md) §5;
- the confirmed current communication contract, source obligations, planned page count, and content shape of every planned page;
- the user's natural-language instructions, including any page names/numbers or elements they explicitly require.
@@ -36,6 +36,12 @@ Then author one plan that decides all of the following without presenting an opt
For Layout/Deck, template size is evidence, not policy. A short template may use every prototype when the content genuinely fits; a 20–30 page source may contribute only a few suitable pages, or several pages may be reorganized into a new sequence. Never infer that all pages must be kept or that visible sample content is protected merely because it exists in the template. Style and Brand have no prototype set.
+**Hard rule — Slide prototypes drive authoring**: Every template SVG is a
+complete Slide prototype with resolved Master + Layout + Slide context. Use
+these files for `page_layouts`; standalone Master/Layout definition SVGs are
+invalid. An unselected authored Slide prototype may still supply a
+`pptx_layouts` definition, while mirror exposes only actual source Slides.
+
Record the resulting exporter plan internally:
| Internal value | When the authored plan requires it |
@@ -79,11 +85,11 @@ For Style-only or Style + Brand, write `pptx_structure.mode: flat` plus `templat
For `mirror` / `layout`, write `pptx_structure.mode: structured` plus `template_adherence: strict|adaptive`; mirror always writes `strict`. Do not write legacy `baseline`, `template`, `preserve`, `layout_strategy`, or Layout-kind rows.
- **Master roster**: Write one `pptx_masters` row per Master as `<master_key>: <picker name>` and copy the workspace's prototype roster. Keys use 1–64 ASCII letters, digits, dots, underscores, or hyphens, start with a letter/digit, and contain no spaces; human-readable spaces belong only in the picker name. Master visuals are root-level atomic elements and may never be `<g>`.
-- **Reusable Layout roster**: Write every unique Layout once as `<layout_key>: <master_key> | <PowerPoint layout name> | <prototype source>`. Copy installed `template:<basename>` sources, including currently unused Layouts. A new adaptive Layout uses its first generated `P<NN>` as source. Reuse a key only when fixed atoms and slot ids/types/indices/bounds/binding modes are identical. Name authored keys after composition, never page topic. A Layout may intentionally have zero slots; do not manufacture an empty `utility` kind or full-page fake slot.
+- **Reusable Layout roster**: Write every unique Layout once as `<layout_key>: <master_key> | <PowerPoint layout name> | <prototype source>`. Each installed `template:<basename>` source is a complete Slide prototype, including one not selected for the current generated deck. A new adaptive Layout uses its first generated `P<NN>` as source. Reuse a key only when fixed atoms and slot ids/types/indices/bounds/binding modes are identical. Name authored keys after composition, never page topic. A Layout may intentionally have zero slots; do not manufacture an empty `utility` kind or full-page fake slot.
- **Page assignment**: Write exactly one `page_pptx_layouts` row per page. Each key must exist in `pptx_layouts`. Check that distinct compositions do not collapse into role-only keys and that one skeleton does not split into topic-specific keys.
- **Slot planning**: Each reusable slot is a direct root `<g id>` with `data-pptx-placeholder`, positive design-zone bounds, and exactly one compatible direct carrier. Bounds come from the intended safe area, column, panel inset, or media frame—not sample text ink. A genuinely composite region may use only the explicit `object` + `proxy` downgrade.
- **Adaptive refinement**: Initial definitions are complete. If construction shows that reusable framing or slot topology/bounds must change, return to Strategist to add a definition sourced from that page and update its assignment before execution resumes. Executor never mutates or extends the contract; export only compiles declared structure and never discovers or clusters Layouts.
-- **Input prototypes**: Add one `page_layouts` row per page. Strict preserves that SVG's contract; adaptive keeps its Master and may declare a new output Layout; mirror also preserves literal visuals and text-node topology.
+- **Input prototypes**: Add one `page_layouts` row per page using a complete Slide prototype. Strict preserves that SVG's contract; adaptive keeps its Master and may declare a new output Layout; mirror also preserves literal visuals and text-node topology.
**Visualization compatibility**: Use `page_layouts` with optional Chart/Table
`page_visualizations` only when the prototype shell can carry the actual §IX
diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.md
index 6de0558a..96e3e28b 100644
--- a/skills/ppt-master/references/template-designer.md
+++ b/skills/ppt-master/references/template-designer.md
@@ -45,7 +45,7 @@ Input priority for PPTX-backed template creation depends on the AI-derived inter
| Mode | Authoritative inputs | Model-facing inputs |
|---|---|---|
-| `standard` / `fidelity` | Finalized brief for the newly designed output; `analysis/manifest.json` for factual canvas/theme/resources | `authoring-svg/authoring_summary.json`, layered authoring SVGs, optional flat spot checks, and exported resources as visual references. Do not read `authoring_manifest.json`. Source Master/Layout topology is informational only and is not mined into output structure. |
+| `standard` / `fidelity` | Finalized brief for the newly designed output; `analysis/manifest.json` for factual canvas/theme/resources | `authoring-svg/authoring_summary.json`, every layered source Master/Layout as structural and visual evidence, layered source Slides, optional flat spot checks, and exported resources. Do not read `authoring_manifest.json`. `standard` authors a compact result; `fidelity` authors broader useful source-aligned coverage. Neither copies source identities merely because they exist. |
| `mirror` | `analysis/manifest.json`, `analysis/native_structure.json`, and `svg/inheritance.json`; the compiler validates the tool-only authoring manifest | `authoring-svg/authoring_summary.json` plus layered authoring SVGs as the editable preservation IR; optional `authoring-svg-flat/` for complete-page verification; matching lossless `svg/` and optional `svg-flat/` only as immutable backing. |
**Mandatory — authored construction bundle**: As soon as `replication_mode`
@@ -73,10 +73,12 @@ ownership.
| Mode | Output structure contract |
|---|---|
-| `standard` / `fidelity` | Author project-canonical SVG prototypes and an intentional new Master/Layout/slot system. Source visual language and assets may guide the design, but source ownership, keys, picker names, parent relationships, placeholders, and repeated Slide-local elements do not define or seed the output topology. Choose page-fit contours from the full native vocabulary before their authoring forms; keep exact native atoms independent, materialize a Boolean result only where one contour requires it, and use freeform last. |
-| `mirror` | Materialize a new workspace from the validated source graph one-to-one: keep the Master/Layout identities and parentage, slide assignments, placeholder type/index/bounds, and supported visual/native-object facts that are actually present. Edit the authoring IR; materialization may rehydrate converter-supported native payload only for unchanged source refs. Mechanical normalization maps fixed-layer source groups into the direct atoms required by the current explicit SVG contract while preserving ownership, paint order, and appearance; it must not invent missing facts or semantically redesign the graph. |
+| `standard` / `fidelity` | Review the complete source Master/Layout inventory, then author complete project-canonical Slide SVG prototypes and an intentional new Master/Layout/slot system. Every retained Layout has at least one Slide prototype. `standard` stays compact; `fidelity` retains broader useful source-aligned families. Source identities do not define the output topology. Choose page-fit contours from the full native vocabulary before their authoring forms; keep exact native atoms independent, materialize a Boolean result only where one contour requires it, and use freeform last. |
+| `mirror` | Materialize one complete SVG per validated source Slide, retaining only its referenced Layout and parent Master. Keep reachable identities, parentage, assignment, placeholder facts, and supported visual/native facts. Mechanical normalization completes inherited context and maps fixed-layer source groups into direct atoms while preserving ownership, paint order, and appearance; it must not invent missing facts or semantically redesign the reachable graph. |
-Every page remains a complete standalone SVG preview.
+Every output is a complete standalone Slide SVG preview that resolves Master +
+Layout + Slide context. Explicit layer markers retain ownership; standalone
+Master/Layout definition SVGs are not template artifacts.
**Authored preset rule**: In `standard` / `fidelity`, when one registered
PowerPoint preset exactly expresses one complete object, use
@@ -96,20 +98,17 @@ When one preset is insufficient, apply the same reference's compound-page gate:
keep faithful atoms independent unless one contour requires Boolean
materialization, then use freeform only if neither construction succeeds.
-**Hard rule — complete mirror graph**: Preserve every supported source Layout represented by the validated import,
-including Layouts unused by source Slides. Emit one complete source-page
-prototype per source Slide and one definition-only
-`layout_<layout_key>.svg` prototype for each otherwise unrepresented Layout.
-The definition prototype carries the exact parent Master identity, Layout
-identity, fixed atoms, and placeholder contract but is not a generated page.
-This also retains a source Master that is reachable only through unused Layouts.
-Never silently drop or merge an identity, and never invent a carrier page.
+**Hard rule — reachable mirror graph**: Emit exactly one complete source-page
+prototype per source Slide and preserve only the transitive chain `Slide →
+Layout → Master`. Source Master/Layout identities outside that closure remain
+analysis evidence and produce no SVG. Use `standard` / `fidelity` when useful
+unreferenced source structures must be re-authored as complete Slide prototypes.
-**Hard rule — no duplicate authored Layout contracts**: In `standard` / `fidelity`, distinct output Layout keys must differ in fixed Layout atoms or slot topology/type/index/bounds/binding. Topic, sample wording, or Slide-local content alone never justifies another authored key. Mirror keeps source Layout identities even when two source contracts are visibly equivalent.
+**Hard rule — no duplicate authored Layout contracts**: In `standard` / `fidelity`, distinct output Layout keys must differ in fixed Layout atoms or slot topology/type/index/bounds/binding. Topic, sample wording, or Slide-local content alone never justifies another authored key. Mirror keeps distinct reachable source Layout identities even when two source contracts are visibly equivalent.
**Downstream boundary**: Stage 1 independently confirms the current communication contract. Strategist then inspects the installed prototypes, the Deck's descriptive application context, and the current content to author one application plan. It records `mirror`, `layout`, or `style` and, where applicable, `strict` or `adaptive` only as internal exporter values. Explicit user language overrides AI judgment, but the confirmation UI never asks the user to choose these implementation labels. Template_Designer does not preselect that project-level plan.
-For `mirror`, `<design_spec_path> §V` must be followed by a `Source Preservation Map` that records each source slide's Master/Layout assignment and output file. The map is evidence of one-to-one preservation, not a design-decision log. `standard` and `fidelity` record only their newly authored output roster and structure; do not add a source-topology disposition table.
+For `mirror`, `<design_spec_path> §V` must be followed by a `Source Preservation Map` that records each source Slide's retained Master/Layout assignment and output file. When source identities fall outside the reachable closure, one sentence may note that they exist but were not materialized; no per-identity analysis is required. The map is execution evidence, not a design-decision log. `standard` and `fidelity` record only their newly authored output roster and structure.
---
@@ -123,7 +122,7 @@ The output page set is determined by the confirmed natural-language creation int
| `fidelity` | The natural-language intent calls for broader, source-aligned but newly designed coverage | Canonical roles plus intentionally designed variants that cover the useful source composition range |
| `mirror` | The natural-language intent calls for preserving validated native source facts | One SVG prototype materialized from the authoring IR per source slide, named `<NNN>_<page_type>.svg` by source order |
-**Hard rule — mode controls authorship**: `standard` and `fidelity` create new SVG documents and their own Master/Layout system. `mirror` maps the validated imported source contract into a new workspace and must not reauthor, distill, reinterpret, or supplement its structure.
+**Hard rule — mode controls authorship**: `standard` and `fidelity` inspect the complete source structure but create new SVG documents and their own Master/Layout system. `mirror` maps validated source Slides and their reachable structure into a new workspace and must not reauthor, distill, reinterpret, or supplement that closure.
### Standard mode
@@ -170,16 +169,17 @@ When the derived implementation writes `replication_mode: mirror`, materialize a
- Kind eligibility: Create Layout mirror is legal only when the validated source contract is already brand-neutral and application-neutral. If supported source facts retain organization-specific identity or reusable application policy, stop and return to Create Template dispatch: use `standard` / `fidelity` to author a new Layout, or Create Deck to retain those facts. Removing, repainting, retyping, or discarding application rules is never mirror.
- Model-facing authoring source: `authoring-svg/authoring_summary.json`, layered `authoring-svg/*.svg`, `svg/inheritance.json`, and `analysis/native_structure.json`. Do not read `authoring-svg/authoring_manifest.json`; materialization validates it internally. When present, use `authoring-svg-flat/` only for full-page verification. Matching lossless `svg/` and optional `svg-flat/` files are immutable backing; materialization resolves only the layered backing.
-- Precondition: the import evidence identifies every source Master/Layout, parent relationship, picker name, placeholder contract, and fixed visual layer. Stop only when required facts or supported geometry are missing; unused identities are not a stop condition.
-- Output: `<template_workspace>/templates/<NNN>_<page_type>.svg` for every source slide, plus `layout_<layout_key>.svg` for every source Layout unused by all source slides. `<NNN>` is the zero-padded source slide index (3 digits) and `<page_type>` is derived from `analysis/manifest.json` `pageTypeCandidates` — `cover` / `toc` / `chapter` / `content` / `ending`. When the page-type heuristic is ambiguous, fall back to `content`. Preserve source slide order via the numeric prefix; definition-only files are not generated pages.
-- Required preservation: preserve source Master/Layout keys and picker names, Layout-to-Master parentage, slide assignments, placeholder type/index/bounds, supported native-object metadata, geometry, decoration, sprite-sheet wrappers, original example text, chart previews, fonts, effects, and paint order whenever the importer represents them.
-- Allowed normalization: add or normalize explicit root declarations and asset paths, and recursively expand fixed Master/Layout group wrappers into direct atoms. The mapping must remain one-to-one at the ownership level and must not change paint order or appearance.
+- Precondition: the import evidence identifies every source Slide and its referenced Layout/Master, picker names, placeholder contract, and fixed visual layers. Stop when required reachable facts or supported mirrored geometry are missing; unused source identities are out of scope.
+- Output: `<template_workspace>/templates/<NNN>_<page_type>.svg` for every source Slide and no standalone Master/Layout SVG. `<NNN>` is the zero-padded source slide index (3 digits) and `<page_type>` comes from `analysis/manifest.json` `pageTypeCandidates` — `cover` / `toc` / `chapter` / `content` / `ending`, falling back to `content`. Preserve source Slide order.
+- Context completion: each source-page SVG resolves Master + Layout + Slide context while retaining explicit layer markers, so completion does not flatten ownership.
+- Required preservation: within the reachable closure, preserve source Master/Layout keys and picker names, Layout-to-Master parentage, slide assignments, placeholder type/index/bounds, supported native-object metadata, geometry, decoration, sprite-sheet wrappers, original example text, chart previews, fonts, effects, and paint order whenever the importer represents them.
+- Allowed normalization: add or normalize explicit root declarations and asset paths, complete inherited context, and recursively expand fixed Master/Layout group wrappers into direct atoms. The mapping must remain one-to-one at the ownership level and must not change paint order or appearance.
- Forbidden: commonality extraction, semantic synthesis, merging, splitting, promotion, demotion, renaming, re-parenting, decorative simplification, placeholder invention, or replacement of supported source-native metadata / SVG fallback with a model-authored approximation.
-- `<design_spec_path>` §V Page Roster lists every emitted file and marks definition-only prototypes explicitly. `Source Preservation Map` records each source-slide assignment plus every unused Layout definition and its parent Master.
+- `<design_spec_path>` §V gives each emitted source-Slide prototype a roster row. If relevant, one sentence notes source Master/Layout identities outside the mirror closure; `Source Preservation Map` records each retained source-Slide assignment.
**Mirror consumption boundary**: `replication_mode: mirror` describes source-to-workspace fidelity and only makes literal downstream reuse technically possible. Strategist independently derives the application plan from the current communication contract, content, actual prototype roster, and any explicit natural-language instruction. It may select, repeat, skip, reorder, or reorganize prototypes; no internal scope forces source page count, source order, or one output slide per source slide.
-**What mirror is not**: a redesign, topology-cleanup, or recovery mode. It may mechanically transcode the imported representation into the current explicit SVG/package contract, so byte identity is not promised. Charts, SmartArt, OLE objects, and EMF / WMF media that fail to round-trip in `pptx_template_import.py` will fail the same way in mirror. If the import workspace has missing media or unsupported objects, mirror inherits those gaps — report them before materialization begins.
+**What mirror is not**: a redesign, topology-cleanup, or recovery mode. It may mechanically complete inheritance and transcode the imported representation into the current explicit SVG/package contract, so byte identity is not promised. Charts, SmartArt, OLE objects, and EMF / WMF media that fail to round-trip in `pptx_template_import.py` will fail the same way in mirror. If the import workspace has missing media or unsupported objects, mirror inherits those gaps — report them before materialization begins.
---
@@ -260,9 +260,9 @@ page_count: <N>
- Optional XML snippet for any reusable component unique to this template
## V. Page Roster
-One row per emitted SVG describing what this template's version of cover / chapter / content / ending looks like: background treatment, decorative anchors, layout rhythm, image behavior, content density, intended role, reusable slots, and structural capacity. Do not add required/optional/repeatable status or fixed/replaceable/example-only content policy. For `standard` / `fidelity`, record the newly authored Layout key and PowerPoint picker name. For `mirror`, record the preserved source Master/Layout keys and picker names without redesigning them. Roster entries must match the actual SVG files on disk.
+One row per complete Slide SVG describing what this template's version of cover / chapter / content / ending looks like: background treatment, decorative anchors, layout rhythm, image behavior, content density, intended role, reusable slots, and structural capacity. Do not add required/optional/repeatable status or fixed/replaceable/example-only content policy. For `standard` / `fidelity`, record the newly authored Layout key and PowerPoint picker name. For `mirror`, record the preserved reachable Master/Layout keys and picker names without redesigning them. Roster entries must match every SVG on disk.
-For `mirror`, add `### Source Preservation Map` immediately after the roster with columns `Source slide`, `Source Master`, `Source Layout`, `Output SVG`, and `Preservation status`. This is a one-to-one mapping record. Do not add synthesis rationale or source-structure disposition rows to `standard` / `fidelity` templates.
+For `mirror`, add `### Source Preservation Map` immediately after the roster with columns `Source slide`, `Source Master`, `Source Layout`, `Output SVG`, and `Preservation status`. When relevant, add one sentence that unreferenced source identities were not materialized by mirror; do not add individual disposition rows or synthesis rationale. Do not add source-structure disposition rows to `standard` / `fidelity` templates.
## VI. Assets (omit when none)
Logos, cover backgrounds, brand textures bundled with the template package — file name, dimensions, intended usage.
@@ -358,9 +358,9 @@ If PPTX import output exists:
**Precondition**:
-- For `standard`, inspect enough lightweight complete-page IR documents to understand the requested visual direction and reusable assets; do not analyze source topology.
-- For `fidelity`, inspect every lightweight complete-page IR document so the newly designed roster covers the useful source composition range; do not derive output ownership from source Master/Layout recurrence.
-- For `mirror`, verify every authoring Master, Layout, and Slide listed by `authoring_summary.json` against `analysis/native_structure.json` and `svg/inheritance.json`, then materialize from the IR with matching lossless payload backing. The compiler validates each machine-manifest record. Before materialization begins, report the verified source slide indexes.
+- For `standard`, inspect the complete lightweight source Master/Layout inventory plus enough complete-page IR documents to understand the requested visual direction, structural vocabulary, and reusable assets. Author a compact new structure; source identities are evidence, not output requirements.
+- For `fidelity`, inspect every lightweight source Master/Layout and complete-page IR document so the newly designed roster covers the useful source structure and composition range. Author broader source-aligned families without automatically copying every source identity.
+- For `mirror`, verify every source Slide and its referenced Layout/Master against `authoring_summary.json`, `analysis/native_structure.json`, and `svg/inheritance.json`, then materialize only that reachable graph from the IR with matching lossless payload backing. Before materialization begins, report source Slide indexes plus retained and omitted Master/Layout identities.
### 2.1 PPTX Import Mode Rule
@@ -368,9 +368,9 @@ The imported PPTX has a different authority level in each replication mode.
| Mode | Required behavior |
|---|---|
-| `standard` | Use source visuals/assets as references, then author the project-canonical roster and its Master/Layout/slot structure from the confirmed brief. Do not preserve or distill source topology. |
-| `fidelity` | Use the complete visual roster as design reference, then author a broader canonical roster and its own Master/Layout/slot structure. Match the source visual language closely, but do not cluster, merge, or split source Layouts into output families. |
-| `mirror` | Preserve validated source pages, inheritance, placeholders, native objects, and visuals from the lossless import while creating a new workspace. Do not simplify, redesign, rename structure, infer new common structure, or fill gaps. |
+| `standard` | Review the complete source Master/Layout and visual evidence, then author a compact project-canonical roster and its Master/Layout/slot structure from the confirmed brief. Do not preserve source identities merely because they exist. |
+| `fidelity` | Review the complete source Master/Layout and visual roster, then author a broader canonical roster and its own useful source-aligned Master/Layout/slot families. Match the source visual language closely without implying one-to-one identity retention. |
+| `mirror` | Preserve validated source Slides and their reachable inheritance, placeholders, native objects, and visuals while creating a new workspace. Complete each standalone SVG's inherited context, but do not simplify, redesign, rename retained structure, infer new common structure, or fill semantic gaps. |
**Hard rule — mirror materialization is mechanical**: Mirror may normalize namespaces,
portable asset paths, explicit root declarations, and fixed-layer group wrappers
@@ -631,10 +631,10 @@ templates/
- [x] Naming convention applied (standard / fidelity: letter-suffix variants; mirror: `<NNN>_<page_type>.svg`)
- [x] Templates follow design spec (colors, fonts, layout)
- [x] Deck Template Overview and factual Page Roster describe the recurring application and actual prototypes without mandatory use policy; Layout output contains no application or identity contract
-- [x] `standard` / `fidelity` SVGs and Master/Layout contracts were newly authored; `mirror` SVGs were materialized from the authoring IR while preserving the source graph without semantic redesign
+- [x] `standard` / `fidelity` inspected complete source Master/Layout evidence and represented each retained Layout through a newly authored Slide prototype; `mirror` SVGs preserve only source Slides and their reachable structure without semantic redesign
- [x] Placeholder markers are clear and standardized for `standard` / `fidelity`; preview-only sample text remains readable without changing source markers, while mirror preserves literal source text plus source placeholder type/index/bounds
- [x] Every SVG is a complete preview with explicit root Master/Layout identity and `native_structure_mode: structured`; authored modes use canonical fixed layers/slots, while mirror preserves source ownership and mechanically expands fixed-layer groups into direct atoms
-- [x] Authored `standard` / `fidelity` Layout keys are non-duplicative; mirror keeps distinct source Layout identities even when their current visible contracts are equivalent
+- [x] Authored `standard` / `fidelity` Layout keys are non-duplicative; mirror keeps distinct reachable source Layout identities even when their current visible contracts are equivalent
- [x] Template creation used the authoring IR; lossless expanded imports remained immutable payload backing for mirror materialization, while `standard` / `fidelity` used helper-generated compact canonical preset groups and `<design_spec_path>` paint
- [x] Both scopes route bitmaps to `images/` and keep one canonical copy of every imported vector under `icons/imported/`
- [ ] **Next step**: Validate assets, export review evidence when requested or required for multiple Masters, then register only library scope
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 6952752d..2c240a21 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -52,7 +52,7 @@ python3 scripts/update_repo.py
|------|-----------------|---------------|
| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `workflow_log.py`, `workflow_transcript.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py`, `pptx_delivery_check.py` | [docs/project.md](./docs/project.md) |
-| SVG pipeline | `preset_shape_svg.py`, `shape_boolean_svg.py`, `svg_authoring_view.py`, `authoring_roundtrip.py`, `compact_svg_coordinates.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py`, `narration_sync.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native shape authoring](../references/native-shape-authoring.md) |
+| SVG pipeline | `preset_shape_svg.py`, `shape_boolean_svg.py`, `svg_authoring_view.py`, `authoring_roundtrip.py`, `compact_svg_coordinates.py`, `compact_svg_styles.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py`, `narration_sync.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native shape authoring](../references/native-shape-authoring.md) |
| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
| Animation resources | `sound_sync.py` | [sound vocabulary and sync](../templates/sounds/README.md); [docs/pptx-animations.md](./docs/pptx-animations.md) |
@@ -119,6 +119,7 @@ python3 scripts/pptx_template_import.py <template.pptx> --inheritance-mode both
python3 scripts/svg_authoring_view.py <imported-svg-or-dir> -o <output-dir> --projection-kind layered
python3 scripts/svg_authoring_view.py <authoring-dir> --refresh-summary
python3 scripts/compact_svg_coordinates.py <template_workspace>/templates --inplace --keep-native-frames
+python3 scripts/compact_svg_styles.py <template_workspace>/templates --inplace
python3 scripts/mirror_template_materialize.py <import_workspace> <template_workspace>
python3 scripts/svg_to_pptx.py <import_workspace> --roundtrip
python3 scripts/template_preview_pptx.py <template_workspace>
@@ -131,17 +132,20 @@ verification tree is required. No derived narrative digest is generated
because `analysis/manifest.json` already owns those facts.
`svg_authoring_view.py` creates a lightweight, non-destructive editable IR
-bundle from PPTX-imported SVGs. It removes embedded `txbody` payloads,
-duplicate hidden geometry carriers, and import-identity attributes from the
-copy while retaining visible fallback geometry, text, images, stable element
-ids, root Master/Layout markers, selected native-shape intent, and
-document-local `data-pptx-source-ref` values.
+bundle from PPTX-imported SVGs. Recognized native shapes become one visible
+geometry carrier plus at most one structured text body; recognized tables keep
+one compact semantic JSON payload plus a preview cache. The projection removes
+duplicate render geometry and import-only identity/payload attributes while
+retaining text, images, stable ids, root Master/Layout markers, native-shape
+intent, and document-local `data-pptx-source-ref` values. It also promotes a
+common page font to the root and removes inherited presentation declarations
+that merely repeat the root/group value.
Relative local image references are rewritten so the projected copy still
renders from its new location. The bundle's `authoring_summary.json` is the
model-readable current-file index; `authoring_manifest.json` records
source/authoring hashes and object paths for tools without duplicating opaque
-payload and does not enter model context. Round-trip flat bundles also replace
-large source-backed objects with compact `native-restore` image proxies whose
+payload and does not enter model context. Unsupported opaque source objects may
+become compact `native-restore` image proxies whose
hashed SVG previews live under `images/source-object-previews/`. Unchanged
proxies restore the original native PowerPoint objects; complete removal deletes
a Slide-local source object, while inherited-proxy removal and any proxy or
@@ -164,11 +168,18 @@ It consumes only the layered `authoring-svg/` IR as editable input, loads its
tool-only manifest internally, and validates it against immutable `svg/`,
`analysis/native_structure.json`,
`svg/inheritance.json`, `sources/source.pptx`, and any extracted-vector
-inventory, then publishes a complete structured template roster atomically.
+inventory, then publishes a structured Slide roster atomically. Mirror retains
+only the Layout/Master chain reachable from each source Slide. Every output SVG
+resolves Master + Layout + Slide context while keeping layer ownership explicit;
+source identities unused by every Slide produce no SVG.
+For a PPTX-backed mirror, `templates/source_themes.json` carries the exact Theme
+bytes for each retained Master; it is validated tool input, not an SVG prototype
+or model-editing surface.
Unchanged supported Slide-local/slot refs may recover native payload; edited
refs keep their current SVG fallback. Fixed Master/Layout wrappers are expanded
mechanically into direct atoms, source visibility flags become canonical root
-metadata, and imported vectors are copied once to `icons/imported/`. Large
+metadata, and decoration-only imported vectors are copied once to
+`icons/imported/`. Semantic objects remain inline. Large
opaque `txBody`, shape-style, and custom-geometry payloads are deduplicated into
`templates/native_payloads.json.gz`; repeated native restoration attributes
are stored there as short `data-pptx-native-ref` records. Structural metadata
@@ -184,7 +195,7 @@ payloads go to their semantic workspace directories.
The destination must be empty, and the command does not write
`templates/design_spec.md`; Template_Designer owns that authored brief.
-`template_preview_pptx.py` reads a template workspace, exports every public `templates/*.svg` prototype as one structured review slide, and verifies the resulting Master/Layout package. In a project root containing Layout and Deck specs, it previews the active Layout roster. Canonical definition-only `layout_<layout_key>.svg` prototypes are registered as reusable Layouts through internal carrier slides that are removed before publication; they never increase the review deck's visible slide count. This is an on-demand review action: its default output is `exports/<template_id>_template_preview.pptx`, and that directory need not exist before the command runs. It refuses an existing output unless an intentional re-export passes `--force`. `--visual-only` is an explicit migration aid for legacy SVG rosters: it creates a slide-local visual review deck without validating or claiming a reusable Master/Layout contract. This diagnostic path does not require a project `spec_lock.md`; it may retain generic theme/text defaults inside its clean one-Master/one-Layout shell. New structured templates use the default mode when a review deck is requested.
+`template_preview_pptx.py` reads a template workspace, exports every complete `templates/*.svg` Slide prototype as one structured review slide, and verifies the resulting Master/Layout package. In a project root containing Layout and Deck specs, it previews the active Layout roster. Standalone `layout_<layout_key>.svg` definition files are rejected; every reusable Layout must be represented by a complete Slide prototype. This is an on-demand review action: its default output is `exports/<template_id>_template_preview.pptx`, and that directory need not exist before the command runs. It refuses an existing output unless an intentional re-export passes `--force`. `--visual-only` is an explicit migration aid for legacy SVG rosters: it creates a slide-local visual review deck without validating or claiming a reusable Master/Layout contract. This diagnostic path does not require a project `spec_lock.md`; it may retain generic theme/text defaults inside its clean one-Master/one-Layout shell. New structured templates use the default mode when a review deck is requested.
Template fill (direct PPTX, no SVG conversion):
@@ -292,6 +303,7 @@ python3 scripts/extract_svg_assets.py <layered_svg_dir> --icons-dir <icons_dir>
python3 scripts/extract_svg_assets.py <flat_svg_dir> --icons-dir <icons_dir> --icon-namespace imported --reuse-inventory <layered_inventory.json> --inplace --id-prefix flat
python3 scripts/extract_svg_pictures.py "<svg_file>" --select "<group_id>" --resource-root "<workspace>" --images-dir "<picture_assets_dir>" --inplace # optional create-template normalization: one selected group -> one SVG picture
python3 scripts/compact_svg_coordinates.py <template_workspace>/templates --inplace --keep-native-frames
+python3 scripts/compact_svg_styles.py <template_workspace>/templates --inplace
python3 scripts/mirror_template_materialize.py <import_workspace> <template_workspace> # Type A mirror only; destination owns no roster
```
@@ -299,12 +311,18 @@ Round-trip import runs the flat vector extraction automatically after creating
`authoring-svg-flat/`; the manual two-pass commands above remain the
create-template path.
-`extract_svg_assets.py` fingerprints each extracted subtree before generated-ID
-namespacing. Process the layered authoring view first, then pass its inventory to
+`extract_svg_assets.py` extracts only non-semantic decoration. Any subtree that
+contains a semantic object, text, table, chart, relationship, or other
+meaning-bearing authoring content stays inline. Each imported asset and its
+placeholder declare `data-pptx-asset-role="decoration"`; the v2 inventory
+records the same role, and round-trip/template consumers reject missing or
+different roles. The extractor fingerprints each eligible subtree before
+generated-ID namespacing. Process the layered authoring view first, then pass its inventory to
the flat view with `--reuse-inventory`; matching flat subtrees reference the
existing layered asset instead of creating a duplicate file. Only unmatched
flat-only vectors create new assets. Create-template stores these assets once in
-`<workspace>/icons/imported/` and writes `data-icon="imported/<name>"` references.
+`<workspace>/icons/imported/` and writes decoration-marked
+`data-icon="imported/<name>"` references.
Inventories retain any `data-pptx-source-ref` values carried by the extracted
subtree, so re-inlining preserves authoring-manifest object identity.
Rerunning a namespaced pass against an already rewritten projection inventories
@@ -329,11 +347,11 @@ embedded.
For SVG-authoring routes, `svg_output/` is the complete visible page-design source: every exported text, image, shape, background, and template-derived layout element is present in the page SVG or explicitly referenced by it. Export may translate represented content into Master/Layout/Slide parts or native objects, but it does not retrieve missing visible content from templates or planning files. Speaker notes, animation, narration, transitions, `template-fill-pptx`, and `native-enhance-pptx` remain separately owned capabilities.
-Native `svg_to_pptx.py` release export reads the project's explicit structure mode. Free-design, Brand-only, Style-only, and other `template_reuse_scope: style` projects use `flat`, omit Master/Layout mappings and SVG structure metadata, keep every represented object Slide-local, and materialize one clean project-owned Master plus one Blank Layout from the current color/typography lock. Stock content placeholders and unused built-in Layouts are removed; only the standard date/footer/slide-number capability hooks remain. A Deck/Layout application uses `structured` only when Strategist derives `template_reuse_scope: mirror|layout`: each project supplies unique Master/Layout definitions and one Layout assignment per generated page before SVG generation, and every SVG root repeats its assigned identity. A template-backed definition may remain unused and still register without a published carrier slide. Fixed Master/Layout visuals are direct semantic atoms; ordinary groups are invalid there, while one validated compact authored-preset `<g>` is the sole group exception because it compiles to one native shape. Reusable slots are top-level groups with positive design-zone bounds plus one compatible carrier. Composite `object` regions use explicit proxy binding, and zero-slot Layouts are valid.
+Native `svg_to_pptx.py` release export reads the project's explicit structure mode. Free-design, Brand-only, Style-only, and other `template_reuse_scope: style` projects use `flat`, omit Master/Layout mappings and SVG structure metadata, keep every represented object Slide-local, and materialize one clean project-owned Master plus one Blank Layout from the current color/typography lock. Stock content placeholders and unused built-in Layouts are removed; only the standard date/footer/slide-number capability hooks remain. A Deck/Layout application uses `structured` only when Strategist derives `template_reuse_scope: mirror|layout`: each project supplies unique Master/Layout definitions and one Layout assignment per generated page before SVG generation, and every SVG root repeats its assigned identity. An unselected complete template Slide may still supply a reusable Layout definition without becoming a published page. Fixed Master/Layout visuals are direct semantic atoms; ordinary groups are invalid there, while one validated compact authored-preset `<g>` is the sole group exception because it compiles to one native shape. Reusable slots are top-level groups with positive design-zone bounds plus one compatible carrier. Composite `object` regions use explicit proxy binding, and zero-slot Layouts are valid.
Structured template export compiles only the declared structure, maps locked typography/colors into PowerPoint defaults, creates the named Master/Layout parts, and reads the package back before publication. It never clusters pages, promotes repeated chrome heuristically, or invents placeholders. Flat export is the normal free-design/Brand-only/Style-only/style-scope route: it creates only the clean project-owned shell and performs no promotion or deduplication of Slide content.
-Template `page_layouts` records authoring-input provenance, `pptx_masters` / `pptx_layouts` own unique reusable definitions, and `page_pptx_layouts` owns page assignment. Strict preserves its Master/Layout/slot contract; adaptive retains its Master and may use a new Layout key only when fixed Layout atoms or slot topology/bounds change. `standard` / `fidelity` author new SVGs and a new Master/Layout/slot contract. `mirror` materializes a new workspace from the complete validated source identity graph—including unused Layout definitions—without semantic synthesis or gap filling, while mechanically expanding fixed-layer group wrappers into the direct atoms required by the structured contract.
+Template `page_layouts` records authoring-input provenance, `pptx_masters` / `pptx_layouts` own unique reusable definitions, and `page_pptx_layouts` owns page assignment. Strict preserves its Master/Layout/slot contract; adaptive retains its Master and may use a new Layout key only when fixed Layout atoms or slot topology/bounds change. `standard` / `fidelity` inspect complete source structure evidence and author compact or broader useful Slide rosters. `mirror` materializes source Slides and their reachable identity graph without semantic synthesis or gap filling, while completing inherited context and mechanically expanding fixed-layer group wrappers into direct atoms.
Legacy structured/template contracts using `baseline`, `template`, `preserve`, `layout_strategy`, `data-pptx-layout-kind`, `distilled`/`utility`, direct atomic placeholders, or incomplete root Master identity must be replaced by a new workspace created through [`create-template`](../workflows/create-template.md). Generate new structured SVG pages from that workspace; do not upgrade the existing PPTX/SVG in place. Explicit flat free-design/Brand-only/Style-only projects intentionally omit root Master identity.
diff --git a/skills/ppt-master/scripts/authoring_roundtrip.py b/skills/ppt-master/scripts/authoring_roundtrip.py
index a43f2470..f99bf68f 100644
--- a/skills/ppt-master/scripts/authoring_roundtrip.py
+++ b/skills/ppt-master/scripts/authoring_roundtrip.py
@@ -29,7 +29,12 @@ from typing import Any
from urllib.parse import unquote, urlsplit, urlunsplit
from xml.etree import ElementTree as ET
-from extract_svg_assets import extract_file
+from extract_svg_assets import (
+ ASSET_ROLE_ATTRIBUTE,
+ DECORATION_ASSET_ROLE,
+ VECTOR_INVENTORY_SCHEMA,
+ extract_file,
+)
from pptx_workspace import ROUNDTRIP_MANIFEST_PATH
from slide_roster import discover_slide_svgs
from svg_authoring_view import (
@@ -47,7 +52,6 @@ from svg_compatibility import normalize_single_child_group_filters
SVG_NS = "http://www.w3.org/2000/svg"
XLINK_NS = "http://www.w3.org/1999/xlink"
-VECTOR_INVENTORY_SCHEMA = "vector_asset_inventory.v1"
IMPORTED_ICON_NAMESPACE = "imported"
_URL_ID_RE = re.compile(r"url\(\s*(['\"]?)#([^)'\"\s]+)\1\s*\)")
_PRESERVED_EFFECT_ATTRIBUTES = frozenset({
@@ -484,6 +488,10 @@ def _load_current_assets(
raise AuthoringRoundtripError(
"Flat authoring vector inventory must use icon_namespace='imported'"
)
+ if inventory.get("asset_role") != DECORATION_ASSET_ROLE:
+ raise AuthoringRoundtripError(
+ "Flat authoring vector inventory must use asset_role='decoration'"
+ )
assets_raw = inventory.get("assets")
if not isinstance(assets_raw, list):
raise AuthoringRoundtripError("Vector inventory assets must be an array")
@@ -506,6 +514,10 @@ def _load_current_assets(
raise AuthoringRoundtripError(
f"vector assets[{index}] is missing a required string field"
)
+ if raw.get("role") != DECORATION_ASSET_ROLE:
+ raise AuthoringRoundtripError(
+ f"vector assets[{index}] is not a decoration asset"
+ )
icon = str(values["icon"])
origin = str(values["svg"])
if icon in records:
@@ -521,6 +533,16 @@ def _load_current_assets(
)
if not asset_path.is_file() or asset_path.suffix.lower() != ".svg":
raise AuthoringRoundtripError(f"Vector asset is missing: {asset_path}")
+ try:
+ asset_root = ET.parse(asset_path).getroot()
+ except ET.ParseError as exc:
+ raise AuthoringRoundtripError(
+ f"Vector asset is invalid SVG XML: {asset_path}: {exc}"
+ ) from exc
+ if asset_root.get(ASSET_ROLE_ATTRIBUTE) != DECORATION_ASSET_ROLE:
+ raise AuthoringRoundtripError(
+ f"Vector asset is not declared as decoration: {asset_path}"
+ )
records[icon] = VectorAssetRecord(
icon=icon,
asset_path=asset_path,
@@ -554,8 +576,22 @@ def _baseline_assets(
raise AuthoringRoundtripError(
f"Generated baseline vector asset {index} is incomplete"
)
+ if raw.get("role") != DECORATION_ASSET_ROLE:
+ raise AuthoringRoundtripError(
+ f"Generated baseline vector asset {index} is not decoration"
+ )
icon = str(values["icon"])
asset_path = icons_root / str(values["asset"])
+ try:
+ asset_root = ET.parse(asset_path).getroot()
+ except ET.ParseError as exc:
+ raise AuthoringRoundtripError(
+ f"Generated baseline vector asset is invalid: {asset_path}: {exc}"
+ ) from exc
+ if asset_root.get(ASSET_ROLE_ATTRIBUTE) != DECORATION_ASSET_ROLE:
+ raise AuthoringRoundtripError(
+ f"Generated baseline vector asset lacks decoration role: {asset_path}"
+ )
actual_sha = _sha256_file(asset_path)
records[icon] = VectorAssetRecord(
icon=icon,
@@ -611,6 +647,10 @@ def _generate_baseline_bundle(
raise AuthoringRoundtripError(
"Flat vector inventory must use icon_namespace='imported'"
)
+ if inventory.get("asset_role") != DECORATION_ASSET_ROLE:
+ raise AuthoringRoundtripError(
+ "Flat vector inventory must use asset_role='decoration'"
+ )
baseline_icons = baseline_root / "_baseline_icons"
entries: list[dict[str, Any]] = []
for document in sorted(documents.values(), key=lambda item: item.name):
@@ -729,6 +769,14 @@ def _referenced_assets(
icon = (element.get("data-icon") or "").strip()
if not icon or icon in referenced:
continue
+ if (
+ icon.startswith(f"{IMPORTED_ICON_NAMESPACE}/")
+ and element.get(ASSET_ROLE_ATTRIBUTE) != DECORATION_ASSET_ROLE
+ ):
+ raise AuthoringRoundtripError(
+ f"{document_name} imported vector {icon!r} is not marked "
+ "as decoration"
+ )
record = assets.get(icon)
if record is None:
if icon.startswith(f"{IMPORTED_ICON_NAMESPACE}/"):
diff --git a/skills/ppt-master/scripts/compact_svg_styles.py b/skills/ppt-master/scripts/compact_svg_styles.py
new file mode 100644
index 00000000..d845f57f
--- /dev/null
+++ b/skills/ppt-master/scripts/compact_svg_styles.py
@@ -0,0 +1,420 @@
+#!/usr/bin/env python3
+"""
+PPT Master - SVG Inherited Style Compactor
+
+Normalize generated SVG authoring files to root/group defaults plus local
+overrides. The compactor promotes one common page font to the SVG root and
+removes presentation declarations that repeat an inherited value.
+
+Usage:
+ python3 scripts/compact_svg_styles.py <svg-file-or-directory> [--inplace]
+
+Examples:
+ python3 scripts/compact_svg_styles.py projects/example/svg_output --inplace
+ python3 scripts/compact_svg_styles.py imported/authoring-svg-flat
+
+Dependencies:
+ None (standard library only).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import stat
+import sys
+import tempfile
+from collections import Counter
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+from xml.etree import ElementTree as ET
+
+from console_encoding import configure_utf8_stdio
+from svg_to_pptx.drawingml.utils import INHERITABLE_ATTRS
+
+configure_utf8_stdio()
+
+SVG_NS = "http://www.w3.org/2000/svg"
+INHERITABLE_ATTRIBUTES = tuple(INHERITABLE_ATTRS)
+_DEFINITION_SUBTREES = frozenset({
+ "clipPath",
+ "defs",
+ "filter",
+ "linearGradient",
+ "marker",
+ "mask",
+ "pattern",
+ "radialGradient",
+ "symbol",
+})
+
+ET.register_namespace("", SVG_NS)
+
+
+@dataclass
+class StyleCompactionStats:
+ """Count semantics-preserving authoring-style reductions."""
+
+ root_font_defaults: int = 0
+ root_style_declarations_normalized: int = 0
+ shadowed_attributes_removed: int = 0
+ redundant_attributes_removed: int = 0
+ redundant_style_declarations_removed: int = 0
+
+ @property
+ def changed_declarations(self) -> int:
+ return (
+ self.root_font_defaults
+ + self.root_style_declarations_normalized
+ + self.shadowed_attributes_removed
+ + self.redundant_attributes_removed
+ + self.redundant_style_declarations_removed
+ )
+
+ def merge(self, other: "StyleCompactionStats") -> None:
+ self.root_font_defaults += other.root_font_defaults
+ self.root_style_declarations_normalized += (
+ other.root_style_declarations_normalized
+ )
+ self.shadowed_attributes_removed += other.shadowed_attributes_removed
+ self.redundant_attributes_removed += other.redundant_attributes_removed
+ self.redundant_style_declarations_removed += (
+ other.redundant_style_declarations_removed
+ )
+
+ def as_dict(self) -> dict[str, int]:
+ return {
+ "root_font_defaults": self.root_font_defaults,
+ "root_style_declarations_normalized": (
+ self.root_style_declarations_normalized
+ ),
+ "shadowed_attributes_removed": self.shadowed_attributes_removed,
+ "redundant_attributes_removed": self.redundant_attributes_removed,
+ "redundant_style_declarations_removed": (
+ self.redundant_style_declarations_removed
+ ),
+ "changed_declarations": self.changed_declarations,
+ }
+
+
+@dataclass(frozen=True)
+class _StyleDeclaration:
+ raw: str
+ name: str
+ value: str
+
+
+def _local_name(name: object) -> str:
+ return name.rsplit("}", 1)[-1] if isinstance(name, str) else ""
+
+
+def _style_declarations(value: str | None) -> list[_StyleDeclaration] | None:
+ if value is None:
+ return []
+ declarations: list[_StyleDeclaration] = []
+ for raw in value.split(";"):
+ stripped = raw.strip()
+ if not stripped:
+ continue
+ if ":" not in stripped:
+ return None
+ raw_name, raw_value = stripped.split(":", 1)
+ name = raw_name.strip().lower()
+ normalized_value = raw_value.strip()
+ if not name or not normalized_value:
+ return None
+ declarations.append(
+ _StyleDeclaration(
+ raw=stripped,
+ name=name,
+ value=normalized_value,
+ )
+ )
+ return declarations
+
+
+def _style_values(
+ declarations: list[_StyleDeclaration],
+) -> dict[str, str]:
+ return {
+ declaration.name: declaration.value
+ for declaration in declarations
+ }
+
+
+def _write_style(
+ element: ET.Element,
+ declarations: list[_StyleDeclaration],
+) -> None:
+ if declarations:
+ element.set("style", ";".join(item.raw for item in declarations))
+ else:
+ element.attrib.pop("style", None)
+
+
+def _effective_value(
+ element: ET.Element,
+ name: str,
+ parents: dict[ET.Element, ET.Element],
+ cache: dict[tuple[int, str], str | None],
+) -> str | None:
+ key = (id(element), name)
+ if key in cache:
+ return cache[key]
+ declarations = _style_declarations(element.get("style"))
+ if declarations is None:
+ cache[key] = None
+ return None
+ style_value = _style_values(declarations).get(name)
+ if style_value is not None:
+ cache[key] = style_value
+ return style_value
+ attribute_value = element.get(name)
+ if attribute_value is not None:
+ cache[key] = attribute_value
+ return attribute_value
+ parent = parents.get(element)
+ resolved = (
+ _effective_value(parent, name, parents, cache)
+ if parent is not None
+ else None
+ )
+ cache[key] = resolved
+ return resolved
+
+
+def _normalize_root_font_family(
+ root: ET.Element,
+ stats: StyleCompactionStats,
+) -> None:
+ declarations = _style_declarations(root.get("style"))
+ if declarations is None:
+ return
+ style_values = _style_values(declarations)
+ style_family = style_values.get("font-family")
+ if style_family is not None:
+ root.set("font-family", style_family)
+ retained = [
+ item for item in declarations
+ if item.name != "font-family"
+ ]
+ _write_style(root, retained)
+ stats.root_style_declarations_normalized += 1
+ return
+ if root.get("font-family") is not None:
+ return
+
+ parents = {
+ child: parent
+ for parent in root.iter()
+ for child in parent
+ }
+
+ def inside_definition(element: ET.Element) -> bool:
+ current = parents.get(element)
+ while current is not None:
+ if _local_name(current.tag) in _DEFINITION_SUBTREES:
+ return True
+ current = parents.get(current)
+ return False
+
+ text_elements = [
+ element
+ for element in root.iter()
+ if _local_name(element.tag) == "text"
+ and "".join(element.itertext()).strip()
+ and not inside_definition(element)
+ ]
+ if not text_elements:
+ return
+ cache: dict[tuple[int, str], str | None] = {}
+ families = [
+ _effective_value(
+ element,
+ "font-family",
+ parents,
+ cache,
+ )
+ for element in text_elements
+ ]
+ if any(family is None or not family.strip() for family in families):
+ return
+ counts = Counter(str(family) for family in families)
+ common = min(
+ counts,
+ key=lambda family: (-counts[family], len(family), family),
+ )
+ root.set("font-family", common)
+ stats.root_font_defaults += 1
+
+
+def _remove_redundant_inherited_styles(
+ element: ET.Element,
+ inherited: dict[str, str],
+ stats: StyleCompactionStats,
+) -> None:
+ if _local_name(element.tag) in _DEFINITION_SUBTREES:
+ return
+ declarations = _style_declarations(element.get("style"))
+ if declarations is None:
+ return
+ style_values = _style_values(declarations)
+ remove_style_names: set[str] = set()
+ effective = dict(inherited)
+
+ for name in INHERITABLE_ATTRIBUTES:
+ style_value = style_values.get(name)
+ attribute_value = element.get(name)
+ if style_value is not None:
+ if attribute_value is not None:
+ element.attrib.pop(name, None)
+ stats.shadowed_attributes_removed += 1
+ if style_value == inherited.get(name):
+ remove_style_names.add(name)
+ stats.redundant_style_declarations_removed += sum(
+ item.name == name for item in declarations
+ )
+ else:
+ effective[name] = style_value
+ continue
+ if attribute_value is None:
+ continue
+ if attribute_value == inherited.get(name):
+ element.attrib.pop(name, None)
+ stats.redundant_attributes_removed += 1
+ else:
+ effective[name] = attribute_value
+
+ if remove_style_names:
+ _write_style(
+ element,
+ [
+ item for item in declarations
+ if item.name not in remove_style_names
+ ],
+ )
+ for child in element:
+ _remove_redundant_inherited_styles(child, effective, stats)
+
+
+def compact_svg_style_tree(root: ET.Element) -> StyleCompactionStats:
+ """Compact inherited declarations without changing effective SVG styles."""
+ if _local_name(root.tag) != "svg":
+ raise ValueError("Style compaction requires an SVG root element")
+ stats = StyleCompactionStats()
+ _normalize_root_font_family(root, stats)
+ _remove_redundant_inherited_styles(root, {}, stats)
+ return stats
+
+
+def _svg_files(input_path: Path) -> list[Path]:
+ if input_path.is_file():
+ return [input_path] if input_path.suffix.lower() == ".svg" else []
+ return sorted(
+ path for path in input_path.rglob("*.svg")
+ if path.is_file()
+ )
+
+
+def _compact_svg_bytes(
+ path: Path,
+) -> tuple[bytes, StyleCompactionStats]:
+ original = path.read_bytes()
+ parser = ET.XMLParser(
+ target=ET.TreeBuilder(insert_comments=True, insert_pis=True),
+ )
+ root = ET.fromstring(original, parser=parser)
+ stats = compact_svg_style_tree(root)
+ if stats.changed_declarations == 0:
+ return original, stats
+ payload = ET.tostring(
+ root,
+ encoding="utf-8",
+ xml_declaration=original.lstrip().startswith(b"<?xml"),
+ )
+ if not payload.endswith(b"\n"):
+ payload += b"\n"
+ return payload, stats
+
+
+def _write_atomic(path: Path, payload: bytes) -> None:
+ mode = stat.S_IMODE(path.stat().st_mode)
+ with tempfile.NamedTemporaryFile(
+ mode="wb",
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ dir=path.parent,
+ delete=False,
+ ) as handle:
+ temporary_path = Path(handle.name)
+ handle.write(payload)
+ try:
+ temporary_path.chmod(mode)
+ os.replace(temporary_path, path)
+ except OSError:
+ temporary_path.unlink(missing_ok=True)
+ raise
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Promote a common page font and remove redundant inherited SVG "
+ "presentation declarations."
+ ),
+ )
+ parser.add_argument("input", type=Path, help="SVG file or directory")
+ parser.add_argument(
+ "--inplace",
+ action="store_true",
+ help="Atomically replace changed SVG files",
+ )
+ return parser
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ args = build_parser().parse_args(argv)
+ input_path = args.input.resolve()
+ svg_files = _svg_files(input_path)
+ if not svg_files:
+ print(f"[ERROR] No SVG files found: {input_path}", file=sys.stderr)
+ return 1
+
+ prepared: list[tuple[Path, bytes, StyleCompactionStats]] = []
+ total = StyleCompactionStats()
+ try:
+ for path in svg_files:
+ payload, stats = _compact_svg_bytes(path)
+ prepared.append((path, payload, stats))
+ total.merge(stats)
+ except (OSError, ET.ParseError, ValueError) as exc:
+ print(f"[ERROR] SVG style compaction failed: {exc}", file=sys.stderr)
+ return 1
+
+ changed_files = 0
+ if args.inplace:
+ for path, payload, _stats in prepared:
+ if payload == path.read_bytes():
+ continue
+ _write_atomic(path, payload)
+ changed_files += 1
+ else:
+ changed_files = sum(
+ payload != path.read_bytes()
+ for path, payload, _stats in prepared
+ )
+
+ print(json.dumps({
+ "input": str(input_path),
+ "inplace": bool(args.inplace),
+ "file_count": len(prepared),
+ "changed_files": changed_files,
+ "styles": total.as_dict(),
+ }, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/docs/multilingual-text-smoke.md b/skills/ppt-master/scripts/docs/multilingual-text-smoke.md
index 00ff9fae..73af1c79 100644
--- a/skills/ppt-master/scripts/docs/multilingual-text-smoke.md
+++ b/skills/ppt-master/scripts/docs/multilingual-text-smoke.md
@@ -205,6 +205,7 @@ with TemporaryDirectory(prefix="ppt-master-multilingual-smoke-") as tmp:
marker,
context,
{
+ "schema": "ppt-master.semantic-table.v2",
"x": 10,
"y": 10,
"width": 600,
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 01779c74..ecc4f5bb 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -34,26 +34,28 @@ output directory contains the editable SVGs, one model-readable
The projected copy:
-- removes embedded `txbody` metadata;
-- removes hidden native geometry carriers while retaining and unwrapping their
- visible preview geometry;
-- removes source-object identity/style/hash attributes that are only useful to
- an exact import round trip;
-- keeps visible paths, text, images, stable ids, Master/Layout root markers,
- selected native-shape intent, and a document-local `data-pptx-source-ref` on
+- translates each recognized native shape into one visible geometry carrier
+ plus at most one structured text body;
+- translates each recognized native table into one inline
+ `ppt-master.semantic-table.v2` payload with table/cell/run defaults and named
+ cell styles, plus an external authoring-preview cache;
+- removes duplicate render geometry, embedded `txbody`, and import-only
+ identity/style/hash payloads;
+- keeps visible semantic paths, text, images, stable ids, Master/Layout root
+ markers, native-shape intent, and a document-local `data-pptx-source-ref` on
each imported logical object;
- rewrites relative local asset references for the projection's new location;
-- compacts imported model-facing frames and safe transform page coordinates to
- at most two decimals.
+- compacts model-facing coordinates, promotes a common page font to the root,
+ and removes descendant presentation declarations equal to inherited values.
Round-trip publication applies two object-level compactions after projection:
-- text-free vector decorations that cross the readability threshold move to
- editable `icons/imported/*.svg` assets; the page retains one compact
- `<use data-icon="imported/...">`, and
- `authoring-svg-flat_vector_asset_inventory.json` reconnects its source refs;
-- large semantic/native-payload objects that cannot safely become editable
- vector assets become
+- non-semantic vector decorations that cross the readability threshold may
+ move to `icons/imported/*.svg`; the asset, placeholder, and v2 inventory all
+ declare the fixed `decoration` role. Any subtree containing semantic
+ authoring content remains inline;
+- unsupported opaque source objects that do not yet have a closed semantic IR
+ may become
`<image data-pptx-source-proxy="native-restore">` references whose hashed SVG
previews live under `images/source-object-previews/`.
@@ -78,7 +80,7 @@ the complete imported SVG remains immutable native-payload backing. Final
`templates/*.svg` files are materialized and validated from that pair. A
complete-page `authoring-svg-flat/` bundle is the user's editable source for an
imported-deck round-trip. `pptx_to_svg.py --roundtrip` places image media in
-`images/`, vectors in `icons/imported/`, cues/audio/video/notes in their named
+`images/`, decoration-only vectors in `icons/imported/`, cues/audio/video/notes in their named
directories, opaque payloads in `native-payloads/`, the source package in
`sources/`, and tool-owned backing/contracts in `analysis/`; `assets/` is
invalid. `svg_to_pptx.py --roundtrip` always reads `authoring-svg-flat/`,
@@ -373,6 +375,31 @@ or matrix `a/b/c/d` coefficients. Type A mirror materialization invokes the
same compactor before native-record externalization; `standard` and `fidelity`
use the shared final pass before template validation.
+## `compact_svg_styles.py`
+
+Normalize generated authoring SVG to shared root/group defaults plus local
+overrides:
+
+```bash
+python3 scripts/compact_svg_styles.py <svg-file-or-directory>
+python3 scripts/compact_svg_styles.py <svg-file-or-directory> --inplace
+```
+
+The default run reports proposed changes without writing. `--inplace` prepares
+the complete input set first and then atomically replaces changed files. When
+every rendered `<text>` has a resolvable typeface, the most common page
+`font-family` becomes one root declaration. Descendants retain only true
+exceptions. The same pass removes any supported inheritable presentation
+attribute or inline declaration that exactly repeats its effective parent
+value; it never invents a paint, size, weight, or other non-font default.
+
+Default Generate runs it before the first-page and final checks, Quick runs it
+before its final check, and Create Template runs it before structured-template
+validation. PPTX import projections and mirror materialization call the same
+tree-level implementation directly. SVG-to-PPTX continues to accept valid
+explicit declarations; this is the canonical generated-authoring form, not a
+compatibility restriction on external SVG input.
+
## `extract_svg_assets.py`
Factor large vector subtrees out of lightweight authoring IR documents and
@@ -399,10 +426,14 @@ asset's internal ids. The second pass reuses a fingerprint-matched asset and
writes no duplicate SVG file. Unmatched flat-only subtrees still extract
normally. Use `--clean-stale` on both import-workspace passes to remove stale
generated files for their respective prefixes. In create-template workspaces,
-`imported` is the fixed namespace: assets live once under `icons/imported/`, and
-the working SVGs reference them as `data-icon="imported/<name>"`. Inventory
-entries retain source refs from each extracted subtree, allowing expansion to
-reconnect the authoring-manifest mapping. A rerun on an
+`imported` is the fixed decoration-only namespace: assets live once under
+`icons/imported/`, and the working SVGs reference them as
+`data-icon="imported/<name>"`. Each asset root and placeholder declares
+`data-pptx-asset-role="decoration"`; the v2 inventory repeats that role. The
+extractor and both consumers fail closed if a semantic marker or semantic
+descendant crosses this boundary. Inventory entries may retain source refs from
+eligible decoration subtrees, allowing expansion to reconnect the
+authoring-manifest mapping. A rerun on an
already rewritten namespaced projection inventories those references and does
not progressively extract their remaining parent or sibling geometry. An
in-place pass over an authoring bundle refreshes `authoring_summary.json`
@@ -421,8 +452,8 @@ python3 scripts/mirror_template_materialize.py \
The command treats `<import_workspace>/authoring-svg/` as the sole editable
source. It reads the tool-only layered authoring manifest internally and
validates it against immutable lossless SVG
-hashes, source PPTX hash, complete Master/Layout/Slide graph, inheritance
-visibility facts, source-ref closure, and extracted-vector inventory before it
+hashes, source PPTX hash, the source Slide roster and reachable Master/Layout
+graph, inheritance visibility facts, source-ref closure, and extracted-vector inventory before it
writes anything. It accepts an absent/empty destination or a project
`templates/` containing unique qualified Brand/Style specs plus, for a
Layout-over-Deck transition, one qualified Deck spec with no staged roster. A
@@ -432,8 +463,15 @@ new Layout or Deck must be composed with the other structural kind. It stages th
result before atomic publication, so a failed preflight cannot leave a partial
template.
-Materialization preserves source page order and emits one definition-only
-`layout_<layout_key>.svg` for every source Layout unused by all source Slides.
+Materialization preserves source Slide order and only the Layout/Master chains
+reachable from those Slides. Each source Slide becomes one standalone prototype
+with Master + Layout + Slide context resolved. Explicit layer markers preserve
+ownership; source Master/Layout identities unused by every Slide produce no SVG.
+The v2 report lists source counts plus retained and omitted structure keys.
+For PPTX-backed mirror input, `templates/source_themes.json` stores the exact
+Theme bytes keyed by retained Master. Structured export validates that sidecar
+against the Master roster and installs one Theme per Master; it is not an SVG
+prototype or page-authoring input.
It mechanically expands fixed Master/Layout group wrappers into direct atoms,
rehydrates only unchanged converter-supported Slide-local/slot refs, keeps the
current SVG fallback for edited refs, preserves explicit text hard breaks, and
@@ -470,7 +508,7 @@ structured export validate output attributes, text/tspan topology, and
referenced-resource hashes against
the prototype.
-The output routes reusable vectors once to `icons/imported/`, image media to
+The output routes reusable decoration vectors once to `icons/imported/`, image media to
`images/`, audio and video to their semantic directories, and opaque referenced
files to `native-payloads/imported/`. The JSON report
reports payload occurrence, native-record, unique-byte, and compressed-store
diff --git a/skills/ppt-master/scripts/extract_svg_assets.py b/skills/ppt-master/scripts/extract_svg_assets.py
index 0c35340d..6373050e 100644
--- a/skills/ppt-master/scripts/extract_svg_assets.py
+++ b/skills/ppt-master/scripts/extract_svg_assets.py
@@ -2,16 +2,15 @@
"""
PPT Master - Large Vector Asset Extractor
-Factor large inline vector groups (complex illustrations) out of working SVGs
-into project icon assets, leaving a one-line `<use data-icon="namespace/id"/>`
-placeholder behind — so the working SVG stays readable (structure, not a wall of
-`<path>`). Visually lossless and reversible: the existing icon embedding path
-re-inlines each asset before export, so the exported PPTX remains native shapes,
-not an embedded picture.
+Factor large non-semantic vector decorations out of working SVGs into project
+icon assets, leaving a compact decoration-marked `<use data-icon>` placeholder
+behind. Semantic objects and semantic descendants always remain inline. The
+existing icon embedding path re-inlines each asset before export, so the
+exported PPTX remains native shapes rather than an embedded picture.
-Because re-inlining restores the extracted vector subtree, the detection
-threshold is a readability convenience — it changes which blobs are factored
-out, not whether the export stays editable.
+Because re-inlining restores the extracted decoration subtree, the detection
+threshold is a readability convenience. It never expands the eligible asset
+role beyond decoration.
Usage:
python3 scripts/extract_svg_assets.py <svg_dir> [options]
@@ -47,8 +46,13 @@ from urllib.parse import urlsplit, urlunsplit
from xml.etree import ElementTree as ET
from console_encoding import configure_utf8_stdio
+from pptx_shapes import (
+ NATIVE_FALLBACK_SHA256_ATTR,
+ svg_native_fallback_fingerprint,
+)
from svg_authoring_view import (
AUTHORING_MANIFEST_NAME,
+ SEMANTIC_OBJECT_ATTRIBUTE,
write_authoring_summary,
)
@@ -62,8 +66,12 @@ DEFAULT_MIN_DRAWABLES = 20
DEFAULT_MIN_BYTES = 3000
DEFAULT_MIN_DECORATION_BYTES = 3000
SOURCE_REF_ATTRIBUTE = "data-pptx-source-ref"
+ASSET_ROLE_ATTRIBUTE = "data-pptx-asset-role"
+DECORATION_ASSET_ROLE = "decoration"
+VECTOR_INVENTORY_SCHEMA = "vector_asset_inventory.v2"
ICON_NAMESPACE_RE = re.compile(r"^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$")
URL_REF_RE = re.compile(r"url\(\s*(['\"]?)#([^)'\"]\S*?)\1\s*\)")
+_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
def _local(tag: object) -> str:
@@ -92,6 +100,14 @@ def _has_semantic_content(elem: ET.Element) -> bool:
return any(_local(e.tag) in SEMANTIC_CONTENT for e in elem.iter())
+def _has_semantic_object(elem: ET.Element) -> bool:
+ """Semantic authoring objects must never move into imported decoration."""
+ return any(
+ item.get(SEMANTIC_OBJECT_ATTRIBUTE) is not None
+ for item in elem.iter()
+ )
+
+
def _is_existing_placeholder(elem: ET.Element) -> bool:
return _local(elem.tag) == "use" and elem.get("data-icon") is not None
@@ -104,6 +120,7 @@ def _is_extractable_subtree(elem: ET.Element) -> bool:
"""Pure vector subtrees can be moved; semantic content must stay inline."""
if (
_local(elem.tag) in DEFINITION_CONTAINERS
+ or _has_semantic_object(elem)
or _has_icon_placeholder(elem)
or _is_chart_group(elem)
or _has_semantic_content(elem)
@@ -331,7 +348,10 @@ def _find_extractable(root: ET.Element, min_drawables: int, min_bytes: int) -> l
found: list[ET.Element] = []
def walk(elem: ET.Element) -> None:
- if _local(elem.tag) in DEFINITION_CONTAINERS:
+ if (
+ _local(elem.tag) in DEFINITION_CONTAINERS
+ or elem.get(SEMANTIC_OBJECT_ATTRIBUTE) is not None
+ ):
return
for child in list(elem):
if _local(child.tag) != "g":
@@ -339,6 +359,7 @@ def _find_extractable(root: ET.Element, min_drawables: int, min_bytes: int) -> l
continue
if (
not _is_chart_group(child)
+ and not _has_semantic_object(child)
and not _has_semantic_content(child)
and not _has_icon_placeholder(child)
and _large_enough(child, min_drawables, min_bytes)
@@ -375,7 +396,10 @@ def _find_extractable_runs(
found.append((parent, list(run)))
def walk(elem: ET.Element) -> None:
- if _local(elem.tag) in DEFINITION_CONTAINERS:
+ if (
+ _local(elem.tag) in DEFINITION_CONTAINERS
+ or elem.get(SEMANTIC_OBJECT_ATTRIBUTE) is not None
+ ):
return
run: list[ET.Element] = []
for child in list(elem):
@@ -399,8 +423,20 @@ def _asset_svg(
height: str | None,
) -> bytes:
"""Standalone, independently-viewable SVG carrying the group in page coords."""
+ semantic_inputs = [group, *dependencies]
+ if any(
+ _has_semantic_object(item)
+ or _has_semantic_content(item)
+ or _is_chart_group(item)
+ for item in semantic_inputs
+ ):
+ raise ValueError(
+ "Semantic authoring content must remain inline and cannot become "
+ "imported decoration assets"
+ )
svg = ET.Element(f"{{{SVG_NS}}}svg")
svg.set("data-icon-style", "preserve-color")
+ svg.set(ASSET_ROLE_ATTRIBUTE, DECORATION_ASSET_ROLE)
if view_box:
svg.set("viewBox", view_box)
if width:
@@ -548,6 +584,11 @@ def _existing_placeholder_entries(
asset = _icon_asset_for_namespace(icon_name, icon_namespace)
if asset is None:
continue
+ if elem.get(ASSET_ROLE_ATTRIBUTE) != DECORATION_ASSET_ROLE:
+ raise ValueError(
+ f"Imported vector placeholder {icon_name!r} must declare "
+ f"{ASSET_ROLE_ATTRIBUTE}={DECORATION_ASSET_ROLE!r}"
+ )
if asset in known_assets:
continue
@@ -560,6 +601,7 @@ def _existing_placeholder_entries(
"icon": icon_name,
"asset": asset,
"source": "existing-placeholder",
+ "role": DECORATION_ASSET_ROLE,
"asset_exists": (icons_dir / asset).exists(),
},
)
@@ -575,9 +617,19 @@ def _existing_placeholder_entries(
).hexdigest()
try:
root = ET.parse(asset_path).getroot()
- except ET.ParseError:
- pass
+ except ET.ParseError as exc:
+ raise ValueError(
+ f"Imported vector asset is invalid SVG XML: "
+ f"{asset_path}: {exc}"
+ ) from exc
else:
+ role = root.get(ASSET_ROLE_ATTRIBUTE)
+ if role != DECORATION_ASSET_ROLE:
+ raise ValueError(
+ f"Imported vector asset must declare "
+ f"{ASSET_ROLE_ATTRIBUTE}={DECORATION_ASSET_ROLE!r}: "
+ f"{asset_path}"
+ )
entry["drawable_count"] = _drawable_count(root)
entry["byte_count"] = _xml_size(root)
entry["elements"] = _tag_histogram(root)
@@ -602,6 +654,14 @@ def _load_reusable_assets(inventory_path: Path, icons_dir: Path) -> dict[str, di
except json.JSONDecodeError as exc:
raise ValueError(f"invalid reuse inventory JSON: {inventory_path}: {exc}") from exc
+ if payload.get("schema") != VECTOR_INVENTORY_SCHEMA:
+ raise ValueError(
+ f"unsupported reuse inventory schema: {payload.get('schema')!r}"
+ )
+ if payload.get("asset_role") != DECORATION_ASSET_ROLE:
+ raise ValueError(
+ "reuse inventory must declare asset_role='decoration'"
+ )
entries = payload.get("assets")
if not isinstance(entries, list):
raise ValueError(f"reuse inventory has no assets list: {inventory_path}")
@@ -615,11 +675,16 @@ def _load_reusable_assets(inventory_path: Path, icons_dir: Path) -> dict[str, di
asset_sha256 = entry.get("asset_sha256")
asset = entry.get("asset")
icon = entry.get("icon")
+ role = entry.get("role")
if not all(
isinstance(value, str) and value
for value in (source_sha256, asset_sha256, asset, icon)
):
continue
+ if role != DECORATION_ASSET_ROLE:
+ raise ValueError(
+ f"reusable asset {icon!r} is not a decoration asset"
+ )
fingerprinted += 1
asset_path = icons_dir / asset
if not asset_path.is_file():
@@ -631,6 +696,16 @@ def _load_reusable_assets(inventory_path: Path, icons_dir: Path) -> dict[str, di
raise ValueError(
f"reusable asset hash does not match its inventory: {asset_path}"
)
+ try:
+ asset_root = ET.parse(asset_path).getroot()
+ except ET.ParseError as exc:
+ raise ValueError(
+ f"reusable asset is not valid SVG XML: {asset_path}: {exc}"
+ ) from exc
+ if asset_root.get(ASSET_ROLE_ATTRIBUTE) != DECORATION_ASSET_ROLE:
+ raise ValueError(
+ f"reusable asset lacks its decoration role: {asset_path}"
+ )
current = reusable.get(source_sha256)
if current is None or asset < str(current["asset"]):
reusable[source_sha256] = entry
@@ -652,6 +727,25 @@ def _rewritten_path(svg_path: Path, rewritten_dir: Path | None, inplace: bool) -
return rewritten_dir / svg_path.name
+def _fresh_native_fallback_markers(root: ET.Element) -> set[ET.Element]:
+ """Snapshot native markers whose visible fallback is fresh before extraction."""
+ fresh: set[ET.Element] = set()
+ for element in root.iter():
+ expected = element.get(NATIVE_FALLBACK_SHA256_ATTR)
+ if (
+ expected is None
+ or expected != expected.strip()
+ or not _SHA256_RE.fullmatch(expected)
+ ):
+ continue
+ if svg_native_fallback_fingerprint(
+ element,
+ document_root=root,
+ ) == expected.lower():
+ fresh.add(element)
+ return fresh
+
+
def extract_file(
svg_path: Path,
icons_dir: Path,
@@ -668,6 +762,7 @@ def extract_file(
ET.register_namespace("", SVG_NS)
tree = ET.parse(svg_path)
root = tree.getroot()
+ fresh_native_markers = _fresh_native_fallback_markers(root)
view_box = root.get("viewBox")
width = root.get("width")
height = root.get("height")
@@ -745,6 +840,7 @@ def extract_file(
reused_asset = str(reusable["asset"])
placeholder = ET.Element(f"{{{SVG_NS}}}use")
placeholder.set("data-icon", reused_icon)
+ placeholder.set(ASSET_ROLE_ATTRIBUTE, DECORATION_ASSET_ROLE)
for node in nodes:
if node in parent:
parent.remove(node)
@@ -755,6 +851,7 @@ def extract_file(
"icon": reused_icon,
"asset": reused_asset,
"source": "reused-inventory",
+ "role": DECORATION_ASSET_ROLE,
"source_sha256": source_sha256,
"asset_sha256": reusable["asset_sha256"],
"reused_from_svg": reusable.get("svg"),
@@ -789,6 +886,7 @@ def extract_file(
placeholder = ET.Element(f"{{{SVG_NS}}}use")
placeholder.set("data-icon", icon_reference)
+ placeholder.set(ASSET_ROLE_ATTRIBUTE, DECORATION_ASSET_ROLE)
for node in nodes:
if node in parent:
parent.remove(node)
@@ -800,6 +898,7 @@ def extract_file(
"icon": icon_reference,
"asset": asset,
"source": "extracted",
+ "role": DECORATION_ASSET_ROLE,
"source_sha256": source_sha256,
"asset_sha256": hashlib.sha256(asset_bytes).hexdigest(),
"drawable_count": _drawable_count(group),
@@ -811,6 +910,12 @@ def extract_file(
})
_optimize_definitions(root)
+ live_elements = set(root.iter())
+ for marker in fresh_native_markers & live_elements:
+ marker.set(
+ NATIVE_FALLBACK_SHA256_ATTR,
+ svg_native_fallback_fingerprint(marker, document_root=root),
+ )
rewritten = _rewritten_path(svg_path, rewritten_dir, inplace)
rewritten.parent.mkdir(parents=True, exist_ok=True)
tree.write(rewritten, encoding="utf-8", xml_declaration=True)
@@ -819,7 +924,9 @@ def extract_file(
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
- description="Factor large inline vector groups out of SVGs into reusable assets.",
+ description=(
+ "Factor large non-semantic SVG decorations into reusable assets."
+ ),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("svg_dir", help="Directory of working SVGs (e.g. import_ws/svg or project/svg_output)")
@@ -993,10 +1100,11 @@ def extract_directory(
)
manifest = {
- "schema": "vector_asset_inventory.v1",
+ "schema": VECTOR_INVENTORY_SCHEMA,
"svg_dir": manifest_path(svg_dir),
"icons_dir": manifest_path(icons_dir),
"icon_namespace": icon_namespace or None,
+ "asset_role": DECORATION_ASSET_ROLE,
"rewritten_dir": (
None
if inplace
diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.py
index 2b4b619b..2fdd8acb 100644
--- a/skills/ppt-master/scripts/mirror_template_materialize.py
+++ b/skills/ppt-master/scripts/mirror_template_materialize.py
@@ -29,13 +29,20 @@ import sys
import tempfile
from collections import Counter
from dataclasses import dataclass
-from pathlib import Path
+from pathlib import Path, PurePosixPath
from typing import Any, Iterable
from urllib.parse import unquote, urlsplit, urlunsplit
from xml.etree import ElementTree as ET
+from zipfile import BadZipFile, ZipFile
from compact_svg_coordinates import compact_svg_tree, format_coordinate
+from compact_svg_styles import compact_svg_style_tree
from console_encoding import configure_utf8_stdio
+from extract_svg_assets import (
+ ASSET_ROLE_ATTRIBUTE,
+ DECORATION_ASSET_ROLE,
+ VECTOR_INVENTORY_SCHEMA,
+)
from native_payloads import (
PAYLOAD_STORE_RELATIVE_PATH,
NativePayloadError,
@@ -47,18 +54,27 @@ from native_payloads import (
hydrate_native_payload_refs,
serialize_native_payload_store,
)
-from pptx_shapes import svg_preset_preview_fingerprint
+from pptx_shapes import (
+ NATIVE_FALLBACK_SHA256_ATTR,
+ svg_native_fallback_fingerprint,
+ svg_preset_preview_fingerprint,
+)
from svg_authoring_view import (
AUTHORING_MANIFEST_NAME,
AUTHORING_SCHEMA,
+ SEMANTIC_OBJECT_ATTRIBUTE,
SOURCE_REF_ATTRIBUTE,
semantic_subtree_sha256,
)
from svg_finalize.flatten_tspan import flatten_text_with_tspans
from svg_to_pptx.pptx_package.template_structure import (
+ SOURCE_THEMES_FILENAME,
+ SOURCE_THEMES_SCHEMA,
TemplateStructureError,
+ load_template_source_themes,
parse_template_slides,
)
+from svg_to_pptx.native_objects import stamp_native_fallback_baseline
from template_text_slots import (
analyze_template_text_slots,
text_slot_integrity_sha256,
@@ -76,13 +92,14 @@ configure_utf8_stdio()
SVG_NS = "http://www.w3.org/2000/svg"
XLINK_NS = "http://www.w3.org/1999/xlink"
XML_NS = "http://www.w3.org/XML/1998/namespace"
+DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
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.v2-min"
IMPORTED_ICON_NAMESPACE = "imported"
+_FRESH_NATIVE_FALLBACK_ATTR = "data-pptx-mirror-fresh-fallback"
TRANSPARENT_PIXEL_DATA_URI = (
"data:image/png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUA"
@@ -135,6 +152,7 @@ _AXIS_REFLECTION_RE = re.compile(
rf"translate\(\s*({_TRANSFORM_NUMBER})[\s,]+"
rf"({_TRANSFORM_NUMBER})\s*\)\s*$"
)
+_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
class MirrorMaterializationError(RuntimeError):
@@ -180,6 +198,7 @@ class RestorationStats:
rehydrated_refs: int = 0
fallback_refs: int = 0
structural_refs: int = 0
+ semantic_refs: int = 0
detached_connector_endpoints: int = 0
upright_text_compensations: int = 0
@@ -187,6 +206,7 @@ class RestorationStats:
self.rehydrated_refs += other.rehydrated_refs
self.fallback_refs += other.fallback_refs
self.structural_refs += other.structural_refs
+ self.semantic_refs += other.semantic_refs
self.detached_connector_endpoints += other.detached_connector_endpoints
self.upright_text_compensations += other.upright_text_compensations
@@ -195,6 +215,7 @@ class RestorationStats:
"rehydrated_refs": self.rehydrated_refs,
"fallback_refs": self.fallback_refs,
"structural_refs": self.structural_refs,
+ "semantic_refs": self.semantic_refs,
"detached_connector_endpoints": self.detached_connector_endpoints,
"upright_text_compensations": self.upright_text_compensations,
}
@@ -287,6 +308,7 @@ def _template_execution_manifest_files(
"warning_count": 0,
"by_code": {},
},
+ "source_themes": SOURCE_THEMES_FILENAME,
"templates": templates,
}
files.append(MaterializedFile(
@@ -332,6 +354,74 @@ def _source_import_summary(import_workspace: Path) -> dict[str, object] | None:
}
+def _source_theme_bundle(
+ import_workspace: Path,
+ native: dict[str, Any],
+ masters: dict[str, dict[str, Any]],
+ retained_master_keys: set[str],
+) -> bytes:
+ """Package exact source Theme parts for every reachable mirror Master."""
+ source = native.get("source")
+ if not isinstance(source, dict):
+ raise MirrorMaterializationError("Native source facts are missing")
+ template_name = _require_string(
+ source.get("templateFile"),
+ context="native source template",
+ )
+ template_path = _resolve_inside(
+ import_workspace,
+ template_name,
+ context="native source template",
+ )
+ records: dict[str, dict[str, str]] = {}
+ try:
+ with ZipFile(template_path) as archive:
+ for master_key in sorted(retained_master_keys):
+ theme_part = _require_string(
+ masters[master_key].get("themePart"),
+ context=f"Master {master_key!r} themePart",
+ )
+ normalized = PurePosixPath(theme_part)
+ if (
+ theme_part != normalized.as_posix()
+ or normalized.is_absolute()
+ or ".." in normalized.parts
+ ):
+ raise MirrorMaterializationError(
+ f"Master {master_key!r} has unsafe Theme part {theme_part!r}"
+ )
+ try:
+ theme_xml = archive.read(theme_part)
+ except KeyError as exc:
+ raise MirrorMaterializationError(
+ f"Master {master_key!r} Theme part is missing: {theme_part}"
+ ) from exc
+ try:
+ theme_root = ET.fromstring(theme_xml)
+ except ET.ParseError as exc:
+ raise MirrorMaterializationError(
+ f"Master {master_key!r} Theme part is malformed"
+ ) from exc
+ if theme_root.tag != f"{{{DML_NS}}}theme":
+ raise MirrorMaterializationError(
+ f"Master {master_key!r} Theme part is not a:theme"
+ )
+ records[master_key] = {
+ "source_part": theme_part,
+ "encoding": "base64",
+ "sha256": hashlib.sha256(theme_xml).hexdigest(),
+ "payload": base64.b64encode(theme_xml).decode("ascii"),
+ }
+ except BadZipFile as exc:
+ raise MirrorMaterializationError(
+ f"Source template is not a valid PPTX package: {template_path}"
+ ) from exc
+ return _json_bytes({
+ "schema": SOURCE_THEMES_SCHEMA,
+ "masters": records,
+ })
+
+
def _local_name(name: object) -> str:
return name.rsplit("}", 1)[-1] if isinstance(name, str) else ""
@@ -497,6 +587,7 @@ def _source_identity(element: ET.Element) -> str | None:
def _load_authoring_documents(
workspace: Path,
+ required_names: set[str],
) -> tuple[Path, dict[str, AuthoringDocument]]:
authoring_root = workspace / "authoring-svg"
manifest_path = authoring_root / AUTHORING_MANIFEST_NAME
@@ -533,6 +624,7 @@ def _load_authoring_documents(
context="authoring_manifest.json documents",
)
documents: dict[str, AuthoringDocument] = {}
+ manifest_names: set[str] = set()
for index, raw in enumerate(documents_raw):
if not isinstance(raw, dict):
raise MirrorMaterializationError(f"documents[{index}] must be an object")
@@ -540,14 +632,17 @@ def _load_authoring_documents(
raw.get("authoring"),
context=f"documents[{index}].authoring",
)
+ if authoring_name in manifest_names:
+ raise MirrorMaterializationError(
+ f"Duplicate authoring manifest document: {authoring_name}"
+ )
+ manifest_names.add(authoring_name)
+ if authoring_name not in required_names:
+ continue
source_name = _require_string(
raw.get("source"),
context=f"documents[{index}].source",
)
- if authoring_name in documents:
- raise MirrorMaterializationError(
- f"Duplicate authoring manifest document: {authoring_name}"
- )
authoring_path = _resolve_inside(
authoring_root,
authoring_name,
@@ -617,26 +712,16 @@ def _load_authoring_documents(
source_refs=refs,
)
- actual_authoring_files = {
- path.relative_to(authoring_root).as_posix()
- for path in authoring_root.rglob("*.svg")
- if path.is_file()
- }
- if actual_authoring_files != set(documents):
+ if required_names != set(documents):
raise MirrorMaterializationError(
- "Authoring manifest/file roster differs; missing="
- f"{sorted(set(documents) - actual_authoring_files)}, extra="
- f"{sorted(actual_authoring_files - set(documents))}"
+ "Reachable authoring manifest roster differs; missing="
+ f"{sorted(required_names - set(documents))}, extra="
+ f"{sorted(set(documents) - required_names)}"
)
- if manifest.get("file_count") != len(documents):
+ if manifest.get("file_count") != len(documents_raw):
raise MirrorMaterializationError(
"authoring_manifest.json file_count does not match documents"
)
- expected_ref_count = sum(len(document.source_refs) for document in documents.values())
- if manifest.get("source_ref_count") != expected_ref_count:
- raise MirrorMaterializationError(
- "authoring_manifest.json source_ref_count does not match documents"
- )
return authoring_root, documents
@@ -656,26 +741,36 @@ def _load_vector_assets(
raise MirrorMaterializationError(
"Mirror vector inventory must use icon_namespace='imported'"
)
+ if inventory.get("asset_role") != DECORATION_ASSET_ROLE:
+ raise MirrorMaterializationError(
+ "Mirror vector inventory must use asset_role='decoration'"
+ )
icons_root = workspace / "icons"
records: dict[str, VectorAssetRecord] = {}
- for index, raw in enumerate(
- _require_list(inventory.get("assets"), context="vector inventory assets")
- ):
+ assets = _require_list(
+ inventory.get("assets"),
+ context="vector inventory assets",
+ )
+ if inventory.get("asset_count") != len(assets):
+ raise MirrorMaterializationError("Vector inventory asset_count is stale")
+ for index, raw in enumerate(assets):
if not isinstance(raw, dict):
raise MirrorMaterializationError(f"vector assets[{index}] must be an object")
icon = _require_string(raw.get("icon"), context=f"assets[{index}].icon")
asset = _require_string(raw.get("asset"), context=f"assets[{index}].asset")
origin = _require_string(raw.get("svg"), context=f"assets[{index}].svg")
+ if raw.get("role") != DECORATION_ASSET_ROLE:
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} is not declared as decoration"
+ )
+ if origin not in documents:
+ continue
if not icon.startswith(f"{IMPORTED_ICON_NAMESPACE}/"):
raise MirrorMaterializationError(
f"Vector asset {icon!r} is outside imported/ namespace"
)
if icon in records:
raise MirrorMaterializationError(f"Duplicate vector asset id: {icon}")
- if origin not in documents:
- raise MirrorMaterializationError(
- f"Vector asset {icon!r} names unknown origin document {origin!r}"
- )
asset_path = _resolve_inside(
icons_root,
asset,
@@ -683,6 +778,11 @@ def _load_vector_assets(
)
if not asset_path.is_file() or asset_path.suffix.lower() != ".svg":
raise MirrorMaterializationError(f"Vector asset is missing: {asset_path}")
+ asset_root = _parse_svg(asset_path)
+ if asset_root.get(ASSET_ROLE_ATTRIBUTE) != DECORATION_ASSET_ROLE:
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} lacks its decoration role"
+ )
expected_sha256 = _require_string(
raw.get("asset_sha256"),
context=f"vector asset {icon!r} asset_sha256",
@@ -708,8 +808,6 @@ def _load_vector_assets(
expected_sha256=expected_sha256,
source_refs=tuple(refs_raw),
)
- if inventory.get("asset_count") != len(records):
- raise MirrorMaterializationError("Vector inventory asset_count is stale")
return records
@@ -723,12 +821,17 @@ def _source_ref_counts(root: ET.Element) -> dict[str, int]:
def _imported_icon_refs(root: ET.Element) -> set[str]:
- return {
- value
- for element in root.iter()
- if (value := (element.get("data-icon") or "").strip())
- if value.startswith(f"{IMPORTED_ICON_NAMESPACE}/")
- }
+ refs: set[str] = set()
+ for element in root.iter():
+ value = (element.get("data-icon") or "").strip()
+ if not value.startswith(f"{IMPORTED_ICON_NAMESPACE}/"):
+ continue
+ if element.get(ASSET_ROLE_ATTRIBUTE) != DECORATION_ASSET_ROLE:
+ raise MirrorMaterializationError(
+ f"Imported vector {value!r} is not marked as decoration"
+ )
+ refs.add(value)
+ return refs
def _validate_source_ref_closure(
@@ -835,8 +938,9 @@ def _load_inheritance(workspace: Path) -> dict[str, Any]:
def _validate_graph_roster(
native: dict[str, Any],
inheritance: dict[str, Any],
- documents: dict[str, AuthoringDocument],
-) -> None:
+ retained_master_keys: set[str],
+ retained_layout_keys: set[str],
+) -> set[str]:
masters = _require_list(native.get("masters"), context="native masters")
layouts = _require_list(native.get("layouts"), context="native layouts")
slides = _require_list(native.get("slides"), context="native slides")
@@ -844,15 +948,50 @@ def _validate_graph_roster(
inheritance.get("masters"),
context="inheritance masters",
)
- master_file_by_part = {
- _require_string(item.get("partPath"), context="inheritance Master partPath"):
- _require_string(item.get("file"), context="inheritance Master file")
- for item in inheritance_masters_raw
- if isinstance(item, dict)
+ retained_masters = [
+ item
+ for item in masters
+ if isinstance(item, dict) and item.get("key") in retained_master_keys
+ ]
+ retained_layouts = [
+ item
+ for item in layouts
+ if isinstance(item, dict) and item.get("key") in retained_layout_keys
+ ]
+ if len(retained_masters) != len(retained_master_keys):
+ raise MirrorMaterializationError(
+ "Reachable Master roster differs from native graph"
+ )
+ if len(retained_layouts) != len(retained_layout_keys):
+ raise MirrorMaterializationError(
+ "Reachable Layout roster differs from native graph"
+ )
+ required_master_parts = {
+ _require_string(
+ master.get("packagePart"),
+ context=f"native Master {master.get('key')!r} packagePart",
+ )
+ for master in retained_masters
}
+ master_file_by_part: dict[str, str] = {}
+ for item in inheritance_masters_raw:
+ if not isinstance(item, dict):
+ continue
+ part_path = item.get("partPath")
+ if part_path not in required_master_parts:
+ continue
+ master_file_by_part[_require_string(
+ part_path,
+ context="inheritance Master partPath",
+ )] = _require_string(
+ item.get("file"),
+ context="inheritance Master file",
+ )
for index, master in enumerate(masters):
if not isinstance(master, dict):
raise MirrorMaterializationError(f"native masters[{index}] must be an object")
+ if master.get("key") not in retained_master_keys:
+ continue
package_part = _require_string(
master.get("packagePart"),
context=f"native masters[{index}].packagePart",
@@ -865,8 +1004,14 @@ def _validate_graph_roster(
master["svgFile"] = svg_file
expected_files: set[str] = set()
for collection, field in (
- (masters, "svgFile"),
- (layouts, "svgFile"),
+ (
+ retained_masters,
+ "svgFile",
+ ),
+ (
+ retained_layouts,
+ "svgFile",
+ ),
(slides, "layeredSvgFile"),
):
for index, item in enumerate(collection):
@@ -875,38 +1020,55 @@ def _validate_graph_roster(
expected_files.add(
_require_string(item.get(field), context=f"native {field}[{index}]")
)
- if expected_files != set(documents):
+ expected_role_count = len(retained_masters) + len(retained_layouts) + len(slides)
+ if len(expected_files) != expected_role_count:
raise MirrorMaterializationError(
- "Native graph and authoring document roster differ; missing="
- f"{sorted(expected_files - set(documents))}, extra="
- f"{sorted(set(documents) - expected_files)}"
+ "Reachable Master/Layout/Slide authoring files must be role-distinct"
)
- inherited_masters = {
- _require_string(item.get("file"), context="inheritance master file")
- for item in inheritance_masters_raw
- if isinstance(item, dict)
- }
- inherited_layouts = {
- _require_string(item.get("file"), context="inheritance layout file"): item
- for item in _require_list(inheritance.get("layouts"), context="inheritance layouts")
- if isinstance(item, dict)
+ retained_layout_files = {
+ _require_string(
+ item.get("svgFile"),
+ context=f"native Layout {item.get('key')!r} svgFile",
+ )
+ for item in retained_layouts
}
+ inherited_layouts: dict[str, dict[str, Any]] = {}
+ for item in _require_list(
+ inheritance.get("layouts"),
+ context="inheritance layouts",
+ ):
+ if not isinstance(item, dict) or item.get("file") not in retained_layout_files:
+ continue
+ inherited_layouts[_require_string(
+ item.get("file"),
+ context="inheritance layout file",
+ )] = item
inherited_slides = {
int(item.get("index")): item
for item in _require_list(inheritance.get("slides"), context="inheritance slides")
if isinstance(item, dict) and isinstance(item.get("index"), int)
}
- if inherited_masters != {item["svgFile"] for item in masters}:
- raise MirrorMaterializationError("Inheritance Master roster differs from native graph")
- if set(inherited_layouts) != {item["svgFile"] for item in layouts}:
- raise MirrorMaterializationError("Inheritance Layout roster differs from native graph")
+ if retained_layout_files != set(inherited_layouts):
+ raise MirrorMaterializationError(
+ "Reachable inheritance Layout roster differs from native graph"
+ )
if set(inherited_slides) != {int(item["index"]) for item in slides}:
raise MirrorMaterializationError("Inheritance Slide roster differs from native graph")
- master_file_by_key = {item["key"]: item["svgFile"] for item in masters}
- layout_file_by_key = {item["key"]: item["svgFile"] for item in layouts}
- for layout in layouts:
+ master_file_by_key = {
+ item["key"]: item["svgFile"]
+ for item in retained_masters
+ }
+ layout_file_by_key = {
+ item["key"]: item["svgFile"]
+ for item in retained_layouts
+ }
+ layout_master_by_key = {
+ item["key"]: item["masterKey"]
+ for item in retained_layouts
+ }
+ for layout in retained_layouts:
inherited = inherited_layouts[layout["svgFile"]]
if inherited.get("master") != master_file_by_key.get(layout.get("masterKey")):
raise MirrorMaterializationError(
@@ -926,6 +1088,10 @@ def _validate_graph_roster(
)
for slide in slides:
inherited = inherited_slides[int(slide["index"])]
+ if slide.get("masterKey") != layout_master_by_key.get(slide.get("layoutKey")):
+ raise MirrorMaterializationError(
+ f"Slide {slide.get('index')} Master does not match its Layout parent"
+ )
if inherited.get("layout") != layout_file_by_key.get(slide.get("layoutKey")):
raise MirrorMaterializationError(
f"Slide {slide.get('index')} Layout parent differs across native facts"
@@ -946,6 +1112,7 @@ def _validate_graph_roster(
raise MirrorMaterializationError(
f"Slide {slide.get('index')} showInheritedShapes differs across facts"
)
+ return expected_files
def _absolutize_local_hrefs(root: ET.Element, base_dir: Path) -> None:
@@ -976,12 +1143,18 @@ def _rehydrate_tree(
def restore(element: ET.Element) -> ET.Element:
source_ref = element.get(SOURCE_REF_ATTRIBUTE)
record = document.source_refs.get(source_ref or "")
+ contains_semantic_object = any(
+ item.get(SEMANTIC_OBJECT_ATTRIBUTE) is not None
+ for item in element.iter()
+ )
if source_ref and record is None:
raise MirrorMaterializationError(
f"{document.name} contains unknown source ref {source_ref!r}"
)
if source_ref and source_ref in excluded_refs:
stats.structural_refs += 1
+ elif source_ref and contains_semantic_object:
+ stats.semantic_refs += 1
elif source_ref and record is not None:
actual_hash = semantic_subtree_sha256(
element,
@@ -989,6 +1162,8 @@ def _rehydrate_tree(
)
if actual_hash == record.initial_authoring_subtree_sha256:
restored = copy.deepcopy(_source_element(source_root, record.source_path))
+ for marker in _fresh_native_fallbacks(restored):
+ marker.set(_FRESH_NATIVE_FALLBACK_ATTR, "true")
_absolutize_local_hrefs(restored, document.source_path.parent)
stats.rehydrated_refs += 1
return restored
@@ -1151,12 +1326,34 @@ def _prepared_document(
excluded_refs: set[str],
) -> tuple[ET.Element, RestorationStats]:
root = _parse_svg(document.authoring_path)
+ fresh_native_fallbacks = _fresh_native_fallbacks(root)
_absolutize_local_hrefs(root, document.authoring_path.parent)
stats = _rehydrate_tree(root, document, excluded_refs=excluded_refs)
_annotate_unchanged_explicit_text_breaks(root, document, excluded_refs)
+ for marker in fresh_native_fallbacks & set(root.iter()):
+ marker.set(_FRESH_NATIVE_FALLBACK_ATTR, "true")
return root, stats
+def _fresh_native_fallbacks(root: ET.Element) -> set[ET.Element]:
+ """Snapshot valid input guards before mirror-only normalization."""
+ fresh: set[ET.Element] = set()
+ for element in root.iter():
+ expected = element.get(NATIVE_FALLBACK_SHA256_ATTR)
+ if (
+ expected is None
+ or expected != expected.strip()
+ or _SHA256_RE.fullmatch(expected) is None
+ ):
+ continue
+ if svg_native_fallback_fingerprint(
+ element,
+ document_root=root,
+ ) == expected.lower():
+ fresh.add(element)
+ return fresh
+
+
def _safe_prefix(value: str) -> str:
normalized = _SAFE_KEY_RE.sub("-", value).strip("-.")
return normalized or "node"
@@ -2240,6 +2437,17 @@ def _compose_template(
slide_backgrounds.append(item)
else:
item.set("id", item.get("id") or f"slide-{slide['index']}-node-{index + 1}")
+ if _local_name(item.tag) == "g" and _visible_leaf(item):
+ bounds = _frame(item)
+ if bounds is None:
+ raise MirrorMaterializationError(
+ f"Slide {slide['index']} root group "
+ f"{item.get('id')!r} has no positive source frame"
+ )
+ item.set(
+ "data-pptx-bounds",
+ " ".join(format_coordinate(value) for value in bounds),
+ )
slide_content.append(item)
if len(slide_backgrounds) > 1:
raise MirrorMaterializationError(
@@ -2341,6 +2549,14 @@ def _refresh_preset_preview_hashes(root: ET.Element) -> None:
descendant.set("data-pptx-preview-sha256", fingerprint)
+def _refresh_fresh_native_fallback_hashes(root: ET.Element) -> None:
+ """Rebind valid guards changed only by deterministic mirror normalization."""
+ for element in root.iter():
+ if element.attrib.pop(_FRESH_NATIVE_FALLBACK_ATTR, None) is None:
+ continue
+ stamp_native_fallback_baseline(element, document_root=root)
+
+
def _sanitize_connector_references(root: ET.Element) -> int:
"""Drop endpoint bindings whose native target is absent from this SVG tree."""
identities = {
@@ -2642,27 +2858,96 @@ def materialize_mirror_template(
import_workspace: Path,
template_workspace: Path,
) -> dict[str, Any]:
- """Validate one Type A import graph and publish its mirror SVG contract."""
- authoring_root, documents = _load_authoring_documents(import_workspace)
- vector_assets = _load_vector_assets(import_workspace, documents)
- referenced_icons = _validate_source_ref_closure(documents, vector_assets)
+ """Publish source Slide prototypes with their reachable mirror structure."""
native = _load_native_graph(import_workspace)
inheritance = _load_inheritance(import_workspace)
- _validate_graph_roster(native, inheritance, documents)
-
- masters = {item["key"]: item for item in native["masters"]}
- layouts = {item["key"]: item for item in native["layouts"]}
- slides = sorted(native["slides"], key=lambda item: int(item["index"]))
+ masters: dict[str, dict[str, Any]] = {}
+ for index, item in enumerate(
+ _require_list(native.get("masters"), context="native masters")
+ ):
+ if not isinstance(item, dict):
+ raise MirrorMaterializationError(
+ f"native masters[{index}] must be an object"
+ )
+ key = _require_string(item.get("key"), context=f"native masters[{index}].key")
+ if key in masters:
+ raise MirrorMaterializationError(f"Duplicate native Master key: {key}")
+ masters[key] = item
+ layouts: dict[str, dict[str, Any]] = {}
+ for index, item in enumerate(
+ _require_list(native.get("layouts"), context="native layouts")
+ ):
+ if not isinstance(item, dict):
+ raise MirrorMaterializationError(
+ f"native layouts[{index}] must be an object"
+ )
+ key = _require_string(item.get("key"), context=f"native layouts[{index}].key")
+ if key in layouts:
+ raise MirrorMaterializationError(f"Duplicate native Layout key: {key}")
+ layouts[key] = item
+ slides: list[dict[str, Any]] = []
+ for index, item in enumerate(
+ _require_list(native.get("slides"), context="native slides")
+ ):
+ if not isinstance(item, dict) or not isinstance(item.get("index"), int):
+ raise MirrorMaterializationError(
+ f"native slides[{index}] requires an integer index"
+ )
+ slides.append(item)
+ slides.sort(key=lambda item: int(item["index"]))
+ if not slides:
+ raise MirrorMaterializationError(
+ "Mirror materialization requires at least one source Slide"
+ )
if [int(item["index"]) for item in slides] != list(range(1, len(slides) + 1)):
raise MirrorMaterializationError(
"Mirror source slide indexes must be contiguous and start at 1"
)
+ retained_layout_keys = {
+ str(slide["layoutKey"])
+ for slide in slides
+ }
+ missing_layout_keys = retained_layout_keys - set(layouts)
+ if missing_layout_keys:
+ raise MirrorMaterializationError(
+ "Source Slides reference missing Layout key(s): "
+ + ", ".join(sorted(missing_layout_keys))
+ )
+ retained_master_keys = {
+ str(layouts[layout_key]["masterKey"])
+ for layout_key in retained_layout_keys
+ }
+ missing_master_keys = retained_master_keys - set(masters)
+ if missing_master_keys:
+ raise MirrorMaterializationError(
+ "Reachable Layouts reference missing Master key(s): "
+ + ", ".join(sorted(missing_master_keys))
+ )
+ selected_document_names = _validate_graph_roster(
+ native,
+ inheritance,
+ retained_master_keys,
+ retained_layout_keys,
+ )
+ authoring_root, documents = _load_authoring_documents(
+ import_workspace,
+ selected_document_names,
+ )
+ vector_assets = _load_vector_assets(import_workspace, documents)
+ referenced_icons = _validate_source_ref_closure(documents, vector_assets)
+ source_theme_bundle = _source_theme_bundle(
+ import_workspace,
+ native,
+ masters,
+ retained_master_keys,
+ )
prepared_masters: dict[str, ET.Element] = {}
prepared_layouts: dict[str, ET.Element] = {}
prepared_slides: dict[int, ET.Element] = {}
total_stats = RestorationStats()
- for key, master in masters.items():
+ for key in sorted(retained_master_keys):
+ master = masters[key]
document = documents[master["svgFile"]]
root, stats = _prepared_document(
document,
@@ -2671,7 +2956,8 @@ def materialize_mirror_template(
_namespace_ids(root, f"m-{_safe_prefix(str(key))}-")
prepared_masters[key] = root
total_stats.merge(stats)
- for key, layout in layouts.items():
+ for key in sorted(retained_layout_keys):
+ layout = layouts[key]
document = documents[layout["svgFile"]]
root, stats = _prepared_document(
document,
@@ -2693,12 +2979,15 @@ def materialize_mirror_template(
prepared_slides[index] = root
total_stats.merge(stats)
- slides_by_layout: dict[str, list[dict[str, Any]]] = {key: [] for key in layouts}
+ slides_by_layout: dict[str, list[dict[str, Any]]] = {
+ key: [] for key in retained_layout_keys
+ }
for slide in slides:
slides_by_layout[str(slide["layoutKey"])].append(slide)
plans_by_layout: dict[str, list[SlotPlan]] = {}
- for key, layout in layouts.items():
+ for key in sorted(retained_layout_keys):
+ layout = layouts[key]
master_key = str(layout["masterKey"])
plans_by_layout[key] = _slot_plans(
layout,
@@ -2727,24 +3016,6 @@ def materialize_mirror_template(
)
materialized_roots.append((filename, root))
- unused_layouts = [
- layout for key, layout in layouts.items() if not slides_by_layout[key]
- ]
- for layout in sorted(unused_layouts, key=lambda item: str(item["key"])):
- master = masters[str(layout["masterKey"])]
- filename = Path("templates") / f"layout_{layout['key']}.svg"
- root = _compose_template(
- native=native,
- master=master,
- layout=layout,
- master_root=prepared_masters[str(master["key"])],
- layout_root=prepared_layouts[str(layout["key"])],
- slide=None,
- slide_root=None,
- slot_plans=plans_by_layout[str(layout["key"])],
- )
- materialized_roots.append((filename, root))
-
asset_sources: dict[Path, Path] = {}
files: list[MaterializedFile] = []
output_roots: list[tuple[Path, ET.Element]] = []
@@ -2764,7 +3035,9 @@ def materialize_mirror_template(
_compensate_reflected_group_text(root)
)
compact_svg_tree(root, compact_native_frames=False)
+ compact_svg_style_tree(root)
_refresh_preset_preview_hashes(root)
+ _refresh_fresh_native_fallback_hashes(root)
try:
native_payload_stats.merge(
externalize_native_payloads(root, native_payloads)
@@ -2795,7 +3068,9 @@ def materialize_mirror_template(
icon_root
)
compact_svg_tree(icon_root, compact_native_frames=False)
+ compact_svg_style_tree(icon_root)
_refresh_preset_preview_hashes(icon_root)
+ _refresh_fresh_native_fallback_hashes(icon_root)
try:
native_payload_stats.merge(
externalize_native_payloads(icon_root, native_payloads)
@@ -2833,6 +3108,8 @@ def materialize_mirror_template(
_source_import_summary(import_workspace),
)
)
+ source_themes_path = Path("templates") / SOURCE_THEMES_FILENAME
+ files.append(MaterializedFile(source_themes_path, source_theme_bundle))
for relative_target, source in sorted(asset_sources.items()):
files.append(MaterializedFile(relative_target, source.read_bytes()))
@@ -2872,6 +3149,16 @@ def materialize_mirror_template(
)
try:
parse_template_slides(template_paths)
+ staged_source_themes = load_template_source_themes(
+ staged_root / "templates"
+ )
+ if (
+ staged_source_themes is None
+ or set(staged_source_themes) != retained_master_keys
+ ):
+ raise TemplateStructureError(
+ "Mirror source Theme roster does not match retained Masters"
+ )
except TemplateStructureError as exc:
raise MirrorMaterializationError(
f"Materialized structured SVG contract is invalid: {exc}"
@@ -2894,16 +3181,26 @@ def materialize_mirror_template(
)
return {
- "schema": "ppt-master.mirror-materialization-report.v1",
+ "schema": "ppt-master.mirror-materialization-report.v2",
"import_workspace": str(import_workspace),
"template_workspace": str(template_workspace),
"source_slide_indexes": [int(item["index"]) for item in slides],
"source_slide_count": len(slides),
- "master_count": len(masters),
- "layout_count": len(layouts),
- "unused_layout_count": len(unused_layouts),
+ "source_structure": {
+ "master_count": len(masters),
+ "layout_count": len(layouts),
+ },
+ "retained_structure": {
+ "master_keys": sorted(retained_master_keys),
+ "layout_keys": sorted(retained_layout_keys),
+ },
+ "omitted_structure": {
+ "master_keys": sorted(set(masters) - retained_master_keys),
+ "layout_keys": sorted(set(layouts) - retained_layout_keys),
+ },
"template_svg_count": len(materialized_roots),
"template_execution_manifest": execution_manifest_path.as_posix(),
+ "source_themes": source_themes_path.as_posix(),
"template_text_slot_manifest_count": len(materialized_roots),
"imported_vector_count": len(referenced_icons),
"packaged_asset_count": len(asset_sources),
diff --git a/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py
index 8cf4a9f9..cf624aef 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py
@@ -37,12 +37,14 @@ Cell painting order:
from __future__ import annotations
import copy
+import json
import math
from dataclasses import dataclass
from typing import Any
from xml.etree import ElementTree as ET
from pptx_effects import txbody_has_run_effects
+from semantic_table import compact_semantic_table_payload
from .color_resolver import ColorPalette, find_color_elem, resolve_color
from .emu_units import (
@@ -632,27 +634,6 @@ def _strict_merge_span(value: str | None) -> int:
return span
-def _canonical_merge_slave_is_empty(tc: ET.Element) -> bool:
- tc_pr = tc.find("a:tcPr", NS)
- if tc_pr is None or tc_pr.attrib or list(tc_pr):
- return False
- tx_body = tc.find("a:txBody", NS)
- if tx_body is None:
- return False
- paragraph_count = 0
- for child in tx_body:
- name = child.tag.rsplit("}", 1)[-1]
- if name in {"bodyPr", "lstStyle"}:
- if child.attrib or list(child):
- return False
- continue
- if name == "p" and not child.attrib and not list(child):
- paragraph_count += 1
- continue
- return False
- return paragraph_count > 0 and not (tx_body.text or "").strip()
-
-
def _canonical_native_merge_status(
rows: list[ET.Element],
col_count: int,
@@ -729,9 +710,6 @@ def _canonical_native_merge_status(
or v_merge != (row_idx > region.row)
):
return "unsupported-merge-topology"
- if not is_anchor and not _canonical_merge_slave_is_empty(tc):
- return "unsupported-merge-topology"
-
return None
@@ -750,10 +728,14 @@ def _table_has_unsupported_style(tbl: ET.Element) -> bool:
for name in ("firstCol", "lastCol", "lastRow", "bandCol", "rtl")
):
return True
- return any(
- child.tag.rsplit("}", 1)[-1] != "tableStyleId"
- for child in tbl_pr
- )
+ for child in tbl_pr:
+ name = child.tag.rsplit("}", 1)[-1]
+ if name == "tableStyleId":
+ continue
+ if name == "effectLst" and not child.attrib and not list(child):
+ continue
+ return True
+ return False
_DIRECT_BORDER_TAGS = {
@@ -761,37 +743,10 @@ _DIRECT_BORDER_TAGS = {
"lnR": "right",
"lnT": "top",
"lnB": "bottom",
+ "lnTlToBr": "diagonal_down",
+ "lnBlToTr": "diagonal_up",
}
_DIRECT_BORDER_WIDTH_MAX = 20116800
-_OPAQUE_COLOR_MODIFIERS = {
- "tint",
- "shade",
- "lumMod",
- "lumOff",
- "satMod",
- "satOff",
-}
-
-
-def _validate_opaque_border_color(color_elem: ET.Element | None) -> None:
- if color_elem is None:
- raise ValueError("missing border color")
- name = color_elem.tag.rsplit("}", 1)[-1]
- if name not in {"srgbClr", "schemeClr"} or set(color_elem.attrib) != {"val"}:
- raise ValueError("unsupported border color")
- for modifier in color_elem:
- modifier_name = modifier.tag.rsplit("}", 1)[-1]
- if (
- modifier_name not in _OPAQUE_COLOR_MODIFIERS
- or set(modifier.attrib) != {"val"}
- or list(modifier)
- ):
- raise ValueError("unsupported border color modifier")
- value = modifier.get("val", "")
- if not value.isdigit() or not 0 <= int(value) <= 100000:
- raise ValueError("invalid border color modifier")
-
-
def _direct_border_payload(
ln: ET.Element,
palette: ColorPalette | None,
@@ -815,9 +770,21 @@ def _direct_border_payload(
children = list(ln)
child_names = [child.tag.rsplit("}", 1)[-1] for child in children]
- if child_names == ["noFill"]:
- no_fill = children[0]
- if no_fill.attrib or list(no_fill):
+ if child_names.count("noFill") == 1:
+ no_fill = next(
+ child for child in children
+ if child.tag.rsplit("}", 1)[-1] == "noFill"
+ )
+ if (
+ no_fill.attrib
+ or list(no_fill)
+ or any(
+ name not in {
+ "noFill", "prstDash", "round", "headEnd", "tailEnd",
+ }
+ for name in child_names
+ )
+ ):
raise ValueError("invalid noFill border")
return {"style": "none"}
@@ -873,9 +840,8 @@ def _direct_border_payload(
if solid_fill.attrib or len(list(solid_fill)) != 1:
raise ValueError("invalid solid border fill")
color_elem = find_color_elem(solid_fill)
- _validate_opaque_border_color(color_elem)
try:
- color, alpha = resolve_color(color_elem, palette)
+ color, alpha = resolve_color(color_elem, palette, strict=True)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError("invalid solid border color") from exc
if color is None or alpha != 1.0:
@@ -901,11 +867,18 @@ def _table_has_unsupported_direct_formatting(
return True
tc_pr = tc.find("a:tcPr", NS)
if tc_pr is not None:
- allowed_attrs = {"marL", "marR", "marT", "marB", "anchor"}
+ allowed_attrs = {
+ "marL", "marR", "marT", "marB", "anchor",
+ "anchorCtr", "horzOverflow",
+ }
if any(name not in allowed_attrs for name in tc_pr.attrib):
return True
if tc_pr.get("anchor") not in {None, "t", "ctr", "b"}:
return True
+ if tc_pr.get("anchorCtr") not in {None, "0", "1", "false", "true"}:
+ return True
+ if tc_pr.get("horzOverflow") not in {None, "clip", "overflow"}:
+ return True
if any(
child.tag.rsplit("}", 1)[-1]
not in {"solidFill", "noFill", *_DIRECT_BORDER_TAGS}
@@ -932,12 +905,18 @@ def _table_has_unsupported_direct_formatting(
return True
solid_fill = tc_pr.find("a:solidFill", NS)
if solid_fill is not None:
- if solid_fill.find(".//a:alpha", NS) is not None:
- return True
- if _cell_fill_hex(tc_pr, palette) is None:
+ fill = resolve_fill(tc_pr, palette)
+ if (
+ not fill.attrs
+ or not fill.attrs.get("fill", "").startswith("#")
+ or set(fill.attrs) - {"fill", "fill-opacity"}
+ ):
return True
tx_body = tc.find("a:txBody", NS)
- if _text_body_has_unsupported_formatting(tx_body):
+ if (
+ _text_body_has_unsupported_formatting(tx_body)
+ or _table_text_has_unsupported_outline(tx_body, palette)
+ ):
return True
return False
@@ -1025,10 +1004,14 @@ def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
p_pr = paragraph.find("a:pPr", NS)
if p_pr is not None:
+ alignment = p_pr.get("algn")
+ if alignment not in {None, "l", "ctr", "r", "just"}:
+ return True
p_pr_tags = [child.tag.rsplit("}", 1)[-1] for child in p_pr]
if p_pr_tags.count("defRPr") > 1 or p_pr_tags.count("buNone") > 1:
return True
- if any(tag.startswith("bu") and tag != "buNone" for tag in p_pr_tags):
+ bullet_tags = [tag for tag in p_pr_tags if tag.startswith("bu")]
+ if bullet_tags and "buNone" not in bullet_tags:
return True
for run in paragraph.findall("a:r", NS):
@@ -1045,6 +1028,64 @@ def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
allowed_text_attrs = {"{http://www.w3.org/XML/1998/namespace}space"}
if any(name not in allowed_text_attrs for name in text_node.attrib):
return True
+ r_pr = run.find("a:rPr", NS)
+ if _table_run_props_have_unsupported_formatting(r_pr):
+ return True
+ end_r_pr = paragraph.find("a:endParaRPr", NS)
+ if _table_run_props_have_unsupported_formatting(end_r_pr):
+ return True
+ return False
+
+
+def _table_run_props_have_unsupported_formatting(
+ run_props: ET.Element | None,
+) -> bool:
+ """Return whether one run uses semantics outside the normalized schema."""
+ if run_props is None:
+ return False
+ allowed_children = {
+ "effectLst", "latin", "ea", "cs", "sym", "ln", "solidFill",
+ }
+ for child in run_props:
+ name = child.tag.rsplit("}", 1)[-1]
+ if name not in allowed_children:
+ return True
+ if name == "effectLst" and (child.attrib or list(child)):
+ return True
+ return False
+
+
+def _native_run_outline_payload(
+ line: ET.Element | None,
+ palette: ColorPalette | None,
+) -> dict[str, Any] | None:
+ """Normalize one visible text outline into the shared line schema."""
+ if line is None:
+ return None
+ if line.find("a:noFill", NS) is not None:
+ return None
+ raw_width = line.get("w")
+ if raw_width is None:
+ return None
+ if not raw_width.isdigit() or int(raw_width) == 0:
+ return None
+ return _direct_border_payload(line, palette)
+
+
+def _table_text_has_unsupported_outline(
+ tx_body: ET.Element | None,
+ palette: ColorPalette | None,
+) -> bool:
+ if tx_body is None:
+ return False
+ for run_props in tx_body.findall(".//a:rPr", NS):
+ line = run_props.find("a:ln", NS)
+ if line is None:
+ continue
+ try:
+ _native_run_outline_payload(line, palette)
+ except ValueError:
+ return True
return False
@@ -1196,7 +1237,7 @@ def _native_table_payload(
for row_cells in cells:
row_payload: list[Any] = []
for slot in row_cells:
- if slot is None or slot.is_dropped:
+ if slot is None:
row_payload.append("")
continue
cell_payload = _native_cell_payload(
@@ -1204,6 +1245,10 @@ def _native_table_payload(
palette,
theme_fonts,
)
+ if slot.is_dropped:
+ cell_payload["merge_continuation"] = True
+ row_payload.append(cell_payload)
+ continue
if slot.row_span > 1:
cell_payload["row_span"] = slot.row_span
if slot.col_span > 1:
@@ -1211,7 +1256,7 @@ def _native_table_payload(
row_payload.append(cell_payload)
rows_payload.append(row_payload)
payload["rows"] = rows_payload
- return payload
+ return compact_semantic_table_payload(payload)
def _native_cell_payload(
@@ -1234,9 +1279,11 @@ def _native_cell_payload(
else:
cell = {"text": _cell_plain_text(tx_body)}
- fill = _cell_fill_hex(tc_pr, palette)
+ fill, fill_opacity = _cell_fill_payload(tc_pr, palette)
if fill:
cell["fill"] = fill
+ if fill_opacity is not None:
+ cell["fill_opacity"] = fill_opacity
if rich_paragraphs is None:
color = _cell_text_color(tx_body, palette)
if color:
@@ -1259,6 +1306,7 @@ def _native_cell_payload(
if borders:
cell["borders"] = borders
_copy_cell_margins(tc_pr, cell)
+ _copy_cell_layout_options(tc_pr, cell)
return cell
@@ -1283,7 +1331,7 @@ def _cell_paragraph_payloads(
text = "".join(node.text or "" for node in paragraph.findall(".//a:t", NS))
p_pr = paragraph.find("a:pPr", NS)
align = p_pr.get("algn") if p_pr is not None else None
- if align in {"l", "ctr", "r"}:
+ if align in {"l", "ctr", "r", "just"}:
payloads.append({"text": text, "align": align})
else:
payloads.append(text)
@@ -1378,9 +1426,58 @@ def _native_run_payload(
language = _effective_run_attr(r_pr, default_r_pr, source)
if language and language.strip():
payload[target] = language.strip()
+
+ raw_baseline = _effective_run_attr(r_pr, default_r_pr, "baseline")
+ if raw_baseline is not None:
+ try:
+ baseline = int(raw_baseline)
+ except ValueError:
+ baseline = 0
+ if baseline:
+ payload["baseline_percent"] = _round_payload_number(
+ baseline / 1000.0
+ )
+
+ outline = _native_run_outline_payload(
+ _effective_run_child(r_pr, default_r_pr, "ln"),
+ palette,
+ )
+ if outline is not None:
+ payload["outline"] = outline
return payload
+def _paragraph_line_spacing_percent(
+ p_pr: ET.Element | None,
+) -> int | float | None:
+ if p_pr is None:
+ return None
+ spacing = p_pr.find("a:lnSpc/a:spcPct", NS)
+ raw = spacing.get("val") if spacing is not None else None
+ if raw is None or not raw.isdigit():
+ return None
+ percent = int(raw) / 1000.0
+ if percent == 100:
+ return None
+ return _round_payload_number(percent)
+
+
+def _run_style_signature(run: dict[str, Any]) -> tuple[tuple[str, Any], ...]:
+ """Return one hashable signature for deciding whether runs are required."""
+ return tuple(
+ sorted(
+ (
+ key,
+ json.dumps(value, sort_keys=True, separators=(",", ":"))
+ if isinstance(value, dict)
+ else value,
+ )
+ for key, value in run.items()
+ if key != "text"
+ )
+ )
+
+
def _cell_rich_paragraph_payloads(
tx_body: ET.Element | None,
palette: ColorPalette | None,
@@ -1390,25 +1487,31 @@ def _cell_rich_paragraph_payloads(
if tx_body is None or not _legacy_text_body_has_unsupported_formatting(tx_body):
return None
- paragraphs: list[tuple[str | None, list[dict[str, Any]]]] = []
+ paragraphs: list[
+ tuple[str | None, int | float | None, list[dict[str, Any]]]
+ ] = []
style_signatures: set[tuple[tuple[str, Any], ...]] = set()
needs_runs = False
run_only_fields = {
"italic", "underline", "strike", "font_family", "lang", "alt_lang",
+ "baseline_percent", "outline",
}
for paragraph in tx_body.findall("a:p", NS):
p_pr = paragraph.find("a:pPr", NS)
align = p_pr.get("algn") if p_pr is not None else None
- if align not in {"l", "ctr", "r"}:
+ if align not in {"l", "ctr", "r", "just"}:
align = None
+ line_spacing_percent = _paragraph_line_spacing_percent(p_pr)
default_r_pr = p_pr.find("a:defRPr", NS) if p_pr is not None else None
runs = [
_native_run_payload(run, default_r_pr, palette, theme_fonts)
for run in paragraph.findall("a:r", NS)
]
- paragraphs.append((align, runs))
+ paragraphs.append((align, line_spacing_percent, runs))
+ if line_spacing_percent is not None:
+ needs_runs = True
for run in runs:
- style = tuple(sorted((key, value) for key, value in run.items() if key != "text"))
+ style = _run_style_signature(run)
style_signatures.add(style)
if run_only_fields.intersection(run):
needs_runs = True
@@ -1419,7 +1522,7 @@ def _cell_rich_paragraph_payloads(
return None
payloads: list[dict[str, Any]] = []
- for align, runs in paragraphs:
+ for align, line_spacing_percent, runs in paragraphs:
paragraph_payload: dict[str, Any]
if runs:
paragraph_payload = {"runs": runs}
@@ -1427,16 +1530,28 @@ def _cell_rich_paragraph_payloads(
paragraph_payload = {"text": ""}
if align is not None:
paragraph_payload["align"] = align
+ if line_spacing_percent is not None:
+ paragraph_payload["line_spacing_percent"] = line_spacing_percent
payloads.append(paragraph_payload)
return payloads
-def _cell_fill_hex(tc_pr: ET.Element | None, palette: ColorPalette | None) -> str | None:
+def _cell_fill_payload(
+ tc_pr: ET.Element | None,
+ palette: ColorPalette | None,
+) -> tuple[str | None, int | float | None]:
+ """Return one normalized solid cell fill and optional opacity."""
fill = resolve_fill(tc_pr, palette)
color = fill.attrs.get("fill") if fill.attrs else None
- if color and color.startswith("#"):
- return color
- return None
+ if not color or not color.startswith("#"):
+ return None, None
+ opacity_raw = fill.attrs.get("fill-opacity")
+ opacity = (
+ _round_payload_number(float(opacity_raw))
+ if opacity_raw is not None
+ else None
+ )
+ return color, opacity
def _cell_text_color(tx_body: ET.Element | None, palette: ColorPalette | None) -> str | None:
@@ -1483,7 +1598,7 @@ def _cell_align(tx_body: ET.Element | None) -> str | None:
return None
p_pr = tx_body.find("a:p/a:pPr", NS)
align = p_pr.get("algn") if p_pr is not None else None
- if align in {"l", "ctr", "r"}:
+ if align in {"l", "ctr", "r", "just"}:
return align
return None
@@ -1546,6 +1661,20 @@ def _copy_cell_margins(tc_pr: ET.Element | None, cell: dict[str, Any]) -> None:
cell[target] = _round_payload_number(emu_to_px(value))
+def _copy_cell_layout_options(
+ tc_pr: ET.Element | None,
+ cell: dict[str, Any],
+) -> None:
+ """Copy native cell layout semantics not represented by SVG text."""
+ if tc_pr is None:
+ return
+ if tc_pr.get("anchorCtr") is not None:
+ cell["anchor_center"] = ooxml_bool(tc_pr.get("anchorCtr"))
+ horizontal_overflow = tc_pr.get("horzOverflow")
+ if horizontal_overflow is not None:
+ cell["horizontal_overflow"] = horizontal_overflow
+
+
# ---------------------------------------------------------------------------
# Cell text & borders
# ---------------------------------------------------------------------------
diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.json
index df220e75..09128e22 100644
--- a/skills/ppt-master/scripts/prompt_audit_manifest.json
+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json
@@ -1870,7 +1870,7 @@
{
"path": "skills/ppt-master/templates/spec_lock_reference.md",
"role": "reference",
- "fingerprint": "c35477d35410",
+ "fingerprint": "e5c9c162d0ff",
"reason": "This reference mirrors the owner field grammar or ownership boundary."
},
{
@@ -1882,7 +1882,7 @@
{
"path": "skills/ppt-master/workflows/stages/apply-template-workspace.md",
"role": "compatibility",
- "fingerprint": "1c393e47c311",
+ "fingerprint": "4375357b2252",
"reason": "This site documents a legacy or omission compatibility boundary."
}
]
@@ -2026,7 +2026,7 @@
{
"path": "skills/ppt-master/templates/spec_lock_reference.md",
"role": "reference",
- "fingerprint": "2d6dba6c449e",
+ "fingerprint": "0e01eedc2c4b",
"reason": "This reference mirrors the owner field grammar or ownership boundary."
}
]
diff --git a/skills/ppt-master/scripts/semantic_table.py b/skills/ppt-master/scripts/semantic_table.py
new file mode 100644
index 00000000..fffb1b1a
--- /dev/null
+++ b/skills/ppt-master/scripts/semantic_table.py
@@ -0,0 +1,522 @@
+#!/usr/bin/env python3
+"""Compact and expand the canonical semantic-table.v2 payload."""
+
+from __future__ import annotations
+
+import copy
+import json
+import re
+from collections.abc import Iterable
+from typing import Any
+
+
+SEMANTIC_TABLE_SCHEMA = "ppt-master.semantic-table.v2"
+
+_TOP_LEVEL_FIELDS = {
+ "schema",
+ "name",
+ "x",
+ "y",
+ "width",
+ "height",
+ "strict_grid",
+ "header_rows",
+ "column_widths",
+ "row_heights",
+ "style",
+ "defaults",
+ "cell_styles",
+ "columns",
+ "rows",
+}
+_TABLE_STYLE_FIELDS = {
+ "band_row",
+ "font_family",
+ "font_size",
+ "header_font_size",
+ "header_fill",
+ "header_text",
+ "body_fill",
+ "body_text",
+ "band_fill",
+ "border_color",
+ "border_width",
+ "padding",
+ "valign",
+ "lang",
+ "table_style_id",
+}
+_CELL_FORMAT_FIELDS = (
+ "fill",
+ "fill_opacity",
+ "color",
+ "font_size",
+ "bold",
+ "align",
+ "valign",
+ "borders",
+ "padding",
+ "padding_left",
+ "padding_right",
+ "padding_top",
+ "padding_bottom",
+ "border_color",
+ "border_width",
+ "lang",
+ "anchor_center",
+ "horizontal_overflow",
+)
+_CELL_FIELDS = set(_CELL_FORMAT_FIELDS) | {
+ "text",
+ "paragraphs",
+ "row_span",
+ "col_span",
+ "merge_continuation",
+ "cell_style",
+}
+_PARAGRAPH_DEFAULT_FIELDS = (
+ "align",
+ "line_spacing_percent",
+)
+_PARAGRAPH_FIELDS = set(_PARAGRAPH_DEFAULT_FIELDS) | {"text", "runs"}
+_RUN_DEFAULT_FIELDS = (
+ "bold",
+ "italic",
+ "underline",
+ "strike",
+ "color",
+ "font_size",
+ "font_family",
+ "lang",
+ "alt_lang",
+ "baseline_percent",
+ "outline",
+)
+_RUN_FIELDS = set(_RUN_DEFAULT_FIELDS) | {"text"}
+_DEFAULT_SECTIONS = {
+ "cell": set(_CELL_FORMAT_FIELDS),
+ "paragraph": set(_PARAGRAPH_DEFAULT_FIELDS),
+ "run": set(_RUN_DEFAULT_FIELDS),
+}
+_MERGED_OBJECT_FIELDS = {"padding"}
+_STYLE_NAME_RE = re.compile(r"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$")
+
+
+def _canonical_json(value: Any) -> str:
+ return json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+
+
+def _payload_size(payload: dict[str, Any], defaults: dict[str, Any]) -> int:
+ return len(_canonical_json({"payload": payload, "defaults": defaults}))
+
+
+def _require_object(value: Any, label: str) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise RuntimeError(f"Native PPTX table {label} must be an object")
+ return value
+
+
+def _reject_unknown_fields(
+ value: dict[str, Any],
+ allowed: set[str],
+ label: str,
+) -> None:
+ unknown = sorted(set(value) - allowed)
+ if unknown:
+ raise RuntimeError(
+ f"Native PPTX table {label} contains unsupported field(s): "
+ + ", ".join(unknown)
+ )
+
+
+def _format_layers(*layers: dict[str, Any]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for layer in layers:
+ for key, value in layer.items():
+ if (
+ key in _MERGED_OBJECT_FIELDS
+ and isinstance(value, dict)
+ and isinstance(result.get(key), dict)
+ ):
+ merged = copy.deepcopy(result[key])
+ merged.update(copy.deepcopy(value))
+ result[key] = merged
+ else:
+ result[key] = copy.deepcopy(value)
+ return result
+
+
+def _validated_defaults(payload: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ raw_defaults = payload.get("defaults", {})
+ defaults = _require_object(raw_defaults, "defaults")
+ _reject_unknown_fields(defaults, set(_DEFAULT_SECTIONS), "defaults")
+ result: dict[str, dict[str, Any]] = {}
+ for section, allowed in _DEFAULT_SECTIONS.items():
+ raw_section = defaults.get(section, {})
+ section_data = _require_object(raw_section, f"defaults.{section}")
+ _reject_unknown_fields(
+ section_data,
+ allowed,
+ f"defaults.{section}",
+ )
+ result[section] = copy.deepcopy(section_data)
+ return result
+
+
+def _validated_cell_styles(payload: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ raw_styles = payload.get("cell_styles", {})
+ styles = _require_object(raw_styles, "cell_styles")
+ result: dict[str, dict[str, Any]] = {}
+ for name, raw_style in styles.items():
+ if not isinstance(name, str) or not _STYLE_NAME_RE.fullmatch(name):
+ raise RuntimeError(
+ "Native PPTX table cell style names must use lower-case kebab-case"
+ )
+ style = _require_object(raw_style, f"cell_styles.{name}")
+ _reject_unknown_fields(
+ style,
+ set(_CELL_FORMAT_FIELDS),
+ f"cell_styles.{name}",
+ )
+ result[name] = copy.deepcopy(style)
+ return result
+
+
+def _expand_run(value: Any, run_defaults: dict[str, Any]) -> dict[str, Any]:
+ run = _require_object(value, "run")
+ _reject_unknown_fields(run, _RUN_FIELDS, "run")
+ return _format_layers(run_defaults, run)
+
+
+def _expand_paragraph(
+ value: Any,
+ paragraph_defaults: dict[str, Any],
+ run_defaults: dict[str, Any],
+) -> dict[str, Any]:
+ if isinstance(value, str):
+ paragraph = {"text": value}
+ else:
+ paragraph = _require_object(value, "paragraph")
+ _reject_unknown_fields(paragraph, _PARAGRAPH_FIELDS, "paragraph")
+ expanded = _format_layers(paragraph_defaults, paragraph)
+ if "runs" in expanded:
+ runs = expanded["runs"]
+ if not isinstance(runs, list):
+ raise RuntimeError("Native PPTX table paragraph runs must be a list")
+ expanded["runs"] = [_expand_run(run, run_defaults) for run in runs]
+ return expanded
+
+
+def _expand_cell(
+ value: Any,
+ defaults: dict[str, dict[str, Any]],
+ cell_styles: dict[str, dict[str, Any]],
+) -> dict[str, Any]:
+ if isinstance(value, dict):
+ cell = copy.deepcopy(value)
+ _reject_unknown_fields(cell, _CELL_FIELDS, "cell")
+ else:
+ cell = {"text": "" if value is None else str(value)}
+
+ style_name = cell.pop("cell_style", None)
+ if style_name is None:
+ style = {}
+ elif not isinstance(style_name, str) or style_name not in cell_styles:
+ raise RuntimeError(
+ f"Native PPTX table cell references unknown cell_style: {style_name!r}"
+ )
+ else:
+ style = cell_styles[style_name]
+
+ expanded = _format_layers(defaults["cell"], style, cell)
+ if "paragraphs" in expanded:
+ paragraphs = expanded["paragraphs"]
+ if not isinstance(paragraphs, list):
+ raise RuntimeError("Native PPTX table cell paragraphs must be a list")
+ expanded["paragraphs"] = [
+ _expand_paragraph(
+ paragraph,
+ defaults["paragraph"],
+ defaults["run"],
+ )
+ for paragraph in paragraphs
+ ]
+ return expanded
+
+
+def expand_semantic_table_payload(payload: dict[str, Any]) -> dict[str, Any]:
+ """Expand semantic-table.v2 defaults and named styles into canonical cells."""
+ source = _require_object(payload, "payload")
+ if source.get("schema") != SEMANTIC_TABLE_SCHEMA:
+ raise RuntimeError(
+ "Native PPTX table metadata requires schema "
+ f"{SEMANTIC_TABLE_SCHEMA!r}"
+ )
+ _reject_unknown_fields(source, _TOP_LEVEL_FIELDS, "payload")
+ style = source.get("style", {})
+ if not isinstance(style, dict):
+ raise RuntimeError("Native PPTX table style must be an object")
+ _reject_unknown_fields(style, _TABLE_STYLE_FIELDS, "style")
+
+ defaults = _validated_defaults(source)
+ cell_styles = _validated_cell_styles(source)
+ expanded = {
+ key: copy.deepcopy(value)
+ for key, value in source.items()
+ if key not in {"schema", "defaults", "cell_styles", "columns", "rows"}
+ }
+ if "columns" in source:
+ columns = source["columns"]
+ if not isinstance(columns, list):
+ raise RuntimeError("Native PPTX table columns must be a list")
+ expanded["columns"] = [
+ _expand_cell(cell, defaults, cell_styles) for cell in columns
+ ]
+ if "rows" in source:
+ rows = source["rows"]
+ if not isinstance(rows, list):
+ raise RuntimeError("Native PPTX table rows must be a list")
+ expanded_rows: list[list[dict[str, Any]]] = []
+ for row_index, row in enumerate(rows, start=1):
+ if not isinstance(row, list):
+ raise RuntimeError(
+ f"Native PPTX table row {row_index} must be a list"
+ )
+ expanded_rows.append(
+ [_expand_cell(cell, defaults, cell_styles) for cell in row]
+ )
+ expanded["rows"] = expanded_rows
+ return expanded
+
+
+def _iter_cells(payload: dict[str, Any]) -> Iterable[dict[str, Any]]:
+ columns = payload.get("columns")
+ if isinstance(columns, list):
+ for cell in columns:
+ if isinstance(cell, dict):
+ yield cell
+ rows = payload.get("rows")
+ if isinstance(rows, list):
+ for row in rows:
+ if not isinstance(row, list):
+ continue
+ for cell in row:
+ if isinstance(cell, dict):
+ yield cell
+
+
+def _iter_paragraphs(cells: Iterable[dict[str, Any]]) -> Iterable[dict[str, Any]]:
+ for cell in cells:
+ paragraphs = cell.get("paragraphs")
+ if not isinstance(paragraphs, list):
+ continue
+ for paragraph in paragraphs:
+ if isinstance(paragraph, dict):
+ yield paragraph
+
+
+def _iter_runs(paragraphs: Iterable[dict[str, Any]]) -> Iterable[dict[str, Any]]:
+ for paragraph in paragraphs:
+ runs = paragraph.get("runs")
+ if not isinstance(runs, list):
+ continue
+ for run in runs:
+ if isinstance(run, dict):
+ yield run
+
+
+def _most_common_value(items: list[dict[str, Any]], field: str) -> Any:
+ counts: dict[str, int] = {}
+ values: dict[str, Any] = {}
+ order: list[str] = []
+ for item in items:
+ signature = _canonical_json(item[field])
+ if signature not in counts:
+ counts[signature] = 0
+ values[signature] = item[field]
+ order.append(signature)
+ counts[signature] += 1
+ winner = max(order, key=lambda signature: counts[signature])
+ return copy.deepcopy(values[winner])
+
+
+def _promote_defaults(
+ payload: dict[str, Any],
+ defaults: dict[str, dict[str, Any]],
+ section: str,
+ items: list[dict[str, Any]],
+ fields: tuple[str, ...],
+) -> None:
+ if not items:
+ return
+ for field in fields:
+ if any(field not in item for item in items):
+ continue
+ value = _most_common_value(items, field)
+ before = _payload_size(payload, defaults)
+ matching = [item for item in items if item[field] == value]
+ defaults[section][field] = value
+ for item in matching:
+ del item[field]
+ after = _payload_size(payload, defaults)
+ if after < before:
+ continue
+ del defaults[section][field]
+ for item in matching:
+ item[field] = copy.deepcopy(value)
+
+
+def _compact_plain_paragraphs(payload: dict[str, Any]) -> None:
+ for cell in _iter_cells(payload):
+ paragraphs = cell.get("paragraphs")
+ if not isinstance(paragraphs, list):
+ continue
+ for index, paragraph in enumerate(paragraphs):
+ if (
+ isinstance(paragraph, dict)
+ and set(paragraph) == {"text"}
+ and isinstance(paragraph["text"], str)
+ ):
+ paragraphs[index] = paragraph["text"]
+
+
+def _cell_style_signature(cell: dict[str, Any]) -> dict[str, Any]:
+ return {
+ field: copy.deepcopy(cell[field])
+ for field in _CELL_FORMAT_FIELDS
+ if field in cell
+ }
+
+
+def _factor_cell_styles(
+ payload: dict[str, Any],
+ defaults: dict[str, dict[str, Any]],
+) -> dict[str, dict[str, Any]]:
+ cells = list(_iter_cells(payload))
+ signatures: dict[str, dict[str, Any]] = {}
+ matching_cells: dict[str, list[dict[str, Any]]] = {}
+ order: list[str] = []
+ for cell in cells:
+ style = _cell_style_signature(cell)
+ if not style:
+ continue
+ signature = _canonical_json(style)
+ if signature not in signatures:
+ signatures[signature] = style
+ matching_cells[signature] = []
+ order.append(signature)
+ matching_cells[signature].append(cell)
+
+ cell_styles: dict[str, dict[str, Any]] = {}
+ for signature in order:
+ matched = matching_cells[signature]
+ if len(matched) < 2:
+ continue
+ name = f"cell-{len(cell_styles) + 1}"
+ before = len(
+ _canonical_json(
+ {"payload": payload, "defaults": defaults, "cell_styles": cell_styles}
+ )
+ )
+ style = signatures[signature]
+ cell_styles[name] = copy.deepcopy(style)
+ for cell in matched:
+ for field in style:
+ del cell[field]
+ cell["cell_style"] = name
+ after = len(
+ _canonical_json(
+ {"payload": payload, "defaults": defaults, "cell_styles": cell_styles}
+ )
+ )
+ if after < before:
+ continue
+ del cell_styles[name]
+ for cell in matched:
+ del cell["cell_style"]
+ cell.update(copy.deepcopy(style))
+ return cell_styles
+
+
+def compact_semantic_table_payload(payload: dict[str, Any]) -> dict[str, Any]:
+ """Return a deterministic, lossless semantic-table.v2 representation."""
+ source = _require_object(payload, "payload")
+ if "schema" in source:
+ working = expand_semantic_table_payload(source)
+ else:
+ working = copy.deepcopy(source)
+
+ defaults: dict[str, dict[str, Any]] = {
+ "cell": {},
+ "paragraph": {},
+ "run": {},
+ }
+ cells = list(_iter_cells(working))
+ total_cells = len(working.get("columns", [])) + sum(
+ len(row) for row in working.get("rows", []) if isinstance(row, list)
+ )
+ if cells and len(cells) == total_cells:
+ _promote_defaults(
+ working,
+ defaults,
+ "cell",
+ cells,
+ _CELL_FORMAT_FIELDS,
+ )
+
+ paragraphs = list(_iter_paragraphs(cells))
+ paragraph_count = sum(
+ len(cell["paragraphs"])
+ for cell in cells
+ if isinstance(cell.get("paragraphs"), list)
+ )
+ if paragraphs and len(paragraphs) == paragraph_count:
+ _promote_defaults(
+ working,
+ defaults,
+ "paragraph",
+ paragraphs,
+ _PARAGRAPH_DEFAULT_FIELDS,
+ )
+
+ runs = list(_iter_runs(paragraphs))
+ run_count = sum(
+ len(paragraph["runs"])
+ for paragraph in paragraphs
+ if isinstance(paragraph.get("runs"), list)
+ )
+ if runs and len(runs) == run_count:
+ _promote_defaults(
+ working,
+ defaults,
+ "run",
+ runs,
+ _RUN_DEFAULT_FIELDS,
+ )
+
+ _compact_plain_paragraphs(working)
+ cell_styles = _factor_cell_styles(working, defaults)
+ compact_defaults = {
+ section: values for section, values in defaults.items() if values
+ }
+
+ result: dict[str, Any] = {"schema": SEMANTIC_TABLE_SCHEMA}
+ for key, value in working.items():
+ if key not in {"columns", "rows"}:
+ result[key] = value
+ if compact_defaults:
+ result["defaults"] = compact_defaults
+ if cell_styles:
+ result["cell_styles"] = cell_styles
+ if "columns" in working:
+ result["columns"] = working["columns"]
+ if "rows" in working:
+ result["rows"] = working["rows"]
+
+ expand_semantic_table_payload(result)
+ return result
diff --git a/skills/ppt-master/scripts/svg_authoring_view.py b/skills/ppt-master/scripts/svg_authoring_view.py
index 6404f289..ac653bbd 100644
--- a/skills/ppt-master/scripts/svg_authoring_view.py
+++ b/skills/ppt-master/scripts/svg_authoring_view.py
@@ -4,8 +4,9 @@ PPT Master - SVG Authoring View
Create a lightweight, non-destructive editable IR from PPTX-imported SVG
files. The source SVG remains the native-payload authority; the authoring copy
-keeps visible SVG content, compact shape intent, and stable source references
-while hiding bulky import-only payloads and duplicate hidden geometry carriers.
+translates recognized shapes and tables into compact semantic components,
+keeps stable source references, and omits bulky import-only/render-duplicate
+payloads.
Usage:
python3 scripts/svg_authoring_view.py <svg-file-or-directory> \
@@ -36,6 +37,7 @@ import argparse
import copy
import hashlib
import json
+import math
import os
import re
import shutil
@@ -49,7 +51,12 @@ from urllib.parse import urlsplit, urlunsplit
from xml.etree import ElementTree as ET
from compact_svg_coordinates import compact_svg_tree
+from compact_svg_styles import compact_svg_style_tree
from console_encoding import configure_utf8_stdio
+from pptx_shapes import (
+ NATIVE_FALLBACK_SHA256_ATTR,
+ svg_native_fallback_fingerprint,
+)
from svg_compatibility import normalize_single_child_group_filters
configure_utf8_stdio()
@@ -63,6 +70,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"
+SEMANTIC_OBJECT_ATTRIBUTE = "data-pptx-semantic-object"
+SEMANTIC_SHAPE_KIND = "shape"
+SEMANTIC_TABLE_KIND = "table"
# Keep ordinary text and vectors inline. Large semantic/native payload objects
# that cannot move to an editable vector asset become atomic source proxies.
SOURCE_PROXY_MIN_BYTES = 4096
@@ -77,6 +87,7 @@ _DRAWABLE_TAGS = frozenset({
"rect",
})
_URL_ID_RE = re.compile(r"url\(\s*(['\"]?)#([^)'\"\s]+)\1\s*\)")
+_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
ET.register_namespace("", SVG_NS)
ET.register_namespace("xlink", XLINK_NS)
@@ -92,7 +103,11 @@ AUTHORING_OMITTED_SOURCE_ATTRIBUTES = {
"data-pptx-gradient-ooxml",
"data-pptx-gradient-ooxml-sha256",
"data-pptx-gradient-preview-sha256",
+ "data-pptx-custgeom",
+ "data-pptx-geometry-sha256",
"data-pptx-preview-sha256",
+ NATIVE_FALLBACK_SHA256_ATTR,
+ "data-pptx-roundtrip-object",
"data-pptx-shape-id",
"data-pptx-shape-name",
"data-pptx-shape-scope",
@@ -282,6 +297,25 @@ def _index_initial_authoring_references(
)
+def _fresh_native_fallback_markers(root: ET.Element) -> set[ET.Element]:
+ """Return native markers whose source fallback guard is currently valid."""
+ fresh: set[ET.Element] = set()
+ for element in root.iter():
+ expected = element.get(NATIVE_FALLBACK_SHA256_ATTR)
+ if (
+ expected is None
+ or expected != expected.strip()
+ or _SHA256_RE.fullmatch(expected) is None
+ ):
+ continue
+ if svg_native_fallback_fingerprint(
+ element,
+ document_root=root,
+ ) == expected.lower():
+ fresh.add(element)
+ return fresh
+
+
@dataclass
class ProjectionStats:
txbody_metadata: int = 0
@@ -291,10 +325,14 @@ class ProjectionStats:
compatibility_normalizations: int = 0
asset_references_rewritten: int = 0
coordinate_attributes_compacted: int = 0
+ style_declarations_compacted: int = 0
inherited_text_attributes_compacted: int = 0
single_tspans_collapsed: int = 0
source_object_proxies: int = 0
source_object_proxy_bytes: int = 0
+ semantic_shapes: int = 0
+ semantic_tables: int = 0
+ semantic_table_preview_bytes: int = 0
unused_definitions_pruned: int = 0
source_attributes: Counter[str] = field(default_factory=Counter)
@@ -308,12 +346,16 @@ class ProjectionStats:
"source_attributes": dict(sorted(self.source_attributes.items())),
"asset_references_rewritten": self.asset_references_rewritten,
"coordinate_attributes_compacted": self.coordinate_attributes_compacted,
+ "style_declarations_compacted": self.style_declarations_compacted,
"inherited_text_attributes_compacted": (
self.inherited_text_attributes_compacted
),
"single_tspans_collapsed": self.single_tspans_collapsed,
"source_object_proxies": self.source_object_proxies,
"source_object_proxy_bytes": self.source_object_proxy_bytes,
+ "semantic_shapes": self.semantic_shapes,
+ "semantic_tables": self.semantic_tables,
+ "semantic_table_preview_bytes": self.semantic_table_preview_bytes,
"unused_definitions_pruned": self.unused_definitions_pruned,
}
@@ -327,12 +369,16 @@ class ProjectionStats:
self.coordinate_attributes_compacted += (
other.coordinate_attributes_compacted
)
+ self.style_declarations_compacted += other.style_declarations_compacted
self.inherited_text_attributes_compacted += (
other.inherited_text_attributes_compacted
)
self.single_tspans_collapsed += other.single_tspans_collapsed
self.source_object_proxies += other.source_object_proxies
self.source_object_proxy_bytes += other.source_object_proxy_bytes
+ self.semantic_shapes += other.semantic_shapes
+ self.semantic_tables += other.semantic_tables
+ self.semantic_table_preview_bytes += other.semantic_table_preview_bytes
self.unused_definitions_pruned += other.unused_definitions_pruned
self.source_attributes.update(other.source_attributes)
@@ -379,6 +425,376 @@ def _is_hidden_geometry_carrier(element: ET.Element) -> bool:
)
+def _is_semantic_shape_candidate(element: ET.Element) -> bool:
+ if (
+ _local_name(element.tag) != "g"
+ or element.get("data-pptx-object") not in {"shape", "connector"}
+ or (
+ element.get("data-pptx-prst") is None
+ and element.get("data-pptx-geometry-kind") != "custom"
+ )
+ ):
+ return False
+ if any(
+ name in element.attrib
+ for name in (
+ "data-pptx-placeholder",
+ "data-pptx-placeholder-type",
+ "data-pptx-placeholder-idx",
+ )
+ ):
+ return False
+ if any(
+ item.get("data-pptx-effect-status") == "unsupported"
+ or item.get("data-pptx-effect-ooxml") is not None
+ for item in element.iter()
+ ):
+ return False
+ carriers = [
+ child
+ for child in element
+ if child.get("data-pptx-part") == "geometry"
+ and _local_name(child.tag) in _DRAWABLE_TAGS
+ ]
+ if len(carriers) != 1:
+ return False
+ visible_texts = [
+ item
+ for item in element.iter()
+ if _local_name(item.tag) == "text"
+ ]
+ if any(text not in list(element) for text in visible_texts):
+ return False
+ if any(
+ item.get("data-pptx-inline-formula") is not None
+ for text in visible_texts
+ for item in text.iter()
+ ):
+ return False
+ positional_texts = [
+ text
+ for text in visible_texts
+ if any(
+ _local_name(item.tag) == "tspan"
+ and any(item.get(name) is not None for name in ("x", "y", "dy"))
+ for item in text.iter()
+ )
+ ]
+ if len(visible_texts) > 1 and positional_texts:
+ return False
+ for text in positional_texts:
+ try:
+ if not _normalize_semantic_text_lines(copy.deepcopy(text)):
+ return False
+ except ValueError:
+ return False
+ if element.get("data-pptx-object") == "connector" and visible_texts:
+ return False
+ if len(visible_texts) > 1:
+ if any(text.get("transform") is not None for text in visible_texts):
+ return False
+ anchors = {
+ (item.get("x"), item.get("text-anchor", "start"))
+ for item in visible_texts
+ }
+ if len(anchors) != 1:
+ return False
+ try:
+ baselines = [_semantic_text_baseline(text) for text in visible_texts]
+ except ValueError:
+ return False
+ if any(current <= previous for previous, current in zip(
+ baselines,
+ baselines[1:],
+ )):
+ return False
+ for child in element:
+ tag = _local_name(child.tag)
+ part = child.get("data-pptx-part")
+ if child is carriers[0] or tag in {"metadata", "text", "a"}:
+ continue
+ if part in {"geometry-preview", "placeholder-sppr"}:
+ continue
+ if tag == "g" and all(
+ _local_name(item.tag) in {"g", "text", "tspan", "a"}
+ for item in child.iter()
+ ):
+ continue
+ return False
+ return True
+
+
+def _mark_semantic_objects(root: ET.Element, stats: ProjectionStats) -> None:
+ """Mark source objects whose authoring truth has a closed semantic IR."""
+ for element in root.iter():
+ if element.get("data-pptx-replace-with") == SEMANTIC_TABLE_KIND:
+ element.set(SEMANTIC_OBJECT_ATTRIBUTE, SEMANTIC_TABLE_KIND)
+ stats.semantic_tables += 1
+ continue
+ if _is_semantic_shape_candidate(element):
+ element.set(SEMANTIC_OBJECT_ATTRIBUTE, SEMANTIC_SHAPE_KIND)
+ stats.semantic_shapes += 1
+
+
+def _make_geometry_carrier_visible(element: ET.Element) -> int:
+ """Turn one import-only hidden carrier into the authored geometry surface."""
+ changed = 0
+ for name in ("visibility", "display", "pointer-events"):
+ if name in element.attrib:
+ del element.attrib[name]
+ changed += 1
+
+ style = element.get("style")
+ if style is not None:
+ declarations = [
+ declaration.strip()
+ for declaration in style.split(";")
+ if declaration.strip()
+ ]
+ retained = [
+ declaration
+ for declaration in declarations
+ if declaration.split(":", 1)[0].strip().lower()
+ not in {"display", "pointer-events", "visibility"}
+ ]
+ normalized = "; ".join(retained)
+ if normalized:
+ if normalized != style:
+ element.set("style", normalized)
+ changed += 1
+ else:
+ del element.attrib["style"]
+ changed += 1
+ return changed
+
+
+def _semantic_text_baseline(element: ET.Element) -> float:
+ raw = element.get("y")
+ if raw is None:
+ raise ValueError("Semantic shape text requires an explicit y baseline")
+ try:
+ value = float(raw)
+ except ValueError as exc:
+ raise ValueError(
+ f"Semantic shape text has a non-numeric y baseline: {raw!r}"
+ ) from exc
+ if not math.isfinite(value):
+ raise ValueError(
+ f"Semantic shape text has a non-finite y baseline: {raw!r}"
+ )
+ return value
+
+
+def _semantic_text_font_size(element: ET.Element) -> float:
+ raw = element.get("font-size")
+ if raw is None:
+ return 16.0
+ try:
+ value = float(raw)
+ except ValueError:
+ return 16.0
+ return value if math.isfinite(value) and value > 0 else 16.0
+
+
+def _semantic_text_has_content(element: ET.Element) -> bool:
+ return bool("".join(element.itertext()))
+
+
+def _normalize_semantic_text_lines(text: ET.Element) -> bool:
+ """Lower compatible positioned tspans into one semantic line model."""
+ positional = [
+ child
+ for child in text
+ if _local_name(child.tag) == "tspan"
+ and any(child.get(name) is not None for name in ("x", "y", "dy"))
+ ]
+ if not positional:
+ return False
+
+ parent_x = text.get("x")
+ advances: list[float] = []
+ for child in positional:
+ if child.get("y") is not None:
+ raise ValueError(
+ "Semantic shape text cannot normalize an absolute tspan y"
+ )
+ child_x = child.get("x")
+ if child_x is not None and child_x != parent_x:
+ raise ValueError(
+ "Semantic shape text cannot normalize a tspan x jump"
+ )
+ raw_dy = child.get("dy")
+ try:
+ advance = float(raw_dy or "0")
+ except ValueError as exc:
+ raise ValueError(
+ f"Semantic shape text has a non-numeric tspan dy: {raw_dy!r}"
+ ) from exc
+ if not math.isfinite(advance) or advance <= 0:
+ raise ValueError(
+ f"Semantic shape text requires a positive finite tspan dy: {raw_dy!r}"
+ )
+ advances.append(advance)
+
+ first_line = ET.Element(f"{{{SVG_NS}}}tspan")
+ first_line.text = text.text
+ lines: list[ET.Element] = [first_line]
+ current = first_line
+ for child in list(text):
+ clone = copy.deepcopy(child)
+ if child in positional:
+ for name in ("x", "y", "dy"):
+ clone.attrib.pop(name, None)
+ clone.set("data-paragraph-line-break", "1")
+ lines.append(clone)
+ current = clone
+ continue
+ current.append(clone)
+
+ lines = [line for line in lines if _semantic_text_has_content(line)]
+ if len(lines) < 2:
+ return False
+ for child in list(text):
+ text.remove(child)
+ text.text = None
+ text.set("data-pptx-text-model", "lines")
+ line_height = min(advances)
+ text.set(
+ "data-paragraph-line-height",
+ f"{line_height:.6f}".rstrip("0").rstrip("."),
+ )
+ for line in lines:
+ text.append(line)
+ return True
+
+
+def _semantic_paragraph_from_text(
+ source: ET.Element,
+ parent: ET.Element,
+ *,
+ space_before: float,
+) -> ET.Element:
+ """Wrap one rendered SVG text line as one semantic paragraph run tree."""
+ paragraph = ET.Element(f"{{{SVG_NS}}}tspan")
+ presentation_attributes = _TSPAN_INHERITED_ATTRIBUTES | {
+ "baseline-shift",
+ "opacity",
+ "stroke-linecap",
+ "stroke-linejoin",
+ "stroke-width",
+ "style",
+ }
+ for name in presentation_attributes:
+ value = source.get(name)
+ if value is not None and value != parent.get(name):
+ paragraph.set(name, value)
+ if space_before > 0:
+ paragraph.set(
+ "data-paragraph-space-before",
+ f"{space_before:.6f}".rstrip("0").rstrip("."),
+ )
+ paragraph.text = source.text
+ for child in source:
+ paragraph.append(copy.deepcopy(child))
+ return paragraph
+
+
+def _merge_semantic_shape_texts(
+ shape: ET.Element,
+ texts: list[ET.Element],
+) -> ET.Element:
+ """Represent multiple rendered text rows as one paragraph-based text body."""
+ baselines = [_semantic_text_baseline(text) for text in texts]
+ positive_advances = [
+ current - previous
+ for previous, current in zip(baselines, baselines[1:])
+ if current > previous
+ ]
+ line_height = _semantic_text_font_size(texts[0]) * 1.5
+ if positive_advances:
+ line_height = min(line_height, min(positive_advances))
+ line_height = max(line_height, 1.0)
+
+ combined = copy.deepcopy(texts[0])
+ for child in list(combined):
+ combined.remove(child)
+ combined.text = None
+ combined.set("data-pptx-text-model", "paragraphs")
+ combined.set(
+ "data-paragraph-line-height",
+ f"{line_height:.6f}".rstrip("0").rstrip("."),
+ )
+ previous_baseline = baselines[0]
+ for index, (source, baseline) in enumerate(zip(texts, baselines)):
+ space_before = (
+ 0.0
+ if index == 0
+ else max(0.0, baseline - previous_baseline - line_height)
+ )
+ combined.append(
+ _semantic_paragraph_from_text(
+ source,
+ combined,
+ space_before=space_before,
+ )
+ )
+ previous_baseline = baseline
+
+ siblings = list(shape)
+ first_index = siblings.index(texts[0])
+ for text in texts:
+ shape.remove(text)
+ shape.insert(first_index, combined)
+ return combined
+
+
+def _compact_semantic_shapes(root: ET.Element, stats: ProjectionStats) -> None:
+ """Collapse each semantic shape to one geometry carrier and one text body."""
+ for shape in root.iter():
+ if shape.get(SEMANTIC_OBJECT_ATTRIBUTE) != SEMANTIC_SHAPE_KIND:
+ continue
+ carriers = [
+ child
+ for child in shape
+ if child.get("data-pptx-part") == "geometry"
+ and _local_name(child.tag) in _DRAWABLE_TAGS
+ ]
+ if len(carriers) != 1:
+ raise ValueError("Semantic shape requires exactly one geometry carrier")
+ carrier = carriers[0]
+ stats.compatibility_normalizations += _make_geometry_carrier_visible(carrier)
+
+ direct_texts = [
+ child for child in shape
+ if _local_name(child.tag) == "text"
+ ]
+ all_texts = [
+ item for item in shape.iter()
+ if _local_name(item.tag) == "text"
+ ]
+ for text in direct_texts:
+ if _normalize_semantic_text_lines(text):
+ stats.compatibility_normalizations += 1
+ if len(all_texts) > 1:
+ if direct_texts != all_texts:
+ raise ValueError(
+ "Multi-paragraph semantic shape text must be direct children"
+ )
+ _merge_semantic_shape_texts(shape, direct_texts)
+
+ for child in list(shape):
+ if child is carrier:
+ continue
+ tag = _local_name(child.tag)
+ part = child.get("data-pptx-part")
+ if tag in _DRAWABLE_TAGS or part in {
+ "geometry-detail",
+ "geometry-preview",
+ }:
+ _remove_child(shape, child)
+ stats.compatibility_normalizations += 1
+
+
def _append_tail(parent: ET.Element, index: int, tail: str | None) -> None:
if not tail:
return
@@ -470,7 +886,10 @@ def _project_subtree(parent: ET.Element, stats: ProjectionStats) -> None:
_remove_child(parent, child)
continue
- if _is_hidden_geometry_carrier(child):
+ if (
+ _is_hidden_geometry_carrier(child)
+ and parent.get(SEMANTIC_OBJECT_ATTRIBUTE) != SEMANTIC_SHAPE_KIND
+ ):
stats.hidden_geometry_carriers += 1
_remove_child(parent, child)
continue
@@ -638,11 +1057,16 @@ def _source_proxy_asset_bytes(
authoring_dir: Path,
proxy_dir: Path,
stats: ProjectionStats,
+ *,
+ strip_element_transform: bool = False,
) -> bytes:
asset_root = ET.Element(root.tag, dict(root.attrib))
for definitions in _selected_definitions(root, [element]):
asset_root.append(definitions)
- asset_root.append(copy.deepcopy(element))
+ asset_element = copy.deepcopy(element)
+ if strip_element_transform:
+ asset_element.attrib.pop("transform", None)
+ asset_root.append(asset_element)
for item in asset_root.iter():
item.attrib.pop(SOURCE_REF_ATTRIBUTE, None)
item.attrib.pop(SOURCE_PROXY_ATTRIBUTE, None)
@@ -697,6 +1121,72 @@ def _source_proxy_element(
return proxy
+def _compact_semantic_tables(
+ root: ET.Element,
+ references: list[SourceReference],
+ output_dir: Path,
+ preview_dir: Path,
+ stats: ProjectionStats,
+) -> dict[Path, bytes]:
+ """Keep table data inline while moving only its rendered preview aside."""
+ assets: dict[Path, bytes] = {}
+ reference_by_id = {
+ reference.source_ref: reference
+ for reference in references
+ }
+ for element in list(root.iter()):
+ if element.get(SEMANTIC_OBJECT_ATTRIBUTE) != SEMANTIC_TABLE_KIND:
+ continue
+ source_ref = element.get(SOURCE_REF_ATTRIBUTE)
+ if not source_ref or source_ref not in reference_by_id:
+ raise ValueError("Semantic table has no source reference")
+ payload_metadata = [
+ child
+ for child in element
+ if _local_name(child.tag) == "metadata"
+ and child.get("type") == "application/json"
+ ]
+ if len(payload_metadata) != 1:
+ raise ValueError(
+ f"Semantic table {source_ref} requires exactly one JSON payload"
+ )
+
+ preview_source = copy.deepcopy(element)
+ for child in list(preview_source):
+ if _local_name(child.tag) == "metadata":
+ preview_source.remove(child)
+ payload = _source_proxy_asset_bytes(
+ root,
+ preview_source,
+ output_dir,
+ preview_dir,
+ stats,
+ strip_element_transform=True,
+ )
+ digest = hashlib.sha256(payload).hexdigest()
+ asset_path = preview_dir / f"semantic-table-preview-{digest}.svg"
+ previous = assets.get(asset_path)
+ if previous is not None and previous != payload:
+ raise ValueError(f"Semantic table preview hash collision: {asset_path.name}")
+ assets[asset_path] = payload
+
+ metadata = payload_metadata[0]
+ metadata.tail = None
+ for child in list(element):
+ element.remove(child)
+ element.append(metadata)
+ preview = ET.Element(f"{{{SVG_NS}}}image")
+ preview.attrib.update(_proxy_canvas_attributes(root))
+ preview.set(
+ "href",
+ os.path.relpath(asset_path, output_dir).replace(os.sep, "/"),
+ )
+ preview.set("data-pptx-part", "authoring-preview")
+ element.append(preview)
+ stats.semantic_table_preview_bytes += len(payload)
+ return assets
+
+
def _prefer_editable_vector_asset(element: ET.Element) -> bool:
"""Keep pure vector decorations available for later `<use>` extraction."""
if any(
@@ -739,6 +1229,11 @@ def _externalize_large_source_objects(
visit(root, False)
assets: dict[Path, bytes] = {}
for parent, element in candidates:
+ if element.get(SEMANTIC_OBJECT_ATTRIBUTE) in {
+ SEMANTIC_SHAPE_KIND,
+ SEMANTIC_TABLE_KIND,
+ }:
+ continue
original_bytes = len(ET.tostring(element, encoding="utf-8"))
if (
original_bytes < SOURCE_PROXY_MIN_BYTES
@@ -808,8 +1303,11 @@ def _render_projection(
if _local_name(root.tag) != "svg":
raise ValueError(f"Root element is not <svg>: {source}")
+ fresh_native_markers = _fresh_native_fallback_markers(root)
source_references = _stamp_source_references(root)
stats = ProjectionStats()
+ _mark_semantic_objects(root, stats)
+ _compact_semantic_shapes(root, stats)
_project_subtree(root, stats)
_compact_text_runs(root, stats)
stats.compatibility_normalizations += len(
@@ -820,14 +1318,33 @@ def _render_projection(
stats.coordinate_attributes_compacted = compact_svg_tree(
root,
).changed_attributes
+ stats.style_declarations_compacted = compact_svg_style_tree(
+ root,
+ ).changed_declarations
source_proxy_assets: dict[Path, bytes] = {}
if source_proxy_dir is not None:
- source_proxy_assets = _externalize_large_source_objects(
+ source_proxy_assets.update(_compact_semantic_tables(
+ root,
+ source_references,
+ output.parent,
+ source_proxy_dir,
+ stats,
+ ))
+ source_proxy_assets.update(_externalize_large_source_objects(
root,
source_references,
output.parent,
source_proxy_dir,
stats,
+ ))
+ live_elements = set(root.iter())
+ for marker in fresh_native_markers & live_elements:
+ if marker.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_TABLE_KIND:
+ marker.attrib.pop(NATIVE_FALLBACK_SHA256_ATTR, None)
+ continue
+ marker.set(
+ NATIVE_FALLBACK_SHA256_ATTR,
+ svg_native_fallback_fingerprint(marker, document_root=root),
)
_index_initial_authoring_references(root, source_references)
@@ -961,6 +1478,14 @@ def _authoring_summary_document(
element.get(SOURCE_PROXY_ATTRIBUTE) == SOURCE_PROXY_KIND
for element in elements
),
+ "semantic_tables": sum(
+ element.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_TABLE_KIND
+ for element in elements
+ ),
+ "semantic_shapes": sum(
+ element.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_SHAPE_KIND
+ for element in elements
+ ),
}
@@ -1064,6 +1589,14 @@ def _authoring_summary_bytes(authoring_dir: Path) -> bytes:
int(document["source_proxies"])
for document in documents
),
+ "semantic_tables": sum(
+ int(document["semantic_tables"])
+ for document in documents
+ ),
+ "semantic_shapes": sum(
+ int(document["semantic_shapes"])
+ for document in documents
+ ),
"machine_source_refs": manifest.get("source_ref_count"),
}
payload = {
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index 0c8835b1..7774450a 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import base64
import binascii
+import copy
import hashlib
import math
import re
@@ -30,6 +31,11 @@ from pptx_to_svg.preset_authoring import (
validate_authored_preset_tree,
)
from resource_paths import icon_dir_for_project
+from svg_authoring_view import (
+ SEMANTIC_OBJECT_ATTRIBUTE,
+ SEMANTIC_SHAPE_KIND,
+ SEMANTIC_TABLE_KIND,
+)
from svg_compatibility import normalize_single_child_group_filters
from .context import (
@@ -200,6 +206,11 @@ def _native_replacement_enabled(elem: ET.Element, ctx: ConvertContext) -> bool:
kind = native_replacement_kind(elem)
if kind == 'formula':
return True
+ if (
+ kind == 'table'
+ and elem.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_TABLE_KIND
+ ):
+ return True
if elem.get('data-pptx-roundtrip-object') == 'source-chart-package':
return kind == 'chart'
return ctx.native_objects_enabled and kind in {'chart', 'table'}
@@ -708,6 +719,127 @@ def _append_shape_text(
)
+def _make_semantic_geometry_carrier_visible(element: ET.Element) -> None:
+ """Remove authoring-only hiding from a semantic geometry carrier clone."""
+ for name in ('visibility', 'display', 'pointer-events'):
+ element.attrib.pop(name, None)
+ style = element.get('style')
+ if style is None:
+ return
+ declarations = [
+ declaration.strip()
+ for declaration in style.split(';')
+ if declaration.strip()
+ ]
+ retained = [
+ declaration
+ for declaration in declarations
+ if declaration.split(':', 1)[0].strip().lower()
+ not in {'display', 'pointer-events', 'visibility'}
+ ]
+ if retained:
+ element.set('style', '; '.join(retained))
+ else:
+ element.attrib.pop('style', None)
+
+
+def _semantic_shape_text_body(
+ shape: ET.Element,
+ ctx: ConvertContext,
+) -> str | None:
+ texts = [
+ child
+ for child in shape
+ if child.tag.replace(f'{{{SVG_NS}}}', '') == 'text'
+ ]
+ nested_texts = [
+ child
+ for child in shape.iter()
+ if child.tag.replace(f'{{{SVG_NS}}}', '') == 'text'
+ ]
+ if nested_texts != texts:
+ raise SvgNativeConversionError(
+ 'Semantic shape text must be one direct SVG text component'
+ )
+ if not texts:
+ return None
+ if len(texts) != 1:
+ raise SvgNativeConversionError(
+ 'Semantic shape requires at most one paragraph-based text component'
+ )
+ frame = shape.get('data-pptx-frame')
+ if frame is None:
+ raise SvgNativeConversionError(
+ 'Semantic shape text requires data-pptx-frame on its owner'
+ )
+
+ text = copy.deepcopy(texts[0])
+ text.set('data-pptx-frame', frame)
+ for name in (
+ 'data-pptx-shape-id',
+ 'data-pptx-shape-name',
+ 'data-pptx-shape-scope',
+ ):
+ text.attrib.pop(name, None)
+ result = convert_text(text, ctx)
+ if result is None:
+ raise SvgNativeConversionError(
+ 'Semantic shape text component produced no native text body'
+ )
+ match = re.search(r'(<p:txBody>.*?</p:txBody>)', result.xml, re.DOTALL)
+ if match is None:
+ raise SvgNativeConversionError(
+ 'Semantic shape text did not compile to a p:txBody'
+ )
+ return match.group(1)
+
+
+def _convert_semantic_shape(
+ shape: ET.Element,
+ ctx: ConvertContext,
+) -> ShapeResult | None:
+ """Compile one normalized semantic SVG shape into one native PPT shape."""
+ if shape.get(SEMANTIC_OBJECT_ATTRIBUTE) != SEMANTIC_SHAPE_KIND:
+ return None
+ carriers = [
+ child
+ for child in shape
+ if child.get('data-pptx-part') == 'geometry'
+ and child.tag.replace(f'{{{SVG_NS}}}', '')
+ in {'circle', 'ellipse', 'line', 'path', 'polygon', 'polyline', 'rect'}
+ ]
+ if len(carriers) != 1:
+ raise SvgNativeConversionError(
+ 'Semantic shape requires exactly one direct geometry carrier'
+ )
+ carrier = copy.deepcopy(carriers[0])
+ _make_semantic_geometry_carrier_visible(carrier)
+ for name in (
+ 'data-pptx-shape-id',
+ 'data-pptx-shape-name',
+ 'data-pptx-shape-scope',
+ 'data-name',
+ ):
+ if carrier.get(name) is None and shape.get(name) is not None:
+ carrier.set(name, str(shape.get(name)))
+
+ if shape.get('data-pptx-geometry-kind') == 'custom':
+ for name in (
+ 'data-pptx-custgeom',
+ 'data-pptx-geometry-kind',
+ 'data-pptx-geometry-sha256',
+ ):
+ carrier.attrib.pop(name, None)
+
+ geometry = convert_element(carrier, ctx)
+ if geometry is None:
+ raise SvgNativeConversionError(
+ 'Semantic shape geometry carrier produced no native shape'
+ )
+ text_body = _semantic_shape_text_body(shape, ctx)
+ return _append_shape_text(geometry, text_body) if text_body else geometry
+
+
def _restore_placeholder_sp_pr(
shape: ShapeResult,
group: ET.Element,
@@ -1049,6 +1181,28 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
return native_result
+ if elem.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_SHAPE_KIND:
+ geometry_ctx = child_ctx
+ if transform and not native_subtree_active:
+ geometry_ctx = ctx.child(
+ 0, 0, 1.0, 1.0,
+ transform_matrix=parse_transform_matrix(transform),
+ filter_id=filter_id,
+ style_overrides=style_overrides,
+ opacity_multiplier=local_opacity,
+ )
+ semantic_result = _convert_semantic_shape(elem, geometry_ctx)
+ ctx.sync_from_child(geometry_ctx)
+ if semantic_result is None:
+ raise SvgNativeConversionError(
+ 'Semantic shape marker did not produce a native shape'
+ )
+ if should_animate_group and elem_id:
+ shape_match = re.search(r'<p:cNvPr id="(\d+)"', semantic_result.xml)
+ if shape_match:
+ ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
+ return semantic_result
+
if (
elem.get('data-pptx-object') in {'shape', 'connector'}
and elem.get('data-pptx-prst') is not None
@@ -1688,9 +1842,10 @@ def convert_svg_to_slide_shapes(
size from rendered SVG boxes.
image_scale: Target image pixels per SVG display pixel.
image_quality: JPEG quality used for opaque optimized rasters.
- native_objects: Convert explicit ``data-pptx-replace-with`` chart/table
- markers to native PowerPoint Chart/Table objects. Formula markers
- are intrinsically native and do not use this opt-in. Default off.
+ native_objects: Convert opt-in ``data-pptx-replace-with`` chart/table
+ markers to native PowerPoint Chart/Table objects. Formula markers and
+ semantic authoring tables are intrinsically native. Default off for
+ other markers.
animation_group_overrides: Explicit top-level SVG group ids from
``animations.json`` that override the legacy chrome-name fallback.
Explicit structural layer/role/placeholder markers remain excluded.
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
index 78ab952f..229adccc 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
@@ -436,7 +436,9 @@ def _validate_native_object_marker_payload(
off_x, off_y, ext_cx, ext_cy, _ = _validate_bounds_inputs(elem, payload, bounds_ctx)
validated_data: list[list[Any]] | FormulaSpec | None = None
if kind == "table":
- table_rows, col_count, _merge_layout = _validate_table_payload(payload)
+ _expanded_payload, table_rows, col_count, _merge_layout = (
+ _validate_table_payload(payload)
+ )
validated_data = table_rows
if ext_cx < col_count or ext_cy < len(table_rows):
raise RuntimeError(
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/fallback_hash.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/fallback_hash.py
index b852c12f..e66a935c 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/fallback_hash.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/fallback_hash.py
@@ -72,6 +72,8 @@ def native_fallback_contract_warnings(
document_root: ET.Element | None = None,
) -> list[str]:
"""Return non-blocking diagnostics for default/checker compatibility."""
+ if elem.get("data-pptx-semantic-object") == "table":
+ return []
expected, invalid = _expected_native_fallback_hash(elem)
if invalid:
return [
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
index 28e1e332..74ddfc35 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
@@ -6,6 +6,8 @@ from dataclasses import dataclass
from typing import Any
from xml.etree import ElementTree as ET
+from semantic_table import expand_semantic_table_payload
+
from .marker_attributes import native_import_source
from ..drawingml.context import ConvertContext, ShapeResult
@@ -23,7 +25,6 @@ from .marker_common import (
_bool_attr,
_bounds,
_clean_hex,
- _compact_key,
_first_present,
_font_size_hpt,
_hex_or_none,
@@ -50,6 +51,8 @@ def _table_text_run(
strike: bool | None = None,
alt_language: str | None = None,
exact_font_face: bool = False,
+ baseline: int | None = None,
+ outline: _TableBorderSpec | None = None,
) -> str:
size_attr = f' sz="{font_size}"' if font_size is not None else ""
bold_attr = f' b="{_bool_attr(bold)}"' if bold is not None else ""
@@ -67,6 +70,7 @@ def _table_text_run(
alt_language_attr = (
f' altLang="{_xml_escape(alt_language)}"' if alt_language else ""
)
+ baseline_attr = f' baseline="{baseline}"' if baseline is not None else ""
color_xml = (
f'<a:solidFill>{color_node_xml(color, theme_color_spec, "text")}</a:solidFill>'
if color else ""
@@ -80,11 +84,25 @@ def _table_text_run(
)
else:
font_xml = _font_face_xml(font_face)
+ outline_xml = ""
+ if outline is not None and outline.style == "solid":
+ assert outline.color is not None and outline.width is not None
+ width = _powerpoint_line_width_emu(
+ outline.width,
+ "table text outline width",
+ )
+ outline_xml = (
+ f'<a:ln w="{width}">'
+ '<a:solidFill>'
+ f'{color_node_xml(outline.color, theme_color_spec, "stroke")}'
+ '</a:solidFill><a:prstDash val="solid"/></a:ln>'
+ )
rtl_xml = '<a:rtl val="1"/>' if text_has_rtl_characters(text) else ''
space_attr = ' xml:space="preserve"' if text != text.strip() else ""
return (
f'<a:r><a:rPr{language_attr}{alt_language_attr}{size_attr}{bold_attr}'
- f'{italic_attr}{underline_attr}{strike_attr}>'
+ f'{italic_attr}{underline_attr}{strike_attr}{baseline_attr}>'
+ f'{outline_xml}'
f'{color_xml}'
f'{font_xml}'
f'{rtl_xml}'
@@ -99,6 +117,7 @@ def _table_paragraph_properties(
emit_align: bool,
text: str,
language: str | None,
+ line_spacing_percent: float | None = None,
) -> str:
"""Build table paragraph properties with project-aware direction."""
attrs = []
@@ -107,7 +126,13 @@ def _table_paragraph_properties(
if text_uses_rtl(text, language):
attrs.append('rtl="1"')
suffix = f" {' '.join(attrs)}" if attrs else ''
- return f'<a:pPr{suffix}/>'
+ if line_spacing_percent is None:
+ return f'<a:pPr{suffix}/>'
+ spacing = round(line_spacing_percent * 1000)
+ return (
+ f'<a:pPr{suffix}><a:lnSpc><a:spcPct val="{spacing}"/>'
+ '</a:lnSpc></a:pPr>'
+ )
def _cell_payload(value: Any) -> dict[str, Any]:
@@ -167,6 +192,8 @@ class _TableRun:
font_family: str | None = None
lang: str | None = None
alt_lang: str | None = None
+ baseline: int | None = None
+ outline: _TableBorderSpec | None = None
@dataclass(frozen=True)
@@ -174,6 +201,7 @@ class _TableParagraph:
text: str
align: str | None = None
runs: tuple[_TableRun, ...] | None = None
+ line_spacing_percent: float | None = None
def _table_rows(payload: dict[str, Any]) -> list[list[Any]]:
@@ -214,9 +242,10 @@ def _table_cell_paragraphs(
raise RuntimeError(
f"Native PPTX table paragraph {idx} must be a string or object"
)
- if set(value) - {"text", "runs", "align"}:
+ if set(value) - {"text", "runs", "align", "line_spacing_percent"}:
raise RuntimeError(
- f"Native PPTX table paragraph {idx} accepts text/runs/align only"
+ "Native PPTX table paragraph "
+ f"{idx} accepts text/runs/align/line_spacing_percent only"
)
has_text = "text" in value
has_runs = "runs" in value
@@ -225,17 +254,35 @@ def _table_cell_paragraphs(
f"Native PPTX table paragraph {idx} requires exactly one of text/runs"
)
align = value.get("align")
- if align is not None and align not in {"l", "ctr", "r"}:
+ if align is not None and align not in {"l", "ctr", "r", "just"}:
raise RuntimeError(
- f"Native PPTX table paragraph {idx} align must be l, ctr, or r"
+ "Native PPTX table paragraph "
+ f"{idx} align must be l, ctr, r, or just"
+ )
+ line_spacing_percent: float | None = None
+ if value.get("line_spacing_percent") is not None:
+ line_spacing_percent = _number(
+ value["line_spacing_percent"],
+ f"table paragraph {idx} line_spacing_percent",
)
+ if not 0 < line_spacing_percent <= 1000:
+ raise RuntimeError(
+ "Native PPTX table paragraph "
+ f"{idx} line_spacing_percent must be in (0, 1000]"
+ )
if has_text:
text = value.get("text")
if not isinstance(text, str):
raise RuntimeError(
f"Native PPTX table paragraph {idx} text must be a string"
)
- paragraphs.append(_TableParagraph(text, align))
+ paragraphs.append(
+ _TableParagraph(
+ text,
+ align,
+ line_spacing_percent=line_spacing_percent,
+ )
+ )
continue
raw_runs = value.get("runs")
@@ -248,7 +295,12 @@ def _table_cell_paragraphs(
for run_idx, run in enumerate(raw_runs, start=1)
)
paragraphs.append(
- _TableParagraph("".join(run.text for run in runs), align, runs)
+ _TableParagraph(
+ "".join(run.text for run in runs),
+ align,
+ runs,
+ line_spacing_percent,
+ )
)
return tuple(paragraphs)
@@ -265,6 +317,7 @@ def _table_run(
allowed = {
"text", "bold", "italic", "underline", "strike", "color",
"font_size", "font_family", "lang", "alt_lang",
+ "baseline_percent", "outline",
}
unknown = set(value) - allowed
if unknown:
@@ -330,6 +383,22 @@ def _table_run(
)
languages[field] = raw.strip()
+ baseline: int | None = None
+ if value.get("baseline_percent") is not None:
+ baseline_percent = _number(
+ value["baseline_percent"],
+ f"table {label} baseline_percent",
+ )
+ if not -100 <= baseline_percent <= 100:
+ raise RuntimeError(
+ f"Native PPTX table {label} baseline_percent must be in [-100, 100]"
+ )
+ baseline = round(baseline_percent * 1000)
+
+ outline: _TableBorderSpec | None = None
+ if value.get("outline") is not None:
+ outline = _table_border_override(value["outline"], "text outline")
+
return _TableRun(
text=text,
bold=booleans["bold"],
@@ -341,6 +410,8 @@ def _table_run(
font_family=font_family,
lang=languages["lang"],
alt_lang=languages["alt_lang"],
+ baseline=baseline,
+ outline=outline,
)
@@ -365,10 +436,36 @@ def _merge_covered_cell_is_blank(value: Any) -> bool:
return True
if not isinstance(value, dict):
return False
- if any(key != "text" for key in value):
- return False
+ if value.get("merge_continuation") is not True:
+ if any(key != "text" for key in value):
+ return False
text = value.get("text")
- return text is None or text == ""
+ if text not in {None, ""}:
+ return False
+ paragraphs = value.get("paragraphs")
+ if paragraphs is None:
+ return True
+ if not isinstance(paragraphs, list):
+ return False
+ for paragraph in paragraphs:
+ if isinstance(paragraph, str):
+ if paragraph:
+ return False
+ continue
+ if not isinstance(paragraph, dict):
+ return False
+ if paragraph.get("text") not in {None, ""}:
+ return False
+ runs = paragraph.get("runs")
+ if runs is not None and (
+ not isinstance(runs, list)
+ or any(
+ not isinstance(run, dict) or run.get("text") not in {None, ""}
+ for run in runs
+ )
+ ):
+ return False
+ return True
def _resolve_table_merge_layout(
@@ -452,7 +549,7 @@ def _resolve_table_merge_layout(
def _grid_is_strict(payload: dict[str, Any]) -> bool:
- value = payload.get("strict_grid", payload.get("strictGrid"))
+ value = payload.get("strict_grid")
return _table_bool(value, "strict_grid", default=False)
@@ -461,14 +558,9 @@ def _table_bool(value: Any, field_name: str, *, default: bool) -> bool:
return default
if isinstance(value, bool):
return value
- if value in (0, 1):
- return bool(value)
- key = _compact_key(value)
- if key in {"1", "on", "true", "yes"}:
- return True
- if key in {"0", "false", "no", "off"}:
- return False
- raise RuntimeError(f"Native PPTX table {field_name} must be a boolean")
+ raise RuntimeError(
+ f"Native PPTX table {field_name} must be a JSON boolean"
+ )
def _table_header_rows(payload: dict[str, Any], row_count: int) -> int:
@@ -520,6 +612,13 @@ def _validate_table_cell_formatting(payload: dict[str, Any], table_rows: list[li
for row in table_rows:
for cell in row:
cell_data = _cell_payload(cell)
+ if "merge_continuation" in cell_data and not isinstance(
+ cell_data["merge_continuation"],
+ bool,
+ ):
+ raise RuntimeError(
+ "Native PPTX table merge_continuation must be a JSON boolean"
+ )
_table_cell_paragraphs(cell_data)
if "bold" in cell_data:
_table_bool(cell_data["bold"], "cell bold", default=False)
@@ -534,11 +633,19 @@ def _validate_table_cell_formatting(payload: dict[str, Any], table_rows: list[li
"table border_width",
)
_table_anchor(cell_data, style)
+ _table_cell_extra_attrs(cell_data)
+ _table_fill_opacity(cell_data)
def _validate_table_payload(
payload: dict[str, Any],
-) -> tuple[list[list[Any]], int, dict[tuple[int, int], _TableMergeRegion]]:
+) -> tuple[
+ dict[str, Any],
+ list[list[Any]],
+ int,
+ dict[tuple[int, int], _TableMergeRegion],
+]:
+ payload = expand_semantic_table_payload(payload)
table_rows = _table_rows(payload)
col_count = _validate_table_lengths(payload, table_rows)
for row in table_rows:
@@ -546,7 +653,7 @@ def _validate_table_payload(
merge_layout = _resolve_table_merge_layout(payload, table_rows, col_count)
_table_header_rows(payload, len(table_rows))
_validate_table_cell_formatting(payload, table_rows)
- return table_rows, col_count, merge_layout
+ return payload, table_rows, col_count, merge_layout
def _native_table_metadata_texts(table_rows: list[list[Any]]) -> dict[str, int]:
@@ -643,22 +750,15 @@ def _table_padding_value(
style: dict[str, Any],
side: str,
) -> int | None:
- side_keys = {
- "left": ("left", "l", "padding_left", "paddingLeft"),
- "right": ("right", "r", "padding_right", "paddingRight"),
- "top": ("top", "t", "padding_top", "paddingTop"),
- "bottom": ("bottom", "b", "padding_bottom", "paddingBottom"),
- }
+ direct_key = f"padding_{side}"
def from_source(source: dict[str, Any]) -> Any:
- for key in side_keys[side]:
- if key in source:
- return source[key]
- padding = source.get("padding", source.get("cell_padding"))
+ if direct_key in source:
+ return source[direct_key]
+ padding = source.get("padding")
if isinstance(padding, dict):
- for key in side_keys[side]:
- if key in padding:
- return padding[key]
+ if side in padding:
+ return padding[side]
elif padding is not None:
return padding
return None
@@ -689,40 +789,78 @@ def _table_padding_attrs(cell_data: dict[str, Any], style: dict[str, Any]) -> st
def _table_anchor(cell_data: dict[str, Any], style: dict[str, Any]) -> str:
raw = _first_present(
cell_data.get("valign"),
- cell_data.get("vertical_align"),
style.get("valign"),
- style.get("vertical_align"),
"middle",
)
- aliases = {
+ values = {
"bottom": "b",
- "b": "b",
- "center": "ctr",
- "ctr": "ctr",
"middle": "ctr",
"top": "t",
- "t": "t",
}
- anchor = aliases.get(_compact_key(raw))
+ anchor = values.get(raw) if isinstance(raw, str) else None
if not anchor:
raise RuntimeError("Native PPTX table valign must be one of: top, middle, bottom")
return anchor
+def _table_cell_extra_attrs(cell_data: dict[str, Any]) -> str:
+ attrs: list[str] = []
+ if "anchor_center" in cell_data:
+ anchor_center = _table_bool(
+ cell_data["anchor_center"],
+ "cell anchor_center",
+ default=False,
+ )
+ attrs.append(f'anchorCtr="{_bool_attr(anchor_center)}"')
+ horizontal_overflow = cell_data.get("horizontal_overflow")
+ if horizontal_overflow is not None:
+ if horizontal_overflow not in {"clip", "overflow"}:
+ raise RuntimeError(
+ "Native PPTX table horizontal_overflow must be clip or overflow"
+ )
+ attrs.append(f'horzOverflow="{horizontal_overflow}"')
+ return (" " + " ".join(attrs)) if attrs else ""
+
+
+def _table_fill_opacity(cell_data: dict[str, Any]) -> float | None:
+ raw = cell_data.get("fill_opacity")
+ if raw is None:
+ return None
+ if cell_data.get("fill") is None:
+ raise RuntimeError(
+ "Native PPTX table fill_opacity requires an explicit cell fill"
+ )
+ opacity = _number(raw, "table cell fill_opacity")
+ if not 0 <= opacity <= 1:
+ raise RuntimeError(
+ "Native PPTX table fill_opacity must be between zero and one"
+ )
+ return opacity
+
+
def _table_border_width(cell_data: dict[str, Any], style: dict[str, Any]) -> float:
- width_raw = cell_data.get("border_width", cell_data.get("borderWidth", style.get("border_width")))
- color_raw = cell_data.get("border_color", cell_data.get("borderColor", style.get("border_color")))
+ width_raw = cell_data.get("border_width", style.get("border_width"))
+ color_raw = cell_data.get("border_color", style.get("border_color"))
if width_raw is None and color_raw is None:
return 0.0
return _number(1 if width_raw is None else width_raw, "table border_width")
-_TABLE_BORDER_SIDES = ("left", "right", "top", "bottom")
+_TABLE_BORDER_SIDES = (
+ "left",
+ "right",
+ "top",
+ "bottom",
+ "diagonal_down",
+ "diagonal_up",
+)
_TABLE_BORDER_TAGS = {
"left": "lnL",
"right": "lnR",
"top": "lnT",
"bottom": "lnB",
+ "diagonal_down": "lnTlToBr",
+ "diagonal_up": "lnBlToTr",
}
@@ -797,10 +935,7 @@ def _table_border_specs(
_TableBorderSpec(
"solid",
color=_clean_hex(
- cell_data.get(
- "border_color",
- cell_data.get("borderColor", style.get("border_color")),
- ),
+ cell_data.get("border_color", style.get("border_color")),
"#D9DEE7",
),
width=legacy_width,
@@ -845,6 +980,25 @@ def _table_border_xml(
return "".join(border_xml)
+def _table_fill_xml(
+ fill: str | None,
+ opacity: float | None,
+ theme_color_spec: ThemeColorSpec | None,
+) -> str:
+ if fill is None:
+ return ""
+ alpha_xml = (
+ f'<a:alpha val="{round(opacity * 100000)}"/>'
+ if opacity is not None and opacity < 1
+ else ""
+ )
+ return (
+ '<a:solidFill>'
+ f'{color_node_xml(fill, theme_color_spec, "fill", alpha_xml)}'
+ '</a:solidFill>'
+ )
+
+
def _table_merge_attrs(
region: _TableMergeRegion | None,
row_idx: int,
@@ -865,7 +1019,7 @@ def _table_merge_attrs(
def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str, Any]) -> ShapeResult:
- table_rows, col_count, merge_layout = _validate_table_payload(payload)
+ payload, table_rows, col_count, merge_layout = _validate_table_payload(payload)
header_rows = _table_header_rows(payload, len(table_rows))
preserve_source_style = native_import_source(elem) == "pptx"
@@ -910,20 +1064,45 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
is_header = row_idx < header_rows
cells_xml: list[str] = []
for col_idx, cell in enumerate(row):
+ cell_data = _cell_payload(cell)
merge_region = merge_layout.get((row_idx, col_idx))
merge_attrs = _table_merge_attrs(merge_region, row_idx, col_idx)
if merge_region is not None and (
row_idx != merge_region.row or col_idx != merge_region.col
):
+ continuation_attrs = ""
+ continuation_border_xml = ""
+ continuation_fill_xml = ""
+ if cell_data.get("merge_continuation") is True:
+ continuation_attrs = (
+ _table_padding_attrs(cell_data, style)
+ + _table_cell_extra_attrs(cell_data)
+ )
+ continuation_border_xml = _table_border_xml(
+ cell_data,
+ style,
+ ctx.theme_color_spec,
+ )
+ continuation_fill = (
+ _clean_hex(cell_data.get("fill"), "#FFFFFF")
+ if cell_data.get("fill") is not None
+ else None
+ )
+ continuation_fill_xml = _table_fill_xml(
+ continuation_fill,
+ _table_fill_opacity(cell_data),
+ ctx.theme_color_spec,
+ )
cells_xml.append(
f'<a:tc{merge_attrs}>'
'<a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody>'
- '<a:tcPr/>'
+ f'<a:tcPr{continuation_attrs}>'
+ f'{continuation_border_xml}{continuation_fill_xml}'
+ '</a:tcPr>'
'</a:tc>'
)
continue
- cell_data = _cell_payload(cell)
if preserve_source_style:
fill = (
_clean_hex(cell_data.get("fill"), "#FFFFFF")
@@ -948,7 +1127,7 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
header_text if is_header else body_text,
)
align = str(cell_data.get("align") or ("ctr" if is_header else "l"))
- if align not in {"l", "ctr", "r"}:
+ if align not in {"l", "ctr", "r", "just"}:
align = "l"
paragraphs = _table_cell_paragraphs(cell_data)
if preserve_source_style:
@@ -1015,6 +1194,7 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
),
text=paragraph_text,
language=language or ctx.primary_language,
+ line_spacing_percent=paragraph.line_spacing_percent,
)
if paragraph.runs is None:
text_run_xml = _table_text_run(
@@ -1047,6 +1227,8 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
strike=run.strike,
alt_language=run.alt_lang,
exact_font_face=run.font_family is not None,
+ baseline=run.baseline,
+ outline=run.outline,
)
for run in paragraph.runs
)
@@ -1054,21 +1236,24 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
f"<a:p>{paragraph_props}{text_run_xml}</a:p>"
)
paragraphs_xml = "".join(paragraph_parts)
- anchor_keys = {"valign", "vertical_align"}
+ anchor_keys = {"valign"}
anchor_attr = ""
if not preserve_source_style or anchor_keys.intersection(cell_data) or anchor_keys.intersection(style):
anchor_attr = f' anchor="{_table_anchor(cell_data, style)}"'
- tc_pr_attrs = f'{anchor_attr}{_table_padding_attrs(cell_data, style)}'
+ tc_pr_attrs = (
+ f'{anchor_attr}'
+ f'{_table_padding_attrs(cell_data, style)}'
+ f'{_table_cell_extra_attrs(cell_data)}'
+ )
border_xml = _table_border_xml(
cell_data,
style,
ctx.theme_color_spec,
)
- fill_xml = (
- '<a:solidFill>'
- f'{color_node_xml(fill, ctx.theme_color_spec, "fill")}'
- '</a:solidFill>'
- if fill else ""
+ fill_xml = _table_fill_xml(
+ fill,
+ _table_fill_opacity(cell_data),
+ ctx.theme_color_spec,
)
cells_xml.append(
f"<a:tc{merge_attrs}>"
@@ -1080,7 +1265,10 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
)
rows_xml.append(f'<a:tr h="{row_heights[row_idx]}">{"".join(cells_xml)}</a:tr>')
- shape_id = ctx.next_id()
+ shape_id = ctx.claim_shape_id(
+ elem.get("data-pptx-shape-id"),
+ elem.get("data-pptx-shape-scope"),
+ )
first_row = _bool_attr(header_rows > 0)
band_row = _bool_attr(band_rows_enabled)
table_style_id = style.get("table_style_id")
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.py
index 45e18129..31549659 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
@@ -4023,8 +4023,8 @@ def _prune_unreferenced_definition_payload_parts(
) -> int:
"""Remove generated native/media payload left by deleted carrier slides.
- Definition-only SVGs are first converted as ordinary slides so their
- reusable structure can be promoted. Removing those internal slides may
+ Unselected complete Slide prototypes are first converted as carrier slides
+ so their reusable Layout can be registered. Removing those carriers may
leave chart, workbook, or media parts with no remaining relationship. Run
an iterative incoming-reference sweep so chart-owned workbooks/styles are
removed after their orphan chart part and relationship sidecar disappear.
@@ -5361,8 +5361,8 @@ def _clear_preserved_slide_collections(extract_dir: Path) -> None:
_write_xml_tree(presentation_path, tree)
-def _install_source_theme_xml(extract_dir: Path, payload: bytes) -> None:
- """Install a validated imported theme into the generated flat package."""
+def _validate_source_theme_xml(payload: bytes) -> None:
+ """Validate one imported Theme part before package installation."""
try:
root = ET.fromstring(payload)
except ET.ParseError as exc:
@@ -5376,6 +5376,11 @@ def _install_source_theme_xml(extract_dir: Path, payload: bytes) -> None:
):
raise ThemeColorError("Imported source theme cannot contain relationships")
+
+def _install_source_theme_xml(extract_dir: Path, payload: bytes) -> None:
+ """Install a validated imported theme into the generated flat package."""
+ _validate_source_theme_xml(payload)
+
theme_paths = sorted((extract_dir / "ppt" / "theme").glob("theme*.xml"))
if not theme_paths:
raise ThemeColorError("Generated PPTX package has no theme part")
@@ -5383,6 +5388,41 @@ def _install_source_theme_xml(extract_dir: Path, payload: bytes) -> None:
theme_path.write_bytes(payload)
+def _install_source_themes_by_master(
+ extract_dir: Path,
+ master_parts_by_key: dict[str, str],
+ payloads_by_key: dict[str, bytes],
+) -> None:
+ """Install one exact source Theme into each structured mirror Master."""
+ expected = set(master_parts_by_key)
+ actual = set(payloads_by_key)
+ if actual != expected:
+ raise ThemeColorError(
+ "Structured source Theme roster differs from Master roster; "
+ f"missing={sorted(expected - actual)}, extra={sorted(actual - expected)}"
+ )
+ for master_key, master_part in master_parts_by_key.items():
+ payload = payloads_by_key[master_key]
+ _validate_source_theme_xml(payload)
+ master_rels = _relationships_path_for_part(extract_dir, master_part)
+ targets = [
+ attrs["Target"]
+ for attrs in _read_relationships(master_rels).values()
+ if attrs.get("Type") == THEME_REL_TYPE and attrs.get("Target")
+ ]
+ if len(targets) != 1:
+ raise ThemeColorError(
+ f"Structured Master {master_key!r} must own one Theme relationship"
+ )
+ theme_part = _resolve_package_target(master_part, targets[0])
+ theme_path = extract_dir / theme_part
+ if not theme_path.is_file():
+ raise ThemeColorError(
+ f"Structured Master {master_key!r} Theme part is missing: {theme_part}"
+ )
+ theme_path.write_bytes(payload)
+
+
def _install_source_embedded_fonts(
extract_dir: Path,
bundle: EmbeddedFontBundle,
@@ -5536,6 +5576,7 @@ def create_pptx_with_native_svg(
master_text_style_spec: MasterTextStyleSpec | None = None,
theme_color_spec: ThemeColorSpec | None = None,
source_theme_xml: bytes | None = None,
+ source_theme_xml_by_master: dict[str, bytes] | None = None,
source_embedded_fonts: EmbeddedFontBundle | None = None,
structured_baseline: bool = False,
baseline_layout_specs: list[TemplateSlideSpec] | None = None,
@@ -5553,12 +5594,12 @@ def create_pptx_with_native_svg(
Args:
svg_files: List of SVG files.
output_path: Output PPTX path.
- layout_definition_files: Optional structured SVG prototypes for Layouts
- that no generated page uses. They are converted on internal carrier
- slides, registered, and removed before the package is published.
+ layout_definition_files: Optional complete Slide SVG prototypes for
+ Layouts that no generated page uses. They are converted on internal
+ carrier slides, registered, and removed before publication.
canvas_format: Canvas format key.
expected_viewbox: Optional project/template-lock canvas contract. Every
- public page and internal Layout definition must match it.
+ public page and internal Layout carrier prototype must match it.
animation_resource_root: Project root for sidecar sound paths. Object
animation sounds retain existing absolute-path compatibility;
transition sounds must remain project-relative WAV files.
@@ -5602,8 +5643,9 @@ def create_pptx_with_native_svg(
oversized sources; ``display`` sizes from rendered SVG boxes.
image_scale: Target image pixels per SVG display pixel.
image_quality: JPEG quality used when opaque rasters are re-encoded.
- native_objects: Replace explicit ``data-pptx-replace-with`` chart/table
- fallback groups with native PowerPoint Chart/Table objects. Default off.
+ native_objects: Replace opt-in ``data-pptx-replace-with`` chart/table
+ fallback groups with native PowerPoint Chart/Table objects. Semantic
+ authoring tables are intrinsically native. Default off for other markers.
conversion_trace_path: Optional JSON path for native conversion diagnostics.
dangerous_nonconforming_export: Apply narrowly defined compatibility
normalizations before strict SVG conversion. Actual contract,
@@ -5641,6 +5683,8 @@ def create_pptx_with_native_svg(
flat/structured theme inheritance. Preserve mode ignores this value.
source_theme_xml: Complete validated source theme used only by an
explicit PPTX-import diagnostic round-trip.
+ source_theme_xml_by_master: Exact validated source themes keyed by
+ structured mirror Master identity.
source_embedded_fonts: Validated source font-list metadata and font
parts used only by an explicit PPTX-import diagnostic round-trip.
primary_language: Canonical BCP-47 deck content language. ``None``
@@ -5651,6 +5695,14 @@ def create_pptx_with_native_svg(
Returns:
Whether all slides were successfully created.
"""
+ if source_theme_xml is not None and source_theme_xml_by_master is not None:
+ raise ThemeColorError(
+ "Use either one diagnostic source Theme or per-Master mirror Themes"
+ )
+ if source_theme_xml_by_master is not None and pptx_structure != "structured":
+ raise ThemeColorError(
+ "Per-Master source Themes are allowed only in structured export"
+ )
text_flow = resolve_text_flow(text_flow, merge_paragraphs)
if primary_language is not None:
primary_language = normalize_language_tag(primary_language)
@@ -5738,20 +5790,20 @@ def create_pptx_with_native_svg(
morph_shape_ids: dict[tuple[str, str], int] = {}
if definition_svg_files and pptx_structure != "structured":
raise ValueError(
- "layout_definition_files requires pptx_structure='structured'"
+ "unselected Layout prototypes require pptx_structure='structured'"
)
public_paths = {path.resolve() for path in public_svg_files}
seen_definition_paths: set[Path] = set()
for path in definition_svg_files:
resolved = path.resolve()
if not path.is_file():
- raise ValueError(f"Layout definition SVG does not exist: {path}")
+ raise ValueError(f"Layout prototype SVG does not exist: {path}")
if resolved in public_paths:
raise ValueError(
- f"Layout definition SVG is already a generated page: {path}"
+ f"Layout prototype SVG is already a generated page: {path}"
)
if resolved in seen_definition_paths:
- raise ValueError(f"Layout definition SVG is repeated: {path}")
+ raise ValueError(f"Layout prototype SVG is repeated: {path}")
seen_definition_paths.add(resolved)
public_slide_count = len(public_svg_files)
svg_files = public_svg_files + definition_svg_files
@@ -5869,18 +5921,18 @@ def create_pptx_with_native_svg(
print(f" SVG file count: {public_slide_count}")
if definition_svg_files:
print(
- " Unused Layout definitions: "
- f"{len(definition_svg_files)} internal prototype(s)"
+ " Unselected Layout prototype carriers: "
+ f"{len(definition_svg_files)}"
)
if use_native_shapes:
print(f" Mode: Native DrawingML shapes (directly editable)")
native_object_mode = (
- "Enabled"
+ "All registered markers enabled"
if native_objects
else (
- "Exact round-trip source packages only"
+ "Semantic tables; exact round-trip source charts"
if native_structure_contract is not None
- else "Disabled"
+ else "Semantic tables only"
)
)
print(
@@ -6094,7 +6146,7 @@ def create_pptx_with_native_svg(
slide_num = i
is_layout_definition = slide_num > public_slide_count
progress_label = (
- f"[Layout definition {slide_num - public_slide_count}/"
+ f"[Layout carrier {slide_num - public_slide_count}/"
f"{len(definition_svg_files)}]"
if is_layout_definition
else f"[Slide {slide_num}/{public_slide_count}]"
@@ -6887,6 +6939,12 @@ def create_pptx_with_native_svg(
use_layout_placeholder_frames=use_layout_placeholder_frames,
verbose=verbose,
)
+ if source_theme_xml_by_master is not None:
+ _install_source_themes_by_master(
+ extract_dir,
+ template_master_parts_by_key,
+ source_theme_xml_by_master,
+ )
master_count = apply_master_text_style_spec(
extract_dir,
master_text_style_spec,
@@ -7205,7 +7263,8 @@ def create_pptx_with_native_svg(
print(f" Trace: {conversion_trace_path}")
print(
f" Slides: {public_slide_count}; "
- f"Layout definitions: {len(definition_svg_files)}"
+ "unselected Layout prototype carriers: "
+ f"{len(definition_svg_files)}"
)
if use_compat_mode and has_any_image:
print(f" Mode: Office compatibility mode (supports all Office versions)")
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.py
index 7b90990c..e1ee19b6 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
@@ -107,9 +107,11 @@ from .narration import (
)
from .template_structure import (
PptxStructureLock,
+ SOURCE_THEMES_FILENAME,
TemplateStructureError,
load_native_structure_contract,
load_pptx_structure_lock,
+ load_template_source_themes,
parse_template_slides,
structured_layout_definition_files,
template_lock_errors,
@@ -1590,9 +1592,10 @@ Recorded narration:
action='store_true',
default=False,
help=(
- 'Replace explicit data-pptx-replace-with chart/table groups with '
+ 'Replace opt-in data-pptx-replace-with chart/table groups with '
'PowerPoint native Chart/Table objects. This data-object route may '
- 'normalize styling or omit fallback-only visuals. Default off: groups '
+ 'normalize styling or omit fallback-only visuals. Semantic authoring '
+ 'tables are always native; default off applies to other markers, which '
'export as editable SVG-derived DrawingML shapes. The default-flow '
'output uses <project>_<ts>_native_charts_tables.pptx.'
),
@@ -1976,6 +1979,7 @@ Recorded narration:
master_text_style_spec = None
theme_color_spec = None
source_theme_xml = None
+ source_theme_xml_by_master = None
source_embedded_fonts = None
if (
pptx_structure in {'flat', 'structured'}
@@ -2017,6 +2021,27 @@ Recorded narration:
except (EmbeddedFontError, ThemeFontError, ThemeColorError) as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
+ source_themes_path = project_path / "templates" / SOURCE_THEMES_FILENAME
+ mirror_source_themes = (
+ structure_lock is not None
+ and structure_lock.mode == "structured"
+ and structure_lock.template_reuse_scope == "mirror"
+ )
+ if source_themes_path.exists() and not mirror_source_themes:
+ print(
+ "Error: templates/source_themes.json is allowed only for a "
+ "structured mirror contract",
+ file=sys.stderr,
+ )
+ return 1
+ if mirror_source_themes:
+ try:
+ source_theme_xml_by_master = load_template_source_themes(
+ project_path / "templates"
+ )
+ except TemplateStructureError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
if args.image_max_dimension < 1:
print("Error: --image-max-dimension must be >= 1", file=sys.stderr)
return 1
@@ -2856,6 +2881,7 @@ Recorded narration:
master_text_style_spec=master_text_style_spec,
theme_color_spec=theme_color_spec,
source_theme_xml=source_theme_xml,
+ source_theme_xml_by_master=source_theme_xml_by_master,
source_embedded_fonts=source_embedded_fonts,
primary_language=primary_language,
dangerous_nonconforming_export=(
diff --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.py
index 217c7455..b2b5c605 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
@@ -16,6 +16,8 @@ Dependencies:
from __future__ import annotations
+import base64
+import binascii
import hashlib
import json
import math
@@ -122,6 +124,10 @@ 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"})
+SOURCE_THEMES_FILENAME = "source_themes.json"
+SOURCE_THEMES_SCHEMA = "ppt-master.source-themes.v1"
+_DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
+_REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
_TEMPLATE_SKIN_ATTRS = frozenset({
"baseline-shift",
"color",
@@ -544,6 +550,92 @@ def _template_replication_mode(template_dir: Path) -> str | None:
return None
+def load_template_source_themes(
+ template_dir: Path,
+) -> dict[str, bytes] | None:
+ """Load exact per-Master themes carried by a Type A mirror workspace."""
+ path = template_dir / SOURCE_THEMES_FILENAME
+ if not path.exists():
+ return None
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise TemplateStructureError(
+ f"Cannot read template source themes {path}: {exc}"
+ ) from exc
+ schema = payload.get("schema") if isinstance(payload, dict) else None
+ if not isinstance(payload, dict) or schema != SOURCE_THEMES_SCHEMA:
+ raise TemplateStructureError(
+ f"Unsupported template source theme schema: {schema!r}"
+ )
+ masters = payload.get("masters")
+ if not isinstance(masters, dict) or not masters:
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} requires a non-empty masters object"
+ )
+
+ themes: dict[str, bytes] = {}
+ for master_key, record in masters.items():
+ if (
+ not isinstance(master_key, str)
+ or not _MASTER_KEY_RE.fullmatch(master_key)
+ ):
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} has invalid Master key {master_key!r}"
+ )
+ if not isinstance(record, dict):
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} must be an object"
+ )
+ if record.get("encoding") != "base64":
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} must use base64"
+ )
+ encoded = record.get("payload")
+ expected_sha256 = record.get("sha256")
+ if (
+ not isinstance(encoded, str)
+ or not isinstance(expected_sha256, str)
+ ):
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} lacks payload/hash"
+ )
+ try:
+ raw = base64.b64decode(encoded, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} has invalid base64"
+ ) from exc
+ if base64.b64encode(raw).decode("ascii") != encoded:
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} base64 is not canonical"
+ )
+ if hashlib.sha256(raw).hexdigest() != expected_sha256.strip().lower():
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} hash differs"
+ )
+ try:
+ root = ET.fromstring(raw)
+ except ET.ParseError as exc:
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} theme is malformed"
+ ) from exc
+ if root.tag != f"{{{_DML_NS}}}theme":
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} is not a:theme"
+ )
+ if any(
+ isinstance(name, str) and name.startswith(f"{{{_REL_NS}}}")
+ for node in root.iter()
+ for name in node.attrib
+ ):
+ raise TemplateStructureError(
+ f"{SOURCE_THEMES_FILENAME} Master {master_key!r} has relationships"
+ )
+ themes[master_key] = raw
+ return themes
+
+
def _template_svg_path(
template_dir: Path,
raw_basename: str,
@@ -807,6 +899,12 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
raw_basename,
f"page_layouts P{slide_num:02d}",
)
+ if basename.startswith("layout_"):
+ raise TemplateStructureError(
+ f"spec_lock.md page_layouts P{slide_num:02d} cannot select "
+ f"obsolete definition-only template SVG {basename!r}; create "
+ "and select a complete Slide prototype"
+ )
prototypes.append(PptxPrototypeReference(
slide_num=slide_num,
template_basename=basename,
@@ -902,11 +1000,17 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
prototype_slide_num = int(page_match.group(1))
elif raw_source.startswith("template:"):
raw_basename = raw_source.split(":", 1)[1].strip()
- _basename, prototype_svg_path = _template_svg_path(
+ basename, prototype_svg_path = _template_svg_path(
template_dir,
raw_basename,
f"pptx_layouts Layout {layout_key!r}",
)
+ if basename.startswith("layout_"):
+ raise TemplateStructureError(
+ f"spec_lock.md Layout {layout_key!r} cannot use obsolete "
+ f"definition-only template SVG {basename!r}; use a "
+ "complete Slide prototype"
+ )
else:
raise TemplateStructureError(
f"spec_lock.md Layout {layout_key!r} prototype source must be "
diff --git a/skills/ppt-master/scripts/template_preview_pptx.py b/skills/ppt-master/scripts/template_preview_pptx.py
index ef02288a..bb34e6d5 100644
--- a/skills/ppt-master/scripts/template_preview_pptx.py
+++ b/skills/ppt-master/scripts/template_preview_pptx.py
@@ -2,8 +2,7 @@
"""
PPT Master - Template Preview PPTX Exporter
-Export public SVG prototypes as a structured review deck while retaining
-definition-only Layout prototypes in the native package.
+Export complete Slide SVG prototypes as a structured review deck.
Usage:
python3 scripts/template_preview_pptx.py <template_workspace> [-o output.pptx]
@@ -45,6 +44,9 @@ from svg_to_pptx.drawingml.utils import font_px_to_hpt # noqa: E402
from svg_to_pptx.pptx_package.builder import ( # noqa: E402
create_pptx_with_native_svg,
)
+from svg_to_pptx.pptx_package.template_structure import ( # noqa: E402
+ load_template_source_themes,
+)
_FRONTMATTER_ID_RE = re.compile(
@@ -143,18 +145,6 @@ def _review_svg_sources(
yield review_files
-def _partition_svg_prototypes(
- svg_files: list[Path],
-) -> tuple[list[Path], list[Path]]:
- """Separate public pages from canonical definition-only Layout SVGs."""
- public_files: list[Path] = []
- definition_files: list[Path] = []
- for path in svg_files:
- target = definition_files if path.stem.startswith("layout_") else public_files
- target.append(path)
- return public_files, definition_files
-
-
_TEMPLATE_SPEC_NAME_RE = re.compile(
r"design_spec\.(?P<kind>brand|style|layout|deck)\.[^/\\]+\.md"
)
@@ -412,18 +402,27 @@ def main(argv: list[str] | None = None) -> int:
all_svg_files = sorted(template_dir.glob("*.svg"))
if not all_svg_files:
raise ValueError(f"template directory has no SVG prototypes: {template_dir}")
- svg_files, layout_definition_files = _partition_svg_prototypes(
- all_svg_files,
- )
- if not svg_files:
+ definition_only_files = [
+ path.name
+ for path in all_svg_files
+ if path.stem.startswith("layout_")
+ ]
+ if definition_only_files:
raise ValueError(
- "template directory contains Layout definitions but no public "
- f"SVG prototypes: {template_dir}"
+ "template workspaces accept only complete Slide prototypes; "
+ "replace definition-only Layout SVG(s) with authored Slide "
+ "prototypes: " + ", ".join(definition_only_files)
)
+ svg_files = all_svg_files
spec_path = _roster_spec(template_dir)
template_id = _template_id(spec_path)
replication_mode = _replication_mode(spec_path)
+ source_themes = load_template_source_themes(template_dir)
+ if source_themes is not None and replication_mode != "mirror":
+ raise ValueError(
+ "source_themes.json is allowed only in a mirror workspace"
+ )
locked_canvas = _canvas_viewbox(spec_path)
if locked_canvas is None:
raise ValueError(
@@ -447,12 +446,7 @@ def main(argv: list[str] | None = None) -> int:
print("PPT Master - Template Preview PPTX Exporter")
print(f" Workspace: {workspace}")
print(f" Template source: {template_dir}")
- print(f" Public SVG prototypes: {len(svg_files)}")
- if layout_definition_files:
- print(
- " Definition-only Layout prototypes: "
- f"{len(layout_definition_files)}"
- )
+ print(f" Slide SVG prototypes: {len(svg_files)}")
if replication_mode == "mirror":
print(" Review placeholder frames: preserved source Slide geometry")
else:
@@ -462,14 +456,9 @@ def main(argv: list[str] | None = None) -> int:
with _review_svg_sources(
workspace,
- all_svg_files,
+ svg_files,
shorten_placeholder_markers=use_full_placeholder_frames,
- ) as review_all_svg_files:
- review_svg_files, review_layout_definition_files = (
- _partition_svg_prototypes(
- review_all_svg_files,
- )
- )
+ ) as review_svg_files:
success = create_pptx_with_native_svg(
svg_files=review_svg_files,
output_path=output_path,
@@ -486,7 +475,7 @@ def main(argv: list[str] | None = None) -> int:
use_layout_placeholder_frames=use_full_placeholder_frames,
master_text_style_spec=text_style,
structure_name=template_id,
- layout_definition_files=review_layout_definition_files,
+ source_theme_xml_by_master=source_themes,
)
if not success or not output_path.is_file():
print("Error: template preview export did not produce a PPTX", file=sys.stderr)
diff --git a/skills/ppt-master/templates/layouts/presentation_core/templates/20_table_summary.svg b/skills/ppt-master/templates/layouts/presentation_core/templates/20_table_summary.svg
index eb719943..97a4a865 100644
--- a/skills/ppt-master/templates/layouts/presentation_core/templates/20_table_summary.svg
+++ b/skills/ppt-master/templates/layouts/presentation_core/templates/20_table_summary.svg
@@ -20,7 +20,7 @@
data-pptx-bounds="88 176 776 408">
<g id="table-summary-table-carrier" data-pptx-carrier="true"
data-pptx-replace-with="table">
- <metadata type="application/json">{"name":"table_summary","x":88,"y":176,"width":776,"height":408,"strict_grid":true,"column_widths":[3,2,2],"row_heights":[1,1,1,1,1],"style":{"font_family":"Arial","font_size":17,"header_font_size":16,"header_fill":"#E2E8F0","header_text":"#334155","body_fill":"#FFFFFF","body_text":"#475569","band_fill":"#F8FAFC","border_color":"#D6DCE3","border_width":1,"padding":{"left":12,"right":12,"top":6,"bottom":6},"valign":"middle"},"columns":[{"text":"Metric","bold":true},{"text":"Current","align":"r","bold":true},{"text":"Target","align":"r","bold":true}],"rows":[[{"text":"Adoption"},{"text":"68%","align":"r","bold":true},{"text":"80%","align":"r"}],[{"text":"Cycle time"},{"text":"12 d","align":"r","bold":true},{"text":"8 d","align":"r"}],[{"text":"Quality"},{"text":"94%","align":"r","bold":true},{"text":"97%","align":"r"}],[{"text":"Cost index"},{"text":"1.08","align":"r","bold":true},{"text":"1.00","align":"r"}]]}</metadata>
+ <metadata type="application/json">{"schema":"ppt-master.semantic-table.v2","name":"table_summary","x":88,"y":176,"width":776,"height":408,"strict_grid":true,"column_widths":[3,2,2],"row_heights":[1,1,1,1,1],"style":{"font_family":"Arial","font_size":17,"header_font_size":16,"header_fill":"#E2E8F0","header_text":"#334155","body_fill":"#FFFFFF","body_text":"#475569","band_fill":"#F8FAFC","border_color":"#D6DCE3","border_width":1,"padding":{"left":12,"right":12,"top":6,"bottom":6},"valign":"middle"},"columns":[{"text":"Metric","bold":true},{"text":"Current","align":"r","bold":true},{"text":"Target","align":"r","bold":true}],"rows":[[{"text":"Adoption"},{"text":"68%","align":"r","bold":true},{"text":"80%","align":"r"}],[{"text":"Cycle time"},{"text":"12 d","align":"r","bold":true},{"text":"8 d","align":"r"}],[{"text":"Quality"},{"text":"94%","align":"r","bold":true},{"text":"97%","align":"r"}],[{"text":"Cost index"},{"text":"1.08","align":"r","bold":true},{"text":"1.00","align":"r"}]]}</metadata>
<rect x="88" y="176" width="776" height="408" rx="8" fill="#FFFFFF" stroke="#D6DCE3" stroke-width="1"/>
<rect x="88" y="176" width="776" height="72" rx="8" fill="#E2E8F0"/>
<rect x="88" y="248" width="776" height="84" fill="#FFFFFF"/>
diff --git a/skills/ppt-master/templates/layouts/presentation_core_43/templates/16_table_summary.svg b/skills/ppt-master/templates/layouts/presentation_core_43/templates/16_table_summary.svg
index b1f11caf..1b7660f4 100644
--- a/skills/ppt-master/templates/layouts/presentation_core_43/templates/16_table_summary.svg
+++ b/skills/ppt-master/templates/layouts/presentation_core_43/templates/16_table_summary.svg
@@ -20,7 +20,7 @@
data-pptx-bounds="76 156 616 536">
<g id="table-summary-table-carrier" data-pptx-carrier="true"
data-pptx-replace-with="table">
- <metadata type="application/json">{"name":"table_summary","x":76,"y":156,"width":616,"height":536,"strict_grid":true,"column_widths":[3,2,2],"row_heights":[1,1,1,1,1],"style":{"font_family":"Arial","font_size":17,"header_font_size":16,"header_fill":"#E2E8F0","header_text":"#334155","body_fill":"#FFFFFF","body_text":"#475569","band_fill":"#F8FAFC","border_color":"#D6DCE3","border_width":1,"padding":{"left":12,"right":12,"top":6,"bottom":6},"valign":"middle"},"columns":[{"text":"Metric","bold":true},{"text":"Current","align":"r","bold":true},{"text":"Target","align":"r","bold":true}],"rows":[[{"text":"Adoption"},{"text":"68%","align":"r","bold":true},{"text":"80%","align":"r"}],[{"text":"Cycle time"},{"text":"12 d","align":"r","bold":true},{"text":"8 d","align":"r"}],[{"text":"Quality"},{"text":"94%","align":"r","bold":true},{"text":"97%","align":"r"}],[{"text":"Cost index"},{"text":"1.08","align":"r","bold":true},{"text":"1.00","align":"r"}]]}</metadata>
+ <metadata type="application/json">{"schema":"ppt-master.semantic-table.v2","name":"table_summary","x":76,"y":156,"width":616,"height":536,"strict_grid":true,"column_widths":[3,2,2],"row_heights":[1,1,1,1,1],"style":{"font_family":"Arial","font_size":17,"header_font_size":16,"header_fill":"#E2E8F0","header_text":"#334155","body_fill":"#FFFFFF","body_text":"#475569","band_fill":"#F8FAFC","border_color":"#D6DCE3","border_width":1,"padding":{"left":12,"right":12,"top":6,"bottom":6},"valign":"middle"},"columns":[{"text":"Metric","bold":true},{"text":"Current","align":"r","bold":true},{"text":"Target","align":"r","bold":true}],"rows":[[{"text":"Adoption"},{"text":"68%","align":"r","bold":true},{"text":"80%","align":"r"}],[{"text":"Cycle time"},{"text":"12 d","align":"r","bold":true},{"text":"8 d","align":"r"}],[{"text":"Quality"},{"text":"94%","align":"r","bold":true},{"text":"97%","align":"r"}],[{"text":"Cost index"},{"text":"1.08","align":"r","bold":true},{"text":"1.00","align":"r"}]]}</metadata>
<rect x="76" y="156" width="616" height="536" rx="8" fill="#FFFFFF" stroke="#D6DCE3" stroke-width="1"/>
<rect x="76" y="156" width="616" height="72" rx="8" fill="#E2E8F0"/>
<rect x="76" y="228" width="616" height="116" fill="#FFFFFF"/>
diff --git a/skills/ppt-master/templates/layouts/report_core/templates/09_table_summary.svg b/skills/ppt-master/templates/layouts/report_core/templates/09_table_summary.svg
index b0bb9d12..89f09156 100644
--- a/skills/ppt-master/templates/layouts/report_core/templates/09_table_summary.svg
+++ b/skills/ppt-master/templates/layouts/report_core/templates/09_table_summary.svg
@@ -22,7 +22,7 @@
data-pptx-bounds="68 196 816 424">
<g id="table-summary-table-carrier" data-pptx-carrier="true"
data-pptx-replace-with="table">
- <metadata type="application/json">{"name":"table_summary","x":68,"y":196,"width":816,"height":424,"strict_grid":true,"column_widths":[3,2,2],"row_heights":[1,1,1,1,1],"style":{"font_family":"Arial","font_size":15,"header_font_size":14,"header_fill":"#F1F5F9","header_text":"#334155","body_fill":"#FFFFFF","body_text":"#475569","band_fill":"#F8FAFC","border_color":"#E2E8F0","border_width":1,"padding":{"left":10,"right":10,"top":5,"bottom":5},"valign":"middle"},"columns":[{"text":"Metric","bold":true},{"text":"Current","align":"r","bold":true},{"text":"Target","align":"r","bold":true}],"rows":[[{"text":"Adoption"},{"text":"68%","align":"r","bold":true},{"text":"80%","align":"r"}],[{"text":"Cycle time"},{"text":"12 d","align":"r","bold":true},{"text":"8 d","align":"r"}],[{"text":"Quality"},{"text":"94%","align":"r","bold":true},{"text":"97%","align":"r"}],[{"text":"Cost index"},{"text":"1.08","align":"r","bold":true},{"text":"1.00","align":"r"}]]}</metadata>
+ <metadata type="application/json">{"schema":"ppt-master.semantic-table.v2","name":"table_summary","x":68,"y":196,"width":816,"height":424,"strict_grid":true,"column_widths":[3,2,2],"row_heights":[1,1,1,1,1],"style":{"font_family":"Arial","font_size":15,"header_font_size":14,"header_fill":"#F1F5F9","header_text":"#334155","body_fill":"#FFFFFF","body_text":"#475569","band_fill":"#F8FAFC","border_color":"#E2E8F0","border_width":1,"padding":{"left":10,"right":10,"top":5,"bottom":5},"valign":"middle"},"columns":[{"text":"Metric","bold":true},{"text":"Current","align":"r","bold":true},{"text":"Target","align":"r","bold":true}],"rows":[[{"text":"Adoption"},{"text":"68%","align":"r","bold":true},{"text":"80%","align":"r"}],[{"text":"Cycle time"},{"text":"12 d","align":"r","bold":true},{"text":"8 d","align":"r"}],[{"text":"Quality"},{"text":"94%","align":"r","bold":true},{"text":"97%","align":"r"}],[{"text":"Cost index"},{"text":"1.08","align":"r","bold":true},{"text":"1.00","align":"r"}]]}</metadata>
<rect x="68" y="196" width="816" height="424" rx="6" fill="#FFFFFF" stroke="#E2E8F0" stroke-width="1"/>
<rect x="68" y="196" width="816" height="64" rx="6" fill="#F1F5F9"/>
<rect x="68" y="260" width="816" height="90" fill="#FFFFFF"/>
diff --git a/skills/ppt-master/templates/spec_lock_reference.md b/skills/ppt-master/templates/spec_lock_reference.md
index c957a80a..22048172 100644
--- a/skills/ppt-master/templates/spec_lock_reference.md
+++ b/skills/ppt-master/templates/spec_lock_reference.md
@@ -122,7 +122,7 @@ New locks always write `title_family` and `body_family`, even when their values
- `pptx_masters` grammar: `<master_key>: <PowerPoint picker name>`.
- `pptx_layouts` grammar: `<layout_key>: <master_key> | <PowerPoint layout name> | <prototype source>`.
- `page_pptx_layouts` grammar: `P` + at least two digits followed by a declared Layout key.
-- `page_layouts` grammar: `P` + at least two digits followed by a template SVG basename.
+- `page_layouts` grammar: `P` + at least two digits followed by a complete Slide template SVG basename. Definition-only `layout_<layout_key>` files are obsolete and are also invalid as `pptx_layouts` sources; author a complete Slide prototype for each reusable Layout.
Catalog-based custom example:
diff --git a/skills/ppt-master/templates/tables/hierarchical_table.svg b/skills/ppt-master/templates/tables/hierarchical_table.svg
index ad174a5d..eefd5cb5 100644
--- a/skills/ppt-master/templates/tables/hierarchical_table.svg
+++ b/skills/ppt-master/templates/tables/hierarchical_table.svg
@@ -14,6 +14,7 @@
data-pptx-replace-with="table">
<metadata type="application/json">
{
+ "schema": "ppt-master.semantic-table.v2",
"name": "hierarchical-table",
"x": 80,
"y": 145,
diff --git a/skills/ppt-master/templates/tables/record_table.svg b/skills/ppt-master/templates/tables/record_table.svg
index fca2a939..2901136c 100644
--- a/skills/ppt-master/templates/tables/record_table.svg
+++ b/skills/ppt-master/templates/tables/record_table.svg
@@ -14,6 +14,7 @@
data-pptx-replace-with="table">
<metadata type="application/json">
{
+ "schema": "ppt-master.semantic-table.v2",
"name": "record-table",
"x": 80,
"y": 150,
diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.md
index c531959c..c7e1d8a8 100644
--- a/skills/ppt-master/workflows/create-template.md
+++ b/skills/ppt-master/workflows/create-template.md
@@ -59,7 +59,7 @@ Both scopes write this contract:
├── templates/ # library: design_spec.md; project: one qualified spec per kind plus the effective Layout-or-Deck SVG roster
├── images/ # optional; every bitmap; SVG href is ../images/<name>
├── icons/
-│ └── imported/ # optional; one canonical copy of imported vector assets
+│ └── imported/ # optional; one canonical copy of imported decoration vectors
└── exports/ # conditional; required package evidence for multi-Master templates
```
@@ -128,12 +128,12 @@ Type A is the canonical mirror path: `analysis/manifest.json`, `analysis/native_
Type B is supported with caveats:
-- **mirror on type B** — require a complete current explicit source contract. Preserve page count/order, literal visuals, root Master/Layout identities, slot metadata, supported native-object metadata, and source ownership in the **new** workspace. Page type for `<NNN>_<page_type>.svg` is read from the source filename when it follows the PPT Master naming convention (`01_cover.svg` → `cover`, `03a_content_two_col.svg` → `content`); fall back to `content` otherwise. A loose visual-only SVG folder has no native structure to preserve and cannot use mirror.
+- **mirror on type B** — require a complete current explicit source contract. Preserve page count/order, literal visuals, each source Slide's declared Layout/Master chain, slot metadata, supported native-object metadata, and source ownership in the **new** workspace. Page type for `<NNN>_<page_type>.svg` is read from the source filename when it follows the PPT Master naming convention (`01_cover.svg` → `cover`, `03a_content_two_col.svg` → `content`); fall back to `content` otherwise. A loose visual-only SVG folder has no native structure to preserve and cannot use mirror. Unreferenced identities are not mirror output.
- **fidelity on type B** — inspect the complete page roster as visual reference, then design a broader new roster and its own Master/Layout/slot system. Existing keys, families, and repeated source chrome are not output-topology inputs.
- **legacy or unstructured type B** — old `baseline` / `preserve` / `layout_strategy: distill` / `data-pptx-layout-kind` / direct-atomic-placeholder inputs, and SVGs with no root Master identity, are visual/contextual reference for `standard` / `fidelity` only. Author a new current contract in the output workspace. Use the original PPTX Type A path when existing native Master/Layout facts must be mirrored; do not mutate the SVG source or claim topology recovery from incomplete metadata.
- **selected free-design subset on type B** — ingest only the explicitly named pages as visual reference, then author a new current structured contract in the output workspace. Do not scan or copy the whole `svg_output/` directory or silently turn unselected pages into template variants.
-**Internal creation-strategy boundary**: `standard`, `fidelity`, and `mirror` are implementation labels derived after understanding the request; they are not user-facing creation modes. `standard` and `fidelity` author a new SVG roster and a new Master/Layout/slot system from the requested result. `mirror` preserves native facts that actually exist in a PPTX package or complete current Type B contract. Mirror may mechanically normalize transport representation for the current compiler, including fixed-layer group expansion, but it never infers missing historical intent or modifies the input. Because mirror preserves supported visual and application facts, Create Layout may use it only when the source contract already satisfies the Layout boundary: brand-neutral and application-neutral. A source outside that boundary must be re-authored internally or retained as a Deck. The strategy creates a template workspace, not a downstream generated deck; future decks are authored anew and do not inherit the source page count/order requirement.
+**Internal creation-strategy boundary**: `standard`, `fidelity`, and `mirror` are derived implementation labels, not user-facing modes. `standard` and `fidelity` review the complete source structure, then author a compact Slide roster or broader useful source-aligned Slide coverage; each retained Layout has a Slide prototype. `mirror` validates and preserves source Slides plus only their reachable Layout/Master graph. It may complete inherited SVG context and normalize compiler transport without changing visible content, ownership, or intent. Create Layout mirror remains legal only for a retained brand-neutral, application-neutral contract; otherwise re-author a Layout or retain a Deck. Future decks do not inherit the source page count/order requirement.
### 1A. `.pptx` reference
@@ -203,7 +203,7 @@ not use this compiler.
**Vector illustration readability pass**:
-Factor large decorative vector groups out of the lightweight IR documents so the model-facing SVGs stay readable while export remains native shapes. Never run this in place on the lossless import SVGs:
+Factor only large non-semantic decorative vector groups out of the lightweight IR documents so the model-facing SVGs stay readable while export remains native shapes. Never run this in place on the lossless import SVGs:
```bash
# layered view — primary read surface and canonical extracted-vector inventory
@@ -214,7 +214,7 @@ python3 skills/ppt-master/scripts/extract_svg_assets.py "<import_workspace>/auth
python3 skills/ppt-master/scripts/extract_svg_assets.py "<import_workspace>/authoring-svg-flat" --icons-dir "<import_workspace>/icons" --icon-namespace imported --reuse-inventory "<import_workspace>/authoring-svg_vector_asset_inventory.json" --inplace --id-prefix flat --min-decoration-bytes 3000 --clean-stale
```
-The authoring SVGs in `<import_workspace>/authoring-svg/` and, when requested, `<import_workspace>/authoring-svg-flat/` are rewritten in place with compact `<use data-icon="imported/..."/>` placeholders. Each in-place extraction refreshes that bundle's `authoring_summary.json` automatically. Extracted assets have one canonical copy under `<import_workspace>/icons/imported/`; never duplicate them under `templates/icons/`. The root `icons/` directory remains a namespace container and must not contain rewritten page SVGs or inventories. The inventory is written beside the processed IR directory and records every preserved `data-pptx-source-ref`; re-inlining an asset therefore re-establishes the referenced object mapping before materialization. The existing icon embedding path re-inlines the extracted assets before final export, preserving multi-color artwork and non-square viewBox geometry as native SVG shapes. Text-bearing groups are never extracted; text must stay readable/editable in the working SVG. Extraction triggers on either many drawable elements or a large pure-vector XML block, so long single-path illustrations are factored out too. Pure-vector decoration runs inside text-bearing groups use a lower size threshold, allowing card borders and decorative paths to be extracted without hiding text. Referenced defs (`gradient` / `pattern` / `filter` / `clipPath` / `marker`) are copied into each asset and namespaced so the asset is self-contained after re-inline. If both layered and flat views are processed into the same icon namespace, keep distinct `--id-prefix` values to avoid asset ID collisions. `--clean-stale` removes only stale generated assets for the current SVG filenames and prefix inside the selected namespace; it is safe in this import workspace but should not be used against a shared hand-curated icon directory without a specific prefix.
+The authoring SVGs in `<import_workspace>/authoring-svg/` and, when requested, `<import_workspace>/authoring-svg-flat/` are rewritten in place with compact `<use data-icon="imported/..." data-pptx-asset-role="decoration"/>` placeholders. Each in-place extraction refreshes that bundle's `authoring_summary.json` automatically. Extracted assets have one canonical copy under `<import_workspace>/icons/imported/`; never duplicate them under `templates/icons/`. The root `icons/` directory remains a namespace container and must not contain rewritten page SVGs or inventories. Every imported asset root, placeholder, and v2 inventory record declares the `decoration` role. Any subtree containing a semantic marker, text, table, chart, relationship, or other meaning-bearing content remains inline; extraction and both consumers fail closed if that boundary is crossed. Eligible decoration records may retain `data-pptx-source-ref`, so re-inlining re-establishes their object mapping before materialization. The existing icon embedding path re-inlines the extracted assets before final export, preserving multi-color artwork and non-square viewBox geometry as native SVG shapes. Extraction triggers on either many drawable elements or a large pure-vector XML block, so long single-path decorations are factored out too. Pure-vector decoration runs beside text use a lower size threshold without moving the text or its semantic ancestor. Referenced defs (`gradient` / `pattern` / `filter` / `clipPath` / `marker`) are copied into each asset and namespaced so the asset is self-contained after re-inline. If both layered and flat views are processed into the same icon namespace, keep distinct `--id-prefix` values to avoid asset ID collisions. `--clean-stale` removes only stale generated assets for the current SVG filenames and prefix inside the selected namespace; it is safe in this import workspace but should not be used against a shared hand-curated icon directory without a specific prefix.
The layered pass owns the canonical extracted-vector pool. Each new asset records a source fingerprint before generated ID namespacing. The flat pass MUST consume the layered inventory through `--reuse-inventory`: an exact fingerprint match writes only a `<use>` reference to the existing layered asset, while an unmatched flat-only subtree may create one new asset under the `flat` prefix. Do not independently extract the two views into parallel asset sets. With `--clean-stale`, a rerun also removes obsolete generated `flat_*` duplicates while retaining every reused layered reference.
@@ -263,7 +263,7 @@ does not turn those vectors into a picture.
| Mode | Required read set |
|---|---|
| `standard` / `fidelity` | `analysis/manifest.json`, exported semantic resources, `svg/inheritance.json`, `authoring-svg/authoring_summary.json`, and every cleaned layered IR document (`authoring-svg/master_*.svg` / `layout_*.svg` / `slide_NN.svg`). Do not read `authoring_manifest.json`; it is compiler-only. The layered IR is the complete read surface: it covers Layouts unused by any sample slide (invisible in `svg-flat/` yet still template vocabulary), and per-page composition follows from `inheritance.json`. Cleaned flat pages are optional composition spot checks, not a required second pass over the same shapes. Source topology remains non-binding; the two modes differ in output design (`fidelity` designs a broader roster covering the useful visual range), not in read coverage. |
-| `mirror` | `analysis/manifest.json`, `analysis/native_structure.json`, `svg/inheritance.json`, `authoring-svg/authoring_summary.json`, and every cleaned layered Master/Layout/Slide IR document. Do not read `authoring_manifest.json`; `mirror_template_materialize.py` loads and validates it internally. The layered `authoring-svg/` tree is the sole editable and materialization input. Cleaned `authoring-svg-flat/` slides are optional visual composition checks only; never edit or feed them into template materialization. Materialization may resolve unchanged refs against the matching lossless backing without placing opaque payload in model context. |
+| `mirror` | `analysis/manifest.json`, `analysis/native_structure.json`, `svg/inheritance.json`, `authoring-svg/authoring_summary.json`, every cleaned source Slide IR document, and only the Master/Layout IR documents reachable from those Slides. Do not read `authoring_manifest.json`; `mirror_template_materialize.py` loads and validates the same reachable set internally. The layered `authoring-svg/` tree is the sole editable and materialization input. Cleaned `authoring-svg-flat/` slides are optional visual composition checks only; never edit or feed them into template materialization. Materialization may resolve unchanged refs against the matching lossless backing without placing opaque payload in model context. |
Use the compact facts in `analysis/manifest.json` for orientation. Use screenshots or the original PPTX only for visual cross-checking. Do not bulk-read opaque lossless payload into model context.
@@ -272,21 +272,19 @@ Interpretation rule (carries forward into Steps 2 and 4):
- `analysis/manifest.json` is the source of truth for facts about the source deck: slide size, theme colors, fonts, background inheritance, reusable resource inventory, declared source layout/master structure, and slide reuse relationships. It dictates which source facts mirror may preserve during materialization, but not `standard` / `fidelity` output topology.
- `authoring_summary.json` is the model-facing index for the current authoring SVG roster and readability statistics. Regenerate it after direct IR edits before analysis.
- `authoring_manifest.json` is machine-only provenance. Do not open or quote it in model context; the mirror compiler validates it internally against the edited IR and immutable backing.
-- `analysis/native_structure.json` is the source of truth for source PowerPoint identity: stable layout keys, picker names, parent masters, placeholder types/indices, and the source-package hash. Mirror preserves those facts one-to-one. `standard` / `fidelity` do not mine them into the new structure.
+- `analysis/native_structure.json` is the source of truth for source PowerPoint identity: stable layout keys, picker names, parent masters, placeholder types/indices, and the source-package hash. Mirror preserves facts reachable from source Slides one-to-one. `standard` / `fidelity` inspect the complete inventory as evidence but author new identities and ownership.
- `analysis/manifest.json`, `analysis/native_structure.json`, and `svg/inheritance.json` intentionally overlap only at contract boundaries so materialization can cross-check source identity, graph ownership, and visibility; do not collapse them into a cache or substitute one for another
- exported `images/` are the canonical reusable image pool — `<image>` references in `svg/` already point at these files directly; SVG/EMF/WMF image media stay in this pool rather than moving to a generic asset directory
-- exported `icons/imported/*.svg` files are the canonical reusable vector illustration pool, but they are **not** part of the default read set. Use `authoring_summary.json` `icon_refs` and the cleaned SVGs first. Query `*_vector_asset_inventory.json` by an exact asset id only when source-ref or fingerprint detail is required; do not load the complete inventory into model context. Open a specific imported SVG only when that asset affects the current design decision.
+- exported `icons/imported/*.svg` files are the canonical reusable decoration pool, but they are **not** part of the default read set. Use `authoring_summary.json` `icon_refs` and the cleaned SVGs first. Query `*_vector_asset_inventory.json` by an exact asset id only when source-ref or fingerprint detail is required; do not load the complete inventory into model context. Open a specific imported SVG only when that decoration affects the current design decision.
- cleaned layered authoring SVGs are the mirror editing and verification surface; they expose source ownership without requiring the model to read opaque payload. Do not use them to promote, demote, merge, or split source structure.
- cleaned complete-page IR documents are optional composition spot checks for authored modes and verification views for mirror. They never replace the layered editable IR or immutable payload backing.
- screenshots remain useful for judging composition and style, but should not override extracted factual metadata unless the import result is clearly incomplete
-**Mirror complete-graph gate**: compare every `analysis/native_structure.json` Layout
-and Master with the layered `authoring_summary.json` roster before offering `mirror`.
-Every source Layout—including one unused by all source slides—must have a
-layered IR document and matching payload backing from which a reusable
-definition SVG can be materialized. Every source Master must own at least one retained Layout. Missing IR documents
-or ambiguous parentage are blocking; unused identities themselves are supported
-and must not be dropped. The compiler performs the exact source-ref and hash
+**Mirror reachable-graph gate**: compare every source Slide and its referenced
+Layout/Master with the layered `authoring_summary.json` roster before offering
+`mirror`. Missing reachable IR, payload backing, or unambiguous parentage is
+blocking. Source identities unused by every Slide remain analysis evidence and
+are omitted from mirror output. The compiler performs exact source-ref and hash
checks from `authoring_manifest.json`.
### Basic norm extraction (mandatory when reference content exists)
@@ -309,18 +307,18 @@ page order/count, page mappings, canvas, and native structure.
| Density rhythm | title scale, content block count, whitespace balance, dense vs. breathing pages | Page-type guidance for Strategist / Executor |
| Page roster semantics | cover / TOC / chapter / content / ending variants and their intended content slots | `design_spec.md §V Page Roster` rows |
| Asset policy | source images / icons / textures that are part of the template vs. sample-only content | `design_spec.md §VI Assets` or omit sample-only assets |
-| Native PowerPoint structure | `analysis/native_structure.json` plus inheritance facts | Mirror maps the validated source graph one-to-one into a new workspace. Standard/fidelity author an independent output graph and do not distill source common structure. |
+| Native PowerPoint structure | `analysis/native_structure.json` plus inheritance facts | Mirror maps each source Slide's reachable chain one-to-one. Standard/fidelity review the complete inventory, then author a compact or broader useful graph expressed through Slide prototypes. |
Distinguish observed facts from template rules: "`slide_07` uses a left photo crop" is a fact; "content pages may use a left photo rail for location / product / case-study pages" is the reusable rule.
**Read gate**:
- `standard` / `fidelity`: read `authoring_summary.json`, every layered IR Master, Layout, and Slide, and the inheritance map; flat pages are optional spot checks
-- `mirror`: read `authoring_summary.json`, verify and report every layered IR Master, Layout, and Slide plus the inheritance map, and leave `authoring_manifest.json` to the compiler
+- `mirror`: read `authoring_summary.json`, verify every source Slide and its referenced Layout/Master plus the inheritance map, report retained and omitted identities, and leave `authoring_manifest.json` to the compiler
Do not treat authoring IR documents as final template assets. `standard` / `fidelity` author new SVGs from the confirmed brief and IR references. Mirror edits the IR and materializes it with lossless native-payload backing.
-> **Mirror-mode materialization path** — use `analysis/native_structure.json` and `svg/inheritance.json` as model-readable structural authority. The cleaned layered IR is the editable source, `authoring_summary.json` is its model-facing index, and lossless layered SVGs are immutable payload backing; optional flat SVGs are verification-only. `mirror_template_materialize.py` consumes the machine manifest internally. Preserve only the roster, appearance, ownership, placeholders, converter-supported native metadata, and available SVG fallbacks that are actually present and validated; do not synthesize missing facts or a different graph.
+> **Mirror-mode materialization path** — `analysis/native_structure.json` and `svg/inheritance.json` own structure; cleaned layered IR is editable, lossless layered SVG is payload backing, and optional flat SVG is verification-only. `mirror_template_materialize.py` reads the machine manifest, emits only source Slide prototypes, and preserves their reachable graph. It completes inherited SVG context while preserving appearance, ownership, placeholders, supported native metadata, and fallbacks without synthesis.
### 1B. Existing SVG assets
@@ -416,7 +414,7 @@ Compose one concise natural-language proposal that states the template the AI in
| Theme direction | Create Layout/Create Deck only. Describe the intended light/dark/mixed behavior in plain language. Create Brand records identity colors instead and does not own a page theme mode. |
| Canvas | Create Layout/Create Deck only. State the recommended canvas with exact pixel size and `viewBox`; do not enumerate same-ratio alternatives unless the user asks or the evidence is genuinely ambiguous. |
| Creation plan | Create Layout/Create Deck only. Describe what will be preserved, what will be rebuilt, how broad the prototype roster will be, and how native structure will be handled. The AI derives the internal `replication_mode` from this prose after confirmation; never ask the user to select `standard`, `fidelity`, or `mirror`. |
-| Native structure plan | Create Layout/Create Deck only. State the planned Master/Layout/slot result. For newly authored output, show the planned Master families and reject one-Master-per-Layout organization or equivalent duplicate Masters. For literal preservation, summarize the exact supported source facts that will be mapped into the new workspace. |
+| Native structure plan | Create Layout/Create Deck only. State the Master/Layout/slot result: compact authored `standard`, broader useful `fidelity`, or source-Slide-reachable `mirror`. Every authored Layout needs a Slide prototype; reject duplicate Masters. |
| Asset bundling | Create Brand/Create Layout/Create Deck only. Recommend included assets, plus excluded candidate assets with a one-line reason when reference assets exist. Create Style records textual provenance only and writes no asset payload. |
Items to surface:
@@ -437,8 +435,8 @@ Items to surface:
| Theme mode | Create Layout/Create Deck only | A: `[fact]` from `analysis/manifest.json` background colors. B: `[fact]` from SVG `fill`. C: `[suggested]` from visual estimate. D: `[fact]` from an independently identified external authority, `[decision]` from user-authored text in any carrier, otherwise `[suggested]`. E: `[decision]`. |
| Canvas format and dimensions | Create Layout/Create Deck only | A/B: `[fact]` from slide size or SVG `width` / `height` / `viewBox`; show `canvas_format`, `canvas_width`, `canvas_height`, `canvas_viewbox`, and `source_viewbox`. C: `[suggested]` from image aspect ratio. D: `[fact]` from an independently identified external authority or `[decision]` from user-authored text in any carrier when specified. E: `[decision]`, default `ppt169` (`1280x720`, `0 0 1280 720`). |
| Internal creation strategy | Create Layout/Create Deck only | `[derived]` from the confirmed natural-language plan and evidence. `standard` is the compact authored implementation, `fidelity` requires A/B page evidence for broader source-aligned coverage, and `mirror` requires A or B with a complete explicit structure contract for literal materialization. Create Layout mirror additionally requires a brand-neutral and application-neutral source. Persist `replication_mode` for tools, not as a user-facing mode. |
-| Native structure facts | Create Layout/Create Deck with Type A or structured Type B | `[fact]` from `analysis/native_structure.json` / source SVG contract: master/layout counts, parentage, page assignments, placeholder identities, and multi-master status. Mirror preserves these validated facts in the new workspace; authored modes do not use them as output topology. |
-| Structure ownership plan | Create Layout/Create Deck only | `[derived]` from the requested result. Authored output creates new Master/Layout ownership, including the reusable-family reason for every additional Master; literal preservation maps source ownership without synthesis. Every Master must own at least one emitted Layout and every Layout must have at least one emitted prototype. |
+| Native structure facts | Create Layout/Create Deck with Type A or structured Type B | `[fact]` from `analysis/native_structure.json` / source SVG contract: master/layout counts, parentage, page assignments, placeholder identities, and multi-master status. Mirror preserves the source-Slide-reachable subset in the new workspace and records the remaining identities only as omitted scope; authored modes do not use source topology as output topology. |
+| Structure ownership plan | Create Layout/Create Deck only | `[derived]`. Authored output explains each additional Master; mirror maps only source-Slide-reachable ownership. Every Master owns an emitted Layout and every Layout has a complete Slide prototype. |
| Reference treatment | Create Layout/Create Deck when a reference exists | `[derived]` per page from the user's prose: closely reproduce geometry/decoration where requested, otherwise adapt the reference into the newly authored system. Literal materialization preserves supported source facts mechanically. |
| Basic template norms | Yes when reference exists | Create Brand uses the identity fields and provenance rules from its child workflow. Create Style uses portable method, page-role, evidence/data, composition/density, visual-default, and image/icon rules while discarding project-specific context. Create Layout/Create Deck use `[fact]` / `[suggested]` layout grammar, image system, density rhythm, page roster semantics, and asset policy from Step 1. |
| Reference source | Optional | already known if Step 1 ran |
@@ -479,10 +477,10 @@ Skipping this gate — including silently inferring values from reference files,
- [ ] For Create Layout/Create Deck, the canvas format is fixed before SVG generation
- [ ] For Create Layout/Create Deck, the AI-derived internal strategy is consistent with the bundle evidence (`fidelity` requires A/B page evidence; `mirror` requires A or structured B; C/D/E channels alone permit only `standard`); Create Layout mirror evidence is already brand-neutral and application-neutral
- [ ] Every supplied visual, textual, documentary, web, and asset channel has been analyzed or explicitly excluded; mixed-input conflicts are surfaced rather than silently resolved
-- [ ] For Create Layout/Create Deck mirror, the source graph and supported geometry are complete; every source Layout absent from the source-slide roster is planned as a definition-only prototype, and any genuinely missing/unsupported facts were reported; Create Layout mirror contains no retained brand identity or reusable application policy
+- [ ] For Create Layout/Create Deck mirror, every source Slide and its reachable Layout/Master chain is valid and context-complete; omitted unreferenced identities and genuinely missing/unsupported reachable facts were reported; Create Layout mirror contains no retained brand identity or reusable application policy
- [ ] Child-specific norms from prior content have been surfaced and accepted, or explicitly marked N/A when no reference exists: identity/provenance for Create Brand; communication/evidence/visual-direction behavior for Create Style; layout/image/density/asset behavior for Create Layout/Create Deck
- [ ] For Create Style, the portable communication method, open page-role vocabulary, evidence/data rules, visual defaults, image/icon direction, and advisory review focus are confirmed; project-specific audience/outcome/page sequence and all identity/structure fields remain N/A
-- [ ] For Create Layout/Create Deck, the plan makes structure ownership explicit: authored output creates a new structure without source-topology distillation; literal materialization maps validated source ownership one-to-one into a new workspace
+- [ ] For Create Layout/Create Deck, the plan makes structure ownership explicit: authored output creates compact (`standard`) or broader useful (`fidelity`) Slide prototypes after reviewing complete source evidence; literal materialization maps source Slides and their reachable graph one-to-one
- [ ] For Create Deck, the recurring presentation family, intended audiences/outcomes, and representative page roles are understood without turning them into mandatory page/content policies; for Create Layout, no application contract or brand identity has leaked into the structure brief
- [ ] For Create Brand, all required identity fields from its child workflow are confirmed and canvas/replication/native-structure fields remain N/A
- [ ] For `library`, metadata is complete enough to register into the relevant index; for `project`, the same portable template metadata is complete and no global registration is planned
@@ -559,8 +557,8 @@ The role interprets the package according to the AI-derived internal creation st
| Mode | Final SVG authority | Structure behavior |
|---|---|---|
-| `standard` / `fidelity` | Newly authored SVGs based on the confirmed brief and visual references | Design an intentional new Master/Layout/slot system. Source topology is neither preserved nor distilled into the output. |
-| `mirror` | Editable `authoring-svg/` IR plus native-structure facts and lossless payload backing | Materialize source pages, Master/Layout identities and parentage, placeholder identity/bounds, ownership, and supported native-object metadata one-to-one in the new workspace. Materialization resolves unchanged source refs; it does not copy the lossless tree as the editable source. |
+| `standard` / `fidelity` | Newly authored SVGs from the brief and complete source evidence | Author a compact or broader useful Master/Layout/slot system; do not retain identities merely because they exist. |
+| `mirror` | Editable IR plus native facts and lossless backing | Materialize source Slides and their reachable Layout/Master chains; resolve inherited context without changing ownership. |
For Type A `mirror`, materialize the reviewed layered IR into a workspace with
no existing roster, using the deterministic compiler:
@@ -574,13 +572,15 @@ Destination `templates/` may be absent/empty or hold unique qualified
Brand/Style specs; a Layout-over-Deck stage may also hold one qualified Deck
spec without its roster. A bare spec, Layout spec, active roster, or other
payload blocks materialization. Before atomic publication, the command verifies
-the layered manifest/source refs, lossless SVG/source-PPTX hashes, complete
-native/inheritance graph, and vector inventory. It emits source-ordered page
-SVGs, unused-Layout definition
-SVGs, `icons/imported/`, referenced `images/`, `audio/`, `video/`, or
+the layered manifest/source refs and lossless hashes for source Slides plus the
+reachable native/inheritance graph and vector inventory. It emits source-ordered Slide
+SVGs only, plus `icons/imported/`, referenced
+`images/`, `audio/`, `video/`, or
`native-payloads/imported/` resources as applicable, and one
deduplicated `templates/native_payloads.json.gz` store when supported native
-payload or repeated restoration metadata exists. It also writes
+payload or repeated restoration metadata exists. A PPTX-backed mirror also
+writes `templates/source_themes.json` with the exact Theme of each retained
+Master. It also writes
`templates/template_execution_manifest.json` with schema
`ppt-master.template-execution-manifest.v1`, a compact tool-readable prototype
roster and grouped source-import warning summary. Each prototype points to one
@@ -598,8 +598,9 @@ not create the Design Spec. Template_Designer writes `<design_spec_path>` from
the confirmed brief and the materialized roster before Step 5. A rerun targets
a workspace with no roster rather than overwriting a partially reviewed one.
-**Hard rule — mode-specific authorship**: `standard` and `fidelity` author new
-project-canonical SVG documents. When one registered PowerPoint preset exactly
+**Hard rule — mode-specific authorship**: `standard` and `fidelity` review all
+source Master/Layout evidence, then author a compact or broader useful canonical
+system without copying unused/duplicate identities. When one registered PowerPoint preset exactly
expresses one complete object, they use the compact canonical
`<g>` emitted by `preset_shape_svg.py`, following
[`native-shape-authoring.md`](../references/native-shape-authoring.md); its
@@ -612,15 +613,14 @@ decides whether to use `shape_boolean_svg.py` under
[`native-shape-authoring.md`](../references/native-shape-authoring.md) §6; a
brief/reference suggestion does not lock the operation. `mirror` preserves the expanded
lossless source contract in a new workspace and may only normalize transport details required by
-the current compiler. Mirror never performs commonality
-extraction, semantic synthesis, merge/split, promotion/demotion, renaming, or
-re-parenting.
+the current compiler. Mirror never performs commonality extraction, semantic
+synthesis, merge/split, promotion/demotion, renaming, or re-parenting.
**Hard rule — multi-Master package boundary**: More than one Master is valid only when `mirror` preserves an existing source graph in the new workspace or an authored template intentionally defines distinct reusable design families. `standard` / `fidelity` must not create one Master per Layout or duplicate equivalent Masters merely for organization. Every declared Master must own at least one emitted Layout, and every declared Layout must be selected by at least one prototype SVG so the complete graph can be compiled and verified.
| Package concern | Requirement |
|---|---|
-| Theme ownership | Every registered Slide Master receives its own Theme part. Two Masters must never resolve to the same `ppt/theme/themeN.xml`. Theme cloning is exporter-owned; do not author or bundle Theme XML in the template workspace. |
+| Theme ownership | Every registered Slide Master receives its own Theme part. Two Masters must never resolve to the same `ppt/theme/themeN.xml`. Theme cloning is exporter-owned. Authored modes do not bundle Theme XML; a PPTX-backed mirror may carry the compiler-written `source_themes.json` sidecar. |
| Creation identity | Any generated `p14:creationId` on Slides, Layouts, or Masters is a valid unsigned 32-bit value and unique across those parts. Cloned structural parts always receive fresh values. |
| Numeric registration | Master and Layout registration IDs are valid and unique in their owning lists; Layout numeric IDs are unique across the complete package, including across different Masters. |
| Relationship graph | The presentation registers the exact Master and Slide rosters; each Master registers exactly its owned Layouts; each Layout targets exactly one declared Master; each Slide targets exactly its declared Layout. |
@@ -629,7 +629,7 @@ SVG authors own the semantic roster, parentage, picker names, direct atoms, and
Do not package `analysis/native_structure.json` or `sources/source.pptx` as template inputs. In `standard` / `fidelity`, author Master/Layout direct semantic atoms and bounded slot groups deliberately from the intended reusable behavior. A validated compact canonical authored-preset `<g>` compiles to one native shape and therefore counts as one semantic atom; it may own a Master/Layout fixed layer or serve as the one direct carrier of an `object` slot. Ordinary groups are not structural atoms or single-object carriers. In `mirror`, edit the layered authoring IR and use inheritance/native facts to preserve source ownership; the lossless trees remain payload backing. Recursively expand fixed Master/Layout group wrappers only because the structured contract requires semantic atoms; preserve transforms, styles, paint order, and appearance, and never flatten or regroup by semantic judgment.
-`<design_spec_path> §V` records the newly authored roster for `standard` / `fidelity`. For `mirror`, add the `Source Preservation Map` required by [template-designer.md](../references/template-designer.md), with one row per source slide and its preserved Master/Layout assignment. Do not add a synthesis-decision table.
+`<design_spec_path> §V` records every emitted Slide. Mirror adds the [required Source Preservation Map](../references/template-designer.md) for source-Slide assignments and, when relevant, one sentence that unreferenced source identities exist but were not materialized. Do not add per-identity analysis or model-authored synthesis rationale.
**Native-shape metadata boundary**: The authoring IR removes opaque payload
from model context while retaining stable source refs. `standard` / `fidelity`
@@ -651,10 +651,10 @@ Downstream, Strategist inspects the installed workspace and current content, the
**Mirror materialization contract** (type A or B): when the derived implementation writes `replication_mode: mirror`, the Template_Designer role:
-1. **Materializes one output SVG per source page** in `<authoring_workspace>/templates/`. Edit and normalize the matching `authoring-svg/` IR document, then run `mirror_template_materialize.py`; the compiler consumes the tool-only authoring manifest together with native structure facts and immutable payload backing. Do not hand-copy or independently rebuild its graph. Preserve the source Master/Layout keys and picker names, Layout parentage, slide assignment, placeholder type/index/bounds, inherited-shape visibility, ownership, paint order, and supported native metadata that are present and validated. Mechanical namespace, root-declaration, asset-path, and fixed-layer group normalization is allowed only when source ownership and appearance remain unchanged.
+1. **Materializes one output SVG per source Slide** in `<authoring_workspace>/templates/`. Edit and normalize the matching `authoring-svg/` IR document, then run `mirror_template_materialize.py`; the compiler consumes the tool-only authoring manifest together with native structure facts and immutable payload backing. Do not hand-copy or independently rebuild its graph. Preserve each Slide's reachable Master/Layout keys and picker names, Layout parentage, assignment, placeholder type/index/bounds, inherited-shape visibility, ownership, paint order, and supported native metadata. Mechanical context completion plus namespace, root-declaration, asset-path, bounds, and fixed-layer group normalization is allowed only when source ownership and appearance remain unchanged.
- Type A model-facing source: `<import_workspace>/authoring-svg/authoring_summary.json` plus the editable SVGs; `<import_workspace>/svg/`, `svg/inheritance.json`, and `analysis/native_structure.json` provide payload and structural backing. The compiler alone reads `<import_workspace>/authoring-svg/authoring_manifest.json`. Optional `<import_workspace>/svg-flat/` is verification-only.
- Type B model-facing source: `<svg_analysis_workspace>/authoring-svg/authoring_summary.json` plus its editable SVGs; the complete explicit source SVG contract is immutable backing
- - For every source Layout unused by all source slides, additionally materialize one definition-only SVG named `layout_<layout_key>.svg` from its layered authoring IR document and payload backing. It carries the exact root identity, fixed atoms, and placeholder contract but is not a generated page assignment. Use source placeholder prompts/carriers; do not invent business content. This definition SVG lets downstream export register the Layout and any otherwise-unused parent Master without retaining an internal carrier slide.
+ - Each source Slide SVG resolves Master + Layout + Slide context and keeps layer markers explicit. Source Master/Layout identities unused by every Slide produce no file; use `standard` / `fidelity` to re-author useful ones as complete Slide prototypes.
2. **Renames each file** using the source-order-first convention `<NNN>_<page_type>.svg`, where `<NNN>` is the source-order index zero-padded to 3 digits and `<page_type>` is typically `cover` / `toc` / `chapter` / `content` / `ending` (fall back to `content` when the type cannot be confidently classified). Examples: `001_cover.svg`, `002_toc.svg`, `003_content.svg`, ..., `050_ending.svg`.
- Type A: derive `<page_type>` from `analysis/manifest.json.pageTypeCandidates`
- Type B: derive `<page_type>` from the source filename when it follows the PPT Master convention (`01_cover.svg` → `cover`, `03a_content_two_col.svg` → `content`); otherwise infer from page content or fall back to `content`
@@ -662,7 +662,7 @@ Downstream, Strategist inspects the installed workspace and current content, the
- Type A: image media come from `<import_workspace>/images/`; other resources retain their semantic source directories
- Type B: resolve relative paths in source `<image href="...">` against the source SVG location and copy each unique asset; if the source already follows PPT Master conventions (assets co-located with SVGs in the same directory), copy the whole asset set and then rewrite paths
- Both scopes: write raster, SVG, EMF, and WMF image media to `<authoring_workspace>/images/`, point SVG references at `../images/<name>`, and route audio, video, or opaque payloads to their semantic workspace directories.
-4. **Copies imported vector assets once** to `<authoring_workspace>/icons/imported/` and rewrites their placeholders to `<use data-icon="imported/<name>"/>`. Never place a second copy under `templates/icons/`. Other explicitly adopted icon-library references keep their existing library namespace. Do not inline these assets manually in the template working SVGs; template validation, preview, and final export all resolve icons from the workspace-root `icons/` directory.
+4. **Copies decoration-only imported vector assets once** to `<authoring_workspace>/icons/imported/` and rewrites their placeholders to `<use data-icon="imported/<name>" data-pptx-asset-role="decoration"/>`. Semantic authoring objects stay inline. Never place a second copy under `templates/icons/`. Other explicitly adopted icon-library references keep their existing library namespace. Do not inline these assets manually in the template working SVGs; template validation, preview, and final export all resolve icons from the workspace-root `icons/` directory.
5. Writes `<design_spec_path>` per [template-designer.md](../references/template-designer.md) §1. The §V Page Roster remains a factual prototype index; explicit SVG metadata is the native Master/Layout contract. `replication_mode: mirror` records how the workspace was created and only makes literal downstream reuse technically possible; it never selects that behavior or forces a 1:1 slide sequence.
Mirror mode does not simplify the visual target or synthesize layer ownership. The sprite-sheet preservation rule applies because crop wrappers carry visible geometry; preserve those wrappers and their source scope faithfully.
@@ -735,12 +735,13 @@ ls -la "<template_source>"
ls -la "<authoring_workspace>/images" "<authoring_workspace>/icons"
```
-Compact safe page-space metadata and transform coordinates, then run SVG
-validation on the template directory. Keep canonical authored-preset and native
-record frames unchanged:
+Compact safe page-space metadata, transform coordinates, and repeated inherited
+presentation declarations, then run SVG validation on the template directory.
+Keep canonical authored-preset and native record frames unchanged:
```bash
python3 skills/ppt-master/scripts/compact_svg_coordinates.py "<template_source>" --inplace --keep-native-frames
+python3 skills/ppt-master/scripts/compact_svg_styles.py "<template_source>" --inplace
python3 skills/ppt-master/scripts/svg_quality_checker.py "<template_source>" --template-mode --format <canvas_format>
```
@@ -753,14 +754,14 @@ python3 skills/ppt-master/scripts/svg_quality_checker.py "<template_source>" --t
- require every SVG root to declare one output Master and Layout; zero-slot Layouts are valid
- reject ordinary Master/Layout `<g>` elements, nested structure markers, missing slot bounds, and carrier-bound slots without exactly one compatible carrier; a validated compact canonical authored-preset `<g>` is the sole fixed-layer group exception and may be one `object` carrier
- validate cross-page Master equality plus same-key Layout atom/slot equality
-- warn when distinct Layout keys have identical static framing/slot contracts. Resolve this for `standard` / `fidelity`; mirror may retain the distinct source identities and records that fact in its Source Preservation Map
+- warn when distinct Layout keys have identical static framing/slot contracts. Resolve this for `standard` / `fidelity`; mirror keeps distinct source identities and records them in its Source Preservation Map
This checker validates the authoring contract, not the compiled OOXML package. Theme ownership, package IDs, and registered part relationships are verified by `template_preview_pptx.py` in Step 6.
**Checklist**:
- [ ] `<design_spec_path>` follows the kind-specific package skeleton: deck = descriptive Overview / Color / Signature / Page Roster plus conditional sections; layout = structure-owned Signature / Page Roster with no Overview, application contract, or identity sections. Generic constraints (SVG rules, pattern libraries, ratio bands, canonical placeholder table) are NOT restated. The source-derived basic norms are present as template-specific layout / image / density / asset rules, not generic advice. Deck Overview identifies recurring situations, audiences/outcomes, delivery assumptions, and representative narrative/page roles; §V Page Roster factually describes every emitted prototype without required/optional/repeatable or fixed/replaceable/example-only policy
-- [ ] Every page declared in `<design_spec_path> §V Page Roster` exists as an SVG file in the template directory (and vice versa — no orphan files)
+- [ ] Every SVG on disk is a complete Slide prototype with a §V roster row; when mirror omits unreferenced source identities, one §V scope sentence records that fact without per-identity analysis
- [ ] Variant filenames follow the letter-suffix convention (e.g. `03a_content_two_col.svg`); variants typically reuse the parent type's placeholder set unless the spec frontmatter declares otherwise
- [ ] If TOC exists, placeholder pattern uses the canonical indexed form
- [ ] `<design_spec_path>` frontmatter declares `canvas_format`, `canvas_width`, `canvas_height`, and `canvas_viewbox`; PPTX/SVG-backed templates also declare `source_canvas_width`, `source_canvas_height`, and `source_viewbox`
@@ -775,15 +776,15 @@ This checker validates the authoring contract, not the compiled OOXML package. T
- [ ] In review output, authored placeholder prompts remain readable; `template_preview_pptx.py` uses preview-only sample text and leaves every canonical source marker and carrier style unchanged
- [ ] `standard` / `fidelity` output SVGs and their Master/Layout/slot contracts were newly authored without preserving or distilling source topology
- [ ] Every additional authored Master represents a distinct reusable design family, not one Layout or an equivalent duplicate; every declared Master owns at least one emitted Layout and every declared Layout has at least one emitted prototype
-- [ ] Mirror output preserves source slide order, Master/Layout identity and parentage, placeholder facts, and ownership; fixed-layer group expansion is mechanical and pixel-equivalent, and the Source Preservation Map lists every source slide
+- [ ] Mirror output preserves source slide order, the full identity and parentage of every retained Master/Layout, placeholder facts, and ownership; context completion and fixed-layer group expansion are mechanical and pixel-equivalent, and the Source Preservation Map lists every source slide
- [ ] Mirror materialization wrote one compact `ppt-master.template-execution-manifest.v1` roster and one linked `ppt-master.template-text-slots.v2-min` diagnostic sidecar per prototype; each slot has only `selector`, `role`, `current_text`, `text_segments`, and `tspan_count`; neither artifact is injected into page authoring, while validation/export check the complete prototype
- [ ] Mirror roots preserve source inherited-shape visibility with canonical lowercase `data-pptx-show-master-shapes` and `data-pptx-show-inherited-shapes`; same-key Layouts agree on the former, while each Slide retains its own latter value
-- [ ] Mirror preflight covered the complete source graph; each unused Layout has one `layout_<layout_key>.svg` definition prototype and each otherwise-unused Master is retained through at least one such Layout
+- [ ] Mirror preflight covered every source Slide and its reachable Layout/Master chain; unreferenced source identities produced no SVG and are reported as omitted
- [ ] For `standard` / `fidelity`, no duplicate-Layout-contract warning remains; mirror may keep equivalent source Layout identities when the preservation map explains them
- [ ] All template-creation edits used the authoring IR; Type A mirror used `mirror_template_materialize.py`, validated its manifest/hash/graph/source-ref closure before atomic publication, reused only converter-supported payload for hash-matching Slide-local/slot refs, deduplicated supported opaque payload and repeated native restoration attributes into `templates/native_payloads.json.gz`, stripped IR-only source-ref metadata, and kept fixed Master/Layout visuals as direct atoms
-- [ ] If any SVG references an extracted vector, it uses `data-icon="imported/<name>"` and the sole SVG asset exists at `<authoring_workspace>/icons/imported/<name>.svg`; `templates/icons/` does not exist and no separate illustration embedding script was added
+- [ ] If any SVG references an extracted vector, it uses `data-icon="imported/<name>" data-pptx-asset-role="decoration"`; the v2 inventory and sole SVG asset under `<authoring_workspace>/icons/imported/` declare the same role; no semantic object or descendant is externalized, `templates/icons/` does not exist, and no separate illustration embedding script was added
- [ ] For `fidelity` mode: every sprite-sheet asset retains its nested `<svg viewBox=...>` crop wrapper; no image whose file aspect differs from its on-page aspect was flattened to a bare `<image>`
-- [ ] For `mirror` mode: source-page SVG count equals source page count, while additional files are exactly the required `layout_<layout_key>.svg` definitions for unused source Layouts; source-page filenames follow the `<NNN>_<page_type>.svg` convention; **no new `{{...}}` authoring placeholders were inserted into materialized source-page SVGs**; §V Page Roster lists every emitted file and marks definition-only prototypes explicitly
+- [ ] For `mirror` mode: SVG count equals source Slide count, filenames follow `<NNN>_<page_type>.svg`, no standalone Master/Layout SVG exists, and **no new `{{...}}` authoring placeholders were inserted**; §V lists every emitted Slide prototype
This step is a **hard gate**. Do not generate a review PPTX, register, install a staged structural transition, or hand the workspace to the main pipeline until validation passes. After a staged project install, rerun the checker on the final `<target_project>/templates/`; it validates the effective Layout roster when Layout and Deck coexist. A one-Master template may skip Step 6 when no review was requested; a multi-Master template must continue to Step 6 and may not register or complete before that package gate passes.
diff --git a/skills/ppt-master/workflows/create-template/create-layout.md b/skills/ppt-master/workflows/create-template/create-layout.md
index f914e750..92b1319f 100644
--- a/skills/ppt-master/workflows/create-template/create-layout.md
+++ b/skills/ppt-master/workflows/create-template/create-layout.md
@@ -33,7 +33,7 @@ Use Create Template Step 1 for source ingestion and internal creation-strategy f
- Colors, font families, branded weight choices, final absolute sizes, logos, voice, and icon style remain source context only. Do not copy them into the layout identity because a layout has no identity segment.
- A source scenario may inform the content shapes or delivery conditions the geometry can support. Do not turn that fit into an application contract. If the reusable artifact prescribes the objective, outcome, narrative sequence, boilerplate, or content policy, return to Create Template dispatch and select Create Deck.
- When the source is branded, state in plain language that Create Layout will omit the identity. The AI therefore derives an authored internal strategy. If the user wants the identity retained with the structure, return to Create Template dispatch and select Create Deck before the shared confirmation marker is emitted.
-- Internally, `standard` and `fidelity` author a new Master/Layout/slot system. `mirror` may be derived only when the complete current source contract is already brand-neutral and application-neutral; it preserves validated structure and visual facts in a new workspace without modifying the source. Never ask the user to choose among these labels.
+- Internally, `standard` and `fidelity` inspect the complete source inventory and author a new Master/Layout/slot system. `mirror` may be derived only when the source-Slide-reachable contract is complete, brand-neutral, and application-neutral; it preserves that reachable structure and its visual facts in a new workspace without modifying the source. Never ask the user to choose among these labels.
Direct conversation text, pasted requirements, converted documents/websites, images, and supplied assets may define or illustrate reusable structure. In a mixed bundle, combine those channels without treating identity-only evidence as layout ownership. Exact user-authored instructions remain decisions whether they arrive in chat or a user-written brief file; vague prose remains suggested interpretation until the shared confirmation gate.
diff --git a/skills/ppt-master/workflows/generate-pptx.md b/skills/ppt-master/workflows/generate-pptx.md
index 701b5bc0..df2ace26 100644
--- a/skills/ppt-master/workflows/generate-pptx.md
+++ b/skills/ppt-master/workflows/generate-pptx.md
@@ -710,6 +710,7 @@ Do not duplicate specialized identity with `data-pptx-role`. Add it only to stru
**First-page gate (Mandatory)** — after the **first** SVG page, before drawing page 2:
```bash
+python3 ${SKILL_DIR}/scripts/compact_svg_styles.py <project_path>/svg_output --inplace
python3 ${SKILL_DIR}/scripts/svg_quality_checker.py <project_path> --stage first-page --json
```
Run the command unfiltered—do not pipe it through `tail`, `head`, `grep`, or another output truncator. Review the complete P01 issue set from that one run before editing. Select any advisory warnings worth addressing, fix all blocking errors and selected warnings in one consolidated edit pass, then perform one verification rerun. Do not rerun merely to reveal the next issue. If verification still fails, treat its complete output as the next batch and repeat the same review → consolidated edit → single verification cycle; never check between individual fixes. If the terminal output itself is truncated, read only the relevant issue arrays from `validation/svg_quality_first_page_report.json`; do not launch another checker run for discovery. After the gate passes, draw P02 through the final page without checker calls.
@@ -732,6 +733,7 @@ gate-signal: method=<rule resolved, or none> | page-local=<count> | not-exercise
**Quality Check Gate (Mandatory)** — only after every planned SVG exists, BEFORE annotation handling and speaker notes:
```bash
+python3 ${SKILL_DIR}/scripts/compact_svg_styles.py <project_path>/svg_output --inplace
python3 ${SKILL_DIR}/scripts/svg_quality_checker.py <project_path> --stage final --json
```
- **MUST**: Before this gate, every §IX `Native-ready` entry `<object-key>=yes` already has one matching draw-time marker group and JSON metadata child; `=no` and incidental microvisuals remain ordinary SVG. A legacy bare `yes|no` is readable only when that page has exactly one eligible object; it never derives from §VII.
diff --git a/skills/ppt-master/workflows/profiles/quick-generate.md b/skills/ppt-master/workflows/profiles/quick-generate.md
index 59af26b0..c41442ea 100644
--- a/skills/ppt-master/workflows/profiles/quick-generate.md
+++ b/skills/ppt-master/workflows/profiles/quick-generate.md
@@ -696,10 +696,11 @@ already present.
After every page and required referenced resource exists, run the Quick branch
of [`verify-charts`](../stages/verify-charts.md) when any data-driven chart was
-authored. Complete all coordinate repairs first; then run the one lockless final
-SVG check:
+authored. Complete all coordinate repairs first; then compact shared root/group
+presentation values and run the one lockless final SVG check:
```bash
+python3 ${SKILL_DIR}/scripts/compact_svg_styles.py <project_path>/svg_output --inplace
python3 ${SKILL_DIR}/scripts/svg_quality_checker.py <project_path> \
--quick-generate --stage final --json
```
diff --git a/skills/ppt-master/workflows/stages/apply-template-workspace.md b/skills/ppt-master/workflows/stages/apply-template-workspace.md
index 48ed4b44..843d38c2 100644
--- a/skills/ppt-master/workflows/stages/apply-template-workspace.md
+++ b/skills/ppt-master/workflows/stages/apply-template-workspace.md
@@ -107,8 +107,9 @@ leave the rest of the document untouched. An in-place root is not rewritten:
- Copy every selected spec from the root to its resolved qualified destination.
- If the root contributes the effective structural owner, copy its declared
- SVG roster and other non-bitmap structural files once. Do not copy a Deck
- roster when Layout is selected; its structure is shadowed by design.
+ SVG roster and other non-bitmap structural files once, including mirror
+ `source_themes.json` when present. Do not copy a Deck roster when Layout is
+ selected; its structure is shadowed by design.
- Copy the root's real package-owned `images/` and `icons/` files once. A
Style-only root has none; reject a Style-only library package carrying asset
or review payloads.
@@ -146,7 +147,7 @@ agent before direct authoring, and every later role read only
is installation input, not a later prompt source. If source and target are the
same project root, that in-place root already satisfies this boundary.
-Template SVGs are authoring prototypes, not export-time overlays. The generated page remains complete in `svg_output/`; `page_layouts` selects the complete prototype and its explicit structure contract for authoring.
+Template SVGs are complete Slide authoring prototypes, not export-time overlays. They already resolve Master + Layout context, so `page_layouts` selects one directly. Standalone Master/Layout definition SVGs are invalid; an unselected authored Slide prototype may still back a reusable Layout definition.
Quick instead realizes the selected prototypes into complete flat, Slide-local
SVGs and never writes `page_layouts` or Master/Layout/placeholder metadata.