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(pptx-layouts): distill completed pages into reusable Layouts
hugohe303b3c0218327
diff --git a/docs/technical-design.md b/docs/technical-design.mdindex 181573c1..e3695aa6 100644--- a/docs/technical-design.md+++ b/docs/technical-design.md@@ -41,6 +41,8 @@ User Input (PDF/DOCX/XLSX/PPTX/URL/Markdown/topic text)↓[Visual self-check (optional, opt-in)] → visual-review workflow (only when the user explicitly requests it)↓+[Reusable Layout distillation (baseline: explicit selection; template: mandatory deferred finalization)] → distill-layouts workflow+ ↓[Post-processing] → total_md_split.py (split notes) → finalize_svg.py → svg_to_pptx.py↓Output:@@ -62,7 +64,7 @@ Output:For every workflow that authors or redesigns visual slides through SVG, `svg_output/` is the complete page-design authority. Every visible text, image, shape, diagram, chart/table fallback, background, and template-derived layout element that should appear on a slide must already exist in that page SVG or be explicitly referenced by it. Templates, `design_spec.md`, and `spec_lock.md` guide SVG authoring; the exporter does not use them as a second visual layer that fills in missing page content.-Minimal semantic markers do not weaken that closure. Existing Layout/Layer/Placeholder/Native metadata remains authoritative. New baseline/free-design pages declare their locked `data-pptx-layout` key/name and explicit reusable structure; only legacy baseline pages without a `pptx_layouts` mapping use root `data-pptx-page-role` instead of filename-only family inference. `data-pptx-role` is reserved for the few structural page-frame objects whose package or animation behavior is not already expressed by specialized metadata. Ordinary titles, body text, cards, KPIs, diagrams, charts, icons, and images are not duplicated into a metadata ontology.+Minimal semantic markers do not weaken that closure. Existing Layout/Layer/Placeholder/Native metadata remains authoritative. Baseline/free-design pages stay unmapped while their visual design is being created and may use root `data-pptx-page-role` for compatibility routing. Deferred template pages carry the selected `page_layouts` prototype but do not finalize `pptx_layouts` or root kind during design. After the complete pages exist, `distill-layouts` writes the all-page output contract: explicit baseline selections plus utility mappings, or strict/adaptive template reconciliation for every page. `data-pptx-role` is reserved for the few structural page-frame objects whose package or animation behavior is not already expressed by specialized metadata.| Domain | Authority ||---|---|@@ -452,19 +454,21 @@ These direct routes share some analysis primitives with the main pipeline, espec**Why there is only one PPTX export route.** Native export reads `svg_output/` and translates supported SVG elements into DrawingML shapes. 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 run, but it is a self-contained visual-preview artifact rather than a PPTX source; users may insert it as an SVG picture, while PowerPoint's manual Convert to Shape command remains outside the supported contract.-**Why baseline has explicit and compatibility routes instead of visual inference.** `svg_to_pptx.py` starts from the actual blank slide-layout relationship in the base package and defaults to `--pptx-structure baseline`. New free-design and brand-only projects write one `pptx_layouts` key/name per page and repeat the matching explicit Master/Layout/placeholder contract in every SVG. The exporter deterministically compiles those declarations: pages with the same reusable contract share one Layout, genuinely different compositions get different Layouts, and concrete content stays on the Slide. A legacy project whose whole mapping section is absent keeps the older compatibility pass: strict-majority background/chrome promotion plus coarse `data-pptx-page-role` families, with filename/id fallbacks. Neither route clusters pages by visual similarity.+**Why baseline has explicit and compatibility routes instead of visual inference.** `svg_to_pptx.py` starts from the actual blank slide-layout relationship in the base package and defaults to `--pptx-structure baseline`. Free-design and brand-only projects initially omit `pptx_layouts`, so the visual pass is not constrained by precomputed compositions and the compatibility route keeps actual content Slide-local. When the user explicitly selects completed pages, `distill-layouts` atomically writes one mapping row for every page: selected pages use `distilled` Layouts and unselected pages share an empty `utility` Layout. The exporter deterministically compiles those declarations but never selects or clusters pages itself. Existing unmapped projects keep the compatibility pass: strict-majority background/chrome promotion plus coarse `data-pptx-page-role` families, with filename/id fallbacks.++**Why reusable layouts require explicit SVG metadata.** Post-design distilled baseline and template routes use the same compiler. Final mapped SVGs declare a Layout key/name/kind at the root, mark only direct children as Master/Layout layers, and attach typed placeholder semantics to Slide-local prototypes. Export validates that shared Master and same-key Layout declarations are structurally identical, then emits real Layout parts and `p:ph` references. In every new distilled contract, including template-based output, the Layout owns the reusable placeholder. Atomic carriers keep matching Slide bindings for rendering fidelity; a final distilled composite object region remains an ordinary visible group and receives one hidden transparent binding proxy. Template mode additionally compares the output with `page_layouts`: strict requires matching key/name, Master/Layout ids/topology/geometry, and placeholder bounds; adaptive requires matching Master structure, and an evolved Layout receives a new key/name rather than mutating an existing identity. Non-mirror paint and typography remain project-controlled; mirror preserves Master and Slide-local non-text visuals plus referenced asset identity, allowing only visible text replacement unless adaptive assigns a genuinely evolved Layout identity. Mirror compares referenced definitions and applicable embedded-style rules through each layer's dependency closure, so private resources of a new adaptive Layout do not falsely count as Slide-local drift. Package read-back verifies exact Slide/Layout/Master shape rosters and order, exact background ownership/payload, physical part and content-type rosters, carrier/proxy roles, placeholder identities, and default bounds. Legacy immediate-template contracts retain Slide binding.-**Why reusable layouts require explicit SVG metadata.** Structured baseline and `--pptx-structure template` use the same compiler. Final slide SVGs declare a Layout key/name at the root, mark only direct root children as Master/Layout layers, and attach typed placeholder semantics to slide-local prototypes. Export validates that shared Master and same-key Layout declarations are structurally and visually identical, then emits real Layout parts and `p:ph` references while leaving every unmarked object Slide-local. Template mode additionally binds this output contract to a selected input template; baseline has `pptx_layouts` without `page_layouts`. This is deterministic structure compilation, not visual-template inference.+**Why reusable bounds are design zones, not measured text boxes.** Every distilled placeholder carries explicit `data-pptx-placeholder-bounds` for the Layout's default semantic region. The value comes from the intended safe area, column, panel inset, or picture frame—not glyph width, line count, or the current content's tight box. The current Slide retains its own authored geometry, so 4:6, 3:7, and 5:5 instances may share one Layout when they express the same semantic composition. Text length therefore cannot accidentally split or mutate the reusable Layout contract.-**Why explicit-Layout text defaults are split between Master and Layout.** Structured baseline and template export write the locked `typography.title` size to every Master `p:titleStyle` level and the locked `typography.body` size to every `p:bodyStyle` / `p:otherStyle` level. Each generated Layout text placeholder additionally copies its prototype's first direct run size into `a:lstStyle/a:lvl1pPr/a:defRPr@sz` while retaining the prompt's direct size. This preserves Layout-specific scale when level-one placeholder text is inserted or reset; direct runs on generated Slides remain unchanged. Missing title/body locks fail explicit Layout export, while legacy baseline, `preserve`, and `flat` retain their previous behavior.+**Why explicit-Layout text defaults are split between Master and Layout.** Structured baseline and template export write the locked `typography.title` size to every Master `p:titleStyle` level and the locked `typography.body` size to every `p:bodyStyle` / `p:otherStyle` level. Each generated Layout text placeholder additionally copies its prototype's first direct run size into `a:lstStyle/a:lvl1pPr/a:defRPr@sz` while retaining the prompt's direct size. This preserves Layout-specific scale when level-one placeholder text is inserted or reset; direct runs on generated Slides remain unchanged. Missing title/body locks fail explicit Layout export, while unmapped baseline, `preserve`, and `flat` retain their previous behavior.-**Why explicit Layout output is read back before publication.** Metadata preflight can prove the authoring contract but cannot prove that package serialization preserved every relationship and registration. Structured baseline and template mode therefore reopen the temporary PPTX and validate the Slide → Layout → Master graph, Layout identity, placeholder type/effective index, reusable frame, and prompt/level-one sizes. Only a package that passes is moved to the requested output; legacy baseline, `preserve`, and `flat` skip this gate.+**Why explicit Layout output is read back before publication.** Metadata preflight can prove the authoring contract but cannot prove that package serialization preserved every relationship and registration. Structured baseline and template mode therefore reopen the temporary PPTX and validate the Slide → Layout → Master graph, exact physical part/content-type rosters, Layout identity, placeholder type/effective index, reusable frame, prompt/level-one sizes, and the exact top-level shape roster/order captured before packaging. Background validation compares the zero-or-one payload of every Slide/Layout/Master part against the pre-promotion expectation, including the untouched base Master background when no authored replacement exists. Distilled output additionally proves that atomic carriers own their expected binding while composite carriers remain ordinary and use hidden transparent proxies. Only a package that passes is moved to the requested output; unmapped baseline, `preserve`, and `flat` skip this gate.-**Why reusable templates rebuild explicit SVG structure.** `pptx_template_import.py` emits layered Master/Layout/Slide references plus source structure facts. `create-template` uses those inputs to rebuild one clean Master and semantic Layouts as complete, explicitly annotated SVG pages; it does not package the original PPTX. Strict use keeps the selected Layout contract, while adaptive use may create a new Layout under the same Master. Both export through deterministic `template` mode. Legacy `preserve` remains readable for existing projects only. Raw PPTX plus one-off generated content still routes to `template-fill-pptx`.+**Why reusable templates rebuild explicit SVG structure.** `pptx_template_import.py` emits layered Master/Layout/Slide references plus source structure facts. `create-template` uses them to rebuild one clean Master and semantic Layouts as complete annotated SVG pages, including at least one page for every retained source Layout (mirror records unused Layouts instead of changing its source-slide count). A source-to-output consolidation table in the template `design_spec.md` makes every retained, merged, or unused Layout auditable. The workflow does not package the original PPTX. Downstream `page_layouts` selects these complete prototypes; only after final SVG construction does strict restore the structural contract or adaptive distill a new Layout under matching Master structure. Legacy `preserve` remains readable for existing projects only. Raw PPTX plus one-off generated content still routes to `template-fill-pptx`.-**Why project-scoped thin templates are an output policy, not another structure mode.** `create-template` keeps `library` as its default indexed output and may instead write the same validated contract directly into an initialized project's `templates/` root. Project bitmaps go to `images/`, extracted icons keep a package copy plus a runtime copy, and no global index is touched. Main-pipeline Step 3 detects that the source and target template roots are identical and consumes the bundle in place. Both scopes still compile through `template + adaptive` or `template + strict`; the exporter has no project-local branch.+**Why project-scoped thin templates are an output policy, not another structure mode.** `create-template` keeps `library` as its default indexed output and may instead write the same validated contract directly into an initialized project's `templates/` root. Project bitmaps go to `images/`, extracted icons keep a package copy plus a runtime copy, and no global index is touched. Main-pipeline Step 3 detects that the source and target template roots are identical and consumes the bundle in place. Both scopes use the same template state machine; a bounds-missing strict legacy prototype takes the immediate compatibility branch, while distillation-capable strict/adaptive projects defer output structure. The exporter has no project-local branch.-**Why each template SVG stays complete while still compiling to a Layout.** A generated SVG is a complete standalone preview, so it repeats inherited Master/Layout visuals together with its selectable Slide content. `page_layouts` names the input reference and `pptx_layouts` names the output Layout; both exist for every template page. Strict keeps the selected contract, while adaptive may lock a new Layout key under the same Master. Export removes repeated inherited copies and emits real Master/Layout parts, leaving actual content on the Slide.+**Why each template SVG stays complete while still compiling to a Layout.** A template SVG is a complete standalone prototype, so it repeats inherited Master/Layout visuals together with selectable Slide content. During generation, `page_layouts` names that input and the output page remains visually complete; `pptx_layouts` is intentionally absent. Post-design distillation then writes the output mapping for every page. Strict copies prototype structure/bounds; adaptive may finalize a new Layout under matching Master structure. Export removes repeated inherited copies and emits real Master/Layout parts, leaving actual content on the Slide.**Why native-object reconstruction uses markers, not automatic object replacement.** The standalone `pptx_to_svg.py` importer emits visible SVG fallback plus `data-pptx-native` metadata only for validated table/chart subsets. Table import covers exact physical row/grid topology, canonical rectangular merges with empty slaves, safe solid/no-fill per-side borders, plain multi-paragraph cells, and a closed run-rich paragraph form. A rich paragraph contains non-empty `runs`; every run requires `text` and may use only `bold`, `italic`, `underline`, `strike`, `color`, `font_size`, one `font_family`, `lang`, and `alt_lang`. Unknown source presentation-only run XML normalizes into that schema, while relationship-bearing text, extensions, line breaks, fields, tabs, bullets, malformed text topology, noncanonical merges, unsafe borders, and non-solid fills remain fallback-only. The normalized fallback for table style `{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}` resolves `wholeTbl`, `firstRow`, horizontal banding, theme colors/fonts, and direct overrides; this is not a full built-in/custom style registry.diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.mdindex 86c9b550..a981e92a 100644--- a/docs/zh/technical-design.md+++ b/docs/zh/technical-design.md@@ -41,6 +41,8 @@↓[视觉自检(可选,opt-in)] → visual-review 工作流(仅在用户明确请求时触发)↓+[可复用 Layout 提炼(baseline 需明确选页;template 为强制后置定稿)] → distill-layouts 工作流+ ↓[后处理] → total_md_split.py(拆分讲稿)→ finalize_svg.py → svg_to_pptx.py↓输出:@@ -61,7 +63,7 @@凡是通过 SVG 创作或重新设计页面的工作流,`svg_output/` 都是完整的页面设计权威。最终幻灯片中应出现的文字、图片、形状、图示、图表 / 表格 fallback、背景和模板派生布局元素,都必须已经存在于对应页面 SVG 中,或被它明确引用。模板、`design_spec.md` 和 `spec_lock.md` 负责指导 SVG 创作;导出器不能把它们当成第二层画面来源,在导出阶段补入 SVG 缺失的页面内容。-最小语义标记不会削弱这条闭包。现有 Layout、Layer、Placeholder 与 Native metadata 始终优先。新的 baseline / 自由设计页面会声明锁定的 `data-pptx-layout` key/name 与显式可复用结构;只有没有 `pptx_layouts` mapping 的旧 baseline 页面继续用根节点 `data-pptx-page-role` 取代纯文件名家族判断。`data-pptx-role` 只补充专用 metadata 尚未表达的少量页面框架、package 或动画行为。普通标题、正文、卡片、KPI、图示、图表、图标和图片不会被重复抄入一套 metadata 本体。+最小语义标记不会削弱这条闭包。现有 Layout、Layer、Placeholder 与 Native metadata 始终优先。Baseline / 自由设计页面在视觉创作期间保持 unmapped,可用根节点 `data-pptx-page-role` 做兼容路由。延后蒸馏的模板页在设计阶段携带 `page_layouts` 选中的完整原型,但不提前定稿 `pptx_layouts` 或根节点 kind。完整页面完成后,`distill-layouts` 才写入全页输出合同:baseline 提升用户选中的成品页并补 utility,template 则逐页执行 strict/adaptive 对照。`data-pptx-role` 只补充专用 metadata 尚未表达的少量页面框架、package 或动画行为。| 领域 | 权威来源 ||---|---|@@ -452,19 +454,21 @@ PowerPoint 的 DrawingML 是 SVG 表达力的严格子集。在转换器已实**为什么只有项目转换器产出的 native PPTX。** Native 导出把 `svg_output/` 中受支持的 SVG 元素逐个翻译成 DrawingML 形状;这是唯一受支持的 SVG→PPTX 路线。`svg_final/` 仍由强制后处理生成,但只承担自包含视觉预览和 SVG 图片插入,不会再被封装成另一份 PPTX,也不为 PowerPoint 手工“转换为形状”提供兼容兜底。-**为什么 baseline 分为显式版式与兼容回退,而不做视觉推断。** `svg_to_pptx.py` 默认使用 `--pptx-structure baseline`。新的自由设计与纯品牌项目会为每页写一条 `pptx_layouts` key/name,并在 SVG 中重复匹配的显式 Master/Layout/placeholder 合同。导出器确定性编译这些声明:合同相同的页面复用同一个 Layout,真正不同的构图生成不同 Layout,具体内容始终留在 Slide。只有整个 mapping section 都缺失的旧项目才继续走兼容路径:严格多数背景/chrome 提升,加上粗粒度 `data-pptx-page-role` 家族与文件名/id fallback。两条路径都不根据视觉相似度聚类页面。+**为什么 baseline 分为显式版式与兼容回退,而不做视觉推断。** `svg_to_pptx.py` 默认使用 `--pptx-structure baseline`。自由设计与纯品牌项目起初省略 `pptx_layouts`,因此视觉设计不会被预先计算的构图限制,兼容路线会把实际内容保留在 Slide。用户明确从成品页中选出可复用页面后,`distill-layouts` 才会原子地为每页写入 mapping:选中页使用 `distilled` Layout,未选页共享空的 `utility` Layout。导出器只确定性编译这些声明,绝不自行选页或聚类。已有 unmapped 项目继续走兼容路径:严格多数背景/chrome 提升,加上粗粒度 `data-pptx-page-role` 家族与文件名/id fallback。++**为什么可复用版式必须依赖显式 SVG 元数据。** 成品后提炼的 baseline 与 template 复用同一套编译器。最终 mapped SVG 在根节点声明 Layout key/name/kind,只允许直接子元素标记 Master/Layout layer,并在 Slide-local 原型上附加占位符类型。导出器验证共享 Master 与同 key Layout 声明一致,再生成真实 Layout part 与 `p:ph`。所有新 distilled 合同(包括模板路线)都由 Layout 持有可复用 placeholder;原子 carrier 保留匹配的 Slide 绑定以维持渲染一致,最终 distilled 的复合对象区域则保持可见 group 为普通对象,并增加一个隐藏透明的绑定代理。Template 还会对照 `page_layouts`:strict 要求 key/name、Master/Layout 的 id/topology/geometry 和 placeholder bounds 一致;adaptive 要求 Master 结构一致,演化后的 Layout 必须使用新 key/name,不能偷换旧身份。非 mirror 的颜色与排版仍由项目控制;mirror 保留 Master、Slide-local 非文本视觉与引用资产身份,只有可见文本允许变化,除非 adaptive 确实建立了演化后的新 Layout 身份。Mirror 会按各层实际依赖闭包比较被引用的定义与适用的内嵌样式规则,因此新 adaptive Layout 的私有资源不会被误判为 Slide-local 漂移。包回读会验证 Slide/Layout/Master 的精确 shape roster 与顺序、背景 ownership 与完整 payload、物理 part 与 content-type roster、carrier/代理职责、占位符身份与默认 bounds。旧 immediate-template 合同继续保留 Slide 绑定行为。-**为什么可复用版式必须依赖显式 SVG 元数据。** Structured baseline 与 `--pptx-structure template` 复用同一套编译器。最终 slide SVG 在根节点声明 Layout key/name,只允许根节点的直接子元素标记 Master/Layout layer,并在 slide-local 原型上附加占位符类型。导出器验证共享 Master 与同 key Layout 的声明在结构和视觉上完全一致,再生成真实 Layout part 与 `p:ph` 引用;所有未标记对象仍保持 Slide-local。Template 模式还会把输出合同绑定到已选输入模板;baseline 只有 `pptx_layouts`,没有 `page_layouts`。这是确定性的结构编译,不是根据视觉相似度猜模板。+**为什么可复用 bounds 是设计区域,不是量出来的文本框。** 每个 distilled placeholder 都必须显式携带 `data-pptx-placeholder-bounds`,表示 Layout 的默认语义区域。它来自安全区、分栏、面板内框或图片框,而不是字形宽度、行数或当前内容的紧包围盒。当前 Slide 仍保留自己的实际几何,因此只要语义构图相同,4:6、3:7、5:5 的实例都可以复用同一个 Layout。这样文本长度不会意外拆分或改变可复用合同。-**为什么显式版式把文字默认值分在 Master 与 Layout 两层。** Structured baseline 与 template 导出都会把锁定的 `typography.title` 字号写入 Master `p:titleStyle` 的全部层级,把锁定的 `typography.body` 字号写入 `p:bodyStyle` / `p:otherStyle` 的全部层级。每个生成的 Layout 文字占位符还会把原型首个直接 run 的字号写入 `a:lstStyle/a:lvl1pPr/a:defRPr@sz`,同时保留提示文字的直接字号。这样,一级占位符文字在插入或重置后仍继承版式特定的字号;生成 Slide 上的直接 run 保持不变。缺少 title/body 锁会让显式版式导出失败,旧 baseline、`preserve`、`flat` 则维持原有行为。+**为什么显式版式把文字默认值分在 Master 与 Layout 两层。** Structured baseline 与 template 导出都会把锁定的 `typography.title` 字号写入 Master `p:titleStyle` 的全部层级,把锁定的 `typography.body` 字号写入 `p:bodyStyle` / `p:otherStyle` 的全部层级。每个生成的 Layout 文字占位符还会把原型首个直接 run 的字号写入 `a:lstStyle/a:lvl1pPr/a:defRPr@sz`,同时保留提示文字的直接字号。这样,一级占位符文字在插入或重置后仍继承版式特定的字号;生成 Slide 上的直接 run 保持不变。缺少 title/body 锁会让显式版式导出失败,unmapped baseline、`preserve`、`flat` 则维持原有行为。-**为什么显式 Layout 导出要在发布前回读候选包。** 元数据预检可以证明作者合同成立,却不能证明 package 序列化完整保留了所有 relationship 与注册信息。因此 structured baseline 与 template 模式都会重新打开临时 PPTX,校验 Slide → Layout → Master 关系链、Layout 身份、占位符类型与有效索引、可复用边界,以及提示文字和一级默认字号。只有通过读回校验的候选包才会移动到目标输出;旧 baseline、`preserve`、`flat` 跳过该门禁。+**为什么显式 Layout 导出要在发布前回读候选包。** 元数据预检可以证明作者合同成立,却不能证明 package 序列化完整保留了所有 relationship 与注册信息。因此 structured baseline 与 template 模式都会重新打开临时 PPTX,校验 Slide → Layout → Master 关系链、精确的物理 part/content-type roster、Layout 身份、占位符类型与有效索引、可复用边界、提示文字与一级默认字号,以及封包前捕获的顶层 shape roster/顺序。背景校验会把每个 Slide/Layout/Master part 的零或一个 payload 与提升前期望精确比较;没有作者 Master 背景时,基础 Master 背景也必须原样保留。Distilled 输出还会验证原子 carrier 持有预期绑定、复合 carrier 保持普通对象,并使用隐藏透明代理。只有通过读回校验的候选包才会移动到目标输出;unmapped baseline、`preserve`、`flat` 跳过该门禁。-**为什么可复用模板统一重建显式 SVG 结构。** `pptx_template_import.py` 输出分层的 Master/Layout/Slide 参考和源结构事实;`create-template` 据此重建一个干净 Master 与语义 Layout,并把它们重复标注在可独立预览的完整 SVG 中,不再封装原 PPTX。严格套用保持所选 Layout 契约,自适应使用可在同一 Master 下新建显式 Layout;两者都走确定性的 `template` 导出。`preserve` 只为旧项目保留兼容读取。+**为什么可复用模板统一重建显式 SVG 结构。** `pptx_template_import.py` 输出分层的 Master/Layout/Slide 参考和源结构事实;`create-template` 据此重建一个干净 Master 与语义 Layout,并为每个保留的源 Layout 至少物化一张可独立预览的完整模板页;mirror 为保持源 Slide 数量,会记录未使用 Layout。模板 `design_spec.md` 中的源到输出合并表让保留、合并与未使用项都可审计。主管线用 `page_layouts` 选中完整原型;最终 SVG 完成后,strict 才恢复原型结构合同,adaptive 才在相同 Master 结构下蒸馏新 Layout。`preserve` 只为旧项目保留兼容读取。-**为什么项目本地薄模板只是输出政策,不是另一种结构模式。** `create-template` 仍以写入索引的 `library` 为默认,也可以把同一份已校验合同直接写到已初始化项目的 `templates/` 根目录。项目位图进入 `images/`,抽取图标同时保留 package 副本与运行时副本,且不修改任何全局索引。主管线 Step 3 发现模板源目录与目标根目录相同时原地消费。两种输出范围仍走 `template + adaptive` 或 `template + strict`;导出器没有项目本地分支。+**为什么项目本地薄模板只是输出政策,不是另一种结构模式。** `create-template` 仍以写入索引的 `library` 为默认,也可以把同一份已校验合同直接写到已初始化项目的 `templates/` 根目录。项目位图进入 `images/`,抽取图标同时保留 package 副本与运行时副本,且不修改任何全局索引。主管线 Step 3 发现模板源目录与目标根目录相同时原地消费。两种输出范围使用同一模板状态机:缺少 bounds 的 strict 旧原型走 immediate 兼容分支,具备蒸馏条件的 strict/adaptive 项目延后定稿输出结构。导出器没有项目本地分支。-**为什么模板 SVG 保持完整却仍能编译成版式。** 每张生成 SVG 都是可独立预览的完整 slide,因此会重复携带继承的 Master/Layout 视觉和可选择的 Slide 内容。`page_layouts` 指定输入参考,`pptx_layouts` 指定输出版式,两者在模板路线中逐页齐全。严格模式保持所选契约;自适应模式可在同一 Master 下锁定新 Layout。导出器移除重复继承层并生成真实 Master/Layout,实际内容仍留在 Slide。+**为什么模板 SVG 保持完整却仍能编译成版式。** 每张模板 SVG 都是可独立预览的完整原型,因此会重复携带继承的 Master/Layout 视觉和可选择的 Slide 内容。生成阶段只有 `page_layouts` 指定输入原型,输出页面保持视觉完整,`pptx_layouts` 刻意缺席。成品后蒸馏再为每页写入输出 mapping:strict 复制原型结构与 bounds,adaptive 可在相同 Master 结构下定稿新 Layout。导出器移除重复继承层并生成真实 Master/Layout,实际内容仍留在 Slide。**为什么原生对象重建使用 marker,而不是自动替换对象。** 独立的 `pptx_to_svg.py` 导入器只为已验证的表格 / 图表子集输出可见 SVG fallback 与 `data-pptx-native` 元数据。表格导入覆盖精确的物理行列 topology、slave 为空的规范矩形 merge、安全的 solid/no-fill 逐边 border、纯文本多段落,以及封闭的 run 级富文本段落。富文本段落包含非空 `runs`;每个 run 必须有 `text`,并且只能使用 `bold`、`italic`、`underline`、`strike`、`color`、`font_size`、单一 `font_family`、`lang` 和 `alt_lang`。来源中未建模但只影响表现的 run XML 会归一化到该 schema;带 relationship 的文本、扩展节点、换行、字段、tab、项目符号、破损文本 topology、非规范 merge、不安全 border 与非纯色填充仍保持 fallback-only。表格样式 `{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}` 的规范化 fallback 会解析 `wholeTbl`、`firstRow`、横向带状行、主题颜色 / 字体和直接格式覆盖;这不代表完整 built-in/custom style registry。diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.mdindex 22c48751..c18419ec 100644--- a/skills/ppt-master/SKILL.md+++ b/skills/ppt-master/SKILL.md@@ -11,7 +11,7 @@ description: >> AI-driven multi-format SVG content generation system. Converts source documents into high-quality SVG pages through multi-role collaboration and exports to PPTX.-**Core Pipeline**: `Source Document → Create Project → [Template] → Strategist → [Image_Generator] → Executor Live Preview → Quality Check → Post-processing → Export`+**Core Pipeline**: `Source Document → Create Project → [Template] → Strategist → [Image_Generator] → Executor Live Preview → Quality Check → [Layout Distillation] → Post-processing → Export`### SVG Page-Design Boundary@@ -38,7 +38,7 @@ description: >> 5. **NO SPECULATIVE EXECUTION** — "Pre-preparing" content for subsequent Steps is FORBIDDEN (e.g., writing SVG code during the Strategist phase)> 6. **NO SUB-AGENT SVG GENERATION** — Executor Step 6 SVG generation is context-dependent and MUST be completed by the current main agent end-to-end. Delegating page SVG generation to sub-agents is FORBIDDEN> 7. **SEQUENTIAL PAGE GENERATION ONLY** — In Executor Step 6, after the global design context is confirmed, SVG pages MUST be generated sequentially page by page in one continuous pass. Grouped page batches (for example, 5 pages at a time) are FORBIDDEN-> 8. **SPEC_LOCK RE-READ PER PAGE** — Before generating each SVG page, Executor MUST `read_file <project_path>/spec_lock.md`. All colors / fonts / icons / images MUST come from this file — no values from memory or invented on the fly. Executor MUST also look up the confirmed `pptx_structure.template_adherence` when present, the current page's `page_rhythm` (`anchor` / `dense` / `breathing`), `pptx_layouts` (the native PowerPoint Layout every newly generated page references), `page_layouts` (the input template SVG, only for a deck/layout template route), and `page_charts` (which chart template to adapt, if any). Deck/layout template routes require both Layout mappings for every page: `strict` reuses the selected contract; `adaptive` may create a new explicit contract from the selected reference. Free-design and brand-only baseline routes require `pptx_layouts` but omit `page_layouts`; only legacy projects may omit the output mapping — see executor-base.md §2.1. This rule exists to resist context-compression drift on long decks and to break the uniform "every page is a card grid" default+> 8. **SPEC_LOCK RE-READ PER PAGE** — Before generating each SVG page, Executor MUST `read_file <project_path>/spec_lock.md`. All colors / fonts / icons / images MUST come from this file — no values from memory or invented on the fly. Executor MUST also look up `pptx_structure.template_adherence` when present, the current page's `page_rhythm` (`anchor` / `dense` / `breathing`), `page_layouts` (the input template SVG), `page_charts`, and `pptx_layouts` only after it has been finalized. New baseline and template-distillation routes intentionally omit the output mapping during visual generation; [`distill-layouts`](workflows/distill-layouts.md) writes it only from complete SVG pages. Legacy immediate-template and preserve locks retain pre-authored mappings. This rule exists to resist context-compression drift on long decks and to break the uniform "every page is a card grid" default> 9. **SVG MUST BE HAND-WRITTEN, NOT SCRIPT-GENERATED** — Every SVG page is written by the main agent directly, one page at a time (see rules 6 and 7). Writing or running a Python / Node / shell script that produces the SVG files in batch — looping over pages, templating from data, or emitting them via a generator — is FORBIDDEN, including under "save tokens", "quick draft", or "user is in a hurry" pretexts. The script-generation path was tried on a feature branch and abandoned: cross-page visual consistency depends on per-page authoring with full upstream context, which a generator script cannot reproduce. **Narrow exception**: `preset_shape_svg.py` may print one deterministic stock-shape fragment to stdout after the main agent has selected its semantic role, frame, and paint. It cannot write `svg_output/`, choose layout, batch shapes, or generate a page; the main agent reads the fragment and inserts it through the normal hand-authored page edit> 10. **FOLLOW DETERMINISTIC ROUTING RULES** — Do not add blocking routing questions when this skill defines a route. If the user request violates a route precondition, state the required prerequisite and stop that route instead of asking the user to choose around the rule. Ordinary finite options, stylistic preferences, and recoverable details are surfaced with a recommended value plus alternatives at the next existing confirmation gate.@@ -285,7 +285,7 @@ elsefi```-The same split applies to all three kinds — bitmaps always land in `images/`, the rest in `templates/`. The spec's `kind` field tells Strategist how to read the `templates/` side; downstream code doesn't distinguish. (Template SVGs in `templates/` are reference material only — the rendered pages live in `svg_output/` and reference images via `../images/`.)+The same split applies to all three kinds — bitmaps always land in `images/`, the rest in `templates/`. The spec's `kind` field tells Strategist how to read the `templates/` side; downstream code doesn't distinguish. Template SVGs are not export-time overlays: visible output still lives completely in `svg_output/`. Their complete visuals and explicit Master/Layout/placeholder metadata are nevertheless the authoring prototypes selected by `page_layouts`.When `create-template` used project output scope, its directory is already thetarget project's `templates/` root and its bitmap/icon runtime copies are already@@ -304,7 +304,7 @@ bundle. For cross-project reuse, recreate/promote the design withLegacy template packages may ship `native_structure.json` + `source_template.pptx`; keep the pair together in `<project>/templates/` for backward-compatible `preserve` export. Current `create-template` output does not package this pair: it rebuilds complete, explicitly layered SVG templates instead. During fusion, never mix one legacy contract with another template's source package.-The Strategist confirmation stage decides whether the selected template is used `strict` or `adaptive`. Both use `pptx_structure.mode: template` for current templates and map every page to one reference SVG plus one output PowerPoint layout. `strict` keeps the referenced layout contract unchanged; `adaptive` may create a new layout key while keeping the template Master contract. Legacy `preserve` remains strict-only compatibility behavior.+The Strategist confirmation stage decides whether the selected template is used `strict` or `adaptive`. New projects map every page to one input SVG in `page_layouts` and normally use `pptx_structure.mode: template` plus `layout_strategy: distill`, deferring `pptx_layouts` until the complete SVG pages exist. Before locking, inspect every selected prototype placeholder for explicit bounds. A bounds-missing strict legacy template uses immediate compatibility instead: omit the strategy and prewrite the kindless mapping; adaptive may still distill new design-zone bounds. Deferred strict restores the referenced structural contract; adaptive may distill a new Layout while keeping the template Master ids/topology/geometry. Non-mirror paint and typography follow the project skin rules. Legacy `preserve` remains compatible.#### Multi-path fusion@@ -622,7 +622,7 @@ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live --daemon> Image facts: trust the `analysis/image_analysis.csv` regenerated at the end of Step 5. If `images/` changed since (the user swapped or added files), re-run `python3 ${SKILL_DIR}/scripts/analyze_images.py <project_path>/images` before laying images out — facts are re-derived on use, never a stale store (Step 4 image-facts note).-**Per-page spec_lock re-read (Mandatory)**: before **each** SVG page, `read_file <project_path>/spec_lock.md` and use only its colors / fonts / icons / images, plus the per-page `page_rhythm` / `page_layouts` / `page_charts` lookups and the route-specific `pptx_structure` / `pptx_layouts` native-layout contract. The output Layout contract is absent only on legacy projects that have not yet been normalized; it is mandatory for every newly generated page. Resists context-compression drift on long decks. See executor-base.md §2.1.+**Per-page spec_lock re-read (Mandatory)**: before **each** SVG page, `read_file <project_path>/spec_lock.md` and use only its colors / fonts / icons / images, plus the per-page `page_rhythm` / `page_layouts` / `page_charts` lookups and the route-specific `pptx_structure` contract. Read `pptx_layouts` only when already finalized. New baseline and deferred-template routes omit it during visual construction; legacy immediate-template and preserve routes retain it. Resists context-compression drift on long decks. See executor-base.md §2.1.> ⚠️ **Main-agent only**: SVG generation MUST stay in the current main agent — page design depends on full upstream context. Do NOT delegate to sub-agents.> ⚠️ **Generation rhythm**: generate pages sequentially, one at a time, in the same continuous context. Do NOT batch (e.g., 5 per group).@@ -631,7 +631,11 @@ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live --daemonEach completed SVG MUST be a standalone, complete representation of that slide's visible design. Template SVGs and locked planning artifacts may guide construction, but export must not reach back to them to add visible objects omitted from `svg_output/`. Speaker notes, animation, narration, transitions, and direct native-PPTX workflows remain separately owned artifacts/capabilities. Before drawing a literal stock shape, apply [`native-shape-authoring.md`](references/native-shape-authoring.md): use the stdout-only helper when one PowerPoint preset exactly matches, keep basic SVG primitives for rect/round-rect/ellipse, and keep free SVG for custom semantics. Never infer a preset from contour similarity.-Every newly generated page root MUST declare the locked `data-pptx-layout` and `data-pptx-layout-name`, including free-design/brand-only pages that remain in `baseline` mode. Every mapped page MUST also mark the standard placeholder slots it actually has — `title` / `subtitle` / `body` / `picture` / `slide-number` / `footer` per [`executor-base.md`](references/executor-base.md) §1.2 — and its `data-pptx-layer` marks: the deck-wide background as `master`, this layout key's static framing as `layout`. A mapped page normally ships at least its title placeholder and master-background mark, or its Layout exports as a bare frame with no insertable slots. Do not duplicate that identity with `data-pptx-page-role`; only a legacy baseline project whose whole `pptx_layouts` section is absent uses the canonical page-role marker. Add `data-pptx-role` only to structural page-frame objects whose package, page-number, or animation behavior is not already expressed by `data-pptx-layer`, `data-pptx-placeholder`, or `data-pptx-native`; such an element needs a stable unique `id`. Do not add generic content roles to ordinary titles, body text, cards, KPIs, diagrams, charts, icons, or images. Full contract: [`references/semantic-svg.md`](references/semantic-svg.md).+Deferred template pages MUST start from the complete `page_layouts` SVG, keep all inherited visible objects in `svg_output/`, preserve provisional root key/name and stable direct-child Master/Layout/placeholder ids, and omit `data-pptx-layout-kind` until post-design distillation. Strict keeps the prototype structure unchanged; adaptive keeps its Master ids/topology/geometry while the Layout may evolve. Non-mirror fill/stroke/effects/font sizes still follow `spec_lock`. Preserve and legacy immediate-template pages continue to implement their locked output mapping while generated.++Free-design/brand-only baseline pages MUST remain visually free at this stage: omit explicit Layout/layer/placeholder metadata and do not pre-compute rich Layouts from the page plan. They may use the canonical root `data-pptx-page-role` for compatibility routing. Without committing to any future Layout, keep a likely replaceable atomic title, standalone body frame, or picture in its own top-level one-carrier group when the design permits; keep accents and labels in sibling groups. If the user later selects finished pages for reuse, [`distill-layouts`](workflows/distill-layouts.md) adds the complete root contract, safe direct prototypes, design-zone bounds, and optional shared framing without changing the visible design.++Do not duplicate specialized identity with `data-pptx-role`. Add it only to structural page-frame objects whose package, page-number, or animation behavior is not already expressed by `data-pptx-layer`, `data-pptx-placeholder`, or `data-pptx-native`; such an element needs a stable unique `id`. Do not add generic content roles to ordinary titles, body text, cards, KPIs, diagrams, charts, icons, or images. Full contract: [`references/semantic-svg.md`](references/semantic-svg.md).**First-page gate (Mandatory)** — after the **first** SVG page, before drawing page 2:```bash@@ -649,7 +653,7 @@ python3 ${SKILL_DIR}/scripts/svg_quality_checker.py <project_path>**Logic Construction Phase**: generate speaker notes → `<project_path>/notes/total.md`-**✅ Checkpoint — Confirm all SVGs and notes are fully generated and quality-checked. Proceed directly to Step 7 post-processing**:+**✅ Checkpoint — Confirm all SVGs and notes are fully generated and quality-checked. Run the applicable conditional gates below, then proceed to Step 7**:```markdown## ✅ Executor Phase Complete- [x] Live preview started before the first SVG and kept available at the reported URL@@ -663,6 +667,20 @@ python3 ${SKILL_DIR}/scripts/svg_quality_checker.py <project_path>> **Visual self-check (opt-in)?** If the user explicitly asked for a per-page visual re-pass on the SVGs ("跑一下视觉自检 / 视觉回看", "visual review", "check pages visually", etc.), run the standalone [`visual-review`](workflows/visual-review.md) workflow before Step 7. Do NOT run it by default and do NOT recommend it based on inferred model capability or deck size — trigger is user request only.+> **Reusable Layout distillation**: Run+> [`distill-layouts`](workflows/distill-layouts.md) after the full SVG quality+> gate when either condition holds: the user selected finished baseline pages+> for reuse, or the template lock carries `layout_strategy: distill` while+> `pptx_layouts` is absent. A complete mapping is already finalized and only+> needs normal validation unless the user explicitly requests re-distillation.+> Baseline+> promotes only the user's pages and maps the rest to one empty `utility`+> Layout. Template distillation processes every `page_layouts` prototype:+> strict restores the exact structural contract, adaptive keeps the Master structure and may+> finalize an evolved Layout. Both derive explicit design-zone bounds and keep+> current Slide geometry independent. If invoked after Step 7, rerun Step+> 7.2–7.3 with the same export flags.+---### Step 7: Post-processing & Export@@ -740,19 +758,23 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>> **PPTX structure mode** — native export first reads> `spec_lock.md` `pptx_structure.mode`, then falls back to `baseline` when the> section is absent. An explicit `--pptx-structure` CLI value overrides the-> lock for diagnostics. New free-design and brand-only baseline projects write-> one `pptx_layouts` key/name per page. Every SVG repeats that mapping on its-> root and explicitly marks reusable Master/Layout elements and native-> placeholders. Export uses the same deterministic Layout compiler and-> final-package read-back gate as template mode: pages with the same static-> Layout/placeholder contract reuse one Layout, genuinely different-> compositions use different Layouts, and concrete content remains Slide-local.-> `page_layouts` stays absent because no input template was selected. If any-> baseline page declares a Layout, every page must declare one and match the-> lock; partial or unlocked metadata fails export. The exporter never clusters-> pages by visual similarity.+> lock for diagnostics. Free-design and brand-only baseline projects initially+> omit `pptx_layouts`: the visual pass stays unconstrained and all actual+> content remains Slide-local. When the user explicitly selects completed pages+> for reuse, [`distill-layouts`](workflows/distill-layouts.md) adds+> `layout_strategy: distill` and an atomic all-page mapping. Selected pages use+> `distilled` contracts; unselected pages share one empty `utility` Layout.+> Every mapped SVG repeats its key/name/kind. Every distilled placeholder has+> explicit design-zone bounds, while its current Slide frame may use different+> geometry. Export then uses the same deterministic Layout compiler and+> final-package read-back gate as template mode. `page_layouts` stays absent+> because no input template was selected. Existing structured baseline projects+> remain readable. If any baseline page declares a Layout, every page must+> declare one and match the lock; partial or unlocked metadata fails export.+> The exporter never selects, clusters, or visually infers reusable pages.>-> A legacy baseline project whose whole `pptx_layouts` section is absent keeps+> An unmapped baseline project — either a new free-design deck before+> distillation or a legacy deck — keeps> the real slide master/layout relationship from the base deck and promotes the> strict-majority identical> native slide background into the slide master (every slide must carry an@@ -770,10 +792,10 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>> pages are complete, baseline assigns conservative semantic layout families:> root `data-pptx-page-role` values `cover` / `toc` / `section` / `ending` become> `Cover` / `Agenda` / `Section` / `Closing`, while `content` becomes `Content`.-> Filename tokens remain a compatibility fallback for marker-free legacy SVGs.+> Filename tokens remain a compatibility fallback for marker-free SVGs.> It also> preserves an existing safety `Cover` assignment made while hiding promoted-> Master chrome. This legacy route does not inspect visual similarity or infer+> Master chrome. This unmapped route does not inspect visual similarity or infer> placeholders,> and all actual page content remains slide-local. When every slide in one> family carries the exact same explicit background, that background moves to@@ -820,12 +842,25 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>> select it for newly created templates.> **Explicit reusable Layout export** — deck/layout template routes set-> `spec_lock.md` `pptx_structure.mode: template`. Every SVG root declares-> `data-pptx-layout`, and direct children+> `spec_lock.md` `pptx_structure.mode: template`. Distillation-capable template+> projects and post-design free-layout reuse set `layout_strategy: distill`;+> template planning owns `page_layouts` but defers `pptx_layouts` until every+> complete SVG page exists. A bounds-missing strict legacy prototype instead+> uses the kindless immediate compatibility contract. Every final mapped root+> declares `data-pptx-layout`; distilled roots also declare+> `data-pptx-layout-kind`. Direct children> explicitly declare master/layout layers, an optional Slide background, or> PowerPoint placeholders. This> mode builds named reusable layouts and placeholder mappings. Structured-> baseline uses the same metadata and compiler without an input template.+> baseline uses the same metadata and compiler without an input template. A+> `utility` Layout is the narrow baseline-only exception for unselected pages;+> its page-specific visible design remains entirely Slide-local.+> A distilled placeholder always creates `p:ph` in the reusable Layout. Atomic+> carriers keep matching Slide bindings for rendering fidelity. A final+> distilled composite object region remains an ordinary visible group and gets+> one hidden transparent binding proxy, preventing an empty inherited object+> slot from painting over a page the user already approved visually. Legacy+> immediate/pre-authored contracts keep their historical binding behavior.> Neither route infers from visual similarity. Static master/layout elements> must be> repeated consistently in PowerPoint paint order. Chart/table placeholders@@ -833,10 +868,18 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>> example live in> [`references/shared-standards.md`](references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata).> Raw PPTX templates still route to `template-fill-pptx`; `template` structure-> mode is for explicitly annotated SVG authoring. Both `strict` and `adaptive`-> template use stay on this deterministic route. Adaptive pages may define new-> layout keys, but they repeat the same Master layer and one internally-> consistent Layout/placeholder contract.+> mode is for complete explicitly annotated SVG authoring. Both `strict` and+> `adaptive` stay on this deterministic route. `page_layouts` selects the input+> prototype; the post-design checker requires strict key/name/Master/Layout/+> placeholder structural equality, or adaptive Master-structure equality plus one internally+> consistent evolved Layout/placeholder contract under a new key/name. Adaptive+> may retain a prototype identity only while that Layout contract is unchanged.+> Non-mirror skin remains project-controlled; mirror compares literal Master,+> reused-Layout, and Slide-local non-text visuals plus referenced asset identity,+> and permits only visible text replacement unless adaptive proves a genuinely+> evolved Layout contract under a new identity.+> The exporter never reads a+> template to add missing visible objects.> Structured baseline and template export also install the locked> `typography.title` size into every> Master `titleStyle` level and the locked `typography.body` size into every@@ -845,19 +888,23 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>> newly inserted or reset placeholder keeps that Layout's local size before it> falls back to the Master. Generated slide runs and Layout prompt runs keep> their direct sizes. Missing or invalid locked title/body sizes fail explicit-> Layout export. Legacy baseline, preserve, and flat modes do not apply either+> Layout export. Unmapped baseline, preserve, and flat modes do not apply either> text-default update.> Before publishing the temporary PPTX, structured baseline and template export> reopen the finished> package and verify `Presentation → Master ↔ Layout ← Slide` registration,-> named custom Layout parts and content types, collision-free placeholder-> identities, prototype bounds, and prompt/level-one sizes. This read-back gate-> does not compare later same-Layout slides' local geometry+> named custom Layout parts and content types, named Master/Layout static-object+> rosters, explicit reusable backgrounds, distilled carrier/proxy roles,+> collision-free placeholder identities, reusable default bounds, and prompt/level-one sizes. This read-back gate+> also verifies atomic carrier bindings, ordinary composite carriers, hidden+> transparent composite binding proxies, and that a `utility` Layout has no+> background, shape, or placeholder. It does not+> compare later same-Layout slides' local geometry> or direct text formatting.-> In every new generated deck, `pptx_layouts` contains exactly one locked layout-> key/name per page; reuse a key for a shared structure instead of creating one-> key per content instance. Only a legacy baseline project may omit the whole-> section and use page-role compatibility families.+> In every mapped deck, `pptx_layouts` contains exactly one locked Layout row per+> page; reuse a key for a shared contract instead of creating one key per content+> instance. A free-design baseline deck omits the whole section until explicit+> distillation and may use page-role compatibility families in the meantime.> **Paragraph editability vs line fidelity** — by default, mergeable dy-stacked> text collapses into one editable PowerPoint text frame. Evenly spaced authoreddiff --git a/skills/ppt-master/references/artifact-ownership.md b/skills/ppt-master/references/artifact-ownership.mdindex 51b03d96..b537dbc4 100644--- a/skills/ppt-master/references/artifact-ownership.md+++ b/skills/ppt-master/references/artifact-ownership.md@@ -18,7 +18,7 @@ Global artifact ownership rules for PPT Master projects.| `analysis/<stem>.slide_library.json` | Native PPTX structure facts | Text slots, geometry, native tables, native chart caches, SmartArt nodes/connections | Direct PPTX workflows use as native fill/structure contract || `analysis/image_analysis.csv` | Regenerated image fact view | Measured facts about the current `images/` folder | Re-run `analyze_images.py` before reading image facts after changes || `design_spec.md` | Human design narrative | Explains design intent, outline, rationale, and resource plan | Strategist writes; humans and later roles read for intent |-| `spec_lock.md` | Execution contract | Literal colors, typography, icons, images, page rhythm, templates, and charts | Executor re-reads before every page; values must be used verbatim |+| `spec_lock.md` | Execution contract | Literal colors, typography, icons, images, page rhythm, input template prototypes, charts, and any finalized native Layout mapping | Strategist writes the planning contract; Executor re-reads it before every page; only `distill-layouts` may add/finalize a deferred baseline or template `pptx_layouts` contract || `images/` | Runtime image pool | User, extracted, AI, web, formula, slice, EMF/WMF assets | Step 5 writes here; `analysis/image_analysis.csv` derives from current contents || `icons/` | Project icon inventory | Icons copied by `icon_sync.py` for this project | Executor uses locked project icons; exporter may fall back to global library only as documented || `templates/` | Project template reference | Step 3 imported specs, template SVGs, and non-image assets | Strategist/Executor read only when Step 3 is triggered |@@ -42,6 +42,8 @@ Global artifact ownership rules for PPT Master projects.| Sources read policy | In `sources/`, read content-type files (`.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml`) and judge by content — a `.json` / `.csv` may be core content or just data. Exclude known sidecars: `*.conversion_profile.json` and `*_files/image_manifest.json`. `analysis/` facts (`source_profile.json`, `<stem>.slide_library.json`) are read per Step 4 / direct-PPTX workflow, not in the `sources/` content scan. || PPTX structure | `slide_library.json` owns native geometry, slot facts, and SmartArt layout/relationships for direct PPTX workflows. || Design contract | `design_spec.md` explains; `spec_lock.md` executes. Executor must not infer execution values from prose. |+| Free-design Layout authority | Before distillation, absence of `pptx_layouts` is intentional. After explicit user selection, `spec_lock.md` owns the complete page-to-Layout mapping and `svg_output/` owns the matching root/layer/placeholder/bounds metadata. Do not add a second manifest or infer Layouts during export. |+| Template Layout authority | `page_layouts` owns the per-page input prototype. On a deferred template route, absence of `pptx_layouts` means pending visual construction; after distillation, `spec_lock.md` owns the complete output mapping and `svg_output/` owns the final structure. Templates validate provenance but never add missing visible objects during export. || Image facts | `images/` is live state; `analysis/image_analysis.csv` is a regenerated view, not a durable cache. || SVG source | `svg_output/` is the only author source for generated pages. || Page-design closure | On SVG-authoring routes, every visible exported-slide object exists in the corresponding page SVG or an explicitly referenced visual asset. |diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.mdindex d23f435c..73c5226e 100644--- a/skills/ppt-master/references/executor-base.md+++ b/skills/ppt-master/references/executor-base.md@@ -4,7 +4,7 @@**Hard rule — complete page SVG**: Every visible object intended for the exported slide MUST exist in the final page SVG or be explicitly referenced by it. Templates and `spec_lock.md` guide construction; they are not export-time overlays for missing visible content.-**Hard rule — minimal semantics without semantic loss**: Any page with a locked `pptx_layouts` row — including a new `baseline` / free-design page — declares `data-pptx-layout` and `data-pptx-layout-name` on the root and does not duplicate that identity with `data-pptx-page-role`. Only a legacy baseline project whose whole mapping section is absent uses root `data-pptx-page-role`. Add `data-pptx-role` only to structural page-frame objects whose package, page-number, or animation behavior is not already expressed by layer, placeholder, or native-object metadata; the marked element uses a stable unique `id`. Ordinary page content keeps normal SVG structure without duplicate semantic classification. See [`semantic-svg.md`](./semantic-svg.md).+**Hard rule — minimal semantics without semantic loss**: Any page with a locked `pptx_layouts` row declares `data-pptx-layout` and `data-pptx-layout-name` on the root and does not duplicate that identity with `data-pptx-page-role`. Free-design and brand-only baseline pages normally have no mapping while their visual composition is being authored; keep structure metadata absent until the user explicitly runs [`distill-layouts`](../workflows/distill-layouts.md). Add `data-pptx-role` only to structural page-frame objects whose package, page-number, or animation behavior is not already expressed by layer, placeholder, or native-object metadata; the marked element uses a stable unique `id`. Ordinary page content keeps normal SVG structure without duplicate semantic classification. See [`semantic-svg.md`](./semantic-svg.md).**Hard rule — supported PPTX route**: The only supported generated-PPTX path is `svg_output/` through the project SVG-to-DrawingML converter. Step 7.2 still generates `svg_final/` as a mandatory self-contained visual preview that may be inserted as an SVG picture. Do not treat PowerPoint's manual Convert-to-Shape operation as an authoring target or compatibility requirement.@@ -102,36 +102,42 @@ Before generating each page, output which template is used:### 1.2 PowerPoint Master / Layout Mapping-`page_layouts` selects an SVG design reference and exists only for a deck/layout template route. `pptx_layouts` declares the native PowerPoint Layout produced at export and also applies to newly authored free-design and brand-only baseline routes. The contracts are independent: a baseline deck has `pptx_layouts` without `page_layouts`.+`page_layouts` selects the input SVG prototype and exists only for a deck/layout template route. `pptx_layouts` declares the native PowerPoint Layout produced at export. New baseline and template-distillation routes write the output mapping only after complete SVG pages exist. Legacy immediate-template and preserve routes retain their pre-authored mapping.-`pptx_structure.template_adherence` records the Strategist's confirmed template-use policy. Both `strict` and `adaptive` require one real `page_layouts` reference and one `pptx_layouts` output mapping per page. Strict keeps the referenced Layout contract; adaptive may create a new explicit Layout while retaining the template Master.+`pptx_structure.template_adherence` records the confirmed template-use policy. Both `strict` and `adaptive` require one real `page_layouts` reference per page. With `layout_strategy: distill`, strict restores the referenced contract after design; adaptive may distill a new explicit Layout while retaining the template Master.| `pptx_structure.mode` | Executor behavior ||---|---|-| `baseline` | Free design or brand-only route. Implement every locked `pptx_layouts` row explicitly while keeping the mode `baseline`. Only a legacy lock whose whole mapping section is absent uses root page-role compatibility behavior. |+| `baseline` | Free design or brand-only route. While `pptx_layouts` is absent, author unconstrained Slide visuals and omit explicit Layout/layer/placeholder metadata. When [`distill-layouts`](../workflows/distill-layouts.md) writes a complete mapping, implement that final contract while remaining in baseline mode. || Missing | Legacy compatibility. Use root page role; a new explicit Layout contract also writes `mode: baseline`. |-| `template` | Every generated SVG MUST implement the matching `pptx_layouts` row and the explicit structure contract below. |+| `template` | With `layout_strategy: distill`, generate a complete page from the selected `page_layouts` prototype, preserve its structural provenance, and defer the final `pptx_layouts` mapping until post-design distillation. A legacy template lock without the strategy implements its pre-authored mapping immediately. || `preserve` | Legacy strict-only compatibility. Use the locked source layout key/name and retain marked preview layers for source-package reuse. |-**Hard rule — every mapped page references one Layout**: Whenever `pptx_layouts` contains `P<NN>: <layout_key> | <layout name>` — in `baseline`, `template`, or `preserve` mode — put both values on the root SVG as `data-pptx-layout` and `data-pptx-layout-name`. Do not also add `data-pptx-page-role`. Baseline implements the authored free-design key/name, strict copies the selected template key/name, adaptive uses the new key/name already locked by Strategist, and preserve retains the source identity. Executor must not improvise another mapping.+**Hard rule — every final mapped page references one Layout**: Whenever `pptx_layouts` contains `P<NN>: <layout_key> | <layout name>`, put both values on the root SVG. A distilled row also ends in `| <layout_kind>` and repeats it as `data-pptx-layout-kind`. Baseline accepts `distilled` or `utility`; template distillation accepts only `distilled`. Do not also add `data-pptx-page-role`. Distiller writes post-design identity; Executor must not predict a final adaptive key from the outline.++**Template construction provenance**: While deferred template distillation is pending, copy the selected complete template SVG as the page's visual/structural prototype. Preserve its root key/name provisionally and retain stable direct-child ids plus Master/Layout/placeholder metadata as the design evolves. Do not add `data-pptx-layout-kind` or `pptx_layouts` yet. Strict keeps the structural contract unchanged; adaptive keeps the Master ids/topology/geometry and may evolve the Layout/placeholder contract. Apply the non-mirror skin rules in §1.0. Distillation validates and finalizes these declarations after all visible geometry is complete.++**Free-design carrier hygiene**: While baseline is unmapped, do not add placeholder metadata or default bounds. When the composition permits, keep each likely replaceable atomic title, standalone body frame, or picture in its own top-level one-carrier group, with accents/labels in sibling groups. This satisfies normal grouping while allowing `distill-layouts` to lift the carrier later without dismantling a complex composition; it does not predeclare a Layout or constrain local geometry.**Hard rule — PowerPoint paint order**: Direct visual children appear in this order: Master background, Layout background, optional Slide background, shared Master shapes, same-key Layout shapes, then slide-local content/placeholders. Backgrounds are the special plane beneath all inherited shapes. Repeat the same Master contract on every page and the same Layout contract on every page sharing a key.-**Mandatory — per-page placeholder coverage**: On every mapped page, mark each standard slot the page actually has: the page heading as `title` (one direct `<text>`), a cover tagline as `subtitle`, the page number as `slide-number`, running footer text as `footer`, a hero / content image as `picture`, and a body block already authored as one merged dy-stacked `<text>` as `body`. A page shipping zero placeholders exports a Layout with no insertable slots — valid only when the page genuinely has none of these. Pages sharing one layout key ship the same slot set (see the shared-contract rules below).+**Mandatory — per-page placeholder coverage**: On every template/pre-authored mapped page, mark each standard slot the page actually has. On a `distilled` page, mark only safe direct atomic carriers chosen from the completed design and give every placeholder explicit `data-pptx-placeholder-bounds`. A `utility` page intentionally has zero placeholders. Pages sharing one layout key ship the same placeholder ids/types/indices/default bounds; their Slide-local geometry may differ.++**Mandatory — reusable layer coverage**: Mark only genuinely stable deck-wide background/chrome as `master` and only reusable behind-content framing as `layout`. A placeholder-only distilled Layout is valid; do not manufacture a divider or panel merely to make the Layout non-empty. A `utility` Layout has neither Layout elements nor placeholders.-**Mandatory — master/layout layer coverage**: On every mapped page, mark the deck-wide background and every-page chrome (footer bar, running logo) `data-pptx-layer="master"`, and mark the static framing that defines this layout key's composition (divider band, header rule, zone panels) `data-pptx-layer="layout"`. A mapped page with zero `data-pptx-layer` marks exports a bare Master and an empty Layout — the layer marks, not the slide content, are what give each Layout its visible design.+**Mandatory — Layout identity**: Different keys differ in reusable static framing or placeholder topology/default bounds. Their current text length, image crop, and Slide-local x/y/width/height never define identity. Identical reusable contracts should share one key; the quality checker reports duplicates.-**Mandatory — different keys differ in the Layout layer**: Pages locked to different layout keys must not carry identical Layout-layer contracts, or they compile to duplicate Layouts. Materialize each composition's identity as Layout-layer zone framing — the table backing panel and its header band, the column panels or central divider, the hero image frame — while the zone's labels, data, and imagery stay Slide-local. When no framing genuinely distinguishes two keys, the pages are one composition: use one key.+**Placeholder ownership**: Keep actual title/subtitle/body/picture/chart/table/object/media/date/footer/slide-number content on the Slide and add the matching `data-pptx-placeholder`. In any `distilled` contract, including a deferred template route, the generated Layout owns the reusable placeholder. Atomic carriers retain a matching Slide binding to preserve their approved rendering. A final distilled `object` may instead mark one direct composite `<g>` as a region proxy: that visible group remains ordinary and export creates a hidden transparent matching binding shape. Legacy immediate/pre-authored template contracts retain their historical binding behavior. Do not duplicate placeholder identity with `data-pptx-role`; in particular, `data-pptx-placeholder="slide-number"` already owns page-number field behavior. A reconstructed `title` normally omits `data-pptx-placeholder-idx`; preserve an explicit imported title index when present. Every indexed placeholder on one Layout uses a unique index. Chart/table placeholders require native markers and a later `--native-objects` export; object/media placeholders must each resolve to one top-level DrawingML object unless the final distilled object-region exception applies.-**Placeholder ownership**: Keep actual title/subtitle/body/picture/chart/table/object/media/date/footer/slide-number content on the Slide and add the matching `data-pptx-placeholder`. Do not duplicate placeholder identity with `data-pptx-role`; in particular, `data-pptx-placeholder="slide-number"` already owns page-number field behavior. A reconstructed `title` normally omits `data-pptx-placeholder-idx`; preserve an explicit imported title index when present. Every indexed placeholder on one Layout uses a unique index. Chart/table placeholders require native markers and a later `--native-objects` export; object/media placeholders must each resolve to one top-level DrawingML object.+**Atomic placeholder carrier exception**: A normal title/subtitle/body/date/footer/slide-number placeholder is one direct `<text>`; picture/media is one direct `<image>` or imported crop `<svg>`; object is one direct supported atomic object. These direct carriers are the narrow exception to the mandatory top-level `<g>` rule and do not count against the 3–8 content-group budget. The post-design distiller has one additional final-state exception: a direct completed `<g>` may be marked `object` with explicit design-zone bounds when the reusable slot is the whole composition region. It is a Layout-only proxy, not a promise to replace the group in-place, and is forbidden in a reusable template prototype, pending template page, utility page, or legacy immediate contract. The separately specified chart/table native-marker group remains its own specialized contract. Any other complex `<g>` composition stays Slide-local without placeholder metadata.-**Atomic placeholder carrier exception**: A normal title/subtitle/body/date/footer/slide-number placeholder is one direct `<text>`; picture/media is one direct `<image>` or imported crop `<svg>`; object is one direct supported atomic object. These direct carriers are the narrow exception to the mandatory top-level `<g>` rule and do not count against the 3–8 content-group budget. Do not wrap multiple drawing atoms in an arbitrary `<g>` and promise that the composite is one placeholder. The separately specified chart/table native-marker group remains its own specialized contract. Any other complex `<g>` composition stays Slide-local without placeholder metadata.+**Layout-content boundary**: Mark only genuinely reusable static framing as `data-pptx-layer="master|layout"`. Never promote concrete titles, body copy, metrics, chart marks, images, or complex page-specific groups into a Layout. The exporter never infers or clusters. [`distill-layouts`](../workflows/distill-layouts.md) finalizes user-selected baseline pages or every deferred template page before export.-**Layout-content boundary**: Mark only genuinely reusable static framing as `data-pptx-layer="master|layout"`. Never promote concrete titles, body copy, metrics, chart marks, images, or complex page-specific groups into a Layout. Do not infer Layout families from visual similarity or cluster completed pages after the fact; implement the exact authored mapping and reuse a key only when its static Layout layer plus placeholder contract is the same.+**Adaptive Layout creation**: Start from the selected complete template SVG, keep every Master element and stable id identical, and evolve only the Layout/placeholder contract needed by the completed composition. Do not finalize the new key or default bounds until post-design distillation. An unchanged reusable contract must keep the prototype key/name; changing only its label is not a new Layout. Pages sharing the final key repeat the same static Layout elements and placeholder ids/types/default bounds.-**Adaptive Layout creation**: Start from the selected template SVG, keep every Master element identical, and change only the Layout layer/placeholder contract needed for the new composition. Pages sharing the new key repeat the same static Layout elements and placeholder ids/types in the same order.+**Deferred template Layout creation**: Keep `page_layouts` as the immutable input-prototype mapping. After every complete page exists, run [`distill-layouts`](../workflows/distill-layouts.md). Strict restores the prototype key/name, Master/Layout ids/topology/geometry, and explicit placeholder bounds. Adaptive validates the Master structure and may finalize a new Layout from the completed design. Project skin remains governed by §1.0. Every template page becomes `distilled`; none becomes `utility`.-**Authored baseline Layout creation**: Build the locked Layout contract directly from the §IX page composition, without selecting or inventing a `page_layouts` template reference. Pages sharing the baseline key repeat the same static Layout elements and placeholder ids/types/bounds in the same order; differing reusable compositions use differing locked keys.+**Distilled baseline Layout creation**: Do not derive a native Layout key from §IX before free-design SVG generation. After the user selects completed pages, follow [`distill-layouts`](../workflows/distill-layouts.md): keep visible geometry unchanged, derive default placeholder bounds from design zones rather than text ink, map unselected pages to one empty utility Layout, and write the complete final lock atomically.**Legacy preserve identity**: In `preserve` mode only, copy source `data-pptx-placeholder-idx` values and retain the source placeholder type/index pairing. Master/Layout preview elements keep `data-pptx-layer` plus `data-pptx-editable="false"`.@@ -201,7 +207,7 @@ Before drawing each page, look up its entry in `page_rhythm` (key format `P<NN>`Before drawing each page, look up its entry in `page_layouts` to decide which basename to inherit (the SVG itself was loaded in §1.0):- Entry present (e.g., `P04: 03a_content_image_text`) → inherit the corresponding SVG already in context. The basename **must match** an actual file in the chosen template directory. If it does not, stop before drawing and report the invalid mapping; neither `strict` nor `adaptive` may fall back to free design inside a template deck.-- No entry for this page with `template_adherence: strict|adaptive` → stop before drawing and report the missing Strategist mapping. Adaptive mode still selects the closest template SVG as its visual/structural reference; flexibility applies to the new output Layout, not to whether a template reference exists.+- No entry for this page with `template_adherence: strict|adaptive` → stop before drawing and report the missing Strategist mapping. Adaptive mode still requires one selected complete template SVG; flexibility applies to the post-design output Layout, not to whether an input prototype exists.- Whole section absent with `pptx_structure.mode: template` → stop before drawing; the current template contract is incomplete.- Whole section absent only in a legacy project without the current template contract → see §1 fallback (legacy page-type matching).@@ -209,20 +215,33 @@ Do **not** invent a layout entry, and do **not** assume a template just because**Per-page PowerPoint layout lookup — `pptx_layouts` section**:-- `pptx_structure.mode: baseline` with a `pptx_layouts` section → a `P<NN>` row is mandatory; apply §1.2 to the root and direct children while keeping the deck in baseline mode. Do not read or create `page_layouts`.-- `pptx_structure.mode: template` or `preserve` → a `P<NN>` row is mandatory; apply §1.2 to the root and direct children. Preserve mode uses the exact source key/name and placeholder indices.-- `pptx_structure.mode: baseline` or missing with the whole `pptx_layouts` section absent → legacy compatibility only. Omit explicit PPTX layer/layout/placeholder metadata, keep the root page role and necessary structural hints, and let baseline export use conservative promotion plus page-role-backed Layout families. Filenames and ids are fallbacks only when the corresponding marker is absent.+- `pptx_structure.mode: baseline` with `layout_strategy: distill` → post-design distillation is complete; a `P<NN>` row and matching root key/name/kind are mandatory. Do not read or create `page_layouts`.+- `pptx_structure.mode: baseline` with `pptx_layouts` but no `layout_strategy` → existing structured-baseline compatibility. A key/name row and matching root metadata are mandatory; do not invent a kind segment.+- `pptx_structure.mode: template` with `layout_strategy: distill` and no `pptx_layouts` → normal template visual construction. Use `page_layouts`, preserve provisional root key/name plus structural provenance, omit root kind, and do not export yet.+- `pptx_structure.mode: template` with `layout_strategy: distill` and complete `pptx_layouts` → post-design distillation is complete; every row/root ends in `distilled` and must pass the selected-prototype comparison.+- `pptx_structure.mode: template` without `layout_strategy`, or `preserve` → legacy immediate/pre-authored behavior; a `P<NN>` row is mandatory. Preserve uses the exact source key/name and placeholder indices.+- `pptx_structure.mode: baseline` with the whole `pptx_layouts` section absent → normal free-design visual construction or undistilled compatibility export. Omit explicit PPTX Layout/layer/placeholder metadata; a root page role may guide conservative compatibility families without constraining composition.- A layout key may repeat across non-adjacent pages. Reuse is based on identical static/placeholder contracts, not page proximity or content wording.-**Page scaffold — author every mapped page in this document order.** One shape resolves the direct-child rule, the paint order, and the grouping exception at first write:+**Distilled-page scaffold — use only after `distill-layouts`.** It applies to selected baseline pages and every deferred template page. Legacy immediate-template, preserve, and kindless structured-baseline pages do not add `data-pptx-layout-kind` by imitation.```xml-<svg viewBox="…" data-pptx-layout="<key>" data-pptx-layout-name="<name>">+<svg viewBox="…" data-pptx-layout="<key>" data-pptx-layout-name="<name>"+ data-pptx-layout-kind="distilled"><rect id="master-bg" data-pptx-layer="master" …/> <!-- deck background --><g id="footer-chrome" data-pptx-layer="master" …>…</g> <!-- every-page chrome --><g id="zone-framing" data-pptx-layer="layout" …>…</g> <!-- this key's framing -->- <text id="page-title" data-pptx-placeholder="title" …>…</text> <!-- direct child, never inside a <g> -->- <text id="page-number" data-pptx-placeholder="slide-number" …>…</text>+ <text id="page-title" data-pptx-placeholder="title"+ data-pptx-placeholder-bounds="60 36 1160 64" …>…</text>+ <text id="main-body" data-pptx-placeholder="body"+ data-pptx-placeholder-idx="1"+ data-pptx-placeholder-bounds="60 120 470 500" …>…</text>+ <image id="hero-image" data-pptx-placeholder="picture"+ data-pptx-placeholder-idx="2"+ data-pptx-placeholder-bounds="570 120 650 500" …/>+ <text id="page-number" data-pptx-placeholder="slide-number"+ data-pptx-placeholder-idx="3"+ data-pptx-placeholder-bounds="1170 670 50 24" …>…</text><g id="content-block-1">…</g> <!-- 3–8 content groups --><g id="content-block-2">…</g></svg>@@ -243,7 +262,7 @@ Before drawing each page, look up its entry in `page_charts` to decide which cha## 3. Execution Guidelines- **Proximity**: group related elements with tight spacing; separate unrelated groups-- **Element grouping (Mandatory)**: wrap every logical content unit — title, core-message line, each content block, card, list item, diagram, and footer chrome — in a top-level `<g id="...">` with a descriptive id. This is a hard requirement per [`shared-standards.md`](shared-standards.md) §4.3, not an optional convenience: aim for 3–8 content groups per slide (chrome excluded), because ungrouped top-level `<text>` / `<rect>` / `<path>` loses real PowerPoint groups and per-element animation anchors, and degrades select/move/edit. The narrow exception is one direct atomic carrier with `data-pptx-placeholder` under §1.2: it stays ungrouped so the native placeholder binding remains valid and is excluded from the group budget. This exception never authorizes an arbitrary composite `<g>` placeholder; complex grouped content remains Slide-local. Authored native preset fragments (`preset_shape_svg.py`) already are one atomic `<g id>` each and count as one group; keep their labels in a sibling parent `<g>`.+- **Element grouping (Mandatory)**: wrap every logical content unit — title, core-message line, each content block, card, list item, diagram, and footer chrome — in a top-level `<g id="...">` with a descriptive id. This is a hard requirement per [`shared-standards.md`](shared-standards.md) §4.3, not an optional convenience: aim for 3–8 content groups per slide (chrome excluded), because ungrouped top-level `<text>` / `<rect>` / `<path>` loses real PowerPoint groups and per-element animation anchors, and degrades select/move/edit. The narrow exception is one direct atomic carrier with `data-pptx-placeholder` under §1.2: it stays ungrouped so one native object can supply the Layout prototype or pre-authored Slide binding, and it is excluded from the group budget. Only the post-design distiller may additionally mark one completed top-level group as a final `distilled` object-region proxy; authoring-time template and legacy routes cannot imitate it. Authored native preset fragments (`preset_shape_svg.py`) already are one atomic `<g id>` each and count as one group; keep their labels in a sibling parent `<g>`.- **Spec adherence**: follow color, layout, canvas format, and typography in the spec- **Template structure**: if templates exist, inherit the visual framework- **Main-agent ownership**: SVG generation must run in the main agent (not sub-agents) — pages share upstream context for cross-page visual continuitydiff --git a/skills/ppt-master/references/semantic-svg.md b/skills/ppt-master/references/semantic-svg.mdindex 0bd34d2c..41ce36ec 100644--- a/skills/ppt-master/references/semantic-svg.md+++ b/skills/ppt-master/references/semantic-svg.md@@ -8,7 +8,7 @@ These markers are not a second content model and do not abbreviate SVG.| Marker | Placement | Purpose ||---|---|---|-| `data-pptx-page-role` | Root `<svg>` | Select the compatibility Layout family only for a legacy baseline page whose project has no `pptx_layouts` mapping. New baseline/free-design pages use `data-pptx-layout` instead. |+| `data-pptx-page-role` | Root `<svg>` | Select the compatibility Layout family for an unmapped baseline page, including free design before Layout distillation and legacy projects without `pptx_layouts`. || `data-pptx-role` | A structural page-frame element | Identify the few objects whose package or animation behavior is not already expressed by specialized metadata. The element also needs a stable unique `id`. |The complete geometry, text, styles, grouping, and asset references remain in@@ -19,8 +19,14 @@ content.Use the existing specialized contracts for specialized facts:-- `data-pptx-layout`, `data-pptx-layout-name`, and `data-pptx-layer` own Master/Layout/Slide structure. A new baseline/free-design page with a locked `pptx_layouts` row uses these markers while remaining `pptx_structure.mode: baseline`;-- `data-pptx-placeholder` owns PowerPoint placeholder identity;+- `data-pptx-layout`, `data-pptx-layout-name`, `data-pptx-layout-kind`, and+ `data-pptx-layer` own Master/Layout/Slide structure. A free-design page uses+ them only after explicit post-design distillation. A deferred template page+ carries the selected prototype key/name and layer provenance during design,+ then adds the final kind only after distillation;+- `data-pptx-placeholder` owns the Layout placeholder prototype. A distilled+ carrier remains an ordinary object on the completed Slide. Legacy immediate+ template and pre-authored structured routes may also bind the Slide shape;- `data-pptx-native` owns native chart/table reconstruction.- `data-pptx-object`, `data-pptx-prst`, `data-pptx-frame`, `data-pptx-av-*`,`data-pptx-geometry-*`, `data-pptx-authoring`, and `data-pptx-part` own@@ -34,17 +40,24 @@ Do not duplicate those facts with `data-pptx-role`. Consumers resolve semanticsin this order: specialized metadata, minimal compiler hints, then legacyfilename/id conventions.-Layout structure is authored, never discovered. Reuse a Layout key only when its-static Layout layer and placeholder contract match exactly. Do not cluster-visually similar pages, move concrete content into a Layout, or mark a complex+The exporter consumes Layout structure; it never discovers or clusters it.+[`distill-layouts`](../workflows/distill-layouts.md) is the explicit authoring+workflow that converts user-selected baseline pages or every deferred template+page into final metadata before export. On template routes, `page_layouts`+selects the input prototype and `pptx_layouts` records the post-design output.+Reuse a key only when its placeholder default frames and static Layout layer+match. Do not move concrete content into a Layout or mark a complexpage-specific group merely to manufacture reuse.Ordinary placeholder carriers are direct atomic objects: one text frame, image,crop SVG, or other supported atomic shape. This is a narrow exception to thetop-level content-group budget, and the carrier does not count toward that-budget. Do not use an arbitrary composite `<g>` as a placeholder; keep complex-groups Slide-local. Native chart/table marker groups remain governed by their-separate specialized contract.+budget. A final post-design `distilled` page may additionally mark one direct+completed `<g>` as an `object` region proxy with explicit design-zone bounds;+the visible group remains ordinary and export adds a hidden transparent binding+proxy. Reusable template SVGs, pending template pages, utility pages, and legacy+immediate contracts may not use this exception. Native chart/table marker+groups remain governed by their separate specialized contract.## 2. Canonical Values@@ -58,6 +71,13 @@ separate specialized contract.| `content` | Ordinary information page | `Content` || `ending` | Closing, thanks, Q&A, or contact page | `Closing` |+### Layout kinds++| Value | Meaning |+|---|---|+| `distilled` | A completed baseline selection or deferred template page distilled into reusable placeholder defaults and optional static framing. Every placeholder has explicit `data-pptx-placeholder-bounds`. |+| `utility` | The empty Freeform Layout shared by baseline pages not selected for distillation. It is forbidden on deferred template routes. |+### Structural roles| Value | Compiler behavior |@@ -77,7 +97,7 @@ continue to own that decision.## 3. Examples-### Legacy baseline fallback page+### Unmapped baseline fallback page```xml<svg xmlns="http://www.w3.org/2000/svg"@@ -96,31 +116,42 @@ continue to own that decision.</svg>```-### Explicit authored Layout page+### Post-design distilled Layout page-This form applies to a new free-design/brand-only baseline page as well as to a-template page. The structure metadata does not change baseline mode into-template mode and does not imply a `page_layouts` reference.+This form applies after the user selects a completed free-design/brand-only+baseline page, or after a deferred template page is reconciled with its+`page_layouts` prototype. Baseline does not imply an input prototype; template+does. Bounds are Layout defaults while current Slide geometry may differ. The+atomic carriers keep their matching Slide bindings, while a composite object+region remains an ordinary visible group with a hidden transparent binding+proxy. The generated Layout receives the reusable PowerPoint placeholders.```xml<svg xmlns="http://www.w3.org/2000/svg"viewBox="0 0 1280 720"- data-pptx-layout="content-default"- data-pptx-layout-name="Content Default">- <rect id="master-bg"- data-pptx-layer="master"+ data-pptx-layout="editorial-visual"+ data-pptx-layout-name="Editorial Visual"+ data-pptx-layout-kind="distilled">+ <path id="layout-rule" data-pptx-layer="layout"data-pptx-editable="false"- x="0" y="0" width="1280" height="720" fill="#FFFFFF"/>-- <g id="layout-header"- data-pptx-layer="layout"- data-pptx-editable="false">- <!-- Complete reusable header drawing remains here. -->- </g>+ d="M72 132H1208" stroke="#D0D5DD"/>- <!-- Placeholder identity is already sufficient; no generic title role. -->+ <!-- Current x/y may differ from the reusable design-zone bounds. --><text id="title-slot" data-pptx-placeholder="title"- x="72" y="92" font-size="32" fill="#172033">{{PAGE_TITLE}}</text>+ data-pptx-placeholder-bounds="72 48 1136 64"+ x="88" y="104" font-size="32" fill="#172033">Quarterly growth</text>++ <text id="body-slot" data-pptx-placeholder="body"+ data-pptx-placeholder-idx="1"+ data-pptx-placeholder-bounds="72 160 432 472"+ x="80" y="190" font-size="20" fill="#344054">Main narrative</text>++ <image id="picture-slot" data-pptx-placeholder="picture"+ data-pptx-placeholder-idx="2"+ data-pptx-placeholder-bounds="544 160 664 472"+ href="../images/quarterly-growth.png"+ x="576" y="176" width="616" height="440"+ preserveAspectRatio="xMidYMid slice"/><!-- Logo has no specialized marker, so the minimal structural hint is useful. --><text id="brand-mark" data-pptx-role="logo"@@ -128,10 +159,30 @@ template mode and does not imply a `page_layouts` reference.<!-- The placeholder already owns slide-number behavior; do not add a role. --><text id="page-number" data-pptx-placeholder="slide-number"+ data-pptx-placeholder-idx="3"+ data-pptx-placeholder-bounds="1152 664 56 24"x="1200" y="680" text-anchor="end">7</text></svg>```+### Unselected page after distillation++The page declares the complete project mapping but keeps every page-specific+visible object Slide-local. No child may carry Layout or placeholder metadata;+an exact shared Master contract is allowed when every page repeats it.++```xml+<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 1280 720"+ data-pptx-layout="freeform-unselected"+ data-pptx-layout-name="Freeform"+ data-pptx-layout-kind="utility">+ <g id="page-content">+ <!-- The complete free-form design remains ordinary SVG. -->+ </g>+</svg>+```+## 4. Validation and CompatibilityThe quality checker validates marker placement, canonical values, and stable@@ -139,13 +190,15 @@ unique IDs. Export consumes explicit authored Layout metadata before baselinecompatibility hints and heuristics:- root `data-pptx-layout` is authoritative when the page has a locked mapping;-- on an unmapped legacy baseline page, root page role is preferred over filename-based Layout classification;+- post-design distillation also requires root `data-pptx-layout-kind` to match the lock;+- a deferred template project with no `pptx_layouts` is pending and cannot enter release export;+- on an unmapped baseline page, root page role is preferred over filename-based Layout classification;- `data-pptx-placeholder="slide-number"` is preferred over a generic role or id;- explicit structural role is preferred over id-token chrome detection;- animation target scanning uses the structural role before id-token fallback.Filename and id heuristics remain compatibility fallbacks only for older SVGs-that lack the corresponding marker. On an unmapped legacy baseline page, a+that lack the corresponding marker. On an unmapped baseline page, acanonical page role is authoritative over the filename. Any explicit structuralrole prevents id-based reinterpretation; an unknown role remains renderable butproduces a quality-check warning.diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.mdindex ac383d52..dd0a9528 100644--- a/skills/ppt-master/references/shared-standards.md+++ b/skills/ppt-master/references/shared-standards.md@@ -389,13 +389,18 @@ table/chart markers are rejected; omit that flag to export their SVG fallback.Semantic markers are minimal compiler hints orthogonal to native SVG semantics.Existing `data-pptx-layout` / layer / placeholder / native-object metadata is-authoritative and read first. New free-design/brand-only baseline pages and all-template/preserve pages declare their locked Layout. Only a legacy baseline-project whose whole `pptx_layouts` section is absent uses-`data-pptx-page-role`. Add `data-pptx-role` only when no specialized marker-expresses the required page-frame behavior; the element also uses a stable-unique `id`. Do not classify ordinary page content or move visible facts out of-SVG attributes/text into metadata. See+authoritative and read first. Deferred template pages carry the selected+prototype structure while authored but do not finalize `pptx_layouts` or root+kind until the complete design exists. Legacy immediate-template/preserve pages+declare their locked output Layout while authored. Free-design/brand-only+baseline pages remain unmapped during visual design; only the explicit post-design+[`distill-layouts`](../workflows/distill-layouts.md) workflow adds a complete+Layout mapping after the user selects reusable pages or after every deferred+template page is complete. An unmapped baseline page+may use `data-pptx-page-role` for compatibility routing. Add `data-pptx-role`+only when no specialized marker expresses the required page-frame behavior;+the element also uses a stable unique `id`. Do not classify ordinary page+content or move visible facts out of SVG attributes/text into metadata. See[`semantic-svg.md`](semantic-svg.md) for the canonical vocabulary and examples.- **Canvas authority**: `viewBox` MUST match the selected canvas dimensions.@@ -418,7 +423,8 @@ These forms are needed only when the stated PPT behavior matters:| One editable PPT text frame with mixed inline formatting | Put the logical line in one `<text>` with non-positional `<tspan>` children. A `<tspan>` with `x`/`y`/`dy` starts a new positioned line; evenly `dy`-stacked lines that repeat the parent `<text>`'s `x` merge into one frame with hard line breaks. A larger accepted gap or list marker starts a new paragraph; `data-pptx-break="soft"` explicitly joins authored rows. The merged frame keeps normal PowerPoint wrapping for later edits. An unmergeable gap or mismatched `x` flattens to separate frames. Separate `<text>` elements stay valid when separate frames are intended. || Stable object grouping or object-level animation anchor | Wrap the intended object in `<g id="...">`. Content grouping is **mandatory** per §4.3 — a top-level `<g id>` is also the animation anchor; it is not an optional convenience. || Native PowerPoint background promotion | Use a direct, full-canvas, solid `<rect>` without transform, filter, clip, rounding, or visible stroke. Other SVG backgrounds remain ordinary slide shapes. Template routes add the ownership metadata in §7. |-| Free-design PowerPoint Layout | Use the locked `pptx_layouts` key/name plus the explicit metadata in §7. A legacy baseline project without that section uses §4.1 page-family/chrome hints. No route infers visual similarity. |+| Reusable free-design PowerPoint Layout | Finish the free design first, then run [`distill-layouts`](../workflows/distill-layouts.md) on pages explicitly selected by the user. The workflow writes the complete `pptx_layouts` mapping and §7 metadata; the exporter itself never infers visual similarity. Before distillation, an unmapped baseline project uses §4.1 compatibility routing. |+| Reusable template-based PowerPoint Layout | Select one complete input SVG per page in `page_layouts`, finish every visible page, then run [`distill-layouts`](../workflows/distill-layouts.md). Strict restores prototype structure/bounds; adaptive keeps Master ids/topology/geometry and may finalize an evolved Layout. Non-mirror skin follows `spec_lock`. |**Hard rule — supported shape conversion**: Every PPT editability claim in this specification refers to the project converter reading `svg_output/` and emitting native DrawingML. `svg_final/` is a self-contained visual preview that may be inserted into PowerPoint as an SVG picture. PowerPoint's manual Convert-to-Shape operation is unsupported; do not narrow the authoring contract to its undocumented SVG subset.@@ -1324,21 +1330,37 @@ defaults to `bottom` and accepts `top`, `left`, or `right`.### Baseline Layout RoutingNative `baseline` export has two deterministic routes. A new free-design or-brand-only project writes one `pptx_layouts` row per page and repeats that-key/name on every SVG root; export compiles the explicit Master/Layout/-placeholder contract in the next section. A legacy project whose entire mapping-section is absent keeps the compatibility family pass below. Mixing declared-and undeclared pages is invalid. Neither route performs visual clustering.--**Explicit baseline route**: Reuse one Layout key only when pages have the same-static Layout layer and placeholder type/index/bounds contract. Different-wording, data, or imagery stays Slide-local and does not create a new Layout;-a genuinely different reusable composition gets a different key, even when both-pages have the semantic role `content`.--**Legacy compatibility route**: After every unstructured SVG page has been-converted, assign the coarse page families below without changing SVG authoring-or live preview.+brand-only project initially omits `pptx_layouts` and keeps all page geometry+Slide-local while the visual design is still free. If the user later selects+finished pages for reuse, [`distill-layouts`](../workflows/distill-layouts.md)+atomically writes one mapping row for every page: selected pages use explicit+`distilled` contracts and unselected pages share an empty `utility` Layout.+Existing structured baseline projects remain readable. An unmapped project uses+the compatibility family pass below. Mixing declared and undeclared pages is+invalid. The authoring workflow may distill a user-selected design; the exporter+never performs visual clustering.++**Explicit baseline route**: Reuse one distilled Layout key only when pages have+the same reusable placeholder type/index/default-bounds contract and any static+Layout layer is identical. A distilled Layout may be placeholder-only; it does+not need decorative Layout shapes. Different wording, data, imagery, or+Slide-local geometry stays on the Slide and does not create a new Layout. For+example, 4:6, 3:7, and 5:5 members may share one Layout when their semantic+zones are the same; the Layout stores one default frame while each Slide keeps+its authored local frame. A genuinely different reusable composition gets a+different key, even when both pages have the semantic role `content`.++**Utility Layout**: In a distilled project, every unselected page maps to the+same `utility` Layout. That Layout has no Layout shapes and no+placeholders; every page-specific visible object remains Slide-local. A shared+deck Master contract may still repeat on the page. The utility Layout exists only+to keep the post-distillation mapping complete and must not be used as evidence+that the page itself was distilled.++**Unmapped compatibility route**: Before free-design distillation, or when+reading a legacy project whose whole mapping section is absent, assign the+coarse page families below after every unstructured SVG page has been converted.+This does not change SVG authoring or live preview.| Root `data-pptx-page-role` | Output layout ||---|---|@@ -1358,8 +1380,8 @@ used it to hide promoted Master shapes from a minority page.**Hard rule — no visual inference**: Keep every actual title, body, picture,chart, table, and page-specific shape on the Slide. Explicit baseline Layouts-consume authored metadata; legacy baseline Layouts do not infer placeholders or-promote visually similar content.+consume authored metadata; unmapped compatibility Layouts do not infer+placeholders or promote visually similar content.**Background rule**: Move a Slide `p:bg` to its family Layout only when everyslide in that family carries exactly the same explicit background. Otherwise,@@ -1376,22 +1398,38 @@ and every non-identical object Slide-local.### Explicit PPTX Master / Layout / Placeholder Metadata-**Trigger**: New free-design/brand-only routes use-`pptx_structure.mode: baseline` plus complete `pptx_layouts`; deck/layout template routes use-`pptx_structure.mode: template` plus complete `page_layouts` and-`pptx_layouts`. Preserve keeps its source-package contract. Direct diagnostics-may pass `--pptx-structure template`. In baseline, explicit Layout metadata-without a complete lock is an error rather than a dormant hint.--**Project lock**: The standard pipeline writes one `pptx_layouts` row per page-using `P<NN>: <layout_key> | <PowerPoint layout name>`. The SVG root values MUST-match that row. Baseline derives the key/name from the authored composition and-does not create `page_layouts`. Template strict uses the selected template-key/name; adaptive may create a new key/name while repeating the same Master-contract. Reuse one layout key only when pages share the same static Layout-layer and placeholder contract; different content is not a reason to create a-new Layout. Every explicit route requires numeric `spec_lock.md` typography-`title` / `body` rows.+**Trigger**: Free-design/brand-only routes use `pptx_structure.mode: baseline`+without `pptx_layouts` during visual authoring. Explicit post-design+distillation adds `layout_strategy: distill` plus complete `pptx_layouts`.+Distillation-capable deck/layout template routes use+`pptx_structure.mode: template` plus `layout_strategy: distill` and complete+`page_layouts`, but omit `pptx_layouts` until every page is complete. A+bounds-missing strict legacy prototype and existing template locks without the+strategy retain immediate mappings. Preserve keeps its source-package contract.+Direct diagnostics may pass `--pptx-structure template`. In baseline, explicit+Layout metadata without a complete lock is an error rather than a dormant hint.+In deferred template authoring, provisional prototype metadata is allowed while+the output mapping is wholly absent, but release export remains blocked until+distillation writes the complete mapping and root kind.++**Project lock**: Legacy immediate-template and existing explicit routes write+one `pptx_layouts` row per page using+`P<NN>: <layout_key> | <PowerPoint layout name>`. Post-design distillation uses+`P<NN>: <layout_key> | <PowerPoint layout name> | <layout_kind>`, where every+baseline kind is `distilled` or `utility`; every deferred template kind is+`distilled`. The SVG root values MUST match that row.+Baseline distillation derives the key/name only from the completed pages that+the user selected and does not create `page_layouts`. Template `page_layouts`+is the input-prototype mapping: strict restores its key/name/Master/Layout/+placeholder structural contract, while adaptive repeats its Master ids/topology/geometry and may create a+new Layout key/name. Adaptive may retain the prototype key/name only when its+static Layout, placeholder identities, and default bounds remain unchanged.+Mirror additionally keeps literal paint, typography, effects, grouping, and+geometry for every reused Master/Layout identity; only visible text changes.+Reuse one key only when pages share the same+placeholder default-frame contract and any static Layout layer; different+content or local geometry is not a reason to create a new Layout. Every explicit+route requires numeric `spec_lock.md` typography `title` / `body` rows.**Master text-style contract**: Structured baseline and template export map thelocked `title` size to every `a:defRPr` in Master `p:titleStyle`, and map the@@ -1406,7 +1444,7 @@ locked `body` size to every level in both `p:bodyStyle` and `p:otherStyle`.**Hard rule — narrow scope**: This Master update changes only Master`p:txStyles//a:defRPr@sz`. It does not rewrite direct run sizes on generatedslides, so the initial slide rendering remains controlled by the authored SVG.-Missing `title` or `body` rows fail explicit Layout export. Legacy baseline,+Missing `title` or `body` rows fail explicit Layout export. Unmapped baseline,`preserve`, and `flat` do not apply this Master text-style update.**Layout level-one text-default contract**: For every text-bearing placeholder@@ -1421,19 +1459,23 @@ prototype size remain unchanged.|---|---|---|| `data-pptx-layout="content"` | root `<svg>` | Binds the slide to one generated reusable layout key || `data-pptx-layout-name="Title and Content"` | root `<svg>` | Sets the PowerPoint layout-picker name; defaults from the layout key |+| `data-pptx-layout-kind="distilled"` | root `<svg>` | Marks a completed baseline selection or deferred template page as `distilled`; baseline-only unselected shells use `utility` || `data-pptx-layer="master"` | direct visual child | Moves one repeated static object/background into the slide master || `data-pptx-layer="layout"` | direct visual child | Moves one repeated static object/background into the selected layout || `data-pptx-layer="slide"` | direct full-canvas solid `<rect>` only | Writes a one-page override as Slide `p:bg` |-| `data-pptx-placeholder="..."` | direct visual child | Keeps actual content on the slide and maps it to a generated layout placeholder |+| `data-pptx-placeholder="..."` | direct visual child | Supplies a generated Layout placeholder prototype. Legacy immediate/pre-authored template contracts and `distilled` atomic carriers bind the current Slide shape; a final distilled composite object region remains ordinary and uses a hidden binding proxy. || `data-pptx-placeholder-bounds="x y width height"` | placeholder element | Overrides the reusable placeholder frame in SVG user units || `data-pptx-placeholder-idx="1"` | placeholder element | Retains an imported source layout placeholder index; optional for reconstructed layouts || `data-pptx-editable="false"` | master/layout element or slide background | Declares intentional editing outside ordinary slide content |**Hard rule — explicit only**: Structured baseline and template export never-promote visually similar content by inference. Every SVG requires root-`data-pptx-layout` and `data-pptx-layout-name`; every-master/layout/placeholder element requires a unique `id` and must be a direct-child of the root SVG.+promote visually similar content by inference. Every mapped SVG requires root+`data-pptx-layout` and `data-pptx-layout-name`; a distilled mapping also+requires `data-pptx-layout-kind`. Every master/layout/placeholder element+requires a unique `id` and must be a direct child of the root SVG. A baseline+`utility` page is the narrow exception: it declares the root contract but contains no+Layout element or placeholder. It may repeat the exact Master contract shared+by every mapped page.**Layer order**: Author the SVG in PowerPoint paint order: Master background,Layout background, optional Slide background, Master shapes, Layout shapes,@@ -1458,24 +1500,27 @@ by this solid-background rule.| `date`, `footer`, `slide-number` | direct `<text>` | `dt`, `ftr`, `sldNum` || `picture` | direct `<image>` or imported crop `<svg>` | `pic` || `chart`, `table` | direct matching `data-pptx-native` marker group | `chart`, `tbl` |-| `object` | one direct text, image, or basic SVG shape | `obj` |+| `object` | one direct text, image, or basic SVG shape; final `distilled` output may instead use one direct composite group as a Layout-only region proxy | `obj` || `media` | direct `<image>` or imported crop `<svg>` | `media` |**Text placeholder carrier**: A multiline text placeholder must remain onenative text frame. Use the default paragraph merge; `--no-merge` and explicit-`data-pptx-text-mode="lines"` cannot bind several line shapes to one PowerPoint-placeholder. Leave strict-line text Slide-local when separate frames are the-required result.+`data-pptx-text-mode="lines"` cannot supply several line shapes as one+PowerPoint placeholder prototype/binding. Leave strict-line text Slide-local+when separate frames are the required result.`title` is normally type-matched without an index in reconstructed layouts; ifan imported source title explicitly has one, preserve that exact index. Everyindexed placeholder on one layout uses a unique OOXML UInt32 index. Explicit-Layout export writes the semantic type on both the Layout and Slide placeholder-(except `obj`, whose OOXML default is already-`obj`) so PowerPoint and `python-pptx` retain the same identity. Date, footer,-and slide-number placeholders enable their matching Layout `p:hf` flags; a-date placeholder also gets a `datetimeFigureOut` field in the reusable Layout-definition. The current Slide keeps its authored date content.+legacy immediate-template/pre-authored export writes the semantic type on both the Layout and+Slide placeholder (except `obj`, whose OOXML default is already `obj`) so+PowerPoint and `python-pptx` retain the same identity. Distilled export always+writes that identity on the Layout; atomic Slide carriers retain a matching+binding, while a composite object region uses an ordinary visible carrier plus+a hidden transparent proxy.+Date, footer, and slide-number placeholders enable their matching Layout `p:hf`+flags; a date placeholder also gets a `datetimeFigureOut` field in the reusable+Layout definition. The current Slide keeps its authored date content.Because an omitted `p:ph@idx` has the effective value `0`, an omitted-indextitle reserves `0`; no other placeholder on that Layout may use the same@@ -1483,23 +1528,44 @@ effective index.**Placeholder prototype**: The first slide using a layout key supplies thatlayout's placeholder formatting. `data-pptx-placeholder-bounds` supplies the-reusable frame; when omitted, the exporter uses the prototype object's native-DrawingML bounds. Repeat the same placeholder ids/types on every slide using-that layout. Actual slide content and local geometry may differ.+reusable default frame. Legacy immediate-template and pre-existing explicit+contracts may omit it and fall back to the prototype object's native DrawingML+bounds. Every newly created template page and every `distilled` Layout provides+it on every placeholder: derive the bounds from+the intended design zone, column, panel inset, safe area, or picture frame —+never from text length, glyph width, line count, or a tight content bounding+box. Repeat the same placeholder ids/types/default bounds on every slide using+that layout. For `distilled`, the Layout always owns the reusable `p:ph`.+Atomic text/picture/native-object carriers keep a matching Slide binding so the+approved rendering stays identical. A direct composite `<g>` is allowed only as+a final distilled `object` region proxy: its visible Slide group remains+ordinary, and export adds one hidden transparent matching binding shape to+suppress empty inherited placeholder paint in PowerPoint-compatible renderers.+The placeholder bounds define the Layout default only; actual Slide content and+local geometry may differ.**Final-package read-back gate**: After writing a temporary structured-baselineor template-mode PPTX and before publishing it, export reopens the package andverifies thateach Slide targets exactly one Layout, one layout key always resolves to thesame part, different keys do not collapse onto one part, and every Layout is-registered through its Master and the Presentation. It also verifies the-Layout picker name/content type, placeholder type and effective index,-matching `p:hf` flags, prototype-derived or explicitly overridden frame,-direct prompt size, and level-one default size. Later slides may keep different-slide-local geometry; only the reusable Layout frame is checked against the-explicit/prototype contract. Any mismatch fails export without replacing the-requested output.-This gate applies to structured baseline and `template`; legacy baseline,+registered through its Master and the Presentation. Physical Slide/Layout/+Master part rosters, their content-type overrides, and their Presentation/+Master registrations must be exact. It also verifies the Layout picker name,+placeholder type and effective index, matching `p:hf` flags, prototype-derived+or explicitly overridden frame, direct prompt size, and level-one default size.+Every owned `p:bg` is checked as an exact zero-or-one payload against the pre-+promotion result; this includes preserving the base Master background when no+authored Master background replaces it. During the same export, every finished+Slide, Layout, and Master must reproduce its exact top-level shape-name roster+and order after packaging. For `distilled`, the gate additionally verifies that+each atomic visible carrier owns the expected binding, each composite visible+carrier remains ordinary, and every composite binding proxy is hidden.+A `utility` Layout must read back with no background, shape, or+placeholder. Later slides may keep different slide-local geometry; only the reusable+Layout frame is checked against the explicit/prototype contract. Any mismatch+fails export without replacing the requested output.+This gate applies to structured baseline and `template`; unmapped baseline,`preserve`, and `flat` retain their existing behavior.**Static structure consistency**: Repeat the same master element ids on everydiff --git a/skills/ppt-master/references/strategist.md b/skills/ppt-master/references/strategist.mdindex 182027a4..a5732e64 100644--- a/skills/ppt-master/references/strategist.md+++ b/skills/ppt-master/references/strategist.md@@ -845,18 +845,19 @@ This is what makes the axis meaningful: a `presentation` deck and a `text` deck1. Read reference template: `templates/design_spec_reference.md`2. Generate complete spec from scratch based on analysis3. Save to: `projects/<project_name>.../design_spec.md`-4. **Generate execution lock**: read `templates/spec_lock_reference.md` and produce `projects/<project_name>.../spec_lock.md` — a distilled, machine-readable short form of the color / typography / icon / image / **page_rhythm** / **pptx_layouts** / **page_layouts** / **page_charts** decisions above. This file is what the Executor re-reads before every page (see [executor-base.md](executor-base.md) §2.1). The values in `spec_lock.md` MUST exactly match the decisions recorded in `design_spec.md`; if they ever diverge, `spec_lock.md` wins and `design_spec.md` should be treated as historical narrative.+4. **Generate execution lock**: read `templates/spec_lock_reference.md` and produce `projects/<project_name>.../spec_lock.md` — a distilled, machine-readable short form of the color / typography / icon / image / **page_rhythm** / **page_layouts** / **page_charts** decisions above. Write `pptx_layouts` before generation only for legacy immediate-template or preserve routes; new baseline/template distillation writes it after the complete SVG pages exist. This file is what the Executor re-reads before every page (see [executor-base.md](executor-base.md) §2.1). The values in `spec_lock.md` MUST exactly match the decisions recorded in `design_spec.md`; if they ever diverge, `spec_lock.md` wins and `design_spec.md` should be treated as historical narrative.- **page_rhythm is mandatory**: Based on the page list in §IX Content Outline, assign each page one of `anchor` / `dense` / `breathing` (see `spec_lock_reference.md` for the full vocabulary). This is what breaks the uniform "every page is a card grid" feel — without it the Executor defaults all pages to `dense`.- **Rhythm follows narrative, not quota**: `breathing` pages mark natural pauses — chapter transitions, standalone emphasis (hero quote / big number), SCQA bridges. Dense decks may legitimately be all `dense`. **Do NOT invent filler pages** ("Thank you", empty dividers) to pad rhythm — every `breathing` page must say something independent. Delivery purpose biases the overall lean (`presentation` toward more `anchor` / `breathing`, `text` toward `dense`; see §6.1) — a bias, never a quota.- **Cover impact is mandatory**: Page `P01` is the deck's first visual contract, not a generic title slide. In `design_spec.md §IX`, add a `Cover impact` line for `P01` that names one concrete hook and one concrete composition strategy. Use the source's strongest available signal: a provocative core claim, object / scene metaphor, hero number, founder / product / audience moment, or a distilled conflict. Pair it with one concrete composition strategy — such as `full-bleed image + floating title`, `typographic poster`, `hero object`, `data hook`, `editorial scene`, `high-contrast abstract geometry`, or a fresh composition the deck's subject suggests (these are starting points, not the allowed set). If no external or AI image is available, still specify a native-SVG visual hook; do not fall back to "title + subtitle + decorative background". (Beautify / template-fill keep the source cover verbatim — this rule does not apply on those preservation paths.)- **Cover rhythm lock**: `P01` remains `anchor` in `spec_lock.md page_rhythm`, but its §IX `Cover impact` must prevent content-page patterns. Do not plan multi-card grids, agenda-like bullets, or equal-weight columns on the cover unless a template explicitly requires that structure, or a preservation path (beautify / template-fill) is transcribing the source cover verbatim.- **Closing impact (only when the deck closes)**: the deck's last page is its final visual contract — the strongest impression after the cover. When the deck genuinely lands on a conclusion / call-to-action / final-takeaway page, give it a `Closing impact` line in §IX: name the one thing the audience should leave with (a distilled takeaway, a forward call, a memorable restatement of the core claim) + one composition that delivers it — never a generic "Thank you" / contact-only slide or a centered-title reprise of the cover. **Do NOT invent a closing page to satisfy this** — the filler-page ban above still holds; apply it only to the page where the deck actually resolves. Same exemptions as the cover: skip on template / beautify / template-fill preservation paths.- - **pptx_structure is mandatory**: Write `mode: baseline` for free design and brand-only routes. When a deck/layout template is confirmed, write `mode: template` plus `template_adherence: strict|adaptive`. Both adherence values stay on explicit template export. Use `mode: preserve` only when reopening a legacy strict project that already carries a validated `native_structure.json` + `source_template.pptx` pair. Do not choose `flat`; it is a CLI-only diagnostic override.- - **pptx_layouts (native output Layout contract)**: Write one `P<NN>: <layout_key> | <PowerPoint layout name>` row for every page in every new generated deck. Free-design and brand-only routes remain `mode: baseline`; derive stable keys and picker names from the compositions planned in §IX, without adding `page_layouts`. Name each key after its composition (`timeline-spine`, `kpi-band-trio`), never after a PowerPoint stock role or the page's topic. Template strict uses the selected template SVG's exact key/name; adaptive may introduce a new stable key/name. Legacy preserve uses the exact source key/name. A legacy baseline project whose whole section is absent remains valid and uses page-role compatibility behavior.- - **Layout-family boundary**: The key identifies the page's composition — its chrome, zone framing, and placeholder set — not its topic and not its slide-local content. Series pages repeating one composition (three directional timetable pages, per-chapter dividers) share one key; a genuinely different composition gets its own key, and the Executor materializes that difference as Layout-layer zone framing (executor-base.md §1.2). Do not split keys because slide-local wording, data, or imagery differ within one composition. Decide families from the authored page plan — never by post-hoc visual clustering, filenames, or content similarity. **Self-check before writing the section** — two failure signals: distinct keys for pages of one composition (topic-splitting; they compile to duplicate Layouts) and one role key covering different compositions (role-clustering; the Layout matches none of them). Re-derive on either.- - **page_layouts (deck/layout templates only)**: Add one `P<NN>: <svg_basename>` row for every page. Strict inherits that SVG contract unchanged. Adaptive uses it as the architecture reference and may evolve the Layout layer under a new `pptx_layouts` key; it must not drop into free design. Omit the whole section for free-design and brand-only routes; their required `pptx_layouts` rows do not imply an SVG template reference.+ - **pptx_structure is mandatory**: Write `mode: baseline` for free design and brand-only routes. Do not add `layout_strategy` during baseline planning; the explicit [`distill-layouts`](../workflows/distill-layouts.md) workflow adds it only after the user selects completed pages. When a deck/layout template is confirmed, write `mode: template` and `template_adherence: strict|adaptive`. Add `layout_strategy: distill` after the template bounds preflight below. Use `mode: preserve` only when reopening a legacy strict project that already carries a validated `native_structure.json` + `source_template.pptx` pair. Do not choose `flat`; it is a CLI-only diagnostic override.+ - **Template bounds preflight**: Inspect every selected `page_layouts` SVG before finalizing the lock. If every placeholder has explicit `data-pptx-placeholder-bounds`, use deferred distillation for either adherence. Adaptive may also use deferred distillation with a legacy bounds-missing prototype because Distiller authors new design-zone bounds. If strict selects any bounds-missing prototype, use legacy immediate-template compatibility: omit `layout_strategy`, write the complete kindless `pptx_layouts` mapping from prototype key/name before generation, and emit one warning naming the legacy template pages. Do not silently convert strict to adaptive or derive strict bounds from sample text.+ - **pptx_layouts (native output Layout contract)**: Omit the whole section during planning for new baseline and distillation-capable template routes. The §IX `Layout` line describes visual composition intent only; it is not a final PowerPoint Layout key. Template `page_layouts` selects the input prototype; [`distill-layouts`](../workflows/distill-layouts.md) writes the output key/name/kind only from the completed SVG. Bounds-missing strict legacy templates, other immediate locks without `layout_strategy`, and preserve locks retain pre-generation mappings.+ - **Post-design reuse boundary**: Do not predict rich reusable Layouts from the outline. After visual construction, only [`distill-layouts`](../workflows/distill-layouts.md) may finalize the output contract. Baseline promotes user-selected pages and maps unselected pages to one utility Layout. Template strict restores the selected prototype's structure/bounds; adaptive retains its Master ids/topology/geometry and may distill an evolved Layout. Non-mirror skin continues to follow `spec_lock`. The exporter never discovers or clusters layouts itself.+ - **page_layouts (deck/layout templates only)**: Add one `P<NN>: <svg_basename>` row for every page. This is the complete input-prototype mapping. Strict later restores that SVG's structural Layout contract; adaptive keeps its Master structure and may evolve the Layout after the page is complete. Omit the whole section for free-design and brand-only routes.- **page_charts (write only for chart pages that match a catalog template)**: For each page in `design_spec.md §VII` whose `reference template path` points to `templates/charts/<name>.svg`, add `P<NN>: <chart_name>`. Pages with `no-template-match` in §VII MUST NOT appear here (Executor would look for a non-existent reference). If the deck has no data-visualization pages, omit the section.- - **Hard rule**: Use both `page_layouts` and `page_charts` only with a compatible template shell. For a chart page without an exact roster match, adaptive mode selects the closest neutral content template and assigns a new explicit Layout key; strict mode must select an existing compatible Layout or revise the outline. Never omit `page_layouts` inside a deck/layout template route.+ - **Hard rule**: Use both `page_layouts` and `page_charts` only with a compatible template shell. For a chart page without an exact roster match, adaptive mode selects the closest neutral input prototype and defers any new output Layout key until post-design distillation; strict mode must select an existing compatible Layout or revise the outline. Never omit `page_layouts` inside a new deck/layout template route.---diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.mdindex d78725eb..a989f9d7 100644--- a/skills/ppt-master/references/template-designer.md+++ b/skills/ppt-master/references/template-designer.md@@ -49,10 +49,12 @@ Input priority for PPTX-backed template creation:7. `summary.md` only as a fast scan; never as the canonical fact source8. screenshots / original PPTX only for style verification-**Native structure output**: Always set `native_structure_mode: template`. Do not ship `native_structure.json` or `source_template.pptx`. Reconstruct one clean Master plus semantic Layouts through explicit SVG structure metadata. Every page remains a complete standalone SVG preview.+**Native structure output**: Always set `native_structure_mode: template`. Do not ship `native_structure.json` or `source_template.pptx`. Reconstruct one clean Master plus semantic Layouts through explicit SVG structure metadata. Every page remains a complete standalone SVG preview, and every retained source Layout is represented by at least one complete template page even when no source Slide used it. Mirror is the page-count exception: retain the Layouts referenced by source Slides, report unused source Layouts, and use fidelity when the full picker roster must be materialized.**Downstream boundary**: The Strategist confirmation stage selects `strict` or `adaptive` when a project consumes this package. Both export through explicit template mode. Strict keeps the referenced Layout contract; adaptive may create a new Layout while retaining the template Master. Template_Designer does not preselect that project-level choice.+When the source has a native Layout graph, `design_spec.md §V` must be followed by a `Source Layout Consolidation` table. Record every retained source Layout key/name and its output SVG plus rebuilt Layout key/picker name; if mirror cannot materialize an unused source Layout, record the explicit unused reason. This table is the audit artifact for consolidation and must not be replaced by prose such as “similar layouts merged.”+---## Page Roster@@ -186,6 +188,8 @@ native_structure_mode: template## V. Page RosterOne row per emitted SVG describing what this template's version of cover / chapter / content / ending looks like (background treatment, decorative anchors, layout rhythm, image behavior, content density, intended content slot). Record the rebuilt Layout key and PowerPoint picker name. For `fidelity` mode, note the cluster source and visual differentiator. For `mirror` mode the roster is the load-bearing content-fit index, so each row must distinguish siblings by column count, hero element, density, and suitable content. Roster entries must match the actual SVG files on disk.+For a source-derived native template, add `### Source Layout Consolidation` immediately after the roster with columns `Source Layout key/name`, `Output SVG`, `Rebuilt key/picker name`, and `Disposition`. Include one row for every retained source Layout, including consolidated and explicitly unused mirror Layouts.+## VI. Assets (omit when none)Logos, cover backgrounds, brand textures bundled with the template package — file name, dimensions, intended usage.@@ -242,6 +246,7 @@ Do:- use a background image asset when the original decorative layer is too complex to recreate cleanly- use cleaned slide SVG references to inspect composition, spacing, text hierarchy, and fixed decorative structure only after factual metadata has been anchored- read every reference SVG under `svg/` — `master_*.svg`, `layout_*.svg`, and every `slide_*.svg` regardless of slide count. Master / layout files describe the deck's shared visual language (read first); slide files describe per-page content (read after). Partial coverage drops template fidelity.+- materialize every retained source Layout into at least one complete template page by composing its Master layer, Layout layer, placeholder contract, and an appropriate Slide sample. When several source Layouts consolidate into one semantic output Layout, record that mapping; never silently drop an unused source Layout.- rename adopted assets to semantic names (`cover_bg.png`, `brand_emblem.png`) rather than carrying raw `image3.png` into the final templateDo not:@@ -255,12 +260,16 @@ Do not:|---|---|| Output semantic layout | Root `data-pptx-layout` + stable `data-pptx-layout-name` || Rebuilt master/layout visual | Direct preview child with `data-pptx-layer="master|layout"` and `data-pptx-editable="false"` |-| Semantic content slot | Direct content child with `data-pptx-placeholder`; add `data-pptx-placeholder-idx` when same-role slots require stable disambiguation |+| Semantic content slot | Direct content child with `data-pptx-placeholder` and explicit `data-pptx-placeholder-bounds`; add `data-pptx-placeholder-idx` when same-role slots require stable disambiguation || Page-only background | Direct full-canvas solid rect with `data-pptx-layer="slide"` || Structural page-frame hint | Optional `data-pptx-role` only when background/decoration/header/footer/logo/watermark/chrome/page-number behavior is not already expressed by layer/placeholder metadata; stable unique `id` required |Repeat inherited visuals in every standalone SVG so browser preview remains complete. Template export validates their equality, moves one copy into the generated Master/Layout parts, and removes the repeated Slide copies. Do not flatten inherited visuals into unmarked slide content.+**Forbidden — deck-instance Layout kind**: Do not carry `data-pptx-layout-kind="distilled|utility"` into a reusable template package. The package owns a pre-authored prototype; downstream completed pages receive their final kind during post-design distillation.++**Composite distilled-source boundary**: When Type B input contains a final distilled top-level group marked as an `object` region proxy, do not copy that marker into the reusable package. Preserve the group as the standalone visual sample, remove its placeholder attributes, and add a separate direct atomic `rect` placeholder proxy at the same design-zone bounds with `fill="none" stroke="none"`. Give that proxy a stable semantic id/type/index. Composite group placeholders are final deck-instance metadata; template prototypes remain atomic.+Use the imported placeholder types verbatim: `title`, `subtitle`, `body`,`picture`, `chart`, `table`, `object`, `media`, `date`, `footer`, and`slide-number`. In particular, do not collapse source `subTitle`, `obj`,@@ -268,6 +277,8 @@ Use the imported placeholder types verbatim: `title`, `subtitle`, `body`,title normally has no index. Assign stable indices only when repeated roles needdisambiguation inside the rebuilt Layout.+**Hard rule — explicit design-zone bounds**: Every placeholder in a newly created template carries `data-pptx-placeholder-bounds="x y width height"`. For imported placeholders, use the source Layout geometry from `manifest.json` / `native_structure.json`. For new or consolidated slots, use the intended safe area, column, panel inset, or media frame. Do not use character count, glyph width, current wrapping, or the tight sample-content box.+### 3. Placeholder Markers> Mirror may retain literal example text instead of `{{...}}` authoring markers, but imported semantic content slots still receive native `data-pptx-placeholder` metadata. The rest of this section defines the preferred authoring vocabulary for standard and fidelity modes.@@ -277,6 +288,7 @@ Use clear placeholder markers for replaceable content:```xml<!-- Text placeholder --><text id="title-slot" data-pptx-placeholder="title"+ data-pptx-placeholder-bounds="80 280 1120 96"x="80" y="320" fill="#FFFFFF" font-size="48" font-weight="bold">{{TITLE}}</text>@@ -462,8 +474,8 @@ templates/- [x] Every page listed in `design_spec.md §V Page Roster` saved to the selected template target (library package directory or project `templates/` root)- [x] Naming convention applied (standard / fidelity: letter-suffix variants; mirror: `<NNN>_<page_type>.svg`)- [x] Templates follow design spec (colors, fonts, layout)-- [x] Placeholder markers are clear and standardized; mirror may keep literal text but still maps imported semantic slots-- [x] Every SVG is a complete preview with explicit Master/Layout/Slide/placeholder metadata and `native_structure_mode: template`+- [x] Placeholder markers are clear and standardized; every slot has explicit design-zone bounds; mirror may keep literal text but still maps imported semantic slots+- [x] Every SVG is a complete preview with explicit Master/Layout/Slide/placeholder metadata and `native_structure_mode: template`; retained source Layouts are materialized, or mirror reports unused Layouts explicitly- [x] Project scope, when selected: bitmaps routed to `images/`; extracted icons copied to both `templates/icons/` and runtime `icons/`- [ ] **Next step**: Validate assets; register only library scope, otherwise hand the in-place project bundle to main Step 3```diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.mdindex cf5afb83..2cb16f3f 100644--- a/skills/ppt-master/scripts/README.md+++ b/skills/ppt-master/scripts/README.md@@ -132,9 +132,9 @@ python3 scripts/svg_to_pptx.py <project_path>For SVG-authoring routes, `svg_output/` is the complete visible page-design source: every exported text, image, shape, background, and template-derived layout element is present in the page SVG or explicitly referenced by it. Export may translate represented content into Master/Layout/Slide parts or native objects, but it does not retrieve missing visible content from templates or planning files. Speaker notes, animation, narration, transitions, `template-fill-pptx`, and `native-enhance-pptx` remain separately owned capabilities.-Native `svg_to_pptx.py` defaults to `baseline`. New free-design/brand-only projects include complete `pptx_layouts` mappings and matching explicit SVG Master/Layout/placeholder metadata; the exporter creates one reusable Layout per contract and validates the finished package. A legacy project whose whole mapping section is absent keeps the compatibility pass: exact z-order-safe shared background/chrome promotion plus coarse root `data-pptx-page-role` families, with filename/id fallbacks. Actual content remains Slide-local in both routes, and no visual-similarity inference is performed. Baseline also prunes unused layouts and maps locked typography/colors into the PowerPoint theme. Use `--pptx-structure flat` for slide-local diagnostics.+Native `svg_to_pptx.py` defaults to `baseline`. Free-design/brand-only projects initially omit `pptx_layouts`, keep all actual content Slide-local, and use the compatibility pass: exact z-order-safe shared background/chrome promotion plus coarse root `data-pptx-page-role` families, with filename/id fallbacks. If the user later selects completed pages for reuse, [`distill-layouts`](../workflows/distill-layouts.md) writes one complete mapping: selected pages use explicit `distilled` Layout contracts and unselected pages share an empty `utility` Layout. The exporter compiles only those declarations, validates the finished package, and performs no visual-similarity inference. Baseline also prunes unused layouts and maps locked typography/colors into the PowerPoint theme. Use `--pptx-structure flat` for slide-local diagnostics.-Structured baseline and deck/layout template routes use the same explicit Layout compiler. Each complete SVG names its output Layout, repeats reusable Master/Layout preview layers, and marks supported content placeholders. Template strict keeps the selected contract; adaptive may create a new Layout while retaining the Master. The exporter validates cross-slide equality, creates one reusable Layout per key, removes repeated inherited copies, and keeps actual content Slide-local. The complete contract lives in [`references/shared-standards.md`](../references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata).+Post-design distilled baseline and distillation-capable deck/layout template routes use the same explicit Layout compiler. A distillation-capable template project selects complete input prototypes in `page_layouts` and defers `pptx_layouts` until every visible SVG page exists. Deferred strict output must match prototype key/name, Master/Layout structure, and placeholder bounds; adaptive must keep Master ids/topology/geometry and may finalize an evolved Layout or author new design-zone bounds for a legacy prototype. Adaptive can reuse the prototype key/name only when that Layout contract is unchanged; evolution receives a new identity. A bounds-missing strict legacy selection instead keeps the complete kindless immediate-template mapping and skips post-design distillation. Non-mirror skin remains project-controlled, while mirror reuses literal visual styling and permits only visible text replacement under an unchanged identity. Every distilled placeholder supplies explicit design-zone bounds independent of current Slide geometry. Atomic carriers retain matching Slide bindings; a final distilled composite object region stays ordinary and receives a hidden transparent binding proxy. The exporter validates prototype and cross-slide contracts, creates one reusable Layout per key, removes repeated inherited copies, and reads the finished package back to verify static/carrier rosters, backgrounds, placeholder identities, proxies, and default bounds.Current `create-template` output always rebuilds explicit SVG structure and does not package `native_structure.json` or `source_template.pptx`. `preserve` remains available only for existing projects that already carry the legacy pair.diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex a2ef773f..00fc06a2 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -71,7 +71,7 @@ Behavior:inputs and package-level processing.- For PPTX template-import workspaces, use `-s svg-flat` when you need a visual round-trip check. The layered `svg/` tree is the machine-readable template source and intentionally does not inline inherited master / layout decoration into each slide.- Native mode is strict about unsupported visual SVG elements: if a visual element cannot be represented or safely preserved, export fails with the SVG file, element tag, and position instead of silently dropping content.-- Omitting `--pptx-structure` reads `spec_lock.md` and falls back to `baseline`. New baseline projects carry one locked `pptx_layouts` row per page and compile their explicit SVG Master/Layout/placeholder metadata into real reusable Layouts. A legacy baseline project whose whole mapping section is absent keeps the coarse root `data-pptx-page-role` family pass plus conservative background/chrome promotion; filenames and ids remain compatibility fallbacks. Neither branch infers visual similarity. Template mode uses the same explicit compiler while also enforcing the selected input-template contract; both strict and adaptive template adherence stay on that mode.+- Omitting `--pptx-structure` reads `spec_lock.md` and falls back to `baseline`. Free-design baseline projects initially omit `pptx_layouts` and use the coarse root `data-pptx-page-role` family pass plus conservative background/chrome promotion. After explicit user page selection, `distill-layouts` writes one complete mapping with `distilled` contracts for selected pages and one empty `utility` Layout for unselected pages. Distillation-capable template projects also defer `pptx_layouts`: `page_layouts` selects the complete input SVG prototype, and post-design distillation writes `distilled` rows for every page. Deferred strict compares prototype structure/bounds; adaptive compares Master ids/topology/geometry and may author new design-zone bounds. A strict legacy selection with any bounds-missing prototype instead omits `layout_strategy` and uses a complete kindless immediate mapping. Non-mirror paint and typography follow `spec_lock`. Pending or partial distillation is blocked from export. No route infers visual similarity.- Template/preserve placeholder semantics distinguish title, subtitle, body, picture, chart, table, generic object, media, date, footer, and slide number. Reconstructed titles are normally type-matched without an index; explicit imported title indices and all other source indices are retained. Imported `subTitle`, `obj`, `media`, and `dt` identities remain distinct through `manifest.json`, `native_structure.json`, Layout XML, and Slide XML.- Baseline/template native export reads `spec_lock.md` typography into the PowerPoint theme: `title_family` becomes the major font and `body_family` / `font_family` becomes the minor font. Matching SVG text emits `+mj-*` / `+mn-*` tokens, while unrelated emphasis/code/brand families stay concrete. Preserve mode keeps the imported source theme; flat mode keeps fixed-font diagnostic output.- Structured baseline and template mode require numeric `typography.title` and `typography.body` rows. They write the title size to every Master `p:titleStyle` level and the body size to every `p:bodyStyle` / `p:otherStyle` level. Each generated Layout text placeholder also stores the prototype's first direct run size in `a:lstStyle/a:lvl1pPr/a:defRPr@sz` while retaining its prompt run size. Slide direct-run sizes remain unchanged. Missing title/body rows fail explicit Layout export; legacy baseline, preserve, and flat do not apply these updates.diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 8671f513..d2fc0059 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -179,8 +179,10 @@ try:native_structure_lock_errors as _native_structure_lock_errors,parse_optional_layout_slides as _parse_optional_layout_slides,parse_preserve_slides as _parse_preserve_structure_slides,+ parse_template_slide as _parse_template_structure_slide,parse_template_slides as _parse_template_structure_slides,template_lock_errors as _template_lock_errors,+ template_prototype_errors as _template_prototype_errors,validate_template_svg as _validate_template_structure_svg,)except ImportError:@@ -192,8 +194,10 @@ except ImportError:_native_structure_lock_errors = None_parse_optional_layout_slides = None_parse_preserve_structure_slides = None+ _parse_template_structure_slide = None_parse_template_structure_slides = None_template_lock_errors = None+ _template_prototype_errors = None_validate_template_structure_svg = Nonetry:@@ -1704,6 +1708,7 @@ class SVGQualityChecker:structure_attrs = {'data-pptx-layer','data-pptx-layout',+ 'data-pptx-layout-kind','data-pptx-layout-name','data-pptx-placeholder','data-pptx-placeholder-bounds',@@ -1717,27 +1722,28 @@ class SVGQualityChecker:):returnif root.get('data-pptx-layout') is not None:- if not any(- elem.get('data-pptx-placeholder') is not None- for elem in root.iter()- ):- result['warnings'].append(- "Mapped page declares data-pptx-layout but no data-pptx-placeholder "- "slot; its Layout exports without insertable placeholders. Mark the "- "page's real slots (title / subtitle / body / picture / slide-number "- "/ footer) unless the page genuinely has none."+ layout_kind = (root.get('data-pptx-layout-kind') or '').strip().lower()+ if layout_kind != 'utility':+ has_placeholder = any(+ elem.get('data-pptx-placeholder') is not None+ for elem in root.iter())- if not any(- elem.get('data-pptx-layer') is not None- for elem in root.iter()- ):- result['warnings'].append(- "Mapped page declares data-pptx-layout but no data-pptx-layer mark; "- "the exported Master gets no shared background/chrome and the Layout "- "gets no static framing. Mark the deck-wide background "- 'data-pptx-layer="master" and this layout key\'s framing '- 'data-pptx-layer="layout".'+ has_layout_layer = any(+ elem.get('data-pptx-layer') == 'layout'+ for elem in root.iter())+ if not has_placeholder and not has_layout_layer:+ result['warnings'].append(+ "Mapped page declares neither a reusable Layout layer nor a "+ "placeholder. Use a utility/freeform contract for an unselected "+ "page, or distill at least one real reusable design element."+ )+ elif not has_placeholder:+ result['warnings'].append(+ "Mapped Layout has reusable framing but no insertable placeholder. "+ "Keep it only when that static framing is the intended reusable "+ "contract."+ )if _validate_template_structure_svg is None:result['warnings'].append("Detected PPTX template structure metadata, but its validator "@@ -2214,6 +2220,7 @@ class SVGQualityChecker:if (structure_lock is not Noneand structure_lock.mode == 'template'+ and structure_lock.layout_strategy == 'distill'and structure_lock.template_adherence in {'strict', 'adaptive'}and _parse_spec_lock is not None):@@ -2222,12 +2229,19 @@ class SVGQualityChecker:page_layouts = lock.get('page_layouts', {})expected_pages = {f'P{index:02d}' for index in range(1, len(svg_files) + 1)}missing_pages = sorted(expected_pages - set(page_layouts))+ extra_pages = sorted(set(page_layouts) - expected_pages)if missing_pages:self._pptx_structure_issues.append(('error','spec_lock.md template export requires page_layouts ''rows for every generated page; missing: ' + ', '.join(missing_pages),))+ if target_path.is_dir() and extra_pages:+ self._pptx_structure_issues.append((+ 'error',+ 'spec_lock.md template export page_layouts references absent '+ 'generated pages: ' + ', '.join(extra_pages),+ ))template_dir = project_path / 'templates'template_svgs = {path.stem for path in template_dir.glob('*.svg')}missing_templates = sorted({@@ -2246,6 +2260,7 @@ class SVGQualityChecker:structure_attrs = {'data-pptx-layer','data-pptx-layout',+ 'data-pptx-layout-kind','data-pptx-layout-name','data-pptx-placeholder','data-pptx-placeholder-bounds',@@ -2280,6 +2295,67 @@ class SVGQualityChecker:and structure_lock is not Noneand structure_lock.layouts)+ distillation_locked = bool(+ baseline_mode+ and structure_lock is not None+ and structure_lock.layout_strategy == 'distill'+ )+ template_distillation_pending = bool(+ locked_mode == 'template'+ and structure_lock is not None+ and structure_lock.layout_strategy == 'distill'+ and not structure_lock.layouts+ )+ if template_distillation_pending:+ premature_kinds = []+ for svg_path in svg_files:+ try:+ root = ET.parse(svg_path).getroot()+ except (OSError, ET.ParseError):+ continue+ if root.get('data-pptx-layout-kind') is not None:+ premature_kinds.append(svg_path.name)+ if premature_kinds:+ self._pptx_structure_issues.append((+ 'error',+ 'template Layout distillation is still pending, but final '+ 'data-pptx-layout-kind metadata already appears on: '+ + ', '.join(premature_kinds),+ ))+ if (+ not premature_kinds+ and _parse_template_structure_slide is not None+ and _template_prototype_errors is not None+ ):+ try:+ pending_specs = [+ _parse_template_structure_slide(svg_path, index)+ for index, svg_path in enumerate(svg_files, start=1)+ ]+ except _TemplateStructureError as exc:+ self._pptx_structure_issues.append(('error', str(exc)))+ else:+ self._pptx_structure_issues.extend(+ ('error', message)+ for message in _template_prototype_errors(+ pending_specs,+ structure_lock,+ require_complete_roster=target_path.is_dir(),+ )+ )+ return+ if (+ target_path.is_dir()+ and distillation_locked+ and (not baseline_layout_locked or not has_metadata)+ ):+ self._pptx_structure_issues.append((+ 'error',+ 'post-design Layout distillation is incomplete: write a complete '+ 'spec_lock.md pptx_layouts mapping and matching root Layout metadata '+ 'for every SVG before the project quality gate',+ ))+ returnif not has_metadata and not structure_locked and not baseline_layout_locked:return@@ -2329,6 +2405,15 @@ class SVGQualityChecker:('error', message)for message in _template_lock_errors(specs, structure_lock))+ if (+ locked_mode == 'template'+ and structure_lock.layout_strategy == 'distill'+ and _template_prototype_errors is not None+ ):+ self._pptx_structure_issues.extend(+ ('error', message)+ for message in _template_prototype_errors(specs, structure_lock)+ )if locked_mode != 'preserve':returnif (@@ -2380,11 +2465,12 @@ class SVGQualityChecker:messages.append(f"layout keys {joined} declare identical static Layout framing ""and placeholder contracts; they compile to duplicate Layouts. "- "Either merge them into one composition key (spec_lock.md "- "pptx_layouts + each SVG root), or — when the compositions "- "genuinely differ — promote each key's distinguishing zone "- 'framing (table backing panel, column panels, hero frame) to '- 'data-pptx-layer="layout" so the keys diverge.'+ "Either merge them into one reusable key (spec_lock.md "+ "pptx_layouts + each SVG root), or — when their reusable "+ "contracts genuinely differ — assign distinct explicit default "+ "placeholder bounds and/or mark only truly stable framing as "+ 'data-pptx-layer="layout". Slide-local content geometry does not '+ "define a Layout.")return messages@@ -2395,6 +2481,7 @@ class SVGQualityChecker:root = ET.parse(str(svg_path)).getroot()except (OSError, ET.ParseError):return None+ layout_kind = (root.get('data-pptx-layout-kind') or '').strip().lower()layout_parts = []placeholder_parts = []for child in list(root):@@ -2406,15 +2493,28 @@ class SVGQualityChecker:layout_parts.append(re.sub(r'\s+', ' ', xml).strip())placeholder = child.get('data-pptx-placeholder')if placeholder is not None:+ explicit_bounds = child.get('data-pptx-placeholder-bounds') or ''+ fallback_geometry = ()+ if not explicit_bounds and layout_kind != 'distilled':+ fallback_geometry = (+ child.get('data-pptx-text-bounds') or '',+ child.get('x') or '',+ child.get('y') or '',+ child.get('width') or '',+ child.get('height') or '',+ )placeholder_parts.append((placeholder,child.tag.rsplit('}', 1)[-1],- child.get('x') or '',- child.get('y') or '',- child.get('data-pptx-placeholder-bounds') or '',+ explicit_bounds,child.get('data-pptx-placeholder-idx') or '',+ fallback_geometry,))- return (tuple(layout_parts), tuple(sorted(placeholder_parts)))+ return (+ layout_kind,+ tuple(layout_parts),+ tuple(sorted(placeholder_parts)),+ )def _check_illustration_resource_contract(self, dir_path: Path) -> None:"""Project-level illustration resource checks."""@@ -2864,6 +2964,14 @@ class SVGQualityChecker:f"{svg_file.name}: reusable templates require root ""data-pptx-layout-name metadata",))+ if root.get('data-pptx-layout-kind') is not None:+ self._template_issues.append((+ 'error',+ 'deck_instance_layout_kind',+ f"{svg_file.name}: reusable template prototypes must omit "+ "data-pptx-layout-kind; downstream completed pages receive "+ "distilled/utility during post-design finalization",+ ))has_structure_child = any(child.get('data-pptx-layer') in {'master', 'layout'}or child.get('data-pptx-placeholder')@@ -2876,6 +2984,20 @@ class SVGQualityChecker:f"{svg_file.name}: reusable templates require at least one ""direct master/layout/placeholder declaration",))+ missing_bounds = [+ child.get('id') or child.tag.rsplit('}', 1)[-1]+ for child in list(root)+ if child.get('data-pptx-placeholder') is not None+ and child.get('data-pptx-placeholder-bounds') is None+ ]+ if missing_bounds:+ self._template_issues.append((+ 'warning',+ 'placeholder_bounds_missing',+ f"{svg_file.name}: newly created reusable templates require "+ "explicit design-zone data-pptx-placeholder-bounds; missing: "+ + ', '.join(missing_bounds),+ ))if native_contract_path.exists() != source_template_path.exists():self._template_issues.append(('error',@@ -3340,8 +3462,10 @@ class SVGQualityChecker:for _sev, kind, msg in warnings:print(f" [{kind}] {msg}")if not errors:- print(" No structural roster issues. Placeholder hints above are advisory only;")- print(" declare 'placeholders:' frontmatter in design_spec.md to silence them.")+ print(" No structural roster issues.")+ print(" Conventional placeholder-name hints may be declared through "+ "'placeholders:' frontmatter. Bounds warnings require explicit "+ "design-zone metadata; create-template treats them as blocking.")def _apply_aggregated_issue_counts(self):"""Mirror project-level aggregate issues into summary counters once."""diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.pyindex c04cfd1f..0a8e3ee5 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@@ -101,6 +101,7 @@ from .template_structure import (TemplateElementSpec,TemplateSlideSpec,TemplateStructureError,+ is_composite_distilled_placeholder,match_native_placeholders,parse_preserve_slides,parse_template_slides,@@ -477,6 +478,35 @@ def _shape_id(elem: ET.Element) -> str | None:return None+def _set_shape_name(elem: ET.Element, name: str) -> None:+ """Give one top-level shape a deterministic read-back identity."""+ for cnv in elem.iter(f"{{{PML_NS}}}cNvPr"):+ cnv.set("name", name)+ return+ raise TemplateStructureError(+ f"Cannot name structured shape {name!r}: p:cNvPr is missing"+ )+++def _top_level_shape_name_roster(root: ET.Element) -> tuple[str, ...]:+ """Return the exact visible top-level shape-name sequence for read-back."""+ sp_tree = root.find(f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")+ if sp_tree is None:+ raise TemplateStructureError("Structured part has no p:cSld/p:spTree")+ names: list[str] = []+ for child in sp_tree:+ if child.tag not in _TOP_LEVEL_SHAPE_TAGS:+ continue+ c_nv_pr = next(child.iter(f"{{{PML_NS}}}cNvPr"), None)+ name = c_nv_pr.get("name") if c_nv_pr is not None else None+ if not name:+ raise TemplateStructureError(+ "Structured part contains a top-level shape without a name"+ )+ names.append(name)+ return tuple(names)++def _top_level_shapes_by_id(root: ET.Element) -> dict[str, ET.Element]:sp_tree = root.find(f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")if sp_tree is None:@@ -1282,6 +1312,21 @@ def _slide_sp_tree(state: _TemplateRuntimeSlide) -> ET.Element:return sp_tree+def _append_shape_to_runtime_slide(+ state: _TemplateRuntimeSlide,+ elem: ET.Element,+) -> None:+ """Append a generated helper shape to one Slide with fresh object ids."""+ existing_ids = [+ int(cnv.attrib["id"])+ for cnv in state.root.iter(f"{{{PML_NS}}}cNvPr")+ if cnv.attrib.get("id", "").isdigit()+ ]+ clone = ET.fromstring(ET.tostring(elem, encoding="utf-8"))+ _renumber_shape_ids(clone, max(existing_ids, default=1) + 1)+ _slide_sp_tree(state).append(clone)++def _presentation_slide_size_emu(extract_dir: Path) -> tuple[int, int]:"""Return the package slide size in EMU."""presentation_path = extract_dir / "ppt" / "presentation.xml"@@ -1377,7 +1422,7 @@ def _remove_template_shape(def _move_template_background(states: list[_TemplateRuntimeSlide],target_path: Path,-) -> None:+) -> str:backgrounds = [_extract_slide_background_xml(state.slide_path.read_text(encoding="utf-8"))for state in states@@ -1423,6 +1468,7 @@ def _move_template_background("during explicit Layout structure assembly")c_sld.remove(background)+ return background_xmldef _move_template_solid_background_shapes(@@ -1430,14 +1476,14 @@ def _move_template_solid_background_shapes(shapes: list[ET.Element],target_path: Path,slide_size_emu: tuple[int, int],-) -> bool:+) -> str | None:"""Move repeated full-slide solid rects into a master/layout p:bg."""backgrounds = [_solid_background_xml_from_shape(shape, slide_size_emu)for shape in shapes]if not any(backgrounds):- return False+ return Noneif any(background is None for background in backgrounds):raise TemplateStructureError("A template background resolves to a full-slide solid rect on only "@@ -1451,7 +1497,7 @@ def _move_template_solid_background_shapes()background_xml = backgrounds[0]if background_xml is None:- return False+ return Nonetarget_xml = target_path.read_text(encoding="utf-8")updated = _put_background_on_part(target_xml, background_xml)if updated is None:@@ -1461,7 +1507,7 @@ def _move_template_solid_background_shapes(target_path.write_text(updated, encoding="utf-8")for state, shape in zip(states, shapes):_remove_template_shape(state, shape)- return True+ return background_xmldef _set_slide_tree_background(@@ -1489,9 +1535,9 @@ def _set_slide_tree_background(def _apply_template_slide_backgrounds(states: list[_TemplateRuntimeSlide],slide_size_emu: tuple[int, int],-) -> int:+) -> dict[str, str]:"""Compile one-page solid backgrounds into slide-level p:bg."""- applied = 0+ applied: dict[str, str] = {}for state in states:items = [item for item in state.spec.elements@@ -1503,12 +1549,20 @@ def _apply_template_slide_backgrounds(shape = _template_shape_for_item(state, item)if shape is None:c_sld = state.root.find(f"{{{PML_NS}}}cSld")- if c_sld is None or c_sld.find(f"{{{PML_NS}}}bg") is None:+ background = (+ c_sld.find(f"{{{PML_NS}}}bg")+ if c_sld is not None+ else None+ )+ if background is None:raise TemplateStructureError(f"{state.spec.svg_path.name}: slide background disappeared ""during explicit Layout structure assembly")- applied += 1+ applied[f"ppt/slides/slide{state.spec.slide_num}.xml"] = ET.tostring(+ background,+ encoding="unicode",+ )continuebackground_xml = _solid_background_xml_from_shape(shape, slide_size_emu)if background_xml is None:@@ -1518,7 +1572,7 @@ def _apply_template_slide_backgrounds()_remove_template_shape(state, shape)_set_slide_tree_background(state, background_xml)- applied += 1+ applied[f"ppt/slides/slide{state.spec.slide_num}.xml"] = background_xmlreturn applied@@ -1528,27 +1582,28 @@ def _move_template_static_shape(target_path: Path,target_rels_path: Path,slide_size_emu: tuple[int, int],-) -> None:+) -> str | None:shapes = [_template_shape_for_item(state, item) for state in states]if any(shape is None for shape in shapes):if not all(shape is None for shape in shapes):raise TemplateStructureError(f"{item.element_id}: structure item is a background on only some slides")- _move_template_background(states, target_path)- return+ return _move_template_background(states, target_path)resolved_shapes = [shape for shape in shapes if shape is not None]- if (- item.is_background- and _move_template_solid_background_shapes(+ if item.is_background:+ background_xml = _move_template_solid_background_shapes(states,resolved_shapes,target_path,slide_size_emu,)- ):- return+ if background_xml is None:+ raise TemplateStructureError(+ f"{item.element_id!r} must compile to one exact p:bg payload"+ )+ return background_xmlcanonical = {_canonical_shape_xml(shape, state.rels)for state, shape in zip(states, resolved_shapes)@@ -1579,9 +1634,11 @@ def _move_template_static_shape(prototype_state.rels,target_rels_path,)+ _set_shape_name(target_shape, f"{item.element_id} {item.layer.title()}")_append_shape_to_part(target_path, target_shape)for state, shape in zip(states, resolved_shapes):_remove_template_shape(state, shape)+ return Nonedef _shape_bounds_emu(@@ -1866,6 +1923,64 @@ def _layout_placeholder_shape(return shape+def _distilled_binding_proxy(+ layout_placeholder: ET.Element,+ item: TemplateElementSpec,+) -> ET.Element:+ """Bind a Layout slot invisibly while leaving its visible carrier ordinary.++ An unbound object placeholder can leak its inherited empty frame into a+ finished Slide in non-PowerPoint renderers. A hidden matching proxy suppresses+ that inheritance. The zero-width transparent run avoids a LibreOffice empty-+ placeholder black fill without adding visible content.+ """+ proxy = ET.fromstring(ET.tostring(layout_placeholder, encoding="utf-8"))+ c_nv_pr = next(proxy.iter(f"{{{PML_NS}}}cNvPr"), None)+ if c_nv_pr is None:+ raise TemplateStructureError(+ f"Cannot create distilled binding for {item.element_id!r}: "+ "p:cNvPr is missing"+ )+ placeholder = proxy.find(f".//{{{PML_NS}}}ph")+ if placeholder is None:+ raise TemplateStructureError(+ f"Cannot create distilled binding for {item.element_id!r}: "+ "p:ph is missing"+ )+ c_nv_pr.set(+ "name",+ "Distilled Binding "+ f"{placeholder.get('type', 'body')} {placeholder.get('idx', '0')}",+ )+ c_nv_pr.set("hidden", "1")+ tx_body = proxy.find(f"{{{PML_NS}}}txBody")+ if tx_body is None:+ raise TemplateStructureError(+ f"Cannot create distilled binding for {item.element_id!r}: "+ "p:txBody is missing"+ )+ for child in list(tx_body):+ if child.tag == f"{{{DML_NS}}}p":+ tx_body.remove(child)+ paragraph = ET.SubElement(tx_body, f"{{{DML_NS}}}p")+ run = ET.SubElement(paragraph, f"{{{DML_NS}}}r")+ run_props = ET.SubElement(+ run,+ f"{{{DML_NS}}}rPr",+ {"lang": "en-US", "sz": "100"},+ )+ solid_fill = ET.SubElement(run_props, f"{{{DML_NS}}}solidFill")+ color = ET.SubElement(solid_fill, f"{{{DML_NS}}}srgbClr", {"val": "FFFFFF"})+ ET.SubElement(color, f"{{{DML_NS}}}alpha", {"val": "0"})+ ET.SubElement(run, f"{{{DML_NS}}}t").text = "\u200b"+ ET.SubElement(+ paragraph,+ f"{{{DML_NS}}}endParaRPr",+ {"lang": "en-US"},+ )+ return proxy++def _patch_slide_placeholder(shape: ET.Element,item: TemplateElementSpec,@@ -1960,13 +2075,15 @@ def _apply_explicit_layout_structure(theme_font_spec: ThemeFontSpec | None,*,verbose: bool = False,-) -> None:+) -> tuple[dict[str, str | None], dict[str, tuple[str, ...]]]:"""Materialize explicit SVG master/layout/placeholder metadata into OOXML."""states = _template_runtime_slides(extract_dir, specs, conversion_traces)states_by_slide = {state.spec.slide_num: state for state in states}slide_size_emu = _presentation_slide_size_emu(extract_dir)master_items = specs[0].master_elements+ expected_backgrounds: dict[str, str | None] = {}+ expected_shape_rosters: dict[str, tuple[str, ...]] = {}states_by_master: dict[str, list[_TemplateRuntimeSlide]] = {}for state in states:master_part = structure.slide_master_part(state.spec.slide_num)@@ -1974,21 +2091,27 @@ def _apply_explicit_layout_structure(for master_part, master_states in states_by_master.items():master_path = extract_dir / master_partmaster_rels_path = _relationships_path_for_part(extract_dir, master_part)+ expected_backgrounds[master_part] = _extract_slide_background_xml(+ master_path.read_text(encoding="utf-8")+ )_clear_master_placeholder_shapes(master_path)for item in master_items:- _move_template_static_shape(+ background_xml = _move_template_static_shape(master_states,item,master_path,master_rels_path,slide_size_emu,)+ if background_xml is not None:+ expected_backgrounds[master_part] = background_xmlspecs_by_layout: dict[str, list[TemplateSlideSpec]] = {}for spec in specs:specs_by_layout.setdefault(spec.layout_key, []).append(spec)placeholder_count = 0layout_shape_count = 0+ created_layout_parts: set[str] = set()for layout_key, layout_specs in specs_by_layout.items():layout_states = [states_by_slide[spec.slide_num] for spec in layout_specs]master_parts = {@@ -2014,6 +2137,7 @@ def _apply_explicit_layout_structure()layout_path = extract_dir / layout_partlayout_rels_path = _relationships_path_for_part(extract_dir, layout_part)+ created_layout_parts.add(layout_part)placeholder_bindings = {binding.element.element_id: binding@@ -2021,13 +2145,15 @@ def _apply_explicit_layout_structure(}for item in prototype.elements:if item.layer == "layout":- _move_template_static_shape(+ background_xml = _move_template_static_shape(layout_states,item,layout_path,layout_rels_path,slide_size_emu,)+ if background_xml is not None:+ expected_backgrounds[layout_part] = background_xmllayout_shape_count += 1continueif not item.placeholder:@@ -2053,24 +2179,64 @@ def _apply_explicit_layout_structure(f"{state.spec.svg_path.name}: placeholder {item.element_id!r} ""did not produce a shape")- _patch_slide_placeholder(- shape,+ composite_distilled_carrier = is_composite_distilled_placeholder(item,- assigned_idx,- theme_font_spec=theme_font_spec,+ prototype.layout_kind,)+ if not composite_distilled_carrier:+ _patch_slide_placeholder(+ shape,+ item,+ assigned_idx,+ theme_font_spec=theme_font_spec,+ )+ if prototype.layout_kind == "distilled":+ _set_shape_name(+ shape,+ f"{item.element_id} Distilled Carrier",+ )+ else:+ _set_shape_name(+ shape,+ f"{item.element_id} Distilled Carrier",+ )+ _append_shape_to_runtime_slide(+ state,+ _distilled_binding_proxy(layout_placeholder, item),+ )placeholder_count += 1_set_template_layout_header_footer(layout_path, prototype.placeholders)for state in layout_states:_set_slide_layout_target(state.rels_path, layout_target)- slide_background_count = _apply_template_slide_backgrounds(+ slide_backgrounds = _apply_template_slide_backgrounds(states,slide_size_emu,)+ expected_backgrounds.update(slide_backgrounds)for state in states:_write_xml_tree(state.slide_path, state.tree)+ expected_backgrounds.setdefault(+ f"ppt/slides/slide{state.spec.slide_num}.xml",+ None,+ )+ expected_shape_rosters[+ f"ppt/slides/slide{state.spec.slide_num}.xml"+ ] = _top_level_shape_name_roster(state.root)+ for part in states_by_master:+ expected_backgrounds.setdefault(+ part,+ _extract_slide_background_xml(+ (extract_dir / part).read_text(encoding="utf-8")+ ),+ )+ for part in created_layout_parts:+ expected_backgrounds.setdefault(part, None)+ for part in (*states_by_master, *created_layout_parts):+ expected_shape_rosters[part] = _top_level_shape_name_roster(+ ET.parse(extract_dir / part).getroot()+ )if verbose:print(@@ -2078,9 +2244,10 @@ def _apply_explicit_layout_structure(f"{len(specs_by_layout)} layout(s), "f"{len(master_items)} master element(s), "f"{layout_shape_count} layout element(s), "- f"{slide_background_count} slide background(s), "+ f"{len(slide_backgrounds)} slide background(s), "f"{placeholder_count} placeholder definition(s)")+ return expected_backgrounds, expected_shape_rostersdef _apply_preserved_structure(@@ -3510,6 +3677,10 @@ def create_pptx_with_native_svg(native_structure_contract.layout(spec.layout_key)else:template_specs = None+ template_background_expectations: dict[str, str | None] | None = None+ template_shape_roster_expectations: (+ dict[str, tuple[str, ...]] | None+ ) = Noneif template_specs is not None and not native_objects:native_placeholders = sorted({item.placeholder@@ -4164,7 +4335,10 @@ def create_pptx_with_native_svg(raise TemplateStructureError("Structured baseline metadata was not parsed before export")- _apply_explicit_layout_structure(+ (+ template_background_expectations,+ template_shape_roster_expectations,+ ) = _apply_explicit_layout_structure(extract_dir,structure,template_specs,@@ -4221,7 +4395,10 @@ def create_pptx_with_native_svg(raise TemplateStructureError("Template structure metadata was not parsed before export")- _apply_explicit_layout_structure(+ (+ template_background_expectations,+ template_shape_roster_expectations,+ ) = _apply_explicit_layout_structure(extract_dir,structure,template_specs,@@ -4359,7 +4536,12 @@ def create_pptx_with_native_svg("Explicit Layout metadata was not parsed before validation")try:- validate_pptx_template_package(temp_output_path, template_specs)+ validate_pptx_template_package(+ temp_output_path,+ template_specs,+ expected_backgrounds=template_background_expectations,+ expected_shape_rosters=template_shape_roster_expectations,+ )except ValueError as exc:context = ("Structured baseline"diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.pyindex 6a449cff..8b416b08 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@@ -55,6 +55,7 @@ from .template_structure import (parse_preserve_slides,parse_template_slides,template_lock_errors,+ template_prototype_errors,)from ..animation_config import (load_animation_config,@@ -277,8 +278,9 @@ Recorded narration:'matching SVG metadata are present; otherwise it promotes safe repeated ''background/chrome and extracts conservative semantic page-role layout ''families (legacy filenames/ids remain fallbacks); '- 'template consumes explicit '- 'data-pptx-layout/layer/placeholder metadata to build reusable layouts; '+ 'template consumes finalized explicit '+ 'data-pptx-layout/layer/placeholder metadata to build reusable layouts '+ '(a deferred page_layouts prototype contract must be distilled first); ''preserve is legacy compatibility for imported source packages; ''flat leaves generated structure slide-local for debugging/comparison.'),@@ -368,7 +370,7 @@ Recorded narration:structure_lock = Nonenative_structure_contract = Nonepptx_structure = args.pptx_structure- if pptx_structure is None or pptx_structure == 'preserve':+ if pptx_structure is None or pptx_structure in {'template', 'preserve'}:try:structure_lock = load_pptx_structure_lock(project_path)except TemplateStructureError as exc:@@ -376,6 +378,14 @@ Recorded narration:return 1if pptx_structure is None:pptx_structure = structure_lock.mode if structure_lock else 'baseline'+ elif (+ pptx_structure == 'template'+ and structure_lock is not None+ and structure_lock.mode != 'template'+ ):+ # Keep the explicit diagnostic override for non-template projects, but+ # never detach a real template project from its pending/ready lock.+ structure_lock = Noneelif pptx_structure == 'preserve':if structure_lock is None or structure_lock.mode != 'preserve':print(@@ -456,7 +466,7 @@ Recorded narration:# A diagnostic baseline override may bypass a stale or damaged# template/preserve lock. A valid baseline lock remains# authoritative, so its pptx_layouts mapping cannot be silently- # downgraded to the legacy page-role route.+ # downgraded to the unmapped page-role route.try:candidate_lock = load_pptx_structure_lock(project_path)except TemplateStructureError:@@ -465,6 +475,18 @@ Recorded narration:structure_lock = candidate_locklocked_layouts = structure_lock.layouts if structure_lock is not None else ()+ if (+ structure_lock is not None+ and structure_lock.layout_strategy == 'distill'+ and (baseline_layout_specs is None or not locked_layouts)+ ):+ print(+ "Error: post-design Layout distillation is incomplete; add a "+ "complete spec_lock.md pptx_layouts mapping and matching "+ "data-pptx-layout metadata before export",+ file=sys.stderr,+ )+ return 1if baseline_layout_specs is None:if locked_layouts:print(@@ -504,6 +526,18 @@ Recorded narration:pptx_structure in {'template', 'preserve'}and structure_lock is not None):+ if (+ pptx_structure == 'template'+ and structure_lock.layout_strategy == 'distill'+ and not structure_lock.layouts+ ):+ print(+ "Error: template Layout distillation is still pending; run the "+ "distill-layouts workflow to write the complete pptx_layouts "+ "mapping and final SVG Layout metadata before export",+ file=sys.stderr,+ )+ return 1try:template_specs = (parse_preserve_slides(native_files)@@ -519,6 +553,19 @@ Recorded narration:for message in lock_errors:print(f" {message}", file=sys.stderr)return 1+ prototype_errors = template_prototype_errors(+ template_specs,+ structure_lock,+ )+ if prototype_errors:+ print(+ "Error: distilled template structure does not match page_layouts "+ "prototypes:",+ file=sys.stderr,+ )+ for message in prototype_errors:+ print(f" {message}", file=sys.stderr)+ return 1if pptx_structure == 'preserve':if native_structure_contract is None:print("Error: preserve mode contract is unavailable", file=sys.stderr)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.pyindex a8e4b35e..0d66d953 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@@ -2,7 +2,7 @@"""PPT Master - Template Structure Metadata-Parse and validate explicit SVG metadata consumed by template-mode PPTX export.+Parse and validate explicit SVG metadata consumed by structured PPTX export.Usage:Imported by svg_to_pptx.pptx_package.builder and svg_quality_checker.py.@@ -36,6 +36,7 @@ _NON_VISUAL_TAGS = frozenset({"defs", "title", "desc", "metadata", "style"})_STRUCTURE_ATTRS = frozenset({"data-pptx-layer","data-pptx-layout",+ "data-pptx-layout-kind","data-pptx-layout-name","data-pptx-placeholder","data-pptx-placeholder-bounds",@@ -93,6 +94,44 @@ _LOCK_ROW_RE = re.compile(r"^-\s+([A-Za-z0-9_]+)\s*:\s*(.+?)\s*$")_LOCK_PAGE_RE = re.compile(r"^P(\d+)$")PPTX_STRUCTURE_MODES = frozenset({"baseline", "template", "preserve", "flat"})TEMPLATE_ADHERENCE_MODES = frozenset({"strict", "adaptive"})+LAYOUT_STRATEGIES = frozenset({"distill"})+DISTILLED_LAYOUT_KINDS = frozenset({"distilled", "utility"})+_TEMPLATE_SKIN_ATTRS = frozenset({+ "color",+ "fill",+ "fill-opacity",+ "filter",+ "font-family",+ "font-size",+ "font-style",+ "font-weight",+ "letter-spacing",+ "opacity",+ "paint-order",+ "stop-color",+ "stop-opacity",+ "stroke",+ "stroke-dasharray",+ "stroke-dashoffset",+ "stroke-linecap",+ "stroke-linejoin",+ "stroke-miterlimit",+ "stroke-opacity",+ "stroke-width",+ "style",+ "text-decoration",+ "word-spacing",+})+_CSS_RULE_RE = re.compile(r"(?s)([^{}]+)\{([^{}]*)\}")+_CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)+_CSS_ID_RE = re.compile(r"#([A-Za-z_][A-Za-z0-9_-]*)")+_CSS_CLASS_RE = re.compile(r"\.([A-Za-z_][A-Za-z0-9_-]*)")+_CSS_ATTR_RE = re.compile(+ r"\[\s*([A-Za-z_:][A-Za-z0-9_.:-]*)"+ r"(?:\s*(?:[~|^$*]?=)\s*(['\"]?)([^\]'\"]+)\2)?\s*\]"+)+_CSS_URL_RE = re.compile(r"url\(\s*(['\"]?)(.*?)\1\s*\)", re.IGNORECASE)+_CSS_TAG_RE = re.compile(r"(?:^|[\s>+~])([A-Za-z_][A-Za-z0-9_-]*|\*)")NATIVE_STRUCTURE_SCHEMA = "ppt-master.native-structure.v1"OOXML_UINT32_MAX = (1 << 32) - 1@@ -108,6 +147,17 @@ class PptxLayoutReference:slide_num: intlayout_key: strlayout_name: str | None = None+ layout_kind: str | None = None+++@dataclass(frozen=True)+class PptxPrototypeReference:+ """One spec_lock page-to-template-SVG prototype declaration."""++ slide_num: int+ template_basename: str+ svg_path: Path+ replication_mode: str | None = None@dataclass(frozen=True)@@ -117,8 +167,10 @@ class PptxStructureLock:mode: strtemplate_adherence: str | None = Nonelayouts: tuple[PptxLayoutReference, ...] = ()+ prototypes: tuple[PptxPrototypeReference, ...] = ()source_template: Path | None = Nonenative_structure: Path | None = None+ layout_strategy: str | None = None@dataclass(frozen=True)@@ -196,6 +248,7 @@ class TemplateSlideSpec:layout_key: strlayout_name: strelements: tuple[TemplateElementSpec, ...]+ layout_kind: str | None = None@propertydef master_elements(self) -> tuple[TemplateElementSpec, ...]:@@ -218,6 +271,31 @@ class TemplateSlideSpec:)+def _is_composite_distilled_placeholder_contract(+ tag: str,+ placeholder: str | None,+ layout_kind: str | None,+) -> bool:+ """Return whether raw SVG metadata declares a composite region proxy."""+ return (+ layout_kind == "distilled"+ and tag == "g"+ and placeholder == "object"+ )+++def is_composite_distilled_placeholder(+ item: TemplateElementSpec,+ layout_kind: str | None,+) -> bool:+ """Return the single parsed-contract predicate for a composite region proxy."""+ return _is_composite_distilled_placeholder_contract(+ item.tag,+ item.placeholder,+ layout_kind,+ )++@dataclass(frozen=True)class TemplatePlaceholderBinding:"""Resolved PowerPoint identity for one template placeholder."""@@ -378,8 +456,31 @@ def _portable_project_file(return resolved+def _template_replication_mode(template_dir: Path) -> str | None:+ """Read the optional replication mode from template design frontmatter."""+ spec_path = template_dir / "design_spec.md"+ try:+ lines = spec_path.read_text(encoding="utf-8").splitlines()+ except OSError:+ return None+ if not lines or lines[0].strip() != "---":+ return None+ for line in lines[1:]:+ stripped = line.strip()+ if stripped == "---":+ return None+ match = re.fullmatch(+ r"replication_mode\s*:\s*[\"']?(standard|fidelity|mirror)[\"']?",+ stripped,+ flags=re.IGNORECASE,+ )+ if match:+ return match.group(1).lower()+ return None++def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:- """Load optional pptx_structure/pptx_layouts sections from spec_lock.md."""+ """Load optional native-structure sections from spec_lock.md."""lock_path = project_path / "spec_lock.md"if not lock_path.is_file():return None@@ -396,7 +497,11 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:current_section = line[3:].strip()sections.setdefault(current_section, [])continue- if current_section not in {"pptx_structure", "pptx_layouts"}:+ if current_section not in {+ "pptx_structure",+ "pptx_layouts",+ "page_layouts",+ }:continuematch = _LOCK_ROW_RE.fullmatch(line)if match:@@ -404,13 +509,17 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:structure_rows = sections.get("pptx_structure", [])layout_rows = sections.get("pptx_layouts", [])+ prototype_rows = sections.get("page_layouts", [])structure_section_present = "pptx_structure" in sectionslayout_section_present = "pptx_layouts" in sections+ prototype_section_present = "page_layouts" in sectionsif (not structure_rowsand not layout_rows+ and not prototype_rowsand not structure_section_presentand not layout_section_present+ and not prototype_section_present):return Nonemode_rows = [value.strip().lower() for key, value in structure_rows if key == "mode"]@@ -448,6 +557,29 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:"adaptive template use must export through template mode")+ strategy_rows = [+ value.strip().lower()+ for key, value in structure_rows+ if key == "layout_strategy"+ ]+ if len(strategy_rows) > 1:+ raise TemplateStructureError(+ "spec_lock.md pptx_structure allows at most one "+ "'- layout_strategy:' row"+ )+ layout_strategy = strategy_rows[0] if strategy_rows else None+ if layout_strategy and layout_strategy not in LAYOUT_STRATEGIES:+ allowed = ", ".join(sorted(LAYOUT_STRATEGIES))+ raise TemplateStructureError(+ "spec_lock.md pptx_structure.layout_strategy must be one of: "+ f"{allowed}"+ )+ if layout_strategy and mode not in {"baseline", "template"}:+ raise TemplateStructureError(+ "spec_lock.md pptx_structure.layout_strategy is allowed only when "+ "mode is baseline or template"+ )+source_rows = [value for key, value in structure_rows if key == "source_template"]@@ -480,6 +612,67 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:"when pptx_structure.mode is preserve")+ prototypes: list[PptxPrototypeReference] = []+ seen_prototype_slides: set[int] = set()+ template_dir = (project_path / "templates").resolve()+ template_replication_mode = _template_replication_mode(template_dir)+ if mode != "template" and prototype_rows:+ raise TemplateStructureError(+ "spec_lock.md page_layouts is allowed only when pptx_structure.mode "+ "is template"+ )+ parsed_prototype_rows = (+ prototype_rows+ if mode == "template" and layout_strategy == "distill"+ else []+ )+ for page_key, raw_value in parsed_prototype_rows:+ page_match = _LOCK_PAGE_RE.fullmatch(page_key)+ if not page_match or int(page_match.group(1)) <= 0:+ raise TemplateStructureError(+ f"spec_lock.md page_layouts key {page_key!r} must be P<NN>"+ )+ slide_num = int(page_match.group(1))+ if slide_num in seen_prototype_slides:+ raise TemplateStructureError(+ f"spec_lock.md page_layouts repeats page P{slide_num:02d}"+ )+ seen_prototype_slides.add(slide_num)+ raw_basename = raw_value.strip()+ basename = (+ raw_basename[:-4]+ if raw_basename.lower().endswith(".svg")+ else raw_basename+ )+ if (+ not basename+ or basename in {".", ".."}+ or "/" in basename+ or "\\" in basename+ or any(ord(char) < 0x20 for char in basename)+ ):+ raise TemplateStructureError(+ f"spec_lock.md P{slide_num:02d} has invalid template SVG basename "+ f"{raw_basename!r}"+ )+ svg_path = (template_dir / f"{basename}.svg").resolve()+ if svg_path.parent != template_dir or not svg_path.is_file():+ raise TemplateStructureError(+ f"spec_lock.md P{slide_num:02d} references missing template SVG "+ f"templates/{basename}.svg"+ )+ prototypes.append(PptxPrototypeReference(+ slide_num=slide_num,+ template_basename=basename,+ svg_path=svg_path,+ replication_mode=template_replication_mode,+ ))++ if mode == "template" and layout_strategy == "distill" and not prototypes:+ raise TemplateStructureError(+ "spec_lock.md template mode requires one page_layouts row per page"+ )+references: list[PptxLayoutReference] = []seen_slides: set[int] = set()for page_key, raw_value in layout_rows:@@ -494,32 +687,69 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:f"spec_lock.md pptx_layouts repeats page P{slide_num:02d}")seen_slides.add(slide_num)- value_parts = raw_value.split("|", 1)- layout_key = value_parts[0].strip()- layout_name = value_parts[1].strip() if len(value_parts) == 2 else None+ layout_key, separator, remainder = raw_value.partition("|")+ layout_key = layout_key.strip()+ layout_name = remainder.strip() if separator else None+ layout_kind = None+ if layout_strategy == "distill" and separator:+ name_part, kind_separator, kind_part = remainder.rpartition("|")+ if kind_separator:+ layout_name = name_part.strip()+ layout_kind = kind_part.strip().lower()if not _LAYOUT_KEY_RE.fullmatch(layout_key):raise TemplateStructureError(f"spec_lock.md P{slide_num:02d} has invalid layout key "f"{layout_key!r}")- if len(value_parts) == 2 and not layout_name:+ if separator and not layout_name:raise TemplateStructureError(f"spec_lock.md P{slide_num:02d} has an empty layout name")+ if layout_strategy == "distill" and separator and not layout_kind:+ raise TemplateStructureError(+ f"spec_lock.md P{slide_num:02d} distilled mapping must end with "+ "'| distilled' or '| utility'"+ )+ if layout_kind and layout_kind not in DISTILLED_LAYOUT_KINDS:+ allowed = ", ".join(sorted(DISTILLED_LAYOUT_KINDS))+ raise TemplateStructureError(+ f"spec_lock.md P{slide_num:02d} layout kind must be one of: "+ f"{allowed}"+ )references.append(PptxLayoutReference(slide_num=slide_num,layout_key=layout_key,layout_name=layout_name,+ layout_kind=layout_kind,))- if mode in {"template", "preserve"} and not references:+ deferred_template = mode == "template" and layout_strategy == "distill"+ if deferred_template and template_adherence not in TEMPLATE_ADHERENCE_MODES:+ raise TemplateStructureError(+ "spec_lock.md deferred template distillation requires exactly one "+ "template_adherence row: strict or adaptive"+ )+ if mode in {"template", "preserve"} and not references and not deferred_template:raise TemplateStructureError(f"spec_lock.md {mode} mode requires one pptx_layouts row per page")+ if deferred_template and layout_section_present and not references:+ raise TemplateStructureError(+ "spec_lock.md deferred template distillation must omit the whole "+ "pptx_layouts section while pending; an empty section is invalid"+ )+ if deferred_template and any(+ reference.layout_name is None for reference in references+ ):+ raise TemplateStructureError(+ "spec_lock.md deferred template pptx_layouts rows require "+ "'<layout_key> | <PowerPoint layout name> | distilled'"+ )if mode == "baseline" and layout_section_present and not references:raise TemplateStructureError("spec_lock.md baseline pptx_layouts section must contain one row per "- "page; omit the whole section only for a legacy baseline project"+ "page; omit the whole section for an undistilled or legacy baseline "+ "project")if mode == "baseline" and any(reference.layout_name is None for reference in references@@ -528,6 +758,59 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:"spec_lock.md baseline pptx_layouts rows require ""'<layout_key> | <PowerPoint layout name>'")+ if layout_strategy == "distill" and mode == "baseline":+ if not references:+ raise TemplateStructureError(+ "spec_lock.md layout_strategy: distill requires a complete "+ "pptx_layouts mapping"+ )+ if any(reference.layout_kind is None for reference in references):+ raise TemplateStructureError(+ "spec_lock.md layout_strategy: distill requires every pptx_layouts "+ "row to end with '| distilled' or '| utility'"+ )+ if not any(+ reference.layout_kind == "distilled" for reference in references+ ):+ raise TemplateStructureError(+ "spec_lock.md layout_strategy: distill requires at least one "+ "user-selected distilled Layout"+ )+ utility_keys = {+ reference.layout_key+ for reference in references+ if reference.layout_kind == "utility"+ }+ if len(utility_keys) > 1:+ raise TemplateStructureError(+ "spec_lock.md layout_strategy: distill allows at most one shared "+ "utility Layout key; found: " + ", ".join(sorted(utility_keys))+ )+ if layout_strategy == "distill" and mode == "template" and references:+ non_distilled = sorted({+ reference.layout_kind or "<missing>"+ for reference in references+ if reference.layout_kind != "distilled"+ })+ if non_distilled:+ raise TemplateStructureError(+ "spec_lock.md deferred template distillation requires every "+ "pptx_layouts row to end with '| distilled'; found: "+ + ", ".join(non_distilled)+ )+ layout_kinds_by_key: dict[str, set[str | None]] = {}+ for reference in references:+ layout_kinds_by_key.setdefault(reference.layout_key, set()).add(+ reference.layout_kind+ )+ mixed_kind_keys = sorted(+ key for key, kinds in layout_kinds_by_key.items() if len(kinds) > 1+ )+ if mixed_kind_keys:+ raise TemplateStructureError(+ "spec_lock.md reuses layout key(s) with different layout kinds: "+ + ", ".join(mixed_kind_keys)+ )if mode == "flat" and layout_section_present:raise TemplateStructureError("spec_lock.md pptx_layouts section is not allowed when "@@ -536,7 +819,9 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:return PptxStructureLock(mode=mode,template_adherence=template_adherence,+ layout_strategy=layout_strategy,layouts=tuple(sorted(references, key=lambda item: item.slide_num)),+ prototypes=tuple(sorted(prototypes, key=lambda item: item.slide_num)),source_template=source_template,native_structure=native_structure,)@@ -770,6 +1055,7 @@ def _validate_placeholder_element(*,svg_path: Path,element_id: str,+ layout_kind: str | None,) -> None:tag = _local_tag(elem)if placeholder in _TEXT_PLACEHOLDERS and tag != "text":@@ -787,10 +1073,21 @@ def _validate_placeholder_element(f"{svg_path.name}: {element_id} media placeholder must be declared ""on a direct <image> or nested crop <svg> element")- if placeholder == "object" and tag not in _OBJECT_PLACEHOLDER_TAGS:+ composite_distilled_object = _is_composite_distilled_placeholder_contract(+ tag,+ placeholder,+ layout_kind,+ )+ if (+ placeholder == "object"+ and tag not in _OBJECT_PLACEHOLDER_TAGS+ and not composite_distilled_object+ ):raise TemplateStructureError(f"{svg_path.name}: {element_id} object placeholder must resolve to "- "one direct text, image, or basic SVG shape"+ "one direct text, image, or basic SVG shape; only a completed "+ "distilled Layout may use one direct group as a Layout-only region "+ "proxy")if placeholder in {"chart", "table"}:native_kind = (elem.get("data-pptx-native") or "").strip().lower()@@ -823,7 +1120,7 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:layout_key = (root.get("data-pptx-layout") or "").strip()if not layout_key:raise TemplateStructureError(- f"{svg_path.name}: template export requires root data-pptx-layout"+ f"{svg_path.name}: explicit Layout export requires root data-pptx-layout")if not _LAYOUT_KEY_RE.fullmatch(layout_key):raise TemplateStructureError(@@ -833,11 +1130,26 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:layout_name = (root.get("data-pptx-layout-name") or "").strip()if not layout_name:layout_name = re.sub(r"[-_.]+", " ", layout_key).strip().title() or layout_key+ layout_kind_raw = root.get("data-pptx-layout-kind")+ layout_kind = (layout_kind_raw or "").strip().lower() or None+ if layout_kind_raw is not None and layout_kind is None:+ raise TemplateStructureError(+ f"{svg_path.name}: data-pptx-layout-kind cannot be empty"+ )+ if layout_kind and layout_kind not in DISTILLED_LAYOUT_KINDS:+ allowed = ", ".join(sorted(DISTILLED_LAYOUT_KINDS))+ raise TemplateStructureError(+ f"{svg_path.name}: data-pptx-layout-kind must be one of: {allowed}"+ )illegal_root_attrs = sorted(attr for attr in _STRUCTURE_ATTRSif (- attr not in {"data-pptx-layout", "data-pptx-layout-name"}+ attr not in {+ "data-pptx-layout",+ "data-pptx-layout-kind",+ "data-pptx-layout-name",+ }and root.get(attr) is not None))@@ -854,7 +1166,7 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:duplicate_ids = sorted(element_id for element_id, count in id_counts.items() if count > 1)if duplicate_ids:raise TemplateStructureError(- f"{svg_path.name}: duplicate SVG id(s) are not allowed in template mode: "+ f"{svg_path.name}: duplicate SVG id(s) are not allowed in explicit Layout mode: "+ ", ".join(duplicate_ids))@@ -866,7 +1178,7 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:if nested_attrs:element_id = elem.get("id") or _local_tag(elem) or "<unnamed>"raise TemplateStructureError(- f"{svg_path.name}: {element_id} uses template metadata below the SVG "+ f"{svg_path.name}: {element_id} uses Layout metadata below the SVG ""root; structure metadata is allowed only on direct children")@@ -894,11 +1206,12 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:if (elem.get("data-pptx-layout") is not None+ or elem.get("data-pptx-layout-kind") is not Noneor elem.get("data-pptx-layout-name") is not None):raise TemplateStructureError(- f"{svg_path.name}: data-pptx-layout and data-pptx-layout-name belong "- "on the root <svg> only"+ f"{svg_path.name}: data-pptx-layout, data-pptx-layout-name, and "+ "data-pptx-layout-kind belong on the root <svg> only")if layer and layer not in _LAYERS:raise TemplateStructureError(@@ -941,7 +1254,7 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:)if (effective_layer or placeholder) and not element_id:raise TemplateStructureError(- f"{svg_path.name}: direct <{tag}> with template metadata requires an id"+ f"{svg_path.name}: direct <{tag}> with Layout metadata requires an id")if editable_raw is not None:if not effective_layer or editable_raw.strip().lower() != "false":@@ -972,12 +1285,19 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:placeholder,svg_path=svg_path,element_id=element_id,+ layout_kind=layout_kind,)placeholder_bounds = _parse_placeholder_bounds(bounds_raw,svg_path=svg_path,element_id=element_id or tag,)+ if layout_kind == "distilled" and placeholder and placeholder_bounds is None:+ raise TemplateStructureError(+ f"{svg_path.name}: distilled Layout placeholder {element_id!r} "+ "requires explicit data-pptx-placeholder-bounds; derive the "+ "reusable frame from the design zone, not the current text bounds"+ )placeholder_idx = _parse_placeholder_idx(placeholder_idx_raw,svg_path=svg_path,@@ -1004,17 +1324,33 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:]if len(backgrounds) > 1:raise TemplateStructureError(- f"{svg_path.name}: template mode allows at most one {scope} "+ f"{svg_path.name}: explicit Layout mode allows at most one {scope} ""solid background")- return TemplateSlideSpec(+ spec = TemplateSlideSpec(slide_num=slide_num,svg_path=svg_path,layout_key=layout_key,layout_name=layout_name,+ layout_kind=layout_kind,elements=tuple(elements),)+ if layout_kind == "utility" and (spec.layout_elements or spec.placeholders):+ raise TemplateStructureError(+ f"{svg_path.name}: utility Layouts must contain zero Layout elements "+ "and placeholders"+ )+ if (+ layout_kind == "distilled"+ and not spec.layout_elements+ and not spec.placeholders+ ):+ raise TemplateStructureError(+ f"{svg_path.name}: distilled Layout must define at least one Layout "+ "element or placeholder"+ )+ return specdef parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:@@ -1024,7 +1360,9 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:for slide_num, svg_path in enumerate(svg_files, start=1)]if not specs:- raise TemplateStructureError("Template export requires at least one SVG slide")+ raise TemplateStructureError(+ "Explicit Layout export requires at least one SVG slide"+ )expected_master = tuple(item.contract_signature() for item in specs[0].master_elements@@ -1036,7 +1374,7 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:if actual_master != expected_master:raise TemplateStructureError(f"{spec.svg_path.name}: master layer contract differs from "- f"{specs[0].svg_path.name}; every template slide must repeat the same "+ f"{specs[0].svg_path.name}; every structured slide must repeat the same ""explicit master elements in the same order")@@ -1052,6 +1390,11 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:f"{spec.svg_path.name}: layout {layout_key!r} uses name "f"{spec.layout_name!r}, expected {prototype.layout_name!r}")+ if spec.layout_kind != prototype.layout_kind:+ raise TemplateStructureError(+ f"{spec.svg_path.name}: layout {layout_key!r} uses kind "+ f"{spec.layout_kind!r}, expected {prototype.layout_kind!r}"+ )if spec.layout_contract != prototype.layout_contract:raise TemplateStructureError(f"{spec.svg_path.name}: layout {layout_key!r} structure differs "@@ -1064,7 +1407,7 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:def parse_optional_layout_slides(svg_files: list[Path],) -> list[TemplateSlideSpec] | None:- """Parse an all-or-none explicit Layout contract, or return legacy absence."""+ """Parse an all-or-none Layout contract, or return unmapped baseline absence."""roots: list[tuple[Path, ET.Element]] = []has_structure_metadata = Falsefor svg_path in svg_files:@@ -1115,6 +1458,7 @@ def parse_optional_layout_slides(empty_layouts = sorted({spec.layout_keyfor spec in specs+ if spec.layout_kind != "utility"if not spec.layout_elements and not spec.placeholders})if empty_layouts:@@ -1180,6 +1524,746 @@ def template_lock_errors(f"does not match spec_lock P{spec.slide_num:02d} layout name "f"{reference.layout_name!r}")+ if spec.layout_kind != reference.layout_kind:+ errors.append(+ f"{spec.svg_path.name}: data-pptx-layout-kind="+ f"{spec.layout_kind!r} does not match spec_lock "+ f"P{spec.slide_num:02d} layout kind {reference.layout_kind!r}"+ )+ return errors+++def _signature_attr_value(+ name: str,+ value: str,+ *,+ svg_path: Path | None,+ asset_identity: bool,+) -> str:+ """Normalize portable asset references without weakening visual identity."""+ if name.rsplit("}", 1)[-1] != "href":+ return value+ if asset_identity:+ if value.startswith("#") or "://" in value:+ return value+ if value.startswith("data:"):+ return "data-sha256:" + hashlib.sha256(+ value.encode("utf-8")+ ).hexdigest()+ if svg_path is None:+ raise TemplateStructureError(+ "literal asset comparison requires the source SVG path"+ )+ asset_path = (svg_path.parent / value).resolve()+ if not asset_path.is_file():+ raise TemplateStructureError(+ f"{svg_path.name}: mirror asset reference does not resolve: "+ f"{value!r}"+ )+ return "file-sha256:" + _file_sha256(asset_path)+ if value.startswith("data:") or "://" in value:+ return value+ return value.replace("\\", "/").rsplit("/", 1)[-1]+++def _element_tree_signature(+ elem: ET.Element,+ *,+ include_skin: bool = False,+ include_text: bool = True,+ svg_path: Path | None = None,+ asset_identity: bool = False,+ ignore_structure_attrs: bool = False,+) -> tuple[object, ...]:+ """Return a stable structural or literal-visual SVG subtree signature."""+ text = (elem.text or "") if include_text else ""+ if _local_tag(elem) not in {"text", "tspan"} and not text.strip():+ text = ""+ attrs = tuple(sorted(+ (+ name,+ _signature_attr_value(+ name,+ value,+ svg_path=svg_path,+ asset_identity=asset_identity,+ ),+ )+ for name, value in elem.attrib.items()+ if (+ not (+ ignore_structure_attrs+ and name.rsplit("}", 1)[-1] in _STRUCTURE_ATTRS+ )+ and (+ include_skin+ or name.rsplit("}", 1)[-1] not in _TEMPLATE_SKIN_ATTRS+ )+ )+ ))+ return (+ elem.tag,+ attrs,+ text,+ tuple(+ _element_tree_signature(+ child,+ include_skin=include_skin,+ include_text=include_text,+ svg_path=svg_path,+ asset_identity=asset_identity,+ ignore_structure_attrs=ignore_structure_attrs,+ )+ for child in elem+ ),+ )+++def _svg_reference_ids(elem: ET.Element) -> set[str]:+ """Return fragment ids referenced anywhere in one SVG subtree."""+ references: set[str] = set()+ for node in elem.iter():+ for name, value in node.attrib.items():+ if name.rsplit("}", 1)[-1] == "href" and value.startswith("#"):+ references.add(value[1:])+ references.update(+ match.group(2)[1:]+ for match in _CSS_URL_RE.finditer(value)+ if match.group(2).startswith("#")+ )+ return references+++def _font_family_names(raw_value: str) -> set[str]:+ """Return normalized CSS font-family names from one declaration value."""+ return {+ value.strip().strip("'\"")+ for value in raw_value.split(",")+ if value.strip().strip("'\"")+ }+++def _font_families_from_declarations(raw: str) -> set[str]:+ """Return font families assigned by one inline or stylesheet declaration."""+ families: set[str] = set()+ for match in re.finditer(+ r"font-family\s*:\s*([^;{}]+)",+ raw,+ flags=re.IGNORECASE,+ ):+ families.update(_font_family_names(match.group(1)))+ return families+++def _scope_selector_tokens(+ root: ET.Element,+ elements: tuple[ET.Element, ...],+) -> tuple[set[str], set[str], set[str], list[dict[str, str]], set[str]]:+ """Collect the small selector vocabulary needed to filter SVG CSS rules."""+ ids: set[str] = set()+ classes: set[str] = set()+ tags: set[str] = set()+ attributes: list[dict[str, str]] = []+ font_families: set[str] = set()+ nodes = [root]+ for element in elements:+ nodes.extend(element.iter())+ for node in nodes:+ tags.add(_local_tag(node))+ node_id = (node.get("id") or "").strip()+ if node_id:+ ids.add(node_id)+ classes.update((node.get("class") or "").split())+ local_attrs = {+ name.rsplit("}", 1)[-1]: value+ for name, value in node.attrib.items()+ }+ attributes.append(local_attrs)+ if local_attrs.get("font-family"):+ font_families.update(+ _font_family_names(local_attrs["font-family"])+ )+ if local_attrs.get("style"):+ font_families.update(+ _font_families_from_declarations(local_attrs["style"])+ )+ return ids, classes, tags, attributes, font_families+++def _css_selector_matches_scope(+ selector: str,+ *,+ ids: set[str],+ classes: set[str],+ tags: set[str],+ attributes: list[dict[str, str]],+) -> bool:+ """Conservatively decide whether one simple SVG selector can affect scope."""+ selector_ids = set(_CSS_ID_RE.findall(selector))+ if selector_ids and not selector_ids.issubset(ids):+ return False+ selector_classes = set(_CSS_CLASS_RE.findall(selector))+ if selector_classes and not selector_classes.issubset(classes):+ return False+ for match in _CSS_ATTR_RE.finditer(selector):+ attr_name = match.group(1).rsplit(":", 1)[-1]+ expected = (match.group(3) or "").strip()+ if not any(+ attr_name in attrs+ and (not expected or attrs[attr_name].strip() == expected)+ for attrs in attributes+ ):+ return False+ selector_tags = {+ tag.lower()+ for tag in _CSS_TAG_RE.findall(selector)+ if tag != "*"+ }+ if selector_tags and not selector_tags.issubset(+ {tag.lower() for tag in tags}+ ):+ return False+ return True+++def _css_asset_signature(value: str, svg_path: Path) -> str:+ """Replace CSS URL assets with byte identities while retaining fragments."""+ def replace(match: re.Match[str]) -> str:+ target = match.group(2).strip()+ if target.startswith("#"):+ return f"url({target})"+ identity = _signature_attr_value(+ "href",+ target,+ svg_path=svg_path,+ asset_identity=True,+ )+ return f"url({identity})"++ return _CSS_URL_RE.sub(replace, value)+++def _normalize_css_declarations(raw: str, svg_path: Path) -> str:+ """Normalize formatting-only CSS differences without changing cascade order."""+ declarations: list[str] = []+ for raw_declaration in raw.split(";"):+ declaration = raw_declaration.strip()+ if not declaration:+ continue+ if ":" not in declaration:+ declarations.append(" ".join(declaration.split()))+ continue+ name, value = declaration.split(":", 1)+ normalized_value = " ".join(+ _css_asset_signature(value.strip(), svg_path).split()+ )+ declarations.append(f"{name.strip().lower()}:{normalized_value}")+ return ";".join(declarations)+++def _scope_css_signature(+ root: ET.Element,+ elements: tuple[ET.Element, ...],+ svg_path: Path,+) -> tuple[tuple[str, str], ...]:+ """Return only stylesheet rules that can affect the selected visual scope."""+ ids, classes, tags, attributes, font_families = _scope_selector_tokens(+ root,+ elements,+ )+ parsed_rules: list[tuple[str, str]] = []+ for style in root.iter():+ if _local_tag(style) != "style":+ continue+ css = _CSS_COMMENT_RE.sub("", style.text or "")+ for match in _CSS_RULE_RE.finditer(css):+ parsed_rules.append((match.group(1).strip(), match.group(2)))++ matched_selectors: dict[int, tuple[str, ...]] = {}+ for index, (raw_selector, body) in enumerate(parsed_rules):+ if raw_selector.startswith("@"):+ continue+ selectors = tuple(+ " ".join(selector.split())+ for selector in raw_selector.split(",")+ if _css_selector_matches_scope(+ selector,+ ids=ids,+ classes=classes,+ tags=tags,+ attributes=attributes,+ )+ )+ if selectors:+ matched_selectors[index] = selectors+ font_families.update(_font_families_from_declarations(body))++ rules: list[tuple[str, str]] = []+ for index, (raw_selector, body) in enumerate(parsed_rules):+ selectors = matched_selectors.get(index)+ if selectors is None:+ if not raw_selector.lower().startswith("@font-face"):+ continue+ declared_families = _font_families_from_declarations(body)+ if not declared_families.intersection(font_families):+ continue+ selectors = ("@font-face",)+ rules.append((+ ",".join(selectors),+ _normalize_css_declarations(body, svg_path),+ ))+ return tuple(rules)+++def _scope_visual_resources_signature(+ root: ET.Element,+ elements: tuple[ET.Element, ...],+ svg_path: Path,+) -> tuple[object, ...]:+ """Capture root inheritance, relevant CSS, and the referenced defs closure."""+ if not elements:+ return ()+ root_attrs = tuple(sorted(+ (+ name,+ _signature_attr_value(+ name,+ value,+ svg_path=svg_path,+ asset_identity=True,+ ),+ )+ for name, value in root.attrib.items()+ if (+ name.rsplit("}", 1)[-1] not in _STRUCTURE_ATTRS+ and not name.rsplit("}", 1)[-1].startswith("data-")+ )+ ))+ css_rules = _scope_css_signature(root, elements, svg_path)+ references: set[str] = set()+ for element in elements:+ references.update(_svg_reference_ids(element))+ for _selector, declarations in css_rules:+ references.update(+ match.group(2)[1:]+ for match in _CSS_URL_RE.finditer(declarations)+ if match.group(2).startswith("#")+ )++ definitions_by_id: dict[str, ET.Element] = {}+ for definitions in root.iter():+ if _local_tag(definitions) != "defs":+ continue+ for definition in definitions.iter():+ definition_id = (definition.get("id") or "").strip()+ if definition_id:+ definitions_by_id[definition_id] = definition++ pending = list(references)+ resolved: set[str] = set()+ while pending:+ reference = pending.pop()+ if reference in resolved:+ continue+ resolved.add(reference)+ definition = definitions_by_id.get(reference)+ if definition is not None:+ pending.extend(_svg_reference_ids(definition) - resolved)+ definition_signatures = tuple(+ (+ reference,+ _element_tree_signature(+ definitions_by_id[reference],+ include_skin=True,+ include_text=True,+ svg_path=svg_path,+ asset_identity=True,+ ) if reference in definitions_by_id else ("missing", reference),+ )+ for reference in sorted(resolved)+ )+ return root_attrs, css_rules, definition_signatures+++def _structure_subtree_signature(+ svg_path: Path,+ elements: tuple[TemplateElementSpec, ...],+ *,+ include_skin: bool = False,+ include_text: bool = True,+ asset_identity: bool = False,+) -> tuple[tuple[str, tuple[object, ...]], ...]:+ """Read structural or literal-visual signatures for direct SVG children."""+ try:+ root = ET.parse(svg_path).getroot()+ materialize_inline_geometry_properties(root)+ except (OSError, ET.ParseError, GeometryStyleError) as exc:+ raise TemplateStructureError(+ f"{svg_path.name}: unable to compare template prototype structure: {exc}"+ ) from exc+ direct_by_id = {+ (child.get("id") or "").strip(): child+ for child in root+ if (child.get("id") or "").strip()+ }+ signatures: list[tuple[str, tuple[object, ...]]] = []+ for item in elements:+ child = direct_by_id.get(item.element_id)+ if child is None:+ raise TemplateStructureError(+ f"{svg_path.name}: structure element {item.element_id!r} is no "+ "longer a direct SVG child"+ )+ signatures.append((+ item.element_id,+ _element_tree_signature(+ child,+ include_skin=include_skin,+ include_text=include_text,+ svg_path=svg_path,+ asset_identity=asset_identity,+ ),+ ))+ if include_skin:+ selected = tuple(+ direct_by_id[item.element_id]+ for item in elements+ if item.element_id in direct_by_id+ )+ signatures.append((+ "__visual_resources__",+ _scope_visual_resources_signature(root, selected, svg_path),+ ))+ return tuple(signatures)+++def _mirror_ordinary_slide_ids(spec: TemplateSlideSpec) -> set[str]:+ """Return stable ids that are ordinary Slide content in one mirror page."""+ try:+ root = ET.parse(spec.svg_path).getroot()+ except (OSError, ET.ParseError) as exc:+ raise TemplateStructureError(+ f"{spec.svg_path.name}: unable to inspect mirror page ownership: {exc}"+ ) from exc+ inherited_ids = {+ item.element_id+ for item in (+ *spec.master_elements,+ *spec.layout_elements,+ *spec.placeholders,+ )+ }+ return {+ element_id+ for child in root+ if _local_tag(child) not in _NON_VISUAL_TAGS+ if (element_id := (child.get("id") or "").strip())+ if element_id not in inherited_ids+ }+++def _mirror_slide_local_signature(+ spec: TemplateSlideSpec,+ protected_ids: set[str],+) -> tuple[tuple[object, ...], tuple[object, ...]]:+ """Capture literal mirror visuals that are Slide-local on either page.++ Visible text values may change, but their element topology, attributes,+ grouping, paint, geometry, and referenced asset bytes remain literal.+ Structure metadata may change when adaptive distillation promotes or+ demotes the same stable SVG id.+ """+ try:+ root = ET.parse(spec.svg_path).getroot()+ materialize_inline_geometry_properties(root)+ except (OSError, ET.ParseError, GeometryStyleError) as exc:+ raise TemplateStructureError(+ f"{spec.svg_path.name}: unable to compare mirror page visuals: {exc}"+ ) from exc+ slide_elements: list[ET.Element] = []+ slide_visuals: list[tuple[object, ...]] = []+ for child in root:+ tag = _local_tag(child)+ if tag in _NON_VISUAL_TAGS:+ continue+ element_id = (child.get("id") or "").strip()+ if element_id and element_id not in protected_ids:+ continue+ slide_elements.append(child)+ slide_visuals.append(+ _element_tree_signature(+ child,+ include_skin=True,+ include_text=False,+ svg_path=spec.svg_path,+ asset_identity=True,+ ignore_structure_attrs=True,+ )+ )+ resources = _scope_visual_resources_signature(+ root,+ tuple(slide_elements),+ spec.svg_path,+ )+ return resources, tuple(slide_visuals)+++def _prototype_placeholder_contract(+ spec: TemplateSlideSpec,+) -> tuple[tuple[object, ...], ...]:+ """Return the strict template placeholder contract without slide content."""+ return tuple(item.contract_signature() for item in spec.placeholders)+++def template_prototype_errors(+ specs: list[TemplateSlideSpec],+ structure_lock: PptxStructureLock,+ *,+ require_complete_roster: bool = True,+) -> list[str]:+ """Compare deferred-template pages with their selected SVG prototypes."""+ if (+ structure_lock.mode != "template"+ or structure_lock.layout_strategy != "distill"+ ):+ return []+ errors: list[str] = []+ prototypes = {+ reference.slide_num: reference+ for reference in structure_lock.prototypes+ }+ adherence = structure_lock.template_adherence or "strict"+ actual_slides = {spec.slide_num for spec in specs}+ prototype_slides = set(prototypes)+ missing_prototypes = sorted(actual_slides - prototype_slides)+ extra_prototypes = sorted(prototype_slides - actual_slides)+ if missing_prototypes:+ errors.append(+ "spec_lock.md page_layouts is missing generated page(s): "+ + ", ".join(f"P{slide_num:02d}" for slide_num in missing_prototypes)+ )+ if require_complete_roster and extra_prototypes:+ errors.append(+ "spec_lock.md page_layouts references absent page(s): "+ + ", ".join(f"P{slide_num:02d}" for slide_num in extra_prototypes)+ )+ for spec in specs:+ reference = prototypes.get(spec.slide_num)+ if reference is None:+ errors.append(+ f"{spec.svg_path.name}: spec_lock.md page_layouts is missing "+ f"prototype P{spec.slide_num:02d}"+ )+ continue+ try:+ prototype = parse_template_slide(reference.svg_path, spec.slide_num)+ except TemplateStructureError as exc:+ errors.append(str(exc))+ continue++ try:+ literal_visual = reference.replication_mode == "mirror"+ expected_master_structure = _structure_subtree_signature(+ prototype.svg_path,+ prototype.master_elements,+ include_skin=literal_visual,+ asset_identity=literal_visual,+ )+ actual_master_structure = _structure_subtree_signature(+ spec.svg_path,+ spec.master_elements,+ include_skin=literal_visual,+ asset_identity=literal_visual,+ )+ except TemplateStructureError as exc:+ errors.append(str(exc))+ continue+ if (+ tuple(item.contract_signature() for item in spec.master_elements)+ != tuple(+ item.contract_signature() for item in prototype.master_elements+ )+ or actual_master_structure != expected_master_structure+ ):+ errors.append(+ f"{spec.svg_path.name}: distilled template Master structure differs "+ f"from prototype {reference.svg_path.name}; strict and adaptive "+ "routes must retain its ids, topology, geometry, and content"+ + (" including mirror visual styling" if literal_visual else "")+ )++ if literal_visual:+ try:+ protected_slide_ids = (+ _mirror_ordinary_slide_ids(prototype)+ | _mirror_ordinary_slide_ids(spec)+ )+ expected_slide_visual = _mirror_slide_local_signature(+ prototype,+ protected_slide_ids,+ )+ actual_slide_visual = _mirror_slide_local_signature(+ spec,+ protected_slide_ids,+ )+ except TemplateStructureError as exc:+ errors.append(str(exc))+ continue+ if actual_slide_visual != expected_slide_visual:+ errors.append(+ f"{spec.svg_path.name}: mirror Slide-local non-text visuals "+ f"differ from prototype {reference.svg_path.name}; preserve "+ "grouping, geometry, paint, effects, and referenced asset "+ "identity, changing only visible text content"+ )++ try:+ expected_layout_structure = _structure_subtree_signature(+ prototype.svg_path,+ prototype.layout_elements,+ include_skin=literal_visual,+ asset_identity=literal_visual,+ )+ actual_layout_structure = _structure_subtree_signature(+ spec.svg_path,+ spec.layout_elements,+ include_skin=literal_visual,+ asset_identity=literal_visual,+ )+ if literal_visual:+ expected_placeholder_visual = _structure_subtree_signature(+ prototype.svg_path,+ prototype.placeholders,+ include_skin=True,+ include_text=False,+ asset_identity=True,+ )+ actual_placeholder_visual = _structure_subtree_signature(+ spec.svg_path,+ spec.placeholders,+ include_skin=True,+ include_text=False,+ asset_identity=True,+ )+ else:+ expected_placeholder_visual = ()+ actual_placeholder_visual = ()+ except TemplateStructureError as exc:+ errors.append(str(exc))+ continue++ placeholder_contract_same = (+ _prototype_placeholder_contract(spec)+ == _prototype_placeholder_contract(prototype)+ )+ layout_contract_same = (+ tuple(item.contract_signature() for item in spec.layout_elements)+ == tuple(+ item.contract_signature() for item in prototype.layout_elements+ )+ and actual_layout_structure == expected_layout_structure+ )+ placeholder_visual_same = (+ actual_placeholder_visual == expected_placeholder_visual+ )+ reusable_contract_same = (+ placeholder_contract_same+ and layout_contract_same+ and placeholder_visual_same+ )++ reuses_prototype_key = spec.layout_key == prototype.layout_key+ if adherence == "adaptive" and not reuses_prototype_key:+ if spec.layout_name == prototype.layout_name:+ errors.append(+ f"{spec.svg_path.name}: adaptive template distillation created "+ f"new layout key {spec.layout_key!r} but reused prototype picker "+ f"name {prototype.layout_name!r}; assign a new key and name to "+ "the evolved Layout contract"+ )+ if reusable_contract_same:+ errors.append(+ f"{spec.svg_path.name}: adaptive template distillation changed "+ "only the Layout key/name while the reusable static, "+ "placeholder, and default-bounds contract is unchanged; "+ f"reuse prototype identity {prototype.layout_key!r} / "+ f"{prototype.layout_name!r}"+ )+ continue++ missing_bounds = [+ item.element_id+ for item in prototype.placeholders+ if item.placeholder_bounds is None+ ]+ if missing_bounds:+ if adherence == "strict":+ errors.append(+ f"{reference.svg_path.name}: deferred strict template "+ "distillation requires explicit data-pptx-placeholder-bounds "+ "on every prototype placeholder; missing: "+ + ", ".join(missing_bounds)+ )+ else:+ errors.append(+ f"{spec.svg_path.name}: adaptive output reused prototype layout "+ f"key {prototype.layout_key!r}, but that prototype lacks explicit "+ "placeholder bounds; assign a new key and name to the evolved "+ "Layout contract"+ )+ continue+ if spec.layout_key != prototype.layout_key:+ errors.append(+ f"{spec.svg_path.name}: strict template distillation must keep "+ f"prototype layout key {prototype.layout_key!r}, found "+ f"{spec.layout_key!r}"+ )+ if spec.layout_name != prototype.layout_name:+ if adherence == "strict":+ errors.append(+ f"{spec.svg_path.name}: strict template distillation must keep "+ f"prototype layout name {prototype.layout_name!r}, found "+ f"{spec.layout_name!r}"+ )+ else:+ errors.append(+ f"{spec.svg_path.name}: adaptive output reused prototype layout "+ f"key {prototype.layout_key!r} but changed its picker name from "+ f"{prototype.layout_name!r} to {spec.layout_name!r}; assign a "+ "new key and name to the evolved Layout contract"+ )+ if not placeholder_contract_same:+ if adherence == "strict":+ errors.append(+ f"{spec.svg_path.name}: strict placeholder id/type/index/default-"+ f"bounds contract differs from prototype "+ f"{reference.svg_path.name}"+ )+ else:+ errors.append(+ f"{spec.svg_path.name}: adaptive output reused prototype layout "+ f"key {prototype.layout_key!r} but changed its placeholder "+ "contract; assign a new key and name"+ )+ if literal_visual and not placeholder_visual_same:+ errors.append(+ f"{spec.svg_path.name}: mirror placeholder geometry or visual "+ f"styling differs from prototype {reference.svg_path.name}; "+ "only visible text content may change under the reused Layout"+ )+ if not layout_contract_same:+ qualifier = "mirror visual/structural" if literal_visual else "structural"+ if adherence == "strict":+ errors.append(+ f"{spec.svg_path.name}: strict Layout {qualifier} contract "+ f"differs from prototype {reference.svg_path.name}"+ )+ else:+ errors.append(+ f"{spec.svg_path.name}: adaptive output reused prototype layout "+ f"key {prototype.layout_key!r} but changed its {qualifier} "+ "contract; assign a new key and name"+ )return errorsdiff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.pyindex 591415de..cfff1a0a 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport posixpathimport sysimport zipfile+from collections import Counterfrom dataclasses import dataclassfrom pathlib import Pathfrom urllib.parse import unquote, urlsplit@@ -40,6 +41,7 @@ from .template_structure import (TemplatePlaceholderBinding,TemplateSlideSpec,TemplateStructureError,+ is_composite_distilled_placeholder,template_placeholder_bindings,)@@ -50,13 +52,30 @@ REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"SLIDE_LAYOUT_REL_TYPE = ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout")+SLIDE_REL_TYPE = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"+)SLIDE_MASTER_REL_TYPE = ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster")SLIDE_LAYOUT_CONTENT_TYPE = ("application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml")+SLIDE_CONTENT_TYPE = (+ "application/vnd.openxmlformats-officedocument.presentationml.slide+xml"+)+SLIDE_MASTER_CONTENT_TYPE = (+ "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"+)PRESENTATION_COLLECTION_ID_MIN = 1 << 31+PRESENTATION_SLIDE_ID_MIN = 256+_TOP_LEVEL_VISIBLE_TAGS = frozenset({+ f"{{{PML_NS}}}sp",+ f"{{{PML_NS}}}pic",+ f"{{{PML_NS}}}graphicFrame",+ f"{{{PML_NS}}}grpSp",+ f"{{{PML_NS}}}cxnSp",+})@dataclass(frozen=True)@@ -137,6 +156,140 @@ class _PackageReader:return result+def _top_level_shape_names(+ root: ET.Element,+ context: str,+ errors: list[str],+) -> tuple[str, ...]:+ """Return deterministic names for every visible top-level OOXML shape."""+ c_sld = root.find(f"{{{PML_NS}}}cSld")+ shape_tree = (+ c_sld.find(f"{{{PML_NS}}}spTree") if c_sld is not None else None+ )+ if shape_tree is None:+ errors.append(f"{context} has no p:cSld/p:spTree")+ return ()+ names: list[str] = []+ for child in shape_tree:+ if child.tag not in _TOP_LEVEL_VISIBLE_TAGS:+ continue+ c_nv_pr = next(child.iter(f"{{{PML_NS}}}cNvPr"), None)+ name = c_nv_pr.get("name") if c_nv_pr is not None else None+ if not name:+ errors.append(f"{context} contains a top-level shape without a name")+ continue+ names.append(name)+ return tuple(names)+++def _validate_named_shape_roster(+ root: ET.Element,+ expected_names: set[str] | tuple[str, ...] | list[str],+ context: str,+ errors: list[str],+ *,+ exact: bool,+ ordered: bool = False,+) -> None:+ """Validate reusable structure and ordinary Slide carriers by stable name."""+ expected_sequence = tuple(expected_names)+ expected_set = set(expected_sequence)+ actual_names = _top_level_shape_names(root, context, errors)+ counts = Counter(actual_names)+ duplicates = sorted(name for name, count in counts.items() if count > 1)+ if duplicates:+ errors.append(+ f"{context} repeats structured shape name(s): " + ", ".join(duplicates)+ )+ actual_set = set(actual_names)+ missing = sorted(expected_set - actual_set)+ if missing:+ errors.append(+ f"{context} is missing structured shape(s): " + ", ".join(missing)+ )+ if exact:+ unexpected = sorted(actual_set - expected_set)+ if unexpected:+ errors.append(+ f"{context} contains unexpected shape(s): "+ + ", ".join(unexpected)+ )+ if ordered and not missing:+ actual_sequence = (+ actual_names+ if exact+ else tuple(name for name in actual_names if name in expected_set)+ )+ if actual_sequence != expected_sequence:+ errors.append(+ f"{context} structured shape order is {actual_sequence}, "+ f"expected {expected_sequence}"+ )+++def _top_level_shape_by_name(+ root: ET.Element,+ name: str,+) -> ET.Element | None:+ c_sld = root.find(f"{{{PML_NS}}}cSld")+ shape_tree = (+ c_sld.find(f"{{{PML_NS}}}spTree") if c_sld is not None else None+ )+ if shape_tree is None:+ return None+ for child in shape_tree:+ if child.tag not in _TOP_LEVEL_VISIBLE_TAGS:+ continue+ c_nv_pr = next(child.iter(f"{{{PML_NS}}}cNvPr"), None)+ if c_nv_pr is not None and c_nv_pr.get("name") == name:+ return child+ return None+++def _has_explicit_background(root: ET.Element) -> bool:+ c_sld = root.find(f"{{{PML_NS}}}cSld")+ return c_sld is not None and c_sld.find(f"{{{PML_NS}}}bg") is not None+++def _xml_payload_signature(elem: ET.Element) -> tuple[object, ...]:+ """Return a namespace-stable exact XML payload signature."""+ return (+ elem.tag,+ tuple(sorted(elem.attrib.items())),+ (elem.text or "").strip(),+ tuple(_xml_payload_signature(child) for child in elem),+ )+++def _background_payload_signatures(+ root: ET.Element,+) -> tuple[tuple[object, ...], ...]:+ c_sld = root.find(f"{{{PML_NS}}}cSld")+ backgrounds = (+ c_sld.findall(f"{{{PML_NS}}}bg")+ if c_sld is not None+ else []+ )+ return tuple(_xml_payload_signature(background) for background in backgrounds)+++def _expected_background_signature(+ background_xml: str,+) -> tuple[object, ...]:+ """Parse a standalone p:bg fragment regardless of its serialized prefix."""+ try:+ wrapper = ET.fromstring(+ f'<root xmlns:p="{PML_NS}" xmlns:a="{DML_NS}">'+ f"{background_xml}</root>"+ )+ except ET.ParseError as exc:+ raise ValueError(f"invalid expected p:bg payload: {exc}") from exc+ children = list(wrapper)+ if len(children) != 1 or children[0].tag != f"{{{PML_NS}}}bg":+ raise ValueError("expected background payload must contain exactly one p:bg")+ return _xml_payload_signature(children[0])++def _relationships_part_for(source_part: str) -> str:directory = posixpath.dirname(source_part)filename = posixpath.basename(source_part)@@ -461,6 +614,8 @@ def _validate_registered_part_roster(entries: list[ET.Element],expected_targets: set[str],context: str,+ *,+ min_id: int = PRESENTATION_COLLECTION_ID_MIN,) -> set[int]:relationships = [relationship@@ -513,8 +668,74 @@ def _validate_registered_part_roster(entries,context,reader.errors,- min_value=PRESENTATION_COLLECTION_ID_MIN,+ min_value=min_id,+ )+++def _numbered_part_family(+ names: frozenset[str],+ directory: str,+ stem: str,+) -> set[str]:+ """Return exact numbered XML parts such as slide12.xml in one directory."""+ prefix = f"{directory}/{stem}"+ parts: set[str] = set()+ for name in names:+ if not name.startswith(prefix) or not name.endswith(".xml"):+ continue+ number = name[len(prefix):-4]+ if (+ number.isdigit()+ and int(number) > 0+ and posixpath.dirname(name) == directory+ ):+ parts.add(name)+ return parts+++def _validate_physical_part_roster(+ reader: _PackageReader,+ expected_parts: set[str],+ directory: str,+ stem: str,+ context: str,+) -> None:+ actual_parts = _numbered_part_family(reader.names, directory, stem)+ if actual_parts != expected_parts:+ reader.errors.append(+ f"{context} physical part roster differs; "+ f"missing={sorted(expected_parts - actual_parts)}, "+ f"extra={sorted(actual_parts - expected_parts)}"+ )+++def _validate_content_type_part_roster(+ overrides: dict[str, list[str]],+ expected_parts: set[str],+ directory: str,+ stem: str,+ content_type: str,+ errors: list[str],+ context: str,+) -> None:+ family = _numbered_part_family(+ frozenset(name.lstrip("/") for name in overrides),+ directory,+ stem,)+ if family != expected_parts:+ errors.append(+ f"[Content_Types].xml {context} Override roster differs; "+ f"missing={sorted(expected_parts - family)}, "+ f"extra={sorted(family - expected_parts)}"+ )+ for part in sorted(expected_parts):+ values = overrides.get(f"/{part}", [])+ if values != [content_type]:+ errors.append(+ f"[Content_Types].xml must declare {part} exactly once as "+ f"{content_type}"+ )def _validate_presentation_master_registration(@@ -538,13 +759,43 @@ def _validate_presentation_master_registration()+def _validate_presentation_slide_registration(+ reader: _PackageReader,+ slide_parts: set[str],+) -> None:+ presentation_part = "ppt/presentation.xml"+ presentation_root = reader.xml(presentation_part)+ if presentation_root is None:+ return+ slide_id_entries = presentation_root.findall(+ f"{{{PML_NS}}}sldIdLst/{{{PML_NS}}}sldId"+ )+ _validate_registered_part_roster(+ reader,+ presentation_part,+ SLIDE_REL_TYPE,+ slide_id_entries,+ slide_parts,+ "Presentation p:sldIdLst",+ min_id=PRESENTATION_SLIDE_ID_MIN,+ )++def validate_pptx_template_package(pptx_path: str | Path,specs: list[TemplateSlideSpec],+ *,+ expected_backgrounds: dict[str, str | None] | None = None,+ expected_shape_rosters: dict[str, tuple[str, ...]] | None = None,) -> None:- """Validate a finished template-mode PPTX against its explicit SVG contract."""+ """Validate a finished structured PPTX against its explicit SVG contract.++ Export supplies pre-packaging background and shape expectations for exact+ serialization read-back. Callers that only have the finished package still+ receive the portable structure, ownership, and relationship checks.+ """if not specs:- raise ValueError("template package validation requires at least one slide spec")+ raise ValueError("structured package validation requires at least one slide spec")specs_by_layout: dict[str, list[TemplateSlideSpec]] = {}bindings_by_layout: dict[str, tuple[TemplatePlaceholderBinding, ...]] = {}@@ -564,6 +815,40 @@ def validate_pptx_template_package(with zipfile.ZipFile(path) as package:reader = _PackageReader(package, errors)overrides = _content_type_overrides(reader)+ if expected_backgrounds is not None:+ for part, background_xml in sorted(expected_backgrounds.items()):+ root = reader.xml(part)+ if root is None:+ continue+ if background_xml is None:+ expected_signatures: tuple[tuple[object, ...], ...] = ()+ else:+ try:+ expected_signatures = (+ _expected_background_signature(background_xml),+ )+ except ValueError as exc:+ errors.append(f"{part} {exc}")+ continue+ actual_signatures = _background_payload_signatures(root)+ if actual_signatures != expected_signatures:+ errors.append(+ f"{part} p:bg count/payload differs from the exact "+ "structured-export expectation"+ )+ if expected_shape_rosters is not None:+ for part, roster in sorted(expected_shape_rosters.items()):+ root = reader.xml(part)+ if root is None:+ continue+ _validate_named_shape_roster(+ root,+ roster,+ part,+ errors,+ exact=True,+ ordered=True,+ )layout_parts_by_key: dict[str, str] = {}keys_by_layout_part: dict[str, str] = {}slide_roots: dict[int, ET.Element] = {}@@ -612,7 +897,9 @@ def validate_pptx_template_package(used_master_parts: set[str] = set()layout_parts_by_master: dict[str, set[str]] = {}+ master_specs_by_part: dict[str, TemplateSlideSpec] = {}for layout_key, layout_specs in specs_by_layout.items():+ prototype = layout_specs[0]layout_part = layout_parts_by_key.get(layout_key)if layout_part is None:errors.append(f"layout key {layout_key!r} has no resolved Layout part")@@ -640,6 +927,20 @@ def validate_pptx_template_package(f"{expected_name!r}")+ if layout_specs[0].layout_kind == "utility" and c_sld is not None:+ if c_sld.find(f"{{{PML_NS}}}bg") is not None:+ errors.append(+ f"{layout_part} utility Layout must not define a background"+ )+ shape_tree = c_sld.find(f"{{{PML_NS}}}spTree")+ if shape_tree is not None and any(+ child.tag in _TOP_LEVEL_VISIBLE_TAGS+ for child in shape_tree+ ):+ errors.append(+ f"{layout_part} utility Layout must not contain shapes"+ )+override_values = overrides.get(f"/{layout_part}", [])if override_values != [SLIDE_LAYOUT_CONTENT_TYPE]:errors.append(@@ -661,20 +962,172 @@ def validate_pptx_template_package(f"Layout {layout_key!r}",errors,)+ expected_layout_names = tuple(+ f"{item.element_id} Layout"+ if item.layer == "layout"+ else f"{item.element_id} Placeholder"+ for item in prototype.elements+ if (+ (item.layer == "layout" and not item.is_background)+ or item.placeholder+ )+ )+ _validate_named_shape_roster(+ layout_root,+ expected_layout_names,+ f"Layout {layout_key!r}",+ errors,+ exact=True,+ ordered=True,+ )+ expected_layout_background = any(+ item.is_background for item in prototype.layout_elements+ )+ actual_layout_background = _has_explicit_background(layout_root)+ if actual_layout_background != expected_layout_background:+ errors.append(+ f"Layout {layout_key!r} background ownership is "+ f"{actual_layout_background}, expected "+ f"{expected_layout_background} from the SVG contract"+ )+ if (+ expected_layout_background+ and expected_backgrounds is not None+ and layout_part not in expected_backgrounds+ ):+ errors.append(+ f"Layout {layout_key!r} has no pre-promotion p:bg payload "+ "for exact read-back"+ )slide_placeholders: dict[int, dict[int, _Placeholder]] = {}for spec in layout_specs:slide_root = slide_roots.get(spec.slide_num)if slide_root is None:continue+ # Atomic distilled carriers bind directly. A composite+ # object region remains ordinary and uses one hidden,+ # transparent matching proxy to suppress empty inherited+ # placeholder paint in non-PowerPoint renderers.+ expected_slide_bindings = bindingsslide_placeholders[spec.slide_num] = _validate_placeholder_roster(slide_root,- bindings,+ expected_slide_bindings,f"Slide {spec.slide_num}",errors,is_layout=False,)+ expected_slide_background = any(+ item.layer == "slide" and item.is_background+ for item in spec.elements+ )+ actual_slide_background = _has_explicit_background(slide_root)+ if actual_slide_background != expected_slide_background:+ errors.append(+ f"Slide {spec.slide_num} background ownership is "+ f"{actual_slide_background}, expected "+ f"{expected_slide_background} from the SVG contract"+ )+ slide_part = f"ppt/slides/slide{spec.slide_num}.xml"+ if (+ expected_slide_background+ and expected_backgrounds is not None+ and slide_part not in expected_backgrounds+ ):+ errors.append(+ f"Slide {spec.slide_num} has no pre-promotion p:bg "+ "payload for exact read-back"+ )+ if spec.layout_kind == "distilled":+ expected_distilled_names = [+ f"{item.element_id} Distilled Carrier"+ for item in spec.placeholders+ ]+ expected_distilled_names.extend(+ "Distilled Binding "+ f"{binding.placeholder_type} {binding.effective_idx}"+ for binding in bindings+ if is_composite_distilled_placeholder(+ binding.element,+ spec.layout_kind,+ )+ )+ _validate_named_shape_roster(+ slide_root,+ expected_distilled_names,+ f"Slide {spec.slide_num}",+ errors,+ exact=False,+ ordered=True,+ )+ bindings_by_element = {+ binding.element.element_id: binding+ for binding in bindings+ }+ for item in spec.placeholders:+ carrier_name = (+ f"{item.element_id} Distilled Carrier"+ )+ carrier = _top_level_shape_by_name(+ slide_root,+ carrier_name,+ )+ carrier_placeholder = (+ carrier.find(f".//{{{PML_NS}}}ph")+ if carrier is not None+ else None+ )+ composite_object = is_composite_distilled_placeholder(+ item,+ spec.layout_kind,+ )+ if composite_object:+ if carrier_placeholder is not None:+ errors.append(+ f"Slide {spec.slide_num} composite carrier "+ f"{carrier_name!r} must remain ordinary"+ )+ elif carrier is not None and carrier_placeholder is None:+ errors.append(+ f"Slide {spec.slide_num} atomic carrier "+ f"{carrier_name!r} must own its p:ph binding"+ )+ placeholder_binding = bindings_by_element[+ item.element_id+ ]+ if not composite_object:+ continue+ binding_name = (+ "Distilled Binding "+ f"{placeholder_binding.placeholder_type} "+ f"{placeholder_binding.effective_idx}"+ )+ binding_shape = _top_level_shape_by_name(+ slide_root,+ binding_name,+ )+ if binding_shape is None:+ continue+ c_nv_pr = next(+ binding_shape.iter(f"{{{PML_NS}}}cNvPr"),+ None,+ )+ if (+ c_nv_pr is None+ or c_nv_pr.get("hidden", "0").lower()+ not in {"1", "true"}+ ):+ errors.append(+ f"Slide {spec.slide_num} binding proxy "+ f"{binding_name!r} must be hidden"+ )+ if binding_shape.find(+ f".//{{{PML_NS}}}ph"+ ) is None:+ errors.append(+ f"Slide {spec.slide_num} binding proxy "+ f"{binding_name!r} has no p:ph"+ )- prototype = layout_specs[0]prototype_placeholders = slide_placeholders.get(prototype.slide_num,{},@@ -683,7 +1136,12 @@ def validate_pptx_template_package(idx = binding.effective_idxlayout_placeholder = layout_placeholders.get(idx)prototype_placeholder = prototype_placeholders.get(idx)- if layout_placeholder is None or prototype_placeholder is None:+ if is_composite_distilled_placeholder(+ binding.element,+ prototype.layout_kind,+ ):+ prototype_placeholder = None+ if layout_placeholder is None:continuecontext = (f"Layout {layout_key!r} placeholder "@@ -699,13 +1157,19 @@ def validate_pptx_template_package(round(value * EMU_PER_PX)for value in binding.element.placeholder_bounds)- else:+ elif prototype_placeholder is not None:expected_bounds = _shape_bounds(prototype_placeholder.shape,f"Slide {prototype.slide_num} placeholder "f"{binding.element.element_id!r}",errors,)+ else:+ expected_bounds = None+ errors.append(+ f"{context} has neither explicit bounds nor a bound "+ "prototype Slide placeholder"+ )if (actual_bounds is not Noneand expected_bounds is not None@@ -716,22 +1180,31 @@ def validate_pptx_template_package(f"{expected_bounds}")- prototype_size = _first_run_size(prototype_placeholder.shape)- if prototype_size is not None:- prompt_size = _first_run_size(layout_placeholder.shape)+ prompt_size = _first_run_size(layout_placeholder.shape)+ default_size = _level_one_default_size(+ layout_placeholder.shape+ )+ if prototype_placeholder is not None:+ prototype_size = _first_run_size(+ prototype_placeholder.shape+ )+ if prototype_size is None:+ continueif prompt_size != prototype_size:errors.append(f"{context} prompt size is {prompt_size!r}, expected "f"{prototype_size!r}")- default_size = _level_one_default_size(- layout_placeholder.shape- )if default_size != prototype_size:errors.append(f"{context} level-1 default size is "f"{default_size!r}, expected {prototype_size!r}")+ elif prompt_size is not None and default_size != prompt_size:+ errors.append(+ f"{context} level-1 default size is {default_size!r}, "+ f"expected its prompt size {prompt_size!r}"+ )master_target = _single_relationship_target(reader,@@ -752,6 +1225,7 @@ def validate_pptx_template_package(continuereader.xml(master_part)used_master_parts.add(master_part)+ master_specs_by_part.setdefault(master_part, prototype)layout_parts_by_master.setdefault(master_part, set()).add(layout_part)@@ -761,6 +1235,40 @@ def validate_pptx_template_package(master_root = reader.xml(master_part)if master_root is None:continue+ master_spec = master_specs_by_part.get(master_part)+ if master_spec is not None:+ _validate_named_shape_roster(+ master_root,+ tuple(+ f"{item.element_id} Master"+ for item in master_spec.master_elements+ if not item.is_background+ ),+ f"Master {master_part}",+ errors,+ exact=True,+ ordered=True,+ )+ expected_master_background = any(+ item.is_background+ for item in master_spec.master_elements+ )+ if (+ expected_master_background+ and not _has_explicit_background(master_root)+ ):+ errors.append(+ f"Master {master_part} is missing its explicit background"+ )+ if (+ expected_master_background+ and expected_backgrounds is not None+ and master_part not in expected_backgrounds+ ):+ errors.append(+ f"Master {master_part} has no pre-promotion p:bg payload "+ "for exact read-back"+ )layout_id_entries = master_root.findall(f"{{{PML_NS}}}sldLayoutIdLst/"f"{{{PML_NS}}}sldLayoutId"@@ -784,10 +1292,64 @@ def validate_pptx_template_package(f"{previous_owner} and {master_part}")+ expected_slide_parts = {+ f"ppt/slides/slide{spec.slide_num}.xml"+ for spec in specs+ }+ expected_layout_parts = set(layout_parts_by_key.values())+ _validate_physical_part_roster(+ reader,+ expected_slide_parts,+ "ppt/slides",+ "slide",+ "Slide",+ )+ _validate_physical_part_roster(+ reader,+ expected_layout_parts,+ "ppt/slideLayouts",+ "slideLayout",+ "Layout",+ )+ _validate_physical_part_roster(+ reader,+ used_master_parts,+ "ppt/slideMasters",+ "slideMaster",+ "Master",+ )+ _validate_content_type_part_roster(+ overrides,+ expected_slide_parts,+ "ppt/slides",+ "slide",+ SLIDE_CONTENT_TYPE,+ errors,+ "Slide",+ )+ _validate_content_type_part_roster(+ overrides,+ expected_layout_parts,+ "ppt/slideLayouts",+ "slideLayout",+ SLIDE_LAYOUT_CONTENT_TYPE,+ errors,+ "Layout",+ )+ _validate_content_type_part_roster(+ overrides,+ used_master_parts,+ "ppt/slideMasters",+ "slideMaster",+ SLIDE_MASTER_CONTENT_TYPE,+ errors,+ "Master",+ )+ _validate_presentation_slide_registration(reader, expected_slide_parts)_validate_presentation_master_registration(reader, used_master_parts)except (OSError, zipfile.BadZipFile) as exc:raise ValueError(f"cannot read template PPTX package {path}: {exc}") from excif errors:details = "\n".join(f" - {error}" for error in errors)- raise ValueError(f"template package read-back failed:\n{details}")+ raise ValueError(f"structured package read-back failed:\n{details}")diff --git a/skills/ppt-master/templates/design_spec_reference.md b/skills/ppt-master/templates/design_spec_reference.mdindex 45f83eb8..1ad9836e 100644--- a/skills/ppt-master/templates/design_spec_reference.md+++ b/skills/ppt-master/templates/design_spec_reference.md@@ -306,6 +306,8 @@ Catalog read: 76 templates## IX. Content Outline+> **Native Layout boundary**: Each `Layout` line below describes visual composition intent, not a final PowerPoint Layout key. Free-design/brand-only pages stay unconstrained during SVG authoring. Template pages select an input prototype through `page_layouts`. Distillation-capable template routes defer the final output mapping, and [`distill-layouts`](../workflows/distill-layouts.md) writes reusable native Layouts only from completed pages. A strict legacy selection whose prototype lacks explicit placeholder bounds instead uses the Strategist's planning-time kindless immediate mapping and does not enter deferred distillation.+### Part 1: [Chapter Name]#### Slide 01 - Coverdiff --git a/skills/ppt-master/templates/spec_lock_reference.md b/skills/ppt-master/templates/spec_lock_reference.mdindex 9dc0415d..9e42c10d 100644--- a/skills/ppt-master/templates/spec_lock_reference.md+++ b/skills/ppt-master/templates/spec_lock_reference.md@@ -75,7 +75,7 @@>> **Size slots are anchors, not a closed menu.** Common slots (`title` / `subtitle` / `annotation`) cover frequent cases. Add role-specific slots (e.g. `cover_title: 88`, `hero_number: 56`, `subheading: 32`, `lead: 30`, `footnote: 16`, `chart_annotation: 16`) for the roles the deck actually uses — common for cover-heavy decks, consulting-style hero numbers, dense pages. **Mandatory — scan `§IX` and declare a slot for every role that recurs across pages, not just the four defaults.** A report / `text`-mode deck almost always recurs a per-page **core-message / lead line** and **page numbers / source credits / footnotes** → declare `lead` and `footnote` for them. `subheading` and `lead` sit between `subtitle` and `body` (their bands overlap `subtitle`) — pick by role, not size — and the core-message `lead` is a **primary** line, **always ≥ `body`**, never smaller. Leaving a recurring lead / footnote undeclared forces the Executor to improvise an unlocked size (and a core line improvised below `body` inverts the hierarchy). **Structural roles (title / body / subtitle / annotation / footnote) render at their locked size on every page — one role, one size, deck-wide.** Intermediate in-band sizes are for special / feature elements only (hero number, display title, one-off emphasis); declare a recurring one as its own slot so it stays consistent too.>-> **Template Master defaults**: `pptx_structure.mode: template` requires both unitless `title` and `body`. Native export writes `title` into every Master `titleStyle` default and `body` into every `bodyStyle` / `otherStyle` default, changing only `a:defRPr@sz`. Direct page-run sizes and role-specific Layout placeholder prototype sizes remain unchanged. Other structure modes do not rewrite Master text-style sizes.+> **Explicit Layout Master defaults**: `pptx_structure.mode: template` and a structured baseline after Layout distillation both require unitless `title` and `body`. Native export writes `title` into every Master `titleStyle` default and `body` into every `bodyStyle` / `otherStyle` default, changing only `a:defRPr@sz`. Direct page-run sizes and role-specific Layout placeholder prototype sizes remain unchanged. Unmapped baseline, `preserve`, and `flat` do not rewrite Master text-style sizes.>> **⚠️ PPT-safe stack discipline (HARD rule).** Native `baseline` / `template` export maps `title_family` to the PowerPoint theme major font and `body_family` (or `font_family`) to the theme minor font. Runs whose resolved face matches either role use `+mj-*` / `+mn-*` theme tokens; other role families remain concrete per-run typefaces. Every exported Latin / EA face MUST therefore resolve to cross-platform pre-installed fonts: `"Microsoft YaHei"` / `SimSun` / `Arial` / `"Times New Roman"` / `Consolas`. Stacks that resolve to non-preinstalled typefaces (Inter / Google Fonts / brand typefaces) may be used only when the Design Spec notes the font-install or embedding requirement. `preserve` keeps the source template theme; `flat` keeps concrete fonts for diagnostics.>@@ -134,13 +134,22 @@> - template_adherence: adaptive> - template_adherence: strict> ```-> Omit the row for free design and brand-only templates. Both values require one `page_layouts` and one `pptx_layouts` row per page. `strict` keeps the selected Layout contract; `adaptive` may create a new explicit Layout under the same template Master.+> Omit the row for free design and brand-only templates. Both values require one `page_layouts` row per page in new projects. Add `- layout_strategy: distill` and omit `pptx_layouts` until every complete SVG page exists, except when strict uses a legacy template page whose placeholder bounds are missing. That compatibility case omits the strategy and writes the complete kindless output mapping before generation. Adaptive may still distill new design-zone bounds.>-> - `baseline` — default for free design and brand-only routes. New projects pair this mode with a complete `pptx_layouts` section and explicit root Layout/layer/placeholder metadata while remaining `baseline`; no deck/layout template or `page_layouts` section is implied. A legacy baseline lock whose entire `pptx_layouts` section is absent retains root `data-pptx-page-role`, conservative shared chrome promotion, and filename/id compatibility fallback. Actual content stays Slide-local in both paths.-> - `template` — required whenever Step 3 loaded a deck/layout template. Requires complete `page_layouts` and `pptx_layouts` sections plus explicit SVG structure metadata on every generated page.+> New template example:+> ```+> - mode: template+> - template_adherence: adaptive+> - layout_strategy: distill+> ```+>+> - `baseline` — default for free design and brand-only routes. During visual construction, omit `pptx_layouts` and explicit root Layout/layer/placeholder metadata so the page composition remains unconstrained. Baseline compatibility export remains available until the user explicitly runs [`distill-layouts`](../workflows/distill-layouts.md).+> - `template` — required whenever Step 3 loaded a deck/layout template. Distillation-capable projects pair it with `layout_strategy: distill`, a complete `page_layouts` input mapping, and no planning-time `pptx_layouts`. Bounds-missing strict legacy prototypes and existing locks without a strategy retain immediate/pre-authored mappings.> - `preserve` — legacy strict-only compatibility for an existing project that already ships `native_structure.json` + `source_template.pptx`. Do not select it for newly created templates.> - `flat` — diagnostic escape hatch. Do not lock this in a normal project; pass it on the CLI when comparing slide-local output.>+> **Post-design distillation**: Baseline adds `- layout_strategy: distill` only after the user selects completed pages. A distillation-capable template route locks the strategy during planning but defers the whole `pptx_layouts` section. [`distill-layouts`](../workflows/distill-layouts.md) writes the complete final mapping and matching root kind after visual generation. Export rejects the pending or partial state. Strict legacy immediate compatibility skips this state.+>> Preserve example:> ```> - mode: preserve@@ -151,33 +160,37 @@## pptx_layouts-> Emit this section for every new generated deck, including free-design and brand-only decks that remain `pptx_structure.mode: baseline`. Include exactly one row per generated page. Value format: `<layout_key> | <PowerPoint layout name>`. Baseline keys/names describe the authored output composition, strict template use copies the selected SVG key/name, adaptive template use may declare a new stable key/name, and preserve uses the legacy native contract. Only a legacy baseline project may omit the whole section and fall back to `data-pptx-page-role`.+> Distillation-capable template projects and free-design/brand-only baseline projects omit this section during visual generation. [`distill-layouts`](../workflows/distill-layouts.md) writes it only from completed SVG pages. Bounds-missing strict legacy templates, other immediate locks without `layout_strategy`, and preserve locks retain pre-authored rows.+>+> Legacy template/preserve value format: `<layout_key> | <PowerPoint layout name>`. Post-design distillation adds one final kind segment: `<layout_key> | <PowerPoint layout name> | <layout_kind>`. Baseline accepts `distilled` or `utility`; template distillation requires `distilled` on every page.>-> Example:+> Distilled baseline example:> ```-> - P01: cover-hero-split | Cover — Hero Split-> - P02: kpi-band-trio | KPI Band Trio-> - P03: section-divider | Section Divider-> - P04: timeline-spine | Timeline Spine-> - P05: section-divider | Section Divider+> - P01: freeform-unselected | Freeform | utility+> - P02: editorial-visual | Editorial Visual | distilled+> - P03: freeform-unselected | Freeform | utility> ```>-> **One key per distinct composition — chrome, zone framing, and placeholder contract.** Series pages repeating one composition (e.g., three directional timetable pages) share one key; a genuinely different composition gets its own key, and its distinguishing zone framing (table backing panel, column panels, hero frame) is authored at the Layout layer so different keys compile to genuinely different Layouts. Name keys after the composition (`timeline-spine`, `section-divider`), never after PowerPoint stock roles or page topics: role keys (`title-content`) collapse different compositions into one mismatched Layout, and topic keys (`timetable-yungui` / `timetable-guangxi`) split one composition into duplicate Layouts. Do not split a shared key merely because slide-local wording, data, or imagery differs. Choose keys from the authored page plan, never from visual clustering, filenames, or content similarity. Zone labels, data, and complex grouped compositions stay Slide-local; do not move concrete content into the Layout to manufacture reuse.+> **Distilled Layout**: `distilled` means a completed page supplied the final reusable contract. Baseline uses user-selected pages; template routes use every `page_layouts` prototype under strict/adaptive rules. Every placeholder carries explicit `data-pptx-placeholder-bounds` derived from its design zone, never from text length or glyph bounds. The same Layout may serve Slides with different local proportions; bounds define only the reusable default.+>+> **Utility Layout**: `utility` is the single empty `freeform-unselected` Layout for unselected baseline pages. It is forbidden in template distillation because every template page has an input prototype.+>+> **All-or-none final state**: Once distillation starts, include exactly one row per generated page and matching `data-pptx-layout` / name / kind on every SVG root. Partial mappings are invalid.## page_layouts- P01: 01_cover- P03: 02a_chapter- P04: 03a_content_abstract-> For a deck/layout template route, include one entry per page. Key: `P<NN>` matching §IX. Value: the template SVG basename without extension. Strict inherits it unchanged; adaptive uses it as the architecture reference and may output a new `pptx_layouts` key.+> For a deck/layout template route, include one entry per page. Key: `P<NN>` matching §IX. Value: the template SVG basename without extension. This is the input prototype mapping, not the final native Layout mapping. Strict restores its structural contract and bounds after design; adaptive retains its Master ids/topology/geometry and may output a new Layout contract. Non-mirror skin follows the project lock.>> **No entry for a page** is valid only when the entire route is free design or brand-only. It is an error in template mode.>-> **Hard rule**: Use both `page_layouts` and `page_charts` only with a compatible shell. Adaptive mode may start from a neutral content template and create a new explicit Layout; strict mode must choose an existing compatible Layout or revise the outline.+> **Hard rule**: Use both `page_layouts` and `page_charts` only with a compatible shell. Adaptive mode may start from a neutral content template and finalize a new explicit Layout after design; strict mode must choose an existing compatible Layout or revise the outline.>-> **Whole section omitted** → free design or brand-only route. This omission applies only to `page_layouts`; every new route still emits complete `pptx_layouts` output mappings.+> **Whole section omitted** → free design or brand-only route, except for an already-existing legacy immediate-template project that predates explicit prototype mapping. New template strict/adaptive routes require complete `page_layouts`. On a distillation-capable route, `pptx_layouts` appears only after post-design distillation; a bounds-missing strict legacy selection instead writes the complete kindless mapping during planning.>-> **Strategist source**: copy the per-page SVG choices from `design_spec.md §VI Page Roster` (or §IX outline if Roster is absent). Names must match files in `templates/` exactly — typos cause silent fallback to free design.+> **Strategist source**: record each project-page choice in project `design_spec.md §IX Content Outline`, using the copied template package's `templates/design_spec.md §V Page Roster` descriptions as the roster authority. Basenames must match files in `templates/` exactly. A typo is a blocking contract error: stop before drawing and report it; never fall back to free design inside template mode.## page_charts- P05: column_chartdiff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.mdindex 31051945..45f4bd91 100644--- a/skills/ppt-master/workflows/create-template.md+++ b/skills/ppt-master/workflows/create-template.md@@ -63,14 +63,16 @@ Branch by the type of reference source the user supplied. This step produces ana| Type | What the user supplied | Tool / read path | Replication modes available ||------|-------------------------|------------------|------------------------------|| **A** `.pptx` reference | A `.pptx` file path | `pptx_template_import.py` → `manifest.json` + `native_structure.json` + `source_template.pptx` + layered/flat SVGs + `assets/` | `standard` / `fidelity` / `mirror` |-| **B** Existing SVG assets | `projects/<x>/svg_output/`, `templates/layouts/<existing>`, or a loose `.svg` folder | `ls` + `Read` each `*.svg`; plus `design_spec.md` / `spec_lock.md` if present | `standard` / `fidelity` (AI visual clustering) / `mirror` (direct 1:1 copy) |+| **B** Existing SVG assets | `projects/<x>/svg_output/`, `templates/layouts/<existing>`, or a loose `.svg` folder | `ls` + `Read` each `*.svg`; plus `design_spec.md` / `spec_lock.md` if present | `standard` / `fidelity` (explicit structure first; visual clustering only when unstructured) / `mirror` (direct 1:1 copy) || **C** Image / visual references | Screenshot folder, single image, PDF pages | `ls` + `Read` each file (multimodal visual recognition) | `standard` only || **D** No reference source | Verbal description only ("McKinsey style", "tech blue", "dark minimal") | — | `standard` only |`fidelity` and `mirror` are not available for type C / D — visual references and verbal-only briefs cannot drive page-by-page replication. Type A is the canonical path: `manifest.json` page-type candidates and the layered `svg/` workspace anchor cluster detection (fidelity) and verbatim copy (mirror) with factual data. Type B is supported with caveats:- **mirror on type B** — direct 1:1 copy. B's SVGs are already self-contained (one file per page, equivalent to `svg-flat/slide_*.svg`). Page-type for the `<NNN>_<page_type>.svg` filename is read from the source filename when it follows the PPT Master naming convention (`01_cover.svg` → `cover`, `03a_content_two_col.svg` → `content`); fall back to `content` otherwise. Particularly natural when the source is `templates/layouts/<existing>` and the user wants to fork an existing template.-- **fidelity on type B** — clustering relies on the AI's visual judgement of the SVGs; there is no `manifest.json.pageTypeCandidates` to anchor it. Variant count and grouping are more subjective and may need iteration. If the input is already a PPT Master template (`templates/layouts/<existing>`), parse the existing variant filenames (`03a_content_two_col` etc.) as authoritative cluster hints rather than re-clustering visually.+- **fidelity on type B** — inspect root `data-pptx-layout`, direct Master/Layout/placeholder metadata, and companion `spec_lock.md` first. When a complete explicit contract exists, its keys and `pptx_layouts` families are authoritative; preserve them instead of visual re-clustering. Strip deck-instance `data-pptx-layout-kind` when rebuilding the reusable template prototype, while retaining key/name/layers/placeholders/bounds. If the input is an existing template, use its metadata and variant filenames. Only fully unstructured SVG input falls back to AI visual clustering.+- **distilled project on type B** — when the source `svg_output/` carries `data-pptx-layout-kind`, ingest only pages explicitly selected by the user or roots marked `distilled`. Skip every `utility` page; it is an empty mapping shell, not a reusable template design. Deduplicate repeated members by explicit Layout key/contract before rebuilding prototypes, then strip the deck-instance kind. A final distilled composite `<g data-pptx-placeholder="object">` is a deck-instance region proxy and cannot survive that stripping: keep the group as the complete visual sample, remove its placeholder attributes, and rebuild its bounds as a separate direct atomic no-fill/no-line object-slot proxy in the reusable template SVG.+- **selected free-design subset on type B** — if a cross-project request names pages from an undistilled free-design project, return to [`distill-layouts`](./distill-layouts.md) first and distill exactly that source subset. Type B intake then receives only the selected `distilled` files. Do not scan or copy the whole `svg_output/` directory and silently turn unselected pages into template variants.**Replication mode boundary**: `standard` / `fidelity` / `mirror` are construction choices for this workflow only. They decide how the template package is created from the reference source; they do not create a downstream generation route, and `mirror` must not force future decks to preserve the source page count or page order.@@ -245,7 +247,7 @@ Items to surface:| Tone summary | Yes | `[suggested]` from analysis (e.g. `Modern, restrained, data-driven`) || Theme mode | Yes | A: `[fact]` from `manifest.json` background colors. B: `[fact]` from SVG `fill`. C: `[suggested]` from visual estimate. D: `[decision]` || Canvas format and dimensions | Yes | A/B: `[fact]` from slide size or SVG `width` / `height` / `viewBox`; show `canvas_format`, `canvas_width`, `canvas_height`, `canvas_viewbox`, and `source_viewbox`. C: `[suggested]` from image aspect ratio. D: `[decision]`, default `ppt169` (`1280x720`, `0 0 1280 720`) |-| Replication mode | Yes | `[decision]` — `standard` always available; `fidelity` and `mirror` available for type A (canonical, manifest-anchored) and type B (AI visual clustering / direct 1:1 copy — see Step 1 caveats); reject `fidelity` / `mirror` upfront for type C / D |+| Replication mode | Yes | `[decision]` — `standard` always available; `fidelity` and `mirror` available for type A (canonical, manifest-anchored) and type B (explicit-structure grouping or unstructured visual clustering / direct 1:1 copy — see Step 1 caveats); reject `fidelity` / `mirror` upfront for type C / D || Native structure facts | Type A only | `[fact]` from `native_structure.json.strategy`: master/layout counts, source placeholder identities, multi-master status, and reason codes. Output remains rebuilt explicit SVG structure (`template`) for every replication mode. || Visual fidelity for fixed pages | Yes for `standard` / `fidelity` when reference exists; **N/A for `mirror`** (mirror is implicitly literal) | `[decision]` — `literal` (preserve original geometry / decoration / sprite crops as-is; for cover / chapter / ending especially) or `adapted` (use the reference for tone/structure but allow design evolution). Different page types may take different settings || Basic template norms | Yes when reference exists | `[fact]` / `[suggested]` — layout grammar, image system, density rhythm, page roster semantics, and asset policy extracted in Step 1 |@@ -335,9 +337,9 @@ For type D, pass only the finalized brief.The role uses the analysis bundle to anchor objective facts such as theme colors, fonts, reusable backgrounds, common branding assets, layout grammar, image-placement rules, density rhythm, and page-slot semantics, then rebuilds the final SVG templates in a simplified, maintainable form.-**Native structure reconstruction**: Do not copy `native_structure.json` or `source_template.pptx` into the final template directory. Use their master/layout/placeholder facts to reconstruct one clean Master plus semantic Layouts through the explicit SVG metadata contract. Every emitted SVG is a complete standalone preview: declare its output Layout, repeat the identical Master layer, repeat the selected Layout layer for pages sharing a key, and keep actual content on the Slide with semantic placeholder markers. Add `data-pptx-role` only to structural page-frame objects whose package/page-number/animation behavior is not already expressed by specialized metadata; do not classify ordinary template content.+**Native structure reconstruction**: Do not copy `native_structure.json` or `source_template.pptx` into the final template directory. Use their master/layout/placeholder facts to reconstruct one clean Master plus semantic Layouts through the explicit SVG metadata contract. Materialize at least one complete template page for every retained source Layout, including unused Layouts. Immediately below `design_spec.md §V Page Roster`, write a `Source Layout Consolidation` table with one row per retained source Layout: source key/name, output SVG, rebuilt key/picker name, or an explicit unused reason. Never silently drop or merge a source Layout. Mirror keeps its exact source-slide count, so report any unused source Layout that cannot be materialized and use fidelity instead when the full Layout picker roster is required. Every emitted SVG repeats the identical Master layer, the selected Layout layer, and semantic Slide placeholders so it remains a complete standalone preview.-Downstream, both template-adherence choices stay on `pptx_structure.mode: template`. `strict` preserves the selected template Layout contract. `adaptive` still references one template SVG per page, keeps the same Master contract, and may author a new explicit Layout key when the source roster has no suitable composition. It never falls back to baseline inside a template deck.+Downstream, both template-adherence choices use `pptx_structure.mode: template` plus `layout_strategy: distill`. `page_layouts` selects one complete input prototype per page; `pptx_layouts` is omitted until the generated SVG pages are complete. Strict restores the prototype contract. Adaptive keeps the prototype Master structure and may distill a new Layout under a new key/name. Neither falls back to baseline inside a template deck. For mirror packages, reused Master/Layout identities retain literal visual styling in addition to structure; only visible text content may change.**Apply the visual-fidelity decision from Step 3**: pages marked `literal` (typically cover / chapter / ending) must reproduce the reference's geometry, decoration, and sprite-sheet crops as-is — "simplified, maintainable form" applies only to genuinely redundant structure, not to load-bearing layout. Pages marked `adapted` may use the reference for tone and structural rhythm but evolve the design.@@ -345,7 +347,7 @@ Downstream, both template-adherence choices stay on `pptx_structure.mode: templa**Mirror-mode override** (type A or B): when `Replication mode: mirror`, this step is a **verbatim copy** rather than a reconstruction. The Template_Designer role:-1. **Copies the cleaned source pages** into the template directory with literal visual fidelity — no content rewriting or decorative simplification. Then annotate the complete page with root Layout identity plus direct Master/Layout/placeholder metadata derived from the layered source. The SVG remains visually identical when opened alone, while export can deterministically reconstruct native structure.+1. **Copies the cleaned source pages** into the template directory with literal visual fidelity — no content rewriting or decorative simplification. Then annotate the complete page with root Layout identity plus direct Master/Layout/placeholder metadata derived from the layered source. Remove any deck-instance `data-pptx-layout-kind`; it is rendering-neutral and does not belong to the reusable prototype. The SVG remains visually identical when opened alone, while export can deterministically reconstruct native structure.- Type A: source is the cleaned flat `<import_workspace>/svg-flat/slide_NN.svg`- Type B: source is each cleaned `*.svg` in the analysis workspace when extraction ran; otherwise each `*.svg` in the input directory (already self-contained)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`.@@ -366,7 +368,7 @@ Mirror mode does not simplify the visual page, but it still reconstructs layer o1. `design_spec.md` — **personality only**. Required sections: Template Overview, Color Scheme, Signature Design Elements, Page Roster (matching the actual SVG files on disk). Skip Typography / Assets / Placeholder Overrides when they would just restate defaults. Declare portable brief frontmatter; `register_template.py` consumes it only in library scope. **Do not** restate generic SVG constraints, layout pattern libraries, font-size ratio bands, the canonical placeholder table, or content methodology — those are sourced from `shared-standards.md` / `design_spec_reference.md` / `strategist.md` and are already in the downstream reader's context. Full scope rule and skeleton: [template-designer.md §1](../references/template-designer.md#1-must-generate-design_specmd).2. Page roster — see [Page Roster](../references/template-designer.md#page-roster) for `standard` / `fidelity` / `mirror` mode rosters, variant naming, and TOC handling3. Placeholder vocabulary — pages should adopt the conventional names (`{{TITLE}}`, `{{CONTENT_AREA}}`, ...) when they fit. Full reference: [Placeholder Reference](../references/template-designer.md#4-placeholder-reference-canonical-convention-overridable-per-template). When a template style legitimately needs different vocabulary (consulting → `{{KEY_MESSAGE}}`, branded cover → `{{BRAND_LOGO}}`), declare a `placeholders:` block in `design_spec.md` frontmatter so the registrar and quality checker treat it as the template's authoritative contract. **Avoid** one-off indexed families such as `{{CHAPTER_01_TITLE}}` — use the indexed TOC pattern instead.- - `{{...}}` placeholders are the authoring vocabulary used to generate final slide content. Each emitted SVG also carries the native reconstruction contract: root `data-pptx-layout` / `data-pptx-layout-name`, direct Master/Layout layers, and direct semantic `data-pptx-placeholder` markers. Minimal structural `data-pptx-role` hints are added only when those specialized markers cannot express required behavior. Both strict and adaptive downstream use set `mode: template` and require `page_layouts` plus `pptx_layouts` for every page.+ - `{{...}}` placeholders are the authoring vocabulary used to generate final slide content. Each emitted SVG also carries the native reconstruction contract: root `data-pptx-layout` / `data-pptx-layout-name`, direct Master/Layout layers, and direct semantic `data-pptx-placeholder` markers with explicit design-zone bounds. Minimal structural `data-pptx-role` hints are added only when those specialized markers cannot express required behavior. Both strict and adaptive downstream set `mode: template`, require complete `page_layouts`, and defer `pptx_layouts` until post-design distillation.4. Template assets (optional) — library scope bundles Logos / PNG / JPG / reference SVG inside the package; project scope applies the `templates/` / `images/` / dual-icon routing defined above---@@ -397,6 +399,7 @@ python3 skills/ppt-master/scripts/svg_quality_checker.py "<template_target>" --t- enforce roster ↔ `design_spec.md` consistency as **errors** (orphan files / missing files break the template contract and, in library scope, the target kind's index)- emit advisory **warnings** when a page lacks a conventional placeholder — these are hints, not failures. Declare a `placeholders:` block in `design_spec.md` frontmatter to silence them when your template intentionally uses a different vocabulary- require every SVG root to declare an output Layout and every SVG to contain at least one direct Master/Layout/placeholder declaration+- emit `placeholder_bounds_missing` for legacy packages; treat that warning as blocking in this creation workflow and add finite positive design-zone bounds to every new placeholder- validate cross-page Master equality plus same-key Layout/placeholder equality**Checklist**:@@ -411,6 +414,8 @@ python3 skills/ppt-master/scripts/svg_quality_checker.py "<template_target>" --t- [ ] Asset files referenced by SVGs exist at their resolved paths. In project scope, bitmap references resolve through `../images/`; no bitmap remains accidentally stranded in `templates/`- [ ] `design_spec.md` frontmatter declares `native_structure_mode: template`; no `native_structure.json` or `source_template.pptx` is packaged- [ ] Every SVG root declares `data-pptx-layout` and `data-pptx-layout-name`; direct Master/Layout elements and semantic placeholders obey the explicit paint-order contract. Structural `data-pptx-role` is used only when specialized metadata cannot express required package/page-number/animation behavior+- [ ] Every placeholder declares explicit design-zone bounds; no bound was derived from sample text length, glyph ink, or current wrapping+- [ ] Every retained source Layout is represented by a complete template page, or `design_spec.md` records its explicit consolidation target/unused reason in `Source Layout Consolidation`- [ ] If any SVG references an extracted vector `data-icon`, the corresponding SVG asset exists under the package's `icons/` directory. Project scope also has the identical runtime copy under `<target_project>/icons/`; do not add a separate illustration embedding script- [ ] For `fidelity` mode: every sprite-sheet asset retains its nested `<svg viewBox=...>` crop wrapper; no image whose file aspect differs from its on-page aspect was flattened to a bare `<image>`- [ ] For `mirror` mode: file count equals source page count (type A: `<template_target>/*_*.svg` matches the cleaned flat `<import_workspace>/svg-flat/slide_*.svg` count; type B: matches the source SVG count); filenames follow the `<NNN>_<page_type>.svg` convention; **no `{{...}}` placeholder strings appear in any copied SVG** (`grep -l "{{" "<template_target>"/*.svg` should return nothing — if the type B source itself contains placeholders, the user should be in `standard` mode, not `mirror`); §V Page Roster in `design_spec.md` lists every emitted file with a one-line description of what the page contains and what content slot it suitsdiff --git a/skills/ppt-master/workflows/distill-layouts.md b/skills/ppt-master/workflows/distill-layouts.mdnew file mode 100644index 00000000..1b11bbc5--- /dev/null+++ b/skills/ppt-master/workflows/distill-layouts.md@@ -0,0 +1,220 @@+---+description: Distill completed free-design or template-based SVG pages into reusable PowerPoint Layouts+---++# Distill Layouts Workflow++Finalize reusable Master/Layout structure only after the complete visible SVG pages exist.++**Trigger**: Run on explicit free-design reuse requests, and automatically after template-based visual generation only when `layout_strategy: distill` is locked and `pptx_layouts` is still absent.++---++## 1. Scope and State++| Project state | Action |+|---|---|+| `mode: baseline` with no `layout_strategy` | Continue only when the user selected finished pages for reuse |+| `mode: template` + `layout_strategy: distill` + no `pptx_layouts` | Continue; every page already has one input prototype in `page_layouts` |+| `layout_strategy: distill` + complete `pptx_layouts` | Validate/no-op and continue to export; re-enter only when the user explicitly asks to re-distill after later SVG changes |+| `mode: template` without `layout_strategy` | Stop; keep the legacy immediate/pre-authored template contract |+| `mode: preserve` | Stop; preserve owns the imported native package contract |+| Raw PPTX request | Route to [`create-template`](./create-template.md) |+| Cross-project package from an already distilled source | Route to [`create-template`](./create-template.md) with only user-selected/`distilled` pages, never `utility` pages |+| Cross-project package from an undistilled free-design source | First complete this workflow for the explicitly selected source pages, then pass only those `distilled` pages to [`create-template`](./create-template.md) |+| Missing completed `svg_output/` | Stop; finish Executor visual construction first |++`page_layouts` is the input prototype mapping. `pptx_layouts` is the output native Layout contract. Do not write the latter before the complete SVG design exists on a deferred template route.++🚧 **GATE**: Read `spec_lock.md`, every SVG in `svg_output/`, every template SVG named by `page_layouts`, the complete page roster, and `animations.json` when present. Distillation writes one all-page output contract; a selected-page-only read is insufficient.++**Hard rule**: Keep this work in the main agent. Do not infer, cluster, or match by visual similarity.++---++## 2. Resolve Prototypes++### 2.1 Baseline selection++**User selection wins**: Use the requested page numbers or filenames. One selected page creates one Layout unless the user explicitly asks to share a family.++⛔ **BLOCKING**: When a baseline reuse request names no pages, present a short candidate list with page number, composition, and reuse rationale, then wait for the user to choose. Do not promote every page automatically.++**Shared baseline family**: Share one key only when the user explicitly requests it. The named prototype supplies the default bounds; otherwise use the first page in the selection order and state that choice. Every member repeats the same placeholder ids/types/indices/default bounds and static Layout elements. Slide-local geometry may differ.++### 2.2 Template prototypes++**Per-page source**: Resolve each `P<NN>` through `page_layouts` to one complete SVG in `templates/`. The template page is both the visual prototype and the structural authority for its Master/Layout/placeholder metadata.++| Adherence | Final contract |+|---|---|+| `strict` | Keep the prototype Layout key/name, Master/Layout ids/topology/geometry, and placeholder id/type/index/default-bounds contract |+| `adaptive` | Keep the prototype Master ids/topology/geometry; derive a new explicit Layout key/name, static framing, placeholder topology, and design-zone bounds only when the completed page evolved |++**Hard rule — stable provenance**: Match inherited structure by `page_layouts` plus stable direct-child `id`. Do not recover a missing object by geometry, text role, filename, or visual similarity.++**Template skin boundary**: For non-mirror templates, colors, strokes, effects, and font sizes follow the project `spec_lock` re-skin rules. Strict locks reusable structure and bounds, not the template package's sample paint. Mirror remains visually literal.++**Strict legacy boundary**: A strict prototype without explicit bounds on every placeholder cannot enter deferred distillation. Return to the Strategist bounds preflight and use legacy immediate-template compatibility, or upgrade the template package. Do not switch the user's strict choice to adaptive automatically.++---++## 3. Build the Final Contract++| Scope | Baseline source | Template source |+|---|---|---|+| Master | Preserve an already exact all-page Master; do not invent one | Preserve the selected template Master ids/topology/geometry in both strict and adaptive; apply the locked project skin |+| Layout | User-selected reusable static framing behind content | Strict copies the prototype; adaptive keeps only stable evolved framing from the completed design |+| Placeholder | Safe direct atomic carrier, or the final composite-object region exception below | Strict keeps the prototype identity/bounds; adaptive keeps template semantics where applicable and derives evolved design-zone bounds |+| Slide | Actual text, imagery, data, icons, complex groups, foreground overlays, local geometry | Same |++**Hard rule — complete-SVG authority**: The finished SVG remains the sole visible page authority. Do not add a visible object from the template during distillation. Missing inherited visuals are an Executor error; return to page generation instead of repairing them invisibly at export time.++**Hard rule — no visible redesign**: Do not change text, geometry, paint, image hrefs, or z-order. Structure-only reparenting is allowed only for the safe single-carrier case below.++**Hard rule — safe placeholder carrier**: Prefer one direct atomic object. When the reusable unit is an already completed multi-object region, the final `distilled` SVG may mark exactly one direct top-level `<g>` as `data-pptx-placeholder="object"` with explicit design-zone bounds. This is a Layout-only region proxy: its visible Slide group remains ordinary and export adds a hidden transparent binding proxy. Do not use this exception in reusable template SVGs, pending template pages, utility pages, or legacy immediate contracts. Nested metadata, unsafe text extraction, and non-top-level groups remain forbidden.++**Single-carrier extraction**: Replace a top-level one-carrier wrapper by its child only when the wrapper has no clip, mask, filter, `animations.json` reference, animation target, or multi-object semantics. Materialize inherited presentation attributes and transforms, preserve the effective paint position and stable referenced id, then run the render-equivalence gate in §7. If the gate cannot run, keep the object Slide-local.++**Native chart/table boundary**: Keep chart/table groups Slide-local by default. Mark one as a placeholder only when it already carries a valid matching `data-pptx-native` contract and export will use the same `--native-objects` choice.++**Final kind**: Add `data-pptx-layout-kind="distilled"` to every selected baseline page and every deferred template page. Template distillation has no utility pages because every page owns a `page_layouts` prototype.++**Finished-Slide preservation**: A distilled marker supplies a Layout prototype without moving visible content. Atomic carriers retain matching Slide bindings for render fidelity. Composite object-region carriers remain ordinary and receive hidden transparent binding proxies, preventing empty inherited slots from painting over an approved page.++```xml+<svg viewBox="0 0 1280 720"+ data-pptx-layout="editorial-visual"+ data-pptx-layout-name="Editorial Visual"+ data-pptx-layout-kind="distilled">+ <g id="visual-frame" data-pptx-layer="layout">...</g>+ <text id="page-title"+ data-pptx-placeholder="title"+ data-pptx-placeholder-bounds="60 36 1160 64">Actual title</text>+ <image id="hero-image"+ data-pptx-placeholder="picture"+ data-pptx-placeholder-idx="1"+ data-pptx-placeholder-bounds="570 120 650 500"+ x="620" y="120" width="600" height="500"+ href="../images/hero.jpg"/>+ ...+</svg>+```++---++## 4. Derive Default Placeholder Bounds++| Placeholder | Bounds source |+|---|---|+| `title` / `subtitle` | Title safe area or header zone |+| `body` | Column, panel inner box, or intended copy region |+| `picture` / `media` | Image frame or intended visual region |+| `chart` / `table` / `object` | Reusable plot, grid, or object zone; chart/table remains conditional under §3 |+| `footer` / `slide-number` | Stable footer or page-number zone |++**Hard rule**: Every placeholder on a `distilled` Layout carries `data-pptx-placeholder-bounds="x y width height"` with four finite values and positive width/height.++**Forbidden — text-tight bounds**: Do not derive bounds from character count, glyph width, line wrapping, text ink, or `data-pptx-text-bounds`. Use the intended design zone. `data-pptx-text-bounds` continues to own only the current Slide text frame.++**Local geometry remains free**: Placeholder bounds define the Layout default. The current object geometry remains the Slide override and may differ across pages using one key.++---++## 5. Complete the All-Page Mapping++### 5.1 Baseline utility mapping++Map every unselected baseline page to one empty utility Layout:++```xml+<svg ...+ data-pptx-layout="freeform-unselected"+ data-pptx-layout-name="Freeform"+ data-pptx-layout-kind="utility">+ ...all visible objects remain Slide-local...+</svg>+```++**Hard rule**: A `utility` Layout has zero Layout elements and zero placeholders. It exists only to keep the baseline mapping complete.++### 5.2 Template mapping++Map every template page to `distilled`. Strict reuses the selected prototype key/name. Adaptive keeps that key/name only when the static Layout, placeholder identities, and default bounds still match; any evolved reusable contract receives both a new key and a new picker name. Pages sharing one key repeat an identical static/placeholder/default-bounds contract.++For a `replication_mode: mirror` package, the Master and every Slide-local non-text element preserve literal paint, fonts, effects, grouping, geometry, and referenced asset identity. A reused Layout/placeholder identity does the same. Only visible text content may change. Adaptive may intentionally evolve a Layout, but it must use the new key/name rule above; the mirror Master and ordinary Slide-local visuals remain literal. Referenced `<defs>` and applicable embedded-style rules are compared by each layer's actual dependency closure, so resources private to a genuinely new adaptive Layout do not masquerade as Slide-local drift.++**Forbidden — template utility**: Do not map any deferred template page to `utility`, omit its prototype, or fall back to free design.++---++## 6. Finalize `spec_lock.md`++Write `layout_strategy: distill` and the complete output mapping atomically. Keep `page_layouts` unchanged on template routes.++```markdown+## pptx_structure+- mode: template+- template_adherence: adaptive+- layout_strategy: distill++## pptx_layouts+- P01: cover-hero | Cover Hero | distilled+- P02: editorial-visual | Editorial Visual | distilled++## page_layouts+- P01: 01_cover+- P02: 03_content+```++**Hard rule**: Write one row for every generated page. Do not leave a partial mapping or mix final and pending SVG roots. Remove `data-pptx-page-role` from every mapped root and remove generic `data-pptx-role` from a carrier that now has specialized placeholder metadata.++**Baseline migration**: Do not silently replace an existing kindless structured-baseline mapping. Proceed only when the request explicitly asks to migrate or re-distill it.++**Completed-state re-entry**: A complete distilled mapping is idempotent. If no SVG structure changed, validate it and continue without rewriting. After later edits, re-distill only on an explicit request and replace the complete mapping/root metadata atomically; never expose a partial pending state.++---++## 7. Validate and Resume Export++Before any extraction or metadata reparenting, render each affected page with the existing fixed-output renderer, then copy the baseline outside `.preview/` before the next render overwrites it:++```bash+python3 skills/ppt-master/scripts/visual_review.py "<project_path>" --pages "<page_stem>"+mkdir -p "<project_path>/analysis/layout_distill_compare"+cp "<project_path>/.preview/<page_stem>.png" "<project_path>/analysis/layout_distill_compare/<page_stem>.before.png"+```++After the structure edit, render the same page again and compare the retained baseline with the new `.preview` PNG:++```bash+python3 skills/ppt-master/scripts/visual_review.py "<project_path>" --pages "<page_stem>"+python3 -c 'from PIL import Image, ImageChops; import sys; a=Image.open(sys.argv[1]).convert("RGBA"); b=Image.open(sys.argv[2]).convert("RGBA"); raise SystemExit(0 if a.size == b.size and ImageChops.difference(a, b).getbbox() is None else 1)' "<project_path>/analysis/layout_distill_compare/<page_stem>.before.png" "<project_path>/.preview/<page_stem>.png"+```++Require exit code 0. If a page differs, undo the extraction and keep that object Slide-local. Pure root metadata additions that do not reparent or change any visible child do not need this comparison.++Run the project quality gate:++```bash+python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>+```++The checker validates complete mappings, explicit bounds, utility emptiness, selected template prototypes, strict structural equality, and adaptive Master-structure equality. Fix every error before export.++| Entry point | Next action |+|---|---|+| Before the first export | Resume `SKILL.md` Step 7 |+| After an existing export | Re-run Step 7.2 `finalize_svg.py`, then repeat the exact prior Step 7.3 invocation with the same native-object, animation, narration, notes, and transition flags |++```markdown+## ✅ Layout Distillation Complete++- [x] Baseline user selections or all template prototypes resolved explicitly+- [x] Every distilled placeholder has explicit design-zone bounds+- [x] Template Master structure matches the selected prototypes+- [x] `spec_lock.md` and every SVG root carry one complete final mapping+- [x] Structure-only edits are pixel-identical to their pre-edit render+- [x] Project quality checker reports zero errors+- [ ] **Next**: Resume or repeat the canonical export steps+```diff --git a/skills/ppt-master/workflows/index.md b/skills/ppt-master/workflows/index.mdindex 118ad67e..7f870cdc 100644--- a/skills/ppt-master/workflows/index.md+++ b/skills/ppt-master/workflows/index.md@@ -27,6 +27,7 @@ Registry for standalone workflows referenced by `SKILL.md` and [`routing.md`](./| `native-narration-pptx` | [`native-narration-pptx.md`](./native-narration-pptx.md) | Compatibility reference for the narration subset of native enhancement | Existing PPTX exists | Prefer `native-enhance-pptx` for new requests | Compatibility entry | Narration-enhanced PPTX | Follow compatibility doc || `live-preview` | [`live-preview.md`](./live-preview.md) | User asks for preview, element selection, browser annotations, or re-entry to the editor | Project exists; SVGs required only for annotation apply/export | Do not apply annotations during active generation | Step 6 auto-start or workflow Step 1/2 | Running preview or applied browser edits/annotations | Blocks only when project/SVG target is missing || `visual-review` | [`visual-review.md`](./visual-review.md) | User explicitly asks for per-page visual review or visual rubric | Generated SVG pages exist | Never inferred from deck size/model identity | Between Step 6 and Step 7 | Findings and fixed SVGs | Blocks on selected severe findings if the workflow says to fix |+| `distill-layouts` | [`distill-layouts.md`](./distill-layouts.md) | User asks to promote finished baseline pages, or a template project reaches deferred structure finalization | Completed SVG pages; template route also requires complete `page_layouts` | Not for preserve, legacy immediate-template, or cross-project registration | After Step 6 or as a post-export re-entry | Complete all-page `pptx_layouts` plus SVG structure metadata | Baseline blocks for missing page selection; template blocks for missing/invalid prototypes || `generate-audio` | [`generate-audio.md`](./generate-audio.md) | User asks for recorded narration, voiceover, audio, or video-style export | Post-processing/export context exists; notes available | Do not call `notes_to_audio.py` directly | After Step 7 | Audio files and optional narration-embedded PPTX | Single backend/voice/settings confirmation |---diff --git a/skills/ppt-master/workflows/refine-spec.md b/skills/ppt-master/workflows/refine-spec.mdindex 63fcba49..2d053f95 100644--- a/skills/ppt-master/workflows/refine-spec.md+++ b/skills/ppt-master/workflows/refine-spec.md@@ -49,6 +49,8 @@ These overlap with what the locked `mode`, visual style, and §6.1 already shape**Keep both files in sync on every change.** Any revision the user approves must land in both `design_spec.md` and `spec_lock.md`; on divergence `spec_lock.md` wins (see [`strategist.md`](../references/strategist.md) §6.2). Iterate as many rounds as the user wants. The loop ends only when the user explicitly approves the spec.+**Re-run the template bounds preflight after structural revisions.** If the user changes `template_adherence` or any `page_layouts` choice, repeat the Strategist preflight in [`strategist.md`](../references/strategist.md) §6.2 before approval and hand-back. Inspect every newly selected prototype. A distillation-capable strict route requires explicit `data-pptx-placeholder-bounds` on every prototype placeholder; adaptive may still defer and author new design-zone bounds when a legacy prototype lacks them. If strict selects any bounds-missing prototype, keep the user's strict choice but switch the lock to legacy immediate-template compatibility: omit `layout_strategy`, write the complete kindless `pptx_layouts` mapping before generation, and surface the required warning. Update both artifacts together; never leave the pre-revision deferred state in `spec_lock.md`.+---## Step 3: Hand backdiff --git a/skills/ppt-master/workflows/routing.md b/skills/ppt-master/workflows/routing.mdindex e9fbf189..dd986eda 100644--- a/skills/ppt-master/workflows/routing.md+++ b/skills/ppt-master/workflows/routing.md@@ -72,6 +72,7 @@ Route selection authority for PPT Master. Use this file before entering the main| Object-level animation tuning | User asks for animation order, timing, effects, or object reveal behavior | [`customize-animations`](./customize-animations.md) | SVG groups / exported context exist | `animations.json` or validated animation config | Stop if requested target objects cannot be identified || Live preview / element selection / annotations | User mentions live preview, preview, visual check in browser, clicking/selecting an element, or applying browser annotations | [`live-preview`](./live-preview.md) | Project exists; for annotation apply, generated SVGs exist | Running preview service or applied annotations plus re-export | Stop only if project path or SVGs are missing || Visual review | User explicitly asks for per-page visual self-check or visual rubric | [`visual-review`](./visual-review.md) between Step 6 and Step 7 | SVG pages exist | Visual review findings and fixes before post-processing | Do not run without explicit user request |+| Finalize reusable Layouts | User asks to promote completed baseline pages, or a template project has `layout_strategy: distill` with missing `pptx_layouts` after SVG generation | [`distill-layouts`](./distill-layouts.md) after Step 6 or explicit post-export re-entry | Completed SVG pages; template route also has one `page_layouts` prototype per page | Baseline: selected Layouts plus one utility; template: every page distilled against strict/adaptive prototype rules | Complete mappings are validation/no-op unless re-distill is explicit; cross-project `create-template` consumes selected/`distilled` pages and skips `utility` || Recorded narration / video export | User asks for narration, voiceover, or video-style export | [`generate-audio`](./generate-audio.md) after post-processing | Notes and exported deck exist | Audio files and optional narration-embedded PPTX | Stop for the workflow's single backend/voice confirmation |---