Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(roundtrip): enforce a semantic SVG workspace contract

hugohe34a892b595d1d
diff --git a/docs/faq.md b/docs/faq.md
index 96d1e985..7c68d448 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -485,7 +485,7 @@ You don't need to supply every detail upfront — the AI agent will ask follow-u
**Step 3 — Wait for the Result**
-The AI agent will handle the rest — analyzing your references, writing the kind-specific specification, building structured layout definitions only for Layout/Deck, and validating the workspace. Brand/Style never create a preview PPTX; Layout/Deck generate `exports/<id>_template_preview.pptx` on request and require it for multiple Masters. Both scopes require `templates/`; Brand/Layout/Deck may use package-owned `images/` and `icons/`, while Style contributes only its Design Spec. Library scope writes a bare `templates/design_spec.md` under `skills/ppt-master/templates/<kind>/<id>/` and registers it; project scope writes `templates/design_spec.<kind>.<id>.md` under `projects/<name>/` and skips registration, allowing one contribution of every kind to coexist. Layout owns the active SVG roster when Layout and Deck are both present. Empty optional directories are omitted. Give that workspace root to Step 3; a project root contributes all of its specs atomically, and installation never copies `exports/`. A compatible legacy-flat Brand/Layout/Deck workspace remains readable only when it satisfies the current kind contract; Layout/Deck also require current structured SVGs. Style has no legacy-flat form, and semantic-legacy packages must be replaced through `create-template` rather than upgraded in place.
+The AI agent will handle the rest — analyzing your references, writing the kind-specific specification, building structured layout definitions only for Layout/Deck, and validating the workspace. Brand/Style never create a preview PPTX; Layout/Deck generate `exports/<id>_template_preview.pptx` on request and require it for multiple Masters. Both scopes require `templates/`; Brand/Layout/Deck may use package-owned `images/` and `icons/`, while Style contributes only its Design Spec. Library scope writes a bare `templates/design_spec.md` under `skills/ppt-master/templates/<kind>/<id>/` and registers it; project scope writes `templates/design_spec.<kind>.<id>.md` under `projects/<name>/` and skips registration, allowing one contribution of every kind to coexist. Layout owns the active SVG roster when Layout and Deck are both present. Empty optional directories are omitted. Give that workspace root to Step 3; a project root contributes all of its specs atomically, and installation never copies `exports/`. Older flat or semantic-legacy packages are reference inputs only and must be rebuilt through `create-template` before Generate can select them.
> **Tip**: The more specific you are about the style and use case, the better the generated template will match your expectations.
diff --git a/docs/technical-design.md b/docs/technical-design.md
index b956e2cb..19992cf0 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -361,7 +361,7 @@ lifecycle is:
| `sources/` | archived originals, normalized Markdown, and converter companion files |
| `analysis/` | machine-extracted facts: PPTX intake bundles and regenerated image analysis |
| `images/` | single runtime image pool for user, extracted, web, AI, sliced, and EMF/WMF assets |
-| `icons/` | project-local icon set copied by `icon_sync.py`; global library fallback at export exists only for legacy compatibility |
+| `icons/` | project-local icon set copied by `icon_sync.py` or supplied by the active workspace; preview, validation, finalization, and export resolve only complete `library/name` references under this root |
| `templates/` | copied template specs / SVG references / non-image template assets |
| `svg_output/` | the only hand-authored SVG source directory |
| `svg_final/` | mandatory normal-flow derived visual-preview SVGs; supported bitmap/SVG resources are inlined when possible, while EMF/WMF retain an external-reference exception; used for IDE/browser preview or manual insertion as SVG pictures |
@@ -427,13 +427,12 @@ remain valid, and an exact path matching a registered canonical root may be
displayed as `library`; an unregistered root remains `explicit`. Current
library workspaces resolve `templates/design_spec.md`, while project roots
resolve every `templates/design_spec.<kind>.<id>.md`; the server parses every
-explicit root's real kinds, while the source label remains provenance only. Compatible flat Brand/Layout/Deck
-packages may resolve direct `design_spec.md` only when they satisfy the current
-kind contract, including current structured SVGs for Layout/Deck. Style has no
-legacy-flat form. A free-form style brief remains ordinary Stage-2 input and
-does not activate a Style workspace. Directory shape never authorizes structure
-migration. A package with legacy Master/Layout/placeholder semantics must be
-replaced by a newly created template workspace before Step 3.
+explicit root's real kinds, while the source label remains provenance only.
+Flat-root packages are not template workspaces. A free-form style brief remains
+ordinary Stage-2 input and does not activate a Style workspace. Directory shape
+never authorizes structure migration. A package with legacy
+Master/Layout/placeholder semantics must be replaced by a newly created
+template workspace before Step 3.
All current Brand/Style/Layout/Deck packages use one workspace routing contract. Brand and Style workspaces omit the SVG roster; empty optional directories are omitted:
@@ -807,6 +806,8 @@ These direct routes share some analysis primitives with the main pipeline, but a
**Why imported and authored shape metadata are separate.** A lossless imported SVG may need native-shape metadata, hidden carriers, and preview fingerprints to recover an advanced PowerPoint shape. That representation stays immutable in the temporary analysis workspace as native-payload backing. `svg_authoring_view.py` creates the editable template-creation IR: lightweight SVGs with document-local source refs plus an `authoring_manifest.json` containing paths and initial hashes, not duplicated payload. `standard` / `fidelity` author project-canonical SVG and use the compact authored-preset group only for exact registered preset matches. Mirror materializes validated templates from the IR and rehydrates converter-supported metadata only for unchanged Slide-local/slot refs; fixed structural layers remain direct atoms, unsupported or edited objects keep their current SVG fallback, and IR-only refs do not enter final template SVGs.
+**Why PPTX round-trip uses a semantic workspace rather than a ZIP-shaped tree.** The editable page source is `authoring-svg-flat/`; PowerPoint image media, imported reusable vectors, cues, audio, video, notes, and opaque payloads live under `images/`, `icons/imported/`, `sounds/`, `audio/`, `video/`, `notes/`, and `native-payloads/`. The exact backing package stays at `sources/source.pptx`, structural and ownership contracts stay under `analysis/`, diagnostics stay under `validation/`, and published decks stay under `exports/`. This keeps authoring paths aligned with normal projects while `analysis/roundtrip_manifest.json` maps semantic files back to package ownership. Import and export use this one contract: root `source_template.pptx`, `native_structure.json`, `conversion-report.json`, and `assets/` are invalid rather than compatibility inputs.
+
**Why there is only one PPTX compiler route.** Native export reads authored SVGs and translates supported SVG elements into DrawingML shapes. The normal deck path reads `svg_output/`; when requested, create-template invokes the same structured compiler on validated template prototypes to produce `exports/<id>_template_preview.pptx` as review evidence. The project does not package whole-slide SVG media or alternate raster renderings into a second PPTX. `svg_final/` is still generated on every standard deck run, but it is only a derived visual-preview / SVG-picture artifact rather than a PPTX source; PowerPoint's manual Convert to Shape command remains outside the supported contract.
**Why structure is authored before visual generation on structured reuse routes.** Master and Layout are not post-processing discoveries. With `template_reuse_scope: mirror|layout`, the Strategist writes unique Master/Layout definitions and complete page assignments before SVG generation; the Executor writes those identities, fixed atoms, and slots while composing each page, and export only compiles declared structure. `template_reuse_scope: style`, free-design, and brand-only decks make the opposite trade: they stay on `mode: flat`, keep every object Slide-local, author no structure metadata, and receive only a clean project-owned Master/Blank-Layout shell at export. Legacy inputs may inform a new `create-template` workspace, but they never enter an in-place structure-upgrade route; neither generation mode triggers heuristic Master/Layout promotion or placeholder inference.
diff --git a/docs/templates-architecture.md b/docs/templates-architecture.md
index e76175d3..1c47a345 100644
--- a/docs/templates-architecture.md
+++ b/docs/templates-architecture.md
@@ -19,7 +19,7 @@
| **Layout** | `templates/layouts/<id>/` | Brand-neutral structure segment only: canvas / page structure / semantic text roles / page types / SVG roster | No brand identity and no recurring communication application | `workflows/create-template/create-layout.md` |
| **Deck** | `templates/decks/<id>/` | A recurring presentation family: descriptive application context + integrated identity + structure | — | `workflows/create-template/create-deck.md` |
-Every newly created Layout/Deck SVG is a complete preview with root Master/Layout key and picker names, direct atomic Master/Layout elements, and top-level semantic slot groups. A normal slot has positive design-zone bounds and exactly one compatible carrier; composite `object` regions use explicit proxy binding, and zero-slot Layouts are valid. These specialized markers are authoritative; minimal `data-pptx-role` hints are added only for structural page-frame behavior they cannot express. Create Template derives `standard` / `fidelity` / `mirror` internally from the natural-language intent and source evidence. Authored strategies create new SVGs and structure; mirror materializes validated source facts. Strategist later derives strict/adaptive exporter behavior from the actual prototypes and current content. None of these implementation values is a required user choice. A legacy-flat Brand/Layout/Deck directory with `design_spec.md` at its root remains readable only when it satisfies the current kind contract; Style has no legacy-flat form. Semantic-legacy packages must be replaced by a newly created template workspace; they are never upgraded in place.
+Every newly created Layout/Deck SVG is a complete preview with root Master/Layout key and picker names, direct atomic Master/Layout elements, and top-level semantic slot groups. A normal slot has positive design-zone bounds and exactly one compatible carrier; composite `object` regions use explicit proxy binding, and zero-slot Layouts are valid. These specialized markers are authoritative; minimal `data-pptx-role` hints are added only for structural page-frame behavior they cannot express. Create Template derives `standard` / `fidelity` / `mirror` internally from the natural-language intent and source evidence. Authored strategies create new SVGs and structure; mirror materializes validated source facts. Strategist later derives strict/adaptive exporter behavior from the actual prototypes and current content. None of these implementation values is a required user choice. Generate accepts only the current nested workspace contract; older flat or semantic-legacy packages must be rebuilt through Create Template and are never upgraded in place.
The four are **parallel reusable-rule bundles**, not PowerPoint package-object types. In library scope, the physical directory and the frontmatter `kind` field correspond one-to-one:
@@ -479,11 +479,8 @@ exact root starts in template mode. Exactly one supplied root is preselected,
while multiple roots remain unselected candidates. A bare template/brand name
or style phrase never resolves to or preselects a workspace. For every selected
root, the post-confirmation apply stage resolves either one library bare spec or
-all project-qualified specs; for directory-shape compatibility, it also accepts
-a legacy-flat Brand/Layout/Deck root containing
-`<workspace>/design_spec.md` when the package satisfies its current kind
-contract. Layout/Deck additionally require current structured SVGs; Style has
-no flat form. Packages using legacy semantics such as
+all project-qualified specs. Flat-root packages are not template workspaces.
+Packages using legacy semantics such as
`native_structure_mode: template`, missing Master identity, direct atomic
placeholders, or distillation-era markers are rejected; `create-template` must
produce a new workspace before generation continues. The `kind` field decides
diff --git a/docs/templates-guide.md b/docs/templates-guide.md
index c52bcbea..20313c66 100644
--- a/docs/templates-guide.md
+++ b/docs/templates-guide.md
@@ -101,7 +101,7 @@ Stage 2 then compares the confirmed communication contract with that installed
state; `template_application` describes **how** to use it and never chooses
**which** template to use.
-> **Compatibility preflight:** Step 3 also accepts a legacy-flat Brand/Layout/Deck workspace with `design_spec.md` directly at the supplied root when it satisfies the current kind contract. Layout/Deck additionally require current structured SVGs; Style has no flat form. Former atomic-placeholder, unmapped Master/Layout, and other semantic-legacy packages are rejected; run `create-template` to create a new workspace, then generate new structured pages from that workspace. Nothing upgrades the old package in place.
+> **Current-workspace preflight:** Step 3 accepts only a workspace root exposing its Design Spec under `templates/`. Flat-root, former atomic-placeholder, unmapped Master/Layout, and other semantic-legacy packages are rejected; run `create-template` to create a new workspace, then generate new structured pages from that workspace. Nothing upgrades the old package in place.
### What does NOT select a template automatically
diff --git a/docs/zh/faq.md b/docs/zh/faq.md
index 40b2a0e2..f20642f3 100644
--- a/docs/zh/faq.md
+++ b/docs/zh/faq.md
@@ -434,7 +434,7 @@ Create Template 会先确认简报,再写入已注册、可发现的 `library`
**第三步 — 等待完成**
-AI 代理会自动完成后续工作——分析参考、写入 kind 专属规范,仅为 Layout/Deck 构建结构定义,并验证工作区。Brand/Style 不生成预览 PPTX;Layout/Deck 可按请求生成 `exports/<id>_template_preview.pptx`,多 Master 时必须生成。两种范围都要求 `templates/`;Brand/Layout/Deck 可使用包自有 `images/` 和 `icons/`,Style 只贡献自己的 Design Spec。`library` 在 `skills/ppt-master/templates/<kind>/<id>/` 写入裸 `templates/design_spec.md` 并完成全局注册;`project` 在 `projects/<name>/` 写入 `templates/design_spec.<kind>.<id>.md` 并跳过注册,四种 kind 均可各自共存一份;Layout 与 Deck 同时存在时,Layout 拥有有效 SVG roster。空的可选目录直接省略。把这个工作区 root 交给 Step 3 时,项目 root 会原子贡献其中全部 spec,安装不会复制 `exports/`。兼容的旧平铺 Brand/Layout/Deck 工作区只有在满足当前 kind 合同时才可读取,Layout/Deck 还必须满足当前 structured SVG 合同;Style 不存在旧平铺形态,语义旧包必须通过 `create-template` 替换,不能原地升级。
+AI 代理会自动完成后续工作——分析参考、写入 kind 专属规范,仅为 Layout/Deck 构建结构定义,并验证工作区。Brand/Style 不生成预览 PPTX;Layout/Deck 可按请求生成 `exports/<id>_template_preview.pptx`,多 Master 时必须生成。两种范围都要求 `templates/`;Brand/Layout/Deck 可使用包自有 `images/` 和 `icons/`,Style 只贡献自己的 Design Spec。`library` 在 `skills/ppt-master/templates/<kind>/<id>/` 写入裸 `templates/design_spec.md` 并完成全局注册;`project` 在 `projects/<name>/` 写入 `templates/design_spec.<kind>.<id>.md` 并跳过注册,四种 kind 均可各自共存一份;Layout 与 Deck 同时存在时,Layout 拥有有效 SVG roster。空的可选目录直接省略。把这个工作区 root 交给 Step 3 时,项目 root 会原子贡献其中全部 spec,安装不会复制 `exports/`。旧平铺或语义旧包只能作为参考输入,必须通过 `create-template` 重建为当前工作区后才能被 Generate 选择。
> **提示**:对风格和使用场景描述得越具体,生成的模板就越符合你的预期。
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index 7c75f230..6566f38b 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -315,7 +315,7 @@ profile 省略规划产物与 `svg_final/`,但项目中仍可按需存在已
| `sources/` | 原件归档、归一化 Markdown、转换器伴随文件 |
| `analysis/` | 机器抽取事实:PPTX intake bundle 与按需重算的图片分析 |
| `images/` | 单一运行时图片池:用户图、抽取图、网络图、AI 图、切片图、EMF/WMF |
-| `icons/` | 由 `icon_sync.py` 复制的项目级图标集;导出时的全局库回退仅用于 legacy compatibility |
+| `icons/` | 由 `icon_sync.py` 复制或由当前工作区提供的项目级图标集;预览、校验、后处理与导出只解析此根目录下完整的 `library/name` 引用 |
| `templates/` | 复制进项目的模板 spec / SVG reference / 非图片模板资产 |
| `svg_output/` | 唯一手写 SVG 源目录 |
| `svg_final/` | 强制派生的视觉预览 SVG;尝试内联受支持位图 / SVG,保留 EMF/WMF 外链例外;服务 IDE / 浏览器,也可手动作为 SVG 图片插入 PowerPoint |
@@ -366,7 +366,7 @@ PPT Master 不只服务 PPT——同一套 SVG → DrawingML 流水线还能产
**为什么保留自由设计选项。** 模板是地板,但很容易变成天花板:它会把整个 deck 锁进模板自有的视觉惯用语,无视内容本身想要怎样被呈现。自由设计的布局从源内容的结构推导而来,而不是从一套固定语法套上去——视觉节奏跟着内容走,而不是跟内容打架。约束模式在窄场景里确实更好(品牌锁定的 deck、强类型场景如学术答辩或政府报告),最终选择仍由用户完成。
-**精确选择,不做语义匹配。** 像 `presentation_core` 这样的裸名字、品牌提及,或“麦肯锡风格”这类风格短语,永远不会 fuzzy-match 到目录。默认页面只从四个 `*_index.json` 列出已注册 Brand/Style/Layout/Deck;聊天发现也读取同一组索引并返回精确 root。显式路径仍有效;若它与某个已注册 canonical root 精确相同,可显示为 `library`,未注册 root 仍是 `explicit`。Library 工作区解析 `templates/design_spec.md`,project root 解析全部 `templates/design_spec.<kind>.<id>.md`;服务端解析每个 explicit root 的真实 kind 集合,来源标签本身不参与优先级。自由文字风格说明仍只是 Stage 2 输入,不会启用 Style 工作区。旧平铺 Brand/Layout/Deck 目录只有在满足当前 kind 合同时,才兼容从根目录读取 `design_spec.md`;Layout/Deck 还必须满足当前 structured SVG 合同。Style 不存在旧平铺形态。目录形态从不授权结构迁移;带旧 Master/Layout/placeholder 语义的包必须先替换为新建的模板工作区。
+**精确选择,不做语义匹配。** 像 `presentation_core` 这样的裸名字、品牌提及,或“麦肯锡风格”这类风格短语,永远不会 fuzzy-match 到目录。默认页面只从四个 `*_index.json` 列出已注册 Brand/Style/Layout/Deck;聊天发现也读取同一组索引并返回精确 root。显式路径仍有效;若它与某个已注册 canonical root 精确相同,可显示为 `library`,未注册 root 仍是 `explicit`。Library 工作区解析 `templates/design_spec.md`,project root 解析全部 `templates/design_spec.<kind>.<id>.md`;服务端解析每个 explicit root 的真实 kind 集合,来源标签本身不参与优先级。自由文字风格说明仍只是 Stage 2 输入,不会启用 Style 工作区。根目录平铺的包不属于模板工作区;目录形态从不授权结构迁移。带旧 Master/Layout/placeholder 语义的包必须先替换为新建的模板工作区。
当前 Brand/Style/Layout/Deck 都采用同一工作区路由合同;Brand 与 Style 不含 SVG roster,空的可选目录直接省略:
diff --git a/docs/zh/templates-architecture.md b/docs/zh/templates-architecture.md
index 0fcbadf0..10323413 100644
--- a/docs/zh/templates-architecture.md
+++ b/docs/zh/templates-architecture.md
@@ -19,7 +19,7 @@
| **Layout** | `templates/layouts/<id>/` | 仅品牌中立的结构段:canvas / page structure / 语义文字角色 / page types / SVG roster | 不写品牌身份,也不拥有可重复沟通场景 | `workflows/create-template/create-layout.md` |
| **Deck** | `templates/decks/<id>/` | 一类可重复演示:描述性应用语境 + 一体化身份与结构 | —— | `workflows/create-template/create-deck.md` |
-每张新建的 Layout/Deck SVG 都是完整预览,并在根节点声明 Master/Layout key 与选择器名称;固定 Master/Layout 视觉是直接原子元素;语义槽位是顶层 group。普通槽位必须有正数设计区域 bounds 和恰好一个兼容 carrier;复合 `object` 区域走显式 proxy 绑定,零槽 Layout 也合法。这些专用标记具有最高优先级;最小 `data-pptx-role` 只补充它们无法表达的页面框架行为。Create Template 根据自然语言意图与来源证据在内部推导 `standard` / `fidelity` / `mirror`;Strategist 再根据真实原型与当前内容推导 strict/adaptive 导出行为。这些实现值都不是用户必选项。仅 Brand/Layout/Deck 的旧式平铺目录可在满足当前 kind 合同时继续读取;Style 没有平铺兼容形态。带旧结构语义的包必须替换为新建模板工作区,不能原地升级。
+每张新建的 Layout/Deck SVG 都是完整预览,并在根节点声明 Master/Layout key 与选择器名称;固定 Master/Layout 视觉是直接原子元素;语义槽位是顶层 group。普通槽位必须有正数设计区域 bounds 和恰好一个兼容 carrier;复合 `object` 区域走显式 proxy 绑定,零槽 Layout 也合法。这些专用标记具有最高优先级;最小 `data-pptx-role` 只补充它们无法表达的页面框架行为。Create Template 根据自然语言意图与来源证据在内部推导 `standard` / `fidelity` / `mirror`;Strategist 再根据真实原型与当前内容推导 strict/adaptive 导出行为。这些实现值都不是用户必选项。Generate 只接受当前嵌套工作区合同;旧平铺或带旧结构语义的包必须通过 Create Template 重建,不能原地升级。
四者是**四种并列的可复用规则包**,不是 PowerPoint 包对象类型。在全局库范围内,物理目录与前置元数据中的 `kind` 字段双向对齐:
@@ -418,7 +418,7 @@ Default Generate 的 [Step 3](../../skills/ppt-master/workflows/generate-pptx.md
普通请求默认自由设计并收起详细控件;明确要求使用模板或提供任意精确 root 时
默认展开模板模式。只提供一个 root 时会预选,多 root 仍只作为未选候选。裸
模板/品牌名称或风格词不会解析或预选工作区。对于每个已选 root,确认后的
-apply 阶段解析一份 library 裸 spec 或全部 project 限定名 spec;为兼容目录形态,也接受根目录直接包含 `<workspace>/design_spec.md`、且满足当前 kind 合同的旧式平铺 Brand/Layout/Deck 工作区。Layout/Deck 还必须带有当前 structured SVG;Style 没有平铺形态。若包仍使用 `native_structure_mode: template`、缺 Master 身份、原子 placeholder 或蒸馏时代标记等旧语义,apply 阶段必须拒绝;先由 `create-template` 产出新工作区,再继续生成。`kind` 字段决定**AI 如何处理已选路径**:
+apply 阶段解析一份 library 裸 spec 或全部 project 限定名 spec;根目录直接包含 `<workspace>/design_spec.md` 的平铺包不是模板工作区。若包仍使用 `native_structure_mode: template`、缺 Master 身份、原子 placeholder 或蒸馏时代标记等旧语义,apply 阶段必须拒绝;先由 `create-template` 产出新工作区,再继续生成。`kind` 字段决定**AI 如何处理已选路径**:
| 用户路径指向 | Stage-1 确认后的 apply 行为(按 kind 分支)|
|---|---|
diff --git a/docs/zh/templates-guide.md b/docs/zh/templates-guide.md
index 10f8e26f..36674f0c 100644
--- a/docs/zh/templates-guide.md
+++ b/docs/zh/templates-guide.md
@@ -83,7 +83,7 @@ Layout 提供结构。指定地址最多选一个,并原子携带
`images/`、`icons/`。最终 Stage 2 再把已确认沟通契约与安装状态适配;
`template_application` 只描述**如何使用**,不负责决定**选哪个模板**。
-> **兼容性预检:** Step 3 也接受 `design_spec.md` 直接位于所给根目录、且满足当前 kind 合同的旧式平铺 Brand/Layout/Deck 工作区。Layout/Deck 还必须带有当前 structured SVG;Style 没有平铺形态。旧的原子 placeholder、未映射 Master/Layout 等语义旧包会被拒绝。先运行 `create-template` 创建新工作区,再从该工作区生成新的 structured 页面;不会原地升级旧包。
+> **当前工作区预检:** Step 3 只接受在 `templates/` 下提供 Design Spec 的工作区根目录。根目录平铺、旧的原子 placeholder、未映射 Master/Layout 等语义旧包都会被拒绝。先运行 `create-template` 创建新工作区,再从该工作区生成新的 structured 页面;不会原地升级旧包。
### 什么**不会**自动选中模板
diff --git a/skills/ppt-master/references/artifact-ownership.md b/skills/ppt-master/references/artifact-ownership.md
index de38385e..8189eb3a 100644
--- a/skills/ppt-master/references/artifact-ownership.md
+++ b/skills/ppt-master/references/artifact-ownership.md
@@ -41,7 +41,7 @@ history, or resumable planning state. Context loss restarts the Quick run.
| `analysis/page-context/P<NN>.usage.json` | Derived optional context telemetry | Measured on-demand page-context size plus hashes of owning inputs/references | `page-context --record-usage` deterministically replaces only the invoked page's snapshot; `page-context-report` summarizes existing snapshots. Telemetry may be partial. Use token data to evaluate context cost, never as content or an execution contract. |
| `images/` | Runtime image pool | User, extracted, AI, web, slice, and EMF/WMF assets | Default Step 5 or Quick Generate resource preparation writes here; `analysis/image_analysis.csv` derives from current contents |
| `images/image_prompts.json`, `image_queries.json`, `image_sources.json` | Conditional resource contracts | AI/web execution status and provenance | Create only for a triggered path, including Quick. They guide preparation/attribution, never page design. |
-| `icons/` | Prepared project icon pool | Bundled icons copied by `icon_sync.py` plus user-provided, template, imported, or custom icon SVGs | SVG authoring may choose any icon in this project-local pool per page; `spec_lock.icons.inventory` indexes the default plan's curated synced bundled pool rather than assigning page usage or defining an exhaustive whitelist. Exporter global fallback is legacy compatibility only. |
+| `icons/` | Prepared project icon pool | Bundled icons copied by `icon_sync.py` plus user-provided, template, imported, or custom icon SVGs | SVG authoring may choose any icon in this project-local pool per page; `spec_lock.icons.inventory` indexes the default plan's curated synced bundled pool rather than assigning page usage or defining an exhaustive whitelist. Preview, finalization, checking, and export resolve only complete `library/name` references under this root. |
| `${SKILL_DIR}/templates/{brands,styles,layouts,decks}/*_index.json` | Library discovery indexes | The complete registered option source for Default Stage-1 template selection and chat listing | The UI server or chat branch reads these indexes only to populate the Stage-1 choice, after the communication recommendation is authored. Never scan kind directories to add options or use index summaries as Stage-1 planning evidence. Derive a library root from kind + entry id. Exact unregistered roots remain explicit inputs. Quick does not read the catalog. |
| `templates/` | Project template reference | Stage-1-confirmed non-free selection or Quick direct-input installed specs, one file per selected workspace, the effective structural SVG roster (Layout when present, otherwise Deck), and non-image assets | Default template-aware Strategist work from Stage 2 onward, Quick's current agent before direct authoring, and every later role read this project-local state only, never the library/external installation root. The active planner reads every installed template Design Spec and the effective structural SVG roster; Brand and Style are intentionally roster-free, and Deck structure is shadowed when Layout is present. Continuous Executor reuses that context; fresh Executor reads the Design Spec once and each selected complete SVG, when any, only before first use or after its SHA changes. |
| `templates/template_execution_manifest.json` (`v1`) + `templates/template_execution/*.text-slots.json` (`v2-min`) | Derived template index | Compact prototype/source-import summary plus per-prototype text-slot diagnostics; the sidecar integrity hash is tool-only | Materialization may publish these deterministic records, but page-context does not inject or require them and models do not read them during page authoring. The complete prototype SVG is the sole visual/template authority; never author from either JSON artifact. |
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index bbf6d9fb..28adf6fe 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -274,7 +274,7 @@ Format: `<index>_<page_name>.svg`. Use one roster-wide zero-padded index width s
Strategist chooses at most one primary bundled stylistic library and may select `simple-icons` alone or alongside it; Executor implements from the complete prepared project-local pool. Library details and selection rules: [`../templates/icons/README.md`](../templates/icons/README.md). This section defines placeholder syntax.
-> **Prepared-project boundary.** Any SVG already under `<project_path>/icons/<lib>/` is valid execution material, whether selected from a bundled library or supplied by the user, a template, or an import workflow. New authoring must resolve there. The global fallback in `finalize_svg.py embed-icons` is legacy compatibility, not permission for Executor to discover or use an unprepared global icon.
+> **Prepared-project boundary.** Any SVG under `<project_path>/icons/<lib>/` is valid prepared material. Authoring, preview, finalization, and export resolve only complete case-sensitive `library/name` references there; no global or template-source fallback exists.
> **Icon identifiers are case-sensitive filenames.** Every `data-icon` value must use the exact project-local relative basename (`tabler-outline/award`, never `tabler-outline/Award`). Strategist records its curated bundled pool in `spec_lock.md`; Executor need not add other already-prepared project-local icons to that inventory. Custom identifiers preserve the custom file's exact case; the pipeline never silently lowercases names.
diff --git a/skills/ppt-master/references/executor-image.md b/skills/ppt-master/references/executor-image.md
index bb111fd2..d665c7a5 100644
--- a/skills/ppt-master/references/executor-image.md
+++ b/skills/ppt-master/references/executor-image.md
@@ -24,7 +24,7 @@ Handle images by status; enum and lifecycle: [`svg-image-embedding.md`](svg-imag
**Reference syntax**: see [`svg-image-embedding.md`](svg-image-embedding.md).
-**Template-bundled images**: [`apply-template-workspace.md`](../workflows/stages/apply-template-workspace.md) copies them into project `images/`. Outside `mirror`, reference `../images/<name>` and never copy a template SVG's bare sibling href: the rendered page lives in `svg_output/`. `mirror` ([`executor-structured.md`](./executor-structured.md) §1.1) keeps hrefs verbatim; export resolves them against `images/`.
+**Template-bundled images**: [`apply-template-workspace.md`](../workflows/stages/apply-template-workspace.md) copies them into project `images/`. Every page, including `mirror`, must rebase the same bytes to exact `../images/<name>`; this transport rewrite is not a visual edit. Never retain a bare or source-template href: preview, validation, and export resolve the written path exactly.
**Default — active image integration (may override when plain placement is
stronger)**: Treat loaded [`image-layout-patterns.md`](./image-layout-patterns.md)
diff --git a/skills/ppt-master/references/executor-structured.md b/skills/ppt-master/references/executor-structured.md
index e498c12e..182c1608 100644
--- a/skills/ppt-master/references/executor-structured.md
+++ b/skills/ppt-master/references/executor-structured.md
@@ -55,7 +55,7 @@ When `spec_lock.md` records the AI-derived `template_reuse_scope: mirror`, Execu
1. **Per-page reference selection** — Strategist selects one mirror page per project page via `spec_lock.md page_layouts` (e.g., `P04: 015_content`). The basename is the mirror filename without extension; Strategist made this choice by reading `design_spec.md §V Page Roster` descriptions, not by guessing.
2. **Copy, don't fill** — use the retained full mirror SVG as the starting point, then edit slide-specific text in place. Preserve every non-text element and every `data-pptx-*` structure attribute verbatim. Do not reopen the same path + SHA merely because another page selects it.
3. **What you may edit** — decide the semantic slot mapping and replacement text only. Change only visible string values already carried by `<text>` and `<tspan>` nodes that express slide-specific content (title, body, captions, KPI labels, dates, page numbers). Keep the number, order, nesting relationship, and **all attributes** of every `<text>` / `<tspan>` node unchanged. Never merge or split nodes, move a string between nodes, add a new tspan, or delete an empty carrier. `svg_quality_checker.py` and export validate attributes, topology, and prototype hashes against the complete prototype internally.
-4. **What you must not touch** — element positions, sizes, fonts, colors, fills, strokes, gradients, **which image each `<image>` points at**, `<g>` grouping, sprite-sheet `<svg viewBox>` wrappers, decorative `<rect>` / `<path>` / `<circle>` / `<polygon>` shapes, `<use data-icon="...">` markers, embedded chart data structures. Mirror's value is preserving the source deck's visual identity — any geometric / decorative drift defeats the purpose. **The `href` path is not the image**: normalizing a bare `href="cover_bg.png"` to `href="../images/<name>"` (when Step 3 relocated the asset to `images/`) points at the *same* image and changes nothing visual — that is an allowed path fix, not a fidelity edit. Leaving the bare href as-is is also fine; the exporter and live preview resolve bare hrefs against `images/` either way.
+4. **What you must not touch** — element positions, sizes, fonts, colors, fills, strokes, gradients, **which image each `<image>` points at**, `<g>` grouping, sprite-sheet `<svg viewBox>` wrappers, decorative `<rect>` / `<path>` / `<circle>` / `<polygon>` shapes, `<use data-icon="...">` markers, embedded chart data structures. Mirror's value is preserving the source deck's visual identity — any geometric / decorative drift defeats the purpose. **The `href` path is not the image**: normalize a bare `href="cover_bg.png"` to the exact `href="../images/<name>"` when Step 3 relocates those same bytes to `images/`; this required transport rewrite changes nothing visual. Do not leave the bare href or point back into the source template. Preview, validation, and export resolve the written SVG-relative path exactly and never search another directory by basename.
5. **Content fit** — if the replacement needs a different number of text segments/items, do not merge/split nodes, drop sourced content, or restructure the grid. Report `warning: P<NN> content does not fit mirror reference <basename>; choose another prototype or change template_reuse_scope to layout/style`, then return to Strategist to select the prototype or scope and update the planning mappings.
6. **Visible text editing** — mirror SVGs may keep literal source text rather than `{{...}}` authoring markers. Edit values in place while retaining imported semantic `data-pptx-placeholder` identity and exact text topology.
7. **Output filename** — follow the standard project SVG naming convention (`<index>_<page_name>.svg` where `<index>` matches the project page index, not the mirror source index). The mirror filename is the *reference*, not the *output*.
diff --git a/skills/ppt-master/references/pptx-structure-interface.md b/skills/ppt-master/references/pptx-structure-interface.md
index 03e3587e..6a474c71 100644
--- a/skills/ppt-master/references/pptx-structure-interface.md
+++ b/skills/ppt-master/references/pptx-structure-interface.md
@@ -181,7 +181,7 @@ video or audio media from a decorative SVG group.
## 3. Legacy Template Input Boundary
-Existing structured/template projects or packages that carry `native_structure.json` / `source_template.pptx`, `pptx_structure.mode: baseline|template|preserve`, `layout_strategy`, `data-pptx-layout-kind`, `distilled` / `utility`, direct atomic placeholders, or an incomplete root Master identity are not generation/export inputs and are never upgraded in place. Create a separate current workspace through [`create-template`](../workflows/create-template.md). A project explicitly declaring `pptx_structure.mode: flat` is the current free-design/brand-only route and needs no conversion merely because it has no Master/Layout metadata.
+Existing structured/template projects or source-analysis packages that carry `analysis/native_structure.json` / `sources/source.pptx`, `pptx_structure.mode: baseline|template|preserve`, `layout_strategy`, `data-pptx-layout-kind`, `distilled` / `utility`, direct atomic placeholders, or an incomplete root Master identity are not generation/export inputs and are never upgraded in place. Create a separate current workspace through [`create-template`](../workflows/create-template.md). A project explicitly declaring `pptx_structure.mode: flat` is the current free-design/brand-only route and needs no conversion merely because it has no Master/Layout metadata.
| Available source | Allowed create-template behavior |
|---|---|
diff --git a/skills/ppt-master/references/strategist-template.md b/skills/ppt-master/references/strategist-template.md
index 0d2d4360..b65da7d0 100644
--- a/skills/ppt-master/references/strategist-template.md
+++ b/skills/ppt-master/references/strategist-template.md
@@ -12,7 +12,7 @@ Conditional extension for applying an installed Brand/Style/Layout/Deck workspac
**Template vs preset**: A style mention and a Style workspace are different inputs. Bare names and style words remain interpretive input and never resolve to a local path; only a selected and installed workspace activates the rules below. Every installed `<project_path>/templates/design_spec.<kind>.<id>.md` is a template-design source; read all of them. The presence of a `design_spec.style.*.md` file is what marks an active Direction / method segment. Whether a source root was labelled `library` or `explicit` is installation provenance only and never affects Stage-2 precedence.
-**Legacy template boundary**: A Layout/Deck template containing `native_structure.json`, `source_template.pptx`, missing root Master identity, direct atomic placeholders, or old `baseline` / `preserve` / distillation metadata is not a Generate Step 3 input. Create a current workspace through [`create-template`](../workflows/create-template.md), preferably from the original PPTX when native topology matters. Brand and Style are intentionally roster-free; never reject either for omitting SVG or Master identity. Do not mutate the input in place.
+**Source-analysis template boundary**: A Layout/Deck template containing `analysis/native_structure.json`, `sources/source.pptx`, missing root Master identity, direct atomic placeholders, or old `baseline` / `preserve` / distillation metadata is not a Generate Step 3 input. Create a current workspace through [`create-template`](../workflows/create-template.md), preferably from the original PPTX when native topology matters. Brand and Style are intentionally roster-free; never reject either for omitting SVG or Master identity. Do not mutate the input in place.
**No template-mode confirmation**: Never ask the user to select `template_reuse_scope`, `template_adherence`, `mirror`, `layout`, `style`, `strict`, or `adaptive`. These are internal execution values for the current exporter. The user communicates intent in natural language; explicit instructions such as “全部原样保留”, “从中选合适的页面”, “可以重组”, or “只参考视觉” are authoritative. Without an explicit instruction, Strategist decides.
diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.md
index bf147975..6de0558a 100644
--- a/skills/ppt-master/references/template-designer.md
+++ b/skills/ppt-master/references/template-designer.md
@@ -23,11 +23,11 @@ Generate reusable structured page templates inside the workspace selected by Cre
When the workflow provides a PPTX reference source, the effective input package comes from the unified `pptx_template_import.py` preparation workspace and becomes:
- finalized template brief
-- `manifest.json` — single source of truth for source-deck facts (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 source-graph quality facts
-- `source_template.pptx` — byte-preserved analysis copy for visual/package cross-checking; never a final template asset
-- `conversion-report.json` — source-recovery and fidelity diagnostics, when present
-- exported `assets/`
+- `analysis/manifest.json` — source-deck facts (slide size, theme, per-master themes, resources, image map, placeholders, layouts, masters, slides, SVG file paths, page-type candidates)
+- `analysis/native_structure.json` — stable source master/layout keys, picker names, parent-master relationships, placeholder type/index/geometry, source hash, and source-graph quality facts
+- `sources/source.pptx` — byte-preserved backing package for visual/package cross-checking; never a final template asset
+- `validation/conversion-report.json` — source-recovery and fidelity diagnostics, when present
+- exported `images/` plus other populated semantic resource directories
- `svg/master_*.svg` / `svg/layout_*.svg` — immutable layered native-payload backing; every master / layout in the deck rendered once, including ones no sample slide references
- `svg/slide_NN.svg` — immutable slide-local native-payload backing; do not bulk-read because opaque native payload is retained
- `svg/inheritance.json` — which layout / master each slide consumes
@@ -37,7 +37,7 @@ When the workflow provides a PPTX reference source, the effective input package
PPTX import interpretation:
-- Placeholder guides in master / layout SVGs are layout signals. Use `manifest.json` placeholder records for type / index / geometry / base style; do not copy dashed guide boxes into final templates unless the visual design truly uses dashed boxes.
+- Placeholder guides in master / layout SVGs are layout signals. Use `analysis/manifest.json` placeholder records for type / index / geometry / base style; do not copy dashed guide boxes into final templates unless the visual design truly uses dashed boxes.
- Charts, SmartArt, diagrams, and OLE objects may appear as typed placeholders in layered SVGs. In flat SVGs they may show preview images. Treat them as source intent markers, not reusable decorative assets.
- The asset filenames referenced by SVGs are governed by the manifest asset map. Prefer those references over inventing duplicate asset names.
@@ -45,8 +45,8 @@ Input priority for PPTX-backed template creation depends on the AI-derived inter
| Mode | Authoritative inputs | Model-facing inputs |
|---|---|---|
-| `standard` / `fidelity` | Finalized brief for the newly designed output; `manifest.json` for factual canvas/theme/assets | `authoring-svg/authoring_summary.json`, layered authoring SVGs, optional flat spot checks, and exported assets as visual references. Do not read `authoring_manifest.json`. Source Master/Layout topology is informational only and is not mined into output structure. |
-| `mirror` | `manifest.json`, `native_structure.json`, and `svg/inheritance.json`; the compiler validates the tool-only authoring manifest | `authoring-svg/authoring_summary.json` plus layered authoring SVGs as the editable preservation IR; optional `authoring-svg-flat/` for complete-page verification; matching lossless `svg/` and optional `svg-flat/` only as immutable backing. |
+| `standard` / `fidelity` | Finalized brief for the newly designed output; `analysis/manifest.json` for factual canvas/theme/resources | `authoring-svg/authoring_summary.json`, layered authoring SVGs, optional flat spot checks, and exported resources as visual references. Do not read `authoring_manifest.json`. Source Master/Layout topology is informational only and is not mined into output structure. |
+| `mirror` | `analysis/manifest.json`, `analysis/native_structure.json`, and `svg/inheritance.json`; the compiler validates the tool-only authoring manifest | `authoring-svg/authoring_summary.json` plus layered authoring SVGs as the editable preservation IR; optional `authoring-svg-flat/` for complete-page verification; matching lossless `svg/` and optional `svg-flat/` only as immutable backing. |
**Mandatory — authored construction bundle**: As soon as `replication_mode`
resolves to `standard` or `fidelity`, and before selecting any page or template
@@ -56,7 +56,7 @@ retain both for the active authoring context. Do not load this bundle for
`mirror`; it preserves source-owned geometry and never selects or authors
replacement contours.
-Use the compact facts in `manifest.json` for orientation. Open screenshots or the original PPTX only for visual cross-checking.
+Use the compact facts in `analysis/manifest.json` for orientation. Open screenshots or the original PPTX only for visual cross-checking.
**Native structure output**: Always set `native_structure_mode: structured`.
@@ -169,9 +169,9 @@ Extension page types beyond the canonical four (transition / appendix / disclaim
When the derived implementation writes `replication_mode: mirror`, materialize a new template workspace from validated imported facts rather than designing a new system:
- Kind eligibility: Create Layout mirror is legal only when the validated source contract is already brand-neutral and application-neutral. If supported source facts retain organization-specific identity or reusable application policy, stop and return to Create Template dispatch: use `standard` / `fidelity` to author a new Layout, or Create Deck to retain those facts. Removing, repainting, retyping, or discarding application rules is never mirror.
-- Model-facing authoring source: `authoring-svg/authoring_summary.json`, layered `authoring-svg/*.svg`, `svg/inheritance.json`, and `native_structure.json`. Do not read `authoring-svg/authoring_manifest.json`; materialization validates it internally. When present, use `authoring-svg-flat/` only for full-page verification. Matching lossless `svg/` and optional `svg-flat/` files are immutable backing; materialization resolves only the layered backing.
+- Model-facing authoring source: `authoring-svg/authoring_summary.json`, layered `authoring-svg/*.svg`, `svg/inheritance.json`, and `analysis/native_structure.json`. Do not read `authoring-svg/authoring_manifest.json`; materialization validates it internally. When present, use `authoring-svg-flat/` only for full-page verification. Matching lossless `svg/` and optional `svg-flat/` files are immutable backing; materialization resolves only the layered backing.
- Precondition: the import evidence identifies every source Master/Layout, parent relationship, picker name, placeholder contract, and fixed visual layer. Stop only when required facts or supported geometry are missing; unused identities are not a stop condition.
-- Output: `<template_workspace>/templates/<NNN>_<page_type>.svg` for every source slide, plus `layout_<layout_key>.svg` for every source Layout unused by all source slides. `<NNN>` is the zero-padded source slide index (3 digits) and `<page_type>` is derived from `manifest.json` `pageTypeCandidates` — `cover` / `toc` / `chapter` / `content` / `ending`. When the page-type heuristic is ambiguous, fall back to `content`. Preserve source slide order via the numeric prefix; definition-only files are not generated pages.
+- Output: `<template_workspace>/templates/<NNN>_<page_type>.svg` for every source slide, plus `layout_<layout_key>.svg` for every source Layout unused by all source slides. `<NNN>` is the zero-padded source slide index (3 digits) and `<page_type>` is derived from `analysis/manifest.json` `pageTypeCandidates` — `cover` / `toc` / `chapter` / `content` / `ending`. When the page-type heuristic is ambiguous, fall back to `content`. Preserve source slide order via the numeric prefix; definition-only files are not generated pages.
- Required preservation: preserve source Master/Layout keys and picker names, Layout-to-Master parentage, slide assignments, placeholder type/index/bounds, supported native-object metadata, geometry, decoration, sprite-sheet wrappers, original example text, chart previews, fonts, effects, and paint order whenever the importer represents them.
- Allowed normalization: add or normalize explicit root declarations and asset paths, and recursively expand fixed Master/Layout group wrappers into direct atoms. The mapping must remain one-to-one at the ownership level and must not change paint order or appearance.
- Forbidden: commonality extraction, semantic synthesis, merging, splitting, promotion, demotion, renaming, re-parenting, decorative simplification, placeholder invention, or replacement of supported source-native metadata / SVG fallback with a model-authored approximation.
@@ -353,14 +353,14 @@ Templates must strictly follow the finalized template brief and the generated `<
If PPTX import output exists:
- Prefer imported theme colors and fonts over visually guessed values
-- Reuse exported `assets/` images directly — `<image>` references in `svg/` already point at canonical files
-- Treat page-type candidates from `manifest.pageTypeCandidates` as hints, not guarantees
+- Reuse exported `images/` directly — raster images and SVG/EMF/WMF image media use the same canonical pool, and `<image>` references in `svg/` already point at it
+- Treat page-type candidates from `analysis/manifest.json.pageTypeCandidates` as hints, not guarantees
**Precondition**:
- For `standard`, inspect enough lightweight complete-page IR documents to understand the requested visual direction and reusable assets; do not analyze source topology.
- For `fidelity`, inspect every lightweight complete-page IR document so the newly designed roster covers the useful source composition range; do not derive output ownership from source Master/Layout recurrence.
-- For `mirror`, verify every authoring Master, Layout, and Slide listed by `authoring_summary.json` against `native_structure.json` and `svg/inheritance.json`, then materialize from the IR with matching lossless payload backing. The compiler validates each machine-manifest record. Before materialization begins, report the verified source slide indexes.
+- For `mirror`, verify every authoring Master, Layout, and Slide listed by `authoring_summary.json` against `analysis/native_structure.json` and `svg/inheritance.json`, then materialize from the IR with matching lossless payload backing. The compiler validates each machine-manifest record. Before materialization begins, report the verified source slide indexes.
### 2.1 PPTX Import Mode Rule
@@ -573,7 +573,7 @@ Mirror mode emits one SVG per source slide, named by source order:
└── 050_ending.svg
```
-Filenames preserve the source slide order via the 3-digit prefix; `<page_type>` is derived from `manifest.json` `pageTypeCandidates`. Literal source text and validated native structure facts are preserved when the authoring IR is materialized into the new workspace; IR-only refs and its manifest are not copied into the template output.
+Filenames preserve the source slide order via the 3-digit prefix; `<page_type>` is derived from `analysis/manifest.json` `pageTypeCandidates`. Literal source text and validated native structure facts are preserved when the authoring IR is materialized into the new workspace; IR-only refs and its manifest are not copied into the template output.
**Hard rule — common routing**: Keep `<design_spec_path>`, template SVGs, and non-bitmap template-source assets in `templates/`; place every bitmap in `images/`; place each imported vector exactly once in `icons/imported/` and reference it as `data-icon="imported/<name>"`. Never create `templates/icons/`. Write a review deck to `exports/` when explicitly requested and always for a multi-Master package gate. Create Template must not create optional directories or placeholder files solely to retain empty paths. An initialized project may already contain empty scaffolding; leave it untouched and omit it from completion unless real template files were written or adopted there. Do not branch asset placement by output scope.
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index a58f98e4..cfca9c5f 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -120,7 +120,7 @@ python3 scripts/svg_authoring_view.py <imported-svg-or-dir> -o <output-dir> --pr
python3 scripts/svg_authoring_view.py <authoring-dir> --refresh-summary
python3 scripts/compact_svg_coordinates.py <template_workspace>/templates --inplace --keep-native-frames
python3 scripts/mirror_template_materialize.py <import_workspace> <template_workspace>
-python3 scripts/svg_to_pptx.py <import_workspace> -s authoring-svg-flat --roundtrip
+python3 scripts/svg_to_pptx.py <import_workspace> --roundtrip
python3 scripts/template_preview_pptx.py <template_workspace>
python3 scripts/template_preview_pptx.py <legacy_template_workspace> --visual-only
```
@@ -128,7 +128,7 @@ python3 scripts/template_preview_pptx.py <legacy_template_workspace> --visual-on
Template import defaults to the canonical layered `svg/` tree. Use
`--inheritance-mode both` only when a separate self-contained `svg-flat/`
verification tree is required. No derived narrative digest is generated
-because `manifest.json` already owns those facts.
+because `analysis/manifest.json` already owns those facts.
`svg_authoring_view.py` creates a lightweight, non-destructive editable IR
bundle from PPTX-imported SVGs. It removes embedded `txbody` payloads,
@@ -148,7 +148,7 @@ IR edits. The full imported SVG remains unchanged as native-payload backing.
Template creation edits the IR and materializes validated `templates/*.svg`;
the layered IR directory itself is not a final template or direct release
export source. A complete-page flat IR may be selected with
-`-s authoring-svg-flat --roundtrip`: `authoring_roundtrip.py` regenerates its
+`--roundtrip`: `authoring_roundtrip.py` reads `authoring-svg-flat/`, regenerates its
deterministic extraction baseline, restores unchanged refs from the immutable
layered backing, and sends the temporary result through preserve export while
leaving edited/deleted/new authoring content in place.
@@ -156,8 +156,8 @@ leaving edited/deleted/new authoring content in place.
`mirror_template_materialize.py` is the deterministic Type A mirror compiler.
It consumes only the layered `authoring-svg/` IR as editable input, loads its
tool-only manifest internally, and validates it against immutable `svg/`,
-`native_structure.json`,
-`svg/inheritance.json`, `source_template.pptx`, and any extracted-vector
+`analysis/native_structure.json`,
+`svg/inheritance.json`, `sources/source.pptx`, and any extracted-vector
inventory, then publishes a complete structured template roster atomically.
Unchanged supported Slide-local/slot refs may recover native payload; edited
refs keep their current SVG fallback. Fixed Master/Layout wrappers are expanded
@@ -173,7 +173,8 @@ readable. The v1 execution manifest points to per-prototype
tool metadata and are not injected into model context. Checker and export
validate output attributes, topology, and resource hashes against the complete
prototype internally. Bitmap assets
-go to `images/`; other referenced source assets go to `templates/assets/`.
+and Office vector image media go to `images/`; audio, video, and opaque source
+payloads go to their semantic workspace directories.
The destination must be empty, and the command does not write
`templates/design_spec.md`; Template_Designer owns that authored brief.
diff --git a/skills/ppt-master/scripts/authoring_roundtrip.py b/skills/ppt-master/scripts/authoring_roundtrip.py
index 93a7efd2..128ab4b6 100644
--- a/skills/ppt-master/scripts/authoring_roundtrip.py
+++ b/skills/ppt-master/scripts/authoring_roundtrip.py
@@ -8,7 +8,7 @@ source objects recover their original round-trip metadata; edited objects stay
as authored SVG and are converted normally.
Usage:
- Imported by svg_to_pptx.py for ``-s <flat-authoring-dir> --roundtrip``.
+ Imported by svg_to_pptx.py for ``--roundtrip``.
Dependencies:
None (standard library and sibling PPT Master modules only).
@@ -19,15 +19,18 @@ from __future__ import annotations
import copy
import hashlib
import json
+import os
import re
import tempfile
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Any
+from urllib.parse import unquote, urlsplit, urlunsplit
from xml.etree import ElementTree as ET
from extract_svg_assets import extract_file
+from pptx_workspace import ROUNDTRIP_MANIFEST_PATH
from slide_roster import discover_slide_svgs
from svg_authoring_view import (
AUTHORING_MANIFEST_NAME,
@@ -65,6 +68,7 @@ class AuthoringDocument:
authoring_path: Path
flat_source_path: Path
layered_source_path: Path
+ initial_authoring_sha256: str
source_refs: dict[str, SourceRefRecord]
@@ -221,13 +225,56 @@ def _load_documents(
f"Flat authoring backing SVG directory is missing: {source_root}"
)
+ roundtrip_manifest = _load_json(
+ project_path / ROUNDTRIP_MANIFEST_PATH,
+ context="round-trip workspace manifest",
+ )
+ if roundtrip_manifest.get("schema") != "ppt-master.roundtrip-workspace.v1":
+ raise AuthoringRoundtripError(
+ "Unsupported round-trip workspace manifest schema: "
+ f"{roundtrip_manifest.get('schema')!r}"
+ )
+ directories = roundtrip_manifest.get("directories")
+ if not isinstance(directories, dict):
+ raise AuthoringRoundtripError(
+ "Round-trip workspace manifest directories must be an object"
+ )
+ flat_root_raw = directories.get("flatSvg")
+ layered_root_raw = directories.get("layeredSvg")
+ if not isinstance(flat_root_raw, str) or not flat_root_raw:
+ raise AuthoringRoundtripError(
+ "Round-trip workspace manifest has no flat SVG backing directory"
+ )
+ if not isinstance(layered_root_raw, str) or not layered_root_raw:
+ raise AuthoringRoundtripError(
+ "Round-trip workspace manifest has no layered SVG backing directory"
+ )
+ flat_root = _resolve_inside(
+ project_path,
+ flat_root_raw,
+ context="round-trip flat SVG backing directory",
+ )
+ layered_root = _resolve_inside(
+ project_path,
+ layered_root_raw,
+ context="round-trip layered SVG backing directory",
+ )
+ if source_root != flat_root:
+ raise AuthoringRoundtripError(
+ "Authoring manifest source_root does not match the round-trip flat "
+ "SVG backing directory"
+ )
+ if not layered_root.is_dir():
+ raise AuthoringRoundtripError(
+ f"Round-trip layered SVG backing directory is missing: {layered_root}"
+ )
+
documents_raw = manifest.get("documents")
if not isinstance(documents_raw, list):
raise AuthoringRoundtripError(
"authoring_manifest.json documents must be an array"
)
documents: dict[str, AuthoringDocument] = {}
- layered_root = project_path / "svg"
for index, raw in enumerate(documents_raw):
if not isinstance(raw, dict):
raise AuthoringRoundtripError(f"documents[{index}] must be an object")
@@ -278,6 +325,11 @@ def _load_documents(
f"Flat backing SVG changed: {flat_source_path.name}; expected "
f"{expected_source_sha}, found {actual_source_sha}"
)
+ initial_authoring_sha = raw.get("initial_authoring_sha256")
+ if not isinstance(initial_authoring_sha, str) or not initial_authoring_sha:
+ raise AuthoringRoundtripError(
+ f"documents[{index}].initial_authoring_sha256 must be a non-empty string"
+ )
refs_raw = raw.get("source_refs")
if not isinstance(refs_raw, dict):
@@ -323,6 +375,7 @@ def _load_documents(
authoring_path=authoring_path,
flat_source_path=flat_source_path,
layered_source_path=layered_source_path,
+ initial_authoring_sha256=initial_authoring_sha,
source_refs=refs,
)
@@ -765,7 +818,49 @@ def _serialize_svg(root: ET.Element) -> bytes:
return payload if payload.endswith(b"\n") else payload + b"\n"
+def _rebase_resource_references(
+ element: ET.Element,
+ source_dir: Path,
+ target_dir: Path,
+ project_path: Path,
+ *,
+ recursive: bool,
+) -> None:
+ """Rebase exact local SVG resource hrefs without path guessing."""
+ nodes = element.iter() if recursive else (element,)
+ project_root = project_path.resolve()
+ for node in nodes:
+ if _local_name(node.tag) == "a":
+ continue
+ for name in ("href", f"{{{XLINK_NS}}}href"):
+ raw = node.get(name)
+ if raw is None or not raw or raw.startswith("#") or raw.startswith("data:"):
+ continue
+ parsed = urlsplit(raw)
+ if (
+ parsed.scheme
+ or parsed.netloc
+ or parsed.query
+ or parsed.fragment
+ or not parsed.path
+ or Path(unquote(parsed.path)).is_absolute()
+ ):
+ raise AuthoringRoundtripError(
+ f"Unsupported SVG resource reference in {element.tag}: {raw!r}"
+ )
+ resolved = (source_dir / unquote(parsed.path)).resolve()
+ try:
+ resolved.relative_to(project_root)
+ except ValueError as exc:
+ raise AuthoringRoundtripError(
+ f"SVG resource reference escapes the project: {raw!r}"
+ ) from exc
+ relative = os.path.relpath(resolved, target_dir).replace(os.sep, "/")
+ node.set(name, urlunsplit(("", "", relative, "", "")))
+
+
def _materialize_document(
+ project_path: Path,
document: AuthoringDocument,
baseline_path: Path,
output_path: Path,
@@ -888,7 +983,15 @@ def _materialize_document(
raise AuthoringRoundtripError(
f"{document.name} cannot find {source_ref!r} in layered source"
)
- return [copy.deepcopy(source)]
+ restored = copy.deepcopy(source)
+ _rebase_resource_references(
+ restored,
+ document.layered_source_path.parent,
+ output_path.parent,
+ project_path,
+ recursive=True,
+ )
+ return [restored]
if _local_name(element.tag) == "use":
icon = (element.get("data-icon") or "").strip()
@@ -913,6 +1016,13 @@ def _materialize_document(
for replacement in replacements:
clone.append(replacement)
clone.attrib.pop(SOURCE_REF_ATTRIBUTE, None)
+ _rebase_resource_references(
+ clone,
+ document.authoring_path.parent,
+ output_path.parent,
+ project_path,
+ recursive=False,
+ )
if source_ref and source_ref.startswith("slide:"):
source = layered_index.get(source_ref)
if source is not None:
@@ -940,9 +1050,25 @@ def _materialize_document(
value = current_root.get(name)
if value is not None:
output_root.set(name, value)
+ layered_defs_root = copy.deepcopy(layered_root)
+ current_defs_root = copy.deepcopy(current_root)
+ _rebase_resource_references(
+ layered_defs_root,
+ document.layered_source_path.parent,
+ output_path.parent,
+ project_path,
+ recursive=True,
+ )
+ _rebase_resource_references(
+ current_defs_root,
+ document.authoring_path.parent,
+ output_path.parent,
+ project_path,
+ recursive=True,
+ )
merged_defs = _merge_defs(
- layered_root,
- current_root,
+ layered_defs_root,
+ current_defs_root,
include_authoring_changes=defs_changed or bool(edited_refs),
)
if merged_defs is not None and list(merged_defs):
@@ -980,8 +1106,14 @@ def _materialize_document(
output_path.write_bytes(_serialize_svg(output_root))
return {
"file": document.name,
+ "document_unchanged": (
+ _sha256_file(document.authoring_path)
+ == document.initial_authoring_sha256
+ ),
"source_ref_count": len(expected_refs),
+ "source_ref_ids": sorted(expected_refs),
"unchanged_refs": len(unchanged_refs),
+ "unchanged_ref_ids": sorted(unchanged_refs),
"edited_refs": len(edited_refs),
"edited_ref_ids": sorted(edited_refs),
"deleted_refs": len(deleted_refs),
@@ -1041,6 +1173,7 @@ def materialize_flat_authoring_roundtrip(
)
document_reports = [
_materialize_document(
+ project_path,
document,
baseline_root / document.name,
output_dir / document.name,
diff --git a/skills/ppt-master/scripts/confirm_ui/server.py b/skills/ppt-master/scripts/confirm_ui/server.py
index b39a7237..61348ca5 100644
--- a/skills/ppt-master/scripts/confirm_ui/server.py
+++ b/skills/ppt-master/scripts/confirm_ui/server.py
@@ -206,13 +206,11 @@ _TEMPLATE_SPEC_NAME_RE = re.compile(
def _template_design_specs(workspace_root: Path) -> list[Path]:
"""Return every Design Spec one template workspace root exposes.
- A single-kind workspace keeps the exact ``templates/design_spec.md``, and a
- compatible legacy-flat root keeps ``design_spec.md`` beside its pages. A
+ A single-kind workspace keeps the exact ``templates/design_spec.md``. A
multi-kind workspace keeps one ``templates/design_spec.<kind>.<id>.md`` per
- kind — the same shape the apply stage installs into a consuming project — so
- one root can carry, for example, a Brand plus a Style. Order is stable so
- candidate keys and the options digest do not depend on directory listing
- order.
+ kind — the same shape the apply stage installs into a consuming project.
+ Order is stable so candidate keys and the options digest do not depend on
+ directory listing order.
"""
templates_dir = workspace_root / 'templates'
current = templates_dir / 'design_spec.md'
@@ -231,12 +229,9 @@ def _template_design_specs(workspace_root: Path) -> list[Path]:
return [current]
if multi:
return multi
- legacy = workspace_root / 'design_spec.md'
- if legacy.is_file():
- return [legacy]
raise ValueError(
'template workspace is missing templates/design_spec.md, '
- 'templates/design_spec.<kind>.<id>.md, or legacy design_spec.md: '
+ 'or templates/design_spec.<kind>.<id>.md: '
f'{workspace_root}'
)
diff --git a/skills/ppt-master/scripts/docs/project.md b/skills/ppt-master/scripts/docs/project.md
index e61c7532..ac6ca02a 100644
--- a/skills/ppt-master/scripts/docs/project.md
+++ b/skills/ppt-master/scripts/docs/project.md
@@ -257,21 +257,21 @@ python3 scripts/pptx_template_import.py <template.pptx> --inheritance-mode layer
```
Notes:
-- Extracts reusable media assets from `ppt/media/`
+- Extracts package resources into semantic workspace directories
- Summarizes slide size, theme colors, font metadata, and per-master theme metadata
- Resolves slide / layout / master relationships from OOXML relationships; every master and layout is included even when no sample slide currently references it
-- Generates `manifest.json` (single source of truth for slide size, theme, per-master themes, assets, layouts, masters, placeholders, slides, SVG file paths, and page-type candidates), `native_structure.json`, `source_template.pptx`, `assets/`, `conversion-report.json`, and shape-level SVGs under `svg/`
+- Generates `analysis/manifest.json` (source facts and resource inventory), `analysis/native_structure.json`, `sources/source.pptx`, `validation/conversion-report.json`, populated semantic resource directories, and shape-level SVGs under `svg/`
- **SVG output defaults to the layered authoring source** (`--inheritance-mode layered`):
- `svg/` — layered template view for designers: every master and layout in the deck rendered once as `svg/master_*.svg` / `svg/layout_*.svg` (including ones no sample slide currently references); `svg/slide_NN.svg` contains only that slide's own shapes; `svg/inheritance.json` records parentage plus source-owned `showInheritedShapes` / `showMasterShapes` booleans.
- `svg-flat/` — optional verification view emitted only by `--inheritance-mode both`: each `slide_NN.svg` is self-contained (the effective visible Master/Layout contributions plus Slide-local content painted into one file), so opening any slide in isolation shows the full page like PowerPoint would. Background inheritance remains independent of inherited-shape visibility. Useful for previews, screenshots, and "did this slide actually render correctly" sanity checks.
-- `manifest.json` records `svgFile` for slides / layouts / masters, `flatSvgFile` for slides when `svg-flat/` exists, placeholder type / index / geometry / base style, an asset map used by SVG `href` values, and common assets reused through slide / layout / master inheritance. Placeholder semantics keep `subTitle`, `obj`, `media`, and `dt` distinct as `subtitle`, `object`, `media`, and `date`.
-- `conversion-report.json` owns tolerant source-recovery diagnostics; it is not a cache or a duplicate of the structural manifests
+- `analysis/manifest.json` records `svgFile` for slides / layouts / masters, `flatSvgFile` for slides when `svg-flat/` exists, placeholder type / index / geometry / base style, a resource map used by SVG `href` values, and common images reused through slide / layout / master inheritance. Placeholder semantics keep `subTitle`, `obj`, `media`, and `dt` distinct as `subtitle`, `object`, `media`, and `date`.
+- `validation/conversion-report.json` owns tolerant source-recovery diagnostics; it is not a cache or a duplicate of the structural manifests
- Layered slide SVGs keep only the slide's own background; inherited master / layout backgrounds stay in the corresponding master / layout SVGs
- Placeholder guides are intentionally lightweight in `svg/` master / layout files; `svg-flat/` hides those guides and is the visual preview source
- Charts, SmartArt, diagrams, and OLE objects become typed placeholders in `svg/`; `svg-flat/` shows a preview image with a corner badge when one exists, otherwise a visible placeholder. Tables are converted into real SVG content.
-- Pass `--inheritance-mode both` to add `svg-flat/`, or `--inheritance-mode flat` for the legacy round-trip view (single self-contained `svg/` tree without master/layout/inheritance files).
+- Pass `--inheritance-mode both` to add `svg-flat/`, or `--inheritance-mode flat` for a self-contained projection-only `svg/` tree without master/layout/inheritance files. Imported-deck round-trip uses the separate `authoring-svg-flat/` contract.
- SVG export reads OOXML directly via `pptx_to_svg` — no PowerPoint or Keynote dependency, runs on any platform
-- `<image>` elements in `svg/` reference files in `assets/` directly; pass `--embed-images` to inline as data URIs instead
+- `<image>` elements in `svg/` reference files in `images/` directly; raster images and SVG/EMF/WMF image media share that directory. Pass `--embed-images` to inline them as data URIs instead.
- External linked images and missing media are strict failures. Office vector media such as EMF / WMF are converted to PNG previews when the local toolchain can do so; otherwise the import fails instead of silently dropping content.
- Required in `/create-template` whenever the reference source is `.pptx`
- Default output directory is `<pptx_stem>_template_import/`
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 347ce38d..5fefa726 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -55,19 +55,15 @@ The layered authoring bundle remains the editable source for template creation;
the complete imported SVG remains immutable native-payload backing. Final
`templates/*.svg` files are materialized and validated from that pair. A
complete-page `authoring-svg-flat/` bundle is the user's editable source for an
-imported-deck round-trip. Keep its SVGs in that directory, its corresponding
-bitmaps in the sibling `assets/` pool, and its extracted vectors in the sibling
-`icons/` pool; do not duplicate those resources into a second `images/` tree.
-With `-s authoring-svg-flat --roundtrip`, export verifies the manifest and
-immutable backing graph, regenerates the deterministic extraction baseline,
-restores every unchanged source-referenced object into a temporary layered
-slide, and retains edited/deleted/new authoring content. It then enters the
-same source-preserving package route as `-s svg --roundtrip`; the temporary
-materialization never rewrites the authoring bundle. The dangerous exporter is
-a separate flat compatibility mechanism and does not restore source objects.
-More generally, an SVG may reference a resource anywhere under the project
-root through an exact SVG-relative or project-root-relative path; export never
-recursively guesses among files with the same name.
+imported-deck round-trip. `pptx_to_svg.py --roundtrip` places image media in
+`images/`, vectors in `icons/imported/`, cues/audio/video/notes in their named
+directories, opaque payloads in `native-payloads/`, the source package in
+`sources/`, and tool-owned backing/contracts in `analysis/`; `assets/` is
+invalid. `svg_to_pptx.py --roundtrip` always reads `authoring-svg-flat/`,
+restores unchanged source refs from `analysis/roundtrip-svg/`, and retains
+edits/deletions/new content without rewriting the bundle. Unchanged slides and
+resources pass through byte-for-byte; an edit rebuilds only its owner. Resource
+hrefs resolve exactly relative to the SVG and must remain inside the workspace.
Regenerate the summary after direct edits that do not pass through one of the
in-place normalization tools:
@@ -444,8 +440,9 @@ structured export validate output attributes, text/tspan topology, and
referenced-resource hashes against
the prototype.
-The output routes reusable vectors once to `icons/imported/`, bitmaps to
-`images/`, and other referenced files to `templates/assets/`. The JSON report
+The output routes reusable vectors once to `icons/imported/`, image media to
+`images/`, audio and video to their semantic directories, and opaque referenced
+files to `native-payloads/imported/`. The JSON report
reports payload occurrence, native-record, unique-byte, and compressed-store
counts and is written to stdout only. The command intentionally does not create
`templates/design_spec.md`; Template_Designer writes the package-specific rules
@@ -574,13 +571,10 @@ python3 scripts/svg_to_pptx.py <project_path> --no-image-optimize
python3 scripts/svg_to_pptx.py <project_path> --native-charts-and-tables
python3 scripts/svg_to_pptx.py <project_path> --pptx-structure structured # deck/layout template override
python3 scripts/svg_to_pptx.py <project_path> --pptx-structure flat # free-design/brand-only override
-# Exact source-structure diagnostic emitted by pptx_to_svg.py --roundtrip:
-python3 scripts/svg_to_pptx.py <pptx_import_output> -s svg --roundtrip
# Template-import visual round-trip diagnostic only:
python3 scripts/svg_to_pptx.py <template_import_output> -s svg-flat
-# Editable authoring-svg-flat -> source-preserving PPTX round-trip:
-python3 scripts/svg_to_pptx.py <pptx_import_output> -s authoring-svg-flat \
- --roundtrip --no-notes --no-animations
+# Editable authoring-svg-flat/ -> source-preserving PPTX round-trip:
+python3 scripts/svg_to_pptx.py <pptx_import_output> --roundtrip
# The same compatibility mode defaults to svg_output/ when -s is omitted:
python3 scripts/svg_to_pptx.py <project_path> \
--enable-dangerous-nonconforming-svg-export
@@ -664,7 +658,7 @@ Behavior:
- `--no-merge`: each dy-stacked line becomes an independent frame with its own placement.
- Detection is conservative: mixed-layout `<text>` falls back to per-line frames. Use `--reflow-text` only for resizable body copy and `--no-merge` only for independent line objects or absolute line positions.
- Native release export reads `svg_output/`; `-s <directory>` selects another project-relative SVG source. `-s final` remains an explicit diagnostic comparison against post-processed SVGs and does not change artifact ownership. `--enable-dangerous-nonconforming-svg-export` is a separate, explicitly requested flat compatibility path for either the default or selected source; it forces flat structure, restores no imported source object, and cannot combine with `--roundtrip` or `--quick-generate`.
-- `--roundtrip` consumes the validated source package and structure sidecar emitted by `pptx_to_svg.py --roundtrip`. With `-s svg`, it reads the layered `slide_*.svg` files directly. With another `-s`, that directory must be a flat authoring IR with a valid `authoring_manifest.json`; export deterministically regenerates its pre-edit projection/extraction baseline, restores unchanged source refs from the layered backing, keeps edits/deletions/new elements, and records those counts in postflight. An unchanged imported chart with a closed validated source package automatically restores its original chart XML, style/color parts, workbook, and theme override without enabling ordinary semantic Chart/Table replacement. Its visible-fallback fingerprint remains authoritative: editing the SVG fallback disables stale exact replacement instead of discarding that edit.
+- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, and rebuilds only edited owners. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement.
- `svg_final/` may be opened directly or inserted into PowerPoint as an SVG picture. PowerPoint's manual Convert-to-Shape operation is outside the compatibility contract.
- On every SVG-authoring route, each file in `svg_output/` is the complete visible
page-design source. Templates and locks may guide authoring, but finalize/export
@@ -862,7 +856,10 @@ python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
python3 scripts/svg_finalize/embed_icons.py --dry-run svg_output/*.svg
```
-Replaces `<use data-icon="chunk-filled/name" .../>`, `<use data-icon="tabler-filled/name" .../>` and `<use data-icon="tabler-outline/name" .../>` placeholders with actual SVG path elements. Use for manual icon embedding checks outside `finalize_svg.py`.
+Replaces project-local `<use data-icon="library/name" .../>` placeholders with
+SVG paths. The exact case-sensitive file must exist under the workspace
+`icons/`; bare, aliased, template-source, and unsynced references fail. Use
+this only for manual checks outside `finalize_svg.py`.
## SVG Compatibility Contract
diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.py
index 0680cf23..ff50ff27 100644
--- a/skills/ppt-master/scripts/finalize_svg.py
+++ b/skills/ppt-master/scripts/finalize_svg.py
@@ -51,7 +51,7 @@ configure_utf8_stdio()
# Import finalize helpers from the internal package.
sys.path.insert(0, str(Path(__file__).parent))
-from resource_paths import icon_search_dirs_for_project # noqa: E402
+from resource_paths import icon_dir_for_project # noqa: E402
from svg_finalize.align_embed_images import (
align_and_embed_images_in_svg,
count_office_vector_refs_in_svg,
@@ -182,7 +182,6 @@ def _process_candidate_directory(
max_dimension: int | None,
image_scale: float,
icons_dir: Path,
- icons_fallback_dir: Path | None,
) -> bool:
"""Run every selected finalization pass against one unpublished candidate."""
# Core normalization: downstream image/rect processors read XML geometry.
@@ -207,7 +206,6 @@ def _process_candidate_directory(
icons_dir,
dry_run=False,
verbose=False,
- fallback_dir=icons_fallback_dir,
)
icons_count += count
for svg_file in candidate_dir.glob('*.svg'):
@@ -342,7 +340,7 @@ def finalize_project(
"""
svg_output = project_dir / 'svg_output'
svg_final = project_dir / 'svg_final'
- icons_dir, icons_fallback_dir = icon_search_dirs_for_project(project_dir)
+ icons_dir = icon_dir_for_project(project_dir)
# Check if svg_output exists
if not svg_output.exists():
@@ -381,7 +379,6 @@ def finalize_project(
max_dimension=max_dimension,
image_scale=image_scale,
icons_dir=icons_dir,
- icons_fallback_dir=icons_fallback_dir,
)
except Exception as exc:
safe_print(
diff --git a/skills/ppt-master/scripts/icon_sync.py b/skills/ppt-master/scripts/icon_sync.py
index 4b97ad0b..b7ee0b4e 100644
--- a/skills/ppt-master/scripts/icon_sync.py
+++ b/skills/ppt-master/scripts/icon_sync.py
@@ -35,23 +35,34 @@ from console_encoding import configure_utf8_stdio
configure_utf8_stdio()
-_LIB_ALIASES = {"chunk": "chunk-filled"}
_STYLISTIC_LIBRARIES = {
"chunk-filled",
"phosphor-duotone",
"tabler-filled",
"tabler-outline",
}
+_SYNC_LIBRARIES = _STYLISTIC_LIBRARIES | {"simple-icons"}
_GLOBAL_ICONS_DIR = Path(__file__).resolve().parent.parent / "templates" / "icons"
def _split_name(icon_name: str) -> tuple[str, str]:
- """`lib/name` -> (lib, name), applying the chunk→chunk-filled alias."""
- if "/" not in icon_name:
- # legacy un-prefixed names live in chunk-filled/
- return "chunk-filled", icon_name
+ """Validate and split one complete bundled ``library/name`` id."""
+ if icon_name.count("/") != 1:
+ raise ValueError(
+ f"icon id must use the complete library/name form: {icon_name!r}"
+ )
lib, name = icon_name.split("/", 1)
- return _LIB_ALIASES.get(lib, lib), name
+ if lib not in _SYNC_LIBRARIES:
+ raise ValueError(f"unsupported bundled icon library: {lib!r}")
+ if (
+ not name
+ or name in {".", ".."}
+ or "/" in name
+ or "\\" in name
+ or Path(name).name != name
+ ):
+ raise ValueError(f"invalid icon name: {name!r}")
+ return lib, name
def sync_icons(project_path: Path, icon_names: list[str], global_dir: Path = _GLOBAL_ICONS_DIR) -> tuple[list[str], list[str]]:
@@ -97,7 +108,11 @@ def main(argv: Optional[list[str]] = None) -> int:
print(f"[ERROR] project not found: {project}", file=sys.stderr)
return 1
- requested_libraries = {_split_name(raw)[0] for raw in args.icons}
+ try:
+ requested_libraries = {_split_name(raw)[0] for raw in args.icons}
+ except ValueError as exc:
+ print(f"[ERROR] {exc}", file=sys.stderr)
+ return 1
stylistic_libraries = sorted(requested_libraries & _STYLISTIC_LIBRARIES)
if len(stylistic_libraries) > 1:
print(
diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.py
index 16c5004c..2b4b619b 100644
--- a/skills/ppt-master/scripts/mirror_template_materialize.py
+++ b/skills/ppt-master/scripts/mirror_template_materialize.py
@@ -63,6 +63,13 @@ from template_text_slots import (
analyze_template_text_slots,
text_slot_integrity_sha256,
)
+from pptx_workspace import (
+ AUDIO_EXTENSIONS,
+ IMAGE_EXTENSIONS,
+ VIDEO_EXTENSIONS,
+ conversion_report_path,
+ native_structure_path,
+)
configure_utf8_stdio()
@@ -86,17 +93,6 @@ ET.register_namespace("", SVG_NS)
ET.register_namespace("xlink", XLINK_NS)
_NON_VISUAL_TAGS = frozenset({"defs", "desc", "metadata", "style", "title"})
-_BITMAP_EXTENSIONS = frozenset({
- ".avif",
- ".bmp",
- ".gif",
- ".jpeg",
- ".jpg",
- ".png",
- ".tif",
- ".tiff",
- ".webp",
-})
_INHERITED_PRESENTATION_ATTRIBUTES = frozenset({
"color",
"fill",
@@ -302,7 +298,7 @@ def _template_execution_manifest_files(
def _source_import_summary(import_workspace: Path) -> dict[str, object] | None:
"""Summarize source-owned tolerant-import diagnostics by stable code."""
- report_path = import_workspace / "conversion-report.json"
+ report_path = conversion_report_path(import_workspace)
try:
report = json.loads(report_path.read_text(encoding="utf-8"))
except FileNotFoundError:
@@ -792,7 +788,7 @@ def _validate_source_ref_closure(
def _load_native_graph(workspace: Path) -> dict[str, Any]:
- native_path = workspace / "native_structure.json"
+ native_path = native_structure_path(workspace)
native = _load_json(native_path, context="native structure")
if native.get("schema") != NATIVE_STRUCTURE_SCHEMA:
raise MirrorMaterializationError(
@@ -2440,10 +2436,16 @@ def _rewrite_packaged_assets(
else f"{source.stem}{detected_extension}"
)
relative_target = Path("images") / packaged_name
- elif source.suffix.lower() in _BITMAP_EXTENSIONS:
+ elif source.suffix.lower() in IMAGE_EXTENSIONS:
relative_target = Path("images") / source.name
+ elif source.suffix.lower() in VIDEO_EXTENSIONS:
+ relative_target = Path("video") / source.name
+ elif source.suffix.lower() in AUDIO_EXTENSIONS:
+ relative_target = Path("audio") / source.name
else:
- relative_target = Path("templates") / "assets" / source.name
+ relative_target = (
+ Path("native-payloads") / "imported" / source.name
+ )
previous = asset_sources.get(relative_target)
if previous is not None and _sha256_file(previous) != _sha256_file(source):
raise MirrorMaterializationError(
diff --git a/skills/ppt-master/scripts/pptx_animations.py b/skills/ppt-master/scripts/pptx_animations.py
index 10589b6a..36c51c9a 100644
--- a/skills/ppt-master/scripts/pptx_animations.py
+++ b/skills/ppt-master/scripts/pptx_animations.py
@@ -3569,9 +3569,11 @@ def validate_pptx_animation_package(
pptx_path: str | Path,
*,
require_supported_effects: bool = False,
+ skip_slide_numbers: set[int] | None = None,
) -> None:
- """Validate timing placement and shape references for every slide part."""
+ """Validate generated timing, excluding byte-preserved source slides."""
path = Path(pptx_path)
+ skipped = skip_slide_numbers or set()
errors: list[str] = []
try:
with zipfile.ZipFile(path) as package:
@@ -3581,6 +3583,9 @@ def validate_pptx_animation_package(
if re.fullmatch(r'ppt/slides/slide\d+\.xml', name)
)
for name in names:
+ match = re.search(r'slide(\d+)\.xml$', name)
+ if match is not None and int(match.group(1)) in skipped:
+ continue
slide_data = package.read(name)
try:
root = ET.fromstring(slide_data)
diff --git a/skills/ppt-master/scripts/pptx_template_import.py b/skills/ppt-master/scripts/pptx_template_import.py
index bd0bc4e7..4deb3ba0 100644
--- a/skills/ppt-master/scripts/pptx_template_import.py
+++ b/skills/ppt-master/scripts/pptx_template_import.py
@@ -3,12 +3,13 @@
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` — source-structure facts and
- a byte-identical analysis copy used to rebuild explicit SVG structure
-- `assets/` — extracted reusable image assets
-- `conversion-report.json` — source-recovery and fidelity diagnostics emitted
+- `analysis/manifest.json` — source of truth for slide size, theme, resources,
+ image inventory, and per-slide / per-layout / per-master metadata
+- `analysis/native_structure.json` + `sources/source.pptx` — source-structure
+ facts and a byte-identical backing package
+- `images/`, `audio/`, `sounds/`, `video/`, and `native-payloads/` — semantic
+ source resources, created only when populated
+- `validation/conversion-report.json` — source-recovery diagnostics emitted
with SVG conversion
- `svg/` — canonical layered template view (every master
and layout in the deck rendered once each as `master_*.svg` /
@@ -30,6 +31,12 @@ from xml.etree import ElementTree as ET
from zipfile import BadZipFile
from console_encoding import configure_utf8_stdio
+from pptx_workspace import (
+ CONVERSION_REPORT_PATH,
+ TEMPLATE_MANIFEST_PATH,
+ reject_removed_workspace_layout,
+ template_manifest_path,
+)
from template_import.manifest import build_manifest
from template_import.native_structure import (
CONTRACT_NAME,
@@ -39,8 +46,8 @@ from template_import.native_structure import (
configure_utf8_stdio()
-_MANIFEST_NAME = "manifest.json"
-_CONVERSION_REPORT_NAME = "conversion-report.json"
+_MANIFEST_NAME = TEMPLATE_MANIFEST_PATH.as_posix()
+_CONVERSION_REPORT_NAME = CONVERSION_REPORT_PATH.as_posix()
def parse_args() -> argparse.Namespace:
@@ -66,14 +73,14 @@ def parse_args() -> argparse.Namespace:
"--manifest-only",
action="store_true",
help=(
- "Only extract manifest.json + reusable assets + the native "
- "structure/source pair, without exporting slides to SVG"
+ "Only extract analysis manifests, semantic resources, and the "
+ "source-package bundle, without exporting slides to SVG"
),
)
parser.add_argument(
"--embed-images",
action="store_true",
- help="Inline images as data: URIs instead of writing files to assets/",
+ help="Inline images as data: URIs instead of writing files to images/",
)
parser.add_argument(
"--inheritance-mode",
@@ -86,42 +93,53 @@ def parse_args() -> argparse.Namespace:
"'both': also emit svg-flat/ with self-contained per-slide "
"verification files. In this mode svg/ still holds the layered "
"renderings (template designers see master/layout/slide as "
- "separate files). 'flat': emit only self-contained slide SVGs "
- "in svg/, the round-trip view used by svg_to_pptx."
+ "separate files). 'flat': emit only projection-only, "
+ "self-contained slide SVGs in svg/. Imported-deck round-trip "
+ "uses the separate authoring-svg-flat/ contract."
),
)
return parser.parse_args()
-def _managed_asset_paths(output_dir: Path) -> set[Path]:
- """Read the previous manifest's exact exported-asset roster."""
- manifest_path = output_dir / _MANIFEST_NAME
+def _managed_resource_paths(output_dir: Path) -> set[Path]:
+ """Read the previous manifest's exact semantic-resource roster."""
+ manifest_path = template_manifest_path(output_dir)
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError):
return set()
if not isinstance(manifest, dict):
return set()
- assets = manifest.get("assets")
- if not isinstance(assets, dict):
- return set()
- export_dir = assets.get("exportDir")
- asset_names = assets.get("allAssets")
- if export_dir != "assets" or not isinstance(asset_names, list):
- return set()
- if any(
- not isinstance(name, str)
- or not name
- or name in {".", ".."}
- or "/" in name
- or "\\" in name
- for name in asset_names
- ):
- return set()
- return {
- Path("assets") / name
- for name in asset_names
- }
+ resources = manifest.get("resources")
+ if isinstance(resources, dict) and isinstance(resources.get("items"), list):
+ paths: set[Path] = set()
+ allowed_roots = {
+ "audio",
+ "images",
+ "native-payloads",
+ "sounds",
+ "video",
+ }
+ for item in resources["items"]:
+ if not isinstance(item, dict):
+ return set()
+ value = item.get("workspacePath")
+ if not isinstance(value, str):
+ return set()
+ path = Path(value)
+ if (
+ path.drive
+ or path.anchor
+ or path.is_absolute()
+ or not path.parts
+ or ".." in path.parts
+ or path.parts[0] not in allowed_roots
+ ):
+ return set()
+ paths.add(path)
+ return paths
+
+ return set()
def main() -> int:
@@ -145,7 +163,12 @@ def main() -> int:
print("Error: --skip-manifest and --manifest-only cannot be used together")
return 1
- previous_assets = _managed_asset_paths(output_dir)
+ try:
+ reject_removed_workspace_layout(output_dir)
+ except RuntimeError as exc:
+ print(f"Error: {exc}")
+ return 1
+ previous_resources = _managed_resource_paths(output_dir)
output_dir.parent.mkdir(parents=True, exist_ok=True)
staging_root = Path(tempfile.mkdtemp(
prefix=f".{output_dir.name}.import-",
@@ -171,6 +194,7 @@ def main() -> int:
print(f"Error: failed to extract PPTX metadata: {exc}")
return 1
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest_path.write_text(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
@@ -192,12 +216,12 @@ def main() -> int:
from pptx_to_svg.converter import ConvertOptions
options = ConvertOptions(
- media_subdir="assets",
+ images_subdir="images",
embed_images=args.embed_images,
keep_hidden=False,
inheritance_mode=args.inheritance_mode,
asset_name_map=(
- manifest.get("assets", {}).get("assetMap", {})
+ manifest.get("images", {}).get("imageMap", {})
if manifest else {}
),
)
@@ -223,7 +247,7 @@ def main() -> int:
SOURCE_TEMPLATE_NAME,
_CONVERSION_REPORT_NAME,
},
- managed_relative_paths=previous_assets,
+ managed_relative_paths=previous_resources,
)
except (OSError, RuntimeError, ValueError) as exc:
print(f"Error: failed to publish PPTX template workspace: {exc}")
@@ -233,7 +257,7 @@ def main() -> int:
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(f"Manifest: {_MANIFEST_NAME}")
print(f"Native structure: {CONTRACT_NAME}")
print(f"Source package analysis copy: {SOURCE_TEMPLATE_NAME}")
print(
@@ -241,8 +265,8 @@ def main() -> int:
f"{native_structure['strategy']['recommendedMode']}"
)
print("Template output mode: explicit SVG structure")
- print(f"Assets exported: {len(manifest['assets']['allAssets'])}")
- print(f"Common assets: {len(manifest['assets']['commonAssets'])}")
+ print(f"Images exported: {len(manifest['images']['allImages'])}")
+ print(f"Common images: {len(manifest['images']['commonImages'])}")
print(f"Slides analyzed: {len(manifest['slides'])}")
print(f"Layouts (unique): {len(manifest.get('layouts', []))}")
print(f"Masters (unique): {len(manifest.get('masters', []))}")
diff --git a/skills/ppt-master/scripts/pptx_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg.py
index cf69dddc..ac1eed71 100644
--- a/skills/ppt-master/scripts/pptx_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg.py
@@ -3,20 +3,24 @@
Usage:
python3 pptx_to_svg.py <pptx_file> [-o <output_dir>] [--embed-images]
- [--media-subdir <name>] [--keep-hidden]
+ [--images-subdir <name>] [--keep-hidden]
[--inheritance-mode {both,layered,flat}]
[--roundtrip]
[--strict]
-Output structure (default --inheritance-mode both):
+Output structure (``--roundtrip``):
<output_dir>/
- svg/ layered machine input: masters/layouts/slides
- svg-flat/ self-contained visual preview slides
+ authoring-svg-flat/ sole editable SVG page source
animations.json normalized transition/object-motion sidecar
- <media_subdir>/ (default: assets/)
- image1.png
- image2.png
- ...
+ images/ raster/SVG/EMF/WMF picture resources
+ sounds/ transition/object cue audio, when present
+ audio/ source narration/media audio, when present
+ video/ source video bytes, when present
+ notes/ imported speaker notes, when present
+ native-payloads/ opaque source payloads, when present
+ analysis/ structure, manifests, and immutable SVG backing
+ validation/ conversion diagnostics
+ sources/source.pptx immutable backing package in --roundtrip
If -o is omitted, writes alongside the source file as <pptx_stem>_pptx_to_svg/.
@@ -37,6 +41,12 @@ from zipfile import BadZipFile
sys.path.insert(0, str(Path(__file__).resolve().parent))
from console_encoding import configure_utf8_stdio
+from pptx_workspace import (
+ AUTHORING_SVG_FLAT_DIR,
+ CONVERSION_REPORT_PATH,
+ NATIVE_STRUCTURE_PATH,
+ SOURCE_PPTX_PATH,
+)
from pptx_to_svg import convert_pptx_to_svg
from pptx_to_svg.converter import ConvertOptions
@@ -83,9 +93,14 @@ def parse_args() -> argparse.Namespace:
help="Output directory (default: <pptx_stem>_pptx_to_svg beside source)",
)
parser.add_argument(
- "--media-subdir",
- default="assets",
- help="Subdirectory for extracted media (default: assets)",
+ "--images-subdir",
+ default="images",
+ help="Subdirectory for extracted image resources (default: images)",
+ )
+ parser.add_argument(
+ "--sounds-subdir",
+ default="sounds",
+ help="Subdirectory for transition/object cue audio (default: sounds)",
)
parser.add_argument(
"--embed-images",
@@ -105,7 +120,9 @@ def parse_args() -> argparse.Namespace:
"How to render inheritance. 'both' (default) writes layered SVGs "
"under svg/ and complete preview slides under svg-flat/. "
"'layered' writes only svg/ plus inheritance.json. 'flat' writes "
- "self-contained slides under svg/ for backward compatibility."
+ "self-contained slides under svg/. Round-trip import requires "
+ "'both' internally and publishes authoring-svg-flat/ as its sole "
+ "editable SVG source."
),
)
parser.add_argument(
@@ -120,9 +137,9 @@ def parse_args() -> argparse.Namespace:
"--roundtrip",
action="store_true",
help=(
- "Also preserve a validated source package/Layout sidecar for the "
- "diagnostic SVG-to-PPTX --roundtrip path. Requires layered or both "
- "inheritance output."
+ "Create the source-preserving SVG round-trip workspace, including "
+ "authoring-svg-flat/, semantic resources, and immutable analysis "
+ "backing. Requires --inheritance-mode both."
),
)
return parser.parse_args()
@@ -145,7 +162,8 @@ def main() -> int:
)
options = ConvertOptions(
- media_subdir=args.media_subdir,
+ images_subdir=args.images_subdir,
+ sound_subdir=args.sounds_subdir,
embed_images=args.embed_images,
keep_hidden=args.keep_hidden,
inheritance_mode=args.inheritance_mode,
@@ -171,7 +189,7 @@ def main() -> int:
if result.diagnostics:
print(
f"Warning: {len(result.diagnostics)} source construct(s) were "
- "normalized, omitted, or replaced; see conversion-report.json.",
+ "normalized, omitted, or replaced; see the validation report.",
file=sys.stderr,
)
for item in result.diagnostics[:20]:
@@ -211,10 +229,11 @@ def main() -> int:
)
print(f"Output: {output_dir}")
print(f"Animation config: {output_dir / 'animations.json'}")
- print(f"Conversion report: {output_dir / 'conversion-report.json'}")
+ print(f"Conversion report: {output_dir / CONVERSION_REPORT_PATH}")
if result.native_structure is not None:
- print(f"Round-trip source: {output_dir / 'source_template.pptx'}")
- print(f"Round-trip structure: {output_dir / 'native_structure.json'}")
+ print(f"Editable SVG source: {output_dir / AUTHORING_SVG_FLAT_DIR}")
+ print(f"Round-trip source: {output_dir / SOURCE_PPTX_PATH}")
+ print(f"Round-trip structure: {output_dir / NATIVE_STRUCTURE_PATH}")
return 0
diff --git a/skills/ppt-master/scripts/pptx_to_svg/converter.py b/skills/ppt-master/scripts/pptx_to_svg/converter.py
index 60b12391..72b5b790 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/converter.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/converter.py
@@ -21,10 +21,10 @@ import re
import shutil
import tempfile
from collections.abc import Callable
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from html import unescape
from pathlib import Path, PurePosixPath
-from urllib.parse import unquote, urlsplit
+from urllib.parse import unquote, urlsplit, urlunsplit
from xml.etree import ElementTree as ET
from xml.sax.saxutils import quoteattr
@@ -35,6 +35,22 @@ from pptx_embedded_fonts import (
capture_embedded_fonts,
write_embedded_font_bundle,
)
+from pptx_workspace import (
+ AUTHORING_SVG_FLAT_DIR,
+ CONVERSION_REPORT_PATH,
+ NATIVE_STRUCTURE_PATH,
+ ROUNDTRIP_FLAT_SVG_DIR,
+ ROUNDTRIP_LAYERED_SVG_DIR,
+ ROUNDTRIP_MANIFEST_PATH,
+ SOURCE_PPTX_PATH,
+ PackageResourceInventory,
+ conversion_report_path,
+ inventory_package_resources,
+ reject_removed_workspace_layout,
+ slide_animation_config_sha256,
+ write_workspace_resources,
+)
+from svg_authoring_view import project_svg_batch
from svg_to_pptx.animation_config import (
validate_animation_config_errors,
validate_transition_config,
@@ -63,6 +79,7 @@ from .ooxml_loader import (
SlideRef,
part_show_master_sp,
)
+from .notes_import import ImportedSpeakerNote, import_speaker_notes
from .slide_to_svg import assemble_part_solo, assemble_slide
from .transition_import import (
TransitionImportError,
@@ -81,14 +98,18 @@ _MANAGED_TRANSITION_SOUND_RE = re.compile(
_SVG_HREF_RE = re.compile(
r"\b(?:href|xlink:href)\s*=\s*[\"']([^\"']+)[\"']"
)
+_SVG_HREF_ATTRIBUTE_RE = re.compile(
+ r"(?P<prefix>\b(?:href|xlink:href)\s*=\s*)"
+ r"(?P<quote>[\"'])(?P<value>[^\"']+)(?P=quote)"
+)
-def _validate_media_subdir(value: str) -> None:
+def _validate_resource_subdir(value: str) -> None:
"""Reject media output paths that can escape the conversion workspace."""
path = Path(value)
if path.drive or path.anchor or path.is_absolute() or ".." in path.parts:
raise ValueError(
- f"media_subdir must stay within the output workspace: {value!r}"
+ f"resource subdirectory must stay within the output workspace: {value!r}"
)
@@ -166,8 +187,10 @@ def _extract_theme_info(
class ConvertOptions:
"""Convert behavior knobs.
- media_subdir: where to write media files relative to output_dir. SVG image
- href will use './<media_subdir>/<filename>'.
+ images_subdir: where to write image files relative to output_dir. SVG image
+ href will use './<images_subdir>/<filename>'.
+ sound_subdir: where to write transition/object cue audio relative to
+ output_dir. New workspaces use ``sounds``.
embed_images: when True, base64-encode images inline instead of writing
files. Default False (matches svg_to_pptx default of external images).
keep_hidden: include shapes marked hidden="1". Default False.
@@ -181,17 +204,15 @@ class ConvertOptions:
svg/inheritance.json describing the reuse graph. Optimised for
template authors who need to see "what is shared vs. unique".
- "flat": inline the inherited shapes visible under the source
- ``showMasterSp`` flags. Used by svg_to_pptx round-trip and any caller
- that wants self-contained slides (preview pages, screenshot pipelines).
+ ``showMasterSp`` flags for preview pages and screenshot pipelines.
strict: stop on the first unsupported or malformed source construct.
Default False keeps usable content and records structured diagnostics.
- roundtrip: preserve a validated source-package structure sidecar and mark
- layered slide SVG roots with their exact source Layout identities.
- This is an opt-in diagnostic path for reconstructing the imported deck;
- it does not make SVG a lossless container for arbitrary PPTX semantics.
+ roundtrip: create the fixed semantic workspace and source-preserving
+ package contracts used by the editable ``authoring-svg-flat/`` route.
"""
- media_subdir: str = "assets"
+ images_subdir: str = "images"
+ sound_subdir: str = "sounds"
embed_images: bool = False
keep_hidden: bool = False
inheritance_mode: str = "both"
@@ -242,6 +263,10 @@ class ConvertResult:
theme_fonts: dict[str, str] = field(default_factory=dict)
theme_xml: bytes | None = None
embedded_fonts: EmbeddedFontBundle | None = None
+ resource_inventory: PackageResourceInventory = field(
+ default_factory=PackageResourceInventory
+ )
+ speaker_notes: tuple[ImportedSpeakerNote, ...] = ()
native_structure: dict[str, object] | None = None
source_pptx_path: Path | None = None
layouts: list[PartArtifact] = field(default_factory=list)
@@ -335,6 +360,7 @@ def _roundtrip_native_structure(
"slides": [
{
"index": slide.index,
+ "slidePath": slide.part.path,
"layoutPath": slide.layout.path if slide.layout else None,
"masterPath": slide.master.path if slide.master else None,
"showInheritedShapes": part_show_master_sp(slide.part),
@@ -467,13 +493,23 @@ def convert_pptx_to_svg(
f"inheritance_mode must be 'flat', 'layered', or 'both', "
f"got {options.inheritance_mode!r}"
)
- if options.roundtrip and options.inheritance_mode == "flat":
+ if options.roundtrip and options.inheritance_mode != "both":
+ raise ValueError(
+ "roundtrip requires inheritance_mode 'both' so the editable flat "
+ "authoring view and layered source backing are both complete"
+ )
+ if options.roundtrip and (
+ options.images_subdir != "images"
+ or options.sound_subdir != "sounds"
+ or options.embed_images
+ ):
raise ValueError(
- "roundtrip requires inheritance_mode 'layered' or 'both' so source "
- "Master/Layout visuals are not duplicated on regenerated slides"
+ "roundtrip uses fixed images/ and sounds/ resource directories "
+ "and does not support inline images"
)
if not options.embed_images:
- _validate_media_subdir(options.media_subdir)
+ _validate_resource_subdir(options.images_subdir)
+ _validate_resource_subdir(options.sound_subdir)
emit_layered = options.inheritance_mode in {"layered", "both"}
emit_flat = options.inheritance_mode in {"flat", "both"}
result = ConvertResult(
@@ -482,6 +518,12 @@ def convert_pptx_to_svg(
)
with OoxmlPackage(pptx_path) as pkg:
+ if pkg.zip is not None:
+ result.resource_inventory = inventory_package_resources(pkg.zip)
+ image_name_map = result.resource_inventory.image_name_map()
+ image_name_map.update(options.asset_name_map)
+ options = replace(options, asset_name_map=image_name_map)
+ result.speaker_notes = import_speaker_notes(pkg)
result.canvas_px = pkg.slide_size_px
# Default theme summary is kept for compatibility; conversion itself
@@ -635,7 +677,8 @@ def _read_back_slide_transition(
transition = import_slide_transition(
pkg,
slide,
- media_subdir=options.media_subdir,
+ media_subdir=options.sound_subdir,
+ resource_path_map=result.resource_inventory.path_map(),
)
except TransitionImportError as exc:
message = f"Slide transition was not reconstructed: {exc}"
@@ -742,7 +785,7 @@ def _convert_slide(
svg, media = assemble_slide(
pkg, slide, palette,
theme_fonts=theme_fonts,
- media_subdir=options.media_subdir,
+ media_subdir=options.images_subdir,
embed_images=options.embed_images,
keep_hidden=options.keep_hidden,
inheritance_mode=mode,
@@ -841,7 +884,7 @@ def _render_part(
role=role,
parent_master=parent_master,
theme_fonts=theme_fonts,
- media_subdir=options.media_subdir,
+ media_subdir=options.images_subdir,
embed_images=options.embed_images,
keep_hidden=options.keep_hidden,
asset_name_map=options.asset_name_map,
@@ -873,11 +916,14 @@ def _path_lexists(path: Path) -> bool:
def _managed_svg_paths(output_dir: Path) -> list[Path]:
"""Return converter-owned SVG files without traversing user directories."""
managed: list[Path] = []
- for dirname, filename_re in (
- ("svg", _MANAGED_PRIMARY_SVG_RE),
- ("svg-flat", _MANAGED_FLAT_SVG_RE),
+ for relative_dir, filename_re, carries_inheritance in (
+ (Path("svg"), _MANAGED_PRIMARY_SVG_RE, True),
+ (Path("svg-flat"), _MANAGED_FLAT_SVG_RE, False),
+ (ROUNDTRIP_LAYERED_SVG_DIR, _MANAGED_PRIMARY_SVG_RE, True),
+ (ROUNDTRIP_FLAT_SVG_DIR, _MANAGED_FLAT_SVG_RE, False),
+ (AUTHORING_SVG_FLAT_DIR, _MANAGED_FLAT_SVG_RE, False),
):
- svg_dir = output_dir / dirname
+ svg_dir = output_dir / relative_dir
if svg_dir.is_symlink():
managed.append(svg_dir)
continue
@@ -890,14 +936,22 @@ def _managed_svg_paths(output_dir: Path) -> list[Path]:
and (path.is_file() or path.is_symlink())
)
inheritance = svg_dir / "inheritance.json"
- if dirname == "svg" and _path_lexists(inheritance):
+ if carries_inheritance and _path_lexists(inheritance):
managed.append(inheritance)
+ if relative_dir == AUTHORING_SVG_FLAT_DIR:
+ for filename in (
+ "authoring_manifest.json",
+ "authoring_summary.json",
+ ):
+ sidecar = svg_dir / filename
+ if _path_lexists(sidecar):
+ managed.append(sidecar)
return managed
def _managed_report_artifact_paths(output_dir: Path) -> set[Path]:
"""Return optional artifacts owned by the previous conversion report."""
- report_path = output_dir / "conversion-report.json"
+ report_path = conversion_report_path(output_dir)
if report_path.is_symlink() or not report_path.is_file():
return set()
try:
@@ -911,10 +965,14 @@ def _managed_report_artifact_paths(output_dir: Path) -> set[Path]:
return set()
managed = {Path("animations.json")}
- if artifacts.get("sourceTemplate") == SOURCE_TEMPLATE_NAME:
- managed.add(Path(SOURCE_TEMPLATE_NAME))
- if artifacts.get("nativeStructure") == NATIVE_STRUCTURE_NAME:
- managed.add(Path(NATIVE_STRUCTURE_NAME))
+ source_template = artifacts.get("sourceTemplate")
+ if source_template == SOURCE_TEMPLATE_NAME:
+ managed.add(Path(str(source_template)))
+ native_structure = artifacts.get("nativeStructure")
+ if native_structure == NATIVE_STRUCTURE_NAME:
+ managed.add(Path(str(native_structure)))
+ if artifacts.get("roundtripManifest") == ROUNDTRIP_MANIFEST_PATH.as_posix():
+ managed.add(ROUNDTRIP_MANIFEST_PATH)
embedded_font_paths = [artifacts.get("embeddedFontManifest")]
raw_font_parts = artifacts.get("embeddedFontParts")
if isinstance(raw_font_parts, list):
@@ -935,6 +993,32 @@ def _managed_report_artifact_paths(output_dir: Path) -> set[Path]:
continue
managed.add(path)
animation_media = artifacts.get("animationMedia")
+ managed_lists = [animation_media, artifacts.get("resources"), artifacts.get("notes")]
+ managed_resource_roots = {
+ "audio",
+ "images",
+ "native-payloads",
+ "notes",
+ "sounds",
+ "video",
+ }
+ for values in managed_lists:
+ if not isinstance(values, list):
+ continue
+ for value in values:
+ if not isinstance(value, str):
+ continue
+ path = Path(value)
+ if (
+ path.drive
+ or path.anchor
+ or path.is_absolute()
+ or not path.parts
+ or ".." in path.parts
+ or path.parts[0] not in managed_resource_roots
+ ):
+ continue
+ managed.add(path)
if not isinstance(animation_media, list):
return managed
for value in animation_media:
@@ -1144,7 +1228,7 @@ def publish_staged_workspace(
for path in managed_svg
}
relative_paths.update(_referenced_local_paths(output_dir, managed_svg))
- relative_paths.add(Path("conversion-report.json"))
+ relative_paths.add(CONVERSION_REPORT_PATH)
relative_paths.update(_managed_report_artifact_paths(output_dir))
relative_paths.update(_validated_relative_paths(managed_root_files or set()))
relative_paths.update(_validated_relative_paths(managed_relative_paths or set()))
@@ -1190,15 +1274,51 @@ def _write_artifact_tree(
"""Write a complete converter roster into an empty staging directory.
Layout:
- - ``svg/`` primary view (layered when emitted, otherwise flat)
- - ``svg-flat/`` self-contained per-slide renders (only in "both" mode)
- - ``<media_subdir>/`` shared image assets, referenced by both views
+ - normal conversion uses ``svg/`` and optional ``svg-flat/``
+ - round-trip conversion keeps immutable SVG backing under ``analysis/``
+ and publishes only ``authoring-svg-flat/`` as the editable page source
+ - ``images/`` shared image assets, referenced by both views
+ - semantic resource directories for sounds, audio, video, and opaque
+ native payloads when the source package contains them
"""
output_dir.mkdir(parents=True, exist_ok=True)
- svg_dir = output_dir / "svg"
- svg_dir.mkdir(exist_ok=True)
- media_dir = output_dir / options.media_subdir
+ svg_dir = output_dir / (
+ ROUNDTRIP_LAYERED_SVG_DIR if options.roundtrip else Path("svg")
+ )
+ svg_dir.mkdir(parents=True, exist_ok=True)
+ media_dir = output_dir / options.images_subdir
+ sound_dir = output_dir / options.sound_subdir
media_written: dict[str, bytes] = {}
+ sounds_written: dict[str, bytes] = {}
+
+ def _svg_for_target(svg: str, target_dir: Path) -> str:
+ """Rebase generated local hrefs from the normal one-level SVG root."""
+ source_dir = output_dir / "svg"
+ project_root = output_dir.resolve()
+
+ def replace_href(match: re.Match[str]) -> str:
+ raw = unescape(match.group("value"))
+ parsed = urlsplit(raw)
+ if (
+ not raw
+ or raw.startswith("#")
+ or parsed.scheme
+ or parsed.netloc
+ or not parsed.path
+ ):
+ return match.group(0)
+ resolved = (source_dir / unquote(parsed.path)).resolve()
+ try:
+ resolved.relative_to(project_root)
+ except ValueError as exc:
+ raise RuntimeError(
+ f"Generated SVG resource escapes the workspace: {raw!r}"
+ ) from exc
+ relative = os.path.relpath(resolved, target_dir).replace(os.sep, "/")
+ rebased = urlunsplit(("", "", relative, parsed.query, parsed.fragment))
+ return f"{match.group('prefix')}{quoteattr(rebased)}"
+
+ return _SVG_HREF_ATTRIBUTE_RE.sub(replace_href, svg)
def _collect_media(media: dict[str, bytes]) -> None:
for filename, blob in media.items():
@@ -1213,18 +1333,34 @@ def _write_artifact_tree(
# Layered mode: write masters and layouts first so they sort ahead of slides.
for art in result.masters:
- (svg_dir / art.filename).write_text(art.svg, encoding="utf-8")
+ (svg_dir / art.filename).write_text(
+ _svg_for_target(art.svg, svg_dir),
+ encoding="utf-8",
+ )
_collect_media(art.media_files)
for art in result.layouts:
- (svg_dir / art.filename).write_text(art.svg, encoding="utf-8")
+ (svg_dir / art.filename).write_text(
+ _svg_for_target(art.svg, svg_dir),
+ encoding="utf-8",
+ )
_collect_media(art.media_files)
# Slides (primary view).
for art in result.slides:
target = svg_dir / f"slide_{art.index:02d}.svg"
- target.write_text(art.svg, encoding="utf-8")
+ target.write_text(
+ _svg_for_target(art.svg, target.parent),
+ encoding="utf-8",
+ )
_collect_media(art.media_files)
- _collect_media(result.animation_media_files)
+ for filename, blob in result.animation_media_files.items():
+ _validate_media_filename(filename)
+ existing = sounds_written.get(filename)
+ if existing is not None and existing != blob:
+ raise RuntimeError(
+ f"Sound filename collision with different bytes: {filename}"
+ )
+ sounds_written[filename] = blob
# Inheritance graph alongside the layered SVGs (only meaningful when we
# actually emitted a layered view).
@@ -1233,21 +1369,31 @@ def _write_artifact_tree(
# Flat companion view (only when result.flat_slides is populated).
if result.flat_slides:
- flat_dir = output_dir / "svg-flat"
- flat_dir.mkdir(exist_ok=True)
+ flat_dir = output_dir / (
+ ROUNDTRIP_FLAT_SVG_DIR if options.roundtrip else Path("svg-flat")
+ )
+ flat_dir.mkdir(parents=True, exist_ok=True)
for art in result.flat_slides:
target = flat_dir / f"slide_{art.index:02d}.svg"
- target.write_text(art.svg, encoding="utf-8")
+ target.write_text(
+ _svg_for_target(art.svg, target.parent),
+ encoding="utf-8",
+ )
_collect_media(art.media_files)
_write_animation_config(output_dir, result)
+ _write_speaker_notes(output_dir, result)
if result.native_structure is not None:
if result.source_pptx_path is None:
raise RuntimeError(
"Round-trip source structure is missing its source PPTX path"
)
- shutil.copy2(result.source_pptx_path, output_dir / SOURCE_TEMPLATE_NAME)
- (output_dir / NATIVE_STRUCTURE_NAME).write_text(
+ source_target = output_dir / SOURCE_TEMPLATE_NAME
+ source_target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(result.source_pptx_path, source_target)
+ structure_target = output_dir / NATIVE_STRUCTURE_NAME
+ structure_target.parent.mkdir(parents=True, exist_ok=True)
+ structure_target.write_text(
json.dumps(
result.native_structure,
ensure_ascii=False,
@@ -1269,6 +1415,11 @@ def _write_artifact_tree(
embedded_fonts_descriptor=embedded_fonts_descriptor,
embedded_font_paths=embedded_font_paths,
)
+ write_workspace_resources(
+ output_dir,
+ result.resource_inventory,
+ include_images=not options.embed_images,
+ )
if media_written:
media_dir.mkdir(parents=True, exist_ok=True)
for filename, blob in media_written.items():
@@ -1284,6 +1435,228 @@ def _write_artifact_tree(
)
continue
target.write_bytes(blob)
+ if sounds_written:
+ sound_dir.mkdir(parents=True, exist_ok=True)
+ for filename, blob in sounds_written.items():
+ target = sound_dir / filename
+ if _path_lexists(target):
+ if (
+ target.is_symlink()
+ or not target.is_file()
+ or target.read_bytes() != blob
+ ):
+ raise RuntimeError(
+ f"Sound filename collision with different bytes: {filename}"
+ )
+ continue
+ target.write_bytes(blob)
+ if result.native_structure is not None:
+ _write_roundtrip_manifest(output_dir, result, options)
+ flat_dir = output_dir / ROUNDTRIP_FLAT_SVG_DIR
+ authoring_dir = output_dir / AUTHORING_SVG_FLAT_DIR
+ mapping = [
+ (source, authoring_dir / source.name)
+ for source in sorted(flat_dir.glob("slide_*.svg"))
+ ]
+ if len(mapping) != len(result.slides):
+ raise RuntimeError(
+ "Round-trip flat backing roster does not match the slide roster"
+ )
+ project_svg_batch(
+ mapping,
+ flat_dir,
+ authoring_dir,
+ force=False,
+ projection_kind="flat",
+ )
+
+
+def _sha256_file(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 _write_speaker_notes(output_dir: Path, result: ConvertResult) -> None:
+ """Write imported notes into the standard per-slide Markdown contract."""
+ if not result.speaker_notes:
+ return
+ notes_dir = output_dir / "notes"
+ notes_dir.mkdir(parents=True, exist_ok=True)
+ combined = ["# Speaker Notes"]
+ for note in result.speaker_notes:
+ content = note.markdown.strip() + "\n"
+ (notes_dir / note.filename).write_text(content, encoding="utf-8")
+ combined.extend([
+ "",
+ f"## Slide {note.slide_index:02d}",
+ "",
+ note.markdown.strip(),
+ ])
+ (notes_dir / "total.md").write_text(
+ "\n".join(combined).rstrip() + "\n",
+ encoding="utf-8",
+ )
+
+
+def _write_roundtrip_manifest(
+ output_dir: Path,
+ result: ConvertResult,
+ options: ConvertOptions,
+) -> None:
+ """Record immutable source, editable sidecars, and semantic resources."""
+ source_path = output_dir / SOURCE_PPTX_PATH
+ animation_path = output_dir / "animations.json"
+ resource_manifest = result.resource_inventory.manifest(
+ include_images=not options.embed_images,
+ )
+ materialized_resource_paths = {
+ Path(str(item["workspacePath"]))
+ for item in resource_manifest["items"]
+ if isinstance(item, dict)
+ and item.get("materialized") is True
+ and isinstance(item.get("workspacePath"), str)
+ }
+ notes_by_index = {
+ note.slide_index: note
+ for note in result.speaker_notes
+ }
+ flat_by_index = {
+ slide.index: slide
+ for slide in result.flat_slides
+ }
+ native_slides = []
+ if isinstance(result.native_structure, dict):
+ raw_slides = result.native_structure.get("slides")
+ if isinstance(raw_slides, list):
+ native_slides = raw_slides
+ native_by_index = {
+ int(item.get("index")): item
+ for item in native_slides
+ if isinstance(item, dict) and isinstance(item.get("index"), int)
+ }
+ native_masters = (
+ result.native_structure.get("masters")
+ if isinstance(result.native_structure, dict)
+ else None
+ )
+ master_parts = {
+ str(item.get("key")): str(item.get("packagePart"))
+ for item in native_masters or []
+ if isinstance(item, dict)
+ and item.get("key")
+ and item.get("packagePart")
+ }
+ native_layouts = (
+ result.native_structure.get("layouts")
+ if isinstance(result.native_structure, dict)
+ else None
+ )
+ layout_parts = {
+ str(item.get("key")): str(item.get("packagePart"))
+ for item in native_layouts or []
+ if isinstance(item, dict)
+ and item.get("key")
+ and item.get("packagePart")
+ }
+ slides: list[dict[str, object]] = []
+ for slide in result.slides:
+ layered_path = ROUNDTRIP_LAYERED_SVG_DIR / f"slide_{slide.index:02d}.svg"
+ native_slide = native_by_index.get(slide.index, {})
+ row: dict[str, object] = {
+ "index": slide.index,
+ "sourcePart": native_slide.get("packagePart"),
+ "layoutPart": layout_parts.get(str(native_slide.get("layoutKey"))),
+ "masterPart": master_parts.get(str(native_slide.get("masterKey"))),
+ "layeredSvg": layered_path.as_posix(),
+ "layeredSvgSha256": _sha256_file(output_dir / layered_path),
+ "animationSha256": slide_animation_config_sha256(
+ result.animation_config,
+ f"slide_{slide.index:02d}",
+ ),
+ }
+ referenced_svg_paths = [output_dir / layered_path]
+ if slide.index in flat_by_index:
+ flat_path = ROUNDTRIP_FLAT_SVG_DIR / f"slide_{slide.index:02d}.svg"
+ row["flatSvg"] = flat_path.as_posix()
+ row["flatSvgSha256"] = _sha256_file(output_dir / flat_path)
+ referenced_svg_paths.append(output_dir / flat_path)
+ derived_paths = sorted(
+ _referenced_local_paths(output_dir, referenced_svg_paths)
+ - materialized_resource_paths,
+ key=lambda path: path.as_posix(),
+ )
+ derived_resources: list[dict[str, str]] = []
+ for relative in derived_paths:
+ target = output_dir / relative
+ if not target.is_file():
+ raise RuntimeError(
+ "Round-trip SVG references a missing derived resource: "
+ f"{relative.as_posix()}"
+ )
+ derived_resources.append({
+ "file": relative.as_posix(),
+ "sha256": _sha256_file(target),
+ })
+ row["derivedResources"] = derived_resources
+ note = notes_by_index.get(slide.index)
+ if note is not None:
+ note_path = Path("notes") / note.filename
+ row["notes"] = {
+ "file": note_path.as_posix(),
+ "sha256": _sha256_file(output_dir / note_path),
+ "sourcePart": note.source_part,
+ "sourceSha256": note.source_sha256,
+ }
+ slides.append(row)
+ payload = {
+ "schema": "ppt-master.roundtrip-workspace.v1",
+ "source": {
+ "file": SOURCE_PPTX_PATH.as_posix(),
+ "sha256": _sha256_file(source_path),
+ },
+ "structure": NATIVE_STRUCTURE_PATH.as_posix(),
+ "conversionReport": CONVERSION_REPORT_PATH.as_posix(),
+ "sidecars": {
+ "animations": {
+ "file": "animations.json",
+ "sha256": _sha256_file(animation_path),
+ },
+ "notesTotal": (
+ {
+ "file": "notes/total.md",
+ "sha256": _sha256_file(output_dir / "notes/total.md"),
+ }
+ if result.speaker_notes
+ else None
+ ),
+ },
+ "directories": {
+ "authoringSvg": AUTHORING_SVG_FLAT_DIR.as_posix(),
+ "layeredSvg": ROUNDTRIP_LAYERED_SVG_DIR.as_posix(),
+ "flatSvg": (
+ ROUNDTRIP_FLAT_SVG_DIR.as_posix()
+ if result.flat_slides
+ else None
+ ),
+ "images": options.images_subdir,
+ "sounds": options.sound_subdir,
+ "audio": "audio",
+ "video": "video",
+ "notes": "notes",
+ "nativePayloads": "native-payloads",
+ },
+ "slides": slides,
+ "resources": resource_manifest,
+ }
+ target = output_dir / ROUNDTRIP_MANIFEST_PATH
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(
+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
def _write_artifacts(
@@ -1293,6 +1666,7 @@ def _write_artifacts(
) -> None:
"""Stage a complete conversion, then atomically publish its exact roster."""
output_dir = output_dir.absolute()
+ reject_removed_workspace_layout(output_dir)
output_dir.parent.mkdir(parents=True, exist_ok=True)
staging_root = Path(tempfile.mkdtemp(
prefix=f".{output_dir.name}.convert-",
@@ -1316,7 +1690,7 @@ def _write_conversion_report(
) -> None:
"""Write the user-visible tolerant-import report."""
animation_media = [
- (PurePosixPath(options.media_subdir) / filename).as_posix()
+ (PurePosixPath(options.sound_subdir) / filename).as_posix()
for filename in sorted(result.animation_media_files)
]
source_theme: dict[str, object] = {
@@ -1341,6 +1715,15 @@ def _write_conversion_report(
artifacts: dict[str, object] = {
"animationConfig": "animations.json",
"animationMedia": animation_media,
+ "resources": [
+ resource.workspace_path
+ for resource in result.resource_inventory.resources
+ if not (options.embed_images and resource.kind == "image")
+ ],
+ "notes": [
+ (Path("notes") / note.filename).as_posix()
+ for note in result.speaker_notes
+ ] + (["notes/total.md"] if result.speaker_notes else []),
}
if embedded_font_paths:
artifacts["embeddedFontManifest"] = embedded_font_paths[-1]
@@ -1348,6 +1731,7 @@ def _write_conversion_report(
if result.native_structure is not None:
artifacts["sourceTemplate"] = SOURCE_TEMPLATE_NAME
artifacts["nativeStructure"] = NATIVE_STRUCTURE_NAME
+ artifacts["roundtripManifest"] = ROUNDTRIP_MANIFEST_PATH.as_posix()
report = {
"schemaVersion": 1,
"source": result.source_file,
@@ -1360,7 +1744,9 @@ def _write_conversion_report(
"sourceDocument": source_document,
"diagnostics": [item.to_dict() for item in result.diagnostics],
}
- (output_dir / "conversion-report.json").write_text(
+ report_path = output_dir / CONVERSION_REPORT_PATH
+ report_path.parent.mkdir(parents=True, exist_ok=True)
+ report_path.write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
diff --git a/skills/ppt-master/scripts/pptx_to_svg/notes_import.py b/skills/ppt-master/scripts/pptx_to_svg/notes_import.py
new file mode 100644
index 00000000..995c9bfa
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_to_svg/notes_import.py
@@ -0,0 +1,114 @@
+"""Import PowerPoint speaker notes into the project notes Markdown contract."""
+
+from __future__ import annotations
+
+import hashlib
+from dataclasses import dataclass
+from xml.etree import ElementTree as ET
+
+from .emu_units import NS
+from .ooxml_loader import OoxmlPackage
+
+
+_NOTES_REL_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide"
+)
+_EXCLUDED_PLACEHOLDER_TYPES = frozenset({
+ "dt",
+ "ftr",
+ "hdr",
+ "sldImg",
+ "sldNum",
+})
+
+
+@dataclass(frozen=True)
+class ImportedSpeakerNote:
+ """One source notes part projected into editable Markdown."""
+
+ slide_index: int
+ source_part: str
+ source_sha256: str
+ markdown: str
+
+ @property
+ def filename(self) -> str:
+ """Return the canonical index-based notes filename."""
+ return f"slide_{self.slide_index:02d}.md"
+
+
+def _paragraph_text(paragraph: ET.Element) -> str:
+ pieces: list[str] = []
+ for node in paragraph.iter():
+ tag = node.tag.rsplit("}", 1)[-1] if isinstance(node.tag, str) else ""
+ if tag == "t" and node.text:
+ pieces.append(node.text)
+ elif tag == "br":
+ pieces.append("\n")
+ text = "".join(pieces).strip()
+ if not text:
+ return ""
+ paragraph_properties = paragraph.find("a:pPr", NS)
+ if (
+ paragraph_properties is not None
+ and paragraph_properties.find("a:buChar", NS) is not None
+ ):
+ return f"- {text}"
+ return text
+
+
+def _notes_markdown(root: ET.Element) -> str:
+ blocks: list[str] = []
+ for shape in root.findall(".//p:sp", NS):
+ placeholder = shape.find("p:nvSpPr/p:nvPr/p:ph", NS)
+ placeholder_type = placeholder.get("type") if placeholder is not None else None
+ if placeholder_type in _EXCLUDED_PLACEHOLDER_TYPES:
+ continue
+ text_body = shape.find("p:txBody", NS)
+ if text_body is None:
+ continue
+ paragraphs = [
+ text
+ for paragraph in text_body.findall("a:p", NS)
+ if (text := _paragraph_text(paragraph))
+ ]
+ if paragraphs:
+ blocks.append("\n".join(paragraphs))
+ return "\n\n".join(blocks).strip()
+
+
+def import_speaker_notes(pkg: OoxmlPackage) -> tuple[ImportedSpeakerNote, ...]:
+ """Return every non-empty source speaker note in presentation order."""
+ notes: list[ImportedSpeakerNote] = []
+ for slide in pkg.iter_slides():
+ source_part = next(
+ (
+ relationship.get("target", "")
+ for relationship in slide.part.rels.values()
+ if relationship.get("type") == _NOTES_REL_TYPE
+ and not relationship.get("external")
+ ),
+ "",
+ )
+ if not source_part:
+ continue
+ payload = pkg.read_part_bytes(source_part)
+ if payload is None:
+ continue
+ try:
+ root = ET.fromstring(payload)
+ except ET.ParseError:
+ continue
+ markdown = _notes_markdown(root)
+ if not markdown:
+ continue
+ notes.append(ImportedSpeakerNote(
+ slide_index=slide.index,
+ source_part=source_part,
+ source_sha256=hashlib.sha256(payload).hexdigest(),
+ markdown=markdown,
+ ))
+ return tuple(notes)
+
+
+__all__ = ["ImportedSpeakerNote", "import_speaker_notes"]
diff --git a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py
index d6325225..78eecc4b 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py
@@ -86,7 +86,7 @@ def convert_blip_fill(
slide_part: PartRef,
pkg: OoxmlPackage,
*,
- media_subdir: str = "assets",
+ media_subdir: str = "images",
embed_inline: bool = False,
asset_name_map: dict[str, str] | None = None,
strict: bool = False,
@@ -205,7 +205,7 @@ def convert_picture(
slide_part: PartRef,
pkg: OoxmlPackage,
*,
- media_subdir: str = "assets",
+ media_subdir: str = "images",
embed_inline: bool = False,
asset_name_map: dict[str, str] | None = None,
strict: bool = False,
diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
index 51030871..bc3afc2e 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
@@ -119,7 +119,7 @@ class AssemblyContext:
slide_part: PartRef
slide_number: int | None = None
theme_fonts: dict[str, str] = field(default_factory=dict)
- media_subdir: str = "assets"
+ media_subdir: str = "images"
embed_images: bool = False
keep_hidden: bool = False
strict: bool = False
@@ -225,7 +225,7 @@ def assemble_slide(
palette: ColorPalette | None,
*,
theme_fonts: dict[str, str] | None = None,
- media_subdir: str = "assets",
+ media_subdir: str = "images",
embed_images: bool = False,
keep_hidden: bool = False,
inheritance_mode: str = "flat",
@@ -337,7 +337,7 @@ def assemble_part_solo(
role: str,
parent_master: PartRef | None = None,
theme_fonts: dict[str, str] | None = None,
- media_subdir: str = "assets",
+ media_subdir: str = "images",
embed_images: bool = False,
keep_hidden: bool = False,
asset_name_map: dict[str, str] | None = None,
diff --git a/skills/ppt-master/scripts/pptx_to_svg/transition_import.py b/skills/ppt-master/scripts/pptx_to_svg/transition_import.py
index c61745f2..8c7cd30f 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/transition_import.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/transition_import.py
@@ -112,6 +112,7 @@ def import_slide_transition(
slide: SlideRef,
*,
media_subdir: str,
+ resource_path_map: dict[str, str] | None = None,
) -> TransitionImport | None:
"""Read one slide transition and resolve its optional WAV relationship."""
slide_xml = pkg.read_part_bytes(slide.part.path)
@@ -127,15 +128,19 @@ def import_slide_transition(
media_files: dict[str, bytes] = {}
relationship_id = readback.summary.sound_relationship_id
if relationship_id is not None:
- sound_path, sound_bytes = _resolve_transition_sound(
+ source_part, sound_path, sound_bytes = _resolve_transition_sound(
pkg,
slide,
relationship_id,
)
- media_files[sound_path] = sound_bytes
- config["sound"] = (
- PurePosixPath(media_subdir) / sound_path
- ).as_posix()
+ mapped_path = (resource_path_map or {}).get(source_part)
+ if mapped_path is not None:
+ config["sound"] = mapped_path
+ else:
+ media_files[sound_path] = sound_bytes
+ config["sound"] = (
+ PurePosixPath(media_subdir) / sound_path
+ ).as_posix()
return TransitionImport(config=config, media_files=media_files)
@@ -160,7 +165,7 @@ def _resolve_transition_sound(
pkg: OoxmlPackage,
slide: SlideRef,
relationship_id: str,
-) -> tuple[str, bytes]:
+) -> tuple[str, str, bytes]:
relationship = slide.part.rels.get(relationship_id)
if relationship is None:
raise TransitionImportError(
@@ -189,7 +194,7 @@ def _resolve_transition_sound(
f"transition sound part is not a valid WAV file: {target}"
)
digest = hashlib.sha256(payload).hexdigest()[:16]
- return f"transition_sound_{digest}.wav", payload
+ return target, f"transition_sound_{digest}.wav", payload
__all__ = [
diff --git a/skills/ppt-master/scripts/pptx_workspace.py b/skills/ppt-master/scripts/pptx_workspace.py
new file mode 100644
index 00000000..c2dbff86
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_workspace.py
@@ -0,0 +1,580 @@
+#!/usr/bin/env python3
+"""
+PPT Master - PPTX Semantic Workspace
+
+Own the semantic on-disk paths and package-resource inventory shared by PPTX
+import, template preparation, and source-preserving SVG round trips.
+
+Usage:
+ Imported by pptx_to_svg.py, pptx_template_import.py, and svg_to_pptx.py.
+
+Examples:
+ inventory = inventory_package_resources(package)
+ write_workspace_resources(workspace, inventory)
+
+Dependencies:
+ None (only uses standard library)
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import posixpath
+import re
+import zipfile
+from collections import defaultdict
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+from xml.etree import ElementTree as ET
+
+
+SOURCE_PPTX_PATH = Path("sources/source.pptx")
+NATIVE_STRUCTURE_PATH = Path("analysis/native_structure.json")
+ROUNDTRIP_MANIFEST_PATH = Path("analysis/roundtrip_manifest.json")
+TEMPLATE_MANIFEST_PATH = Path("analysis/manifest.json")
+CONVERSION_REPORT_PATH = Path("validation/conversion-report.json")
+AUTHORING_SVG_FLAT_DIR = Path("authoring-svg-flat")
+ROUNDTRIP_SVG_ROOT = Path("analysis/roundtrip-svg")
+ROUNDTRIP_LAYERED_SVG_DIR = ROUNDTRIP_SVG_ROOT / "layered"
+ROUNDTRIP_FLAT_SVG_DIR = ROUNDTRIP_SVG_ROOT / "flat"
+REMOVED_WORKSPACE_ENTRIES = (
+ Path("assets"),
+ Path("conversion-report.json"),
+ Path("manifest.json"),
+ Path("native_structure.json"),
+ Path("source_template.pptx"),
+ Path("svg_flat"),
+)
+
+IMAGE_EXTENSIONS = frozenset({
+ ".avif",
+ ".bmp",
+ ".emf",
+ ".gif",
+ ".jpeg",
+ ".jpg",
+ ".png",
+ ".svg",
+ ".tif",
+ ".tiff",
+ ".webp",
+ ".wmf",
+})
+VIDEO_EXTENSIONS = frozenset({
+ ".avi",
+ ".m4v",
+ ".mkv",
+ ".mov",
+ ".mp4",
+ ".mpeg",
+ ".mpg",
+ ".webm",
+ ".wmv",
+})
+AUDIO_EXTENSIONS = frozenset({
+ ".aac",
+ ".aif",
+ ".aiff",
+ ".flac",
+ ".m4a",
+ ".mp3",
+ ".oga",
+ ".ogg",
+ ".wav",
+ ".wma",
+})
+
+_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
+_DOC_REL_NS = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+)
+_TRANSITION_TAG = (
+ "{http://schemas.openxmlformats.org/presentationml/2006/main}transition"
+)
+_REL_ATTR_PREFIX = f"{{{_DOC_REL_NS}}}"
+
+
+def source_pptx_path(workspace: Path) -> Path:
+ """Return the semantic preserved-source package path."""
+ return workspace / SOURCE_PPTX_PATH
+
+
+def native_structure_path(workspace: Path) -> Path:
+ """Return the semantic native-structure contract path."""
+ return workspace / NATIVE_STRUCTURE_PATH
+
+
+def template_manifest_path(workspace: Path) -> Path:
+ """Return the semantic template-import manifest path."""
+ return workspace / TEMPLATE_MANIFEST_PATH
+
+
+def conversion_report_path(workspace: Path) -> Path:
+ """Return the semantic conversion-report path."""
+ return workspace / CONVERSION_REPORT_PATH
+
+
+def reject_removed_workspace_layout(workspace: Path) -> None:
+ """Reject mixed workspaces instead of guessing or migrating old paths."""
+ if not workspace.is_dir():
+ return
+ present = [
+ path.as_posix()
+ for path in REMOVED_WORKSPACE_ENTRIES
+ if (workspace / path).exists()
+ ]
+ if present:
+ raise RuntimeError(
+ "Output workspace uses removed paths: "
+ + ", ".join(present)
+ + "; choose a clean directory and import again"
+ )
+
+
+def _safe_basename(value: str) -> str:
+ cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", value.strip())
+ return cleaned.strip("._") or "resource"
+
+
+def _sha256(payload: bytes) -> str:
+ return hashlib.sha256(payload).hexdigest()
+
+
+def _source_part_for_relationships(rels_path: str) -> str | None:
+ if rels_path == "_rels/.rels":
+ return None
+ marker = "/_rels/"
+ if marker not in rels_path or not rels_path.endswith(".rels"):
+ return None
+ parent, filename = rels_path.split(marker, 1)
+ return f"{parent}/{filename[:-5]}"
+
+
+def _resolve_relationship_target(source_part: str | None, target: str) -> str:
+ normalized = target.replace("\\", "/")
+ if normalized.startswith("/"):
+ return normalized.lstrip("/")
+ base_dir = posixpath.dirname(source_part or "")
+ return posixpath.normpath(posixpath.join(base_dir, normalized)).lstrip("/")
+
+
+def _transition_relationship_ids(
+ package: zipfile.ZipFile,
+ source_part: str | None,
+) -> set[str]:
+ if source_part is None or not source_part.startswith("ppt/slides/"):
+ return set()
+ try:
+ root = ET.fromstring(package.read(source_part))
+ except (KeyError, ET.ParseError):
+ return set()
+ ids: set[str] = set()
+ for transition in root.iter(_TRANSITION_TAG):
+ for node in transition.iter():
+ for name, value in node.attrib.items():
+ if name.startswith(_REL_ATTR_PREFIX) and value:
+ ids.add(value)
+ return ids
+
+
+@dataclass(frozen=True)
+class PackageResource:
+ """One source package payload exposed through a semantic workspace path."""
+
+ package_part: str
+ kind: str
+ workspace_path: str
+ payload: bytes
+ relationship_types: tuple[str, ...] = ()
+ source_parts: tuple[str, ...] = ()
+ owner_parts: tuple[str, ...] = ()
+
+ @property
+ def sha256(self) -> str:
+ return _sha256(self.payload)
+
+ def manifest_row(self, *, materialized: bool = True) -> dict[str, object]:
+ """Return the compact machine-readable inventory record."""
+ return {
+ "packagePart": self.package_part,
+ "kind": self.kind,
+ "workspacePath": self.workspace_path,
+ "sha256": self.sha256,
+ "bytes": len(self.payload),
+ "relationshipTypes": list(self.relationship_types),
+ "sourceParts": list(self.source_parts),
+ "ownerParts": list(self.owner_parts),
+ "materialized": materialized,
+ }
+
+
+@dataclass(frozen=True)
+class PackageResourceInventory:
+ """Deterministic semantic projection of source package payloads."""
+
+ resources: tuple[PackageResource, ...] = ()
+
+ def path_map(self) -> dict[str, str]:
+ """Map source package part names to workspace-relative paths."""
+ return {
+ resource.package_part: resource.workspace_path
+ for resource in self.resources
+ }
+
+ def image_name_map(self) -> dict[str, str]:
+ """Map package image parts to basenames used by SVG hrefs."""
+ return {
+ resource.package_part: PurePosixPath(resource.workspace_path).name
+ for resource in self.resources
+ if resource.kind == "image"
+ }
+
+ def manifest(self, *, include_images: bool = True) -> dict[str, object]:
+ """Return the versioned resource inventory payload."""
+ return {
+ "schema": "ppt-master.workspace-resources.v1",
+ "items": [
+ resource.manifest_row(
+ materialized=include_images or resource.kind != "image",
+ )
+ for resource in self.resources
+ ],
+ }
+
+
+@dataclass(frozen=True)
+class WorkspaceResourceSpec:
+ """One semantic resource mapped back to its source package part."""
+
+ package_part: str
+ kind: str
+ workspace_path: Path
+ materialized: bool
+
+
+def workspace_resource_specs(
+ workspace: Path,
+ manifest: dict[str, object],
+) -> tuple[WorkspaceResourceSpec, ...]:
+ """Validate and resolve the resource map used by round-trip export."""
+ resources = manifest.get("resources")
+ if not isinstance(resources, dict):
+ raise RuntimeError("Round-trip manifest resources must be an object")
+ if resources.get("schema") != "ppt-master.workspace-resources.v1":
+ raise RuntimeError(
+ "Unsupported round-trip resource schema: "
+ f"{resources.get('schema')!r}"
+ )
+ items = resources.get("items")
+ if not isinstance(items, list):
+ raise RuntimeError("Round-trip manifest resources.items must be an array")
+
+ workspace_root = workspace.resolve()
+ specs: list[WorkspaceResourceSpec] = []
+ seen_package_parts: set[str] = set()
+ for index, raw in enumerate(items):
+ context = f"round-trip resources.items[{index}]"
+ if not isinstance(raw, dict):
+ raise RuntimeError(f"{context} must be an object")
+ package_part = raw.get("packagePart")
+ kind = raw.get("kind")
+ workspace_path = raw.get("workspacePath")
+ materialized = raw.get("materialized")
+ if not isinstance(package_part, str) or not package_part:
+ raise RuntimeError(f"{context}.packagePart must be a non-empty string")
+ package_path = PurePosixPath(package_part)
+ if (
+ package_path.is_absolute()
+ or ".." in package_path.parts
+ or "\\" in package_part
+ or not any(
+ package_part.startswith(prefix)
+ for prefix in (
+ "ppt/media/",
+ "ppt/embeddings/",
+ "ppt/model3d/",
+ )
+ )
+ ):
+ raise RuntimeError(
+ f"{context}.packagePart is outside the supported PPTX payload roots"
+ )
+ if package_part in seen_package_parts:
+ raise RuntimeError(f"{context} repeats package part {package_part!r}")
+ if not isinstance(kind, str) or not kind:
+ raise RuntimeError(f"{context}.kind must be a non-empty string")
+ if not isinstance(workspace_path, str) or not workspace_path:
+ raise RuntimeError(f"{context}.workspacePath must be a non-empty string")
+ relative = Path(workspace_path)
+ if (
+ relative.drive
+ or relative.anchor
+ or relative.is_absolute()
+ or ".." in relative.parts
+ ):
+ raise RuntimeError(f"{context}.workspacePath must stay project-relative")
+ resolved = (workspace_root / relative).resolve()
+ try:
+ resolved.relative_to(workspace_root)
+ except ValueError as exc:
+ raise RuntimeError(
+ f"{context}.workspacePath resolves outside the project"
+ ) from exc
+ if not isinstance(materialized, bool):
+ raise RuntimeError(f"{context}.materialized must be a boolean")
+ if materialized and not resolved.is_file():
+ raise RuntimeError(
+ f"Materialized round-trip resource is missing: {workspace_path}"
+ )
+ specs.append(WorkspaceResourceSpec(
+ package_part=package_part,
+ kind=kind,
+ workspace_path=relative,
+ materialized=materialized,
+ ))
+ seen_package_parts.add(package_part)
+ return tuple(specs)
+
+
+def _is_semantic_owner_part(package_part: str) -> bool:
+ return any(
+ package_part.startswith(prefix)
+ for prefix in (
+ "ppt/slides/slide",
+ "ppt/slideLayouts/slideLayout",
+ "ppt/slideMasters/slideMaster",
+ "ppt/notesSlides/notesSlide",
+ )
+ ) and package_part.endswith(".xml")
+
+
+def _resource_owner_parts(
+ package_part: str,
+ parents_by_target: dict[str, set[str]],
+) -> tuple[str, ...]:
+ """Resolve Slide/Layout/Master/Notes owners through relationship chains."""
+ owners: set[str] = set()
+ visited = {package_part}
+ pending = [package_part]
+ while pending:
+ current = pending.pop()
+ for parent in parents_by_target.get(current, set()):
+ if parent in visited:
+ continue
+ visited.add(parent)
+ if _is_semantic_owner_part(parent):
+ owners.add(parent)
+ else:
+ pending.append(parent)
+ return tuple(sorted(owners))
+
+
+def _classify_resource(
+ package_part: str,
+ relationship_types: set[str],
+ *,
+ transition_only: bool,
+) -> tuple[str, Path]:
+ suffix = PurePosixPath(package_part).suffix.lower()
+ if suffix in IMAGE_EXTENSIONS:
+ return "image", Path("images")
+ if (
+ suffix in VIDEO_EXTENSIONS
+ or any(rel_type.endswith("/video") for rel_type in relationship_types)
+ ):
+ return "video", Path("video")
+ if suffix in AUDIO_EXTENSIONS:
+ if transition_only:
+ return "sound", Path("sounds")
+ return "audio", Path("audio")
+ if package_part.startswith("ppt/embeddings/"):
+ return "native-payload", Path("native-payloads/embeddings")
+ if package_part.startswith("ppt/model3d/"):
+ return "native-payload", Path("native-payloads/model3d")
+ return "native-payload", Path("native-payloads/media")
+
+
+def inventory_package_resources(
+ package: zipfile.ZipFile,
+) -> PackageResourceInventory:
+ """Classify reusable and opaque PPTX payloads into semantic directories."""
+ references: dict[str, list[dict[str, object]]] = defaultdict(list)
+ parents_by_target: dict[str, set[str]] = defaultdict(set)
+ names = set(package.namelist())
+ for rels_path in sorted(name for name in names if name.endswith(".rels")):
+ source_part = _source_part_for_relationships(rels_path)
+ transition_ids = _transition_relationship_ids(package, source_part)
+ try:
+ root = ET.fromstring(package.read(rels_path))
+ except (KeyError, ET.ParseError):
+ continue
+ for relationship in root.findall(f"{{{_REL_NS}}}Relationship"):
+ if relationship.attrib.get("TargetMode") == "External":
+ continue
+ rel_id = relationship.attrib.get("Id", "")
+ rel_type = relationship.attrib.get("Type", "")
+ target = relationship.attrib.get("Target", "")
+ if not rel_id or not rel_type or not target:
+ continue
+ resolved = _resolve_relationship_target(source_part, target)
+ if source_part:
+ parents_by_target[resolved].add(source_part)
+ references[resolved].append({
+ "relationshipType": rel_type,
+ "sourcePart": source_part or "",
+ "transition": rel_id in transition_ids,
+ })
+
+ candidate_parts = sorted(
+ name
+ for name in names
+ if not name.endswith("/")
+ and (
+ name.startswith("ppt/media/")
+ or name.startswith("ppt/embeddings/")
+ or name.startswith("ppt/model3d/")
+ )
+ )
+ allocated: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
+ resources: list[PackageResource] = []
+ for package_part in candidate_parts:
+ rows = references.get(package_part, [])
+ relationship_types = {
+ str(row["relationshipType"])
+ for row in rows
+ if row.get("relationshipType")
+ }
+ transition_flags = [bool(row.get("transition")) for row in rows]
+ transition_only = bool(transition_flags) and all(transition_flags)
+ kind, directory = _classify_resource(
+ package_part,
+ relationship_types,
+ transition_only=transition_only,
+ )
+ payload = package.read(package_part)
+ digest = _sha256(payload)
+ original_name = _safe_basename(PurePosixPath(package_part).name)
+ key = (directory.as_posix(), original_name.lower())
+ allocations = allocated[key]
+ existing_name = next(
+ (name for known_digest, name in allocations if known_digest == digest),
+ None,
+ )
+ if existing_name is None:
+ stem = Path(original_name).stem
+ suffix = Path(original_name).suffix
+ existing_name = (
+ original_name
+ if not allocations
+ else f"{stem}_{len(allocations) + 1}{suffix}"
+ )
+ allocations.append((digest, existing_name))
+ workspace_path = (directory / existing_name).as_posix()
+ resources.append(PackageResource(
+ package_part=package_part,
+ kind=kind,
+ workspace_path=workspace_path,
+ payload=payload,
+ relationship_types=tuple(sorted(relationship_types)),
+ source_parts=tuple(sorted({
+ str(row["sourcePart"])
+ for row in rows
+ if row.get("sourcePart")
+ })),
+ owner_parts=_resource_owner_parts(
+ package_part,
+ parents_by_target,
+ ),
+ ))
+ return PackageResourceInventory(resources=tuple(resources))
+
+
+def write_workspace_resources(
+ workspace: Path,
+ inventory: PackageResourceInventory,
+ *,
+ include_images: bool = True,
+) -> tuple[str, ...]:
+ """Write the exact resource inventory without overwriting different bytes."""
+ written: list[str] = []
+ for resource in inventory.resources:
+ if resource.kind == "image" and not include_images:
+ continue
+ relative = Path(resource.workspace_path)
+ target = workspace / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if target.exists():
+ if not target.is_file() or target.read_bytes() != resource.payload:
+ raise RuntimeError(
+ "Semantic resource path collides with different content: "
+ f"{relative}"
+ )
+ else:
+ target.write_bytes(resource.payload)
+ written.append(relative.as_posix())
+ return tuple(written)
+
+
+def load_roundtrip_manifest(workspace: Path) -> dict[str, object] | None:
+ """Load the semantic round-trip manifest when present."""
+ path = workspace / ROUNDTRIP_MANIFEST_PATH
+ if not path.is_file():
+ return None
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise RuntimeError(f"Cannot read round-trip manifest {path}: {exc}") from exc
+ if not isinstance(raw, dict):
+ raise RuntimeError(f"Round-trip manifest must be a JSON object: {path}")
+ return raw
+
+
+def slide_animation_config_sha256(
+ config: dict[str, object],
+ slide_stem: str,
+) -> str:
+ """Hash global motion settings plus one slide's animation configuration."""
+ slides = config.get("slides")
+ slide_config = slides.get(slide_stem) if isinstance(slides, dict) else None
+ payload = {
+ "global": {
+ key: value
+ for key, value in config.items()
+ if key != "slides"
+ },
+ "slide": slide_config,
+ }
+ serialized = json.dumps(
+ payload,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ return _sha256(serialized)
+
+
+__all__ = [
+ "AUDIO_EXTENSIONS",
+ "CONVERSION_REPORT_PATH",
+ "REMOVED_WORKSPACE_ENTRIES",
+ "IMAGE_EXTENSIONS",
+ "NATIVE_STRUCTURE_PATH",
+ "PackageResource",
+ "PackageResourceInventory",
+ "ROUNDTRIP_MANIFEST_PATH",
+ "SOURCE_PPTX_PATH",
+ "TEMPLATE_MANIFEST_PATH",
+ "VIDEO_EXTENSIONS",
+ "WorkspaceResourceSpec",
+ "conversion_report_path",
+ "inventory_package_resources",
+ "load_roundtrip_manifest",
+ "native_structure_path",
+ "reject_removed_workspace_layout",
+ "source_pptx_path",
+ "slide_animation_config_sha256",
+ "template_manifest_path",
+ "write_workspace_resources",
+ "workspace_resource_specs",
+]
diff --git a/skills/ppt-master/scripts/register_template.py b/skills/ppt-master/scripts/register_template.py
index f9df58aa..f021b2f3 100644
--- a/skills/ppt-master/scripts/register_template.py
+++ b/skills/ppt-master/scripts/register_template.py
@@ -14,8 +14,7 @@ in ``templates/README.md``; each kind's schema lives in its directory README:
Current workspaces keep ``design_spec.md`` and any SVG roster under
``<workspace>/templates/``. Assets live in optional ``images/`` / ``icons/``
directories. Explicitly generated review artifacts go to the optional, ignored
-``exports/`` directory. Legacy flat roots remain readable for Brand/Layout/Deck;
-Style uses only the current nested one-file contract.
+``exports/`` directory. Every kind uses this nested workspace contract.
Index entry schemas (the JSON file is the single source of truth — README
files describe the kind and usage in prose but do **not** enumerate templates;
@@ -434,15 +433,13 @@ def _has_qualified_roster_spec(template_dir: Path) -> bool:
def _template_content_dir(template_root: Path) -> Path:
- """Resolve the canonical source directory, with legacy-flat compatibility."""
+ """Resolve the only canonical template source directory."""
nested = template_root / "templates"
if (nested / "design_spec.md").is_file() or _has_kind_qualified_spec(nested):
return nested
- if (template_root / "design_spec.md").is_file():
- return template_root
raise SpecParseError(
- "missing templates/design_spec.md, templates/design_spec.<kind>.<id>.md, "
- f"or legacy design_spec.md in {template_root}"
+ "missing templates/design_spec.md or "
+ f"templates/design_spec.<kind>.<id>.md in {template_root}"
)
@@ -1161,12 +1158,7 @@ def _extract_entry(
"""Build the index entry + extras for a single template."""
template_root = template_dir
template_dir = _template_content_dir(template_root)
- if kind == "style" and template_dir == template_root:
- raise SpecParseError(
- "Style workspaces require templates/design_spec.md; "
- "legacy-flat design_spec.md is not supported"
- )
- if template_id is not None and template_dir != template_root:
+ if template_id is not None:
exact_spec = template_dir / "design_spec.md"
if not exact_spec.is_file():
raise SpecParseError(
@@ -1268,7 +1260,7 @@ def _extract_entry(
extras = OrderedDict(
pages=pages,
primary_color=str(primary_color),
- page_prefix="templates/" if template_dir != template_root else "",
+ page_prefix="templates/",
preview=(
f"exports/{resolved_template_id}_template_preview.pptx"
if (
@@ -1364,10 +1356,7 @@ def _enumerate_ids(kind: str) -> list[str]:
return sorted(
p.name for p in base.iterdir()
if p.is_dir()
- and (
- (p / "templates" / "design_spec.md").is_file()
- or (p / "design_spec.md").is_file()
- )
+ and (p / "templates" / "design_spec.md").is_file()
)
diff --git a/skills/ppt-master/scripts/resource_paths.py b/skills/ppt-master/scripts/resource_paths.py
index fc85b772..a0cdabc0 100644
--- a/skills/ppt-master/scripts/resource_paths.py
+++ b/skills/ppt-master/scripts/resource_paths.py
@@ -33,7 +33,6 @@ SVG_WORK_DIR_NAMES = frozenset({
'svg_output',
'svg_final',
'svg-flat',
- 'svg_flat',
})
SVG_FINAL_CANDIDATE_PREFIX = '.svg_final.candidate-'
TEMPLATE_SOURCE_DIR_NAME = 'templates'
@@ -85,23 +84,14 @@ def project_root_for_svg_path(svg_path: Path) -> Path:
return base
-def global_icons_dir() -> Path:
- """Return the skill-level icon library directory."""
- return Path(__file__).resolve().parent.parent / 'templates' / 'icons'
+def icon_dir_for_project(project_path: Path) -> Path:
+ """Return the only valid icon root for a project."""
+ return Path(project_path) / 'icons'
-def icon_search_dirs_for_project(project_path: Path) -> tuple[Path, Path | None]:
- """Return project-first icon dirs plus the global fallback when needed."""
- global_dir = global_icons_dir()
- project_icons_dir = Path(project_path) / 'icons'
- if project_icons_dir.is_dir():
- return project_icons_dir, global_dir
- return global_dir, None
-
-
-def icon_search_dirs_for_svg(svg_path: Path) -> tuple[Path, Path | None]:
- """Return icon dirs for an SVG file path or SVG directory path."""
- return icon_search_dirs_for_project(project_root_for_svg_path(svg_path))
+def icon_dir_for_svg(svg_path: Path) -> Path:
+ """Return the project-local icon root for one SVG input."""
+ return icon_dir_for_project(project_root_for_svg_path(svg_path))
def _decode_svg_data_uri(raw: str) -> tuple[bytes | None, str | None]:
@@ -244,43 +234,31 @@ def svg_data_uri_payload_error(raw: str) -> str | None:
return f'inline SVG data URI is not closed: {nested_error}'
-def external_image_reference_candidates(
+def external_image_reference_path(
svg_dir: Path,
href: str,
*,
project_root: Path | None = None,
-) -> list[Path]:
- """Return deterministic project-local candidates for an SVG image href."""
+) -> Path | None:
+ """Resolve one exact SVG-relative image reference inside the project."""
parsed = urlsplit(href)
- if parsed.scheme and parsed.scheme not in {'file'}:
- return []
- decoded = unquote(
- parsed.path
- if parsed.scheme
- else href.split('?', 1)[0].split('#', 1)[0]
- )
+ if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment:
+ return None
+ decoded = unquote(parsed.path)
+ if not decoded or Path(decoded).is_absolute():
+ return None
svg_dir = Path(svg_dir)
resolved_project_root = (
Path(project_root).resolve()
if project_root is not None
else project_root_for_svg_path(svg_dir).resolve()
)
- candidates = [
- svg_dir / decoded,
- resolved_project_root / decoded,
- resolved_project_root / 'images' / decoded,
- resolved_project_root / 'templates' / decoded,
- ]
- safe_candidates: list[Path] = []
- for candidate in candidates:
- resolved = candidate.resolve()
- try:
- resolved.relative_to(resolved_project_root)
- except ValueError:
- continue
- if resolved not in safe_candidates:
- safe_candidates.append(resolved)
- return safe_candidates
+ resolved = (svg_dir / decoded).resolve()
+ try:
+ resolved.relative_to(resolved_project_root)
+ except ValueError:
+ return None
+ return resolved
def resolve_external_image_reference(
@@ -289,29 +267,10 @@ def resolve_external_image_reference(
*,
project_root: Path | None = None,
) -> Path | None:
- """Resolve an SVG image href to an existing file, or return None."""
- for candidate in external_image_reference_candidates(
- svg_dir,
- href,
- project_root=project_root,
- ):
- if candidate.is_file():
- return candidate
- return None
-
-
-def unresolved_external_image_reference_path(
- svg_dir: Path,
- href: str,
- *,
- project_root: Path | None = None,
-) -> Path:
- """Return the first candidate path for diagnostics when resolution fails."""
- candidates = external_image_reference_candidates(
+ """Resolve an exact SVG-relative image href, or return None."""
+ candidate = external_image_reference_path(
svg_dir,
href,
project_root=project_root,
)
- if candidates:
- return candidates[0].resolve()
- return (Path(svg_dir) / href).resolve()
+ return candidate if candidate is not None and candidate.is_file() else None
diff --git a/skills/ppt-master/scripts/svg_authoring_view.py b/skills/ppt-master/scripts/svg_authoring_view.py
index f2a6d2f8..67c98022 100644
--- a/skills/ppt-master/scripts/svg_authoring_view.py
+++ b/skills/ppt-master/scripts/svg_authoring_view.py
@@ -24,8 +24,8 @@ The output directory is an authoring bundle: editable SVGs plus one
model-readable `authoring_summary.json` and one tool-only
`authoring_manifest.json` provenance sidecar. Layered IR remains the
template-creation input; final templates are materialized from it. A flat
-authoring bundle may also be selected explicitly by the SVG exporter through
-its dangerous compatibility mode. Directory runs prepare and stage the
+authoring bundle at ``authoring-svg-flat/`` is the sole editable source for
+``svg_to_pptx.py --roundtrip``. Directory runs prepare and stage the
complete batch before publishing it, so a failed page leaves the existing
destination set unchanged.
"""
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.py
index 6e8021d7..108afb9f 100644
--- a/skills/ppt-master/scripts/svg_editor/server.py
+++ b/skills/ppt-master/scripts/svg_editor/server.py
@@ -60,7 +60,7 @@ if str(_ROOT_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_ROOT_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
-from resource_paths import icon_search_dirs_for_project # noqa: E402
+from resource_paths import icon_dir_for_project # noqa: E402
from slide_roster import discover_slide_svgs # noqa: E402
from server_common import ( # noqa: E402
claim_lock as _claim_lock,
@@ -166,11 +166,10 @@ def _inline_icons(
content: str,
icons_dir: Path,
target_dir: Path,
- fallback_dir: Optional[Path] = None,
) -> tuple[str, list[dict]]:
"""Replace <use data-icon="..."/> with rendered <g> for browser preview.
- Resolve icons from the project directory first, then the shared library.
+ Resolve icons only from the prepared project directory.
Returns (rewritten_content, warnings). Each warning is
``{"icon": <name>, "reason": <str>}`` so the frontend can surface
"icon X not found" to the user instead of silently dropping it.
@@ -189,7 +188,7 @@ def _inline_icons(
if not icon_name:
warnings.append({'icon': '', 'reason': 'missing data-icon attribute'})
continue
- icon_path, _ = resolve_icon_path(icon_name, icons_dir, fallback_dir)
+ icon_path, _ = resolve_icon_path(icon_name, icons_dir)
color = str(attrs.get('fill', '#000000'))
elements, style, base_size = extract_paths_from_icon(
icon_path,
@@ -436,8 +435,7 @@ def create_app(
project_path = Path(project_dir).resolve()
svg_dir = project_path / 'svg_output'
images_dir = project_path / 'images'
- assets_dir = project_path / 'assets'
- icons_dir, icons_fallback_dir = icon_search_dirs_for_project(project_path)
+ icons_dir = icon_dir_for_project(project_path)
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.config['PROJECT_PATH'] = project_path
@@ -542,42 +540,6 @@ def create_app(
return jsonify({'error': 'not found'}), 404
return send_from_directory(str(images_dir), filename)
- @app.route('/assets/<path:filename>')
- def serve_asset(filename: str):
- """Serve media extracted by pptx_to_svg.py as `../assets/*`."""
- if not assets_dir.exists():
- return jsonify({'error': 'assets directory not found'}), 404
- target = (assets_dir / filename).resolve()
- try:
- target.relative_to(assets_dir.resolve())
- except ValueError:
- return jsonify({'error': 'invalid path'}), 400
- if not target.exists() or not target.is_file():
- return jsonify({'error': 'not found'}), 404
- return send_from_directory(str(assets_dir), filename)
-
- @app.route('/<path:filename>')
- def serve_bare_asset(filename: str):
- """Resolve a template SVG's bare image href (e.g. `href="cover_bg.png"`).
-
- Mirror templates copy hrefs verbatim, so a bare filename reaches the
- browser as `/<filename>` (no `../images/` prefix). Resolve it against the
- project's images/ then assets/. Every real route (`/api/*`, `/images/*`,
- `/assets/*`, `/static/*`, `/`) is more specific and matches first; this
- only catches the leftover bare references and 404s otherwise.
- """
- for base in (images_dir, assets_dir):
- if not base.exists():
- continue
- target = (base / filename).resolve()
- try:
- target.relative_to(base.resolve())
- except ValueError:
- continue
- if target.exists() and target.is_file():
- return send_from_directory(str(base), filename)
- return jsonify({'error': 'not found'}), 404
-
@app.route('/api/slides')
def get_slides():
svg_dir = app.config['SVG_DIR']
@@ -719,7 +681,6 @@ def create_app(
content,
icons_dir,
svg_file.parent,
- icons_fallback_dir,
)
if not pending_edits:
_cache_put(
diff --git a/skills/ppt-master/scripts/svg_finalize/embed_icons.py b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
index 3c216d29..bc49c7cf 100644
--- a/skills/ppt-master/scripts/svg_finalize/embed_icons.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
@@ -4,17 +4,13 @@ SVG Icon Embedding Tool
Replaces icon placeholders in SVG files with actual icon code.
-Placeholder syntax (new SVGs must include a library prefix):
+Placeholder syntax (every SVG must include the exact project-local namespace):
<use data-icon="chunk-filled/rocket" x="100" y="200" width="48" height="48" fill="#0076A8"/>
<use data-icon="tabler-filled/home" x="100" y="200" width="48" height="48" fill="#0076A8"/>
<use data-icon="tabler-outline/home" x="100" y="200" width="48" height="48" fill="#0076A8"/>
<use data-icon="tabler-outline/home" x="100" y="200" width="48" height="48" fill="#0076A8" stroke-width="3"/>
<use data-icon="imported/layered_slide_06_ill01"/>
-Legacy compatibility accepted by the resolver:
- <use data-icon="rocket" .../> -> chunk-filled/rocket
- <use data-icon="chunk/rocket" .../> -> chunk-filled/rocket
-
Optional `stroke-width` (stroke-style libraries only — e.g. tabler-outline):
Default 2 (matches the source). Pass 1.5 for thin, 3 for bold.
Ignored on fill-style libraries.
@@ -24,20 +20,22 @@ After replacement:
<path d="..."/>
</g>
-Icon libraries (subdirectories of templates/icons/):
- chunk-filled/ - 640+ fill icons, 16x16 viewBox (use prefix: chunk-filled/name; legacy 'chunk/' also accepted)
+Project icon namespaces (subdirectories of <project>/icons/):
+ chunk-filled/ - 640+ fill icons, 16x16 viewBox
tabler-filled/ - 1000+ fill icons, 24x24 viewBox (use prefix: tabler-filled/name)
tabler-outline/ - 5000+ stroke icons, 24x24 viewBox (use prefix: tabler-outline/name)
phosphor-duotone/ - 1200+ duotone icons, 256x256 viewBox (single color + 0.2-opacity backplate)
simple-icons/ - 3400+ brand logos, 24x24 viewBox (brand-inset library — used alongside the chosen primary library, NOT as a standalone library for generic icons)
- imported/ - project-local extracted vector illustrations with data-icon-style="preserve-color"; preserve source colors and natural viewBox aspect ratio
+ imported/ - extracted vector illustrations with data-icon-style="preserve-color"; preserve source colors and natural viewBox aspect ratio
+
+Bundled icons must first be copied into the project with icon_sync.py. This
+tool never reads templates/icons directly and never accepts a bare icon name.
Usage:
python3 scripts/svg_finalize/embed_icons.py <svg_file> [svg_file2] ...
python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
Options:
- --icons-dir <path> Icon directory path (default: templates/icons/)
--dry-run Only show what would be replaced, without modifying files
--verbose Show detailed information
"""
@@ -50,31 +48,30 @@ import sys
import argparse
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
-from xml.etree import ElementTree as ET
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from resource_paths import icon_dir_for_svg # noqa: E402
from svg_to_pptx.drawingml.utils import parse_project_geometry_length # noqa: E402
configure_utf8_stdio()
-# Default icon directory
-DEFAULT_ICONS_DIR = Path(__file__).parent.parent.parent / 'templates' / 'icons'
-
# Icon base size per library
ICON_BASE_SIZES = {
'chunk-filled': 16,
- 'chunk': 16, # backward compat alias → chunk-filled/
'tabler-filled': 24,
'tabler-outline': 24,
'phosphor-duotone': 256,
'simple-icons': 24,
+ 'imported': 24,
}
-_ICON_LIBRARY_ALIASES = {'chunk': 'chunk-filled'}
+_ICON_IDENTIFIER_RE = re.compile(
+ r'(?P<library>[a-z0-9][a-z0-9-]*)/(?P<name>[A-Za-z0-9][A-Za-z0-9._-]*)'
+)
DEFAULT_ICON_BASE_SIZE = 24
BaseGeometry = float | tuple[float, float, float, float]
@@ -112,7 +109,7 @@ def _format_number(value: object) -> str:
def _base_geometry(base_size: BaseGeometry) -> tuple[float, float, float, float]:
- """Normalize legacy square icon size and full viewBox geometry."""
+ """Normalize scalar icon size and full viewBox geometry."""
if isinstance(base_size, tuple):
return base_size
return 0.0, 0.0, float(base_size), float(base_size)
@@ -169,22 +166,24 @@ def _extract_shape_elements(content: str, color: str) -> list[str]:
return elements
-def _resolve_in_dir(icon_name: str, icons_dir: Path) -> tuple[Path, float]:
- """Resolve `icon_name` against a single icons dir (no fallback)."""
- if '/' in icon_name:
- lib, name = icon_name.split('/', 1)
- lib = _ICON_LIBRARY_ALIASES.get(lib, lib) # resolve aliases
- icon_path = icons_dir / lib / f'{name}.svg'
- base_size = ICON_BASE_SIZES.get(lib, 24)
- else:
- # Backward compatibility: un-prefixed names fall back to legacy chunk-filled/ library
- icon_path = icons_dir / 'chunk-filled' / f'{icon_name}.svg'
- base_size = 16
- if not icon_path.exists():
- icon_path = icons_dir / f'{icon_name}.svg' # legacy flat layout
- base_size = 16
+def _split_icon_identifier(icon_name: str) -> tuple[str, str]:
+ """Parse one complete canonical ``library/name`` identifier."""
+ match = _ICON_IDENTIFIER_RE.fullmatch(icon_name)
+ if match is None:
+ raise ValueError(
+ "data-icon must be a complete project-local library/name identifier: "
+ f"{icon_name!r}"
+ )
+ return match.group('library'), match.group('name')
- return icon_path, base_size
+
+def _resolve_in_dir(icon_name: str, icons_dir: Path) -> tuple[Path, float]:
+ """Resolve one canonical identifier against exactly one icon root."""
+ library, name = _split_icon_identifier(icon_name)
+ return (
+ icons_dir / library / f'{name}.svg',
+ ICON_BASE_SIZES.get(library, DEFAULT_ICON_BASE_SIZE),
+ )
def _casefold_icon_name_in_dir(icon_name: str, icons_dir: Path) -> str | None:
@@ -192,24 +191,11 @@ def _casefold_icon_name_in_dir(icon_name: str, icons_dir: Path) -> str | None:
if not icons_dir.is_dir():
return None
- search_dirs: list[Path] = []
- expected_name = icon_name
- if '/' in icon_name:
- raw_lib, expected_name = icon_name.split('/', 1)
- requested_lib = _ICON_LIBRARY_ALIASES.get(raw_lib.casefold(), raw_lib)
- library_dir = icons_dir / requested_lib
- if not library_dir.is_dir():
- library_dir = next(
- (
- path for path in icons_dir.iterdir()
- if path.is_dir()
- and path.name.casefold() == requested_lib.casefold()
- ),
- library_dir,
- )
- search_dirs.append(library_dir)
- else:
- search_dirs.extend((icons_dir / 'chunk-filled', icons_dir))
+ try:
+ requested_lib, expected_name = _split_icon_identifier(icon_name)
+ except ValueError:
+ return None
+ search_dirs = [icons_dir / requested_lib]
expected_filename = f'{expected_name}.svg'.casefold()
for search_dir in search_dirs:
@@ -231,31 +217,21 @@ def _casefold_icon_name_in_dir(icon_name: str, icons_dir: Path) -> str | None:
def suggest_icon_name(
icon_name: str,
icons_dir: Path,
- fallback_dir: Path | None = None,
) -> str | None:
- """Suggest an exact project-first icon identifier without auto-correcting it."""
- suggestion = _casefold_icon_name_in_dir(icon_name, icons_dir)
- if suggestion is None and fallback_dir is not None:
- suggestion = _casefold_icon_name_in_dir(icon_name, fallback_dir)
- return suggestion
+ """Suggest exact casing inside the declared project-local namespace."""
+ return _casefold_icon_name_in_dir(icon_name, icons_dir)
-def resolve_icon_path(icon_name: str, icons_dir: Path, fallback_dir: Path | None = None) -> tuple[Path, float]:
- """
- Resolve icon name to file path and base size, e.g. "chunk-filled/home" →
- icons_dir/chunk-filled/home.svg. "chunk/" is a backward-compat alias; an
- un-prefixed name falls back to chunk-filled/ then a legacy flat layout.
-
- Resolution is project-first: if the icon is absent under ``icons_dir`` and a
- ``fallback_dir`` (the global library) is given, the fallback's path is
- returned instead. Returns (path, base_size); the path may not exist when
- neither dir has the icon.
- """
+def resolve_icon_path(icon_name: str, icons_dir: Path) -> tuple[Path, float]:
+ """Resolve one complete identifier only under the supplied icon root."""
icon_path, base_size = _resolve_in_dir(icon_name, icons_dir)
- if fallback_dir is not None and not icon_path.exists():
- fb_path, fb_size = _resolve_in_dir(icon_name, fallback_dir)
- if fb_path.exists():
- return fb_path, fb_size
+ resolved_root = icons_dir.resolve()
+ try:
+ icon_path.resolve().relative_to(resolved_root)
+ except ValueError as exc:
+ raise ValueError(
+ f"data-icon escapes the project-local icon root: {icon_name!r}"
+ ) from exc
return icon_path, base_size
@@ -473,7 +449,12 @@ def generate_icon_group(attrs: dict[str, str | float], elements: list[str], styl
</g>'''
-def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, verbose: bool = False, fallback_dir: Path | None = None) -> int:
+def process_svg_file(
+ svg_path: Path,
+ icons_dir: Path,
+ dry_run: bool = False,
+ verbose: bool = False,
+) -> int:
"""
Process a single SVG file, replacing all icon placeholders.
@@ -487,8 +468,7 @@ def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, ver
Number of icons replaced
"""
if not svg_path.exists():
- print(f"[ERROR] File not found: {svg_path}")
- return 0
+ raise FileNotFoundError(f"SVG file not found: {svg_path}")
content = svg_path.read_text(encoding='utf-8')
@@ -512,20 +492,24 @@ def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, ver
icon_name = attrs.get('icon')
if not icon_name:
- continue
+ raise ValueError(
+ f'{svg_path.name}: icon placeholder has an empty data-icon value'
+ )
- icon_path, _ = resolve_icon_path(str(icon_name), icons_dir, fallback_dir)
+ try:
+ icon_path, _ = resolve_icon_path(str(icon_name), icons_dir)
+ except ValueError as exc:
+ raise ValueError(f'{svg_path.name}: {exc}') from exc
if not icon_path.exists():
- suggestion = suggest_icon_name(str(icon_name), icons_dir, fallback_dir)
+ suggestion = suggest_icon_name(str(icon_name), icons_dir)
hint = (
f"; identifiers are case-sensitive; use '{suggestion}'"
if suggestion else ""
)
- print(
- f"[WARN] Icon not found: {icon_name}{hint} "
- f"(in {svg_path.name})"
+ raise FileNotFoundError(
+ f'{svg_path.name}: project-local icon not found: '
+ f'{icon_name}{hint}'
)
- continue
elements, style, base_size = extract_paths_from_icon(
icon_path,
@@ -533,11 +517,9 @@ def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, ver
)
color = resolve_icon_color(attrs, style)
if not elements:
- print(
- f"[WARN] Icon has no embeddable shapes: {icon_name} "
- f"(in {svg_path.name})"
+ raise ValueError(
+ f'{svg_path.name}: icon has no embeddable shapes: {icon_name}'
)
- continue
replacement = generate_icon_group(attrs, elements, style, base_size)
@@ -557,7 +539,7 @@ def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, ver
return replaced_count
-def main() -> None:
+def main() -> int:
"""Run the CLI entry point."""
parser = argparse.ArgumentParser(
description='Replace icon placeholders in SVG files with actual icon code',
@@ -567,13 +549,10 @@ Examples:
python3 scripts/svg_finalize/embed_icons.py svg_output/01_cover.svg
python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
python3 scripts/svg_finalize/embed_icons.py --dry-run svg_output/*.svg
- python3 scripts/svg_finalize/embed_icons.py --icons-dir my_icons/ output.svg
'''
)
parser.add_argument('files', nargs='+', help='SVG files to process')
- parser.add_argument('--icons-dir', type=Path, default=DEFAULT_ICONS_DIR,
- help=f'Icon directory path (default: {DEFAULT_ICONS_DIR})')
parser.add_argument('--dry-run', action='store_true',
help='Only show what would be replaced, without modifying files')
parser.add_argument('--verbose', '-v', action='store_true',
@@ -581,12 +560,6 @@ Examples:
args = parser.parse_args()
- # Validate icon directory
- if not args.icons_dir.exists():
- print(f"[ERROR] Icon directory not found: {args.icons_dir}")
- sys.exit(1)
-
- print(f"[DIR] Icon directory: {args.icons_dir}")
if args.dry_run:
print("[PREVIEW] Preview mode (no files will be modified)")
print()
@@ -594,18 +567,28 @@ Examples:
total_replaced = 0
total_files = 0
- for file_pattern in args.files:
- svg_path = Path(file_pattern)
- if svg_path.exists():
- count = process_svg_file(svg_path, args.icons_dir, args.dry_run, args.verbose)
+ try:
+ for file_pattern in args.files:
+ svg_path = Path(file_pattern)
+ icons_dir = icon_dir_for_svg(svg_path)
+ count = process_svg_file(
+ svg_path,
+ icons_dir,
+ args.dry_run,
+ args.verbose,
+ )
total_replaced += count
if count > 0:
total_files += 1
+ except (OSError, ValueError) as exc:
+ print(f'[ERROR] {exc}', file=sys.stderr)
+ return 1
print()
print(f"[Summary] Total: {total_files} file(s), {total_replaced} icon(s)" +
(" (preview)" if args.dry_run else " replaced"))
+ return 0
if __name__ == '__main__':
- main()
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index 0f6c3241..2d5ea12b 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -27,6 +27,10 @@ from urllib.parse import unquote, urlsplit
from xml.etree import ElementTree as ET
from native_payloads import NativePayloadError, hydrate_native_payload_refs
+from pptx_workspace import (
+ NATIVE_STRUCTURE_PATH,
+ SOURCE_PPTX_PATH,
+)
from slide_roster import discover_slide_svgs
from . import svg_contracts
@@ -328,13 +332,13 @@ except ImportError:
try:
from resource_paths import (
SVG_WORK_DIR_NAMES as _SVG_WORK_DIR_NAMES,
- icon_search_dirs_for_svg as _icon_search_dirs_for_svg,
+ icon_dir_for_svg as _icon_dir_for_svg,
project_root_for_svg_path as _project_root_for_svg_path,
resolve_external_image_reference as _resolve_external_image_reference,
)
except ImportError:
_SVG_WORK_DIR_NAMES = frozenset()
- _icon_search_dirs_for_svg = None
+ _icon_dir_for_svg = None
_project_root_for_svg_path = None
_resolve_external_image_reference = None
@@ -3441,20 +3445,14 @@ class SVGQualityChecker:
"post-processing/export will still validate them."
)
return
- if _icon_search_dirs_for_svg is None:
+ if _icon_dir_for_svg is None:
result['warnings'].append(
- "Detected data-icon placeholders, but shared icon search helper could not be imported; "
+ "Detected data-icon placeholders, but the project icon helper could not be imported; "
"post-processing/export will still validate them."
)
return
- icons_dir, fallback_dir = _icon_search_dirs_for_svg(svg_path)
- require_project_local = self._requires_project_local_icons(svg_path)
- project_icons_dir = (
- _project_root_for_svg_path(svg_path) / 'icons'
- if _project_root_for_svg_path is not None
- else None
- )
+ icons_dir = _icon_dir_for_svg(svg_path)
seen = set()
for elem in placeholders:
icon_name = (elem.get('data-icon') or '').strip()
@@ -3465,25 +3463,14 @@ class SVGQualityChecker:
continue
seen.add(icon_name)
- if require_project_local and project_icons_dir is not None:
- local_path, _ = _resolve_icon_path(
- icon_name,
- project_icons_dir,
- None,
- )
- if not local_path.exists():
- result['errors'].append(
- f"Icon is not prepared in the project: {icon_name} "
- f"(expected under {project_icons_dir}); return to "
- "Strategist preparation instead of using the global fallback"
- )
- continue
-
- icon_path, _ = _resolve_icon_path(icon_name, icons_dir, fallback_dir)
+ try:
+ icon_path, _ = _resolve_icon_path(icon_name, icons_dir)
+ except ValueError as exc:
+ result['errors'].append(str(exc))
+ continue
if not icon_path.exists():
- fallback_msg = f", then {fallback_dir}" if fallback_dir else ""
suggestion = (
- _suggest_icon_name(icon_name, icons_dir, fallback_dir)
+ _suggest_icon_name(icon_name, icons_dir)
if _suggest_icon_name is not None else None
)
hint = (
@@ -3491,8 +3478,8 @@ class SVGQualityChecker:
if suggestion else ""
)
result['errors'].append(
- f"Icon not found: {icon_name} (searched {icons_dir}"
- f"{fallback_msg}){hint}"
+ f"Project-local icon not found: {icon_name} "
+ f"(expected under {icons_dir}){hint}"
)
continue
try:
@@ -3513,31 +3500,6 @@ class SVGQualityChecker:
result['info'].get('native_icon_payload_refs', 0) + hydrated
)
- @staticmethod
- def _requires_project_local_icons(svg_path: Path) -> bool:
- """Return whether a generated page belongs to a versioned project."""
- if svg_path.parent.name != 'svg_output' or _project_root_for_svg_path is None:
- return False
- lock_path = _project_root_for_svg_path(svg_path) / 'spec_lock.md'
- try:
- first_line = next(
- (
- line.strip()
- for line in lock_path.read_text(encoding='utf-8-sig').splitlines()
- if line.strip()
- ),
- '',
- )
- except OSError:
- return False
- return bool(
- re.fullmatch(
- r'<!--[ \t]+ppt-master-schema:[ \t]*spec-lock/v[1-9][0-9]*[ \t]+-->',
- first_line,
- re.IGNORECASE,
- )
- )
-
def _check_unsupported_visual_elements(
self,
root: ET.Element,
@@ -6967,8 +6929,8 @@ class SVGQualityChecker:
"workspaces must be re-created through create-template",
))
if check_structure:
- native_contract_path = dir_path / 'native_structure.json'
- source_template_path = dir_path / 'source_template.pptx'
+ native_contract_path = dir_path / NATIVE_STRUCTURE_PATH
+ source_template_path = dir_path / SOURCE_PPTX_PATH
legacy_structure_detected = False
for svg_file in svg_files:
try:
@@ -7039,8 +7001,9 @@ class SVGQualityChecker:
self._template_issues.append((
'error',
'legacy_native_structure_pair',
- "legacy native_structure.json/source_template.pptx template "
- "contracts must be replaced through "
+ "source-analysis native_structure/source.pptx contracts "
+ "must not be packaged as reusable template inputs; rebuild "
+ "through "
"skills/ppt-master/workflows/create-template.md",
))
diff --git a/skills/ppt-master/scripts/svg_to_pptx.py b/skills/ppt-master/scripts/svg_to_pptx.py
index 725c3682..6d80d05f 100644
--- a/skills/ppt-master/scripts/svg_to_pptx.py
+++ b/skills/ppt-master/scripts/svg_to_pptx.py
@@ -7,8 +7,7 @@ diagnostic override; the standard pipeline reads ``svg_output/``:
An imported flat authoring bundle rehydrates unchanged source objects before
the source-preserving export:
- python3 scripts/svg_to_pptx.py <project_path> -s authoring-svg-flat \
- --roundtrip
+ python3 scripts/svg_to_pptx.py <project_path> --roundtrip
An explicit compatibility export may normalize the default ``svg_output/`` or
another project-relative source selected with ``-s`` before strict flat
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
index 3327763d..1ccdb94f 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
@@ -86,8 +86,8 @@ class ConvertContext:
content_type_overrides: dict[str, str] = field(default_factory=dict)
rel_id_counter: int = 2 # rId1 reserved for slideLayout
svg_dir: Path | None = None
- # Explicit project boundary for deterministic resource resolution. Direct
- # library callers may omit it and retain directory-name inference.
+ # Explicit project boundary for deterministic resource resolution. Public
+ # conversion entry points require it; recursive child contexts retain it.
resource_root: Path | None = None
inherited_styles: dict[str, str] = field(default_factory=dict)
# Effective SVG font sizes keyed by element identity. Shared resolution
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 32ff713f..0c8835b1 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -29,7 +29,7 @@ from pptx_to_svg.preset_authoring import (
materialize_compact_authored_preset_tree,
validate_authored_preset_tree,
)
-from resource_paths import icon_search_dirs_for_project, icon_search_dirs_for_svg
+from resource_paths import icon_dir_for_project
from svg_compatibility import normalize_single_child_group_filters
from .context import (
@@ -1642,6 +1642,8 @@ def collect_unsupported_visuals(
def convert_svg_to_slide_shapes(
svg_path: str | Path,
+ *,
+ resource_root: Path,
slide_num: int = 1,
slide_count: int | None = None,
verbose: bool = False,
@@ -1660,7 +1662,6 @@ def convert_svg_to_slide_shapes(
promote_background: bool = True,
text_flow: str | None = None,
dangerous_nonconforming_export: bool = False,
- resource_root: Path | None = None,
) -> tuple[
str,
dict[str, bytes],
@@ -1853,27 +1854,27 @@ def convert_svg_to_slide_shapes(
expand_use_data_icons,
)
- icons_dir, icons_fallback_dir = (
- icon_search_dirs_for_project(resource_root)
- if resource_root is not None
- else icon_search_dirs_for_svg(svg_path)
- )
- if icons_dir.exists():
- expanded = expand_use_data_icons(root, icons_dir, icons_fallback_dir)
- if expanded:
- trace_steps.append({'action': 'expand-use-data-icons', 'count': expanded})
- if verbose and expanded:
- print(f' Expanded {expanded} <use data-icon="..."/> placeholder(s)')
- if expanded:
- hydrated = _hydrate_native_payloads(root, svg_path)
- if hydrated:
- trace_steps.append({
- 'action': 'hydrate-native-payloads-from-icons',
- 'count': hydrated,
- })
- _mark_unchanged_txbody_groups(root)
- _mark_unchanged_preset_previews(root)
- _require_project_freeform_geometry(root, svg_path)
+ icons_dir = icon_dir_for_project(resource_root)
+ try:
+ expanded = expand_use_data_icons(root, icons_dir)
+ except UseExpansionError as exc:
+ raise SvgNativeConversionError(
+ f'{svg_path.name}: icon expansion failed: {exc}'
+ ) from exc
+ if expanded:
+ trace_steps.append({'action': 'expand-use-data-icons', 'count': expanded})
+ if verbose and expanded:
+ print(f' Expanded {expanded} <use data-icon="..."/> placeholder(s)')
+ if expanded:
+ hydrated = _hydrate_native_payloads(root, svg_path)
+ if hydrated:
+ trace_steps.append({
+ 'action': 'hydrate-native-payloads-from-icons',
+ 'count': hydrated,
+ })
+ _mark_unchanged_txbody_groups(root)
+ _mark_unchanged_preset_previews(root)
+ _require_project_freeform_geometry(root, svg_path)
try:
injected_geometry_count = materialize_inline_geometry_properties(root)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
index 86873b4d..915505a1 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -104,11 +104,8 @@ def _resolve_external_image(
) -> Path:
"""Resolve a non-data-URI image href to a file on disk.
- Search order: next to the SVG (``svg_output/``), the project root, the
- project's ``images/`` (the single runtime image pool — template-bundled
- bitmaps plus AI / web / user images all live here), then ``templates/``
- (legacy flat-copied template assets). Raises ``FileNotFoundError`` if none
- of these exist.
+ The href is interpreted exactly relative to the owning SVG and must remain
+ inside the project. No root, ``images/``, or template-path guessing occurs.
"""
candidate = resolve_external_image_reference(
svg_dir,
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 de1c43fe..7242739c 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
@@ -4,7 +4,6 @@ from __future__ import annotations
import hashlib
import json
-import math
import mimetypes
import os
import posixpath
@@ -25,7 +24,6 @@ from xml.etree import ElementTree as ET
from xml.sax.saxutils import escape, quoteattr
from pptx import Presentation
-from pptx.util import Emu
from pptx_embedded_fonts import (
FONT_CONTENT_TYPE,
@@ -63,6 +61,7 @@ from pptx_opc_validation import (
resolve_internal_opc_target as _resolve_internal_opc_target,
verify_internal_relationships,
)
+from pptx_workspace import WorkspaceResourceSpec
from language_tags import normalize_language_tag
from hyperlink_contract import (
HYPERLINK_REL_TYPE,
@@ -150,6 +149,9 @@ SLIDE_REL_TYPE = (
SLIDE_MASTER_REL_TYPE = (
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"
)
+NOTES_SLIDE_REL_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide"
+)
THEME_REL_TYPE = (
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"
)
@@ -204,6 +206,17 @@ class PptxStructureContext:
) from exc
+@dataclass(frozen=True)
+class RoundtripSlidePatch:
+ """One authoring slide overlay applied onto its preserved source part."""
+
+ source_ref_ids: frozenset[str]
+ edited_ref_ids: frozenset[str]
+ deleted_ref_ids: frozenset[str]
+ motion_changed: bool
+ notes_changed: bool
+
+
@dataclass
class _TemplateRuntimeSlide:
"""Parsed slide package state used by explicit Layout structure export."""
@@ -853,6 +866,494 @@ def _write_xml_tree(path: Path, tree: ET.ElementTree) -> None:
tree.write(path, encoding="utf-8", xml_declaration=True)
+def _slide_ref_shape_ids(values: frozenset[str]) -> set[str]:
+ """Return numeric Slide-local ids from authoring source references."""
+ result: set[str] = set()
+ for value in values:
+ match = re.fullmatch(r"slide:(\d+)", value)
+ if match is not None:
+ result.add(match.group(1))
+ return result
+
+
+def _relationship_key(attrs: dict[str, str]) -> tuple[str, str, str | None]:
+ """Return the identity used to reuse one source relationship."""
+ return (
+ attrs.get("Type", ""),
+ attrs.get("Target", ""),
+ attrs.get("TargetMode"),
+ )
+
+
+def _merge_roundtrip_relationships(
+ source_rels: bytes,
+ generated_rels_path: Path,
+ generated_slide_root: ET.Element,
+ required_generated_ids: set[str],
+) -> None:
+ """Retarget generated references into the preserved source rel roster."""
+ try:
+ source_root = ET.fromstring(source_rels)
+ generated_root = ET.parse(generated_rels_path).getroot()
+ except ET.ParseError as exc:
+ raise TemplateStructureError(
+ "Round-trip slide relationships are not valid XML"
+ ) from exc
+
+ source_by_key: dict[tuple[str, str, str | None], str] = {}
+ used_ids: set[str] = set()
+ for relationship in source_root:
+ attrs = _relationship_attrs(relationship)
+ rel_id = attrs.get("Id")
+ if not rel_id:
+ continue
+ used_ids.add(rel_id)
+ source_by_key.setdefault(_relationship_key(attrs), rel_id)
+ numeric_ids = [
+ int(match.group(1))
+ for rel_id in used_ids
+ if (match := re.fullmatch(r"rId(\d+)", rel_id)) is not None
+ ]
+ next_id = max(numeric_ids, default=0) + 1
+
+ id_map: dict[str, str] = {}
+ added_relationship = False
+ for relationship in generated_root:
+ attrs = _relationship_attrs(relationship)
+ generated_id = attrs.get("Id")
+ if not generated_id:
+ raise TemplateStructureError(
+ "Generated round-trip relationship has no Id"
+ )
+ if generated_id not in required_generated_ids:
+ continue
+ existing_id = source_by_key.get(_relationship_key(attrs))
+ if existing_id is not None:
+ id_map[generated_id] = existing_id
+ continue
+
+ assigned_id = generated_id
+ if assigned_id in used_ids:
+ while f"rId{next_id}" in used_ids:
+ next_id += 1
+ assigned_id = f"rId{next_id}"
+ next_id += 1
+ clone = ET.fromstring(ET.tostring(relationship, encoding="utf-8"))
+ clone.set("Id", assigned_id)
+ source_root.append(clone)
+ added_relationship = True
+ used_ids.add(assigned_id)
+ source_by_key[_relationship_key(attrs)] = assigned_id
+ id_map[generated_id] = assigned_id
+
+ missing_relationships = required_generated_ids - set(id_map)
+ if missing_relationships:
+ raise TemplateStructureError(
+ "Generated round-trip slide references missing relationship(s): "
+ + ", ".join(sorted(missing_relationships))
+ )
+
+ for node in generated_slide_root.iter():
+ for attr_name, value in list(node.attrib.items()):
+ if attr_name in _REL_ATTRS and value in id_map:
+ node.set(attr_name, id_map[value])
+ if added_relationship:
+ _write_xml_tree(generated_rels_path, ET.ElementTree(source_root))
+ else:
+ generated_rels_path.write_bytes(source_rels)
+
+
+def _replace_roundtrip_motion(
+ source_root: ET.Element,
+ generated_root: ET.Element,
+) -> None:
+ """Replace source transition/timing nodes with the generated request."""
+ for local_name in ("transition", "timing"):
+ tag = f"{{{PML_NS}}}{local_name}"
+ existing = source_root.find(tag)
+ generated = generated_root.find(tag)
+ if existing is not None:
+ source_root.remove(existing)
+ if generated is None:
+ continue
+ clone = ET.fromstring(ET.tostring(generated, encoding="utf-8"))
+ children = list(source_root)
+ if local_name == "transition":
+ insert_at = next(
+ (
+ index
+ for index, child in enumerate(children)
+ if child.tag in {
+ f"{{{PML_NS}}}timing",
+ f"{{{PML_NS}}}extLst",
+ }
+ ),
+ len(children),
+ )
+ else:
+ insert_at = next(
+ (
+ index
+ for index, child in enumerate(children)
+ if child.tag == f"{{{PML_NS}}}extLst"
+ ),
+ len(children),
+ )
+ source_root.insert(insert_at, clone)
+
+
+def _shape_ids_in_element(element: ET.Element) -> set[str]:
+ """Return every non-visual DrawingML id owned by one shape subtree."""
+ return {
+ value
+ for node in element.iter(f"{{{PML_NS}}}cNvPr")
+ if (value := node.get("id"))
+ }
+
+
+def _renumber_roundtrip_generated_shapes(
+ generated_shapes: list[ET.Element],
+ retained_source_nodes: list[ET.Element],
+ slide_root: ET.Element,
+ *,
+ rewrite_timing: bool,
+) -> None:
+ """Keep generated additions disjoint from retained source shape ids."""
+ used_ids = {
+ value
+ for element in retained_source_nodes
+ for value in _shape_ids_in_element(element)
+ }
+ all_ids = set(used_ids)
+ for element in generated_shapes:
+ all_ids.update(_shape_ids_in_element(element))
+ numeric_ids = [int(value) for value in all_ids if value.isdigit()]
+ next_id = max(numeric_ids, default=1) + 1
+ id_map: dict[str, str] = {}
+ for element in generated_shapes:
+ for node in element.iter(f"{{{PML_NS}}}cNvPr"):
+ old_id = node.get("id")
+ if not old_id:
+ continue
+ if old_id in used_ids:
+ while str(next_id) in all_ids:
+ next_id += 1
+ new_id = str(next_id)
+ next_id += 1
+ node.set("id", new_id)
+ id_map[old_id] = new_id
+ all_ids.add(new_id)
+ used_ids.add(new_id)
+ else:
+ used_ids.add(old_id)
+
+ if not id_map:
+ return
+ for element in generated_shapes:
+ for connector_tag in ("stCxn", "endCxn"):
+ for connector in element.iter(f"{{{PML_NS}}}{connector_tag}"):
+ old_id = connector.get("id")
+ if old_id in id_map:
+ connector.set("id", id_map[old_id])
+ if rewrite_timing:
+ for target in slide_root.findall(
+ f".//{{{PML_NS}}}timing//{{{PML_NS}}}spTgt"
+ ):
+ old_id = target.get("spid")
+ if old_id in id_map:
+ target.set("spid", id_map[old_id])
+
+
+def _apply_roundtrip_slide_overlay(
+ source_slide: bytes,
+ source_rels: bytes,
+ generated_slide_path: Path,
+ generated_rels_path: Path,
+ patch: RoundtripSlidePatch,
+ conversion_trace: dict[str, Any] | None,
+) -> None:
+ """Overlay authored Slide objects onto the exact source slide package part."""
+ try:
+ source_root = ET.fromstring(source_slide)
+ generated_tree = ET.parse(generated_slide_path)
+ except ET.ParseError as exc:
+ raise TemplateStructureError(
+ "Round-trip source or generated slide is not valid XML"
+ ) from exc
+ generated_root = generated_tree.getroot()
+
+ source_tree = source_root.find(
+ f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree"
+ )
+ generated_sp_tree = generated_root.find(
+ f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree"
+ )
+ if source_tree is None or generated_sp_tree is None:
+ raise TemplateStructureError(
+ "Round-trip slide overlay requires source and generated p:spTree"
+ )
+
+ source_shapes: dict[str, ET.Element] = {}
+ source_descendant_ids: dict[str, set[str]] = {}
+ for child in source_tree:
+ if child.tag not in _TOP_LEVEL_SHAPE_TAGS:
+ continue
+ shape_id = _shape_id(child)
+ if not shape_id:
+ raise TemplateStructureError(
+ "Round-trip source slide contains a top-level shape without id"
+ )
+ if shape_id in source_shapes:
+ raise TemplateStructureError(
+ f"Round-trip source slide repeats top-level shape id {shape_id}"
+ )
+ source_shapes[shape_id] = child
+ source_descendant_ids[shape_id] = _shape_ids_in_element(child)
+
+ generated_order: list[str] = []
+ generated_shapes: dict[str, ET.Element] = {}
+ generated_top_id_by_descendant: dict[str, str] = {}
+ for child in generated_sp_tree:
+ if child.tag not in _TOP_LEVEL_SHAPE_TAGS:
+ continue
+ shape_id = _shape_id(child)
+ if not shape_id:
+ raise TemplateStructureError(
+ "Generated round-trip slide contains a top-level shape without id"
+ )
+ if shape_id in generated_shapes:
+ raise TemplateStructureError(
+ f"Generated round-trip slide repeats top-level shape id {shape_id}"
+ )
+ generated_order.append(shape_id)
+ generated_shapes[shape_id] = child
+ for descendant_id in _shape_ids_in_element(child):
+ previous = generated_top_id_by_descendant.setdefault(
+ descendant_id,
+ shape_id,
+ )
+ if previous != shape_id:
+ raise TemplateStructureError(
+ "Generated round-trip slide repeats a shape id across "
+ f"top-level objects: {descendant_id}"
+ )
+
+ source_ref_ids = _slide_ref_shape_ids(patch.source_ref_ids)
+ edited_ids = _slide_ref_shape_ids(patch.edited_ref_ids)
+ deleted_ids = _slide_ref_shape_ids(patch.deleted_ref_ids)
+ affected_top_ids = {
+ shape_id
+ for shape_id, descendant_ids in source_descendant_ids.items()
+ if descendant_ids & (edited_ids | deleted_ids)
+ }
+ authored_top_ids = {
+ shape_id
+ for shape_id in source_shapes
+ if shape_id in source_ref_ids or shape_id in affected_top_ids
+ }
+ deleted_top_ids = authored_top_ids & deleted_ids
+ traced_ids = _trace_native_shape_ids(conversion_trace)
+ generated_by_source_id: dict[str, ET.Element] = {}
+ source_id_by_generated_top_id: dict[str, str] = {}
+ for source_id in authored_top_ids - deleted_top_ids:
+ candidate_ids = [source_id]
+ candidate_ids.extend(traced_ids.get(f"shape-{source_id}", []))
+ generated_top_ids = {
+ generated_top_id_by_descendant[candidate_id]
+ for candidate_id in candidate_ids
+ if candidate_id in generated_top_id_by_descendant
+ }
+ if len(generated_top_ids) > 1:
+ raise TemplateStructureError(
+ "Generated round-trip source object maps to multiple top-level "
+ f"shapes: {source_id}"
+ )
+ if not generated_top_ids:
+ continue
+ generated_top_id = next(iter(generated_top_ids))
+ previous_source_id = source_id_by_generated_top_id.setdefault(
+ generated_top_id,
+ source_id,
+ )
+ if previous_source_id != source_id:
+ raise TemplateStructureError(
+ "Generated round-trip top-level shape maps to multiple source "
+ f"objects: {previous_source_id}, {source_id}"
+ )
+ generated_by_source_id[source_id] = generated_shapes[generated_top_id]
+
+ authored_order = [
+ source_id_by_generated_top_id[generated_top_id]
+ for generated_top_id in generated_order
+ if generated_top_id in source_id_by_generated_top_id
+ ]
+ if len(authored_order) != len(set(authored_order)):
+ raise TemplateStructureError(
+ "Generated round-trip slide has an ambiguous authored shape order"
+ )
+ missing_authored = (
+ authored_top_ids - deleted_top_ids - set(authored_order)
+ )
+ if missing_authored:
+ raise TemplateStructureError(
+ "Edited round-trip source object did not produce a DrawingML shape: "
+ + ", ".join(sorted(missing_authored, key=int))
+ )
+
+ selected_by_id: dict[str, tuple[ET.Element, bool]] = {}
+ for shape_id in authored_order:
+ if shape_id in affected_top_ids:
+ selected_by_id[shape_id] = (
+ generated_by_source_id[shape_id],
+ True,
+ )
+ else:
+ selected_by_id[shape_id] = (source_shapes[shape_id], False)
+ extra_generated = [
+ generated_shapes[shape_id]
+ for shape_id in generated_order
+ if shape_id not in source_id_by_generated_top_id
+ ]
+
+ authored_iterator = iter(authored_order)
+ merged_children: list[tuple[ET.Element, bool]] = []
+ final_authored_slot = 0
+ for child in list(source_tree):
+ shape_id = _shape_id(child) if child.tag in _TOP_LEVEL_SHAPE_TAGS else None
+ if shape_id not in authored_top_ids:
+ merged_children.append((child, False))
+ continue
+ next_shape_id = next(authored_iterator, None)
+ if next_shape_id is not None:
+ merged_children.append(selected_by_id[next_shape_id])
+ final_authored_slot = len(merged_children)
+ if next(authored_iterator, None) is not None:
+ raise TemplateStructureError(
+ "Generated authored shape roster exceeds the source overlay slots"
+ )
+ if not authored_top_ids:
+ final_authored_slot = next(
+ (
+ index
+ for index, (element, _generated) in enumerate(merged_children)
+ if element.tag in _TOP_LEVEL_SHAPE_TAGS
+ ),
+ len(merged_children),
+ )
+ merged_children[final_authored_slot:final_authored_slot] = [
+ (element, True)
+ for element in extra_generated
+ ]
+
+ generated_nodes = [
+ element for element, generated in merged_children if generated
+ ]
+ retained_source_nodes = [
+ element for element, generated in merged_children if not generated
+ ]
+ required_generated_relationship_ids = {
+ relationship_id
+ for element in generated_nodes
+ for relationship_id in _relationship_ids_in_shape(element)
+ }
+ if patch.motion_changed:
+ for local_name in ("transition", "timing"):
+ motion_node = generated_root.find(f"{{{PML_NS}}}{local_name}")
+ if motion_node is not None:
+ required_generated_relationship_ids.update(
+ _relationship_ids_in_shape(motion_node)
+ )
+ _merge_roundtrip_relationships(
+ source_rels,
+ generated_rels_path,
+ generated_root,
+ required_generated_relationship_ids,
+ )
+ if patch.motion_changed:
+ _replace_roundtrip_motion(source_root, generated_root)
+ _renumber_roundtrip_generated_shapes(
+ generated_nodes,
+ retained_source_nodes,
+ source_root,
+ rewrite_timing=patch.motion_changed,
+ )
+
+ for child in list(source_tree):
+ source_tree.remove(child)
+ for child, _generated in merged_children:
+ source_tree.append(child)
+
+ visible_shape_ids = {
+ value
+ for element in source_tree
+ for value in _shape_ids_in_element(element)
+ }
+ if not patch.motion_changed:
+ missing_timing_targets = _timing_shape_ids(source_root) - visible_shape_ids
+ if missing_timing_targets:
+ raise TemplateStructureError(
+ "Edited slide removed source animation target(s); update "
+ "animations.json explicitly: "
+ + ", ".join(sorted(missing_timing_targets, key=int))
+ )
+ _write_xml_tree(generated_slide_path, ET.ElementTree(source_root))
+
+
+def _remove_relationships_by_type(rels_path: Path, rel_type: str) -> int:
+ """Remove every relationship of one type and return the removed count."""
+ tree = ET.parse(rels_path)
+ root = tree.getroot()
+ removed = 0
+ for relationship in list(root):
+ if _relationship_attrs(relationship).get("Type") != rel_type:
+ continue
+ root.remove(relationship)
+ removed += 1
+ if removed:
+ _write_xml_tree(rels_path, tree)
+ return removed
+
+
+def _reinject_roundtrip_resources(
+ extract_dir: Path,
+ resource_root: Path | None,
+ resources: tuple[WorkspaceResourceSpec, ...],
+) -> int:
+ """Write semantic resource bytes back to their exact source package parts."""
+ materialized = [resource for resource in resources if resource.materialized]
+ if not materialized:
+ return 0
+ if resource_root is None:
+ raise TemplateStructureError(
+ "Round-trip resource reinjection requires an explicit project root"
+ )
+ workspace = resource_root.resolve()
+ written = 0
+ for resource in materialized:
+ source = (workspace / resource.workspace_path).resolve()
+ try:
+ source.relative_to(workspace)
+ except ValueError as exc:
+ raise TemplateStructureError(
+ "Round-trip resource resolves outside the project: "
+ f"{resource.workspace_path.as_posix()}"
+ ) from exc
+ if not source.is_file():
+ raise TemplateStructureError(
+ "Materialized round-trip resource is missing: "
+ f"{resource.workspace_path.as_posix()}"
+ )
+ target = extract_dir.joinpath(*PurePosixPath(resource.package_part).parts)
+ if not target.is_file():
+ raise TemplateStructureError(
+ "Round-trip source package part is missing: "
+ f"{resource.package_part}"
+ )
+ shutil.copyfile(source, target)
+ written += 1
+ return written
+
+
COVER_LAYOUT_NAME = "Cover"
@@ -3512,7 +4013,11 @@ def _remove_trailing_layout_definition_slides(
return removed
-def _prune_unreferenced_definition_payload_parts(extract_dir: Path) -> int:
+def _prune_unreferenced_definition_payload_parts(
+ extract_dir: Path,
+ *,
+ preserved_parts: frozenset[str] = frozenset(),
+) -> int:
"""Remove generated native/media payload left by deleted carrier slides.
Definition-only SVGs are first converted as ordinary slides so their
@@ -3558,6 +4063,8 @@ def _prune_unreferenced_definition_payload_parts(extract_dir: Path) -> int:
continue
if not part_name.startswith(candidate_prefixes):
continue
+ if part_name in preserved_parts:
+ continue
canonical = _canonical_opc_part_path(part_name)
if canonical is not None and canonical not in referenced_parts:
orphan_paths.append((path, part_name))
@@ -3886,10 +4393,41 @@ def _add_content_type_override(content_types: str, part_name: str, content_type:
normalized = '/' + part_name.lstrip('/')
if f'PartName="{normalized}"' in content_types:
return content_types
+ extension = PurePosixPath(part_name).suffix.lstrip('.').casefold()
+ try:
+ root = ET.fromstring(content_types)
+ except ET.ParseError:
+ root = None
+ if root is not None:
+ for child in root:
+ if child.tag.rsplit('}', 1)[-1] != 'Default':
+ continue
+ if (
+ child.get('Extension', '').casefold() == extension
+ and child.get('ContentType') == content_type
+ ):
+ return content_types
entry = f' <Override PartName="{normalized}" ContentType="{content_type}"/>'
return content_types.replace('</Types>', entry + '\n</Types>')
+def _content_type_contract(payload: bytes) -> tuple[tuple[str, tuple[tuple[str, str], ...]], ...] | None:
+ """Return the semantic Default/Override roster for exact-byte restoration."""
+ try:
+ root = ET.fromstring(payload)
+ except ET.ParseError:
+ return None
+ entries = [
+ (
+ child.tag.rsplit('}', 1)[-1],
+ tuple(sorted(child.attrib.items())),
+ )
+ for child in root
+ if child.tag.rsplit('}', 1)[-1] in {'Default', 'Override'}
+ ]
+ return tuple(sorted(entries))
+
+
_IMAGE_CONTENT_TYPES = {
'png': 'image/png',
'jpg': 'image/jpeg',
@@ -4752,8 +5290,20 @@ def _create_preserved_base_pptx(
specs: list[TemplateSlideSpec],
output_path: Path,
slide_size_emu: tuple[int, int],
-) -> None:
- """Create empty slides bound to the source package's original layouts."""
+) -> bool:
+ """Create the preserve base and report whether source Slides were retained."""
+ source_roster_matches = (
+ len(specs) == len(contract.slides)
+ and all(
+ spec.slide_num == source_slide.index
+ and spec.layout_key == source_slide.layout_key
+ for spec, source_slide in zip(specs, contract.slides)
+ )
+ )
+ if source_roster_matches:
+ shutil.copy2(contract.source_template, output_path)
+ return True
+
presentation = Presentation(str(contract.source_template))
actual_size = (int(presentation.slide_width), int(presentation.slide_height))
if actual_size != contract.slide_size_emu:
@@ -4786,6 +5336,7 @@ def _create_preserved_base_pptx(
)
presentation.slides.add_slide(layout)
presentation.save(str(output_path))
+ return False
def _clear_preserved_slide_collections(extract_dir: Path) -> None:
@@ -4939,6 +5490,8 @@ def _install_source_embedded_fonts(
def create_pptx_with_native_svg(
svg_files: list[Path],
output_path: Path,
+ *,
+ resource_root: Path,
canvas_format: str | None = None,
verbose: bool = True,
transition: str | None = 'fade',
@@ -4968,12 +5521,14 @@ def create_pptx_with_native_svg(
native_objects: bool = False,
conversion_trace_path: Path | None = None,
dangerous_nonconforming_export: bool = False,
- resource_root: Path | None = None,
doc_metadata: dict[str, Any] | None = None,
structure_name: str | None = None,
pptx_structure: str = "structured",
use_layout_placeholder_frames: bool = False,
native_structure_contract: NativeStructureContract | None = None,
+ roundtrip_passthrough_slides: set[int] | None = None,
+ roundtrip_slide_patches: dict[int, RoundtripSlidePatch] | None = None,
+ roundtrip_resources: tuple[WorkspaceResourceSpec, ...] = (),
theme_font_spec: ThemeFontSpec | None = None,
master_text_style_spec: MasterTextStyleSpec | None = None,
theme_color_spec: ThemeColorSpec | None = None,
@@ -5051,7 +5606,6 @@ def create_pptx_with_native_svg(
normalizations before strict SVG conversion. Actual contract,
conversion, and package failures remain blocking.
resource_root: Explicit project boundary for SVG-local resource paths.
- Direct library callers may omit it to retain legacy inference.
structure_name: Current deck identity used to name a flat Master, Layout,
and theme.
pptx_structure: PPTX structure strategy. ``baseline`` promotes safe
@@ -5068,6 +5622,13 @@ def create_pptx_with_native_svg(
of the tight SVG content frame. Default off for generated decks.
native_structure_contract: Validated source package contract for
``preserve`` mode.
+ roundtrip_passthrough_slides: Source slide indices whose SVG, notes,
+ and motion sidecars are unchanged and may retain their original
+ slide XML and relationships byte-for-byte.
+ roundtrip_slide_patches: Authoring metadata for rebuilt slides that
+ overlay edited objects onto their preserved source slide parts.
+ roundtrip_resources: Semantic workspace payloads copied back to their
+ exact source package parts after slide conversion.
theme_font_spec: Locked project major/minor fonts for flat/structured
release-theme inheritance. Direct diagnostic flat callers may omit it.
master_text_style_spec: Required declared title/body anchors for structured
@@ -5091,6 +5652,51 @@ def create_pptx_with_native_svg(
if primary_language is not None:
primary_language = normalize_language_tag(primary_language)
public_svg_files = list(svg_files)
+ passthrough_slides = set(roundtrip_passthrough_slides or set())
+ slide_patches = dict(roundtrip_slide_patches or {})
+ overlay_slides = set(slide_patches)
+ roundtrip_export = bool(
+ passthrough_slides or overlay_slides or roundtrip_resources
+ )
+ source_motion_slides = passthrough_slides | {
+ index
+ for index, patch in slide_patches.items()
+ if not patch.motion_changed
+ }
+ invalid_passthrough = sorted(
+ index
+ for index in passthrough_slides
+ if index < 1 or index > len(public_svg_files)
+ )
+ if invalid_passthrough:
+ raise ValueError(
+ "Round-trip passthrough slide indices are outside the SVG roster: "
+ + ", ".join(str(index) for index in invalid_passthrough)
+ )
+ invalid_overlays = sorted(
+ index
+ for index in overlay_slides
+ if index < 1 or index > len(public_svg_files)
+ )
+ if invalid_overlays:
+ raise ValueError(
+ "Round-trip overlay slide indices are outside the SVG roster: "
+ + ", ".join(str(index) for index in invalid_overlays)
+ )
+ overlap = sorted(passthrough_slides & overlay_slides)
+ if overlap:
+ raise ValueError(
+ "Round-trip slides cannot be both passthrough and overlay: "
+ + ", ".join(str(index) for index in overlap)
+ )
+ if passthrough_slides and pptx_structure != "preserve":
+ raise ValueError(
+ "Round-trip slide passthrough is available only in preserve mode"
+ )
+ if (overlay_slides or roundtrip_resources) and pptx_structure != "preserve":
+ raise ValueError(
+ "Round-trip overlays and resource reinjection require preserve mode"
+ )
definition_svg_files = list(layout_definition_files or [])
public_slide_names = [path.stem for path in public_svg_files]
morph_pairs = resolve_morph_pairs(
@@ -5331,13 +5937,14 @@ def create_pptx_with_native_svg(
try:
base_pptx = temp_dir / 'base.pptx'
+ preserved_source_slides = False
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(
+ preserved_source_slides = _create_preserved_base_pptx(
native_structure_contract,
template_specs,
base_pptx,
@@ -5358,8 +5965,32 @@ def create_pptx_with_native_svg(
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":
+ source_content_types_bytes = (
+ (extract_dir / '[Content_Types].xml').read_bytes()
+ if roundtrip_export
+ else None
+ )
+ roundtrip_source_parts = (
+ frozenset(
+ path.relative_to(extract_dir).as_posix()
+ for path in extract_dir.rglob('*')
+ if path.is_file()
+ )
+ if roundtrip_export
+ else frozenset()
+ )
+ if (
+ use_native_shapes
+ and pptx_structure == "preserve"
+ and not preserved_source_slides
+ ):
_clear_preserved_slide_collections(extract_dir)
+ if (
+ passthrough_slides or overlay_slides or roundtrip_resources
+ ) and not preserved_source_slides:
+ raise TemplateStructureError(
+ "Round-trip export requires the original source package roster"
+ )
active_theme_font_spec = (
theme_font_spec
if use_native_shapes
@@ -5381,7 +6012,7 @@ def create_pptx_with_native_svg(
and native_structure_contract is None
):
_install_source_theme_xml(extract_dir, source_theme_xml)
- if source_embedded_fonts is not None:
+ if source_embedded_fonts is not None and not roundtrip_export:
installed_typefaces = _install_source_embedded_fonts(
extract_dir,
source_embedded_fonts,
@@ -5471,6 +6102,41 @@ def create_pptx_with_native_svg(
expected_transition_sound: dict[str, str] | None = None
try:
+ slide_xml_path = (
+ extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
+ )
+ rels_path = (
+ extract_dir / 'ppt' / 'slides' / '_rels'
+ / f'slide{slide_num}.xml.rels'
+ )
+ slide_patch = slide_patches.get(slide_num)
+ source_slide_bytes: bytes | None = None
+ source_rels_bytes: bytes | None = None
+ if slide_patch is not None:
+ if is_layout_definition:
+ raise TemplateStructureError(
+ "Internal Layout definitions cannot use round-trip overlays"
+ )
+ try:
+ source_slide_bytes = slide_xml_path.read_bytes()
+ source_rels_bytes = rels_path.read_bytes()
+ except OSError as exc:
+ raise TemplateStructureError(
+ f"Cannot read source slide {slide_num} for overlay: {exc}"
+ ) from exc
+ if slide_num in passthrough_slides:
+ if is_layout_definition:
+ raise TemplateStructureError(
+ "Internal Layout definitions cannot use source-slide passthrough"
+ )
+ if verbose:
+ print(
+ f" {progress_label} {svg_path.name} "
+ "(Source slide passthrough)"
+ )
+ success_count += 1
+ continue
+
# ---- Native shapes mode ----
if use_native_shapes:
slide_cfg = (
@@ -5904,12 +6570,45 @@ def create_pptx_with_native_svg(
with open(rels_path, 'w', encoding='utf-8') as f:
f.write(rels_xml)
+ if slide_patch is not None:
+ if source_slide_bytes is None or source_rels_bytes is None:
+ raise TemplateStructureError(
+ f"Round-trip slide {slide_num} source snapshot is missing"
+ )
+ trace_sink = (
+ conversion_trace
+ if conversion_trace is not None
+ else structure_trace
+ )
+ slide_conversion_trace = next(
+ (
+ entry
+ for entry in reversed(trace_sink or [])
+ if entry.get("slide_num") == slide_num
+ ),
+ None,
+ )
+ _apply_roundtrip_slide_overlay(
+ source_slide_bytes,
+ source_rels_bytes,
+ slide_xml_path,
+ rels_path,
+ slide_patch,
+ slide_conversion_trace,
+ )
+
resolved_advance_after = slide_auto_advance
resolved_advance_on_click = True
# --- Process notes (shared between native and legacy mode) ---
notes_content = ''
- if enable_notes and not is_layout_definition:
+ notes_changed = slide_patch is None or slide_patch.notes_changed
+ if slide_patch is not None and slide_patch.notes_changed:
+ _remove_relationships_by_type(
+ rels_path,
+ NOTES_SLIDE_REL_TYPE,
+ )
+ if enable_notes and not is_layout_definition and notes_changed:
svg_stem = svg_path.stem
notes_content = notes.get(svg_stem, '') if notes else ''
notes_text = markdown_to_plain_text(notes_content) if notes_content else ''
@@ -5935,9 +6634,9 @@ def create_pptx_with_native_svg(
with open(notes_rels_path, 'w', encoding='utf-8') as f:
f.write(notes_rels_xml)
- _append_relationship(
+ _ensure_relationship(
rels_path,
- 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide',
+ NOTES_SLIDE_REL_TYPE,
f'../notesSlides/notesSlide{slide_num}.xml',
)
notes_slides_created.add(slide_num)
@@ -6024,38 +6723,52 @@ def create_pptx_with_native_svg(
narration_slides_created.add(slide_num)
final_slide_xml = slide_xml_path.read_text(encoding='utf-8')
- try:
- resolved_motion = validate_generated_transition_xml(
- final_slide_xml,
- effect=slide_transition,
- effect_options=slide_transition_effect_options,
- duration=slide_transition_duration,
- advance_on_click=resolved_advance_on_click,
- advance_after=resolved_advance_after,
- sound=expected_transition_sound,
- )
- except ValueError as exc:
- raise RuntimeError(
- f'Slide {slide_num} transition validation failed: {exc}'
- ) from exc
- try:
- resolved_animation = validate_generated_animation_xml(
- final_slide_xml,
- expected_animation_targets,
- duration=expected_animation_duration,
- trigger=expected_animation_trigger,
- )
- except ValueError as exc:
- raise RuntimeError(
- f'Slide {slide_num} animation validation failed: {exc}'
- ) from exc
+ preserved_source_motion = (
+ slide_patch is not None and not slide_patch.motion_changed
+ )
+ resolved_motion = None
+ resolved_animation = None
+ if not preserved_source_motion:
+ try:
+ resolved_motion = validate_generated_transition_xml(
+ final_slide_xml,
+ effect=slide_transition,
+ effect_options=slide_transition_effect_options,
+ duration=slide_transition_duration,
+ advance_on_click=resolved_advance_on_click,
+ advance_after=resolved_advance_after,
+ sound=expected_transition_sound,
+ )
+ except ValueError as exc:
+ raise RuntimeError(
+ f'Slide {slide_num} transition validation failed: {exc}'
+ ) from exc
+ try:
+ resolved_animation = validate_generated_animation_xml(
+ final_slide_xml,
+ expected_animation_targets,
+ duration=expected_animation_duration,
+ trigger=expected_animation_trigger,
+ )
+ except ValueError as exc:
+ raise RuntimeError(
+ f'Slide {slide_num} animation validation failed: {exc}'
+ ) from exc
if conversion_trace is not None:
- motion_summary = asdict(resolved_motion)
+ motion_summary = (
+ {"source_preserved": True}
+ if resolved_motion is None
+ else asdict(resolved_motion)
+ )
for trace_entry in reversed(conversion_trace):
if trace_entry.get('slide_num') == slide_num:
trace_entry['motion'] = motion_summary
- trace_entry['animation'] = asdict(resolved_animation)
+ trace_entry['animation'] = (
+ {"source_preserved": True}
+ if resolved_animation is None
+ else asdict(resolved_animation)
+ )
break
if verbose:
@@ -6207,13 +6920,32 @@ def create_pptx_with_native_svg(
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,
+ rebuilt_specs = [
+ spec
+ for spec in template_specs
+ if spec.slide_num not in passthrough_slides | overlay_slides
+ ]
+ if rebuilt_specs:
+ _apply_preserved_structure(
+ extract_dir,
+ rebuilt_specs,
+ native_structure_contract,
+ conversion_trace if conversion_trace is not None else structure_trace,
+ verbose=verbose,
+ )
+
+ if roundtrip_export:
+ pruned_roundtrip_payloads = (
+ _prune_unreferenced_definition_payload_parts(
+ extract_dir,
+ preserved_parts=roundtrip_source_parts,
+ )
)
+ if verbose and pruned_roundtrip_payloads:
+ print(
+ " Round-trip overlay: pruned "
+ f"{pruned_roundtrip_payloads} unused generated payload part(s)"
+ )
if (
use_native_shapes
@@ -6331,9 +7063,28 @@ def create_pptx_with_native_svg(
with open(content_types_path, 'w', encoding='utf-8') as f:
f.write(content_types)
+ if source_content_types_bytes is not None:
+ current_content_types = content_types_path.read_bytes()
+ if (
+ _content_type_contract(current_content_types)
+ == _content_type_contract(source_content_types_bytes)
+ ):
+ content_types_path.write_bytes(source_content_types_bytes)
+
if package_uses_timings:
set_directory_use_timings(extract_dir)
+ reinjected_resources = _reinject_roundtrip_resources(
+ extract_dir,
+ resource_root,
+ roundtrip_resources,
+ )
+ if verbose and reinjected_resources:
+ print(
+ " Round-trip resources: reinjected "
+ f"{reinjected_resources} source package part(s)"
+ )
+
rels_problems = verify_internal_relationships(extract_dir)
if rels_problems:
details = '\n'.join(f' - {p}' for p in rels_problems)
@@ -6349,12 +7100,13 @@ def create_pptx_with_native_svg(
effective_doc_metadata = dict(doc_metadata or {})
if primary_language is not None:
effective_doc_metadata['language'] = primary_language
- _stamp_docprops(
- extract_dir,
- public_slide_count,
- pres_format,
- effective_doc_metadata,
- )
+ if not roundtrip_export or doc_metadata:
+ _stamp_docprops(
+ extract_dir,
+ public_slide_count,
+ pres_format,
+ effective_doc_metadata,
+ )
# Repackage PPTX to a temporary file first. The public output path is
# replaced only after every slide and relationship has succeeded.
@@ -6409,6 +7161,7 @@ def create_pptx_with_native_svg(
validate_pptx_animation_package(
temp_output_path,
require_supported_effects=True,
+ skip_slide_numbers=source_motion_slides,
)
except ValueError as exc:
raise RuntimeError(
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 2e5fa1e1..65884a1e 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
@@ -51,6 +51,16 @@ from pptx_transitions import ( # noqa: E402
normalize_transition_effect_request,
validate_seconds,
)
+from pptx_workspace import ( # noqa: E402
+ AUTHORING_SVG_FLAT_DIR,
+ WorkspaceResourceSpec,
+ conversion_report_path,
+ load_roundtrip_manifest,
+ native_structure_path,
+ slide_animation_config_sha256,
+ source_pptx_path,
+ workspace_resource_specs,
+)
configure_utf8_stdio()
@@ -64,7 +74,7 @@ if __package__ in {None, ''}:
from .dimensions import CANVAS_FORMATS, get_project_info
from .discovery import NotesFileReadError, find_notes_files, find_svg_files
-from .builder import create_pptx_with_native_svg
+from .builder import RoundtripSlidePatch, create_pptx_with_native_svg
from ..native_objects import (
native_fallback_kind,
native_replacement_kind,
@@ -112,16 +122,387 @@ from ..animation_config import (
validate_animation_config_errors,
validate_transition_config,
)
-from template_import.native_structure import (
- CONTRACT_NAME as NATIVE_STRUCTURE_NAME,
- SOURCE_TEMPLATE_NAME,
-)
-
-
def _as_dict(value: object) -> dict:
return value if isinstance(value, dict) else {}
+def _path_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 _roundtrip_slide_parts(
+ row: dict[str, object],
+ *,
+ include_structure: bool,
+) -> set[str]:
+ """Return package owners that make one semantic sidecar slide-relevant."""
+ keys = ["sourcePart"]
+ if include_structure:
+ keys.extend(["layoutPart", "masterPart"])
+ parts = {
+ str(row[key])
+ for key in keys
+ if isinstance(row.get(key), str) and row.get(key)
+ }
+ note = row.get("notes")
+ if isinstance(note, dict) and isinstance(note.get("sourcePart"), str):
+ parts.add(str(note["sourcePart"]))
+ return parts
+
+
+def _resource_owner_parts(item: dict[str, object]) -> set[str]:
+ raw = item.get("ownerParts")
+ if not isinstance(raw, list):
+ raw = item.get("sourceParts")
+ return {
+ str(value)
+ for value in raw or []
+ if isinstance(value, str) and value
+ }
+
+
+def _resource_slide_indices(
+ item: dict[str, object],
+ slide_rows: dict[int, dict[str, object]],
+ *,
+ include_structure: bool,
+) -> set[int]:
+ owners = _resource_owner_parts(item)
+ return {
+ index
+ for index, row in slide_rows.items()
+ if owners & _roundtrip_slide_parts(
+ row,
+ include_structure=include_structure,
+ )
+ }
+
+
+def _roundtrip_passthrough_candidates(
+ project_path: Path,
+ native_files: list[Path],
+ *,
+ source_dir: str,
+ authoring_report: dict[str, object] | None,
+) -> set[int]:
+ """Return source slides whose visual and editable sidecars are unchanged."""
+ manifest = load_roundtrip_manifest(project_path)
+ if manifest is None or manifest.get('schema') != 'ppt-master.roundtrip-workspace.v1':
+ raise RuntimeError(
+ "Round-trip export requires analysis/roundtrip_manifest.json "
+ "with schema ppt-master.roundtrip-workspace.v1"
+ )
+ raw_slides = manifest.get('slides')
+ if not isinstance(raw_slides, list):
+ return set()
+ slide_rows = {
+ int(row['index']): row
+ for row in raw_slides
+ if isinstance(row, dict) and isinstance(row.get('index'), int)
+ }
+ if len(slide_rows) != len(native_files):
+ return set()
+
+ candidates: set[int] = set()
+ if authoring_report is not None:
+ raw_documents = authoring_report.get('documents')
+ if not isinstance(raw_documents, list):
+ return set()
+ reports = {
+ str(row.get('file')): row
+ for row in raw_documents
+ if isinstance(row, dict) and isinstance(row.get('file'), str)
+ }
+ for index in slide_rows:
+ report = reports.get(f'slide_{index:02d}.svg')
+ if not isinstance(report, dict):
+ continue
+ if (
+ report.get('document_unchanged') is True
+ and
+ isinstance(report.get('source_ref_count'), int)
+ and report.get('source_ref_count') == report.get('unchanged_refs')
+ and int(report.get('edited_refs') or 0) == 0
+ and int(report.get('deleted_refs') or 0) == 0
+ and int(report.get('authored_unreferenced') or 0) == 0
+ and report.get('defs_changed') is False
+ ):
+ candidates.add(index)
+ elif source_dir == 'svg':
+ files_by_name = {path.name: path for path in native_files}
+ for index, row in slide_rows.items():
+ relative = row.get('layeredSvg')
+ expected = row.get('layeredSvgSha256')
+ if not isinstance(relative, str) or not isinstance(expected, str):
+ continue
+ path = files_by_name.get(Path(relative).name)
+ if path is not None and _path_sha256(path) == expected:
+ candidates.add(index)
+ else:
+ return set()
+
+ sidecars = manifest.get('sidecars')
+ animation = sidecars.get('animations') if isinstance(sidecars, dict) else None
+ if not isinstance(animation, dict):
+ return set()
+ animation_file = animation.get('file')
+ if not isinstance(animation_file, str):
+ raise RuntimeError(
+ "Round-trip manifest must declare sidecars.animations.file"
+ )
+ current_animation = project_path / animation_file
+ if not current_animation.is_file():
+ return set()
+ try:
+ current_animation_config = json.loads(
+ current_animation.read_text(encoding="utf-8")
+ )
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise RuntimeError(
+ f"Cannot read round-trip animation sidecar {current_animation}: {exc}"
+ ) from exc
+ if not isinstance(current_animation_config, dict):
+ raise RuntimeError(
+ f"Round-trip animation sidecar must be a JSON object: {current_animation}"
+ )
+ for index in tuple(candidates):
+ expected = slide_rows[index].get("animationSha256")
+ if not isinstance(expected, str):
+ raise RuntimeError(
+ f"Round-trip manifest slide {index} lacks animationSha256"
+ )
+ actual = slide_animation_config_sha256(
+ current_animation_config,
+ f"slide_{index:02d}",
+ )
+ if actual != expected:
+ candidates.discard(index)
+
+ notes_dir = project_path / 'notes'
+ for index in tuple(candidates):
+ row = slide_rows[index]
+ note = row.get('notes')
+ canonical_note = notes_dir / f'slide_{index:02d}.md'
+ if isinstance(note, dict):
+ note_file = note.get('file')
+ note_sha = note.get('sha256')
+ if not isinstance(note_file, str) or not isinstance(note_sha, str):
+ candidates.discard(index)
+ continue
+ current_note = project_path / note_file
+ if not current_note.is_file() or _path_sha256(current_note) != note_sha:
+ candidates.discard(index)
+ elif canonical_note.is_file():
+ candidates.discard(index)
+ derived = row.get("derivedResources")
+ if not isinstance(derived, list):
+ raise RuntimeError(
+ f"Round-trip manifest slide {index} lacks derivedResources"
+ )
+ for resource_index, raw in enumerate(derived):
+ if not isinstance(raw, dict):
+ raise RuntimeError(
+ f"Round-trip slide {index} derivedResources[{resource_index}] "
+ "must be an object"
+ )
+ relative = raw.get("file")
+ expected_sha = raw.get("sha256")
+ if not isinstance(relative, str) or not isinstance(expected_sha, str):
+ raise RuntimeError(
+ f"Round-trip slide {index} derived resource is incomplete"
+ )
+ path = (project_path / relative).resolve()
+ try:
+ path.relative_to(project_path.resolve())
+ except ValueError as exc:
+ raise RuntimeError(
+ f"Round-trip derived resource escapes the project: {relative}"
+ ) from exc
+ if not path.is_file() or _path_sha256(path) != expected_sha:
+ candidates.discard(index)
+ break
+ return candidates
+
+
+def _roundtrip_note_changed(
+ project_path: Path,
+ row: dict[str, object],
+ index: int,
+) -> bool:
+ """Return whether one canonical per-slide notes source changed."""
+ note = row.get("notes")
+ if isinstance(note, dict):
+ relative = note.get("file")
+ expected_sha = note.get("sha256")
+ if not isinstance(relative, str) or not isinstance(expected_sha, str):
+ raise RuntimeError(
+ f"Round-trip manifest slide {index} has incomplete notes metadata"
+ )
+ current = project_path / relative
+ return not current.is_file() or _path_sha256(current) != expected_sha
+ return (project_path / "notes" / f"slide_{index:02d}.md").is_file()
+
+
+def _roundtrip_slide_patches(
+ project_path: Path,
+ authoring_report: dict[str, object] | None,
+ passthrough_slides: set[int],
+ *,
+ force_motion_changed: bool,
+ force_notes_changed: bool,
+) -> dict[int, RoundtripSlidePatch]:
+ """Build strict source-overlay metadata for edited authoring slides."""
+ if authoring_report is None:
+ return {}
+ manifest = load_roundtrip_manifest(project_path)
+ if manifest is None:
+ raise RuntimeError("Round-trip manifest is missing")
+ raw_slides = manifest.get("slides")
+ if not isinstance(raw_slides, list):
+ raise RuntimeError("Round-trip manifest slides must be an array")
+ slide_rows = {
+ int(row["index"]): row
+ for row in raw_slides
+ if isinstance(row, dict) and isinstance(row.get("index"), int)
+ }
+ sidecars = manifest.get("sidecars")
+ animation = sidecars.get("animations") if isinstance(sidecars, dict) else None
+ animation_file = animation.get("file") if isinstance(animation, dict) else None
+ if not isinstance(animation_file, str):
+ raise RuntimeError(
+ "Round-trip manifest must declare sidecars.animations.file"
+ )
+ try:
+ animation_config = json.loads(
+ (project_path / animation_file).read_text(encoding="utf-8")
+ )
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise RuntimeError(
+ f"Cannot read round-trip animation sidecar: {exc}"
+ ) from exc
+ if not isinstance(animation_config, dict):
+ raise RuntimeError("Round-trip animation sidecar must be a JSON object")
+
+ documents = authoring_report.get("documents")
+ if not isinstance(documents, list):
+ raise RuntimeError("Authoring round-trip report documents must be an array")
+ patches: dict[int, RoundtripSlidePatch] = {}
+ for raw in documents:
+ if not isinstance(raw, dict) or not isinstance(raw.get("file"), str):
+ raise RuntimeError("Authoring round-trip document report is incomplete")
+ match = re.fullmatch(r"slide_(\d+)\.svg", str(raw["file"]))
+ if match is None:
+ raise RuntimeError(
+ f"Unexpected authoring round-trip slide name: {raw['file']}"
+ )
+ index = int(match.group(1))
+ if index in passthrough_slides:
+ continue
+ row = slide_rows.get(index)
+ if row is None:
+ raise RuntimeError(
+ f"Round-trip manifest has no slide {index} for authoring overlay"
+ )
+ expected_animation = row.get("animationSha256")
+ if not isinstance(expected_animation, str):
+ raise RuntimeError(
+ f"Round-trip manifest slide {index} lacks animationSha256"
+ )
+ motion_changed = force_motion_changed or (
+ slide_animation_config_sha256(
+ animation_config,
+ f"slide_{index:02d}",
+ )
+ != expected_animation
+ )
+
+ def _ref_set(field: str) -> frozenset[str]:
+ value = raw.get(field)
+ if not isinstance(value, list) or not all(
+ isinstance(item, str) for item in value
+ ):
+ raise RuntimeError(
+ f"Authoring round-trip slide {index} has invalid {field}"
+ )
+ return frozenset(value)
+
+ patches[index] = RoundtripSlidePatch(
+ source_ref_ids=_ref_set("source_ref_ids"),
+ edited_ref_ids=_ref_set("edited_ref_ids"),
+ deleted_ref_ids=_ref_set("deleted_ref_ids"),
+ motion_changed=motion_changed,
+ notes_changed=(
+ force_notes_changed
+ or _roundtrip_note_changed(project_path, row, index)
+ ),
+ )
+ return patches
+
+
+def _opaque_roundtrip_slide_dependencies(
+ project_path: Path,
+) -> dict[int, list[str]]:
+ """Map source slides that own video/audio/opaque relationships."""
+ manifest = load_roundtrip_manifest(project_path)
+ if manifest is None:
+ return {}
+ resources = manifest.get('resources')
+ items = resources.get('items') if isinstance(resources, dict) else None
+ if not isinstance(items, list):
+ return {}
+ raw_slides = manifest.get("slides")
+ if not isinstance(raw_slides, list):
+ return {}
+ slide_rows = {
+ int(row["index"]): row
+ for row in raw_slides
+ if isinstance(row, dict) and isinstance(row.get("index"), int)
+ }
+ dependencies: dict[int, list[str]] = {}
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ kind = item.get('kind')
+ owners = _resource_owner_parts(item)
+ notes_owned = any(
+ owner.startswith("ppt/notesSlides/notesSlide")
+ for owner in owners
+ )
+ source_parts = item.get('sourceParts')
+ chart_native_payload = (
+ kind == 'native-payload'
+ and isinstance(source_parts, list)
+ and bool(source_parts)
+ and all(
+ isinstance(source_part, str)
+ and source_part.startswith('ppt/charts/')
+ for source_part in source_parts
+ )
+ )
+ if (
+ not notes_owned
+ and kind not in {'audio', 'native-payload', 'video'}
+ ) or chart_native_payload:
+ continue
+ workspace_path = item.get('workspacePath')
+ if not isinstance(workspace_path, str):
+ continue
+ for index in _resource_slide_indices(
+ item,
+ slide_rows,
+ include_structure=False,
+ ):
+ dependencies.setdefault(index, []).append(workspace_path)
+ return {
+ index: sorted(set(paths))
+ for index, paths in dependencies.items()
+ }
+
+
_PPTX_STRUCTURE_SECTION_RE = re.compile(
r"(?ms)^##[ \t]+pptx_structure[ \t]*\r?\n(.*?)(?=^##[ \t]+|\Z)"
)
@@ -165,7 +546,7 @@ def _load_diagnostic_import_source(
EmbeddedFontBundle | None,
]:
"""Load source-document evidence emitted for diagnostic round-trip."""
- report_path = project_path / 'conversion-report.json'
+ report_path = conversion_report_path(project_path)
if not report_path.is_file():
return None, None, None, None
try:
@@ -1050,8 +1431,7 @@ Examples:
%(prog)s projects/ppt169_demo # Default: native pptx -> exports/, svg_output -> backup/<ts>/
%(prog)s projects/ppt169_demo -o out.pptx # Explicit path (no backup/)
%(prog)s projects/quick_generate_demo --quick-generate # Lockless flat export with normal postflight
- %(prog)s <import_workspace> -s authoring-svg-flat \\
- --roundtrip # Editable IR with source restoration
+ %(prog)s <import_workspace> --roundtrip # authoring-svg-flat/ with source restoration
# Disable transition / change transition effect
%(prog)s projects/ppt169_demo -t none
@@ -1145,12 +1525,11 @@ Recorded narration:
'--roundtrip',
action='store_true',
help=(
- 'Source-preserving import export: rebuild layered slide_*.svg, or '
- 'materialize a flat authoring IR selected with -s, against the '
- 'validated source_template.pptx/native_structure.json emitted by '
- 'pptx_to_svg.py --roundtrip. Unchanged authoring objects recover '
- 'their source semantics; edited objects remain authored SVG. Does '
- 'not alter normal flat/structured release export.'
+ 'Source-preserving import export from authoring-svg-flat/ against '
+ 'the validated sources/source.pptx and analysis contracts emitted '
+ 'by pptx_to_svg.py --roundtrip. Unchanged authoring objects recover '
+ 'their source semantics; edited objects remain authored SVG. No '
+ 'other -s/--source directory is accepted in round-trip mode.'
),
)
parser.add_argument(
@@ -1383,7 +1762,6 @@ Recorded narration:
raw_argv = list(argv) if argv is not None else sys.argv[1:]
legacy_native_objects = '--native-objects' in raw_argv
args = parser.parse_args(raw_argv)
- diagnostic_source = args.source not in {None, 'output'}
compatibility_export = args.enable_dangerous_nonconforming_svg_export
if legacy_native_objects:
print(
@@ -1436,8 +1814,10 @@ Recorded narration:
conflicts: list[str] = []
if args.quick_generate:
conflicts.append('--quick-generate')
- if args.source is None:
- conflicts.append('-s/--source is required')
+ if args.source not in {None, AUTHORING_SVG_FLAT_DIR.as_posix()}:
+ conflicts.append(
+ '-s/--source must be omitted or authoring-svg-flat'
+ )
if args.pptx_structure is not None:
conflicts.append('--pptx-structure must be omitted')
if conflicts:
@@ -1447,8 +1827,11 @@ Recorded narration:
file=sys.stderr,
)
return 1
+ args.source = AUTHORING_SVG_FLAT_DIR.as_posix()
args.pptx_structure = 'preserve'
+ diagnostic_source = args.source not in {None, 'output'}
+
if args.quick_generate:
conflicts: list[str] = []
if args.source not in {None, 'output'}:
@@ -1482,6 +1865,7 @@ Recorded narration:
structure_lock = None
native_structure_contract = None
+ roundtrip_resources: tuple[WorkspaceResourceSpec, ...] = ()
pptx_structure = args.pptx_structure
lock_path = project_path / 'spec_lock.md'
lockless_export = (
@@ -1546,8 +1930,8 @@ Recorded narration:
if args.roundtrip:
structure_lock = PptxStructureLock(
mode='preserve',
- source_template=project_path / SOURCE_TEMPLATE_NAME,
- native_structure=project_path / NATIVE_STRUCTURE_NAME,
+ source_template=source_pptx_path(project_path),
+ native_structure=native_structure_path(project_path),
)
try:
native_structure_contract = load_native_structure_contract(
@@ -1556,6 +1940,19 @@ Recorded narration:
except TemplateStructureError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
+ try:
+ roundtrip_manifest = load_roundtrip_manifest(project_path)
+ if roundtrip_manifest is None:
+ raise RuntimeError(
+ "Round-trip export requires analysis/roundtrip_manifest.json"
+ )
+ roundtrip_resources = workspace_resource_specs(
+ project_path,
+ roundtrip_manifest,
+ )
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
if (
pptx_structure in _RELEASE_PPTX_STRUCTURE_MODES
@@ -1689,12 +2086,12 @@ Recorded narration:
ref_files = native_files
authoring_roundtrip_temporary: tempfile.TemporaryDirectory[str] | None = None
authoring_roundtrip_report: dict[str, object] | None = None
- if args.roundtrip and args.source != 'svg':
+ if args.roundtrip:
authoring_source_dir = project_path / native_source_dir
if not is_flat_authoring_bundle(authoring_source_dir):
print(
- "Error: --roundtrip with a source other than svg requires a "
- "flat authoring bundle with authoring_manifest.json: "
+ "Error: --roundtrip requires authoring-svg-flat/ with "
+ "authoring_manifest.json: "
f"{authoring_source_dir}",
file=sys.stderr,
)
@@ -1725,6 +2122,106 @@ Recorded narration:
f"{totals.get('deleted_refs', 0)} deleted ref(s)"
)
+ roundtrip_passthrough_slides: set[int] = set()
+ roundtrip_slide_patches: dict[int, RoundtripSlidePatch] = {}
+ roundtrip_passthrough_overridden = any((
+ args.no_notes,
+ args.no_animations,
+ args.transition is not None,
+ args.transition_duration is not None,
+ args.auto_advance is not None,
+ args.animation is not None,
+ args.animation_duration is not None,
+ args.animation_stagger is not None,
+ args.animation_trigger is not None,
+ args.animation_config is not None,
+ args.recorded_narration is not None,
+ args.narration_audio_dir is not None,
+ args.use_narration_timings,
+ args.inherit_motion_from is not None,
+ args.image_sizing == 'display',
+ args.text_flow != TEXT_FLOW_PRESERVE,
+ ))
+ if args.roundtrip and not roundtrip_passthrough_overridden:
+ try:
+ roundtrip_passthrough_slides = _roundtrip_passthrough_candidates(
+ project_path.resolve(),
+ native_files,
+ source_dir=args.source or native_source_dir,
+ authoring_report=authoring_roundtrip_report,
+ )
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ if roundtrip_passthrough_slides:
+ print(
+ " Source slide passthrough: "
+ f"{len(roundtrip_passthrough_slides)}/{len(native_files)} "
+ "slide(s) retain original XML and relationships"
+ )
+ if authoring_roundtrip_report is not None:
+ authoring_roundtrip_report['source_slide_passthrough'] = {
+ 'count': len(roundtrip_passthrough_slides),
+ 'slides': sorted(roundtrip_passthrough_slides),
+ }
+ if args.roundtrip:
+ roundtrip_motion_overridden = any((
+ args.no_animations,
+ args.transition is not None,
+ args.transition_duration is not None,
+ args.auto_advance is not None,
+ args.animation is not None,
+ args.animation_duration is not None,
+ args.animation_stagger is not None,
+ args.animation_trigger is not None,
+ args.animation_config is not None,
+ args.recorded_narration is not None,
+ args.narration_audio_dir is not None,
+ args.use_narration_timings,
+ args.inherit_motion_from is not None,
+ ))
+ try:
+ roundtrip_slide_patches = _roundtrip_slide_patches(
+ project_path.resolve(),
+ authoring_roundtrip_report,
+ roundtrip_passthrough_slides,
+ force_motion_changed=roundtrip_motion_overridden,
+ force_notes_changed=args.no_notes,
+ )
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ try:
+ opaque_dependencies = _opaque_roundtrip_slide_dependencies(
+ project_path.resolve()
+ )
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ blocked_dependencies = {
+ index: paths
+ for index, paths in opaque_dependencies.items()
+ if index not in roundtrip_passthrough_slides
+ and index not in roundtrip_slide_patches
+ }
+ if blocked_dependencies:
+ print(
+ "Error: direct layered-SVG rebuild would drop source video, "
+ "audio, or opaque native payload relationships:",
+ file=sys.stderr,
+ )
+ for index, paths in sorted(blocked_dependencies.items()):
+ print(
+ f" slide {index}: " + ", ".join(paths),
+ file=sys.stderr,
+ )
+ print(
+ "Use the imported authoring-svg-flat bundle so edited objects "
+ "can overlay the preserved source slide.",
+ file=sys.stderr,
+ )
+ return 1
+
release_quality_gate = (
args.quick_generate
or args.source in {None, 'output'}
@@ -2351,6 +2848,9 @@ Recorded narration:
baseline_layout_specs=baseline_layout_specs,
layout_definition_files=layout_definition_files,
native_structure_contract=native_structure_contract,
+ roundtrip_passthrough_slides=roundtrip_passthrough_slides,
+ roundtrip_slide_patches=roundtrip_slide_patches,
+ roundtrip_resources=roundtrip_resources,
theme_font_spec=theme_font_spec,
master_text_style_spec=master_text_style_spec,
theme_color_spec=theme_color_spec,
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 132e744a..217c7455 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
@@ -247,6 +247,15 @@ class NativeLayoutSpec:
placeholders: tuple[NativePlaceholderSpec, ...] = ()
+@dataclass(frozen=True)
+class NativeSlideSpec:
+ """One source slide retained by index for exact round-trip passthrough."""
+
+ index: int
+ package_part: str
+ layout_key: str
+
+
@dataclass(frozen=True)
class NativeStructureContract:
"""Validated portable contract for a preserved source PPTX package."""
@@ -256,6 +265,7 @@ class NativeStructureContract:
source_sha256: str
slide_size_emu: tuple[int, int]
layouts: tuple[NativeLayoutSpec, ...]
+ slides: tuple[NativeSlideSpec, ...]
def layout(self, key: str) -> NativeLayoutSpec:
for layout in self.layouts:
@@ -265,6 +275,15 @@ class NativeStructureContract:
f"native_structure.json has no layout key {key!r}"
)
+ def slide(self, index: int) -> NativeSlideSpec:
+ """Return one source slide contract by presentation-order index."""
+ for slide in self.slides:
+ if slide.index == index:
+ return slide
+ raise TemplateStructureError(
+ f"native_structure.json has no source slide {index}"
+ )
+
@dataclass(frozen=True)
class TemplateElementSpec:
@@ -1150,6 +1169,59 @@ def load_native_structure_contract(
seen_keys.add(key)
seen_parts.add(package_part)
+ raw_slides = raw.get("slides")
+ if not isinstance(raw_slides, list) or not raw_slides:
+ raise TemplateStructureError(
+ f"{contract_path.name} must contain at least one source slide"
+ )
+ slides: list[NativeSlideSpec] = []
+ seen_slide_indices: set[int] = set()
+ slide_parts: set[str] = set()
+ for position, item in enumerate(raw_slides, start=1):
+ context = f"{contract_path.name} slides[{position}]"
+ if not isinstance(item, dict):
+ raise TemplateStructureError(f"{context} must be an object")
+ try:
+ slide_index = int(item.get("index"))
+ except (TypeError, ValueError) as exc:
+ raise TemplateStructureError(f"{context} index must be an integer") from exc
+ if slide_index <= 0 or slide_index in seen_slide_indices:
+ raise TemplateStructureError(
+ f"{context} index must be unique and positive"
+ )
+ layout_key = str(item.get("layoutKey") or "")
+ if layout_key not in seen_keys:
+ raise TemplateStructureError(
+ f"{context} references unknown layout key {layout_key!r}"
+ )
+ raw_package_part = item.get("packagePart")
+ if not isinstance(raw_package_part, str) or not raw_package_part:
+ raise TemplateStructureError(
+ f"{context} packagePart must be a non-empty string"
+ )
+ package_part = raw_package_part
+ if (
+ not package_part.startswith("ppt/slides/")
+ or ".." in Path(package_part).parts
+ or not package_part.endswith(".xml")
+ or package_part in slide_parts
+ ):
+ raise TemplateStructureError(
+ f"{context} packagePart must be a unique ppt/slides/*.xml part"
+ )
+ slides.append(NativeSlideSpec(
+ index=slide_index,
+ package_part=package_part,
+ layout_key=layout_key,
+ ))
+ seen_slide_indices.add(slide_index)
+ slide_parts.add(package_part)
+ expected_indices = set(range(1, len(slides) + 1))
+ if seen_slide_indices != expected_indices:
+ raise TemplateStructureError(
+ f"{contract_path.name} source slide indices must be contiguous from 1"
+ )
+
try:
with zipfile.ZipFile(source_template, "r") as package:
package_parts = set(package.namelist())
@@ -1157,7 +1229,7 @@ def load_native_structure_contract(
raise TemplateStructureError(
f"Cannot open preserved source template {source_template}: {exc}"
) from exc
- missing_parts = sorted(seen_parts - package_parts)
+ missing_parts = sorted((seen_parts | slide_parts) - package_parts)
if missing_parts:
raise TemplateStructureError(
f"{source_template.name} is missing layout part(s): " + ", ".join(missing_parts)
@@ -1169,6 +1241,7 @@ def load_native_structure_contract(
source_sha256=expected_sha,
slide_size_emu=slide_size_emu,
layouts=tuple(layouts),
+ slides=tuple(sorted(slides, key=lambda item: item.index)),
)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/use_expander.py b/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
index e5216ea2..253f6304 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
@@ -8,7 +8,7 @@ expansion in memory so ``svg_to_pptx`` can consume ``svg_output/`` directly
without first running the on-disk finalize step.
Public API:
- expand_use_data_icons(root, icons_dir, fallback_dir=None) -> int
+ expand_use_data_icons(root, icons_dir) -> int
Walk the SVG element tree, replace every ``<use data-icon="...">``
with its expanded ``<g>`` group of primitive shapes, and return
the number of replacements made.
@@ -230,7 +230,10 @@ class _LocalUseExpander:
for index, child in enumerate(list(parent)):
if _local_tag(child) == 'defs':
continue
- if _local_tag(child) == 'use' and not child.get('data-icon'):
+ if (
+ _local_tag(child) == 'use'
+ and child.get('data-icon') is None
+ ):
replacement = self._materialize_use(child, stack)
parent.remove(child)
parent.insert(index, replacement)
@@ -484,33 +487,36 @@ def _import_embed_icons():
def _build_replacement_g(
use_elem: ET.Element,
icons_dir: Path,
- fallback_dir: Path | None,
embed_icons_mod,
-) -> ET.Element | None:
+) -> ET.Element:
"""Resolve a single ``<use data-icon="...">`` into an expanded ``<g>``.
- Returns None when the icon name is missing, unresolved, or the icon
- file cannot be parsed. Callers should leave the original ``<use>`` in
- place in that case (matching the on-disk finalize_svg behaviour, which
- also leaves unresolvable placeholders untouched).
+ Invalid or unresolved project-local references are blocking input errors.
"""
use_str = ET.tostring(use_elem, encoding='unicode')
attrs = embed_icons_mod.parse_use_element(use_str)
if 'icon' not in attrs:
- return None
+ raise UseExpansionError('Icon placeholder has no data-icon identifier')
- icon_path, _base_size = embed_icons_mod.resolve_icon_path(
- attrs['icon'], icons_dir, fallback_dir,
- )
+ try:
+ icon_path, _base_size = embed_icons_mod.resolve_icon_path(
+ attrs['icon'], icons_dir,
+ )
+ except ValueError as exc:
+ raise UseExpansionError(str(exc)) from exc
if not icon_path.exists():
- return None
+ raise UseExpansionError(
+ f'Project-local icon is not prepared: {attrs["icon"]}'
+ )
color = attrs.get('fill', '#000000')
elements, style, base_size = embed_icons_mod.extract_paths_from_icon(
icon_path, color,
)
if not elements:
- return None
+ raise UseExpansionError(
+ f'Project-local icon has no renderable geometry: {attrs["icon"]}'
+ )
g_xml = embed_icons_mod.generate_icon_group(attrs, elements, style, base_size)
@@ -519,34 +525,32 @@ def _build_replacement_g(
wrapped = f'<svg xmlns="{SVG_NS}">{g_xml}</svg>'
try:
parsed_root = ET.fromstring(wrapped)
- except ET.ParseError:
- return None
+ except ET.ParseError as exc:
+ raise UseExpansionError(
+ f'Expanded icon is invalid SVG: {attrs["icon"]}'
+ ) from exc
for child in parsed_root:
local = child.tag.split('}')[-1] if '}' in child.tag else child.tag
if local == 'g':
return child
- return None
+ raise UseExpansionError(
+ f'Expanded icon has no group root: {attrs["icon"]}'
+ )
def expand_use_data_icons(
root: ET.Element,
icons_dir: Path,
- fallback_dir: Path | None = None,
) -> int:
"""Replace every ``<use data-icon="...">`` in *root* with its expansion.
Walks the tree, finds use elements that carry a ``data-icon`` attribute,
- builds a new ``<g>`` subtree from the project icon library (falling back to
- the global library when supplied), and swaps it into the parent element at
- the same position.
+ builds a new ``<g>`` subtree from the prepared project icon library, and
+ swaps it into the parent element at the same position.
- Returns the number of placeholders successfully expanded. Unresolvable
- placeholders are left in place so callers can decide whether to warn.
+ Returns the number of placeholders successfully expanded.
"""
- if not icons_dir.exists():
- return 0
-
embed_icons_mod = _import_embed_icons()
# ElementTree elements don't carry a parent reference, so build a map.
@@ -558,17 +562,19 @@ def expand_use_data_icons(
targets: list[ET.Element] = []
for elem in root.iter():
local = elem.tag.split('}')[-1] if '}' in elem.tag else elem.tag
- if local == 'use' and elem.get('data-icon'):
+ if local == 'use' and elem.get('data-icon') is not None:
targets.append(elem)
+ if targets and not icons_dir.is_dir():
+ raise UseExpansionError(
+ f'Project-local icon directory is missing: {icons_dir}'
+ )
expanded = 0
for use_elem in targets:
parent = parent_of.get(use_elem)
if parent is None:
continue
- replacement = _build_replacement_g(use_elem, icons_dir, fallback_dir, embed_icons_mod)
- if replacement is None:
- continue
+ replacement = _build_replacement_g(use_elem, icons_dir, embed_icons_mod)
idx = list(parent).index(use_elem)
parent.remove(use_elem)
parent.insert(idx, replacement)
diff --git a/skills/ppt-master/scripts/template_import/manifest.py b/skills/ppt-master/scripts/template_import/manifest.py
index a3310e80..89d5c346 100644
--- a/skills/ppt-master/scripts/template_import/manifest.py
+++ b/skills/ppt-master/scripts/template_import/manifest.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Internal helper: extract lightweight template assets and style metadata from a PPTX file.
+"""Internal helper: extract template resources and style metadata from a PPTX file.
This helper is intentionally limited in scope:
- extract reusable media assets
@@ -10,8 +10,8 @@ This helper is intentionally limited in scope:
It does NOT try to convert arbitrary PPTX shapes into SVG templates.
Output contract (single source of truth):
- <workspace>/manifest.json — all factual metadata (theme, assets, slides, layouts, masters)
- <workspace>/assets/ — extracted reusable image assets
+ <workspace>/analysis/manifest.json — factual metadata and resource inventory
+ <workspace>/images/ — reusable image assets
This module is a pure library. The CLI entry point lives in
``pptx_template_import.py`` at the scripts root.
@@ -19,10 +19,8 @@ This module is a pure library. The CLI entry point lives in
from __future__ import annotations
-import json
import posixpath
import re
-import shutil
import zipfile
from collections import Counter, defaultdict
from dataclasses import dataclass
@@ -34,6 +32,10 @@ from pptx_to_svg.ooxml_loader import (
blip_embed_relationship_ids,
parse_ooxml_boolean,
)
+from pptx_workspace import (
+ inventory_package_resources,
+ write_workspace_resources,
+)
NS = {
@@ -177,11 +179,6 @@ def emu_to_pixels(value: int) -> int:
return int(round(value / EMU_PER_INCH * 96))
-def sanitize_filename(value: str) -> str:
- value = re.sub(r"[^A-Za-z0-9._-]+", "_", value.strip())
- return value.strip("._") or "asset"
-
-
def part_svg_filename(role: str, seq: int, part_path: str) -> str:
stem = PurePosixPath(part_path).stem
safe_stem = re.sub(r"[^A-Za-z0-9_-]+", "_", stem).strip("_") or role
@@ -560,27 +557,9 @@ def build_manifest(
layout_parent[layout_path] = master_path
layout_parts.append(layout_path)
- asset_dir = output_dir / "assets"
- if asset_dir.exists():
- shutil.rmtree(asset_dir)
- asset_dir.mkdir(parents=True, exist_ok=True)
-
- copied_assets: dict[str, str] = {}
- for info in zf.infolist():
- if not info.filename.startswith("ppt/media/") or info.is_dir():
- continue
- original_name = PurePosixPath(info.filename).name
- safe_name = sanitize_filename(original_name)
- destination = asset_dir / safe_name
- stem = destination.stem
- suffix = destination.suffix
- counter = 2
- while destination.exists():
- destination = asset_dir / f"{stem}_{counter}{suffix}"
- counter += 1
- with zf.open(info.filename) as src, open(destination, "wb") as dst:
- shutil.copyfileobj(src, dst)
- copied_assets[info.filename] = destination.name
+ resource_inventory = inventory_package_resources(zf)
+ write_workspace_resources(output_dir, resource_inventory)
+ copied_assets = resource_inventory.image_name_map()
slide_records: list[SlideRecord] = []
asset_usage: Counter[str] = Counter()
@@ -788,12 +767,13 @@ def build_manifest(
},
"slideSize": slide_size,
"theme": theme_summary,
- "assets": {
- "exportDir": "assets",
- "commonAssets": common_assets,
- "allAssets": sorted(copied_assets.values()),
- "assetMap": copied_assets,
+ "images": {
+ "exportDir": "images",
+ "commonImages": common_assets,
+ "allImages": sorted(copied_assets.values()),
+ "imageMap": copied_assets,
},
+ "resources": resource_inventory.manifest(),
"pageTypeCandidates": dict(sorted(page_type_map.items())),
"layouts": layouts_top,
"masters": masters_top,
diff --git a/skills/ppt-master/scripts/template_import/native_structure.py b/skills/ppt-master/scripts/template_import/native_structure.py
index 0ca85605..1bbe603a 100644
--- a/skills/ppt-master/scripts/template_import/native_structure.py
+++ b/skills/ppt-master/scripts/template_import/native_structure.py
@@ -22,10 +22,12 @@ import shutil
from pathlib import Path
from typing import Any
+from pptx_workspace import NATIVE_STRUCTURE_PATH, SOURCE_PPTX_PATH
+
SCHEMA = "ppt-master.native-structure.v1"
-SOURCE_TEMPLATE_NAME = "source_template.pptx"
-CONTRACT_NAME = "native_structure.json"
+SOURCE_TEMPLATE_NAME = SOURCE_PPTX_PATH.as_posix()
+CONTRACT_NAME = NATIVE_STRUCTURE_PATH.as_posix()
def _sha256(path: Path) -> str:
@@ -39,6 +41,7 @@ def _sha256(path: Path) -> str:
def _copy_source_template(source: Path, destination: Path) -> None:
if source.resolve() == destination.resolve():
return
+ destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
@@ -152,6 +155,7 @@ def build_native_structure(
for slide in slides:
slide_contracts.append({
"index": slide["index"],
+ "packagePart": slide.get("slidePath"),
"pageType": slide.get("pageType"),
"layoutKey": layout_key_by_path.get(slide.get("layoutPath")),
"masterKey": master_key_by_path.get(slide.get("masterPath")),
@@ -194,7 +198,9 @@ def write_native_structure_bundle(
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(
+ contract_path = output_dir / CONTRACT_NAME
+ contract_path.parent.mkdir(parents=True, exist_ok=True)
+ contract_path.write_text(
json.dumps(contract, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
diff --git a/skills/ppt-master/scripts/template_preview_pptx.py b/skills/ppt-master/scripts/template_preview_pptx.py
index 8587bae3..ef02288a 100644
--- a/skills/ppt-master/scripts/template_preview_pptx.py
+++ b/skills/ppt-master/scripts/template_preview_pptx.py
@@ -11,7 +11,6 @@ Usage:
Examples:
python3 scripts/template_preview_pptx.py projects/my_template
python3 scripts/template_preview_pptx.py templates/decks/my_template -o review.pptx
- python3 scripts/template_preview_pptx.py templates/decks/legacy --visual-only
Dependencies:
python-pptx
@@ -146,12 +145,8 @@ def _review_svg_sources(
def _partition_svg_prototypes(
svg_files: list[Path],
- *,
- visual_only: bool,
) -> tuple[list[Path], list[Path]]:
"""Separate public pages from canonical definition-only Layout SVGs."""
- if visual_only:
- return svg_files, []
public_files: list[Path] = []
definition_files: list[Path] = []
for path in svg_files:
@@ -221,33 +216,34 @@ def _resolve_workspace(path: Path) -> tuple[Path, Path]:
candidate = path.expanduser().resolve()
if _roster_spec(candidate / "templates") is not None:
return candidate, candidate / "templates"
-
- if _roster_spec(candidate) is not None:
- if candidate.name == "templates" and (candidate.parent / "exports").is_dir():
- return candidate.parent, candidate
- return candidate, candidate
-
raise ValueError(
- "template workspace must contain templates/design_spec.md, "
- "templates/design_spec.<layout|deck>.<id>.md, or a legacy flat "
- "design_spec.md"
+ "template workspace root must contain templates/design_spec.md or "
+ "templates/design_spec.<layout|deck>.<id>.md"
)
-def _template_id(spec_path: Path, workspace: Path) -> str:
- """Read a portable template id, falling back to the workspace directory name."""
+def _template_id(spec_path: Path) -> str:
+ """Read the required portable template id."""
text = spec_path.read_text(encoding="utf-8")
match = _FRONTMATTER_ID_RE.search(text)
- raw = match.group(1).strip().strip("'\"") if match else workspace.name
+ if match is None:
+ raise ValueError(
+ f"{spec_path.name} frontmatter must declare layout_id or deck_id"
+ )
+ raw = match.group(1).strip().strip("'\"")
safe = _FILENAME_UNSAFE_RE.sub("_", raw).strip(" ._")
return safe or "template"
def _replication_mode(spec_path: Path) -> str:
- """Read the template replication mode, defaulting legacy packages to standard."""
+ """Read the required template replication mode."""
text = spec_path.read_text(encoding="utf-8")
match = _REPLICATION_MODE_RE.search(text)
- return match.group(1) if match else "standard"
+ if match is None:
+ raise ValueError(
+ f"{spec_path.name} frontmatter must declare replication_mode"
+ )
+ return match.group(1)
def _canvas_viewbox(spec_path: Path) -> str | None:
@@ -388,10 +384,7 @@ def build_parser() -> argparse.ArgumentParser:
)
parser.add_argument(
"template_workspace",
- help=(
- "Workspace containing templates/design_spec.md; legacy flat template "
- "directories are also accepted."
- ),
+ help="Workspace root containing templates/design_spec.md.",
)
parser.add_argument(
"-o",
@@ -406,14 +399,6 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true",
help="Replace an existing review PPTX after an intentional re-export.",
)
- parser.add_argument(
- "--visual-only",
- action="store_true",
- help=(
- "Export a legacy SVG roster as slide-local DrawingML for visual review. "
- "This does not validate or claim a reusable Master/Layout contract."
- ),
- )
return parser
@@ -429,7 +414,6 @@ def main(argv: list[str] | None = None) -> int:
raise ValueError(f"template directory has no SVG prototypes: {template_dir}")
svg_files, layout_definition_files = _partition_svg_prototypes(
all_svg_files,
- visual_only=args.visual_only,
)
if not svg_files:
raise ValueError(
@@ -438,16 +422,14 @@ def main(argv: list[str] | None = None) -> int:
)
spec_path = _roster_spec(template_dir)
- template_id = _template_id(spec_path, workspace)
+ template_id = _template_id(spec_path)
replication_mode = _replication_mode(spec_path)
locked_canvas = _canvas_viewbox(spec_path)
- if locked_canvas is None and not args.visual_only:
+ if locked_canvas is None:
raise ValueError(
"design_spec.md frontmatter must declare canvas_viewbox"
)
- use_full_placeholder_frames = (
- not args.visual_only and replication_mode != "mirror"
- )
+ use_full_placeholder_frames = replication_mode != "mirror"
output_path = (
Path(args.output).expanduser().resolve()
if args.output
@@ -460,9 +442,7 @@ def main(argv: list[str] | None = None) -> int:
f"output already exists: {output_path}; use --force to replace it"
)
output_path.parent.mkdir(parents=True, exist_ok=True)
- text_style: MasterTextStyleSpec | None = None
- if not args.visual_only:
- text_style, title_px, body_px = _master_text_style(all_svg_files)
+ text_style, title_px, body_px = _master_text_style(all_svg_files)
print("PPT Master - Template Preview PPTX Exporter")
print(f" Workspace: {workspace}")
@@ -473,9 +453,7 @@ def main(argv: list[str] | None = None) -> int:
" Definition-only Layout prototypes: "
f"{len(layout_definition_files)}"
)
- if args.visual_only:
- print(" Review mode: visual-only legacy compatibility")
- elif replication_mode == "mirror":
+ if replication_mode == "mirror":
print(" Review placeholder frames: preserved source Slide geometry")
else:
print(f" Review Master defaults: title {title_px:g}px, body {body_px:g}px")
@@ -490,12 +468,12 @@ def main(argv: list[str] | None = None) -> int:
review_svg_files, review_layout_definition_files = (
_partition_svg_prototypes(
review_all_svg_files,
- visual_only=args.visual_only,
)
)
success = create_pptx_with_native_svg(
svg_files=review_svg_files,
output_path=output_path,
+ resource_root=workspace,
canvas_format=None,
expected_viewbox=locked_canvas,
verbose=True,
@@ -504,7 +482,7 @@ def main(argv: list[str] | None = None) -> int:
animation=None,
image_optimize=False,
native_objects=True,
- pptx_structure="flat" if args.visual_only else "structured",
+ pptx_structure="structured",
use_layout_placeholder_frames=use_full_placeholder_frames,
master_text_style_spec=text_style,
structure_name=template_id,
@@ -526,14 +504,13 @@ def main(argv: list[str] | None = None) -> int:
)
return 1
- label = "Visual-only template preview" if args.visual_only else "Template preview"
placeholder_status = (
f", {placeholder_count} full-frame placeholder(s)"
if use_full_placeholder_frames
else ""
)
print(
- f"[OK] {label} verified: "
+ "[OK] Template preview verified: "
f"{slide_count} slides, {master_count} master(s), "
f"{layout_count} layout(s){placeholder_status}"
)
diff --git a/skills/ppt-master/templates/icons/README.md b/skills/ppt-master/templates/icons/README.md
index d7bb5b71..8d9e47c2 100644
--- a/skills/ppt-master/templates/icons/README.md
+++ b/skills/ppt-master/templates/icons/README.md
@@ -24,7 +24,7 @@ This directory is the **global library**. The active resource owner copies chose
python3 skills/ppt-master/scripts/icon_sync.py <project_path> tabler-outline/home tabler-outline/bulb simple-icons/github
```
-Missing names and a single selection batch that mixes the four stylistic libraries exit non-zero; `simple-icons` may coexist for real brand marks. Once files are under `<project>/icons/`, they form the prepared project asset pool and may be combined freely with user-provided, custom, or imported icons. `finalize_svg.py embed-icons` embeds **project-first**; its per-icon global fallback exists for legacy compatibility, not new asset discovery.
+Missing names and a single selection batch that mixes the four stylistic libraries exit non-zero; `simple-icons` may coexist for real brand marks. Once files are under `<project>/icons/`, they form the prepared project asset pool and may be combined freely with user-provided, custom, or imported icons. `finalize_svg.py embed-icons`, preview, validation, and native export resolve only this project-local pool.
**Custom icons**: drop your own `.svg` into `<project>/icons/<lib>/` (any `<lib>`, e.g. `custom/`) and reference it as `data-icon="<lib>/<name>"` — it embeds like any library icon.
@@ -63,6 +63,11 @@ Use placeholder syntax **during SVG generation**:
`data-icon` is case-sensitive because it resolves a real filename. Bundled library directories and basenames are canonical lowercase: use `tabler-outline/award`, not `tabler-outline/Award`. Custom icons retain the exact case of their files; the resolver intentionally does not lowercase identifiers.
+Every placeholder resolves only against `<project_path>/icons/`. A complete
+`library/name` identifier is mandatory; bare names, abbreviated namespaces,
+paths into `templates/icons/`, and unsynced bundled-library files fail instead
+of falling back to another root.
+
`finalize_svg.py` auto-embeds all placeholders during post-processing. To run manually:
```bash
diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.md
index 72e2a013..c531959c 100644
--- a/skills/ppt-master/workflows/create-template.md
+++ b/skills/ppt-master/workflows/create-template.md
@@ -100,8 +100,8 @@ The rows are evidence channels, not mutually exclusive routes. Run every matchin
| Type | What the user supplied | Tool / read path | Internal strategies supported by the evidence |
|------|-------------------------|------------------|-----------------------------------------------|
-| **A** `.pptx` reference | A `.pptx` file path | `pptx_template_import.py` → `manifest.json` + `native_structure.json` + `source_template.pptx` + layered SVGs + `assets/`; flat verification SVGs are opt-in | `standard` / `fidelity` / `mirror` |
-| **B** Existing SVG assets | `projects/<x>/svg_output/`, a current template workspace root, a legacy flat template root, or a loose `.svg` folder | Normalize the source directory, create an editable authoring IR bundle with `svg_authoring_view.py`, then use its page SVGs; also read companion `design_spec.md` / `spec_lock.md` when present | `standard` / `fidelity`; `mirror` only when the source already carries a complete explicit Master/Layout/placeholder/native-object contract |
+| **A** `.pptx` reference | A `.pptx` file path | `pptx_template_import.py` → `analysis/manifest.json` + `analysis/native_structure.json` + `sources/source.pptx` + layered SVGs + semantic resource directories; flat verification SVGs are opt-in | `standard` / `fidelity` / `mirror` |
+| **B** Existing SVG assets | `projects/<x>/svg_output/`, a current template workspace root, or a loose `.svg` folder | Normalize the source directory, create an editable authoring IR bundle with `svg_authoring_view.py`, then use its page SVGs; also read companion `design_spec.md` / `spec_lock.md` when present | `standard` / `fidelity`; `mirror` only when the source already carries a complete explicit Master/Layout/placeholder/native-object contract |
| **C** Image / visual references | PNG/JPG/WebP images, screenshots, moodboards, PDF page visuals, or a visual-reference folder | `ls` + `Read` each supplied visual or PDF (multimodal recognition) | `standard` only by itself |
| **D** Text / document / website / asset references | Direct conversation text, pasted requirements, Markdown/TXT, DOCX/PDF/HTML/URL, brand/design manuals, or supplied logo/icon/font assets | Use direct text as-is; read plain text/Markdown; convert supported documents/URLs with `source_to_md.py` into a temporary analysis workspace; inventory explicit assets | `standard` only by itself |
| **E** No reference material | A template request with no external source and no substantive brief yet | Skip analysis; collect every required value in Steps 2–3 | `standard` only |
@@ -122,9 +122,9 @@ below are Create Layout/Create Deck concerns.
| Preserve provenance | Keep facts, explicit user decisions, and AI suggestions distinct. Surface contradictions in Step 2 instead of resolving them silently. |
| Protect mirror | Supplemental text, images, websites, or assets may explain the source but cannot alter a confirmed `mirror` graph or visuals. Use `standard` / `fidelity` when the user wants those inputs to change the resulting system. |
-Type A is the canonical mirror path: `manifest.json`, `native_structure.json`, layered lossless `svg/`, and inheritance facts describe the native structure that still exists in the PPTX package. Optional `svg-flat/` files are complete-page verification views, never structure authority. In `standard` / `fidelity`, imported facts and visuals do not define output topology.
+Type A is the canonical mirror path: `analysis/manifest.json`, `analysis/native_structure.json`, layered lossless `svg/`, and inheritance facts describe the native structure that still exists in the PPTX package. Optional `svg-flat/` files are complete-page verification views, never structure authority. In `standard` / `fidelity`, imported facts and visuals do not define output topology.
-**Type B source normalization**: when the supplied root exposes any `templates/` Design Spec, use `<input>/templates/` as the SVG/spec source and resolve its workspace assets from sibling `<input>/images/` and `<input>/icons/`. Otherwise, use the supplied directory itself as the legacy-flat/loose SVG source. Directory flatness is not a semantic-structure signal.
+**Type B source normalization**: when the supplied root exposes any `templates/` Design Spec, use `<input>/templates/` as the SVG/spec source and resolve its workspace assets from sibling `<input>/images/` and `<input>/icons/`. Otherwise, treat the supplied directory only as a loose SVG evidence source. Directory flatness is not a semantic-structure signal and never makes it a reusable workspace.
Type B is supported with caveats:
@@ -145,11 +145,12 @@ 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 (including source-owned inherited-shape visibility), page-type candidates
-- `native_structure.json` — analysis contract: stable master/layout keys, layout picker names, placeholder type/index/geometry, inherited-shape visibility, source hash, and source-graph quality facts
-- `source_template.pptx` — byte-preserved analysis copy for visual/package cross-checking; it is not copied into the final template package
-- `assets/` — extracted reusable image assets; `manifest.json` owns the asset-name mapping and SVG `href` values reuse that mapping
-- `conversion-report.json` — source-recovery and fidelity diagnostics; retain it for audit because these warnings are not duplicated in the structural manifests
+- `analysis/manifest.json` — source facts: slide size, theme colors, fonts, per-master theme summaries, resource inventory, placeholder metadata, SVG file paths, per-slide / per-layout / per-master metadata (including source-owned inherited-shape visibility), and page-type candidates
+- `analysis/native_structure.json` — stable Master/Layout keys, picker names, placeholder type/index/geometry, inherited-shape visibility, source hash, and source-graph quality facts
+- `sources/source.pptx` — byte-preserved backing package for visual/package cross-checking and exact unchanged-source recovery; it is not copied into the final template package
+- `images/` — PowerPoint image media, including raster images and SVG/EMF/WMF; `analysis/manifest.json` owns the asset-name mapping and SVG `href` values reuse it
+- `sounds/`, `audio/`, `video/`, and `native-payloads/` — conditional semantic resource directories; only populated directories are created
+- `validation/conversion-report.json` — source-recovery and fidelity diagnostics; retain it for audit because these warnings are not duplicated in the structural manifests
- `svg/` — **primary view** (layered template view):
- `svg/master_*.svg` — every slide master in the deck rendered once, including masters that no sample slide currently uses (template packages routinely ship more masters than the visible samples reference)
- `svg/layout_*.svg` — every slide layout in the deck rendered once (its own contribution; master shapes do **not** repeat here)
@@ -157,12 +158,12 @@ This produces, in one workspace:
- `svg/inheritance.json` — which Layout/Master each Slide consumes plus source-owned `showInheritedShapes` / `showMasterShapes` booleans; Layout shapes follow the Slide's `showInheritedShapes`, while Master shapes require that value and the referenced Layout's `showMasterShapes`; backgrounds remain independent
- `svg-flat/` — **optional verification view** (only with `--inheritance-mode both`; one self-contained SVG per slide):
- `svg-flat/slide_NN.svg` — effective Master/Layout contributions permitted by the source visibility flags plus Slide-local content, painted into one SVG so opening any slide on its own shows the full page like PowerPoint would. Background inheritance remains independent. Use this for previews / screenshot pipelines / "what does the slide actually look like" sanity checks.
-- The default `--inheritance-mode layered` emits only the canonical layered view. Pass `both` when a separate complete-page verification tree is worth the storage cost, or `flat` for round-trip use cases (legacy: `svg/` becomes self-contained slides without the master/layout/inheritance files).
-- The importer does not generate a duplicate narrative summary or persistent SVG-size CSV. Read compact facts from `manifest.json`; run ad hoc size measurements outside the canonical workspace when needed.
+- The default `--inheritance-mode layered` emits only the canonical layered view. Pass `both` when a separate complete-page verification tree is worth the storage cost, or `flat` when a projection-only self-contained `svg/` tree without master/layout/inheritance files is explicitly required. Imported-deck round-trip uses the separate `authoring-svg-flat/` contract.
+- The importer does not generate a duplicate narrative summary or persistent SVG-size CSV. Read compact facts from `analysis/manifest.json`; run ad hoc size measurements outside the canonical workspace when needed.
Import fidelity rules:
-- Placeholder metadata is recorded in `manifest.json`; master / layout SVGs show lightweight dashed guides with labels only in `svg/`, not in `svg-flat/`.
+- Placeholder metadata is recorded in `analysis/manifest.json`; master / layout SVGs show lightweight dashed guides with labels only in `svg/`, not in `svg-flat/`.
- Charts, SmartArt, diagrams, and OLE objects are typed placeholders in `svg/`. In `svg-flat/`, they use a preview image with a small badge when one exists; otherwise they stay visible as placeholders. Tables are converted to real SVG.
- Missing media and external linked images fail the import. EMF / WMF Office vector media are converted to PNG previews when supported by the local toolchain; otherwise the import fails.
@@ -261,25 +262,25 @@ does not turn those vectors into a picture.
| Mode | Required read set |
|---|---|
-| `standard` / `fidelity` | `manifest.json`, exported assets, `svg/inheritance.json`, `authoring-svg/authoring_summary.json`, and every cleaned layered IR document (`authoring-svg/master_*.svg` / `layout_*.svg` / `slide_NN.svg`). Do not read `authoring_manifest.json`; it is compiler-only. The layered IR is the complete read surface: it covers Layouts unused by any sample slide (invisible in `svg-flat/` yet still template vocabulary), and per-page composition follows from `inheritance.json`. Cleaned flat pages are optional composition spot checks, not a required second pass over the same shapes. Source topology remains non-binding; the two modes differ in output design (`fidelity` designs a broader roster covering the useful visual range), not in read coverage. |
-| `mirror` | `manifest.json`, `native_structure.json`, `svg/inheritance.json`, `authoring-svg/authoring_summary.json`, and every cleaned layered Master/Layout/Slide IR document. Do not read `authoring_manifest.json`; `mirror_template_materialize.py` loads and validates it internally. The layered `authoring-svg/` tree is the sole editable and materialization input. Cleaned `authoring-svg-flat/` slides are optional visual composition checks only; never edit or feed them into template materialization. Materialization may resolve unchanged refs against the matching lossless backing without placing opaque payload in model context. |
+| `standard` / `fidelity` | `analysis/manifest.json`, exported semantic resources, `svg/inheritance.json`, `authoring-svg/authoring_summary.json`, and every cleaned layered IR document (`authoring-svg/master_*.svg` / `layout_*.svg` / `slide_NN.svg`). Do not read `authoring_manifest.json`; it is compiler-only. The layered IR is the complete read surface: it covers Layouts unused by any sample slide (invisible in `svg-flat/` yet still template vocabulary), and per-page composition follows from `inheritance.json`. Cleaned flat pages are optional composition spot checks, not a required second pass over the same shapes. Source topology remains non-binding; the two modes differ in output design (`fidelity` designs a broader roster covering the useful visual range), not in read coverage. |
+| `mirror` | `analysis/manifest.json`, `analysis/native_structure.json`, `svg/inheritance.json`, `authoring-svg/authoring_summary.json`, and every cleaned layered Master/Layout/Slide IR document. Do not read `authoring_manifest.json`; `mirror_template_materialize.py` loads and validates it internally. The layered `authoring-svg/` tree is the sole editable and materialization input. Cleaned `authoring-svg-flat/` slides are optional visual composition checks only; never edit or feed them into template materialization. Materialization may resolve unchanged refs against the matching lossless backing without placing opaque payload in model context. |
-Use the compact facts in `manifest.json` for orientation. Use screenshots or the original PPTX only for visual cross-checking. Do not bulk-read opaque lossless payload into model context.
+Use the compact facts in `analysis/manifest.json` for orientation. Use screenshots or the original PPTX only for visual cross-checking. Do not bulk-read opaque lossless payload into model context.
Interpretation rule (carries forward into Steps 2 and 4):
-- `manifest.json` is the source of truth for facts about the source deck: slide size, theme colors, fonts, background inheritance, reusable asset inventory, declared source layout/master structure, and slide reuse relationships. It dictates which source facts mirror may preserve during materialization, but not `standard` / `fidelity` output topology.
+- `analysis/manifest.json` is the source of truth for facts about the source deck: slide size, theme colors, fonts, background inheritance, reusable resource inventory, declared source layout/master structure, and slide reuse relationships. It dictates which source facts mirror may preserve during materialization, but not `standard` / `fidelity` output topology.
- `authoring_summary.json` is the model-facing index for the current authoring SVG roster and readability statistics. Regenerate it after direct IR edits before analysis.
- `authoring_manifest.json` is machine-only provenance. Do not open or quote it in model context; the mirror compiler validates it internally against the edited IR and immutable backing.
-- `native_structure.json` is the source of truth for source PowerPoint identity: stable layout keys, picker names, parent masters, placeholder types/indices, and the source-package hash. Mirror preserves those facts one-to-one. `standard` / `fidelity` do not mine them into the new structure.
-- `manifest.json`, `native_structure.json`, and `svg/inheritance.json` intentionally overlap only at contract boundaries so materialization can cross-check source identity, graph ownership, and visibility; do not collapse them into a cache or substitute one for another
-- exported `assets/` are the canonical reusable image pool — `<image>` references in `svg/` already point at these files directly
+- `analysis/native_structure.json` is the source of truth for source PowerPoint identity: stable layout keys, picker names, parent masters, placeholder types/indices, and the source-package hash. Mirror preserves those facts one-to-one. `standard` / `fidelity` do not mine them into the new structure.
+- `analysis/manifest.json`, `analysis/native_structure.json`, and `svg/inheritance.json` intentionally overlap only at contract boundaries so materialization can cross-check source identity, graph ownership, and visibility; do not collapse them into a cache or substitute one for another
+- exported `images/` are the canonical reusable image pool — `<image>` references in `svg/` already point at these files directly; SVG/EMF/WMF image media stay in this pool rather than moving to a generic asset directory
- exported `icons/imported/*.svg` files are the canonical reusable vector illustration pool, but they are **not** part of the default read set. Use `authoring_summary.json` `icon_refs` and the cleaned SVGs first. Query `*_vector_asset_inventory.json` by an exact asset id only when source-ref or fingerprint detail is required; do not load the complete inventory into model context. Open a specific imported SVG only when that asset affects the current design decision.
- cleaned layered authoring SVGs are the mirror editing and verification surface; they expose source ownership without requiring the model to read opaque payload. Do not use them to promote, demote, merge, or split source structure.
- cleaned complete-page IR documents are optional composition spot checks for authored modes and verification views for mirror. They never replace the layered editable IR or immutable payload backing.
- screenshots remain useful for judging composition and style, but should not override extracted factual metadata unless the import result is clearly incomplete
-**Mirror complete-graph gate**: compare every `native_structure.json` Layout
+**Mirror complete-graph gate**: compare every `analysis/native_structure.json` Layout
and Master with the layered `authoring_summary.json` roster before offering `mirror`.
Every source Layout—including one unused by all source slides—must have a
layered IR document and matching payload backing from which a reusable
@@ -301,14 +302,14 @@ page order/count, page mappings, canvas, and native structure.
| Norm area | Extract from | Record as |
|---|---|---|
-| Canvas / page geometry | `manifest.json` slide size, SVG `width` / `height` / `viewBox` | `[fact]` canvas format, pixel dimensions, source `viewBox`, and aspect ratio |
+| Canvas / page geometry | `analysis/manifest.json` slide size, SVG `width` / `height` / `viewBox` | `[fact]` canvas format, pixel dimensions, source `viewBox`, and aspect ratio |
| Identity system | theme colors, font usage, logo / emblem assets, recurring backgrounds | `[fact]` when imported; `[suggested]` only for visual estimates |
| Layout grammar | masters / layouts, repeated chrome, margins, columns, card grids, section dividers | Template-specific rules, not generic spacing boilerplate |
| Image system | image crops/clips, scrim/overlay treatments, baked-alpha treatments, full-bleed zones, hero-image placement, mosaic rules, captions | Template-specific image-placement rules with source examples |
| 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` plus inheritance facts | Mirror maps the validated source graph one-to-one into a new workspace. Standard/fidelity author an independent output graph and do not distill source common structure. |
+| Native PowerPoint structure | `analysis/native_structure.json` plus inheritance facts | Mirror maps the validated source graph one-to-one into a new workspace. Standard/fidelity author an independent output graph and do not distill source common structure. |
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.
@@ -319,7 +320,7 @@ Distinguish observed facts from template rules: "`slide_07` uses a left photo cr
Do not treat authoring IR documents as final template assets. `standard` / `fidelity` author new SVGs from the confirmed brief and IR references. Mirror edits the IR and materializes it with lossless native-payload backing.
-> **Mirror-mode materialization path** — use `native_structure.json` and `svg/inheritance.json` as model-readable structural authority. The cleaned layered IR is the editable source, `authoring_summary.json` is its model-facing index, and lossless layered SVGs are immutable payload backing; optional flat SVGs are verification-only. `mirror_template_materialize.py` consumes the machine manifest internally. Preserve only the roster, appearance, ownership, placeholders, converter-supported native metadata, and available SVG fallbacks that are actually present and validated; do not synthesize missing facts or a different graph.
+> **Mirror-mode materialization path** — use `analysis/native_structure.json` and `svg/inheritance.json` as model-readable structural authority. The cleaned layered IR is the editable source, `authoring_summary.json` is its model-facing index, and lossless layered SVGs are immutable payload backing; optional flat SVGs are verification-only. `mirror_template_materialize.py` consumes the machine manifest internally. Preserve only the roster, appearance, ownership, placeholders, converter-supported native metadata, and available SVG fallbacks that are actually present and validated; do not synthesize missing facts or a different graph.
### 1B. Existing SVG assets
@@ -395,7 +396,7 @@ Skip the analysis. Step 2 will list every Required item as `[decision]`; nothing
Compose one concise natural-language proposal that states the template the AI intends to create, **labelling each material value's provenance**:
-- **`[fact]`** — independently traceable external authority or machine-observable source metadata (e.g. theme color from `manifest.json`, image dimensions, or an identified official manual); a user-authored brief file is not a fact merely because it is a file
+- **`[fact]`** — independently traceable external authority or machine-observable source metadata (e.g. theme color from `analysis/manifest.json`, image dimensions, or an identified official manual); a user-authored brief file is not a fact merely because it is a file
- **`[suggested]`** — AI-inferred from analysis or context (e.g. tone summary, applicable scenarios; visually estimated values from type C)
- **`[decision]`** — an explicit user-authored instruction, including exact values supplied in conversation, pasted text, or a user-written brief file (e.g. a template name, a preservation requirement, a palette, or a layout rule)
- **`[derived]`** — an internal execution value the AI derives from the request and evidence so tools can run deterministically; it is recorded for provenance but never presented as a choice the user must understand
@@ -425,7 +426,7 @@ Items to surface:
| Output scope | Yes | `[decision]` — `library` (default, globally reusable and indexed) or `project` (qualified Design Spec under one initialized shared project root) |
| Target project | Yes for `project`; N/A for `library` | `[decision]` — explicit path to the initialized target workspace; validate it during the Step 4 preflight |
| New template ID | Yes | `[decision]` when supplied; otherwise propose a filesystem-safe ASCII slug as `[suggested]`. In library scope it also becomes the matching index key |
-| Template display name | Yes | `[decision]` when supplied; otherwise `[suggested]`, often from `manifest.json.source.name` for type A |
+| Template display name | Yes | `[decision]` when supplied; otherwise `[suggested]`, often from `analysis/manifest.json.source.name` for type A |
| Category | Create Layout/Create Deck only | `[decision]` when explicit; otherwise `[derived]` for indexing — Create Deck: `brand` / `general` / `scenario` / `government` / `special`; Create Layout: `general` / `scenario` / `government` / `special` |
| Applicable scenarios | Yes | Create Brand: identity use cases. Create Style: broad best-fit discovery context only, without binding a target audience, outcome, or recurring application. Create Layout: content shapes and delivery settings its geometry can support, without communication or narrative ownership. Create Deck: recurring presentation situations inside the application contract. `[suggested]` from analysis unless explicitly authored or externally sourced; user confirms. |
| Application context and representative page roles | Create Deck only | `[decision]` when supplied explicitly; otherwise `[suggested]` from recurring source patterns. Describe the source and intended family without assigning required/optional/repeatable status or fixed/replaceable/example-only policy. |
@@ -433,18 +434,18 @@ Items to surface:
| Communication method and evidence discipline | Create Style only | `[decision]` when explicit; otherwise `[suggested]` from repeated source behavior. State argument flow, message/evidence discipline, page-role vocabulary, and data-expression rules without fixing a page sequence. |
| Visual-system defaults | Create Style only | `[decision]` when explicit; otherwise `[suggested]` from evidence. Palette, typography, mode, and visual-style values remain overrideable seeds, never Brand identity truth or direct final Stage-2 locks. |
| Review focus | Create Style only | `[decision]` when explicit; otherwise `[suggested]`. These checks apply only if the user separately enables visual review; the Style cannot trigger that stage. |
-| Theme mode | Create Layout/Create Deck only | A: `[fact]` from `manifest.json` background colors. B: `[fact]` from SVG `fill`. C: `[suggested]` from visual estimate. D: `[fact]` from an independently identified external authority, `[decision]` from user-authored text in any carrier, otherwise `[suggested]`. E: `[decision]`. |
+| Theme mode | Create Layout/Create Deck only | A: `[fact]` from `analysis/manifest.json` background colors. B: `[fact]` from SVG `fill`. C: `[suggested]` from visual estimate. D: `[fact]` from an independently identified external authority, `[decision]` from user-authored text in any carrier, otherwise `[suggested]`. E: `[decision]`. |
| Canvas format and dimensions | Create Layout/Create Deck only | A/B: `[fact]` from slide size or SVG `width` / `height` / `viewBox`; show `canvas_format`, `canvas_width`, `canvas_height`, `canvas_viewbox`, and `source_viewbox`. C: `[suggested]` from image aspect ratio. D: `[fact]` from an independently identified external authority or `[decision]` from user-authored text in any carrier when specified. E: `[decision]`, default `ppt169` (`1280x720`, `0 0 1280 720`). |
| Internal creation strategy | Create Layout/Create Deck only | `[derived]` from the confirmed natural-language plan and evidence. `standard` is the compact authored implementation, `fidelity` requires A/B page evidence for broader source-aligned coverage, and `mirror` requires A or B with a complete explicit structure contract for literal materialization. Create Layout mirror additionally requires a brand-neutral and application-neutral source. Persist `replication_mode` for tools, not as a user-facing mode. |
-| Native structure facts | Create Layout/Create Deck with Type A or structured Type B | `[fact]` from `native_structure.json` / source SVG contract: master/layout counts, parentage, page assignments, placeholder identities, and multi-master status. Mirror preserves these validated facts in the new workspace; authored modes do not use them as output topology. |
+| Native structure facts | Create Layout/Create Deck with Type A or structured Type B | `[fact]` from `analysis/native_structure.json` / source SVG contract: master/layout counts, parentage, page assignments, placeholder identities, and multi-master status. Mirror preserves these validated facts in the new workspace; authored modes do not use them as output topology. |
| Structure ownership plan | Create Layout/Create Deck only | `[derived]` from the requested result. Authored output creates new Master/Layout ownership, including the reusable-family reason for every additional Master; literal preservation maps source ownership without synthesis. Every Master must own at least one emitted Layout and every Layout must have at least one emitted prototype. |
| Reference treatment | Create Layout/Create Deck when a reference exists | `[derived]` per page from the user's prose: closely reproduce geometry/decoration where requested, otherwise adapt the reference into the newly authored system. Literal materialization preserves supported source facts mechanically. |
| Basic template norms | Yes when reference exists | Create Brand uses the identity fields and provenance rules from its child workflow. Create Style uses portable method, page-role, evidence/data, composition/density, visual-default, and image/icon rules while discarding project-specific context. Create Layout/Create Deck use `[fact]` / `[suggested]` layout grammar, image system, density rhythm, page roster semantics, and asset policy from Step 1. |
| Reference source | Optional | already known if Step 1 ran |
| Theme color | Create Brand/Create Deck only | A: `[fact]` from theme XML. B: `[fact]` from dominant SVG `fill`. C: `[suggested]` from visual estimate (HEX is approximate). D: `[fact]` from an independently identified external authority, `[decision]` from user-authored text in any carrier, otherwise `[suggested]`. E: `[decision]`. Create Layout may use neutral preview paint but stores no identity color. |
-| Fonts | Create Brand/Create Deck only | A: `[fact]` from `manifest.json`. B: `[fact]` from SVG `font-family`. C: font family is not derivable — use `[decision]` if the user supplies one. D: `[fact]` from an independently identified external authority or `[decision]` from user-authored text in any carrier. E: `[decision]` when a custom stack is wanted. Create Layout stores no typeface identity or final type scale; its structural text roles, alignment, wrapping, and capacity remain part of page grammar. |
+| Fonts | Create Brand/Create Deck only | A: `[fact]` from `analysis/manifest.json`. B: `[fact]` from SVG `font-family`. C: font family is not derivable — use `[decision]` if the user supplies one. D: `[fact]` from an independently identified external authority or `[decision]` from user-authored text in any carrier. E: `[decision]` when a custom stack is wanted. Create Layout stores no typeface identity or final type scale; its structural text roles, alignment, wrapping, and capacity remain part of page grammar. |
| Design style | Required for Create Style; optional otherwise | `[decision]` when explicit; otherwise `[suggested]` from analysis. For Style this is an overrideable visual-direction seed, not an exact lookup token or identity lock. |
-| Assets list | Optional for Create Brand/Create Layout/Create Deck; N/A for Create Style | A: `[fact]` from `assets/` listing; user picks which to bundle. B/C/D: retain each file's source and let the user confirm adoption. E: none. Style may cite the reference textually but never adopts an asset. |
+| Assets list | Optional for Create Brand/Create Layout/Create Deck; N/A for Create Style | A: `[fact]` from `analysis/manifest.json` plus populated semantic resource directories; user picks which to bundle. B/C/D: retain each file's source and let the user confirm adoption. E: none. Style may cite the reference textually but never adopts an asset. |
| Keywords | Create Style/Create Layout/Create Deck only | `[suggested]` from analysis (3–5 short tags); user confirms. Create Brand has no keywords field or keyword index payload. |
When the bundle includes Type A for Create Layout/Create Deck, also include in this message:
@@ -539,10 +540,10 @@ author replacement contours.
When the bundle includes Type A, pass the following internal package to the role:
- finalized brief from Step 3
-- `manifest.json`
-- `native_structure.json` and `source_template.pptx`
-- `conversion-report.json` when source-recovery diagnostics exist
-- exported `assets/`
+- `analysis/manifest.json`
+- `analysis/native_structure.json` and `sources/source.pptx`
+- `validation/conversion-report.json` when source-recovery diagnostics exist
+- exported `images/` and any other populated semantic resource directories
- `*_vector_asset_inventory.json`, when the vector readability pass extracted assets, as an exact-id query surface only; do not load it or `icons/imported/*.svg` wholesale
- `authoring-svg/authoring_summary.json` and editable layered IR documents; keep `authoring_manifest.json` bundled for compiler use but do not load it into the role context; optional `authoring-svg-flat/` is a visual cross-check only and never a template materialization input
- for `mirror` only, matching immutable `svg/` payload backing plus `svg/inheritance.json`; immutable `svg-flat/` remains an optional visual cross-check
@@ -576,7 +577,8 @@ payload blocks materialization. Before atomic publication, the command verifies
the layered manifest/source refs, lossless SVG/source-PPTX hashes, complete
native/inheritance graph, and vector inventory. It emits source-ordered page
SVGs, unused-Layout definition
-SVGs, `icons/imported/`, referenced `images/` / `templates/assets/`, and one
+SVGs, `icons/imported/`, referenced `images/`, `audio/`, `video/`, or
+`native-payloads/imported/` resources as applicable, and one
deduplicated `templates/native_payloads.json.gz` store when supported native
payload or repeated restoration metadata exists. It also writes
`templates/template_execution_manifest.json` with schema
@@ -625,7 +627,7 @@ re-parenting.
SVG authors own the semantic roster, parentage, picker names, direct atoms, and slots. The exporter owns OOXML part cloning, Theme isolation, relationship registration, and package identity. Do not encode package repair workarounds in individual template SVGs.
-Do not package `native_structure.json` or `source_template.pptx` as template inputs. In `standard` / `fidelity`, author Master/Layout direct semantic atoms and bounded slot groups deliberately from the intended reusable behavior. A validated compact canonical authored-preset `<g>` compiles to one native shape and therefore counts as one semantic atom; it may own a Master/Layout fixed layer or serve as the one direct carrier of an `object` slot. Ordinary groups are not structural atoms or single-object carriers. In `mirror`, edit the layered authoring IR and use inheritance/native facts to preserve source ownership; the lossless trees remain payload backing. Recursively expand fixed Master/Layout group wrappers only because the structured contract requires semantic atoms; preserve transforms, styles, paint order, and appearance, and never flatten or regroup by semantic judgment.
+Do not package `analysis/native_structure.json` or `sources/source.pptx` as template inputs. In `standard` / `fidelity`, author Master/Layout direct semantic atoms and bounded slot groups deliberately from the intended reusable behavior. A validated compact canonical authored-preset `<g>` compiles to one native shape and therefore counts as one semantic atom; it may own a Master/Layout fixed layer or serve as the one direct carrier of an `object` slot. Ordinary groups are not structural atoms or single-object carriers. In `mirror`, edit the layered authoring IR and use inheritance/native facts to preserve source ownership; the lossless trees remain payload backing. Recursively expand fixed Master/Layout group wrappers only because the structured contract requires semantic atoms; preserve transforms, styles, paint order, and appearance, and never flatten or regroup by semantic judgment.
`<design_spec_path> §V` records the newly authored roster for `standard` / `fidelity`. For `mirror`, add the `Source Preservation Map` required by [template-designer.md](../references/template-designer.md), with one row per source slide and its preserved Master/Layout assignment. Do not add a synthesis-decision table.
@@ -650,16 +652,16 @@ Downstream, Strategist inspects the installed workspace and current content, the
**Mirror materialization contract** (type A or B): when the derived implementation writes `replication_mode: mirror`, the Template_Designer role:
1. **Materializes one output SVG per source page** in `<authoring_workspace>/templates/`. Edit and normalize the matching `authoring-svg/` IR document, then run `mirror_template_materialize.py`; the compiler consumes the tool-only authoring manifest together with native structure facts and immutable payload backing. Do not hand-copy or independently rebuild its graph. Preserve the source Master/Layout keys and picker names, Layout parentage, slide assignment, placeholder type/index/bounds, inherited-shape visibility, ownership, paint order, and supported native metadata that are present and validated. Mechanical namespace, root-declaration, asset-path, and fixed-layer group normalization is allowed only when source ownership and appearance remain unchanged.
- - Type A model-facing source: `<import_workspace>/authoring-svg/authoring_summary.json` plus the editable SVGs; `<import_workspace>/svg/`, `svg/inheritance.json`, and `native_structure.json` provide payload and structural backing. The compiler alone reads `<import_workspace>/authoring-svg/authoring_manifest.json`. Optional `<import_workspace>/svg-flat/` is verification-only.
+ - Type A model-facing source: `<import_workspace>/authoring-svg/authoring_summary.json` plus the editable SVGs; `<import_workspace>/svg/`, `svg/inheritance.json`, and `analysis/native_structure.json` provide payload and structural backing. The compiler alone reads `<import_workspace>/authoring-svg/authoring_manifest.json`. Optional `<import_workspace>/svg-flat/` is verification-only.
- Type B model-facing source: `<svg_analysis_workspace>/authoring-svg/authoring_summary.json` plus its editable SVGs; the complete explicit source SVG contract is immutable backing
- For every source Layout unused by all source slides, additionally materialize one definition-only SVG named `layout_<layout_key>.svg` from its layered authoring IR document and payload backing. It carries the exact root identity, fixed atoms, and placeholder contract but is not a generated page assignment. Use source placeholder prompts/carriers; do not invent business content. This definition SVG lets downstream export register the Layout and any otherwise-unused parent Master without retaining an internal carrier slide.
2. **Renames each file** using the source-order-first convention `<NNN>_<page_type>.svg`, where `<NNN>` is the source-order index zero-padded to 3 digits and `<page_type>` is typically `cover` / `toc` / `chapter` / `content` / `ending` (fall back to `content` when the type cannot be confidently classified). Examples: `001_cover.svg`, `002_toc.svg`, `003_content.svg`, ..., `050_ending.svg`.
- - Type A: derive `<page_type>` from `manifest.json.pageTypeCandidates`
+ - Type A: derive `<page_type>` from `analysis/manifest.json.pageTypeCandidates`
- Type B: derive `<page_type>` from the source filename when it follows the PPT Master convention (`01_cover.svg` → `cover`, `03a_content_two_col.svg` → `content`); otherwise infer from page content or fall back to `content`
3. **Routes bundled assets through the common workspace contract** and rewrites every `<image href="...">` consistently. Keep stable source asset identity in mirror; do not rename, merge, or replace assets by semantic judgment.
- - Type A: assets come from `<import_workspace>/assets/`
+ - Type A: image media come from `<import_workspace>/images/`; other resources retain their semantic source directories
- Type B: resolve relative paths in source `<image href="...">` against the source SVG location and copy each unique asset; if the source already follows PPT Master conventions (assets co-located with SVGs in the same directory), copy the whole asset set and then rewrite paths
- - Both scopes: write bitmaps to `<authoring_workspace>/images/`, point SVG references at `../images/<name>`, and keep non-bitmap template-source assets under `<authoring_workspace>/templates/`.
+ - Both scopes: write raster, SVG, EMF, and WMF image media to `<authoring_workspace>/images/`, point SVG references at `../images/<name>`, and route audio, video, or opaque payloads to their semantic workspace directories.
4. **Copies imported vector assets once** to `<authoring_workspace>/icons/imported/` and rewrites their placeholders to `<use data-icon="imported/<name>"/>`. Never place a second copy under `templates/icons/`. Other explicitly adopted icon-library references keep their existing library namespace. Do not inline these assets manually in the template working SVGs; template validation, preview, and final export all resolve icons from the workspace-root `icons/` directory.
5. Writes `<design_spec_path>` per [template-designer.md](../references/template-designer.md) §1. The §V Page Roster remains a factual prototype index; explicit SVG metadata is the native Master/Layout contract. `replication_mode: mirror` records how the workspace was created and only makes literal downstream reuse technically possible; it never selects that behavior or forces a 1:1 slide sequence.
@@ -766,7 +768,7 @@ This checker validates the authoring contract, not the compiled OOXML package. T
- [ ] Model-facing placeholder bounds and transform page coordinates use at most two decimals; normalized crop/viewBox ratios, path geometry, transform scale/rotation coefficients, authored-preset frames, and tool-side native frames retain their required precision
- [ ] 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 exist at their resolved paths. In both scopes, bitmap references resolve through `../images/`; no bitmap remains accidentally stranded in `templates/`
-- [ ] `<design_spec_path>` frontmatter declares `native_structure_mode: structured`; no `native_structure.json` or `source_template.pptx` is packaged
+- [ ] `<design_spec_path>` frontmatter declares `native_structure_mode: structured`; no `analysis/native_structure.json` or `sources/source.pptx` is packaged
- [ ] Every SVG root declares Master/Layout key and picker names; Master/Layout visuals are direct semantic atoms and obey the explicit paint-order contract. Ordinary `<g>` elements remain forbidden there; a validated helper-generated compact canonical preset `<g>` is the sole group exception because it compiles to one native shape. Structural `data-pptx-role` is used only when specialized metadata cannot express required package/page-number/animation behavior
- [ ] Every slot is a direct `<g id>` with explicit design-zone bounds and exactly one compatible direct carrier, or an explicit composite `object` proxy. A validated compact canonical preset `<g>` may be the one carrier of an `object` slot; an ordinary multi-object group may not. Zero-slot Layouts remain valid
- [ ] For `standard` / `fidelity`, every placeholder bound is the complete editable box rather than the current marker text's tight bounds; general body/object carriers begin at the upper-left and only intentional short focal roles remain centered
@@ -836,7 +838,7 @@ Branch on the confirmed output scope:
| `library` | Run the registrar below after Step 5 passes and Step 6 also passes whenever it was requested or required by a multi-Master roster |
| `project` | Skip the registrar entirely. Do not edit any global template index or library README; continue to Step 8 with index status `Not registered (project workspace)` |
-Run the unified registrar with the kind flag; it derives the corresponding index entry from `templates/design_spec.md` (frontmatter when present, prose fallback otherwise) plus the actual `templates/*.svg` file list. The registrar retains read compatibility with old flat library packages; new creation never writes that shape:
+Run the unified registrar with the kind flag; it derives the corresponding index entry from `templates/design_spec.md` (frontmatter when present, prose fallback otherwise) plus the actual `templates/*.svg` file list. The workspace must already use the current nested contract:
```bash
# For brand
@@ -993,11 +995,9 @@ Brand/Layout/Deck copy or consume package-owned `templates/` plus any existing
`images/` and `icons/`; Style consumes only its own spec and ignores sibling
project scaffolding. It then authors new `svg_output/` pages
under the template contract and exports a new PPTX. Neither the reference
-PPTX/SVG nor the template prototypes are upgraded in place. A legacy-flat
-Brand/Layout/Deck package root remains readable only when it satisfies its
-current kind contract; for Layout/Deck that includes the structured SVG
-contract. Style has no legacy-flat form. Otherwise create a new workspace
-through this route.
+PPTX/SVG nor the template prototypes are upgraded in place. Any older flat or
+semantic-legacy package is input evidence only; create a new current workspace
+through this route before it can be selected by Generate.
---
diff --git a/skills/ppt-master/workflows/routing.md b/skills/ppt-master/workflows/routing.md
index 652ca307..b3f1d1e5 100644
--- a/skills/ppt-master/workflows/routing.md
+++ b/skills/ppt-master/workflows/routing.md
@@ -100,7 +100,6 @@ When a PPTX already contains native Master/Layout parts, `create-template` mirro
| Raw PPTX called a template + new content | Fill Native PPTX unless the user explicitly asks for a reusable template workspace |
| Any supported reference bundle or direct-text brief + reusable template request | Create Template |
| Current template workspace root + content | [`generate-pptx`](./generate-pptx.md) Stage-1 template choice |
-| Legacy-flat Brand/Layout/Deck root satisfying its current kind contract; Layout/Deck also require current structured SVGs | [`apply-template-workspace`](./stages/apply-template-workspace.md) compatibility reader; Style has no flat form |
| Semantic-legacy or incomplete structured package | Create a new workspace through Create Template; do not migrate in place |
| Request to add a master directly to an existing PPTX/SVG | Unsupported; explain the Create Template → Generate PPTX lifecycle |
diff --git a/skills/ppt-master/workflows/stages/apply-template-workspace.md b/skills/ppt-master/workflows/stages/apply-template-workspace.md
index dc58be51..48ed4b44 100644
--- a/skills/ppt-master/workflows/stages/apply-template-workspace.md
+++ b/skills/ppt-master/workflows/stages/apply-template-workspace.md
@@ -18,7 +18,6 @@ resolve to one of these current contracts:
| Input shape | Spec and SVG source | Asset source |
|---|---|---|
| Current workspace root | `<root>/templates/design_spec.md`, or one `design_spec.<kind>.<id>.md` per kind, plus `<root>/templates/` | Existing `<root>/images/` and `<root>/icons/` |
-| Compatible legacy-flat Brand/Layout/Deck root | `<root>/design_spec.md`; Layout/Deck also require current-contract SVGs under `<root>/` | Package-local files |
| Current Create Template handoff | Its exact validated library or project workspace root | Existing portable sibling `images/` and `icons/`; already installed only when the root is the target project |
Spec naming and kind declaration follow [`templates/README.md`](../../templates/README.md); a root exposing several kind-qualified specs contributes all of them. Do not accept only another project's inner `templates/` directory because that omits sibling assets.
@@ -45,7 +44,7 @@ duplicate kinds before validation.
**Hard rule — raw source boundary**: A raw PPTX is not a template workspace. Raw PPTX plus new content uses [`template-fill-pptx`](../template-fill-pptx.md). When the user wants reusable SVG/template generation, run [`create-template`](../create-template.md) first; its validated workspace-root handoff becomes a Stage-1 candidate and is preselected only when it is the sole supplied root. Never add Master/Layout/placeholder structure directly to an existing PPTX or SVG project.
-**Compatibility gate**: Reject semantic-legacy or incomplete structured packages, including old baseline/distillation metadata, incomplete Master identity, or legacy direct atomic placeholders. Create a new current workspace through Create Template; use the original PPTX when native topology must be preserved. A legacy-flat Brand/Layout/Deck directory is readable only when it satisfies its current kind contract; Layout/Deck also require a current structured SVG contract. Style has no legacy-flat form.
+**Current-contract gate**: Reject flat-root, semantic-legacy, or incomplete structured packages, including old baseline/distillation metadata, incomplete Master identity, or legacy direct atomic placeholders. Create a new current workspace through Create Template; use the original PPTX when native topology must be preserved.
## 2. Read the Matching Schema
@@ -69,8 +68,7 @@ roster, and a shadowed Deck still validates its declared contract:
python3 skills/ppt-master/scripts/svg_quality_checker.py "<workspace_root>/templates" --template-mode
```
-Any error blocks installation. A compatible legacy-flat root uses its own root
-as the checker target.
+Any error blocks installation.
## 3. Structured Preflight
@@ -86,8 +84,8 @@ Before copying a Deck or Layout workspace, inspect every SVG root and slot. Bran
Validate each normalized root once. Resolve the effective structural owner as
Layout when selected, otherwise Deck; install only its SVG/non-bitmap
-structural payload, but install every selected spec. A library or
-compatible legacy-flat root contributes one bare `design_spec.md`; install it
+structural payload, but install every selected spec. A library root contributes
+one bare `templates/design_spec.md`; install it
as `design_spec.<kind>.<id>.md`, where `<id>` comes from the matching
frontmatter id field. A current project root may contribute several qualified
specs; preserve each validated qualified filename. Never merge spec bodies,
@@ -96,7 +94,7 @@ and never copy one multi-kind root's shared SVG or asset pool once per kind.
| Installed file | Meaning |
|---|---|
| `templates/design_spec.<kind>.<id>.md` | A template contribution installed into or authored in this project |
-| `templates/design_spec.md` | Library or compatible legacy-flat source shape only; never valid beside qualified project specs |
+| `templates/design_spec.md` | Library source shape only; never valid beside qualified project specs |
For every copied spec, prepend exactly one provenance line under its H1, then
leave the rest of the document untouched. An in-place root is not rewritten:
@@ -125,8 +123,6 @@ After that root-level copy, kinds have these downstream effects:
| `layout` | Expose the actual reusable structure and take structural precedence over Deck; Default Strategist later inspects these prototypes, while Quick's current agent uses them for immediate flat authoring decisions in active context. |
| `deck` | Expose descriptive application context and identity. It also supplies structure and the actual prototype roster only when no Layout is selected. |
-For a compatible legacy-flat package, route SVG/spec/non-bitmaps to project `templates/`, bitmaps to project `images/`, and declared icons to project `icons/`. Do not infer legacy Master/Layout semantics from the flat directory shape.
-
**Atomic install preflight**:
1. Resolve every source and destination path.