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(template-import): preserve native master and layout contracts

hugohe36d90c97f3740
diff --git a/docs/faq.md b/docs/faq.md
index fd628d99..55bc1183 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -238,9 +238,9 @@ Want to turn a PPT you love into a reusable template for PPT Master? Here's how:
**Step 1 — Prepare Reference Material**
-The simplest path is still to prepare screenshots of the key page types from your reference PPT — cover page, table of contents, chapter divider, content page, and closing page. Save them as images in a single folder with clear, descriptive filenames (e.g., `cover.png`, `toc.png`, `chapter.png`, `content.png`, `closing.png`).
+The recommended input is the original `.pptx`. PPT Master extracts theme identity, every master/layout, placeholder type/index metadata, and reusable assets. When that native structure is reusable, the template package preserves the source package and generated pages bind to its original layouts; when the structure is minimal, the workflow rebuilds a clean master plus semantic layouts from layered SVG references.
-If you already have the original `.pptx` template file, you can also provide it as a reference source. PPT Master can extract reusable background images, logos, theme colors, and font metadata from the PPTX first, then use those assets during template reconstruction.
+If no source PPTX exists, screenshots of the key page types still work — cover, TOC, chapter, content, and closing — but geometry, fonts, and inheritance must then be inferred visually.
**Step 2 — Let AI Create the Template**
diff --git a/docs/roadmap.md b/docs/roadmap.md
index e12a1373..4eb6f2ad 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -82,7 +82,7 @@ The past two months' structural capability growth. Single flags / incremental po
- **`--native-objects` hardened from dormant marker to usable opt-in** — the narrow native-object exception (see Non-goals below) now emits charts and pure-text tables that keep the deck's own design instead of snapping to PowerPoint's white default theme. Classic native charts write explicit chart-area / plot-area / axis-line / gridline / label-text colors — inferred from the visible SVG fallback (largest panel `<rect>` → background, fallback text → labels, fallback strokes → axis/grid) or overridden per `style` (`chart_area_fill` / `plot_area_fill` / `text_color` / `axis_color` / `grid_color`, `"none"` for transparent); the color parser normalizes named CSS colors, `#RGB` shorthand, and `rgb()` / `rgba()` to OOXML hex; bar/column series disable negative-value fill inversion so negative bars keep their series color. The activated export is named `<name>_<ts>_native_charts.pptx` to tell it apart from the default flattened-shape export. **The default route is unchanged** — charts/tables still export as SVG-derived DrawingML shapes for cross-renderer fidelity; native objects stay the deliberate opt-in trade documented under Non-goals below
-- **Native package structure + conservative PPTX object round-trip** — native export now keeps the base package's real blank-layout relationship and defaults to a baseline master that promotes only identical backgrounds and a safe leading prefix of repeated chrome. A locked `pptx_structure.mode: template` compiles declared SVG master/layout layers and typed placeholders into reusable PowerPoint layouts without visual inference; every page maps through `pptx_layouts`, same-key pages reuse one contract, and deck/page-type/page-specific solid backgrounds become real Master/Layout/Slide `p:bg` fills. Supplied PPTX templates still use the preservation-oriented `template-fill-pptx` route. The standalone `pptx_to_svg.py` importer emits fallback SVG plus native metadata for supported unmerged tables and classic-chart caches; exporter-canonical solid series/slice colors and exact title/subtitle structures survive a second `--native-objects` export, while unsupported table/chart semantics remain explicit fallback-only markers
+- **Native package structure + conservative PPTX object round-trip** — native export keeps a real master/layout relationship and defaults to a baseline master that promotes only safe shared backgrounds/chrome. A locked `template` mode compiles declared SVG master/layout layers and typed placeholders without visual inference; a reusable PPTX imported through `create-template` can instead lock `preserve`, retain its original master/layout/theme roster (including multiple masters), bind pages to exact source layouts, and restore source placeholder indices. Raw one-off PPTX filling remains the `template-fill-pptx` route. The standalone importer also emits fallback SVG plus native metadata for supported unmerged tables and classic-chart caches; unsupported semantics remain explicit fallback-only markers
---
@@ -112,11 +112,11 @@ 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)
-PPT Master's main route is "AI generates SVG from scratch → DrawingML", with the whole pipeline built around full control of every shape / text / layout. "Parse existing PPTX placeholders + only refill text" is a different product shape requiring handling of arbitrary master / theme / placeholder systems — orthogonal to where this architecture invests.
+PPT Master's main route is "AI generates SVG from scratch → DrawingML", with the whole pipeline built around full control of every shape / text / layout. A structured PPTX can now be converted into a reviewed reusable package whose master/layout/theme are preserved, but 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.
-> **vs. the `template-fill-pptx` route**: "reuse a deck's *own* design and refill it with new content" is a supported capability (see "2026-06" above), with natively-editable output. What's out of scope here is the other shape — parsing an **arbitrary third-party** template's master / theme / placeholder system to do text-only substitution. Different investment points; don't conflate them.
+> **Supported boundaries**: `template-fill-pptx` directly refills selected source slides. `create-template` + `preserve` first turns a structured source into a reviewed reusable contract, then generates new slide content against exact source layouts. What remains out of scope is unreviewed, schema-free text-only substitution against every arbitrary third-party placeholder system.
### Switch to native PowerPoint charts (Excel-native chart)
diff --git a/docs/technical-design.md b/docs/technical-design.md
index 68f46cb3..46569178 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -429,7 +429,9 @@ These direct routes share some analysis primitives with the main pipeline, espec
**Why the default native deck has a baseline master, not inferred templates.** `svg_to_pptx.py` keeps the actual blank slide layout relationship from the base package and defaults to `--pptx-structure baseline`. Baseline promotes only low-risk shared structure: the strict-majority identical slide background (every slide must carry an explicit background, and minority slides keep their own overriding fill), plus a common leading prefix of repeated top-level SVG chrome whose exact id tokens say `logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber`, or `slideNumber`. Chrome promotion also requires identical generated OOXML, no slide-timing reference, and the same leading z-order across a strict majority of slides sharing the master; overlay chrome stays slide-local. Minority slides — covers and section pages — keep every shape slide-local and are rebound to a generated `Cover` layout with `showMasterSp="0"`, following the PowerPoint convention that page-type differences live in layouts under one master rather than in extra masters, so promoted chrome never leaks onto them. Image relationships for promoted chrome are copied to the slide master, base-template slide layouts no generated slide references are pruned from the package, and `pageNumber`/`slideNumber` chrome whose text exactly equals the slide's display number (honoring `firstSlideNum`) becomes an auto-updating slide-number field so reordering slides in PowerPoint renumbers pages. This gives ordinary decks real master/layout structure without guessing reusable layouts or placeholders from visual similarity.
-**Why reusable layouts require explicit SVG metadata.** `--pptx-structure template` is the opt-in path for a generated deck that must remain reusable as a PowerPoint template. The final slide SVGs declare a layout key at the root, mark only direct root children as master/layout layers, and attach typed placeholder semantics to the slide-local prototypes that should become layout placeholders. Export validates that shared master and same-key layout declarations are structurally and visually identical, then emits real layout parts and `p:ph` references while leaving every unmarked object slide-local. This is deterministic structure compilation, not visual-template inference. A supplied PPTX whose existing master/theme must survive still belongs to `template-fill-pptx`; `template` mode does not reconstruct an arbitrary source package.
+**Why reusable layouts require explicit SVG metadata.** `--pptx-structure template` is the opt-in path for a generated deck that must remain reusable as a PowerPoint template. The final slide SVGs declare a layout key at the root, mark only direct root children as master/layout layers, and attach typed placeholder semantics to the slide-local prototypes that should become layout placeholders. Export validates that shared master and same-key layout declarations are structurally and visually identical, then emits real layout parts and `p:ph` references while leaving every unmarked object slide-local. This is deterministic structure compilation, not visual-template inference.
+
+**Why imported reusable templates preserve instead of reconstruct.** `pptx_template_import.py` emits a paired `native_structure.json` and `source_template.pptx`. After `create-template` confirms that the source master/layout graph is reusable, `pptx_structure.mode: preserve` uses that package as the base, binds generated pages to exact source layout parts, removes SVG-only previews of inherited layers, and restores source placeholder type/index identities. Existing multiple masters and unused template layouts remain available in PowerPoint's layout picker. Raw PPTX plus one-off generated content still routes to `template-fill-pptx`; preserve mode begins only from a reusable template package.
**Why each SVG references a layout instead of becoming one.** A generated SVG is a complete slide instance: its actual title, body, pictures, tables, and charts must remain selectable in Normal View. `spec_lock.md` therefore separates `pptx_layouts` (the output PowerPoint layout key/name for every page) from `page_layouts` (an optional input SVG design reference). Pages reuse one output key only when their static layout layer and placeholder contract match. The exporter reads `pptx_structure.mode` from the lock when no CLI override is present. Within that hierarchy, ownership follows scope rather than paint type: a direct full-canvas solid rect becomes Master `p:bg` when deck-wide, Layout `p:bg` when page-type-specific, and Slide `p:bg` when explicitly marked for that scope or left unmarked in the background plane. This keeps new slides inheriting the right background without putting content or selectable full-canvas rectangles into layouts.
diff --git a/docs/templates-guide.md b/docs/templates-guide.md
index 4e465a65..534097bc 100644
--- a/docs/templates-guide.md
+++ b/docs/templates-guide.md
@@ -1,6 +1,6 @@
# Templates Guide: Use, Derive, and Boundaries
-A PPT Master "template" is a **structure + style** preset bundle: a set of page layout SVGs (cover / chapter / TOC / content / ending and their variants), a `design_spec.md` design specification, and matching assets (logos, backgrounds, decorative imagery). It is **not** a PowerPoint Slide Master, and **not** just a color palette — it is a reusable page-skeleton bundle the workflow can invoke directly.
+A PPT Master "template" is a **structure + style** preset bundle: a set of page layout SVGs (cover / chapter / TOC / content / ending and their variants), a `design_spec.md` design specification, and matching assets (logos, backgrounds, decorative imagery). When derived from a structured PPTX it may also carry a native master/layout contract and preserved source package; without that pair it remains a reusable SVG page-skeleton bundle.
This guide answers three questions:
@@ -121,7 +121,7 @@ The workflow will then **mandatorily** confirm a template brief with you before
### Step 1 — Prepare reference material
-**Strongly recommended: hand over the original `.pptx` file.** The current PPTX import pipeline achieves near-high-fidelity reconstruction — the workflow uses [`pptx_template_import.py`](../skills/ppt-master/scripts/pptx_template_import.py) to read OOXML directly, extracting theme colors, fonts, per-master themes, master/layout structure, placeholder metadata, and reusable image assets. It emits a layered `svg/` view as the machine-readable template source plus a self-contained `svg-flat/` view for visual preview, then hands the package to Template_Designer which rebuilds clean, maintainable SVGs. Covers, chapter dividers, and decoration-heavy pages all reproduce reliably. This is by far the most dependable derivation path today.
+**Strongly recommended: hand over the original `.pptx` file.** The importer reads OOXML directly, extracts every master/layout and placeholder, and emits both layered SVG references and a paired `native_structure.json` + byte-preserved `source_template.pptx`. When the source structure is reusable, generated pages can bind to its original layouts; when it is minimal, Template_Designer rebuilds a clean master plus semantic layouts from the layered references.
You can also design from scratch from a brand guideline: provide a logo, primary color HEX, fonts, tone description, and a few mood references — the AI will design the page skeletons on the spot. This suits brands that don't yet have a finished PPT, only a VI manual.
@@ -141,6 +141,7 @@ The workflow does not silently infer values — before generation it lists these
| **Theme mode** | Light / dark / gradient / ... |
| **Canvas format** | Default `ppt169` (16:9); specify other formats up front |
| **Replication mode** | `standard` (default 5-page roster) / `fidelity` (one variant per visually distinct cluster from a `.pptx` source — count is driven by the source) / `mirror` (1:1 verbatim copy of every source slide, no abstraction, no placeholders) — `fidelity` and `mirror` both require a `.pptx` reference |
+| **Native structure strategy** | `preserve` when the source master/layout graph is reusable; `template` to rebuild one master plus semantic layouts when it is minimal. `mirror` uses the rebuilt/baseline path because its inherited layers are flattened. |
| **Visual fidelity** | (required for `standard` / `fidelity` when a reference exists) `literal` (reproduce original geometry / decoration / sprite crops as-is) or `adapted` (use reference for tone and structure but allow design evolution). Cover / chapter / ending are usually `literal`. **Not asked for `mirror`** — mirror is implicitly literal |
| **Keywords** | 3–5 tags for index lookup |
| Theme color / design notes / asset list | Optional — can be auto-extracted from the source |
@@ -224,7 +225,7 @@ Don't confuse the two:
Common misconceptions to avoid:
-- **A template is not a PowerPoint Slide Master.** PPT Master outputs native DrawingML shapes and does not depend on the PowerPoint master mechanism. The template is an SVG skeleton, translated to PPTX shapes at export time
+- **A template is not always a Slide Master, but it may carry one.** Ordinary templates remain SVG skeletons. An imported template with `native_structure.json` + `source_template.pptx` preserves the original master/layout/theme package and binds generated content to source placeholders
- **A template is not a "style skin".** It bundles structure (which blocks per page, how information is hierarchized) with style (colors, fonts, decoration). Trying to swap "skin" without structure tends to put the information architecture and the visuals at odds
- **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
diff --git a/docs/zh/faq.md b/docs/zh/faq.md
index 318f4e53..1e88ed04 100644
--- a/docs/zh/faq.md
+++ b/docs/zh/faq.md
@@ -242,7 +242,7 @@ beautify 和主管线的一句话判别:**原来的分页是要保留的信息
**第一步 — 准备参考材料**
-**最推荐的方式是直接给原始 `.pptx` 文件**。当前的 PPTX 导入管线能做到接近高保真还原——PPT Master 会从 PPTX 中提取主题色、字体、母版/版式结构、可复用图片资源(包括精灵图裁剪关系),再用这些素材重建出干净可维护的模板。封面、章节、装饰繁复的页面都能稳定还原,这是目前最靠谱的派生路径。
+**最推荐的方式是直接给原始 `.pptx` 文件**。PPT Master 会提取主题色、字体、全部 master/layout、placeholder type/idx 和可复用图片资源。源结构完整时,模板包会保留原 package 并让生成页引用原版式;源结构薄弱时,再用 layered SVG 重建一个干净的 master + 语义版式体系。
没有源 PPTX 时,截图集也能跑(`cover.png` / `toc.png` / `chapter.png` / `content.png` / `closing.png`),但保真度会明显下降。建议优先找原始 PPTX。
diff --git a/docs/zh/roadmap.md b/docs/zh/roadmap.md
index 4ddcea49..21417836 100644
--- a/docs/zh/roadmap.md
+++ b/docs/zh/roadmap.md
@@ -82,7 +82,7 @@
- **`--native-objects` 从休眠 marker 硬化为可用级 opt-in** — 那条窄「原生对象」例外(见下文 Non-goals)现在导出的图表与纯文本表格会**保留 deck 自己的设计**,不再塌回 PowerPoint 的白底默认主题。classic 原生图表显式写入 chart-area / plot-area / 轴线 / 网格线 / 标签文字颜色——从可见的 SVG fallback 推断(最大面板型 `<rect>` → 背景、fallback 文字 → 标签、fallback 描边 → 轴线/网格),或用 `style` 显式覆盖(`chart_area_fill` / `plot_area_fill` / `text_color` / `axis_color` / `grid_color`,`"none"` 表透明);颜色解析把命名色、`#RGB` 简写、`rgb()` / `rgba()` 归一为 OOXML hex;bar/column 系列关掉负值反色,负值柱保持系列色。激活导出命名为 `<name>_<ts>_native_charts.pptx` 以与默认压平形状导出区分。**默认路线不变**——图表/表格仍以 SVG 派生的 DrawingML 形状导出以保跨渲染器保真;原生对象仍是下文 Non-goals 里那条刻意的 opt-in 取舍
-- **原生 package 结构 + 保守 PPTX 对象回转** — 原生导出现在保留基础 package 的真实空白版式关系,并默认使用 baseline master;只提升完全一致的背景和安全的前置重复 chrome。锁定的 `pptx_structure.mode: template` 会把 SVG 中声明的 master/layout layer 与有类型的 placeholder 编译成可复用 PowerPoint 版式,不做视觉推断;每页通过 `pptx_layouts` 映射,同 key 页面复用同一 contract,全 deck / 页型 / 单页纯色背景分别成为真实 Master/Layout/Slide `p:bg`。用户提供的 PPTX 模板仍走以保留为目标的 `template-fill-pptx` 路线。独立 `pptx_to_svg.py` 导入器会为受支持的未合并表格与 classic-chart cache 输出 fallback SVG 加原生元数据;由本 exporter 生成的规范纯色系列 / 切片与精确 title/subtitle 结构可经第二次 `--native-objects` 导出继续保留,无法等价表达的表格 / 图表语义则保持明确的 fallback-only marker
+- **原生 package 结构 + 保守 PPTX 对象回转** — 原生导出保留真实 master/layout 关系,默认 baseline 只提升安全的共享背景/chrome。锁定的 `template` 模式把显式 SVG master/layout layer 与有类型的 placeholder 编译成可复用版式,不做视觉推断;通过 `create-template` 导入的可复用 PPTX 还可锁定 `preserve`,保留原 master/layout/theme 清单(包括多母版)、把页面绑定到精确源版式并恢复源 placeholder idx。原始 PPTX 的一次性直接填充继续走 `template-fill-pptx`。导入器也会为受支持的未合并表格与 classic-chart cache 输出 fallback SVG 加原生元数据;无法等价表达的语义保持明确的 fallback-only marker
---
@@ -112,11 +112,11 @@
**对应 Issue**:[#53](https://github.com/hugohe3/ppt-master/issues/53)、[#118](https://github.com/hugohe3/ppt-master/issues/118)
-PPT Master 主路线是「AI 从零生成 SVG → DrawingML」,整条管线围绕完全可控的形状/文字/版式构建。「解析既有 PPTX 占位符 + 仅回填文字」是另一种产品形态,需要处理任意来源的母版 / 主题 / 占位符体系,与现有架构发力点正交。
+PPT Master 主路线是「AI 从零生成 SVG → DrawingML」,整条管线围绕完全可控的形状/文字/版式构建。结构完整的 PPTX 现在可以先转成经过确认的可复用模板包,并保留其 master/layout/theme;但「打开任意 PPTX 后不经规范化就盲填所有占位框」仍是另一种产品形态。
**基础诉求其实很简单**:如果只是「固定位置替换 Excel 数据到 PPT 模板」,直接让 AI 写一段 `python-pptx` 脚本即可,几行代码搞定,不需要本项目这套管线。
-> **与 `template-fill-pptx` 路线的区别**:「复用某份 deck **自己的**设计、把新内容回填进去」是已支持的能力(见上「2026-06」),输出仍原生可编辑。这里拒的是另一种形态——解析**任意第三方**模板的母版 / 主题 / 占位符体系并仅做文字替换;两者发力点不同,别混为一谈。
+> **已支持边界**:`template-fill-pptx` 直接回填选中的源页面;`create-template` + `preserve` 先把结构完整的源文件收敛成经过确认的可复用契约,再让新页面引用精确源版式。仍不做的是未经审查、没有契约的任意第三方 placeholder 全自动文字替换。
### 改用原生 PowerPoint 图表(Excel-native chart)
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index 30270ced..c2961e9d 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -429,7 +429,9 @@ PowerPoint 的 DrawingML 是 SVG 表达力的严格子集。Executor 在一份
**为什么默认 native deck 使用基线母版,而不推断模板。** `svg_to_pptx.py` 会保留基础 package 中空白版式的真实关系,并默认使用 `--pptx-structure baseline`。Baseline 只提升低风险共享结构:严格多数页面完全一致的页面背景(每页都必须携带显式背景,少数派页面保留自己的背景并覆盖母版填充),以及位于 shape 序列开头(视觉后层)、且 id 精确 token 为 `logo`、`footer`、`header`、`watermark`、`chrome`、`pageNumber` 或 `slideNumber` 的重复 SVG chrome。Chrome 还必须在共享同一母版的严格多数页面上生成完全一致的 OOXML、没有被页面动画引用,并保持相同的前置 z-order;覆盖在正文之上的 chrome 继续留在 slide 本地。少数派页面(封面、章节页)的全部元素保持 slide-local,并被改绑到生成的 `Cover` 版式(`showMasterSp="0"`)——遵循 PowerPoint 的惯例:页型差异用同一母版下的版式表达而不是增加母版,因此被提升的母版 chrome 绝不会泄漏到这些页面上。被提升 chrome 的图片关系会复制到 slide master,基础模板中没有任何页面引用的 slide layout 也会从 package 中裁剪掉;`pageNumber`/`slideNumber` chrome 的文本若恰好等于该页应显示的页码(尊重 `firstSlideNum`),会转换为自动更新的 PowerPoint 页码字段,此后在 PowerPoint 中调整页序页码自动重算,其他编号方案保持字面文本不动。这样普通 deck 能获得真实的 master/layout 结构,同时不根据视觉相似度猜测可复用版式或占位符。
-**为什么可复用版式必须依赖显式 SVG 元数据。** `--pptx-structure template` 是生成型 deck 需要继续作为 PowerPoint 模板复用时的 opt-in 路径。最终 slide SVG 在根节点声明 layout key,只允许根节点的直接子元素标记 master/layout layer,并在应成为版式占位框的 slide-local 原型上附加类型语义。导出器会验证共享 master 与同 key layout 的声明在结构和视觉上完全一致,再生成真实 layout part 与 `p:ph` 引用;所有未标记对象仍保持 slide-local。这是确定性的结构编译,不是根据视觉相似度猜模板。若用户提供的是必须保留原有 master/theme 的 PPTX,仍应走 `template-fill-pptx`;`template` 模式不会重建任意来源的 package。
+**为什么可复用版式必须依赖显式 SVG 元数据。** `--pptx-structure template` 是生成型 deck 需要继续作为 PowerPoint 模板复用时的 opt-in 路径。最终 slide SVG 在根节点声明 layout key,只允许根节点的直接子元素标记 master/layout layer,并在应成为版式占位框的 slide-local 原型上附加类型语义。导出器会验证共享 master 与同 key layout 的声明在结构和视觉上完全一致,再生成真实 layout part 与 `p:ph` 引用;所有未标记对象仍保持 slide-local。这是确定性的结构编译,不是根据视觉相似度猜模板。
+
+**为什么导入的可复用模板应保留而不是重建。** `pptx_template_import.py` 会配对输出 `native_structure.json` 与 `source_template.pptx`。当 `create-template` 确认源 master/layout 图谱可复用后,`pptx_structure.mode: preserve` 以该 package 为底包,把生成页绑定到精确的源 layout part,移除 SVG 中仅用于预览的继承层副本,并恢复源 placeholder 的 type/idx 身份。源文件已有的多母版和未被示例页引用的版式也会继续保留在 PowerPoint 的版式选择器中。原始 PPTX 加一次性新内容仍走 `template-fill-pptx`;preserve 模式只从完成封装的可复用模板包开始。
**为什么每个 SVG 应引用版式,而不是直接变成版式。** 生成 SVG 是完整的 slide 实例;其中真实标题、正文、图片、表格和图表必须继续能在普通视图中选择。`spec_lock.md` 因而把 `pptx_layouts`(每页最终引用的 PowerPoint layout key/name)与 `page_layouts`(可选的输入 SVG 设计参考)分开。只有静态 layout layer 与 placeholder contract 相同的页面才复用同一个输出 key。没有 CLI 覆盖时,导出器会读取 lock 中的 `pptx_structure.mode`。在这个继承层级里,归属由复用范围而不是填充类型决定:全画布纯色矩形在全 deck 共享时成为 Master `p:bg`,页型共享时成为 Layout `p:bg`,显式标记为 slide 或位于背景层但未标记时成为 Slide `p:bg`。这样新增页面能继承正确背景,同时不会把实际内容或可选中的全屏矩形塞进版式。
diff --git a/docs/zh/templates-architecture.md b/docs/zh/templates-architecture.md
index 01531046..21c789cb 100644
--- a/docs/zh/templates-architecture.md
+++ b/docs/zh/templates-architecture.md
@@ -14,6 +14,8 @@
| **Layout** | `templates/layouts/<id>/` | 仅结构段:canvas / page structure / page types / SVG roster | 不写品牌身份(无 logo、无品牌色硬约束) | `workflows/create-template.md`(layout 分支)|
| **Deck** | `templates/decks/<id>/` | 全段:身份段 + 结构段 + 中间段(template overview) | —— | `workflows/create-template.md`(deck 分支,默认)|
+从结构完整的 PPTX 导入的 Layout/Deck 可以额外携带一对原生结构文件:`native_structure.json` 记录稳定 master/layout key、版式显示名称、父母版和 placeholder type/idx;`source_template.pptx` 保存原 package。两者必须同时存在且 SHA-256 匹配。下游 `pptx_structure.mode: preserve` 会复用源 master/layout/theme;没有这对文件时继续使用现有 `baseline` 或显式 `template` 重建。
+
三者是**三种并列的 reference bundle**,物理目录与 frontmatter `kind` 字段双向对齐:
```yaml
diff --git a/docs/zh/templates-guide.md b/docs/zh/templates-guide.md
index 320b05ad..c5097457 100644
--- a/docs/zh/templates-guide.md
+++ b/docs/zh/templates-guide.md
@@ -1,6 +1,6 @@
# 模板指南:选用、派生与边界
-PPT Master 的"模板"是一份**结构 + 风格**的预设包:包含若干页面布局 SVG(封面/章节/目录/内容/结尾及其变体)、`design_spec.md` 设计规范,以及配套素材(logo、背景、装饰图)。它不是 PPTX 母版,也不是单纯的配色方案——而是一组可被工作流直接复用的页面骨架。
+PPT Master 的"模板"是一份**结构 + 风格**的预设包:包含若干页面布局 SVG(封面/章节/目录/内容/结尾及其变体)、`design_spec.md` 设计规范,以及配套素材(logo、背景、装饰图)。从结构完整的 PPTX 导入时,它还可以携带原生 master/layout 契约和源模板 package;没有这对文件时,它仍是由工作流复用的 SVG 页面骨架。
本文回答三个问题:
@@ -121,7 +121,7 @@ AI 会把这个目录里的 SVG、`design_spec.md` 和素材复制到项目目
### 第一步:准备参考材料
-**强烈推荐:直接给原始 `.pptx` 文件。** 当前的 PPTX 导入管线已经做到接近高保真还原——工作流会用 [`pptx_template_import.py`](../../skills/ppt-master/scripts/pptx_template_import.py) 直接读取 OOXML,提取主题色、字体、每个 master 的主题摘要、母版/版式结构、placeholder 元数据和可复用图片资源。它会输出作为机器事实源的 layered `svg/`,以及用于视觉预览的自包含 `svg-flat/`,再交给 Template_Designer 重建出干净可维护的 SVG。封面、章节、装饰繁复的页面都能稳定还原,这是目前最靠谱的派生路径。
+**强烈推荐:直接给原始 `.pptx` 文件。** 当前的 PPTX 导入管线会用 [`pptx_template_import.py`](../../skills/ppt-master/scripts/pptx_template_import.py) 直接读取 OOXML,提取主题色、字体、全部 master/layout、placeholder 元数据和可复用图片资源,同时输出 `native_structure.json` 与字节保留的 `source_template.pptx`。结构完整时,后续生成页可以直接引用原版式;结构薄弱时,Template_Designer 才会基于 layered `svg/` 重建干净的 master/layout 规范。
也可以基于品牌指南从零设计:提供 logo、主色 HEX、字体、调性描述、几张氛围参考图,AI 会现场设计页面骨架。适合品牌方还没有成型 PPT、只有 VI 手册的场景。
@@ -141,6 +141,7 @@ AI 会把这个目录里的 SVG、`design_spec.md` 和素材复制到项目目
| **主题模式** | 浅色 / 深色 / 渐变…… |
| **画布格式** | 默认 `ppt169`(16:9),其他格式需提前指定 |
| **复刻模式** | `standard`(默认 5 页基本套)/ `fidelity`(按 PPTX 源里"视觉上真正不同"的版式簇各开一个变体——数量由源决定)/ `mirror`(每张源页 1:1 原样复制,零抽象、不插占位符)—— `fidelity` 和 `mirror` 都必须有 `.pptx` 源 |
+| **原生结构策略** | 有完整 master/layout 时推荐 `preserve`(保留原 package);结构薄弱时用 `template`(重建一个 master + 语义版式)。`mirror` 因为继承层已展平,只走重建/基线路线。 |
| **保真级别** | (`standard` / `fidelity` 有源时必填)`literal`(按原样复刻几何/装饰/精灵图裁剪)/ `adapted`(借结构和调性、允许设计演化)。封面 / 章节 / 结尾通常用 `literal`。**`mirror` 模式不询问**——隐含 literal |
| **关键词** | 3–5 个标签,用于索引检索 |
| 主题色 / 设计风格 / 素材清单 | 可选,可让 AI 从源里自动提取 |
@@ -224,7 +225,7 @@ skills/ppt-master/templates/layouts/<your_template_id>/
避免常见误解:
-- **模板 ≠ 母版(Slide Master)**。PPT Master 的输出是原生 DrawingML 形状,不依赖 PowerPoint 母版机制。模板是 SVG 骨架,最终在导出阶段被翻译为 PPTX 形状
+- **模板不一定等于母版,但可以携带母版**。普通模板仍以 SVG 骨架为主;带 `native_structure.json` + `source_template.pptx` 的导入模板会在导出时保留原 master/layout/theme,并把生成内容绑定到原 placeholder
- **模板不是"风格皮肤"**。它包含结构(页面有几块、信息层级如何分布)+ 风格(配色、字体、装饰),两者不可分割。试图只换"皮肤"不换结构,往往会让信息架构和视觉打架
- **模板不会替你做内容决策**。策略师仍然会按内容判断每页用哪个版式、要不要扩展为变体,模板提供候选,不预设结果
- **`fidelity` 模式不等于像素级搬运**。即便是 `literal` 保真,AI 仍会把杂质和不必要的重复结构清理掉——载体保留几何,但不照抄冗余
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index 27653ca6..d6700467 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -25,7 +25,7 @@ description: >
> 5. **NO SPECULATIVE EXECUTION** — "Pre-preparing" content for subsequent Steps is FORBIDDEN (e.g., writing SVG code during the Strategist phase)
> 6. **NO SUB-AGENT SVG GENERATION** — Executor Step 6 SVG generation is context-dependent and MUST be completed by the current main agent end-to-end. Delegating page SVG generation to sub-agents is FORBIDDEN
> 7. **SEQUENTIAL PAGE GENERATION ONLY** — In Executor Step 6, after the global design context is confirmed, SVG pages MUST be generated sequentially page by page in one continuous pass. Grouped page batches (for example, 5 pages at a time) are FORBIDDEN
-> 8. **SPEC_LOCK RE-READ PER PAGE** — Before generating each SVG page, Executor MUST `read_file <project_path>/spec_lock.md`. All colors / fonts / icons / images MUST come from this file — no values from memory or invented on the fly. Executor MUST also look up the current page's `page_rhythm` (`anchor` / `dense` / `breathing`), `page_layouts` (which template SVG to inherit, if any), `page_charts` (which chart template to adapt, if any), and — when `pptx_structure.mode` is `template` — `pptx_layouts` (which native PowerPoint layout the page references). Empty / absent entries are intentional Strategist signals — see executor-base.md §2.1. This rule exists to resist context-compression drift on long decks and to break the uniform "every page is a card grid" default
+> 8. **SPEC_LOCK RE-READ PER PAGE** — Before generating each SVG page, Executor MUST `read_file <project_path>/spec_lock.md`. All colors / fonts / icons / images MUST come from this file — no values from memory or invented on the fly. Executor MUST also look up the current page's `page_rhythm` (`anchor` / `dense` / `breathing`), `page_layouts` (which template SVG to inherit, if any), `page_charts` (which chart template to adapt, if any), and — when `pptx_structure.mode` is `template` or `preserve` — `pptx_layouts` (which native PowerPoint layout the page references). Empty / absent entries are intentional Strategist signals — see executor-base.md §2.1. This rule exists to resist context-compression drift on long decks and to break the uniform "every page is a card grid" default
> 9. **SVG MUST BE HAND-WRITTEN, NOT SCRIPT-GENERATED** — Every SVG page is written by the main agent directly, one page at a time (see rules 6 and 7). Writing or running a Python / Node / shell script that produces the SVG files in batch — looping over pages, templating from data, or emitting them via a generator — is FORBIDDEN, including under "save tokens", "quick draft", or "user is in a hurry" pretexts. The script-generation path was tried on a feature branch and abandoned: cross-page visual consistency depends on per-page authoring with full upstream context, which a generator script cannot reproduce
> 10. **FOLLOW DETERMINISTIC ROUTING RULES** — Do not add blocking routing questions when this skill defines a route. If the user request violates a route precondition, state the required prerequisite and stop that route instead of asking the user to choose around the rule. Ordinary finite options, stylistic preferences, and recoverable details are surfaced with a recommended value plus alternatives at the next existing confirmation gate.
@@ -263,6 +263,8 @@ find <project_path>/templates -type f \( -iname '*.png' -o -iname '*.jpg' -o -in
The same split applies to all three kinds — bitmaps always land in `images/`, the rest in `templates/`. The spec's `kind` field tells Strategist how to read the `templates/` side; downstream code doesn't distinguish. (Template SVGs in `templates/` are reference material only — the rendered pages live in `svg_output/` and reference images via `../images/`.)
+If the selected structure owner ships `native_structure.json` + `source_template.pptx`, keep the pair together in `<project>/templates/`. During fusion, only the winning **structure segment** may contribute this pair: a layout override without a native pair removes a deck's pair, while a brand-only identity override leaves it intact. Never mix one template's contract with another template's source package.
+
#### Multi-path fusion
When the user gives two or more paths of **different kinds**, Step 3 fuses them into a single `<project>/templates/design_spec.md`. **Default granularity is segment-level integer replacement** — entire identity / structure / middle segments are taken from the highest-priority source for that segment, no implicit field-level mixing.
@@ -641,6 +643,9 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
# Output (default-flow mode):
# exports/<project_name>_<timestamp>.pptx ← native pptx (canonical output, reads svg_output/)
# backup/<timestamp>/svg_output/ ← Executor SVG source backup (always written)
+# backup/<timestamp>/templates/{native_structure.json,source_template.pptx}
+# ← preserve mode only
+# backup/<timestamp>/spec_lock.md ← preserve mode only
#
# Add --svg-snapshot to additionally emit the SVG-image preview pptx alongside the native pptx:
# exports/<project_name>_<timestamp>_svg.pptx ← SVG preview pptx (reads svg_final/)
@@ -664,7 +669,9 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> The `svg_output/`
> snapshot in `backup/<timestamp>/` is always written so the project can be
> re-exported from frozen SVG sources without re-running the LLM. The SVG-rendered
-> preview pptx is opt-in via `--svg-snapshot` — live preview already provides the
+> preview pptx is opt-in via `--svg-snapshot`. Preserve mode also backs up the
+> paired native structure/source files and `spec_lock.md` under the same timestamp.
+> Live preview already provides the
> SVG visual reference, so it's only needed when you want a self-contained file
> to share. Pass `-s output` or `-s final` to force a single source if you need it.
@@ -692,6 +699,17 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> `--pptx-structure flat` only for debugging/comparison when all generated
> backgrounds and chrome must remain slide-local.
+> **Preserved source-template export** — a reusable template package created
+> from a structured PPTX may ship `native_structure.json` plus
+> `source_template.pptx`. Set `pptx_structure.mode: preserve`, add project-relative
+> `source_template` / `native_structure` rows, and map every page in
+> `pptx_layouts` to an exact imported layout key/name. Native export verifies the
+> source SHA-256 and package parts, creates the generated slides against the
+> original layouts (including multiple source masters), removes SVG-only preview
+> copies of inherited master/layout visuals, and binds slide content to the
+> original placeholder type/index. Preserve mode keeps the source layout picker
+> roster; it does not prune unused source layouts.
+
> **Explicit reusable template export** — set `spec_lock.md`
> `pptx_structure.mode: template` (or pass `--pptx-structure template`
> explicitly) only when every SVG root declares `data-pptx-layout` and direct children
@@ -704,8 +722,9 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> example live in
> [`references/shared-standards.md`](references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export).
> Raw PPTX templates still route to `template-fill-pptx`; `template` structure
-> mode is for explicitly annotated SVG authoring, not source-package
-> preservation. In template mode, `pptx_layouts` contains exactly one locked
+> mode is for explicitly annotated SVG authoring. Source-package preservation is
+> available only after `create-template` has produced the reusable native pair.
+> In template mode, `pptx_layouts` contains exactly one locked
> layout key/name per page; reuse a key for a shared structure instead of
> creating one key per content instance.
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index b9a31ab5..65c3b12e 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -13,6 +13,7 @@
| Source list | Read path |
|---|---|
| Chosen template's `design_spec.md` (read frontmatter to detect `replication_mode`) | `templates/design_spec.md` |
+| Preserve-mode native layout/placeholder contract | `templates/native_structure.json` |
| Every distinct `<basename>` in `spec_lock.md page_layouts` | `templates/<basename>.svg` |
| Every distinct chart name in `spec_lock.md page_charts` | `templates/charts/<chart_name>.svg` |
| Chart types in `design_spec.md §VII` not covered above | `templates/charts/<chart_name>.svg` |
@@ -99,13 +100,16 @@ Before generating each page, output which template is used:
|---|---|
| `baseline` or missing | Author ordinary SVG pages. Do not add explicit PPTX structure metadata merely because a page uses a visual template. |
| `template` | Every generated SVG MUST implement the matching `pptx_layouts` row and the explicit structure contract below. |
+| `preserve` | Every generated SVG MUST use the locked source layout key/name. Keep inherited master/layout visuals as marked preview layers; export removes the previews and reuses the original source package parts. |
-**Hard rule — every template-mode page references one layout**: Read `P<NN>: <layout_key> | <layout name>` from `pptx_layouts`, then put both values on the root SVG as `data-pptx-layout` and `data-pptx-layout-name`. Do not invent, rename, or omit a key.
+**Hard rule — every structured page references one layout**: In `template` or `preserve` mode, read `P<NN>: <layout_key> | <layout name>` from `pptx_layouts`, then put both values on the root SVG as `data-pptx-layout` and `data-pptx-layout-name`. Do not invent, rename, or omit a key.
**Hard rule — PowerPoint paint order**: Direct visual children appear in this order: Master background, Layout background, optional Slide background, shared Master shapes, same-key Layout shapes, then slide-local content/placeholders. Backgrounds are the special plane beneath all inherited shapes. Repeat the same Master contract on every page and the same Layout contract on every page sharing a key.
**Placeholder ownership**: Keep actual title/body/picture/chart/table/footer/slide-number content on the Slide and add the matching `data-pptx-placeholder`. Do not move actual content into a Layout. Chart/table placeholders require native markers and a later `--native-objects` export.
+**Preserve-mode source identity**: Copy `data-pptx-placeholder-idx` from the chosen template SVG/native contract whenever the source placeholder has an index. Preserve the source placeholder type/idx pairing; do not assign a convenient new index. Master/layout elements in the SVG are preview copies only and MUST retain `data-pptx-layer` + `data-pptx-editable="false"`; never flatten them into unmarked slide-local content.
+
**Background ownership**:
| Scope | SVG authoring |
@@ -179,7 +183,7 @@ Do **not** invent a layout entry, and do **not** assume a template just because
**Per-page PowerPoint layout lookup — `pptx_layouts` section**:
-- `pptx_structure.mode: template` → a `P<NN>` row is mandatory; apply §1.2 to the root and direct children.
+- `pptx_structure.mode: template` or `preserve` → a `P<NN>` row is mandatory; apply §1.2 to the root and direct children. Preserve mode uses the exact source key/name and placeholder indices.
- `pptx_structure.mode: baseline` or missing → omit explicit PPTX structure metadata; baseline export owns conservative promotion.
- A layout key may repeat across non-adjacent pages. Reuse is based on identical static/placeholder contracts, not page proximity or content wording.
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 1b91cf48..49d370ba 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -949,6 +949,7 @@ spec lock; the SVG metadata remains the exporter source of truth.
| `data-pptx-layer="slide"` | direct full-canvas solid `<rect>` only | Writes a one-page override as Slide `p:bg` |
| `data-pptx-placeholder="..."` | direct visual child | Keeps actual content on the slide and maps it to a generated layout placeholder |
| `data-pptx-placeholder-bounds="x y width height"` | placeholder element | Overrides the reusable placeholder frame in SVG user units |
+| `data-pptx-placeholder-idx="1"` | placeholder element | Retains an imported source layout placeholder index; optional for reconstructed layouts |
| `data-pptx-editable="false"` | master/layout element or slide background | Declares intentional editing outside ordinary slide content |
**Hard rule — explicit only**: Template export never promotes visually similar
@@ -996,6 +997,23 @@ master or layout background.
`--native-objects`; fallback groups contain several shapes and cannot map to one
PowerPoint placeholder.
+### Preserved Source Master / Layout Contract
+
+**Trigger**: A reusable template package ships `native_structure.json` and `source_template.pptx`, and `spec_lock.md` sets `pptx_structure.mode: preserve` with project-relative paths to both files.
+
+| Artifact | Authority |
+|---|---|
+| `source_template.pptx` | Original master/layout/theme/package parts |
+| `native_structure.json` | Stable layout keys, picker names, parent masters, placeholder types/indices, source SHA-256 |
+| `pptx_layouts` | Per-generated-page source layout selection |
+| SVG metadata | Standalone preview layers and slide-content placeholder binding |
+
+**Hard rule — source package wins**: Mark source master/layout visuals as direct `data-pptx-layer="master|layout"` preview children. Preserve export removes those generated copies and renders the original source parts. Unmarked content stays slide-local.
+
+**Placeholder identity**: Keep actual content on the slide. Copy the source placeholder index into `data-pptx-placeholder-idx` when present; the exporter restores the source placeholder type/idx pair. Multiple placeholders with the same semantic role require explicit indices.
+
+**Multi-master boundary**: Preserve every source master already present in the package. Do not synthesize a new master merely for cover/section differences; rebuilt templates continue to prefer one master plus semantic layouts.
+
```xml
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 1280 720"
diff --git a/skills/ppt-master/references/strategist.md b/skills/ppt-master/references/strategist.md
index 97bfb84f..a7326c3c 100644
--- a/skills/ppt-master/references/strategist.md
+++ b/skills/ppt-master/references/strategist.md
@@ -100,6 +100,8 @@ Write the locked value to `spec_lock.md` `- visual_style:` and the rationale to
> **Template vs preset**: a style mention may sound like a template name ("academic style" vs the `academic_defense/` template directory). Step 3 only triggers on an explicit template directory path supplied by the user — bare names and style words never copy templates; they map to a visual-style preset here. If a template was triggered upstream, its files are already in `<project_path>/templates/` and its fused design_spec governs.
+**Native template contract**: When `<project_path>/templates/native_structure.json` exists, read it before assigning page layouts. It is the factual source for PowerPoint layout keys/names, parent masters, and placeholder identities; the template SVG roster remains the visual/content-fit source.
+
**Downstream effect**: e / f / g / h realize the locked mode + visual style. Example: `showcase` + `dark-tech` → e applies one luminous accent on a dark field; g pairs a clean sans with mono; f minimal glow icons; h the `digital-dashboard` rendering.
### e. Color Scheme Recommendation
@@ -839,8 +841,8 @@ This is what makes the axis meaningful: a `presentation` deck and a `text` deck
- **Cover impact is mandatory**: Page `P01` is the deck's first visual contract, not a generic title slide. In `design_spec.md §IX`, add a `Cover impact` line for `P01` that names one concrete hook and one concrete composition strategy. Use the source's strongest available signal: a provocative core claim, object / scene metaphor, hero number, founder / product / audience moment, or a distilled conflict. Pair it with one concrete composition strategy — such as `full-bleed image + floating title`, `typographic poster`, `hero object`, `data hook`, `editorial scene`, `high-contrast abstract geometry`, or a fresh composition the deck's subject suggests (these are starting points, not the allowed set). If no external or AI image is available, still specify a native-SVG visual hook; do not fall back to "title + subtitle + decorative background". (Beautify / template-fill keep the source cover verbatim — this rule does not apply on those preservation paths.)
- **Cover rhythm lock**: `P01` remains `anchor` in `spec_lock.md page_rhythm`, but its §IX `Cover impact` must prevent content-page patterns. Do not plan multi-card grids, agenda-like bullets, or equal-weight columns on the cover unless a template explicitly requires that structure, or a preservation path (beautify / template-fill) is transcribing the source cover verbatim.
- **Closing impact (only when the deck closes)**: the deck's last page is its final visual contract — the strongest impression after the cover. When the deck genuinely lands on a conclusion / call-to-action / final-takeaway page, give it a `Closing impact` line in §IX: name the one thing the audience should leave with (a distilled takeaway, a forward call, a memorable restatement of the core claim) + one composition that delivers it — never a generic "Thank you" / contact-only slide or a centered-title reprise of the cover. **Do NOT invent a closing page to satisfy this** — the filler-page ban above still holds; apply it only to the page where the deck actually resolves. Same exemptions as the cover: skip on template / beautify / template-fill preservation paths.
- - **pptx_structure is mandatory**: Write `mode: baseline` by default. Use `mode: template` only when the user explicitly requests a reusable PowerPoint Master/Layout/Placeholder deliverable. Do not choose `flat`; it is a CLI-only diagnostic override.
- - **pptx_layouts (template structure only)**: When `pptx_structure.mode` is `template`, write one `P<NN>: <layout_key> | <PowerPoint layout name>` row for every page. Reuse a layout key when pages share the same static layout layer and placeholder contract; page content differences do not justify new keys. One-off cover/section layouts are valid. Omit the whole section in baseline mode.
+ - **pptx_structure is mandatory**: Write `mode: baseline` by default. Use `mode: preserve` when the selected template structure segment ships both `templates/native_structure.json` and `templates/source_template.pptx`; add project-relative `source_template` and `native_structure` rows exactly as shown in `spec_lock_reference.md`. Use `mode: template` only when the user explicitly requests a reusable PowerPoint Master/Layout/Placeholder deliverable and no preserved native pair owns the structure. Do not choose `flat`; it is a CLI-only diagnostic override.
+ - **pptx_layouts (template/preserve structure)**: When `pptx_structure.mode` is `template` or `preserve`, write one `P<NN>: <layout_key> | <PowerPoint layout name>` row for every page. In preserve mode, take the exact key/name from the chosen template SVG root and verify it exists in `native_structure.json`; never rename source layouts. In template mode, reuse a layout key when pages share the same static layout layer and placeholder contract; page content differences do not justify new keys. One-off cover/section layouts are valid. Omit the whole section in baseline mode.
- **page_layouts (write only when a template is in use)**: For each page that inherits a template SVG, add `P<NN>: <svg_basename>` (e.g., `P04: 03a_content_image_text`). Pages designed freely get **no entry** — Executor reads the absence as "free design, no inheritance". If zero pages use a template, omit the section entirely.
- **page_charts (write only for chart pages that match a catalog template)**: For each page in `design_spec.md §VII` whose `reference template path` points to `templates/charts/<name>.svg`, add `P<NN>: <chart_name>`. Pages with `no-template-match` in §VII MUST NOT appear here (Executor would look for a non-existent reference). If the deck has no data-visualization pages, omit the section.
- **Hard rule**: Use both `page_layouts` and `page_charts` for the same page only when the layout template is a compatible shell for the chart. Do not pair chart pages with conflicting page layouts (e.g., `waterfall_chart` + timeline layout, KPI cards + circle-diagram layout). If no compatible layout exists, omit the page from `page_layouts`.
diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.md
index 5175b899..54725414 100644
--- a/skills/ppt-master/references/template-designer.md
+++ b/skills/ppt-master/references/template-designer.md
@@ -18,6 +18,8 @@ When the workflow provides a PPTX reference source, the effective input package
- finalized template brief
- `manifest.json` — single source of truth (slide size, theme, per-master themes, assets, asset map, placeholders, layouts, masters, slides, SVG file paths, page-type candidates)
+- `native_structure.json` — stable source master/layout keys, picker names, parent-master relationships, placeholder type/index/geometry, source hash, and preserve-vs-rebuild recommendation
+- `source_template.pptx` — byte-preserved source package paired with `native_structure.json`
- `summary.md` — short orientation digest derived from manifest.json
- exported `assets/`
- `svg/master_*.svg` / `svg/layout_*.svg` — every master / layout in the deck rendered once as standalone SVG, including ones no sample slide references (template packages often ship more design surfaces than the embedded samples exercise)
@@ -35,12 +37,22 @@ PPTX import interpretation:
Input priority for PPTX-backed template creation:
1. `manifest.json` for all factual metadata (theme, assets, unique layout/master structure, slide reuse, page-type guidance)
-2. `svg/master_*.svg` + `svg/layout_*.svg` — the **primary source for the deck's shared visual language**: backgrounds, page chrome, decorative bars, recurring brand motifs. These are what the new template's fixed structure should adopt or reinterpret. Read these before any slide SVG.
-3. `svg/inheritance.json` for confirming which slide uses which layout / master
-4. exported `assets/` for reusable visual resources
-5. `svg/slide_NN.svg` — each slide's unique content, useful for judging composition rhythm and content density (not for fixed structure)
-6. `summary.md` only as a fast scan; never as the canonical fact source
-7. screenshots / original PPTX only for style verification
+2. `native_structure.json` for native PowerPoint identities, source placeholder indices, relationship completeness, and the confirmed structure strategy
+3. `svg/master_*.svg` + `svg/layout_*.svg` — the **primary source for the deck's shared visual language**: backgrounds, page chrome, decorative bars, recurring brand motifs. These are what the new template's fixed structure should adopt or reinterpret. Read these before any slide SVG.
+4. `svg/inheritance.json` for confirming which slide uses which layout / master
+5. exported `assets/` for reusable visual resources
+6. `svg/slide_NN.svg` — each slide's unique content, useful for judging composition rhythm and content density (not for fixed structure)
+7. `summary.md` only as a fast scan; never as the canonical fact source
+8. screenshots / original PPTX only for style verification
+
+**Native structure strategy**:
+
+| Confirmed value | Output behavior |
+|---|---|
+| `preserve` | Copy `native_structure.json` and `source_template.pptx` unchanged. Bind every template SVG to one source layout key/name and source placeholder identities. |
+| `template` | Do not ship the source pair. Reconstruct one master plus semantic layouts through explicit SVG structure metadata. |
+
+Mirror replication cannot use `preserve`: flat SVGs no longer identify which pixels belong to the source master/layout.
---
@@ -138,6 +150,10 @@ source_canvas_width: 1280
source_canvas_height: 720
source_viewbox: "0 0 1280 720"
replication_mode: standard | fidelity | mirror
+# Type-A preserve strategy only; omit these rows for rebuilt templates.
+# native_structure_mode: preserve
+# native_structure: native_structure.json
+# source_template: source_template.pptx
# Optional — only when this template overrides canonical placeholder vocabulary.
# Omit entirely for `mirror` mode (mirror has no placeholders).
# placeholders:
@@ -166,7 +182,7 @@ replication_mode: standard | fidelity | mirror
- 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 content slot). For `fidelity` mode, also note the cluster source and visual differentiator. For `mirror` mode the roster is the **load-bearing artifact** — Strategist picks pages from these descriptions, so each row must include enough detail to distinguish it from siblings (column count, hero element, content density, what kind of content slot it fits — "three-column KPI grid with large numbers, suits quarterly summary"). Roster entries must match the actual SVG files on disk.
+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 content slot). For a preserved template, also record the source native layout key and PowerPoint picker name. For `fidelity` mode, note the cluster source and visual differentiator. For `mirror` mode the roster is the **load-bearing artifact** — Strategist picks pages from these descriptions, so each row must include enough detail to distinguish it from siblings (column count, hero element, content density, what kind of content slot it fits — "three-column KPI grid with large numbers, suits quarterly summary"). Roster entries must match the actual SVG files on disk.
## VI. Assets (omit when none)
Logos, cover backgrounds, brand textures bundled with the template package — file name, dimensions, intended usage.
@@ -215,6 +231,8 @@ If PPTX import output exists:
The imported PPTX is a **reference source**, not a direct conversion target.
+> Preserve exception: `source_template.pptx` is the native package retention target. Keep it byte-identical; only the companion SVG authoring references are simplified.
+
Do:
- preserve brand assets, recurring backgrounds, and stable structural motifs
- rebuild the layout into a clean SVG structure aligned with PPT Master constraints
@@ -229,6 +247,17 @@ Do not:
- mirror PPT-specific complexity when it makes the resulting SVG brittle or hard to edit
- introduce dense low-value vector detail that does not materially improve template reuse
+**Preserve-mode SVG contract**:
+
+| Source fact | Template SVG declaration |
+|---|---|
+| Chosen source layout | Root `data-pptx-layout` + exact `data-pptx-layout-name` |
+| Source master/layout visual | Direct preview child with `data-pptx-layer="master|layout"` and `data-pptx-editable="false"` |
+| Source placeholder | Direct content child with `data-pptx-placeholder`; add exact `data-pptx-placeholder-idx` when the source placeholder has an index |
+| Page-only background | Direct full-canvas solid rect with `data-pptx-layer="slide"` |
+
+Repeat inherited visuals in the standalone SVG so browser preview remains complete. Preserve export removes those preview copies and renders the original source master/layout parts instead. Do not flatten inherited visuals into unmarked slide content.
+
### 3. Placeholder Markers
> **Mirror mode skips this section entirely.** Mirror SVGs are verbatim copies of the source flat slides — they carry no `{{}}` markers. Mirror is only a template-creation mode; downstream generation treats the finished files as normal template roster candidates. The rest of this section applies to `standard` and `fidelity` only.
@@ -330,6 +359,20 @@ templates/<kind_dir>/<template_name>/
└── *.png / *.jpg
```
+Preserve-mode standard/fidelity packages add the native pair:
+
+```
+templates/<kind_dir>/<template_name>/
+├── design_spec.md
+├── native_structure.json
+├── source_template.pptx
+├── 01_cover.svg
+├── 03a_content_two_col.svg
+└── ...
+```
+
+Do not add the pair to mirror packages or rebuilt templates.
+
Mirror mode emits one SVG per source slide, named by source order:
```
@@ -357,6 +400,7 @@ If the template is based on PPTX import output, briefly note:
- which extracted assets were reused directly
- which complex original decorations were intentionally simplified
- whether any page-type mapping required judgment beyond the import heuristic
+- whether native structure was preserved or rebuilt; for preserve, list the retained master/layout counts
---
@@ -364,7 +408,7 @@ If the template is based on PPTX import output, briefly note:
If suitable template resources already exist, use them directly instead of generating new ones:
-1. **Copy template**: copy the spec + template SVGs into the project's `templates/`, and any bundled bitmaps into the project's `images/` (the runtime image pool, referenced as `../images/`)
+1. **Copy template**: copy the spec + template SVGs and optional native structure pair into the project's `templates/`, and any bundled bitmaps into the project's `images/` (the runtime image pool, referenced as `../images/`)
2. **Adjust colors**: Modify colors per the project design spec
3. **Customize**: Make project-specific adjustments
@@ -398,5 +442,6 @@ templates/
- [x] Naming convention applied (standard / fidelity: letter-suffix variants; mirror: `<NNN>_<page_type>.svg`)
- [x] Templates follow design spec (colors, fonts, layout)
- [x] Placeholder markers are clear and standardized (standard / fidelity); mirror SVGs contain **no** `{{}}` markers
+- [x] Native structure strategy applied: preserve pair + source bindings, or explicit rebuilt structure
- [ ] **Next step**: Validate assets and register the template via `register_template.py <id> --kind <deck|layout>`
```
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 9a3d8f78..f2e7b6bd 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -120,6 +120,8 @@ When `spec_lock.md` has no `pptx_structure` section, native `svg_to_pptx.py` fal
Use template structure only when the final slide SVGs explicitly declare reusable PowerPoint structure. The CLI reads `spec_lock.md` `pptx_structure.mode` when `--pptx-structure` is omitted, so a locked `template` project exports structurally through the standard command; an explicit CLI value still overrides the lock. Each SVG names its layout with `data-pptx-layout`; direct root children may opt into master/layout layers with `data-pptx-layer`, and supported text, picture, chart, table, footer, or slide-number elements may declare `data-pptx-placeholder`. The exporter validates the project-level `pptx_layouts` mapping and cross-slide consistency, creates one reusable layout per layout key, and keeps actual content slide-local. A direct full-canvas solid rect becomes a real Master/Layout/Slide `p:bg` according to its declared scope; an unmarked full-canvas solid rect is a Slide override. It never infers placeholders from visual similarity. The complete metadata contract lives in [`references/shared-standards.md`](../references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export).
+Use preserved structure when `create-template` produced `native_structure.json` plus `source_template.pptx`. Lock `pptx_structure.mode: preserve`, point the lock at both project-relative files, and map every page to an exact imported layout key/name. The exporter verifies the source hash and package parts, keeps the source master/layout/theme roster (including multiple source masters), removes SVG preview copies of inherited layers, and binds generated slide content back to source placeholder indices. Preserve mode does not prune unused source layouts.
+
`pptx_to_svg.py` annotates supported unmerged tables and conservative classic-chart caches with `data-pptx-native` metadata. Source table-style inheritance, supported solid cell fills/basic text formatting, chart title/legend/axis titles, and plot-level data-label flags for area/bar/column/line charts are retained when the current schema can represent them. Tables with direct borders, non-solid fills, or mixed rich-text formatting remain fallback-only, as do charts with unsupported label scopes/types, custom axis semantics, trendlines/error bars, or subtype options. Unsupported tables keep their rendered SVG table; unsupported charts keep a baked preview or explicit placeholder. Both carry `data-pptx-native-status`, which `svg_quality_checker.py` and `svg_to_pptx.py --native-objects` report as a warning.
Exporter-canonical classic charts also recover canonical solid series/slice
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index c867b9fb..3756a81b 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -32,6 +32,7 @@ Convert project SVGs into PPTX.
python3 scripts/svg_to_pptx.py <project_path>
python3 scripts/svg_to_pptx.py <project_path> --native-objects
python3 scripts/svg_to_pptx.py <project_path> --pptx-structure template # explicit SVG template metadata
+python3 scripts/svg_to_pptx.py <project_path> --pptx-structure preserve # imported source package contract
python3 scripts/svg_to_pptx.py <project_path> --pptx-structure flat # structure diagnostic
# Template-import visual round-trip diagnostic only:
python3 scripts/svg_to_pptx.py <template_import_output> --only native -s svg-flat
@@ -62,6 +63,7 @@ Behavior:
- For PPTX template-import workspaces, use `-s svg-flat` when you need a visual round-trip check. The layered `svg/` tree is the machine-readable template source and intentionally does not inline inherited master / layout decoration into each slide.
- Native mode is strict about unsupported visual SVG elements: if a visual element cannot be represented or safely preserved, export fails with the SVG file, element tag, and position instead of silently dropping content.
- Omitting `--pptx-structure` reads `spec_lock.md` `pptx_structure.mode`, then falls back to `baseline`; an explicit CLI value overrides the lock. Template mode builds reusable PowerPoint layouts only from explicit SVG metadata: root `data-pptx-layout`, direct-child `data-pptx-layer="master|layout"`, optional `data-pptx-layer="slide"` on a full-canvas solid background, and direct-child `data-pptx-placeholder`. It validates the per-page `pptx_layouts` lock plus cross-slide structure consistency and never infers layouts from visual similarity. Direct full-canvas solid rects compile to Master/Layout/Slide `p:bg` by scope; an unmarked one is a Slide override. Chart/table placeholders also require `--native-objects`. Full contract: [`shared-standards.md`](../../references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export).
+- Preserve mode requires a `create-template` native pair (`native_structure.json` + `source_template.pptx`) declared in `spec_lock.md`. It verifies the source digest, binds each generated page to an imported layout part, retains the source master/layout/theme roster, removes preview-only inherited SVG layers, and restores source placeholder type/index identities. The SVG root still declares `data-pptx-layout`; repeated semantic placeholders may disambiguate with `data-pptx-placeholder-idx`.
- Native output uses content-hash media filenames, so identical images are reused and different images cannot overwrite each other by sharing a basename.
- `[Content_Types].xml` is generated from the actual media extensions written into the PPTX. Unknown media extensions fail unless Python's `mimetypes` can identify them.
- Native export writes to a temporary file first and publishes the requested PPTX only after conversion succeeds. A failed conversion does not replace the main output file.
diff --git a/skills/ppt-master/scripts/pptx_template_import.py b/skills/ppt-master/scripts/pptx_template_import.py
index 59d9295d..6e40efc5 100644
--- a/skills/ppt-master/scripts/pptx_template_import.py
+++ b/skills/ppt-master/scripts/pptx_template_import.py
@@ -5,6 +5,8 @@ Reads OOXML directly via `pptx_to_svg` and writes a reusable reference workspace
- `manifest.json` — single source of truth for slide size, theme colors, fonts,
asset inventory, and per-slide / per-layout / per-master metadata
+- `native_structure.json` + `source_template.pptx` — portable source-package
+ contract for preserving native masters, layouts, themes, and placeholders
- `summary.md` — short human-readable digest derived from manifest.json
- `assets/` — extracted reusable image assets
- `svg/` — primary view: by default the layered template view (every master
@@ -24,6 +26,7 @@ from pathlib import Path
from console_encoding import configure_utf8_stdio
from template_import.manifest import build_manifest
+from template_import.native_structure import write_native_structure_bundle
configure_utf8_stdio()
@@ -42,14 +45,17 @@ def parse_args() -> argparse.Namespace:
parser.add_argument(
"--skip-manifest",
action="store_true",
- help="Skip PPTX metadata extraction and asset inventory generation",
+ help=(
+ "Skip metadata, asset inventory, native structure contract, and "
+ "preserved source-package generation"
+ ),
)
parser.add_argument(
"--manifest-only",
action="store_true",
help=(
- "Only extract manifest.json + summary.md + reusable assets, "
- "without exporting slides to SVG"
+ "Only extract manifest.json + summary.md + reusable assets + the "
+ "native structure/source pair, without exporting slides to SVG"
),
)
parser.add_argument(
@@ -98,6 +104,7 @@ def main() -> int:
return 1
manifest = None
+ native_structure = None
manifest_path = output_dir / "manifest.json"
if not args.skip_manifest:
try:
@@ -110,12 +117,27 @@ def main() -> int:
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
+ try:
+ native_structure = write_native_structure_bundle(
+ pptx_path,
+ output_dir,
+ manifest,
+ )
+ except (OSError, ValueError) as exc:
+ print(f"Error: failed to write native structure bundle: {exc}")
+ return 1
if args.manifest_only:
print(f"Imported PPTX template source: {pptx_path.name}")
print(f"Output directory: {output_dir}")
if manifest is not None:
print(f"Manifest: {manifest_path.name}")
+ print("Native structure: native_structure.json")
+ print("Preserved source package: source_template.pptx")
+ print(
+ "Recommended structure mode: "
+ f"{native_structure['strategy']['recommendedMode']}"
+ )
print("Summary: summary.md")
print(f"Assets exported: {len(manifest['assets']['allAssets'])}")
print(f"Common assets: {len(manifest['assets']['commonAssets'])}")
@@ -147,6 +169,11 @@ def main() -> int:
print(f"Flat companion slides: {len(result.flat_slides)} (svg-flat/)")
print(f"SVG bytes (primary): {total_bytes}")
print(f"Output directory: {output_dir}")
+ if native_structure is not None:
+ print(
+ "Native structure: "
+ f"{native_structure['strategy']['recommendedMode']} recommended"
+ )
return 0
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index c8748f6a..fe02b1af 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -76,14 +76,24 @@ except ImportError:
try:
from svg_to_pptx.pptx_package.template_structure import (
TemplateStructureError as _TemplateStructureError,
+ PptxLayoutReference as _PptxLayoutReference,
+ PptxStructureLock as _PptxStructureLock,
+ load_native_structure_contract as _load_native_structure_contract,
load_pptx_structure_lock as _load_pptx_structure_lock,
+ native_structure_lock_errors as _native_structure_lock_errors,
+ parse_preserve_slides as _parse_preserve_structure_slides,
parse_template_slides as _parse_template_structure_slides,
template_lock_errors as _template_lock_errors,
validate_template_svg as _validate_template_structure_svg,
)
except ImportError:
_TemplateStructureError = None
+ _PptxLayoutReference = None
+ _PptxStructureLock = None
+ _load_native_structure_contract = None
_load_pptx_structure_lock = None
+ _native_structure_lock_errors = None
+ _parse_preserve_structure_slides = None
_parse_template_structure_slides = None
_template_lock_errors = None
_validate_template_structure_svg = None
@@ -1029,6 +1039,7 @@ class SVGQualityChecker:
'data-pptx-layout-name',
'data-pptx-placeholder',
'data-pptx-placeholder-bounds',
+ 'data-pptx-placeholder-idx',
'data-pptx-editable',
}
if not any(
@@ -1459,6 +1470,7 @@ class SVGQualityChecker:
'data-pptx-layout-name',
'data-pptx-placeholder',
'data-pptx-placeholder-bounds',
+ 'data-pptx-placeholder-idx',
'data-pptx-editable',
}
has_metadata = False
@@ -1474,21 +1486,51 @@ class SVGQualityChecker:
):
has_metadata = True
break
- template_locked = structure_lock is not None and structure_lock.mode == 'template'
- if not has_metadata and not template_locked:
+ locked_mode = structure_lock.mode if structure_lock is not None else None
+ structure_locked = locked_mode in {'template', 'preserve'}
+ if not has_metadata and not structure_locked:
return
try:
- specs = _parse_template_structure_slides(svg_files)
+ if locked_mode == 'preserve':
+ if _parse_preserve_structure_slides is None:
+ return
+ specs = _parse_preserve_structure_slides(svg_files)
+ else:
+ specs = _parse_template_structure_slides(svg_files)
except _TemplateStructureError as exc:
self._pptx_structure_issues.append(('error', str(exc)))
return
- if not template_locked:
+ if not structure_locked:
return
self._pptx_structure_issues.extend(
('error', message)
for message in _template_lock_errors(specs, structure_lock)
)
+ if locked_mode != 'preserve':
+ return
+ if (
+ _load_native_structure_contract is None
+ or _native_structure_lock_errors is None
+ ):
+ self._pptx_structure_issues.append((
+ 'error',
+ 'Preserve mode validator could not load the native structure contract.',
+ ))
+ return
+ try:
+ contract = _load_native_structure_contract(structure_lock)
+ except _TemplateStructureError as exc:
+ self._pptx_structure_issues.append(('error', str(exc)))
+ return
+ self._pptx_structure_issues.extend(
+ ('error', message)
+ for message in _native_structure_lock_errors(
+ specs,
+ structure_lock,
+ contract,
+ )
+ )
def _check_illustration_resource_contract(self, dir_path: Path) -> None:
"""Project-level illustration resource checks."""
@@ -1892,6 +1934,88 @@ class SVGQualityChecker:
Issues are aggregated and printed in :py:meth:`print_summary` so the
per-file report stays focused on intrinsic SVG validity.
"""
+ native_contract_path = dir_path / 'native_structure.json'
+ source_template_path = dir_path / 'source_template.pptx'
+ native_contract = None
+ if native_contract_path.exists() != source_template_path.exists():
+ self._template_issues.append((
+ 'error',
+ 'native_structure_pair',
+ "native_structure.json and source_template.pptx must be shipped together",
+ ))
+ elif native_contract_path.exists():
+ if (
+ _PptxStructureLock is None
+ or _load_native_structure_contract is None
+ or _TemplateStructureError is None
+ ):
+ self._template_issues.append((
+ 'error',
+ 'native_structure_validator',
+ "native structure validator is unavailable",
+ ))
+ else:
+ try:
+ native_contract = _load_native_structure_contract(_PptxStructureLock(
+ mode='preserve',
+ source_template=source_template_path,
+ native_structure=native_contract_path,
+ ))
+ except _TemplateStructureError as exc:
+ self._template_issues.append((
+ 'error',
+ 'native_structure_invalid',
+ str(exc),
+ ))
+ if (
+ native_contract is not None
+ and _PptxLayoutReference is not None
+ and _parse_preserve_structure_slides is not None
+ and _template_lock_errors is not None
+ and _native_structure_lock_errors is not None
+ ):
+ try:
+ native_specs = _parse_preserve_structure_slides(svg_files)
+ native_layouts = {
+ layout.key: layout for layout in native_contract.layouts
+ }
+ references = tuple(
+ _PptxLayoutReference(
+ slide_num=spec.slide_num,
+ layout_key=spec.layout_key,
+ layout_name=(
+ native_layouts[spec.layout_key].name
+ if spec.layout_key in native_layouts
+ else spec.layout_name
+ ),
+ )
+ for spec in native_specs
+ )
+ native_lock = _PptxStructureLock(
+ mode='preserve',
+ layouts=references,
+ source_template=source_template_path,
+ native_structure=native_contract_path,
+ )
+ native_errors = _template_lock_errors(native_specs, native_lock)
+ native_errors.extend(_native_structure_lock_errors(
+ native_specs,
+ native_lock,
+ native_contract,
+ ))
+ for message in native_errors:
+ self._template_issues.append((
+ 'error',
+ 'native_structure_svg',
+ message,
+ ))
+ except _TemplateStructureError as exc:
+ self._template_issues.append((
+ 'error',
+ 'native_structure_svg',
+ str(exc),
+ ))
+
spec_path = dir_path / 'design_spec.md'
spec_text = spec_path.read_text(encoding='utf-8') if spec_path.exists() else ""
spec_pages = self._extract_spec_roster(spec_text) if spec_text else []
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 7c1ff376..eb5c1f5b 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -503,6 +503,7 @@ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None
'data-pptx-layer',
'data-pptx-placeholder',
'data-pptx-placeholder-bounds',
+ 'data-pptx-placeholder-idx',
):
value = elem.get(attr)
if value is not None:
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 320aa1a2..fc23297a 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
@@ -60,9 +60,12 @@ from .slide_xml import (
create_slide_xml_with_svg, create_slide_rels_xml,
)
from .template_structure import (
+ NativeStructureContract,
TemplateElementSpec,
TemplateSlideSpec,
TemplateStructureError,
+ match_native_placeholders,
+ parse_preserve_slides,
parse_template_slides,
)
@@ -1404,10 +1407,13 @@ def _layout_placeholder_shape(
def _patch_slide_placeholder(
shape: ET.Element,
item: TemplateElementSpec,
- placeholder_idx: int,
+ placeholder_idx: int | None,
+ placeholder_type: str | None = None,
) -> None:
- placeholder_type = _TEMPLATE_PLACEHOLDER_TYPES.get(item.placeholder or "")
- if placeholder_type is None:
+ resolved_type = placeholder_type or _TEMPLATE_PLACEHOLDER_TYPES.get(
+ item.placeholder or ""
+ )
+ if resolved_type is None:
raise TemplateStructureError(
f"Unsupported placeholder type: {item.placeholder!r}"
)
@@ -1434,11 +1440,11 @@ def _patch_slide_placeholder(
for existing in list(nv_pr):
if existing.tag == f"{{{PML_NS}}}ph":
nv_pr.remove(existing)
- placeholder_attrs = (
- {"type": placeholder_type}
- if item.placeholder == "title"
- else {"idx": str(placeholder_idx)}
- )
+ placeholder_attrs: dict[str, str] = {}
+ if placeholder_type is not None or item.placeholder == "title" or placeholder_idx is None:
+ placeholder_attrs["type"] = resolved_type
+ if placeholder_idx is not None:
+ placeholder_attrs["idx"] = str(placeholder_idx)
ph = ET.Element(f"{{{PML_NS}}}ph", placeholder_attrs)
ext_tag = f"{{{PML_NS}}}extLst"
insert_at = next(
@@ -1541,6 +1547,7 @@ def _apply_template_structure(
layout_rels_path = _relationships_path_for_part(extract_dir, layout_part)
placeholder_idx = 1
+ assigned_placeholder_indices: set[int] = set()
for item in prototype.elements:
if item.layer == "layout":
_move_template_static_shape(
@@ -1559,10 +1566,19 @@ def _apply_template_structure(
raise TemplateStructureError(
f"Placeholder {item.element_id!r} cannot be a slide background"
)
+ assigned_idx = (
+ item.placeholder_idx
+ if item.placeholder_idx is not None
+ else placeholder_idx
+ )
+ if item.placeholder != "title" and assigned_idx in assigned_placeholder_indices:
+ raise TemplateStructureError(
+ f"Layout {layout_key!r} repeats placeholder idx {assigned_idx}"
+ )
layout_placeholder = _layout_placeholder_shape(
prototype_shape,
item,
- placeholder_idx,
+ assigned_idx,
)
_append_shape_to_part(layout_path, layout_placeholder)
for state in layout_states:
@@ -1572,9 +1588,10 @@ def _apply_template_structure(
f"{state.spec.svg_path.name}: placeholder {item.element_id!r} "
"did not produce a shape"
)
- _patch_slide_placeholder(shape, item, placeholder_idx)
+ _patch_slide_placeholder(shape, item, assigned_idx)
if item.placeholder != "title":
- placeholder_idx += 1
+ assigned_placeholder_indices.add(assigned_idx)
+ placeholder_idx = max(placeholder_idx, assigned_idx + 1)
placeholder_count += 1
_set_template_layout_header_footer(layout_path, prototype.placeholders)
@@ -1599,6 +1616,76 @@ def _apply_template_structure(
)
+def _apply_preserved_structure(
+ extract_dir: Path,
+ specs: list[TemplateSlideSpec],
+ contract: NativeStructureContract,
+ conversion_traces: list[dict[str, Any]] | None,
+ *,
+ verbose: bool = False,
+) -> None:
+ """Drop preview-only inherited layers and bind content to source placeholders."""
+ states = _template_runtime_slides(extract_dir, specs, conversion_traces)
+ removed_preview_shapes = 0
+ removed_preview_backgrounds = 0
+ placeholder_count = 0
+ for state in states:
+ removed_background = False
+ for item in state.spec.elements:
+ if item.layer not in {"master", "layout"}:
+ continue
+ shape = _template_shape_for_item(state, item)
+ if shape is not None:
+ _remove_template_shape(state, shape)
+ removed_preview_shapes += 1
+ continue
+ if removed_background:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: multiple inherited preview "
+ "backgrounds resolved to one slide background"
+ )
+ common_slide = state.root.find(f"{{{PML_NS}}}cSld")
+ background = (
+ common_slide.find(f"{{{PML_NS}}}bg")
+ if common_slide is not None
+ else None
+ )
+ if common_slide is None or background is None:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: inherited preview background "
+ "did not produce a removable slide background"
+ )
+ common_slide.remove(background)
+ removed_background = True
+ removed_preview_backgrounds += 1
+
+ layout = contract.layout(state.spec.layout_key)
+ for item, source_placeholder in match_native_placeholders(state.spec, layout):
+ shape = _template_shape_for_item(state, item)
+ if shape is None:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: placeholder {item.element_id!r} "
+ "cannot resolve to a slide background"
+ )
+ _patch_slide_placeholder(
+ shape,
+ item,
+ source_placeholder.idx,
+ source_placeholder.placeholder_type,
+ )
+ placeholder_count += 1
+ _write_xml_tree(state.slide_path, state.tree)
+
+ if verbose:
+ print(
+ " Preserved structure: "
+ f"{len({spec.layout_key for spec in specs})} source layout(s), "
+ f"{removed_preview_shapes} preview shape(s) removed, "
+ f"{removed_preview_backgrounds} preview background(s) removed, "
+ f"{placeholder_count} source placeholder binding(s)"
+ )
+
+
def _promote_common_chrome_shapes_to_masters(
extract_dir: Path,
structure: PptxStructureContext,
@@ -2648,6 +2735,66 @@ def _stamp_docprops(
app_path.write_text(app, encoding='utf-8')
+def _create_preserved_base_pptx(
+ contract: NativeStructureContract,
+ specs: list[TemplateSlideSpec],
+ output_path: Path,
+ slide_size_emu: tuple[int, int],
+) -> None:
+ """Create empty slides bound to the source package's original layouts."""
+ presentation = Presentation(str(contract.source_template))
+ actual_size = (int(presentation.slide_width), int(presentation.slide_height))
+ if actual_size != contract.slide_size_emu:
+ raise TemplateStructureError(
+ f"{contract.source_template.name} slide size does not match "
+ f"{contract.contract_path.name}"
+ )
+ if actual_size != slide_size_emu:
+ raise TemplateStructureError(
+ "Generated SVG canvas does not match the preserved source template size"
+ )
+
+ layouts_by_part = {
+ str(layout.part.partname).lstrip("/"): layout
+ for master in presentation.slide_masters
+ for layout in master.slide_layouts
+ }
+ slide_ids = presentation.slides._sldIdLst
+ for slide_id in list(slide_ids):
+ presentation.part.drop_rel(slide_id.rId)
+ slide_ids.remove(slide_id)
+
+ for spec in specs:
+ layout_contract = contract.layout(spec.layout_key)
+ layout = layouts_by_part.get(layout_contract.package_part)
+ if layout is None:
+ raise TemplateStructureError(
+ f"Preserved source package did not load layout part "
+ f"{layout_contract.package_part!r}"
+ )
+ presentation.slides.add_slide(layout)
+ presentation.save(str(output_path))
+
+
+def _clear_preserved_slide_collections(extract_dir: Path) -> None:
+ """Remove source slide-order metadata that cannot apply to generated pages."""
+ presentation_path = extract_dir / "ppt" / "presentation.xml"
+ tree = ET.parse(presentation_path)
+ root = tree.getroot()
+ custom_shows = root.find(f"{{{PML_NS}}}custShowLst")
+ if custom_shows is not None:
+ root.remove(custom_shows)
+ for extension_list in root.findall(f".//{{{PML_NS}}}extLst"):
+ for extension in list(extension_list):
+ if any(
+ child.tag.rsplit("}", 1)[-1] == "sectionLst"
+ for child in extension.iter()
+ if isinstance(child.tag, str)
+ ):
+ extension_list.remove(extension)
+ _write_xml_tree(presentation_path, tree)
+
+
def create_pptx_with_native_svg(
svg_files: list[Path],
output_path: Path,
@@ -2681,6 +2828,7 @@ def create_pptx_with_native_svg(
conversion_trace_path: Path | None = None,
doc_metadata: dict[str, Any] | None = None,
pptx_structure: str = "baseline",
+ native_structure_contract: NativeStructureContract | None = None,
) -> bool:
"""Create a PPTX file with native SVG.
@@ -2720,7 +2868,10 @@ def create_pptx_with_native_svg(
pptx_structure: PPTX structure strategy. ``baseline`` promotes safe
shared native backgrounds and leading chrome to slide masters;
``template`` consumes explicit SVG master/layout/placeholder
- metadata; ``flat`` keeps generated structure slide-local.
+ metadata; ``preserve`` reuses an imported source PPTX package;
+ ``flat`` keeps generated structure slide-local.
+ native_structure_contract: Validated source package contract for
+ ``preserve`` mode.
Returns:
Whether all slides were successfully created.
@@ -2732,13 +2883,20 @@ def create_pptx_with_native_svg(
# Native shapes mode takes priority over compat mode
if use_native_shapes:
use_compat_mode = False
- if pptx_structure not in {"baseline", "template", "flat"}:
+ if pptx_structure not in {"baseline", "template", "preserve", "flat"}:
raise ValueError(f"Unsupported pptx_structure: {pptx_structure}")
- template_specs = (
- parse_template_slides(svg_files)
- if use_native_shapes and pptx_structure == "template"
- else None
- )
+ if use_native_shapes and pptx_structure == "template":
+ template_specs = parse_template_slides(svg_files)
+ elif use_native_shapes and pptx_structure == "preserve":
+ if native_structure_contract is None:
+ raise TemplateStructureError(
+ "Preserve export requires a validated native structure contract"
+ )
+ template_specs = parse_preserve_slides(svg_files)
+ for spec in template_specs:
+ native_structure_contract.layout(spec.layout_key)
+ else:
+ template_specs = None
if template_specs is not None and not native_objects:
native_placeholders = sorted({
item.placeholder
@@ -2827,22 +2985,36 @@ def create_pptx_with_native_svg(
temp_dir = _create_writable_work_dir(output_path)
try:
- # Create base PPTX with python-pptx
- prs = Presentation()
- prs.slide_width = width_emu
- prs.slide_height = height_emu
-
- blank_layout = prs.slide_layouts[6]
- for _ in svg_files:
- prs.slides.add_slide(blank_layout)
-
base_pptx = temp_dir / 'base.pptx'
- prs.save(str(base_pptx))
+ if (
+ use_native_shapes
+ and pptx_structure == "preserve"
+ and native_structure_contract is not None
+ and template_specs is not None
+ ):
+ _create_preserved_base_pptx(
+ native_structure_contract,
+ template_specs,
+ base_pptx,
+ (width_emu, height_emu),
+ )
+ else:
+ # Create the standard base PPTX with python-pptx.
+ prs = Presentation()
+ prs.slide_width = width_emu
+ prs.slide_height = height_emu
+
+ blank_layout = prs.slide_layouts[6]
+ for _ in svg_files:
+ prs.slides.add_slide(blank_layout)
+ prs.save(str(base_pptx))
# Extract PPTX
extract_dir = temp_dir / 'pptx_content'
with zipfile.ZipFile(base_pptx, 'r') as zf:
zf.extractall(extract_dir)
+ if use_native_shapes and pptx_structure == "preserve":
+ _clear_preserved_slide_collections(extract_dir)
structure = _read_slide_layout_targets(extract_dir, len(svg_files))
media_dir = extract_dir / 'ppt' / 'media'
@@ -2878,7 +3050,7 @@ def create_pptx_with_native_svg(
conversion_trace: list[dict[str, Any]] | None = [] if conversion_trace_path else None
structure_trace: list[dict[str, Any]] | None = (
[]
- if use_native_shapes and pptx_structure in {"baseline", "template"}
+ if use_native_shapes and pptx_structure in {"baseline", "template", "preserve"}
else None
)
@@ -3282,6 +3454,30 @@ def create_pptx_with_native_svg(
verbose=verbose,
)
+ if (
+ use_native_shapes
+ and pptx_structure == "preserve"
+ and success_count == len(svg_files)
+ ):
+ _convert_page_number_texts_to_fields(
+ extract_dir,
+ len(svg_files),
+ conversion_trace if conversion_trace is not None else structure_trace,
+ context="Preserve",
+ verbose=verbose,
+ )
+ if template_specs is None or native_structure_contract is None:
+ raise TemplateStructureError(
+ "Preserved structure metadata was not parsed before export"
+ )
+ _apply_preserved_structure(
+ extract_dir,
+ template_specs,
+ native_structure_contract,
+ conversion_trace if conversion_trace is not None else structure_trace,
+ verbose=verbose,
+ )
+
# Update [Content_Types].xml
content_types_path = extract_dir / '[Content_Types].xml'
with open(content_types_path, 'r', encoding='utf-8') as f:
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 2611dd36..8e570f10 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
@@ -33,7 +33,10 @@ from .narration import NARRATION_EXTENSIONS, find_narration_files, probe_audio_d
from .slide_xml import TRANSITIONS
from .template_structure import (
TemplateStructureError,
+ load_native_structure_contract,
load_pptx_structure_lock,
+ native_structure_lock_errors,
+ parse_preserve_slides,
parse_template_slides,
template_lock_errors,
)
@@ -219,13 +222,14 @@ Recorded narration:
'to tell it apart from a plain shape export.')
parser.add_argument(
'--pptx-structure',
- choices=['baseline', 'template', 'flat'],
+ choices=['baseline', 'template', 'preserve', 'flat'],
default=None,
help=(
'PPTX structure strategy for native export. When omitted, read '
'spec_lock.md pptx_structure.mode, falling back to baseline. baseline '
'promotes safe repeated background/chrome; template consumes explicit '
'data-pptx-layout/layer/placeholder metadata to build reusable layouts; '
+ 'preserve binds generated slides to an imported source template package; '
'flat leaves generated structure slide-local for debugging/comparison.'
),
)
@@ -326,6 +330,7 @@ Recorded narration:
print(f"Error: Path does not exist: {project_path}")
return 1
structure_lock = None
+ native_structure_contract = None
pptx_structure = args.pptx_structure
if pptx_structure is None:
try:
@@ -334,6 +339,28 @@ Recorded narration:
print(f"Error: {exc}", file=sys.stderr)
return 1
pptx_structure = structure_lock.mode if structure_lock else 'baseline'
+ elif pptx_structure == 'preserve':
+ try:
+ structure_lock = load_pptx_structure_lock(project_path)
+ except TemplateStructureError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ if structure_lock is None or structure_lock.mode != 'preserve':
+ print(
+ "Error: --pptx-structure preserve requires a preserve-mode "
+ "spec_lock.md with source_template/native_structure rows",
+ file=sys.stderr,
+ )
+ return 1
+ if pptx_structure == 'preserve':
+ if structure_lock is None:
+ print("Error: preserve mode requires spec_lock.md", file=sys.stderr)
+ return 1
+ try:
+ native_structure_contract = load_native_structure_contract(structure_lock)
+ 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
@@ -396,9 +423,17 @@ Recorded narration:
print("Error: No SVG files found")
return 1
- if gen_native and pptx_structure == 'template' and structure_lock is not None:
+ if (
+ gen_native
+ and pptx_structure in {'template', 'preserve'}
+ and structure_lock is not None
+ ):
try:
- template_specs = parse_template_slides(native_files)
+ template_specs = (
+ parse_preserve_slides(native_files)
+ if pptx_structure == 'preserve'
+ else parse_template_slides(native_files)
+ )
except TemplateStructureError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
@@ -408,6 +443,23 @@ Recorded narration:
for message in lock_errors:
print(f" {message}", file=sys.stderr)
return 1
+ if pptx_structure == 'preserve':
+ if native_structure_contract is None:
+ print("Error: preserve mode contract is unavailable", file=sys.stderr)
+ return 1
+ preserve_errors = native_structure_lock_errors(
+ template_specs,
+ structure_lock,
+ native_structure_contract,
+ )
+ if preserve_errors:
+ print(
+ "Error: PPTX structure does not match native_structure.json:",
+ file=sys.stderr,
+ )
+ for message in preserve_errors:
+ print(f" {message}", file=sys.stderr)
+ return 1
if args.native_objects:
fallbacks = _native_object_fallbacks(native_files)
@@ -690,6 +742,7 @@ Recorded narration:
image_quality=args.image_quality,
native_objects=args.native_objects,
pptx_structure=pptx_structure,
+ native_structure_contract=native_structure_contract,
)
success = True
@@ -758,6 +811,26 @@ Recorded narration:
print(f" [warn] svg_output backup skipped: {exc}")
elif verbose:
print(f" [info] svg_output/ not found, backup skipped")
+ if pptx_structure == 'preserve' and structure_lock is not None:
+ try:
+ preserve_sources = [
+ project_path / 'spec_lock.md',
+ structure_lock.source_template,
+ structure_lock.native_structure,
+ ]
+ for source in preserve_sources:
+ if source is None or not source.is_file():
+ continue
+ source_path = source.resolve()
+ relative = source_path.relative_to(project_path.resolve())
+ destination = backup_dir / relative
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source_path, destination)
+ if verbose:
+ print(f" preserve contract backup: {backup_dir}")
+ except (OSError, ValueError) as exc:
+ if verbose:
+ print(f" [warn] preserve contract backup skipped: {exc}")
if success and cache_dir is not None and cache_dir.is_dir() and not args.keep_cache:
try:
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 a4d9350a..1fa928a5 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,10 +16,14 @@ Dependencies:
from __future__ import annotations
+import hashlib
+import json
import math
import re
+import zipfile
from dataclasses import dataclass
from pathlib import Path
+from typing import Any
from xml.etree import ElementTree as ET
@@ -30,6 +34,7 @@ _STRUCTURE_ATTRS = frozenset({
"data-pptx-layout-name",
"data-pptx-placeholder",
"data-pptx-placeholder-bounds",
+ "data-pptx-placeholder-idx",
"data-pptx-editable",
})
_LAYERS = frozenset({"master", "layout", "slide"})
@@ -46,7 +51,8 @@ _TEXT_PLACEHOLDERS = frozenset({"title", "body", "footer", "slide-number"})
_LAYOUT_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_LOCK_ROW_RE = re.compile(r"^-\s+([A-Za-z0-9_]+)\s*:\s*(.+?)\s*$")
_LOCK_PAGE_RE = re.compile(r"^P(\d+)$")
-PPTX_STRUCTURE_MODES = frozenset({"baseline", "template", "flat"})
+PPTX_STRUCTURE_MODES = frozenset({"baseline", "template", "preserve", "flat"})
+NATIVE_STRUCTURE_SCHEMA = "ppt-master.native-structure.v1"
class TemplateStructureError(RuntimeError):
@@ -68,6 +74,48 @@ class PptxStructureLock:
mode: str
layouts: tuple[PptxLayoutReference, ...] = ()
+ source_template: Path | None = None
+ native_structure: Path | None = None
+
+
+@dataclass(frozen=True)
+class NativePlaceholderSpec:
+ """One placeholder exposed by a preserved source layout."""
+
+ semantic_role: str
+ placeholder_type: str
+ idx: int | None
+ geometry: tuple[float, float, float, float] | None = None
+
+
+@dataclass(frozen=True)
+class NativeLayoutSpec:
+ """One named layout retained from the source PPTX package."""
+
+ key: str
+ name: str
+ package_part: str
+ master_key: str
+ placeholders: tuple[NativePlaceholderSpec, ...] = ()
+
+
+@dataclass(frozen=True)
+class NativeStructureContract:
+ """Validated portable contract for a preserved source PPTX package."""
+
+ source_template: Path
+ contract_path: Path
+ source_sha256: str
+ slide_size_emu: tuple[int, int]
+ layouts: tuple[NativeLayoutSpec, ...]
+
+ def layout(self, key: str) -> NativeLayoutSpec:
+ for layout in self.layouts:
+ if layout.key == key:
+ return layout
+ raise TemplateStructureError(
+ f"native_structure.json has no layout key {key!r}"
+ )
@dataclass(frozen=True)
@@ -80,6 +128,7 @@ class TemplateElementSpec:
layer: str | None = None
placeholder: str | None = None
placeholder_bounds: tuple[float, float, float, float] | None = None
+ placeholder_idx: int | None = None
is_background: bool = False
def contract_signature(self) -> tuple[object, ...]:
@@ -90,6 +139,7 @@ class TemplateElementSpec:
self.layer,
self.placeholder,
self.placeholder_bounds,
+ self.placeholder_idx,
self.is_background,
)
@@ -186,6 +236,44 @@ def _is_full_canvas_solid_rect(
return True
+def _portable_project_file(
+ project_path: Path,
+ raw_value: str,
+ field_name: str,
+ suffix: str,
+) -> Path:
+ """Resolve a project-relative structure file without allowing escape."""
+ value = raw_value.strip()
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
+ value = value[1:-1].strip()
+ if not value:
+ raise TemplateStructureError(
+ f"spec_lock.md pptx_structure.{field_name} cannot be empty"
+ )
+ candidate = Path(value)
+ if candidate.is_absolute():
+ raise TemplateStructureError(
+ f"spec_lock.md pptx_structure.{field_name} must be project-relative"
+ )
+ root = project_path.resolve()
+ resolved = (root / candidate).resolve()
+ try:
+ resolved.relative_to(root)
+ except ValueError as exc:
+ raise TemplateStructureError(
+ f"spec_lock.md pptx_structure.{field_name} escapes the project directory"
+ ) from exc
+ if resolved.suffix.lower() != suffix:
+ raise TemplateStructureError(
+ f"spec_lock.md pptx_structure.{field_name} must reference a {suffix} file"
+ )
+ if not resolved.is_file():
+ raise TemplateStructureError(
+ f"spec_lock.md pptx_structure.{field_name} does not exist: {candidate}"
+ )
+ return resolved
+
+
def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
"""Load optional pptx_structure/pptx_layouts sections from spec_lock.md."""
lock_path = project_path / "spec_lock.md"
@@ -226,6 +314,38 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
f"spec_lock.md pptx_structure.mode must be one of: {allowed}"
)
+ source_rows = [
+ value for key, value in structure_rows if key == "source_template"
+ ]
+ contract_rows = [
+ value for key, value in structure_rows if key == "native_structure"
+ ]
+ source_template = None
+ native_structure = None
+ if mode == "preserve":
+ if len(source_rows) != 1 or len(contract_rows) != 1:
+ raise TemplateStructureError(
+ "spec_lock.md preserve mode requires exactly one '- source_template:' "
+ "row and one '- native_structure:' row"
+ )
+ source_template = _portable_project_file(
+ project_path,
+ source_rows[0],
+ "source_template",
+ ".pptx",
+ )
+ native_structure = _portable_project_file(
+ project_path,
+ contract_rows[0],
+ "native_structure",
+ ".json",
+ )
+ elif source_rows or contract_rows:
+ raise TemplateStructureError(
+ "spec_lock.md source_template/native_structure rows are allowed only "
+ "when pptx_structure.mode is preserve"
+ )
+
references: list[PptxLayoutReference] = []
seen_slides: set[int] = set()
for page_key, raw_value in layout_rows:
@@ -258,18 +378,188 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
layout_name=layout_name,
))
- if mode == "template" and not references:
+ if mode in {"template", "preserve"} and not references:
raise TemplateStructureError(
- "spec_lock.md template mode requires one pptx_layouts row per page"
+ f"spec_lock.md {mode} mode requires one pptx_layouts row per page"
)
- if mode != "template" and references:
+ if mode not in {"template", "preserve"} and references:
raise TemplateStructureError(
"spec_lock.md pptx_layouts is allowed only when pptx_structure.mode "
- "is template"
+ "is template or preserve"
)
return PptxStructureLock(
mode=mode,
layouts=tuple(sorted(references, key=lambda item: item.slide_num)),
+ source_template=source_template,
+ native_structure=native_structure,
+ )
+
+
+def _file_sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _native_geometry(raw: Any, context: str) -> tuple[float, float, float, float] | None:
+ if raw is None:
+ return None
+ if not isinstance(raw, dict):
+ raise TemplateStructureError(f"{context} geometry must be an object or null")
+ try:
+ values = tuple(float(raw[key]) for key in ("x", "y", "width", "height"))
+ except (KeyError, TypeError, ValueError) as exc:
+ raise TemplateStructureError(f"{context} geometry is invalid") from exc
+ if not all(math.isfinite(value) for value in values) or values[2] <= 0 or values[3] <= 0:
+ raise TemplateStructureError(f"{context} geometry must be finite and positive")
+ return values
+
+
+def load_native_structure_contract(
+ structure_lock: PptxStructureLock,
+) -> NativeStructureContract:
+ """Load and verify the native structure bundle selected by preserve mode."""
+ if structure_lock.mode != "preserve":
+ raise TemplateStructureError(
+ "native structure contracts are available only in preserve mode"
+ )
+ source_template = structure_lock.source_template
+ contract_path = structure_lock.native_structure
+ if source_template is None or contract_path is None:
+ raise TemplateStructureError(
+ "preserve mode is missing source_template or native_structure"
+ )
+ try:
+ raw = json.loads(contract_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise TemplateStructureError(
+ f"Cannot read native structure contract {contract_path}: {exc}"
+ ) from exc
+ if not isinstance(raw, dict) or raw.get("schema") != NATIVE_STRUCTURE_SCHEMA:
+ raise TemplateStructureError(
+ f"{contract_path.name} must use schema {NATIVE_STRUCTURE_SCHEMA!r}"
+ )
+
+ source = raw.get("source")
+ expected_sha = source.get("sha256") if isinstance(source, dict) else None
+ if not isinstance(expected_sha, str) or not re.fullmatch(r"[0-9a-f]{64}", expected_sha):
+ raise TemplateStructureError(
+ f"{contract_path.name} source.sha256 must be a lowercase SHA-256 digest"
+ )
+ actual_sha = _file_sha256(source_template)
+ if actual_sha != expected_sha:
+ raise TemplateStructureError(
+ f"{source_template.name} does not match {contract_path.name} source.sha256"
+ )
+
+ slide_size = raw.get("slideSize")
+ try:
+ slide_size_emu = (
+ int(slide_size["width_emu"]),
+ int(slide_size["height_emu"]),
+ )
+ except (KeyError, TypeError, ValueError) as exc:
+ raise TemplateStructureError(
+ f"{contract_path.name} slideSize must contain width_emu/height_emu"
+ ) from exc
+ if slide_size_emu[0] <= 0 or slide_size_emu[1] <= 0:
+ raise TemplateStructureError(
+ f"{contract_path.name} slideSize values must be positive"
+ )
+
+ raw_layouts = raw.get("layouts")
+ if not isinstance(raw_layouts, list) or not raw_layouts:
+ raise TemplateStructureError(
+ f"{contract_path.name} must contain at least one layout"
+ )
+ layouts: list[NativeLayoutSpec] = []
+ seen_keys: set[str] = set()
+ seen_parts: set[str] = set()
+ for index, item in enumerate(raw_layouts, start=1):
+ context = f"{contract_path.name} layouts[{index}]"
+ if not isinstance(item, dict):
+ raise TemplateStructureError(f"{context} must be an object")
+ key = str(item.get("key") or "")
+ name = str(item.get("name") or "").strip()
+ package_part = str(item.get("packagePart") or "")
+ master_key = str(item.get("masterKey") or "")
+ if not _LAYOUT_KEY_RE.fullmatch(key):
+ raise TemplateStructureError(f"{context} has invalid key {key!r}")
+ if key in seen_keys:
+ raise TemplateStructureError(f"{context} repeats layout key {key!r}")
+ if not name:
+ raise TemplateStructureError(f"{context} name cannot be empty")
+ if (
+ not package_part.startswith("ppt/slideLayouts/")
+ or ".." in Path(package_part).parts
+ or not package_part.endswith(".xml")
+ ):
+ raise TemplateStructureError(
+ f"{context} packagePart must be a ppt/slideLayouts/*.xml part"
+ )
+ if package_part in seen_parts:
+ raise TemplateStructureError(
+ f"{context} repeats package part {package_part!r}"
+ )
+ if not master_key:
+ raise TemplateStructureError(f"{context} masterKey cannot be empty")
+
+ raw_placeholders = item.get("placeholders", [])
+ if not isinstance(raw_placeholders, list):
+ raise TemplateStructureError(f"{context} placeholders must be a list")
+ placeholders: list[NativePlaceholderSpec] = []
+ for ph_index, placeholder in enumerate(raw_placeholders, start=1):
+ ph_context = f"{context} placeholders[{ph_index}]"
+ if not isinstance(placeholder, dict):
+ raise TemplateStructureError(f"{ph_context} must be an object")
+ semantic_role = str(placeholder.get("semanticRole") or "other")
+ placeholder_type = str(placeholder.get("type") or "obj")
+ raw_idx = placeholder.get("idx")
+ try:
+ placeholder_idx = int(raw_idx) if raw_idx is not None else None
+ except (TypeError, ValueError) as exc:
+ raise TemplateStructureError(
+ f"{ph_context} idx must be an integer or null"
+ ) from exc
+ if placeholder_idx is not None and placeholder_idx < 0:
+ raise TemplateStructureError(f"{ph_context} idx cannot be negative")
+ placeholders.append(NativePlaceholderSpec(
+ semantic_role=semantic_role,
+ placeholder_type=placeholder_type,
+ idx=placeholder_idx,
+ geometry=_native_geometry(placeholder.get("geometry"), ph_context),
+ ))
+ layouts.append(NativeLayoutSpec(
+ key=key,
+ name=name,
+ package_part=package_part,
+ master_key=master_key,
+ placeholders=tuple(placeholders),
+ ))
+ seen_keys.add(key)
+ seen_parts.add(package_part)
+
+ try:
+ with zipfile.ZipFile(source_template, "r") as package:
+ package_parts = set(package.namelist())
+ except (OSError, zipfile.BadZipFile) as exc:
+ raise TemplateStructureError(
+ f"Cannot open preserved source template {source_template}: {exc}"
+ ) from exc
+ missing_parts = sorted(seen_parts - package_parts)
+ if missing_parts:
+ raise TemplateStructureError(
+ f"{source_template.name} is missing layout part(s): " + ", ".join(missing_parts)
+ )
+
+ return NativeStructureContract(
+ source_template=source_template,
+ contract_path=contract_path,
+ source_sha256=expected_sha,
+ slide_size_emu=slide_size_emu,
+ layouts=tuple(layouts),
)
@@ -304,6 +594,23 @@ def _parse_placeholder_bounds(
return x, y, width, height
+def _parse_placeholder_idx(
+ raw: str | None,
+ *,
+ svg_path: Path,
+ element_id: str,
+) -> int | None:
+ if raw is None:
+ return None
+ value = raw.strip()
+ if not value or not value.isdigit():
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} data-pptx-placeholder-idx must be "
+ "a non-negative integer"
+ )
+ return int(value)
+
+
def _validate_placeholder_element(
elem: ET.Element,
placeholder: str,
@@ -410,6 +717,7 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
(placeholder_raw or "").strip().lower() or None
)
bounds_raw = elem.get("data-pptx-placeholder-bounds")
+ placeholder_idx_raw = elem.get("data-pptx-placeholder-idx")
editable_raw = elem.get("data-pptx-editable")
is_background = _is_full_canvas_solid_rect(elem, canvas)
effective_layer = layer or ("slide" if is_background else None)
@@ -456,6 +764,11 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
f"{svg_path.name}: {element_id or tag} has placeholder bounds without "
"data-pptx-placeholder"
)
+ if placeholder_idx_raw is not None and not placeholder:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} has placeholder idx without "
+ "data-pptx-placeholder"
+ )
if (effective_layer or placeholder) and not element_id:
raise TemplateStructureError(
f"{svg_path.name}: direct <{tag}> with template metadata requires an id"
@@ -495,6 +808,11 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
svg_path=svg_path,
element_id=element_id or tag,
)
+ placeholder_idx = _parse_placeholder_idx(
+ placeholder_idx_raw,
+ svg_path=svg_path,
+ element_id=element_id or tag,
+ )
if effective_layer or placeholder:
elements.append(TemplateElementSpec(
@@ -504,6 +822,7 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
layer=effective_layer,
placeholder=placeholder,
placeholder_bounds=placeholder_bounds,
+ placeholder_idx=placeholder_idx,
is_background=is_background,
))
visual_order += 1
@@ -571,12 +890,23 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
return specs
+def parse_preserve_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
+ """Parse preserve-mode slides before source master grouping is known."""
+ specs = [
+ parse_template_slide(svg_path, slide_num)
+ for slide_num, svg_path in enumerate(svg_files, start=1)
+ ]
+ if not specs:
+ raise TemplateStructureError("Preserve export requires at least one SVG slide")
+ return specs
+
+
def template_lock_errors(
specs: list[TemplateSlideSpec],
structure_lock: PptxStructureLock,
) -> list[str]:
"""Return mismatches between parsed SVG layouts and the project lock."""
- if structure_lock.mode != "template":
+ if structure_lock.mode not in {"template", "preserve"}:
return []
errors: list[str] = []
references = {
@@ -616,6 +946,112 @@ def template_lock_errors(
return errors
+_PRESERVE_PLACEHOLDER_TYPES = {
+ "title": frozenset({"title", "ctrTitle"}),
+ "body": frozenset({"body", "subTitle", "obj"}),
+ "picture": frozenset({"pic", "obj"}),
+ "chart": frozenset({"chart", "obj"}),
+ "table": frozenset({"tbl", "obj"}),
+ "footer": frozenset({"ftr"}),
+ "slide-number": frozenset({"sldNum"}),
+}
+
+
+def match_native_placeholders(
+ spec: TemplateSlideSpec,
+ layout: NativeLayoutSpec,
+) -> tuple[tuple[TemplateElementSpec, NativePlaceholderSpec], ...]:
+ """Match slide placeholder markers to source layout placeholder identities."""
+ available = list(layout.placeholders)
+ matches: list[tuple[TemplateElementSpec, NativePlaceholderSpec]] = []
+ for item in spec.placeholders:
+ allowed_types = _PRESERVE_PLACEHOLDER_TYPES.get(item.placeholder or "", frozenset())
+ candidate_index = None
+ for index, candidate in enumerate(available):
+ if candidate.placeholder_type not in allowed_types:
+ continue
+ if item.placeholder_idx is not None and candidate.idx != item.placeholder_idx:
+ continue
+ candidate_index = index
+ break
+ if candidate_index is None:
+ idx_note = (
+ f" idx={item.placeholder_idx}"
+ if item.placeholder_idx is not None
+ else ""
+ )
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: placeholder {item.element_id!r} "
+ f"({item.placeholder}{idx_note}) has no compatible source placeholder "
+ f"in layout {layout.key!r}"
+ )
+ matches.append((item, available.pop(candidate_index)))
+ return tuple(matches)
+
+
+def native_structure_lock_errors(
+ specs: list[TemplateSlideSpec],
+ structure_lock: PptxStructureLock,
+ contract: NativeStructureContract,
+) -> list[str]:
+ """Return preserve-mode mismatches against the imported source contract."""
+ if structure_lock.mode != "preserve":
+ return []
+ errors: list[str] = []
+ references = {item.slide_num: item for item in structure_lock.layouts}
+ contract_layouts = {layout.key: layout for layout in contract.layouts}
+
+ for reference in structure_lock.layouts:
+ layout = contract_layouts.get(reference.layout_key)
+ if layout is None:
+ errors.append(
+ f"spec_lock.md P{reference.slide_num:02d} references unknown source "
+ f"layout key {reference.layout_key!r}"
+ )
+ continue
+ if reference.layout_name and reference.layout_name != layout.name:
+ errors.append(
+ f"spec_lock.md P{reference.slide_num:02d} layout name "
+ f"{reference.layout_name!r} does not match source name {layout.name!r}"
+ )
+
+ master_contracts: dict[str, tuple[tuple[object, ...], ...]] = {}
+ layout_contracts: dict[str, tuple[tuple[object, ...], ...]] = {}
+ for spec in specs:
+ reference = references.get(spec.slide_num)
+ if reference is None:
+ continue
+ layout = contract_layouts.get(reference.layout_key)
+ if layout is None:
+ continue
+ master_contract = tuple(
+ item.contract_signature() for item in spec.master_elements
+ )
+ expected_master = master_contracts.setdefault(
+ layout.master_key,
+ master_contract,
+ )
+ if master_contract != expected_master:
+ errors.append(
+ f"{spec.svg_path.name}: preview master layer differs from another "
+ f"page using source master {layout.master_key!r}"
+ )
+ expected_layout = layout_contracts.setdefault(
+ layout.key,
+ spec.layout_contract,
+ )
+ if spec.layout_contract != expected_layout:
+ errors.append(
+ f"{spec.svg_path.name}: preview layout/placeholder contract differs "
+ f"from another page using source layout {layout.key!r}"
+ )
+ try:
+ match_native_placeholders(spec, layout)
+ except TemplateStructureError as exc:
+ errors.append(str(exc))
+ return errors
+
+
def validate_template_svg(svg_path: Path) -> list[str]:
"""Return per-file template metadata errors for quality-check integration."""
try:
diff --git a/skills/ppt-master/scripts/template_import/manifest.py b/skills/ppt-master/scripts/template_import/manifest.py
index 40c4f190..1c3209ad 100644
--- a/skills/ppt-master/scripts/template_import/manifest.py
+++ b/skills/ppt-master/scripts/template_import/manifest.py
@@ -65,6 +65,7 @@ class SlideRecord:
text_samples: list[str]
text_count: int
shape_count: int
+ placeholders: list[dict[str, Any]]
page_type: str
svg_file: str
flat_svg_file: str
@@ -87,9 +88,13 @@ def summarize_part_record(
bg_asset = detect_background_asset(root, rels)
image_targets = extract_image_targets(root, rels)
+ display_name = part_display_name(root, part_path)
+ layout_type = root.attrib.get("type") if root is not None else None
return {
"path": part_path,
"name": PurePosixPath(part_path).name,
+ "displayName": display_name,
+ "layoutType": layout_type,
"svgFile": svg_file,
"parentPath": parent_path,
"themePath": theme_path,
@@ -100,6 +105,7 @@ def summarize_part_record(
"textSamples": extract_text_samples(root),
"textCount": len(root.findall(".//a:t", NS)) if root is not None else 0,
"shapeCount": count_slide_shapes(root),
+ "drawableShapeCount": count_drawable_shapes(root),
"usedBySlides": used_by_slides,
}
@@ -201,6 +207,38 @@ def parse_xfrm_record(sp: ET.Element) -> dict[str, int] | None:
}
+def part_display_name(root: ET.Element | None, part_path: str) -> str:
+ """Return the PowerPoint picker name, falling back to the package stem."""
+ if root is not None:
+ common_slide = root.find("p:cSld", NS)
+ if common_slide is not None:
+ name = (common_slide.attrib.get("name") or "").strip()
+ if name:
+ return name
+ matching_name = (root.attrib.get("matchingName") or "").strip()
+ if matching_name:
+ return matching_name
+ return PurePosixPath(part_path).stem
+
+
+def placeholder_semantic_role(placeholder_type: str | None) -> str:
+ """Map an OOXML placeholder type to the exporter role vocabulary."""
+ normalized = placeholder_type or "obj"
+ role_by_type = {
+ "title": "title",
+ "ctrTitle": "title",
+ "body": "body",
+ "subTitle": "body",
+ "obj": "body",
+ "pic": "picture",
+ "chart": "chart",
+ "tbl": "table",
+ "ftr": "footer",
+ "sldNum": "slide-number",
+ }
+ return role_by_type.get(normalized, "other")
+
+
def extract_placeholders(root: ET.Element | None) -> list[dict[str, Any]]:
if root is None:
return []
@@ -209,11 +247,16 @@ def extract_placeholders(root: ET.Element | None) -> list[dict[str, Any]]:
ph = sp.find("p:nvSpPr/p:nvPr/p:ph", NS)
if ph is None:
continue
+ non_visual = sp.find("p:nvSpPr/p:cNvPr", NS)
+ placeholder_type = ph.attrib.get("type")
record: dict[str, Any] = {
- "type": ph.attrib.get("type"),
+ "type": placeholder_type,
"idx": ph.attrib.get("idx"),
"size": ph.attrib.get("sz"),
"orient": ph.attrib.get("orient"),
+ "semanticRole": placeholder_semantic_role(placeholder_type),
+ "shapeId": non_visual.attrib.get("id") if non_visual is not None else None,
+ "shapeName": non_visual.attrib.get("name") if non_visual is not None else None,
"geometry": parse_xfrm_record(sp),
"textSamples": extract_text_samples(sp, limit=2),
}
@@ -224,6 +267,30 @@ def extract_placeholders(root: ET.Element | None) -> list[dict[str, Any]]:
return placeholders
+def count_drawable_shapes(root: ET.Element | None) -> int:
+ """Count top-level visual shapes that are not placeholder definitions."""
+ if root is None:
+ return 0
+ sp_tree = root.find("p:cSld/p:spTree", NS)
+ if sp_tree is None:
+ return 0
+ visual_tags = {
+ f"{{{NS['p']}}}sp",
+ f"{{{NS['p']}}}grpSp",
+ f"{{{NS['p']}}}graphicFrame",
+ f"{{{NS['p']}}}pic",
+ f"{{{NS['p']}}}cxnSp",
+ }
+ count = 0
+ for child in sp_tree:
+ if child.tag not in visual_tags:
+ continue
+ if child.find("p:nvSpPr/p:nvPr/p:ph", NS) is not None:
+ continue
+ count += 1
+ return count
+
+
def extract_placeholder_text_style(sp: ET.Element) -> dict[str, Any]:
style: dict[str, Any] = {}
rpr = sp.find(".//a:rPr", NS) or sp.find(".//a:endParaRPr", NS)
@@ -572,6 +639,7 @@ def build_manifest(pptx_path: Path, output_dir: Path) -> dict[str, Any]:
image_targets = extract_image_targets(slide_root, slide_rels)
texts = extract_text_samples(slide_root)
shape_count = count_slide_shapes(slide_root)
+ placeholders = extract_placeholders(slide_root)
page_type = classify_slide(index, len(slide_parts), texts, len(image_targets), shape_count)
resolved_bg = copied_assets.get(bg_asset, PurePosixPath(bg_asset).name if bg_asset else None)
@@ -623,6 +691,7 @@ def build_manifest(pptx_path: Path, output_dir: Path) -> dict[str, Any]:
text_samples=texts,
text_count=len(texts),
shape_count=shape_count,
+ placeholders=placeholders,
page_type=page_type,
svg_file=slide_svg_filename(index),
flat_svg_file=slide_svg_filename(index),
@@ -740,6 +809,7 @@ def build_manifest(pptx_path: Path, output_dir: Path) -> dict[str, Any]:
"textSamples": slide.text_samples,
"textCount": slide.text_count,
"shapeCount": slide.shape_count,
+ "placeholders": slide.placeholders,
"pageType": slide.page_type,
}
for slide in slide_records
diff --git a/skills/ppt-master/scripts/template_import/native_structure.py b/skills/ppt-master/scripts/template_import/native_structure.py
new file mode 100644
index 00000000..acba23a7
--- /dev/null
+++ b/skills/ppt-master/scripts/template_import/native_structure.py
@@ -0,0 +1,193 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Native Template Structure Contract
+
+Build a portable master/layout contract from the PPTX template import manifest.
+
+Usage:
+ Imported by pptx_template_import.py.
+
+Examples:
+ write_native_structure_bundle(source_pptx, output_dir, manifest)
+
+Dependencies:
+ None (only uses standard library)
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import shutil
+from pathlib import Path
+from typing import Any
+
+
+SCHEMA = "ppt-master.native-structure.v1"
+SOURCE_TEMPLATE_NAME = "source_template.pptx"
+CONTRACT_NAME = "native_structure.json"
+
+
+def _sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _copy_source_template(source: Path, destination: Path) -> None:
+ if source.resolve() == destination.resolve():
+ return
+ shutil.copy2(source, destination)
+
+
+def _has_reusable_structure(manifest: dict[str, Any]) -> bool:
+ layouts = manifest.get("layouts", [])
+ masters = manifest.get("masters", [])
+ slides = manifest.get("slides", [])
+ used_layouts = [layout for layout in layouts if layout.get("usedBySlides")]
+ candidate_layouts = used_layouts or layouts
+ if any(
+ layout.get("backgroundAsset")
+ or int(layout.get("drawableShapeCount") or 0) > 0
+ or any(
+ placeholder.get("semanticRole") not in {"footer", "slide-number", "other"}
+ for placeholder in layout.get("placeholders", [])
+ )
+ for layout in candidate_layouts
+ ):
+ return True
+ if any(
+ master.get("backgroundAsset")
+ or int(master.get("drawableShapeCount") or 0) > 0
+ or master.get("imageAssets")
+ for master in masters
+ ):
+ return True
+ return any(slide.get("placeholders") for slide in slides)
+
+
+def build_native_structure(
+ source_pptx: Path,
+ manifest: dict[str, Any],
+) -> dict[str, Any]:
+ """Build the portable source-package structure contract."""
+ masters = manifest.get("masters", [])
+ layouts = manifest.get("layouts", [])
+ slides = manifest.get("slides", [])
+ master_key_by_path = {
+ master["path"]: f"master_{index:02d}"
+ for index, master in enumerate(masters, start=1)
+ }
+ layout_key_by_path = {
+ layout["path"]: f"layout_{index:02d}"
+ for index, layout in enumerate(layouts, start=1)
+ }
+ complete_graph = (
+ bool(masters and layouts)
+ and all(
+ layout.get("parentPath") in master_key_by_path
+ for layout in layouts
+ )
+ and all(
+ slide.get("layoutPath") in layout_key_by_path
+ and slide.get("masterPath") in master_key_by_path
+ for slide in slides
+ )
+ )
+ reusable_structure = _has_reusable_structure(manifest)
+ recommended_mode = "preserve" if complete_graph and reusable_structure else "template"
+ reasons: list[str] = []
+ if not complete_graph:
+ reasons.append("incomplete-master-layout-graph")
+ if not reusable_structure:
+ reasons.append("source-structure-is-minimal")
+ if complete_graph and reusable_structure:
+ reasons.append("source-master-layout-contract-is-reusable")
+ if len(masters) > 1:
+ reasons.append("source-uses-multiple-masters")
+
+ master_contracts = []
+ for master in masters:
+ key = master_key_by_path[master["path"]]
+ master_contracts.append({
+ "key": key,
+ "name": master.get("displayName") or master.get("name") or key,
+ "packagePart": master["path"],
+ "themePart": master.get("themePath"),
+ "theme": master.get("theme") or {"colors": {}, "fonts": {}},
+ "backgroundAsset": master.get("backgroundAsset"),
+ "imageAssets": master.get("imageAssets", []),
+ "drawableShapeCount": master.get("drawableShapeCount", 0),
+ "layoutKeys": [
+ layout_key_by_path[layout["path"]]
+ for layout in layouts
+ if layout.get("parentPath") == master["path"]
+ ],
+ })
+
+ layout_contracts = []
+ for layout in layouts:
+ key = layout_key_by_path[layout["path"]]
+ layout_contracts.append({
+ "key": key,
+ "name": layout.get("displayName") or layout.get("name") or key,
+ "type": layout.get("layoutType"),
+ "packagePart": layout["path"],
+ "masterKey": master_key_by_path.get(layout.get("parentPath")),
+ "backgroundAsset": layout.get("backgroundAsset"),
+ "imageAssets": layout.get("imageAssets", []),
+ "drawableShapeCount": layout.get("drawableShapeCount", 0),
+ "placeholders": layout.get("placeholders", []),
+ "usedBySlides": layout.get("usedBySlides", []),
+ "svgFile": layout.get("svgFile"),
+ })
+
+ slide_contracts = []
+ for slide in slides:
+ slide_contracts.append({
+ "index": slide["index"],
+ "pageType": slide.get("pageType"),
+ "layoutKey": layout_key_by_path.get(slide.get("layoutPath")),
+ "masterKey": master_key_by_path.get(slide.get("masterPath")),
+ "placeholders": slide.get("placeholders", []),
+ "layeredSvgFile": slide.get("svgFile"),
+ "flatSvgFile": slide.get("flatSvgFile"),
+ })
+
+ return {
+ "schema": SCHEMA,
+ "source": {
+ "name": source_pptx.name,
+ "templateFile": SOURCE_TEMPLATE_NAME,
+ "sha256": _sha256(source_pptx),
+ },
+ "slideSize": manifest.get("slideSize", {}),
+ "strategy": {
+ "preservationEligible": complete_graph,
+ "reusableStructureDetected": reusable_structure,
+ "recommendedMode": recommended_mode,
+ "hasMultipleMasters": len(masters) > 1,
+ "reasonCodes": reasons,
+ },
+ "masters": master_contracts,
+ "layouts": layout_contracts,
+ "slides": slide_contracts,
+ }
+
+
+def write_native_structure_bundle(
+ source_pptx: Path,
+ output_dir: Path,
+ manifest: dict[str, Any],
+) -> dict[str, Any]:
+ """Copy the source template and write its portable structure contract."""
+ source_copy = output_dir / SOURCE_TEMPLATE_NAME
+ _copy_source_template(source_pptx, source_copy)
+ contract = build_native_structure(source_pptx, manifest)
+ (output_dir / CONTRACT_NAME).write_text(
+ json.dumps(contract, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ return contract
diff --git a/skills/ppt-master/templates/spec_lock_reference.md b/skills/ppt-master/templates/spec_lock_reference.md
index 98212254..b52cc2d2 100644
--- a/skills/ppt-master/templates/spec_lock_reference.md
+++ b/skills/ppt-master/templates/spec_lock_reference.md
@@ -127,11 +127,19 @@
>
> - `baseline` — default. Preserve the conservative shared Master/background/chrome behavior; no explicit reusable placeholder layouts are authored.
> - `template` — use only when the user explicitly requests a reusable PowerPoint template/master/layout deliverable. Requires a complete `pptx_layouts` section and explicit SVG structure metadata on every generated page.
+> - `preserve` — use when the selected reusable template ships `native_structure.json` + `source_template.pptx`. Add both project-relative rows below and map every page under `pptx_layouts`.
> - `flat` — diagnostic escape hatch. Do not lock this in a normal project; pass it on the CLI when comparing slide-local output.
+>
+> Preserve example:
+> ```
+> - mode: preserve
+> - source_template: templates/source_template.pptx
+> - native_structure: templates/native_structure.json
+> ```
## pptx_layouts
-> Emit this section only when `pptx_structure.mode` is `template`. Include exactly one row per generated page. Value format: `<layout_key> | <PowerPoint layout name>`.
+> Emit this section only when `pptx_structure.mode` is `template` or `preserve`. Include exactly one row per generated page. Value format: `<layout_key> | <PowerPoint layout name>`. Preserve mode uses exact keys/names from `native_structure.json` and the selected template SVG root.
>
> Example:
> ```
diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.md
index dbf84ea1..fac7c165 100644
--- a/skills/ppt-master/workflows/create-template.md
+++ b/skills/ppt-master/workflows/create-template.md
@@ -43,7 +43,7 @@ Branch by the type of reference source the user supplied. This step produces ana
| Type | What the user supplied | Tool / read path | Replication modes available |
|------|-------------------------|------------------|------------------------------|
-| **A** `.pptx` reference | A `.pptx` file path | `pptx_template_import.py` → `manifest.json` + `svg/master_*.svg` + `svg/layout_*.svg` + `svg/slide_*.svg` + `svg-flat/slide_*.svg` + `assets/` | `standard` / `fidelity` / `mirror` |
+| **A** `.pptx` reference | A `.pptx` file path | `pptx_template_import.py` → `manifest.json` + `native_structure.json` + `source_template.pptx` + layered/flat SVGs + `assets/` | `standard` / `fidelity` / `mirror` |
| **B** Existing SVG assets | `projects/<x>/svg_output/`, `templates/layouts/<existing>`, or a loose `.svg` folder | `ls` + `Read` each `*.svg`; plus `design_spec.md` / `spec_lock.md` if present | `standard` / `fidelity` (AI visual clustering) / `mirror` (direct 1:1 copy) |
| **C** Image / visual references | Screenshot folder, single image, PDF pages | `ls` + `Read` each file (multimodal visual recognition) | `standard` only |
| **D** No reference source | Verbal description only ("McKinsey style", "tech blue", "dark minimal") | — | `standard` only |
@@ -66,6 +66,8 @@ python3 skills/ppt-master/scripts/pptx_template_import.py "<reference_template.p
This produces, in one workspace:
- `manifest.json` — single source of truth: slide size, theme colors, fonts, per-master theme summaries, asset inventory, placeholder metadata, SVG file paths, per-slide / per-layout / per-master metadata, page-type candidates
+- `native_structure.json` — portable machine contract: stable master/layout keys, source package parts, layout picker names, placeholder type/index/geometry, source hash, and a preserve-vs-rebuild recommendation
+- `source_template.pptx` — byte-preserved source package paired with `native_structure.json`; required for downstream `pptx_structure.mode: preserve`
- `summary.md` — short human-readable digest derived from manifest.json (for quick scanning only)
- `assets/` — extracted reusable image assets; `manifest.json` owns the asset-name mapping and SVG `href` values reuse that mapping
- `svg/` — **primary view** (layered template view):
@@ -102,16 +104,18 @@ The source SVGs in `<import_workspace>/svg/` / `<import_workspace>/svg-flat/` ar
**Read order during analysis** (read everything below before composing Step 2):
1. `manifest.json` (factual metadata: slide size, theme, assets, layouts, masters, slide page-types)
-2. cleaned `svg/master_*.svg` and `svg/layout_*.svg` — read these **before** any slide SVG; they show the deck's shared visual language (background, headers, footers, decorative bars). This is what the new template's fixed structure should adapt from.
-3. `svg/inheritance.json` — confirms which slide uses which layout/master
-4. exported `assets/`
-5. cleaned slide SVG references from `svg/` — content unique to each slide; consult after the master/layout language is understood
-6. `summary.md` only as a quick orientation aid
-7. user-provided screenshots or the original PPTX only for visual cross-checking
+2. `native_structure.json` (stable native keys, source layout names/placeholders, relationship completeness, recommended structure strategy)
+3. cleaned `svg/master_*.svg` and `svg/layout_*.svg` — read these **before** any slide SVG; they show the deck's shared visual language (background, headers, footers, decorative bars). This is what the new template's fixed structure should adapt from.
+4. `svg/inheritance.json` — confirms which slide uses which layout/master
+5. exported `assets/`
+6. cleaned slide SVG references from `svg/` — content unique to each slide; consult after the master/layout language is understood
+7. `summary.md` only as a quick orientation aid
+8. user-provided screenshots or the original PPTX only for visual cross-checking
Interpretation rule (carries forward into Steps 2 and 4):
- `manifest.json` is the source of truth for slide size, theme colors, fonts, background inheritance, reusable asset inventory, unique layout/master structure, and slide reuse relationships
+- `native_structure.json` is the source of truth for native PowerPoint identity: stable layout keys, picker names, parent masters, placeholder types/indices, and the source-package hash
- `summary.md` is a quick scan; never treat it as the canonical fact source — go back to `manifest.json` if anything is unclear
- exported `assets/` are the canonical reusable image pool — `<image>` references in `svg/` already point at these files directly
- exported `icons/*.svg` are the canonical reusable vector illustration pool, but they are **not** part of the default read set. Read the cleaned SVGs and `*_vector_asset_inventory.json` first; open a specific icon SVG only when the cleaned page or inventory shows that the extracted asset is relevant to the current design decision. This is what makes the SVG work surface smaller.
@@ -133,6 +137,7 @@ Before composing Step 2, extract the template's reusable norms from the previous
| 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 | `native_structure.json` strategy, masters/layouts, picker names, placeholder type/index, source slide mapping | Preserve contract when reusable; otherwise rebuild one master plus semantic layouts |
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.
@@ -204,6 +209,7 @@ Compose a single message that surfaces every Required brief item to the user, **
| Theme mode | Recommended localized mode with English ID, plus available modes such as `light` / `dark` / `mixed` with localized explanations |
| Canvas format | Recommended canvas, plus other supported formats from [`canvas-formats.md`](../references/canvas-formats.md) that fit the source aspect ratio or user intent. Always show the concrete pixel size and `viewBox`; do not treat two same-ratio formats such as `ppt169` (`1280x720`) and `banner` (`1920x1080`) as interchangeable. |
| Replication mode | Recommended localized mode with English ID, plus all modes available for the current input type; list forbidden modes for type C / D as unavailable with localized reasons |
+| Native structure strategy | For type A, show the `native_structure.json` recommendation and both choices: preserve source package (`preserve`) or rebuild explicit layouts (`template`). `mirror` cannot use preserve because its flat SVGs do not identify inherited layers. |
| Visual fidelity for fixed pages | Recommended localized choice with English ID, plus both `literal` / `adapted` options when applicable |
| Asset bundling | Recommended included assets, plus excluded candidate assets with a one-line reason when reference assets exist |
@@ -219,6 +225,7 @@ Items to surface:
| Theme mode | Yes | A: `[fact]` from `manifest.json` background colors. B: `[fact]` from SVG `fill`. C: `[suggested]` from visual estimate. D: `[decision]` |
| Canvas format and dimensions | Yes | 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: `[decision]`, default `ppt169` (`1280x720`, `0 0 1280 720`) |
| Replication mode | Yes | `[decision]` — `standard` always available; `fidelity` and `mirror` available for type A (canonical, manifest-anchored) and type B (AI visual clustering / direct 1:1 copy — see Step 1 caveats); reject `fidelity` / `mirror` upfront for type C / D |
+| Native structure strategy | Type A only | `[fact]` recommendation from `native_structure.json.strategy`; preserve (`preserve`) when the source graph is complete/reusable, rebuild (`template`) when minimal/incomplete. Force rebuild for `mirror`. |
| Visual fidelity for fixed pages | Yes for `standard` / `fidelity` when reference exists; **N/A for `mirror`** (mirror is implicitly literal) | `[decision]` — `literal` (preserve original geometry / decoration / sprite crops as-is; for cover / chapter / ending especially) or `adapted` (use the reference for tone/structure but allow design evolution). Different page types may take different settings |
| Basic template norms | Yes when reference exists | `[fact]` / `[suggested]` — layout grammar, image system, density rhythm, page roster semantics, and asset policy extracted in Step 1 |
| Reference source | Optional | already known if Step 1 ran |
@@ -232,10 +239,11 @@ For type A, also include in this message:
- the exact cleaned `master_*.svg`, `layout_*.svg`, `slide_*.svg` filenames you read from the layered `svg/` view (proof of the hard read gate)
- a one-line summary of the master / layout structure you extracted
+- the native structure recommendation, including master/layout counts, multi-master status, and reason codes
The user replies with corrections, additions, or "all good".
-> **Persist the brief into `design_spec.md`**. When the Template_Designer writes `design_spec.md` in Step 4, declare a YAML frontmatter block at the top with the confirmed brief (`template_id`, `category`, `summary`, `keywords`, `primary_color`, `canvas_format`, `canvas_width`, `canvas_height`, `canvas_viewbox`, `source_viewbox`, `replication_mode`, etc.). `register_template.py` reads this in Step 6, so the brief flows directly into the index without the AI re-deriving it from prose. See Step 6 for the recommended frontmatter shape.
+> **Persist the brief into `design_spec.md`**. When the Template_Designer writes `design_spec.md` in Step 4, declare a YAML frontmatter block at the top with the confirmed brief (`template_id`, `category`, `summary`, `keywords`, `primary_color`, `canvas_format`, `canvas_width`, `canvas_height`, `canvas_viewbox`, `source_viewbox`, `replication_mode`, `native_structure_mode`, etc.). `register_template.py` reads this in Step 6, so the brief flows directly into the index without the AI re-deriving it from prose. See Step 6 for the recommended frontmatter shape.
---
@@ -283,6 +291,7 @@ If the input source is type A, pass the following internal package to the role:
- finalized brief from Step 3
- `manifest.json`
+- `native_structure.json` and `source_template.pptx`
- `summary.md` (orientation only)
- exported `assets/`
- `*_vector_asset_inventory.json`, when the vector readability pass extracted assets; do not bulk-read `icons/*.svg`
@@ -295,6 +304,8 @@ For type D, pass only the finalized brief.
The role uses the analysis bundle to anchor objective facts such as theme colors, fonts, reusable backgrounds, common branding assets, layout grammar, image-placement rules, density rhythm, and page-slot semantics, then rebuilds the final SVG templates in a simplified, maintainable form.
+**Native structure strategy**: When the confirmed strategy is `preserve`, copy `native_structure.json` and `source_template.pptx` unchanged into the final template directory. Author every template SVG with the source layout key/name on the root, source master/layout visuals as preview layers, and slide content as source-compatible placeholder markers. When the strategy is `template`, do not copy the native pair; reconstruct one master plus semantic layouts through the explicit metadata contract. Mirror mode always takes this rebuild/baseline path because flat slides do not retain layer ownership.
+
**Apply the visual-fidelity decision from Step 3**: pages marked `literal` (typically cover / chapter / ending) must reproduce the reference's geometry, decoration, and sprite-sheet crops as-is — "simplified, maintainable form" applies only to genuinely redundant structure, not to load-bearing layout. Pages marked `adapted` may use the reference for tone and structural rhythm but evolve the design.
**Sprite-sheet preservation (do NOT simplify away)**: PPTX-exported assets are often sprite sheets — a single tall/large image referenced from multiple slides, each cropping a different region via nested `<svg ... viewBox="...">` wrappers around `<image width="1" height="1">`. This nesting is **load-bearing geometry**, not redundant structure. When rebuilding, preserve the exact `viewBox` crop and the outer `<svg>` placement for every image; do not flatten to a single `<image>` with direct `x/y/width/height`. Verify by sampling: if any asset's pixel dimensions don't match the on-page display aspect, it is a sprite and the wrapper must stay.
@@ -320,7 +331,7 @@ Mirror mode does **not** invoke the "reconstruct into clean SVG" pathway. The sp
1. `design_spec.md` — **personality only**. Required sections: Template Overview, Color Scheme, Signature Design Elements, Page Roster (matching the actual SVG files on disk). Skip Typography / Assets / Placeholder Overrides when they would just restate defaults. Declare brief frontmatter for `register_template.py`. **Do not** restate generic SVG constraints, layout pattern libraries, font-size ratio bands, the canonical placeholder table, or content methodology — those are sourced from `shared-standards.md` / `design_spec_reference.md` / `strategist.md` and are already in the downstream reader's context. Full scope rule and skeleton: [template-designer.md §1](../references/template-designer.md#1-must-generate-design_specmd).
2. Page roster — see [Page Roster](../references/template-designer.md#page-roster) for `standard` / `fidelity` / `mirror` mode rosters, variant naming, and TOC handling
3. Placeholder vocabulary — pages should adopt the conventional names (`{{TITLE}}`, `{{CONTENT_AREA}}`, ...) when they fit. Full reference: [Placeholder Reference](../references/template-designer.md#4-placeholder-reference-canonical-convention-overridable-per-template). When a template style legitimately needs different vocabulary (consulting → `{{KEY_MESSAGE}}`, branded cover → `{{BRAND_LOGO}}`), declare a `placeholders:` block in `design_spec.md` frontmatter so the registrar and quality checker treat it as the template's authoritative contract. **Avoid** one-off indexed families such as `{{CHAPTER_01_TITLE}}` — use the indexed TOC pattern instead.
- - `{{...}}` placeholders are the authoring contract used to generate final slide content; they are not PowerPoint `p:ph` objects. If the downstream deliverable must expose reusable PowerPoint layouts, lock `pptx_structure.mode: template`, map every page under `pptx_layouts`, and make the final generated slide SVGs follow the explicit `data-pptx-layout` / `data-pptx-layer` / `data-pptx-placeholder` contract in [shared standards](../references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export).
+ - `{{...}}` placeholders are the authoring contract used to generate final slide content; they are not PowerPoint `p:ph` objects. For reconstructed layouts, use `pptx_structure.mode: template`. For a template package carrying `native_structure.json` + `source_template.pptx`, use `mode: preserve`. Both modes require `pptx_layouts` and explicit root/layer/placeholder metadata; preserve-mode placeholders retain the source `data-pptx-placeholder-idx`.
4. Template assets (optional) — Logos / PNG / JPG / reference SVG bundled with the template package
---
@@ -344,6 +355,7 @@ python3 skills/ppt-master/scripts/svg_quality_checker.py "skills/ppt-master/temp
- skip `spec_lock.md` drift checks (templates do not ship a spec_lock)
- enforce roster ↔ `design_spec.md` consistency as **errors** (orphan files / missing files break the target kind's index)
- emit advisory **warnings** when a page lacks a conventional placeholder — these are hints, not failures. Declare a `placeholders:` block in `design_spec.md` frontmatter to silence them when your template intentionally uses a different vocabulary
+- validate `native_structure.json` and `source_template.pptx` as an inseparable pair, including source hash, package layout parts, SVG layout keys/names, and placeholder compatibility
**Checklist**:
@@ -355,6 +367,7 @@ python3 skills/ppt-master/scripts/svg_quality_checker.py "skills/ppt-master/temp
- [ ] SVG `viewBox` matches the declared canvas dimensions, not just the aspect ratio (for `ppt169`: `0 0 1280 720`; for `banner`: `0 0 1920 1080`); `width` / `height`, if written, equal it
- [ ] Placeholder names follow the canonical convention where applicable; templates with intentionally different vocabularies (e.g. `{{KEY_MESSAGE}}` instead of `{{PAGE_TITLE}}`) should declare a `placeholders:` frontmatter block to silence advisory warnings
- [ ] Asset files referenced by SVGs actually exist in the template package
+- [ ] When native strategy is `preserve`, both `native_structure.json` and `source_template.pptx` exist; every SVG root references a contract layout key/name and every placeholder uses a compatible source type/index
- [ ] If any SVG references an extracted vector `data-icon`, the corresponding SVG asset exists directly under the package's `icons/` directory; do not add a separate illustration embedding script
- [ ] 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: file count equals source page count (type A: `ls templates/<kind_dir>/<id>/*_*.svg | wc -l` matches the cleaned flat `<import_workspace>/svg-flat/slide_*.svg | wc -l`; type B: matches the source SVG count); filenames follow the `<NNN>_<page_type>.svg` convention; **no `{{...}}` placeholder strings appear in any copied SVG** (`grep -l "{{" templates/<kind_dir>/<id>/*.svg` should return nothing — if the type B source itself contains placeholders, the user should be in `standard` mode, not `mirror`); §V Page Roster in `design_spec.md` lists every emitted file with a one-line description of what the page contains and what content slot it suits
@@ -402,6 +415,10 @@ The index file is a **discovery index** — it lets the AI answer "what template
> source_canvas_width: 1280
> source_canvas_height: 720
> source_viewbox: "0 0 1280 720"
+> # Type-A preserve strategy only; omit all three rows for rebuilt templates.
+> native_structure_mode: preserve
+> native_structure: native_structure.json
+> source_template: source_template.pptx
> page_count: 5
> primary_color: "#005587"
> ---