Skip to content

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

feat(page-context): add measured per-page execution views

hugohe31d04c8019e7b
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 2c310992..4b59b5aa 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -24,7 +24,7 @@ Structural capability growth since March 2026. Single flags and incremental poli
- **Source-less generation**: the `topic-research` stage supports "topic only, no source files"
- **PPTX export step-change**: SVG clipPath → DrawingML picture geometry, marker → native arrows, output consolidated to `exports/`
- **Chart library expands to 70 templates + three icon libraries** (simple-icons / phosphor-duotone / brand-logo)
-- **`spec_lock.md` machine-readable contract**: Strategist locks the spec, Executor re-reads it before every page — cross-page consistency gets a real guarantee
+- **`spec_lock.md` machine-readable contract**: Strategist locks the spec, Executor rebuilds its read-only page-context projection before every page — cross-page consistency gets a real guarantee
- **Per-element animation support** + recorded narration / video export ([`workflows/stages/generate-audio.md`](../skills/ppt-master/workflows/stages/generate-audio.md)); the current behavior is opt-in, with element animation defaulting to `none`
### 2026-05 — Visual editing + AI image systematization
diff --git a/docs/rules/prompt-style.md b/docs/rules/prompt-style.md
index 5cd18887..1bd0f0c3 100644
--- a/docs/rules/prompt-style.md
+++ b/docs/rules/prompt-style.md
@@ -74,7 +74,8 @@ Begin substantive paragraphs with a bolded short label. Reuse this fixed vocabul
✅ Good (from `executor-base.md`):
```
-**Hard rule**: Before generating **each** SVG page, `read_file <project_path>/spec_lock.md`.
+**Hard rule**: Before generating **each** SVG page, run:
+`python3 skills/ppt-master/scripts/project_manager.py page-context <project_path> P<NN> --bundle --record-usage`.
**Forbidden — values outside the lock**:
- Colors (fill / stroke / stop-color) MUST come from `colors`
diff --git a/docs/technical-design.md b/docs/technical-design.md
index dc71d644..8f4232b9 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -162,14 +162,16 @@ sources/*.facts.json ───────────┤
analysis/source_profile.json ───┼─> Strategist -> design_spec.md + spec_lock.md
analysis/image_analysis.csv ────┘
-spec_lock.md + images/ + icons/ + templates/
- + templates/template_execution_manifest.json
- + selected templates/template_execution/*.text-slots.json
- └─> Executor -> svg_output/
- ├─> svg_quality_checker.py -> exports/svg_quality_report.json
- ├─> finalize_svg.py -> svg_final/
- └─> svg_to_pptx.py -> exports/<name>_<ts>.pptx + <output_stem>.report.json
- backup/<ts>/svg_output/
+design_spec.md + spec_lock.md + images/ + icons/ + templates/
+ └─> project_manager.py page-context <project> P<NN> --bundle
+ + [selected complete prototype SVG]
+ + [mirror text-slots.v2-min]
+ ├─> Executor -> svg_output/
+ │ ├─> svg_quality_checker.py -> exports/svg_quality_report.json
+ │ ├─> finalize_svg.py -> svg_final/
+ │ └─> svg_to_pptx.py -> exports/<name>_<ts>.pptx + <output_stem>.report.json
+ │ backup/<ts>/svg_output/
+ └─> --record-usage -> analysis/page-context/P<NN>.usage.json
Direct OOXML routes:
analysis/<stem>.slide_library.json + source PPTX + fill_plan.json
@@ -270,8 +272,8 @@ These invariants are stronger than ordinary implementation preferences. If a cha
|---|---|
| `sources/` content-type files are the main-pipeline content contract | text, tables, and chart values come from content-type files in `sources/` (Markdown is primary, but `.txt` / `.csv` / `.json` / `.yaml` / … count too); known sidecars (`*.conversion_profile.json`, `*_files/image_manifest.json`) are excluded |
| `analysis/` stores machine facts, not design contracts | `source_profile.json` and intake artifacts inform Strategist; they do not lock page count/order except in workflows that say so |
-| `design_spec.md` explains the design; `spec_lock.md` executes it | Executor reads locked values from `spec_lock.md`, not from prose memory |
-| `spec_lock.md` is re-read before every page | colors, fonts, icons, images, rhythm, layouts, and chart choices stay stable across long decks |
+| `design_spec.md` explains the design; `spec_lock.md` executes it | the per-page projection derives narrative and locked values from their owning artifacts, not from prose memory |
+| `page-context` is rebuilt before every page | each read-only view contains the current global lock, page brief, rhythm, chart/image choice, and route-selected template inputs |
| `svg_output/` is the only hand-authored SVG directory | quality checks, manual edits, re-export, and `update_spec.py` target authored source |
| `svg_final/` is mandatory but derived | it is regenerated from `svg_output/` for self-contained visual preview or manual insertion as an SVG picture; it does not become the native export source of truth, and PowerPoint Convert to Shape is outside the supported contract |
| Native PPTX export reads `svg_output/` by default | converter preserves icons, `preserveAspectRatio`, rounded rects, and native image crop metadata before finalization rewrites them |
@@ -348,7 +350,7 @@ PPT Master uses **role switching within one main agent** rather than parallel su
**Image analysis goes through regenerated metadata, not pixels.** When images exist, Strategist and Executor use `analyze_images.py` output (`analysis/image_analysis.csv`) rather than directly opening image files. The CSV is a regenerated view over the live `images/` folder, not a durable cache. Re-running it before image-sensitive decisions is the staleness strategy: user images, extracted images, web images, AI outputs, formulas, and sliced elements all converge into the same measured fact table.
-**Per-page spec_lock re-read** is the long-deck anti-drift mechanism — full rationale in § Spec Propagation below.
+**Per-page context projection** is the long-deck anti-drift mechanism — full rationale in § Spec Propagation below.
---
@@ -371,10 +373,16 @@ The Strategist phase produces two artifacts that look redundant but serve differ
- `design_spec.md` — human-readable narrative; the "why" of the deck (communication intent, audience outcome, narrative / template / visual rationale, page outline)
- `spec_lock.md` — machine-readable execution contract; the compact communication trace plus the exact values Executor must literally use (HEX colors, font stacks, icon library, image resources, and structure mappings)
-Why both? Without `spec_lock.md`, the Executor would re-read `design_spec.md` per page during long decks and the LLM's context-compression drift would gradually mutate colors and fonts mid-deck. `spec_lock.md` is the **anti-drift mechanism** — [Generate PPTX Step 6](../skills/ppt-master/workflows/generate-pptx.md#step-6-executor-phase) mandates `read_file <project>/spec_lock.md` before every page, so values stay verbatim across 20+ slides.
+Why both? Without `spec_lock.md`, the Executor would derive exact values from narrative prose and context-compression drift would gradually mutate colors and fonts mid-deck. [Generate PPTX Step 6](../skills/ppt-master/workflows/generate-pptx.md#step-6-executor-phase) instead rebuilds a read-only `page-context` view before every page. The projector reads the current lock and the matching `design_spec.md` page block, then emits only the global execution values and current-page routing facts needed for authoring.
+
+The view omits universal SVG/icon prohibitions already owned by the always-loaded Executor core and retains only project-specific forbidden rows. It selects images from the current page brief, explicit image-resource page assignments, and mirror prototype references. Images assigned elsewhere are excluded; any unresolved legacy image remains in a compatibility subset, and `confirmed-none` appears only when every locked image has a deterministic assignment elsewhere.
The lock is also the per-page routing table. Beyond global colors and typography, it carries `page_rhythm` (`anchor` / `dense` / `breathing`), `page_charts` (which chart template should be adapted), image rows with placement/cropping contracts, and the locked `mode` / `visual_style` references that decide which execution rule files are loaded. `template_reuse_scope: mirror|layout` projects additionally carry `page_layouts` (which input template SVG each page inherits), unique `pptx_masters` / `pptx_layouts` definitions, and `page_pptx_layouts` assignments. `template_reuse_scope: style`, free-design, and brand-only projects use `pptx_structure.mode: flat` and omit those sections entirely rather than writing empty values. Empty entries elsewhere are meaningful signals: no chart or no image is often a design decision rather than missing data.
+`page-context --bundle` is route-sensitive: flat pages add no template payload, structured layout pages add the complete selected prototype, and mirror pages add that prototype plus `ppt-master.template-text-slots.v2-min`. Each v2-min slot contains only selector, role, current/segmented text, and tspan count. A top-level tool hash covers selectors plus immutable text/tspan topology and attributes; page-context recomputes it and every projected field from the complete prototype, then strips the hash before model output. Legacy v1 sidecars receive the same compatibility validation and are projected to this shape in memory. The model supplies semantic decisions and replacement text. Checker and structured export validate output attributes, text topology, and resource hashes against the complete prototype internally.
+
+`--record-usage` requires `--bundle` and writes a derived, input-hashed snapshot for that page under `analysis/page-context/`; expected-but-absent optional inputs are recorded so later artifact creation also makes the snapshot stale. Token counting lazily uses `o200k_base`; a missing `tiktoken` installation records `tokens: null` without blocking execution. `page-context-report` excludes stale snapshots and exposes the measured component totals used to decide whether a future mirror text-patch tool is warranted; no such tool is introduced by this phase.
+
`update_spec.py` propagates a post-generation change in two coordinated steps: write the new value to `spec_lock.md`, then literal-replace it across every `svg_output/*.svg`. The tool's scope is deliberately narrow — only `colors.*` (HEX values, case-insensitive replacement) and `typography.font_family` (attribute-scoped). Other fields (font sizes, icons, images, canvas) are intentionally **not supported** because their replacements would need attribute-scoped or semantic awareness whose risk/benefit doesn't justify bulk propagation. For those, edit `spec_lock.md` and re-author the affected pages.
The tool refuses to back up: it relies on git for revert. Adding a backup mechanism would just duplicate git's job and create stale snapshots.
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index db5d0e14..fd82fa07 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -163,14 +163,16 @@ sources/*.facts.json ───────────┤
analysis/source_profile.json ───┼─> Strategist -> design_spec.md + spec_lock.md
analysis/image_analysis.csv ────┘
-spec_lock.md + images/ + icons/ + templates/
- + templates/template_execution_manifest.json
- + 当前原型的 templates/template_execution/*.text-slots.json
- └─> Executor -> svg_output/
- ├─> svg_quality_checker.py -> exports/svg_quality_report.json
- ├─> finalize_svg.py -> svg_final/
- └─> svg_to_pptx.py -> exports/<name>_<ts>.pptx + <output_stem>.report.json
- backup/<ts>/svg_output/
+design_spec.md + spec_lock.md + images/ + icons/ + templates/
+ └─> project_manager.py page-context <project> P<NN> --bundle
+ + [当前完整原型 SVG]
+ + [mirror text-slots.v2-min]
+ ├─> Executor -> svg_output/
+ │ ├─> svg_quality_checker.py -> exports/svg_quality_report.json
+ │ ├─> finalize_svg.py -> svg_final/
+ │ └─> svg_to_pptx.py -> exports/<name>_<ts>.pptx + <output_stem>.report.json
+ │ backup/<ts>/svg_output/
+ └─> --record-usage -> analysis/page-context/P<NN>.usage.json
直接 OOXML 路由:
analysis/<stem>.slide_library.json + 源 PPTX + fill_plan.json
@@ -271,8 +273,8 @@ CLI 仍支持三种导入模式:`--move`、`--copy`,以及“仓库内文件
|---|---|
| `sources/` 内容型文件是主流水线内容契约 | 主 SVG 路线中的文本、表格和图表数值来自 `sources/` 内容型文件(Markdown 为主,`.txt` / `.csv` / `.json` / `.yaml` 等同样计入);已知 sidecar(`*.conversion_profile.json`、`*_files/image_manifest.json`)排除在外 |
| `analysis/` 存机器事实,不存设计契约 | `source_profile.json` 和 intake artifact 辅助 Strategist;除非工作流明确规定,否则不锁定页数 / 页序 |
-| `design_spec.md` 解释设计;`spec_lock.md` 执行设计 | Executor 从 `spec_lock.md` 取锁定值,而不是从叙述记忆里取 |
-| 每页生成前重读 `spec_lock.md` | 长 deck 中的颜色、字体、图标、图片、节奏、布局和图表选择保持稳定 |
+| `design_spec.md` 解释设计;`spec_lock.md` 执行设计 | 逐页视图从各自权威 artifact 派生叙事和锁定值,而不是从叙述记忆里取 |
+| 每页生成前重建 `page-context` | 只读视图包含当前全局 lock、页面 brief、节奏、图表/图片选择和按路线选出的模板输入 |
| `svg_output/` 是唯一手写 SVG 目录 | 质量检查、手工编辑、重导出和 `update_spec.py` 都面向作者源 |
| `svg_final/` 是派生产物 | 它必须能从 `svg_output/` 重建,只负责自包含视觉预览,不应成为 native 导出的事实源 |
| native PPTX 标准导出读取 `svg_output/` | 唯一受支持的可编辑形状路线由项目转换器执行;它要在 finalize 重写前保留图标、`preserveAspectRatio`、圆角矩形和原生图片裁剪语义 |
@@ -344,7 +346,7 @@ PPT Master 用的是**单主代理内的角色切换**,不是并行子代理
**图片分析走重算元数据,不读像素。** 当项目里存在图片时,Strategist 和 Executor 使用 `analyze_images.py` 的输出(`analysis/image_analysis.csv`),而不是直接打开图片文件。这个 CSV 是基于当前 `images/` 目录重算出来的视图,不是持久缓存。每次做图片敏感决策前重跑分析,就是它的防陈旧策略:用户图、抽取图、网络图、AI 图、公式图和切片图最终都会汇入同一张可度量事实表。
-**逐页 spec_lock 重读** 是长 deck 的抗漂移机制——完整理由见下面的 § 设计规范的传播。
+**逐页上下文投影** 是长 deck 的抗漂移机制——完整理由见下面的 § 设计规范的传播。
---
@@ -367,10 +369,16 @@ Strategist 阶段产出两份看起来冗余但服务不同对象的产物:
- `design_spec.md` —— 人类可读叙述;deck 的「为什么」(沟通意图、受众变化、叙事 / 模板 / 视觉理由、页面大纲)
- `spec_lock.md` —— 机器可读执行契约;包含紧凑沟通追踪,以及 Executor 必须**字面照搬**的精确值(HEX 颜色、字体栈、图标库、图片资源与结构映射)
-为什么两份都要?没有 `spec_lock.md` 的话,Executor 在长 deck 里会逐页重读 `design_spec.md`,LLM 上下文压缩漂移会逐渐扭曲色值和字体。`spec_lock.md` 是**抗漂移机制**——[Generate PPTX Step 6](../../skills/ppt-master/workflows/generate-pptx.md#step-6-executor-phase) 强制要求生成每一页前 `read_file <project>/spec_lock.md`,让数值在 20+ 页里保持字面一致。
+为什么两份都要?没有 `spec_lock.md`,Executor 就会从叙述文本推导精确值,上下文压缩漂移会在长 deck 中逐渐扭曲色值和字体。[Generate PPTX Step 6](../../skills/ppt-master/workflows/generate-pptx.md#step-6-executor-phase) 改为每页生成前重建只读 `page-context` 视图:投影器读取当前 lock 和 `design_spec.md` 中对应的页面 block,只输出创作该页所需的全局执行值和逐页路由事实。
+
+该视图省略 Executor core 已经恒定加载的通用 SVG/图标禁令,只保留项目专属 forbidden 行。图片从当前页 brief、图片资源表中的显式页分配和 mirror 原型引用中选择;已分配给其他页面的图片会被排除,仍无法归属的 legacy 图片保留在兼容子集中,只有所有锁定图片都能确定归属到其他页面时才记录 `confirmed-none`。
这份 lock 同时也是逐页路由表。除了全局配色和字体,它还承载 `page_rhythm`(`anchor` / `dense` / `breathing`)、`page_charts`(某页应适配哪个图表模板)、带放置/裁剪契约的图片行,以及决定加载哪些执行规则文件的 `mode` / `visual_style`。`template_reuse_scope: mirror|layout` 项目额外承载 `page_layouts`(每页继承哪个输入模板 SVG)、唯一的 `pptx_masters` / `pptx_layouts` 定义,以及 `page_pptx_layouts` 页面分配;`template_reuse_scope: style`、自由设计和 brand-only 项目使用 `pptx_structure.mode: flat`,那些段整段省略,而不是写成空值。其余字段的空值本身仍是信号:没有图表、没有图片,很多时候是设计选择,而不是漏填。
+`page-context --bundle` 按路线收敛输入:flat 页面不增加模板 payload;structured layout 页面增加当前完整原型;mirror 页面再增加 `ppt-master.template-text-slots.v2-min`。v2-min 的每个 slot 只包含 selector、role、当前/分段文本和 tspan 数量;顶层 tool hash 覆盖 selector 及不可变文字/tspan 拓扑和属性。page-context 会根据完整原型重算该 hash 与所有投影字段,再从模型输出中剥离 hash;旧 v1 sidecar 也会经过同等兼容校验并在内存中投影成同一形状。模型只负责语义决策和 replacement 文本;Checker 与 structured export 在内部根据完整原型校验输出属性、文字拓扑和资源 hash。
+
+`--record-usage` 必须与 `--bundle` 同用;它在 `analysis/page-context/` 下写入当前页的派生快照,并记录所有输入 hash;预期但缺失的可选输入也会记录,因此后续补出产物会使快照过期。token 计数按需加载 `o200k_base`;没有安装 `tiktoken` 时写入 `tokens: null`,但不阻塞执行。`page-context-report` 排除过期快照,并汇总各组件的实测 token,用于判断未来是否值得引入 mirror text-patch 工具;本阶段不引入该工具。
+
`update_spec.py` 把生成后的修改用两个协调步骤传播:把新值写入 `spec_lock.md`,然后字面替换到每一份 `svg_output/*.svg`。工具的范围**故意收得很窄**——只支持 `colors.*`(HEX 值,大小写不敏感替换)和 `typography.font_family`(属性级)。其他字段(字号、图标、图片、画布)**有意不支持**——它们的替换需要属性级或语义级理解,风险/收益不值得做批量传播。这些情况手动改 `spec_lock.md` 然后重做受影响的页面。
工具拒绝做备份:依赖 git 回滚。加备份机制只是重复 git 的工作,还会留下过时快照。
diff --git a/skills/ppt-master/references/artifact-ownership.md b/skills/ppt-master/references/artifact-ownership.md
index 2a33a7de..c2cbc66e 100644
--- a/skills/ppt-master/references/artifact-ownership.md
+++ b/skills/ppt-master/references/artifact-ownership.md
@@ -19,11 +19,13 @@ 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, charts, `template_reuse_scope`, and the route's PowerPoint structure mode; mirror/layout template routes additionally own input prototypes, the Master roster, and the complete page-to-Master/Layout mapping | Strategist writes the route-specific contract; Executor re-reads it before every page and may add a new adaptive Layout identity only on a structured mirror/layout route while authoring the page that first needs it |
+| `spec_lock.md` | Execution contract | Literal colors, typography, icons, images, page rhythm, charts, `template_reuse_scope`, and the route's PowerPoint structure mode; mirror/layout template routes additionally own input prototypes, the Master roster, and the complete page-to-Master/Layout mapping | Strategist writes the route-specific contract; `page-context` projects the current-page subset for Executor. Executor may add a new adaptive Layout identity only on a structured mirror/layout route while authoring the page that first needs it. |
+| `project_manager.py page-context` stdout | Derived per-page context | Read-only model-facing projection of current `design_spec.md`, `spec_lock.md`, and selected template assets | Generate immediately before each page with `--bundle`; never edit or persist it as a replacement source of truth. Flat bundles contain context only; layout adds the complete selected prototype; mirror adds that prototype plus the minimal text-slot view. |
+| `analysis/page-context/P<NN>.usage.json` | Derived context telemetry | Actual model-facing bundle size by page and component | `page-context --record-usage` deterministically replaces that page's snapshot; `page-context-report` summarizes current snapshots. Use token data to evaluate later context tooling, never as content or an execution 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 |
-| `templates/template_execution_manifest.json` + `templates/template_execution/*.text-slots.json` | Model-readable template execution index | Compact prototype roster and source-import summary plus per-prototype exact mirror-safe text-slot selectors/topology | Read the roster once; before each mirror page, read only the selected text-slot sidecar and complete template SVG. Layout reuse needs the complete SVG but not the mirror-only sidecar. Never author from either JSON artifact alone. |
+| `templates/template_execution_manifest.json` (`v1`) + `templates/template_execution/*.text-slots.json` (`v2-min`) | Template execution index | Compact prototype roster/source-import summary plus per-prototype `selector`, `role`, `current_text`, `text_segments`, and `tspan_count`; the sidecar's top-level integrity hash is tool-only | Read the roster once; `page-context --bundle` validates and strips the tool hash, then includes the selected minimal projection and complete prototype for mirror, or the complete prototype alone for layout. Missing, malformed, or stale derived sidecars fall back to the complete SVG. Attributes, topology, and hashes remain tool-validated; never author from either JSON artifact alone. |
| `<import_workspace>/svg/` | Imported native-payload backing | Complete PPTX-derived metadata, hidden carriers, fallback evidence, and source structure | Keep immutable; create-template materialization may resolve a validated source ref against these files, but models do not edit or bulk-read them |
| `<import_workspace>/svg-flat/` | Optional complete-page verification backing | Self-contained visual composition generated only by explicit `--inheritance-mode both` | Keep immutable when requested; never use as authoring or materialization input |
| `<import_workspace>/authoring-svg/` | Template-creation author source | Layered editable SVG IR for imported Master, Layout, and Slide objects | Template_Designer reads and edits this bundle; final template SVGs are materialized from it rather than copied from lossless backing |
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index 4ba9ba21..3e2c31ac 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -29,11 +29,17 @@ Always-loaded Executor authority for flat SVG page authoring and behavior shared
Before the first SVG page, output a confirmation listing: the compact communication intent + desired audience outcome, canvas dimensions, body font size, color scheme (primary/secondary/accent HEX), font plan, and the live-preview URL reported by the launcher. If the preview launch failed, state that failure before generating SVGs instead of silently proceeding. Prevents purpose/spec/execution drift.
-### 2.1 Per-page spec_lock re-read (Mandatory)
+### 2.1 Per-page execution context (Mandatory)
-> Long decks drift off the declared palette/icons mid-deck due to context compression. `spec_lock.md` is the canonical execution reference — re-read it per page to bypass model memory.
+**Hard rule**: Before generating **each** SVG page, load its canonical projection and record the model-facing context size:
-**Hard rule**: Before generating **each** SVG page, `read_file <project_path>/spec_lock.md`. Use only values from this file, not from memory. Re-read the global `communication` section along with the technical locks. The current page's `design_spec.md §IX` brief must be in immediate context; if context was auto-compacted or the brief is not immediately available, re-read `design_spec.md` for that page before drawing.
+```bash
+python3 skills/ppt-master/scripts/project_manager.py page-context <project_path> P<NN> --bundle --record-usage
+```
+
+Use the bundle's communication contract, canvas, mode/style, colors, typography, icons, current `design_spec.md §IX` brief, and current-page lock assignments. The bundle is a read-only projection of `design_spec.md` and `spec_lock.md`; it does not replace either required gate artifact or authorize values absent from the lock. After an approved upstream lock change, rerun the command before drawing the affected page.
+
+**Source facts**: The bundle carries page intent and locked execution values, not the complete source corpus. Read the relevant `sources/` content and resolve listed `Fact IDs` from `sources/*.facts.json` when the page needs concrete claims, quotes, names, or data.
**Per-page communication trace**: Read the current §IX `Core message` and `Audience move` before choosing composition. The page must advance at least one purpose named in `communication.communication_intent` and move the audience toward `communication.audience_outcome`; `communication.core_message` remains the deck-wide north star. A page that cannot state this movement is an upstream outline defect — surface `warning: P<NN> has no communication move` instead of compensating with decorative layout. Do not invent a new purpose, ask, or outcome at execution time. Structural pages may advance the contract by establishing relevance / tension / decision frame or by completing the final commitment; they are not exempt from having a reason to exist.
@@ -55,7 +61,7 @@ The §IX wording and sourced facts remain authoritative. Do not rewrite, drop, o
> Note: block-level phrasing, applied *within* the page's `page_rhythm` density (below), not against it.
-**Missing `spec_lock.md`** → stop before drawing and report the missing gate artifact. Recover through [`failure-recovery.md`](../workflows/governance/failure-recovery.md) §3; do not generate from `design_spec.md` alone or silently downgrade.
+**Missing `spec_lock.md` or `design_spec.md`** → stop before drawing and report the missing gate artifact. Recover through [`failure-recovery.md`](../workflows/governance/failure-recovery.md) §3; do not bypass a failed page-context command or silently downgrade.
**Missing field in an existing lock**: follow [`failure-recovery.md`](../workflows/governance/failure-recovery.md) §2.
@@ -71,7 +77,7 @@ The §IX wording and sourced facts remain authoritative. Do not rewrite, drop, o
- Images MUST reference files listed under `images`; no invented filenames
- Formula PNGs are images with `Acquire Via: formula`; place a `Rendered` file only from its listed path, use the normal placeholder for `Needs-Manual`, and never recreate the formula as text.
-If a page needs a value not in `spec_lock.md`, surface it — do not silently invent one. When an intentional deck-wide or recurring color, type role/size, icon, or image is approved, extend `spec_lock.md` **before** drawing the first affected object, re-read the lock, and only then author the page; do not draw with a temporary hardcoded value and retroactively silence drift warnings.
+If a page needs a value not in `spec_lock.md`, surface it — do not silently invent one. When an intentional deck-wide or recurring color, type role/size, icon, or image is approved, extend `spec_lock.md` **before** drawing the first affected object, regenerate that page's context bundle, and only then author the page; do not draw with a temporary hardcoded value and retroactively silence drift warnings.
**Per-page layout rhythm — `page_rhythm` section**:
diff --git a/skills/ppt-master/references/executor-structured.md b/skills/ppt-master/references/executor-structured.md
index 996df8fc..d3be6006 100644
--- a/skills/ppt-master/references/executor-structured.md
+++ b/skills/ppt-master/references/executor-structured.md
@@ -8,25 +8,21 @@ Conditional Executor authority for `template_reuse_scope: mirror|layout` with `p
## 1. Template Reuse Rules
-### 1.0 Pre-generation Template Read
+### 1.0 Template Context Load
-**Hard rule**: Read the compact template roster once, but never treat a summary as the full page prototype.
-
-| Source list | Read path |
+| Context | Load policy |
|---|---|
-| Chosen template's `design_spec.md` (template capabilities) | `templates/design_spec.md` |
-| Model-readable execution roster, when present | `templates/template_execution_manifest.json` |
-| Selected mirror prototype's text-slot sidecar | The roster entry's `text_slots_path` under `templates/` |
-
-When `template_execution_manifest.json` and the selected entry's `text_slots_path` exist, read the compact roster once for selection/orientation and the sidecar before authoring each mirror page; then read the selected complete `templates/<basename>.svg`, which remains the visual/structural authority. Layout reuse reads the selected complete SVG but does not need the mirror-only sidecar. When the manifest, selected entry, or sidecar is unavailable, batch-read every distinct `<basename>` in `spec_lock.md page_layouts` before page 1. On mirror, preserve text topology directly from the complete SVG under §1.1; missing derived metadata alone does not invalidate the workspace.
+| Chosen template's `templates/design_spec.md` capabilities | Once before page generation |
+| `templates/template_execution_manifest.json`, when present | Once for prototype roster/orientation |
+| Current page context and selected prototype | Run [`executor-base.md`](./executor-base.md) §2.1 immediately before that page |
-`spec_lock.md` is the only route-wide artifact that must be re-read for every page. Keep the current `design_spec.md §IX` page brief in immediate context, re-reading that brief after context compaction as required by [`executor-base.md`](./executor-base.md) §2.1.
+**Hard rule**: The current-page bundle carries the selected complete prototype SVG. A `mirror` bundle also carries the selected `ppt-master.template-text-slots.v2-min` view; a `layout` bundle omits that mirror-only view. Never author a structured page from the roster or sidecar alone.
-**Exception**: user mid-deck adds pages or swaps templates introducing a basename absent from the original roster/batch → read the new file once, continue.
+**Missing or malformed derived sidecar** → continue from the complete prototype SVG in the bundle. Missing derived metadata alone does not invalidate a legacy workspace or authorize changing text topology.
-> The execution manifest reduces roster/context load; it never authorizes writing from selectors alone. The selected full SVG must be open before editing that page.
+**Exception**: If the user adds a page or swaps its prototype mid-deck, update the owning planning mapping and regenerate that page's bundle before authoring it.
-Resolve the per-page template SVG via `spec_lock.md page_layouts` (authoritative). There is no filename/page-type fallback.
+Resolve the per-page template SVG from `page_context.template.prototype`; the owning `spec_lock.md page_layouts` row remains authoritative. There is no filename/page-type fallback.
**Resolution order (per page):**
@@ -56,13 +52,13 @@ When `spec_lock.md` confirms `template_reuse_scope: mirror`, Executor switches t
1. **Per-page reference selection** — Strategist selects one mirror page per project page via `spec_lock.md page_layouts` (e.g., `P04: 015_content`). The basename is the mirror filename without extension; Strategist made this choice by reading `design_spec.md §V Page Roster` descriptions, not by guessing.
2. **Copy, don't fill** — open the referenced full mirror SVG immediately before authoring the page. Copy it as the starting point, then edit slide-specific text in place. Preserve every non-text element and every `data-pptx-*` structure attribute verbatim.
-3. **What you may edit** — only the visible string values already carried by `<text>` and `<tspan>` nodes that express slide-specific content (title, body, captions, KPI labels, dates, page numbers). Keep the number, order, nesting relationship, and **all attributes** of every `<text>` / `<tspan>` node unchanged. Never merge or split nodes, move a string between nodes, add a new tspan, or delete an empty carrier. The selected `text_slots_path` sidecar exposes the expected selectors/counts/hashes, but the complete SVG remains authoritative.
+3. **What you may edit** — decide the semantic slot mapping and replacement text only. Change only visible string values already carried by `<text>` and `<tspan>` nodes that express slide-specific content (title, body, captions, KPI labels, dates, page numbers). Keep the number, order, nesting relationship, and **all attributes** of every `<text>` / `<tspan>` node unchanged. Never merge or split nodes, move a string between nodes, add a new tspan, or delete an empty carrier. The minimal sidecar exposes only `selector`, `role`, `current_text`, `text_segments`, and `tspan_count`; `svg_quality_checker.py` and export validate attributes, topology, and prototype hashes internally.
4. **What you must not touch** — element positions, sizes, fonts, colors, fills, strokes, gradients, **which image each `<image>` points at**, `<g>` grouping, sprite-sheet `<svg viewBox>` wrappers, decorative `<rect>` / `<path>` / `<circle>` / `<polygon>` shapes, `<use data-icon="...">` markers, embedded chart data structures. Mirror's value is preserving the source deck's visual identity — any geometric / decorative drift defeats the purpose. **The `href` path is not the image**: normalizing a bare `href="cover_bg.png"` to `href="../images/<name>"` (when Step 3 relocated the asset to `images/`) points at the *same* image and changes nothing visual — that is an allowed path fix, not a fidelity edit. Leaving the bare href as-is is also fine; the exporter and live preview resolve bare hrefs against `images/` either way.
5. **Content fit** — if the replacement needs a different number of text segments/items, do not merge/split nodes, drop sourced content, or restructure the grid. Select a better mirror prototype and update the planning mappings, or report `warning: P<NN> content does not fit mirror reference <basename>; choose another prototype or change template_reuse_scope to layout/style`.
6. **Visible text editing** — mirror SVGs may keep literal source text rather than `{{...}}` authoring markers. Edit values in place while retaining imported semantic `data-pptx-placeholder` identity and exact text topology.
7. **Output filename** — follow the standard project SVG naming convention (`<NN>_<page_name>.svg` where `<NN>` matches the project page index, not the mirror source index). The mirror filename is the *reference*, not the *output*.
-**Detecting mirror mode**: read `template_reuse_scope` from `spec_lock.md` before every page. `replication_mode: mirror` in the installed template only determines whether that confirmed scope is legal; it must never force mirror behavior when the confirmed scope is `layout` or `style`.
+**Detecting mirror mode**: read `page_context.template.reuse_scope` from the current page-context bundle. `replication_mode: mirror` in the installed template only determines whether that confirmed scope is legal; it must never force mirror behavior when the confirmed scope is `layout` or `style`.
**Mirror + chart pages**: chart structures inside a mirror SVG are already drawn (axis, series, labels). Treat them as visual references — replace the data labels and series text content to match the project's chart spec, but do not redraw the chart from a `templates/charts/<name>.svg` baseline. A mirror template's `page_charts` entries are normally absent for this reason.
@@ -130,7 +126,7 @@ The exporter writes these solid fills as real Master/Layout/Slide `p:bg`, not se
**Per-page template lookup — `page_layouts` section (`mirror` / `layout` only)**:
-Before drawing each page, look up its entry in `page_layouts` to decide which basename to inherit (the full prototype was loaded in §1.0):
+Before drawing each page, use the bundled `page_context.template.prototype` to identify the inherited basename (the full prototype is included under §1.0):
- Entry present (e.g., `P04: 03a_content_image_text`) → inherit the corresponding full SVG. 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 structured template deck.
- No entry for this page with `template_reuse_scope: mirror|layout` → 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.
diff --git a/skills/ppt-master/references/native-shape-authoring.md b/skills/ppt-master/references/native-shape-authoring.md
index ed56b464..bf128708 100644
--- a/skills/ppt-master/references/native-shape-authoring.md
+++ b/skills/ppt-master/references/native-shape-authoring.md
@@ -79,7 +79,7 @@ preserve/mirror round-trip contract.
## 3. Fragment Generation
Run one command for one selected object. Generated project pages take colors
-from the current page's re-read `spec_lock.md`; `create-template` takes colors
+from the current page-context projection of `spec_lock.md`; `create-template` takes colors
from the confirmed brief and template `design_spec.md`. Mirror/preserve input
keeps the source object's paint instead of regenerating this authored form.
diff --git a/skills/ppt-master/references/strategist.md b/skills/ppt-master/references/strategist.md
index 3f3322ac..bc9a43bb 100644
--- a/skills/ppt-master/references/strategist.md
+++ b/skills/ppt-master/references/strategist.md
@@ -375,7 +375,7 @@ Content-outline and speaker-notes strategy follow the deck's locked **mode** —
This is what makes the axis meaningful: a `presentation` deck and a `text` deck built from the **same source and communication contract** must differ in page grammar, page count recommendation, per-page text volume, visual burden, layout density, rhythm, and notes—not only in font size. Page count stays the user's call; reading mode informs the recommendation when the user has not fixed one. Record it as **Reading Mode** in `design_spec.md §I` (compatibility key `delivery_purpose`, lock key `consumption_mode`). Separately, `communication_intent` / `audience_outcome` determine what the outline must accomplish, while `delivery_context` and `artifact_afterlife` help select the reading mode and still remain independent constraints after selection. The `page_rhythm` leans are a bias, not a quota. Preservation paths keep source wording and structure verbatim: honor reading mode only in styling and notes, never by rephrasing or re-paginating.
-> Note: §IX is the only content copy the Executor re-reads after context compression — what you write there is what survives.
+> Note: §IX is the content copy projected into each Executor page-context — what you write there is what survives context compression.
### 6.2 Planning Artifact Content
@@ -383,7 +383,7 @@ Generate Step 4 creates `design_spec.md` and `spec_lock.md` from their versioned
Fill the scaffolded artifacts from the confirmed state and analysis. In §IX, each page carries layout, title, one core message, an **Audience move**, final content wording, applicable visualization/image references, `Fact IDs` for sourced claims, and `Data class: scenario` for invented demonstration data. Run `project_manager.py validate` after both artifacts are filled.
-**Execution lock content**: `spec_lock.md` is the compact communication and execution contract for colors, typography, icons, images, page rhythm, chart choices, and route-specific PowerPoint structure. Do not copy `content_divergence` into the lock; its effect is already authored into §IX. Free-design, brand-only, and `template_reuse_scope: style` routes write `pptx_structure.mode: flat`; the conditional template module owns every structured mapping. Executor re-reads the lock before every page (see [executor-base.md](executor-base.md) §2.1). Values must match `design_spec.md`; on divergence, `spec_lock.md` wins and the design spec is historical narrative.
+**Execution lock content**: `spec_lock.md` is the compact communication and execution contract for colors, typography, icons, images, page rhythm, chart choices, and route-specific PowerPoint structure. Do not copy `content_divergence` into the lock; its effect is already authored into §IX. Free-design, brand-only, and `template_reuse_scope: style` routes write `pptx_structure.mode: flat`; the conditional template module owns every structured mapping. Executor rebuilds the lock's current-page projection before every page (see [executor-base.md](executor-base.md) §2.1). Values must match `design_spec.md`; on divergence, `spec_lock.md` wins and the design spec is historical narrative.
- **Communication trace is mandatory**: Copy `audience`, `communication_intent`, `audience_outcome`, `core_message`, `delivery_context`, `artifact_afterlife`, and canonical `consumption_mode` into `spec_lock.md communication`. Before finalizing §IX, check that every named purpose has at least one outline obligation and **every Slide block**, including cover / divider / closing pages, has an `Audience move` that advances the global outcome. A page that advances no purpose or outcome should be merged, rewritten, or cut. `project_manager.py validate` and `svg_quality_checker.py` enforce the section / field presence, not the subjective quality of the move.
- **page_rhythm is mandatory**: Based on the page list in §IX Content Outline, assign each page one of `anchor` / `dense` / `breathing`. This is what breaks the uniform "every page is a card grid" feel. New locks may not omit the section; consumer omission behavior is owned by [`executor-base.md`](executor-base.md) §2.1.
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 4f46824c..6fef40bf 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -45,7 +45,7 @@ python3 scripts/update_repo.py
| Area | Primary scripts | Documentation |
|------|-----------------|---------------|
| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |
-| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) |
+| Project management | `project_manager.py`, `page_context.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) |
| SVG pipeline | `preset_shape_svg.py`, `svg_authoring_view.py`, `compact_svg_coordinates.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native preset authoring](../references/native-shape-authoring.md) |
| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
@@ -76,8 +76,17 @@ python3 scripts/project_manager.py import-sources <project_path> <source_files_o
python3 scripts/project_manager.py scaffold-spec <project_path>
python3 scripts/project_manager.py scaffold-lock <project_path>
python3 scripts/project_manager.py validate <project_path>
+python3 scripts/project_manager.py page-context <project_path> P07 --bundle --record-usage
+python3 scripts/project_manager.py page-context-report <project_path>
```
+`page-context` prints a read-only current-page projection by default. The
+optional bundle adds the complete selected prototype for structured layout
+reuse and, for mirror reuse, a minimal text-slot sidecar. `--record-usage`
+requires `--bundle` and writes one derived snapshot under
+`analysis/page-context/`; exact `o200k_base` token counts are optional and
+degrade to `tokens: null` when `tiktoken` is absent.
+
Chart candidate recall:
```bash
@@ -138,9 +147,15 @@ opaque `txBody`, shape-style, and custom-geometry payloads are deduplicated into
are stored there as short `data-pptx-native-ref` records. Structural metadata
stays inline, while checker, template-structure validation, and export hydrate
both layers in memory. Legacy inline payload and v1 payload-only stores remain
-readable. Bitmap assets go to `images/`; other referenced source assets go to
-`templates/assets/`. The destination must be empty, and the command does not
-write `templates/design_spec.md`; Template_Designer owns that authored brief.
+readable. The v1 execution manifest points to per-prototype
+`ppt-master.template-text-slots.v2-min` sidecars. Those sidecars expose only
+text selectors, semantic roles, current/segmented text, and tspan counts;
+page-context validates and strips their top-level tool integrity hash before
+model output, while checker and export validate output attributes, topology,
+and resource hashes against the complete prototype internally. Bitmap assets
+go to `images/`; other referenced source assets go to `templates/assets/`.
+The destination must be empty, and the command does not write
+`templates/design_spec.md`; Template_Designer owns that authored brief.
`template_preview_pptx.py` reads a template workspace, exports every public `templates/*.svg` prototype as one structured review slide, and verifies the resulting Master/Layout package. Canonical definition-only `layout_<layout_key>.svg` prototypes are registered as reusable Layouts through internal carrier slides that are removed before publication; they never increase the review deck's visible slide count. This is an on-demand review action: its default output is `exports/<template_id>_template_preview.pptx`, and that directory need not exist before the command runs. It refuses an existing output unless an intentional re-export passes `--force`. `--visual-only` is an explicit migration aid for legacy SVG rosters: it creates a slide-local visual review deck without validating or claiming a reusable Master/Layout contract. This diagnostic path does not require a project `spec_lock.md`; it may retain generic theme/text defaults inside its clean one-Master/one-Layout shell. New structured templates use the default mode when a review deck is requested.
diff --git a/skills/ppt-master/scripts/docs/project.md b/skills/ppt-master/scripts/docs/project.md
index 12083681..b7cc33dc 100644
--- a/skills/ppt-master/scripts/docs/project.md
+++ b/skills/ppt-master/scripts/docs/project.md
@@ -17,6 +17,8 @@ python3 scripts/project_manager.py scaffold-spec <project_path>
python3 scripts/project_manager.py scaffold-lock <project_path>
python3 scripts/project_manager.py validate <project_path>
python3 scripts/project_manager.py info <project_path>
+python3 scripts/project_manager.py page-context <project_path> P07 [--bundle] [--pretty] [--record-usage]
+python3 scripts/project_manager.py page-context-report <project_path>
```
Notes:
@@ -47,6 +49,48 @@ Notes:
Multi-deck per project: several PPTX imports each get their own `<stem>.*`
artifacts and a `decks[]` entry; re-importing the same stem replaces its entry.
+### Per-page execution view
+
+`page-context` projects `design_spec.md` and `spec_lock.md` into one current-page
+view on stdout. The default command is read-only; `--pretty` changes JSON
+formatting only. `--bundle` appends only the route-selected authoring payloads:
+
+| Project mode | Bundle contents |
+|---|---|
+| `flat` | page context |
+| structured `layout` | page context + complete selected prototype SVG |
+| structured `mirror` | page context + `text-slots.v2-min` + complete selected prototype SVG |
+
+The projection keeps project-specific forbidden rules; universal SVG and icon
+rules remain in the always-loaded execution core. Image rows are selected from
+the current §IX brief, explicit §VIII page assignments, and mirror prototype
+references. When those sources assign images elsewhere but not to the current
+page, the view excludes those assigned images. Any still-unassigned legacy
+image remains in a compatibility subset; `confirmed-none` is emitted only when
+all locked images have a deterministic assignment elsewhere.
+
+Mirror materialization publishes `ppt-master.template-text-slots.v2-min` with
+only `selector`, `role`, `current_text`, `text_segments`, and `tspan_count` per
+text node. Its top-level integrity hash covers selectors plus immutable text
+and tspan topology/attributes. `page-context` recomputes that hash and every
+model-visible field from the complete prototype before stripping the hash from
+the bundle. A legacy v1 sidecar receives the same checks and is projected to the
+same model-facing shape in memory; the workspace is not rewritten. The complete
+SVG remains in the bundle. Checker and structured export validate output
+attributes, text/tspan topology, and referenced-resource hashes internally, so
+authoring supplies only semantic choices and edits only the existing visible
+text values.
+
+`--record-usage` requires `--bundle` and writes a derived snapshot to
+`analysis/page-context/P<NN>.usage.json`. It hashes every input and measures the
+exact controlled stdout plus each component; expected-but-absent optional inputs
+are recorded so later artifact creation invalidates the snapshot. `tiktoken` is
+loaded lazily with `o200k_base`; when unavailable, the command still succeeds
+and records bytes, characters, hashes, and `tokens: null`.
+`page-context-report` summarizes only fresh snapshots and identifies stale or
+token-unavailable pages. The telemetry does not include source-material reads
+or session-level prompt references.
+
Common formats:
- `ppt169`
- `ppt43`
@@ -64,6 +108,8 @@ python3 scripts/project_manager.py scaffold-spec projects/my_presentation_ppt169
python3 scripts/project_manager.py scaffold-lock projects/my_presentation_ppt169_20251116
python3 scripts/project_manager.py validate projects/my_presentation_ppt169_20251116
python3 scripts/project_manager.py info projects/my_presentation_ppt169_20251116
+python3 scripts/project_manager.py page-context projects/my_presentation_ppt169_20251116 P07 --bundle --record-usage
+python3 scripts/project_manager.py page-context-report projects/my_presentation_ppt169_20251116
```
## `project_utils.py`
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index d820f547..34c4bc83 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -165,6 +165,19 @@ fields remain inline. Source `p:sldLayout@showMasterSp` and
Checker, template-structure validation, and export hydrate both store layers in
memory; legacy inline payload and v1 payload-only stores remain readable.
+The published `ppt-master.template-execution-manifest.v1` roster points to one
+compact `ppt-master.template-text-slots.v2-min` sidecar per prototype. Each text
+slot contains only `selector`, `role`, `current_text`, `text_segments`, and
+`tspan_count`; a top-level tool hash covers its selectors and immutable
+text/tspan topology and attributes. A current-page mirror bundle still includes
+the complete prototype SVG. Page projection recomputes the hash and projected
+fields against that prototype, then strips the hash from model context. The
+model chooses semantics and edits only existing visible text values, while
+checker and structured export validate output attributes, text/tspan topology,
+and referenced-resource hashes against the prototype. Runtime page projection
+accepts legacy v1 text-slot sidecars and reduces them to v2-min without
+rewriting the workspace.
+
The output routes reusable vectors once to `icons/imported/`, bitmaps to
`images/`, and other referenced files to `templates/assets/`. The JSON report
reports payload occurrence, native-record, unique-byte, and compressed-store
diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.py
index 7badc511..ebc5b81c 100644
--- a/skills/ppt-master/scripts/mirror_template_materialize.py
+++ b/skills/ppt-master/scripts/mirror_template_materialize.py
@@ -59,6 +59,10 @@ from svg_to_pptx.pptx_package.template_structure import (
TemplateStructureError,
parse_template_slides,
)
+from template_text_slots import (
+ analyze_template_text_slots,
+ text_slot_integrity_sha256,
+)
configure_utf8_stdio()
@@ -70,7 +74,7 @@ VECTOR_INVENTORY_SCHEMA = "vector_asset_inventory.v1"
TEMPLATE_EXECUTION_MANIFEST_NAME = "template_execution_manifest.json"
TEMPLATE_EXECUTION_MANIFEST_SCHEMA = "ppt-master.template-execution-manifest.v1"
TEMPLATE_TEXT_SLOTS_DIR = "template_execution"
-TEMPLATE_TEXT_SLOTS_SCHEMA = "ppt-master.template-text-slots.v1"
+TEMPLATE_TEXT_SLOTS_SCHEMA = "ppt-master.template-text-slots.v2-min"
IMPORTED_ICON_NAMESPACE = "imported"
TRANSPARENT_PIXEL_DATA_URI = (
"data:image/png;base64,"
@@ -206,142 +210,18 @@ class MaterializedFile:
payload: bytes
-def _ancestor_chain(
- element: ET.Element,
- parent_by_child: dict[ET.Element, ET.Element],
-) -> list[ET.Element]:
- """Return one element followed by its ancestors up to the SVG root."""
- chain = [element]
- while chain[-1] in parent_by_child:
- chain.append(parent_by_child[chain[-1]])
- return chain
-
-
-def _stable_text_selector(
- element: ET.Element,
- parent_by_child: dict[ET.Element, ET.Element],
-) -> str:
- """Build a stable, human-readable selector for one materialized text node."""
- segments: list[str] = []
- current = element
- while True:
- element_id = (current.get("id") or "").strip()
- if element_id:
- segments.append(f"#{element_id}")
- break
- parent = parent_by_child.get(current)
- tag = _local_name(current.tag)
- if parent is None:
- segments.append(tag)
- break
- same_tag = [
- child
- for child in parent
- if _local_name(child.tag) == tag
- ]
- position = same_tag.index(current) + 1
- segments.append(f"{tag}:nth-of-type({position})")
- current = parent
- return " > ".join(reversed(segments))
-
-
-def _nearest_attribute(
- chain: list[ET.Element],
- name: str,
-) -> str | None:
- for element in chain:
- value = element.get(name)
- if value is not None:
- return value
- return None
-
-
-def _text_slot_bounds(chain: list[ET.Element]) -> dict[str, float | None]:
- """Read the nearest four-value placeholder/native frame when available."""
- for name in ("data-pptx-placeholder-bounds", "data-pptx-frame"):
- raw = _nearest_attribute(chain, name)
- if raw is None:
- continue
- try:
- values = [float(value) for value in raw.replace(",", " ").split()]
- except ValueError:
- continue
- if len(values) == 4 and all(math.isfinite(value) for value in values):
- return dict(zip(("x", "y", "width", "height"), values))
- return {"x": None, "y": None, "width": None, "height": None}
-
-
-def _text_topology_sha256(element: ET.Element) -> str:
- """Hash text/tspan topology and attributes while excluding visible values."""
- digest = hashlib.sha256()
-
- def visit(node: ET.Element) -> None:
- digest.update(_local_name(node.tag).encode("utf-8"))
- for name, value in sorted(node.attrib.items()):
- digest.update(b"\0a")
- digest.update(name.encode("utf-8"))
- digest.update(b"\0")
- digest.update(value.encode("utf-8"))
- for child in node:
- digest.update(b"\0c")
- visit(child)
- digest.update(b"\0e")
-
- visit(element)
- return digest.hexdigest()
-
-
-def _template_text_slots(root: ET.Element) -> list[dict[str, object]]:
- """Describe exact mirror-safe text replacement slots for one template."""
- parent_by_child = {
- child: parent
- for parent in root.iter()
- for child in parent
- }
- slots: list[dict[str, object]] = []
- for text_element in root.iter():
- if _local_name(text_element.tag) != "text":
- continue
- chain = _ancestor_chain(text_element, parent_by_child)
- placeholder = _nearest_attribute(chain, "data-pptx-placeholder")
- editable_value = _nearest_attribute(chain, "data-pptx-editable")
- inherited_layer = _nearest_attribute(chain, "data-pptx-layer")
- tspans = [
- child
- for child in text_element.iter()
- if child is not text_element and _local_name(child.tag) == "tspan"
- ]
- segments = [
- text_element.text or "",
- *[(tspan.text or "") for tspan in tspans],
- ]
- if tspans and not segments[0].strip():
- segments = segments[1:]
- slots.append({
- "selector": _stable_text_selector(text_element, parent_by_child),
- "role": placeholder or "text",
- "editable": editable_value != "false" and inherited_layer is None,
- "current_text": "".join(text_element.itertext()),
- "text_segments": segments,
- "text_attributes": dict(sorted(text_element.attrib.items())),
- "tspan_count": len(tspans),
- "tspan_attributes": [
- dict(sorted(tspan.attrib.items()))
- for tspan in tspans
- ],
- "topology_sha256": _text_topology_sha256(text_element),
- "bbox": _text_slot_bounds(chain),
- "font_stack": _nearest_attribute(chain, "font-family"),
- })
- return slots
-
-
def _json_bytes(payload: dict[str, object]) -> bytes:
return (
json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
).encode("utf-8")
+def _compact_json_bytes(payload: dict[str, object]) -> bytes:
+ return (
+ json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"
+ ).encode("utf-8")
+
+
def _template_execution_manifest_files(
materialized_roots: list[tuple[Path, ET.Element]],
source_import: dict[str, object] | None,
@@ -354,7 +234,14 @@ def _template_execution_manifest_files(
key=lambda item: item[0].as_posix(),
):
prototype = relative_path.name
- text_slots = _template_text_slots(root)
+ try:
+ analyzed_slots = analyze_template_text_slots(root)
+ except ValueError as exc:
+ raise MirrorMaterializationError(
+ f"Cannot project text slots for {prototype}: {exc}"
+ ) from exc
+ text_slots = [slot.model_payload() for slot in analyzed_slots]
+ editable_text_slot_count = sum(slot.editable for slot in analyzed_slots)
text_slots_path = (
Path("templates")
/ TEMPLATE_TEXT_SLOTS_DIR
@@ -362,10 +249,11 @@ def _template_execution_manifest_files(
)
files.append(MaterializedFile(
text_slots_path,
- _json_bytes({
+ _compact_json_bytes({
"schema": TEMPLATE_TEXT_SLOTS_SCHEMA,
"prototype": prototype,
"text_slot_count": len(text_slots),
+ "tool_integrity_sha256": text_slot_integrity_sha256(analyzed_slots),
"text_slots": text_slots,
}),
))
@@ -377,9 +265,7 @@ def _template_execution_manifest_files(
"layout": root.get("data-pptx-layout"),
"layout_name": root.get("data-pptx-layout-name"),
"text_slot_count": len(text_slots),
- "editable_text_slot_count": sum(
- 1 for slot in text_slots if slot["editable"]
- ),
+ "editable_text_slot_count": editable_text_slot_count,
"text_slots_path": text_slots_path.relative_to(
Path("templates")
).as_posix(),
@@ -389,11 +275,16 @@ def _template_execution_manifest_files(
"replication_mode": "mirror",
"template_root": ".",
"template_count": len(templates),
+ "text_slots_schema": TEMPLATE_TEXT_SLOTS_SCHEMA,
"execution_policy": (
- "Read this compact roster once. Before authoring each page, read the "
- "selected template's text_slots_path and complete prototype SVG. "
- "Replace visible text values only; preserve every text/tspan node, "
- "order, nesting level, and attribute."
+ "Read this compact roster once. Before authoring each page, run "
+ "project_manager.py page-context <project> P<NN> --bundle "
+ "--record-usage; do not "
+ "read text_slots_path directly. The bundle validates the selected "
+ f"{TEMPLATE_TEXT_SLOTS_SCHEMA} projection and includes the complete "
+ "prototype. Choose semantic replacements and edit only existing "
+ "visible text values; structured export validates text/tspan "
+ "topology and attributes against the prototype."
),
"source_import": source_import or {
"warning_count": 0,
diff --git a/skills/ppt-master/scripts/page_context.py b/skills/ppt-master/scripts/page_context.py
new file mode 100644
index 00000000..301effc7
--- /dev/null
+++ b/skills/ppt-master/scripts/page_context.py
@@ -0,0 +1,1037 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Page Context Projection
+
+Build deterministic per-page execution views and optional token telemetry.
+
+Usage:
+ Imported by project_manager.py.
+
+Examples:
+ build_page_context(Path("projects/demo"), "P07")
+
+Dependencies:
+ None for projection; tiktoken is optional for exact usage counts.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import re
+import statistics
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Iterable
+
+from project_specs import default_spec_lock_forbidden, parse_markdown_artifact
+from svg_to_pptx.pptx_package.template_structure import (
+ PptxStructureLock,
+ TemplateStructureError,
+ load_pptx_structure_lock,
+)
+from template_text_slots import (
+ MODEL_TEXT_SLOT_KEYS,
+ TemplateTextSlot,
+ analyze_template_text_slots,
+ text_slot_integrity_sha256,
+)
+
+
+PAGE_CONTEXT_SCHEMA = "ppt-master.page-context.v1"
+PAGE_CONTEXT_USAGE_SCHEMA = "ppt-master.page-context-usage.v1"
+PAGE_CONTEXT_REPORT_SCHEMA = "ppt-master.page-context-usage-report.v1"
+TEXT_SLOTS_V1_SCHEMA = "ppt-master.template-text-slots.v1"
+TEXT_SLOTS_MIN_SCHEMA = "ppt-master.template-text-slots.v2-min"
+EXECUTION_MANIFEST_SCHEMA = "ppt-master.template-execution-manifest.v1"
+TOKEN_ENCODING = "o200k_base"
+PAGE_CONTEXT_TOKEN_TARGET = 800
+TEXT_SLOTS_TOKEN_TARGET = 1000
+
+_PAGE_RE = re.compile(r"^(?:P)?([0-9]+)$", re.IGNORECASE)
+_SLIDE_HEADING_RE = re.compile(
+ r"^####[ \t]+Slide[ \t]+0*([0-9]+)(?:[ \t]*(?:[-:–—]).*)?$",
+ re.IGNORECASE | re.MULTILINE,
+)
+_BLOCK_BOUNDARY_RE = re.compile(r"^#{2,4}[ \t]+", re.MULTILINE)
+_PART_HEADING_RE = re.compile(r"^###[ \t]+(?!#)(.+?)[ \t]*$", re.MULTILINE)
+_PAGE_TOKEN_RE = re.compile(
+ r"(?<![A-Za-z0-9_])P0*([1-9][0-9]*)(?![A-Za-z0-9_])",
+ re.IGNORECASE,
+)
+class PageContextError(RuntimeError):
+ """Reject an incomplete or ambiguous page-context request."""
+
+
+@dataclass(frozen=True)
+class PageRead:
+ """One exact model-visible page payload."""
+
+ kind: str
+ path: str
+ payload: str
+ source_path: Path | None = None
+ source_schema: str | None = None
+
+
+@dataclass(frozen=True)
+class PageContextResult:
+ """One projected page view plus its conditional document payloads."""
+
+ project_path: Path
+ page: str
+ context: dict[str, object]
+ reads: tuple[PageRead, ...]
+ inputs: tuple[Path, ...]
+ absent_inputs: tuple[Path, ...]
+
+
+def normalize_page_key(raw_page: str) -> tuple[str, int]:
+ """Normalize a positive page identifier to the schema's P<NN> form."""
+ match = _PAGE_RE.fullmatch(raw_page.strip())
+ if match is None or int(match.group(1)) <= 0:
+ raise PageContextError("page must be a positive P<NN> identifier")
+ number = int(match.group(1))
+ return f"P{number:02d}", number
+
+
+def _section_index(
+ sections: Iterable[dict[str, object]],
+) -> dict[str, dict[str, object]]:
+ return {
+ str(section["heading"]).strip().casefold(): section
+ for section in sections
+ }
+
+
+def _section_fields(
+ sections: dict[str, dict[str, object]],
+ heading: str,
+) -> dict[str, str]:
+ section = sections.get(heading.casefold())
+ if section is None:
+ return {}
+ fields = section.get("fields", {})
+ if not isinstance(fields, dict):
+ return {}
+ return {str(key): str(value) for key, value in fields.items()}
+
+
+def _forbidden_items(
+ sections: dict[str, dict[str, object]],
+) -> list[str]:
+ section = sections.get("forbidden")
+ if section is None:
+ return []
+ items: list[str] = []
+ default_items = default_spec_lock_forbidden()
+ for raw_line in str(section.get("body", "")).splitlines():
+ line = raw_line.strip()
+ if not line:
+ continue
+ item = re.sub(r"^-[ \t]+", "", line)
+ if item not in default_items:
+ items.append(item)
+ return items
+
+
+def _outline_section(
+ sections: Iterable[dict[str, object]],
+) -> dict[str, object] | None:
+ for section in sections:
+ heading = str(section.get("heading", "")).strip().casefold()
+ if heading == "content outline" or heading.endswith(". content outline"):
+ return section
+ return None
+
+
+def _page_image_filenames(
+ design_sections: Iterable[dict[str, object]],
+ page_number: int,
+) -> tuple[set[str], set[str]]:
+ """Read explicit P<NN> usage from the canonical image-resource table."""
+ section = next(
+ (
+ item
+ for item in design_sections
+ if (
+ (heading := str(item.get("heading", "")).strip().casefold())
+ == "image resource list"
+ or heading.startswith("viii. image resource list")
+ )
+ ),
+ None,
+ )
+ if section is None:
+ return set(), set()
+ table_rows = [
+ [
+ cell.strip().replace(r"\|", "|")
+ for cell in re.split(r"(?<!\\)\|", line.strip().strip("|"))
+ ]
+ for line in str(section.get("body", "")).splitlines()
+ if line.strip().startswith("|") and line.strip().endswith("|")
+ ]
+ if not table_rows:
+ return set(), set()
+ header = {
+ name.casefold(): index
+ for index, name in enumerate(table_rows[0])
+ }
+ filename_index = header.get("filename")
+ purpose_index = header.get("purpose")
+ if filename_index is None or purpose_index is None:
+ return set(), set()
+ assigned: set[str] = set()
+ selected: set[str] = set()
+ for row in table_rows[1:]:
+ if len(row) <= max(filename_index, purpose_index):
+ continue
+ purpose = row[purpose_index]
+ pages = {int(match.group(1)) for match in _PAGE_TOKEN_RE.finditer(purpose)}
+ if not pages:
+ continue
+ filename = row[filename_index].strip().strip("`")
+ if not filename:
+ continue
+ basename = Path(filename).name
+ assigned.add(basename)
+ if page_number in pages:
+ selected.add(basename)
+ return assigned, selected
+
+
+def _locked_image_basename(value: str) -> str:
+ return Path(value.split("|", 1)[0].strip()).name
+
+
+def _outline_image_assignments(
+ design_sections: Iterable[dict[str, object]],
+ locked_images: dict[str, str],
+) -> set[str]:
+ outline = _outline_section(design_sections)
+ if outline is None:
+ return set()
+ body = str(outline.get("body", ""))
+ return {
+ _locked_image_basename(value)
+ for key, value in locked_images.items()
+ if any(
+ _contains_token(body, token)
+ for token in (
+ key,
+ value.split("|", 1)[0].strip(),
+ _locked_image_basename(value),
+ )
+ )
+ }
+
+
+def _slide_block(
+ design_sections: Iterable[dict[str, object]],
+ page_number: int,
+) -> tuple[str | None, str]:
+ outline = _outline_section(design_sections)
+ if outline is None:
+ raise PageContextError("design_spec.md has no Content Outline section")
+ body = str(outline.get("body", ""))
+ matches = [
+ match
+ for match in _SLIDE_HEADING_RE.finditer(body)
+ if int(match.group(1)) == page_number
+ ]
+ if not matches:
+ raise PageContextError(
+ f"design_spec.md Content Outline has no Slide {page_number:02d} block"
+ )
+ if len(matches) > 1:
+ raise PageContextError(
+ f"design_spec.md Content Outline repeats Slide {page_number:02d}"
+ )
+ match = matches[0]
+ next_boundary = _BLOCK_BOUNDARY_RE.search(body, match.end())
+ block_end = next_boundary.start() if next_boundary else len(body)
+ block = body[match.start():block_end].strip()
+ part_matches = list(_PART_HEADING_RE.finditer(body, 0, match.start()))
+ part = part_matches[-1].group(1).strip() if part_matches else None
+ return part, block
+
+
+def _relative_project_path(project_path: Path, path: Path) -> str:
+ try:
+ return path.resolve().relative_to(project_path).as_posix()
+ except ValueError as exc:
+ raise PageContextError(f"path escapes project: {path}") from exc
+
+
+def _prototype_image_refs(svg_path: Path) -> list[str]:
+ try:
+ root = ET.parse(svg_path).getroot()
+ except (OSError, ET.ParseError) as exc:
+ raise PageContextError(f"cannot read prototype SVG {svg_path}: {exc}") from exc
+ refs: set[str] = set()
+ for element in root.iter():
+ if element.tag.rsplit("}", 1)[-1] != "image":
+ continue
+ for name, value in element.attrib.items():
+ if name.rsplit("}", 1)[-1] != "href":
+ continue
+ normalized = value.strip()
+ if normalized and not normalized.startswith(("data:", "#")):
+ refs.add(normalized)
+ return sorted(refs)
+
+
+def _contains_token(text: str, token: str) -> bool:
+ if not token:
+ return False
+ if re.fullmatch(r"[A-Za-z0-9_]+", token):
+ return re.search(
+ rf"(?<![A-Za-z0-9_]){re.escape(token)}(?![A-Za-z0-9_])",
+ text,
+ ) is not None
+ return token in text
+
+
+def _page_images(
+ locked_images: dict[str, str],
+ brief: str,
+ prototype_refs: list[str],
+ assigned_filenames: set[str],
+ resolved_filenames: set[str],
+) -> tuple[str, dict[str, str]]:
+ if not locked_images:
+ return "none", {}
+ ref_basenames = {Path(ref).name for ref in prototype_refs}
+ selected: dict[str, str] = {}
+ unresolved: dict[str, str] = {}
+ for key, value in locked_images.items():
+ basename = _locked_image_basename(value)
+ if (
+ _contains_token(brief, key)
+ or _contains_token(brief, value)
+ or _contains_token(brief, basename)
+ or basename in ref_basenames
+ or basename in assigned_filenames
+ ):
+ selected[key] = value
+ elif basename not in resolved_filenames:
+ unresolved[key] = value
+ if selected and unresolved:
+ return "explicit+unassigned", {**selected, **unresolved}
+ if selected:
+ return "explicit", selected
+ if unresolved:
+ return "unassigned", unresolved
+ return "confirmed-none", {}
+
+
+def _page_template(
+ project_path: Path,
+ structure_lock: PptxStructureLock | None,
+ page_number: int,
+) -> tuple[dict[str, object] | None, Path | None]:
+ if structure_lock is None or structure_lock.mode != "structured":
+ return None, None
+ prototype = next(
+ (item for item in structure_lock.prototypes if item.slide_num == page_number),
+ None,
+ )
+ assignment = next(
+ (item for item in structure_lock.layouts if item.slide_num == page_number),
+ None,
+ )
+ if prototype is None or assignment is None:
+ raise PageContextError(
+ f"structured lock has no complete mapping for P{page_number:02d}"
+ )
+ definition = next(
+ (
+ item
+ for item in structure_lock.layout_definitions
+ if item.layout_key == assignment.layout_key
+ ),
+ None,
+ )
+ if definition is None:
+ raise PageContextError(
+ f"structured lock has no definition for Layout {assignment.layout_key!r}"
+ )
+ master = next(
+ (
+ item
+ for item in structure_lock.masters
+ if item.master_key == definition.master_key
+ ),
+ None,
+ )
+ if master is None:
+ raise PageContextError(
+ f"structured lock has no definition for Master {definition.master_key!r}"
+ )
+ template = {
+ "reuse_scope": structure_lock.template_reuse_scope,
+ "adherence": structure_lock.template_adherence,
+ "prototype": prototype.template_basename,
+ "prototype_path": _relative_project_path(project_path, prototype.svg_path),
+ "layout": {
+ "key": definition.layout_key,
+ "name": definition.layout_name,
+ "source": (
+ f"P{definition.prototype_slide_num:02d}"
+ if definition.prototype_slide_num is not None
+ else _relative_project_path(
+ project_path,
+ definition.prototype_svg_path,
+ )
+ ),
+ },
+ "master": {
+ "key": master.master_key,
+ "name": master.master_name,
+ },
+ }
+ return template, prototype.svg_path
+
+
+def _project_text_slots(
+ payload: object,
+ expected_prototype: str,
+ prototype_slots: tuple[TemplateTextSlot, ...],
+) -> dict[str, object]:
+ if not isinstance(payload, dict):
+ raise PageContextError("text-slot sidecar root must be an object")
+ source_schema = payload.get("schema")
+ if source_schema not in {TEXT_SLOTS_V1_SCHEMA, TEXT_SLOTS_MIN_SCHEMA}:
+ raise PageContextError(f"unsupported text-slot schema: {source_schema!r}")
+ prototype = payload.get("prototype")
+ if prototype != expected_prototype:
+ raise PageContextError(
+ f"text-slot sidecar prototype {prototype!r} does not match "
+ f"{expected_prototype!r}"
+ )
+ raw_slots = payload.get("text_slots")
+ if not isinstance(raw_slots, list):
+ raise PageContextError("text-slot sidecar requires a text_slots array")
+ slots: list[dict[str, object]] = []
+ for index, raw_slot in enumerate(raw_slots, start=1):
+ if not isinstance(raw_slot, dict):
+ raise PageContextError(f"text slot {index} must be an object")
+ missing = [key for key in MODEL_TEXT_SLOT_KEYS if key not in raw_slot]
+ if missing:
+ raise PageContextError(
+ f"text slot {index} is missing: {', '.join(missing)}"
+ )
+ segments = raw_slot["text_segments"]
+ if not isinstance(segments, list) or not all(
+ isinstance(segment, str) for segment in segments
+ ):
+ raise PageContextError(
+ f"text slot {index} text_segments must be an array of strings"
+ )
+ if type(raw_slot["tspan_count"]) is not int or raw_slot["tspan_count"] < 0:
+ raise PageContextError(
+ f"text slot {index} tspan_count must be a non-negative integer"
+ )
+ if not all(
+ isinstance(raw_slot[key], str)
+ for key in ("selector", "role", "current_text")
+ ):
+ raise PageContextError(
+ f"text slot {index} selector/role/current_text must be strings"
+ )
+ slots.append({key: raw_slot[key] for key in MODEL_TEXT_SLOT_KEYS})
+ declared_count = payload.get("text_slot_count")
+ if type(declared_count) is not int or declared_count != len(slots):
+ raise PageContextError(
+ "text-slot sidecar text_slot_count does not match text_slots"
+ )
+ if len(prototype_slots) != len(slots):
+ raise PageContextError(
+ "text-slot sidecar does not match the prototype text-slot count"
+ )
+ expected_slots = [slot.model_payload() for slot in prototype_slots]
+ if source_schema == TEXT_SLOTS_MIN_SCHEMA:
+ integrity = payload.get("tool_integrity_sha256")
+ expected_integrity = text_slot_integrity_sha256(prototype_slots)
+ if integrity != expected_integrity:
+ raise PageContextError(
+ "text-slot sidecar integrity hash does not match the prototype"
+ )
+ if slots != expected_slots:
+ raise PageContextError(
+ "text-slot sidecar values do not match the prototype"
+ )
+ else:
+ for index, (raw_slot, actual_slot, expected_slot) in enumerate(
+ zip(raw_slots, prototype_slots, expected_slots),
+ start=1,
+ ):
+ if raw_slot["selector"] not in {
+ actual_slot.selector,
+ actual_slot.legacy_selector,
+ }:
+ raise PageContextError(
+ f"legacy text slot {index} selector does not match the prototype"
+ )
+ if any(
+ raw_slot[key] != expected_slot[key]
+ for key in MODEL_TEXT_SLOT_KEYS
+ if key != "selector"
+ ):
+ raise PageContextError(
+ f"legacy text slot {index} values do not match the prototype"
+ )
+ if raw_slot.get("topology_sha256") != actual_slot.topology_sha256:
+ raise PageContextError(
+ f"legacy text slot {index} topology hash does not match the prototype"
+ )
+ return {
+ "schema": TEXT_SLOTS_MIN_SCHEMA,
+ "prototype": expected_prototype,
+ "text_slot_count": len(expected_slots),
+ "text_slots": expected_slots,
+ }
+
+
+def _text_slots_read(
+ project_path: Path,
+ prototype_path: Path,
+ inputs: list[Path],
+ absent_inputs: list[Path],
+ warnings: list[str],
+) -> PageRead | None:
+ templates_dir = project_path / "templates"
+ manifest_path = templates_dir / "template_execution_manifest.json"
+ candidate: Path | None = None
+ if manifest_path.is_file():
+ inputs.append(manifest_path)
+ try:
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ if manifest.get("schema") != EXECUTION_MANIFEST_SCHEMA:
+ raise PageContextError("unsupported template execution manifest schema")
+ entries = manifest.get("templates")
+ if not isinstance(entries, list):
+ raise PageContextError("template execution manifest has no templates list")
+ entry = next(
+ (
+ item
+ for item in entries
+ if isinstance(item, dict)
+ and item.get("prototype") == prototype_path.name
+ ),
+ None,
+ )
+ if entry is not None and isinstance(entry.get("text_slots_path"), str):
+ resolved = (templates_dir / str(entry["text_slots_path"])).resolve()
+ if resolved.is_relative_to(templates_dir.resolve()):
+ candidate = resolved
+ except (OSError, json.JSONDecodeError, PageContextError) as exc:
+ warnings.append(
+ f"template execution manifest unavailable; using prototype only ({exc})"
+ )
+ else:
+ absent_inputs.append(manifest_path)
+ conventional = (
+ templates_dir
+ / "template_execution"
+ / f"{prototype_path.stem}.text-slots.json"
+ )
+ if candidate is None:
+ candidate = conventional
+ if not candidate.is_file():
+ absent_inputs.append(candidate)
+ warnings.append(
+ f"{prototype_path.name} has no usable text-slot sidecar; "
+ "use the complete prototype SVG"
+ )
+ return None
+ inputs.append(candidate)
+ try:
+ prototype_root = ET.parse(prototype_path).getroot()
+ prototype_slots = analyze_template_text_slots(prototype_root)
+ source_payload = json.loads(candidate.read_text(encoding="utf-8"))
+ projected = _project_text_slots(
+ source_payload,
+ prototype_path.name,
+ prototype_slots,
+ )
+ except (OSError, ET.ParseError, ValueError, json.JSONDecodeError, PageContextError) as exc:
+ warnings.append(
+ f"{candidate.name} is unusable; use the complete prototype SVG ({exc})"
+ )
+ return None
+ return PageRead(
+ kind="mirror-text-slots-min",
+ path=_relative_project_path(project_path, candidate),
+ payload=_compact_json(projected),
+ source_path=candidate,
+ source_schema=str(source_payload.get("schema")),
+ )
+
+
+def build_page_context(project: str | Path, raw_page: str) -> PageContextResult:
+ """Build one current per-page projection without writing the project."""
+ project_path = Path(project).resolve()
+ if not project_path.is_dir():
+ raise PageContextError(f"project directory not found: {project_path}")
+ page, page_number = normalize_page_key(raw_page)
+ lock_path = project_path / "spec_lock.md"
+ design_path = project_path / "design_spec.md"
+ for required in (lock_path, design_path):
+ if not required.is_file():
+ raise PageContextError(f"required artifact not found: {required.name}")
+ try:
+ lock_sections_raw = parse_markdown_artifact(
+ lock_path,
+ report_duplicate_fields=True,
+ )
+ design_sections = parse_markdown_artifact(design_path)
+ except (OSError, ValueError) as exc:
+ raise PageContextError(str(exc)) from exc
+ lock_sections = _section_index(lock_sections_raw)
+ part, brief = _slide_block(design_sections, page_number)
+ warnings: list[str] = []
+ rhythm_fields = _section_fields(lock_sections, "page_rhythm")
+ rhythm = rhythm_fields.get(page)
+ if rhythm is None:
+ rhythm = "dense"
+ warnings.append(f"page_rhythm has no {page}; using compatibility default dense")
+ chart = _section_fields(lock_sections, "page_charts").get(page)
+ try:
+ structure_lock = load_pptx_structure_lock(project_path)
+ except TemplateStructureError as exc:
+ raise PageContextError(str(exc)) from exc
+ template, prototype_path = _page_template(
+ project_path,
+ structure_lock,
+ page_number,
+ )
+ prototype_refs = (
+ _prototype_image_refs(prototype_path)
+ if prototype_path is not None
+ else []
+ )
+ table_assigned_filenames, assigned_filenames = _page_image_filenames(
+ design_sections,
+ page_number,
+ )
+ locked_images = _section_fields(lock_sections, "images")
+ resolved_filenames = (
+ {_locked_image_basename(value) for value in locked_images.values()}
+ if structure_lock is not None
+ and structure_lock.template_reuse_scope == "mirror"
+ else table_assigned_filenames
+ | _outline_image_assignments(design_sections, locked_images)
+ )
+ image_selection, selected_images = _page_images(
+ locked_images,
+ brief,
+ (
+ prototype_refs
+ if structure_lock is not None
+ and structure_lock.template_reuse_scope == "mirror"
+ else []
+ ),
+ assigned_filenames,
+ resolved_filenames,
+ )
+ inputs = [lock_path, design_path]
+ absent_inputs: list[Path] = []
+ reads: list[PageRead] = []
+ if prototype_path is not None:
+ inputs.append(prototype_path)
+ if (
+ structure_lock is not None
+ and structure_lock.template_reuse_scope == "mirror"
+ ):
+ text_slots = _text_slots_read(
+ project_path,
+ prototype_path,
+ inputs,
+ absent_inputs,
+ warnings,
+ )
+ if text_slots is not None:
+ reads.append(text_slots)
+ reads.append(PageRead(
+ kind="prototype-svg",
+ path=_relative_project_path(project_path, prototype_path),
+ payload=prototype_path.read_text(encoding="utf-8"),
+ source_path=prototype_path,
+ ))
+ global_context = {
+ "communication": _section_fields(lock_sections, "communication"),
+ "canvas": _section_fields(lock_sections, "canvas"),
+ "mode": _section_fields(lock_sections, "mode").get("mode"),
+ "visual_style": _section_fields(
+ lock_sections,
+ "visual_style",
+ ).get("visual_style"),
+ "colors": _section_fields(lock_sections, "colors"),
+ "typography": _section_fields(lock_sections, "typography"),
+ "icons": _section_fields(lock_sections, "icons"),
+ "pptx_structure": _section_fields(lock_sections, "pptx_structure"),
+ "forbidden": _forbidden_items(lock_sections),
+ }
+ global_context = {
+ key: value
+ for key, value in global_context.items()
+ if value not in ({}, [], None, "")
+ }
+ read_set = [
+ {
+ "kind": read.kind,
+ "path": read.path,
+ **(
+ {"schema": TEXT_SLOTS_MIN_SCHEMA}
+ if read.kind == "mirror-text-slots-min"
+ else {}
+ ),
+ }
+ for read in reads
+ ]
+ current_page: dict[str, object] = {
+ "part": part,
+ "brief_markdown": brief,
+ "rhythm": rhythm,
+ "image_selection": image_selection,
+ }
+ if chart is not None:
+ current_page["chart"] = chart
+ if selected_images:
+ current_page["images"] = selected_images
+ if template is not None:
+ current_page["template"] = template
+ context: dict[str, object] = {
+ "schema": PAGE_CONTEXT_SCHEMA,
+ "page": page,
+ "global": global_context,
+ "page_context": current_page,
+ }
+ if read_set:
+ context["read_set"] = read_set
+ if warnings:
+ context["warnings"] = warnings
+ unique_inputs = tuple(dict.fromkeys(path.resolve() for path in inputs))
+ unique_absent_inputs = tuple(
+ path
+ for path in dict.fromkeys(path.resolve() for path in absent_inputs)
+ if not path.exists()
+ )
+ return PageContextResult(
+ project_path=project_path,
+ page=page,
+ context=context,
+ reads=tuple(reads),
+ inputs=unique_inputs,
+ absent_inputs=unique_absent_inputs,
+ )
+
+
+def _compact_json(payload: object) -> str:
+ return json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"
+
+
+def _pretty_json(payload: object) -> str:
+ return json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
+
+
+def render_page_context(
+ result: PageContextResult,
+ *,
+ bundle: bool = False,
+ pretty: bool = False,
+) -> tuple[str, tuple[PageRead, ...]]:
+ """Render the exact stdout payload and return its measured components."""
+ context_payload = (
+ _pretty_json(result.context) if pretty else _compact_json(result.context)
+ )
+ context_read = PageRead(
+ kind="page-context",
+ path="stdout:page-context",
+ payload=context_payload,
+ )
+ if not bundle:
+ return context_payload, (context_read,)
+ reads = (context_read, *result.reads)
+ parts: list[str] = []
+ for read in reads:
+ parts.append(f"<<<{read.kind}:{read.path}>>>\n")
+ parts.append(read.payload.rstrip("\n"))
+ parts.append(f"\n<<<end:{read.kind}>>>\n")
+ return "".join(parts), reads
+
+
+def _sha256_bytes(payload: bytes) -> str:
+ return hashlib.sha256(payload).hexdigest()
+
+
+def _file_sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _token_counter() -> tuple[Callable[[str], int] | None, str]:
+ try:
+ import tiktoken
+ except ImportError:
+ return None, "unavailable"
+ try:
+ encoder = tiktoken.get_encoding(TOKEN_ENCODING)
+ except Exception:
+ return None, "unavailable"
+ return (
+ lambda text: len(encoder.encode(text, disallowed_special=())),
+ "exact",
+ )
+
+
+def _payload_measurement(
+ read: PageRead,
+ count_tokens: Callable[[str], int] | None,
+) -> dict[str, object]:
+ payload = read.payload.encode("utf-8")
+ measurement: dict[str, object] = {
+ "kind": read.kind,
+ "scope": "page",
+ "path": read.path,
+ "sha256": _sha256_bytes(payload),
+ "utf8_bytes": len(payload),
+ "characters": len(read.payload),
+ "tokens": count_tokens(read.payload) if count_tokens else None,
+ }
+ if read.source_path is not None:
+ measurement["source_sha256"] = _file_sha256(read.source_path)
+ if read.source_schema is not None:
+ measurement["source_schema"] = read.source_schema
+ return measurement
+
+
+def record_page_context_usage(
+ result: PageContextResult,
+ output: str,
+ measured_reads: tuple[PageRead, ...],
+) -> tuple[Path, str]:
+ """Write one deterministic, derived token snapshot for the current page."""
+ count_tokens, token_status = _token_counter()
+ documents = [
+ _payload_measurement(read, count_tokens)
+ for read in measured_reads
+ ]
+ output_bytes = output.encode("utf-8")
+ input_records = [
+ {
+ "path": _relative_project_path(result.project_path, path),
+ "exists": True,
+ "sha256": _file_sha256(path),
+ }
+ for path in result.inputs
+ ]
+ input_records.extend(
+ {
+ "path": _relative_project_path(result.project_path, path),
+ "exists": False,
+ }
+ for path in result.absent_inputs
+ )
+ by_kind = {
+ str(item["kind"]): item.get("tokens")
+ for item in documents
+ }
+ route = dict(result.context["global"].get("pptx_structure", {}))
+ template = result.context["page_context"].get("template")
+ if isinstance(template, dict) and isinstance(template.get("reuse_scope"), str):
+ route["template_reuse_scope"] = template["reuse_scope"]
+ usage = {
+ "schema": PAGE_CONTEXT_USAGE_SCHEMA,
+ "page": result.page,
+ "output_mode": "bundle",
+ "route": route,
+ "encoding": TOKEN_ENCODING,
+ "token_status": token_status,
+ "image_selection": result.context["page_context"]["image_selection"],
+ "inputs": input_records,
+ "documents": documents,
+ "controlled_output": {
+ "sha256": _sha256_bytes(output_bytes),
+ "utf8_bytes": len(output_bytes),
+ "characters": len(output),
+ "tokens": count_tokens(output) if count_tokens else None,
+ },
+ "totals": {
+ "page_context": by_kind.get("page-context"),
+ "text_slots_min": by_kind.get("mirror-text-slots-min"),
+ "prototype_svg": by_kind.get("prototype-svg"),
+ },
+ "targets": {
+ "page_context_max_tokens": PAGE_CONTEXT_TOKEN_TARGET,
+ "mirror_text_slots_max_tokens": TEXT_SLOTS_TOKEN_TARGET,
+ },
+ "untracked": ["source-material reads", "session-level prompt references"],
+ }
+ usage_dir = result.project_path / "analysis" / "page-context"
+ usage_dir.mkdir(parents=True, exist_ok=True)
+ usage_path = usage_dir / f"{result.page}.usage.json"
+ temporary_path = usage_path.with_suffix(".usage.json.tmp")
+ temporary_path.write_text(_pretty_json(usage), encoding="utf-8")
+ temporary_path.replace(usage_path)
+ return usage_path, token_status
+
+
+def _nearest_rank(values: list[int], percentile: float) -> int:
+ rank = max(1, math.ceil(percentile * len(values)))
+ return sorted(values)[rank - 1]
+
+
+def _metric(values: list[int], *, target: int | None = None) -> dict[str, object]:
+ if not values:
+ return {
+ "count": 0,
+ "sum": 0,
+ "min": None,
+ "p50": None,
+ "p95": None,
+ "max": None,
+ **({"over_target_count": 0, "target": target} if target else {}),
+ }
+ metric: dict[str, object] = {
+ "count": len(values),
+ "sum": sum(values),
+ "min": min(values),
+ "p50": round(statistics.median(values)),
+ "p95": _nearest_rank(values, 0.95),
+ "max": max(values),
+ }
+ if target is not None:
+ metric.update({
+ "target": target,
+ "over_target_count": sum(value > target for value in values),
+ })
+ return metric
+
+
+def page_context_usage_report(project: str | Path) -> dict[str, object]:
+ """Summarize fresh per-page telemetry without changing recorded history."""
+ project_path = Path(project).resolve()
+ usage_dir = project_path / "analysis" / "page-context"
+ records: list[dict[str, object]] = []
+ stale_pages: list[str] = []
+ unavailable_pages: list[str] = []
+ if usage_dir.is_dir():
+ for usage_path in sorted(usage_dir.glob("P*.usage.json")):
+ try:
+ record = json.loads(usage_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ stale_pages.append(usage_path.stem.split(".", 1)[0])
+ continue
+ page = str(record.get("page", usage_path.stem.split(".", 1)[0]))
+ if record.get("schema") != PAGE_CONTEXT_USAGE_SCHEMA:
+ stale_pages.append(page)
+ continue
+ if record.get("output_mode") != "bundle":
+ stale_pages.append(page)
+ continue
+ stale = False
+ for item in record.get("inputs", []):
+ if not isinstance(item, dict):
+ stale = True
+ break
+ source_path = (project_path / str(item.get("path", ""))).resolve()
+ try:
+ source_path.relative_to(project_path)
+ except ValueError:
+ stale = True
+ break
+ expected_exists = item.get("exists", True)
+ if expected_exists is False:
+ if source_path.exists():
+ stale = True
+ break
+ elif (
+ not source_path.is_file()
+ or _file_sha256(source_path) != item.get("sha256")
+ ):
+ stale = True
+ break
+ if stale:
+ stale_pages.append(page)
+ continue
+ if record.get("token_status") != "exact":
+ unavailable_pages.append(page)
+ records.append(record)
+
+ def tokens_for(kind: str) -> list[int]:
+ values: list[int] = []
+ for record in records:
+ for document in record.get("documents", []):
+ if not isinstance(document, dict) or document.get("kind") != kind:
+ continue
+ value = document.get("tokens")
+ if isinstance(value, int):
+ values.append(value)
+ return values
+
+ controlled = [
+ value
+ for record in records
+ if isinstance(
+ value := record.get("controlled_output", {}).get("tokens"),
+ int,
+ )
+ ]
+ prototype_values = tokens_for("prototype-svg")
+ mirror_records = [
+ record
+ for record in records
+ if isinstance(record.get("route"), dict)
+ and record["route"].get("template_reuse_scope") == "mirror"
+ ]
+ mirror_controlled = [
+ value
+ for record in mirror_records
+ if isinstance(
+ value := record.get("controlled_output", {}).get("tokens"),
+ int,
+ )
+ ]
+ mirror_prototype_values = [
+ int(document["tokens"])
+ for record in mirror_records
+ for document in record.get("documents", [])
+ if isinstance(document, dict)
+ and document.get("kind") == "prototype-svg"
+ and isinstance(document.get("tokens"), int)
+ ]
+ prototype_share = (
+ round(sum(mirror_prototype_values) / sum(mirror_controlled), 4)
+ if mirror_prototype_values and sum(mirror_controlled)
+ else None
+ )
+ return {
+ "schema": PAGE_CONTEXT_REPORT_SCHEMA,
+ "project": project_path.name,
+ "record_count": len(records),
+ "mirror_record_count": len(mirror_records),
+ "pages": sorted(str(record["page"]) for record in records),
+ "stale_pages": sorted(set(stale_pages)),
+ "token_unavailable_pages": sorted(set(unavailable_pages)),
+ "metrics": {
+ "page_context": _metric(
+ tokens_for("page-context"),
+ target=PAGE_CONTEXT_TOKEN_TARGET,
+ ),
+ "mirror_text_slots_min": _metric(
+ tokens_for("mirror-text-slots-min"),
+ target=TEXT_SLOTS_TOKEN_TARGET,
+ ),
+ "prototype_svg": _metric(prototype_values),
+ "controlled_output": _metric(controlled),
+ },
+ "mirror_prototype_share_of_controlled_output": prototype_share,
+ }
diff --git a/skills/ppt-master/scripts/project_manager.py b/skills/ppt-master/scripts/project_manager.py
index ac3c3db0..17f49764 100644
--- a/skills/ppt-master/scripts/project_manager.py
+++ b/skills/ppt-master/scripts/project_manager.py
@@ -8,6 +8,8 @@ Usage:
python3 scripts/project_manager.py scaffold-lock <project_path>
python3 scripts/project_manager.py validate <project_path>
python3 scripts/project_manager.py info <project_path>
+ python3 scripts/project_manager.py page-context <project_path> P07 [--bundle] [--record-usage]
+ python3 scripts/project_manager.py page-context-report <project_path>
"""
from __future__ import annotations
@@ -25,6 +27,12 @@ from pathlib import Path
from urllib.parse import urlparse
from console_encoding import configure_utf8_stdio
+from page_context import (
+ build_page_context,
+ page_context_usage_report,
+ record_page_context_usage,
+ render_page_context,
+)
from project_specs import scaffold_project_artifact, validate_project_artifacts
try:
@@ -903,6 +911,8 @@ def build_parser() -> argparse.ArgumentParser:
python3 scripts/project_manager.py scaffold-lock projects/demo_ppt169_20260718
python3 scripts/project_manager.py validate projects/demo
python3 scripts/project_manager.py info projects/demo
+ python3 scripts/project_manager.py page-context projects/demo P07 --bundle --record-usage
+ python3 scripts/project_manager.py page-context-report projects/demo
""",
)
subparsers = parser.add_subparsers(dest="command", required=True)
@@ -939,6 +949,34 @@ def build_parser() -> argparse.ArgumentParser:
info = subparsers.add_parser("info", help="Print project metadata")
info.add_argument("project_path", help="Project directory")
+
+ page_context = subparsers.add_parser(
+ "page-context",
+ help="Print one deterministic per-page execution view",
+ )
+ page_context.add_argument("project_path", help="Project directory")
+ page_context.add_argument("page", help="Positive page key such as P07")
+ page_context.add_argument(
+ "--bundle",
+ action="store_true",
+ help="Include the selected min sidecar and complete prototype SVG",
+ )
+ page_context.add_argument(
+ "--pretty",
+ action="store_true",
+ help="Pretty-print the page-context JSON payload",
+ )
+ page_context.add_argument(
+ "--record-usage",
+ action="store_true",
+ help="With --bundle, write token telemetry under analysis/page-context/",
+ )
+
+ page_context_report = subparsers.add_parser(
+ "page-context-report",
+ help="Summarize fresh per-page context telemetry",
+ )
+ page_context_report.add_argument("project_path", help="Project directory")
return parser
@@ -1048,6 +1086,35 @@ def main(argv: list[str] | None = None) -> int:
print(f"Created: {info['create_date']}")
return 0
+ if args.command == "page-context":
+ if args.record_usage and not args.bundle:
+ parser.error("page-context --record-usage requires --bundle")
+ result = build_page_context(args.project_path, args.page)
+ output, measured_reads = render_page_context(
+ result,
+ bundle=args.bundle,
+ pretty=args.pretty,
+ )
+ if args.record_usage:
+ _usage_path, token_status = record_page_context_usage(
+ result,
+ output,
+ measured_reads,
+ )
+ if token_status != "exact":
+ print(
+ "[WARN] tiktoken/o200k_base unavailable; recorded bytes "
+ "and hashes without token counts",
+ file=sys.stderr,
+ )
+ print(output, end="")
+ return 0
+
+ if args.command == "page-context-report":
+ report = page_context_usage_report(args.project_path)
+ print(json.dumps(report, ensure_ascii=False, indent=2))
+ return 0
+
parser.error(f"Unknown command: {args.command}")
except Exception as exc:
print(f"[ERROR] {exc}")
diff --git a/skills/ppt-master/scripts/project_specs.py b/skills/ppt-master/scripts/project_specs.py
index 8d19bb86..99d2c0bc 100644
--- a/skills/ppt-master/scripts/project_specs.py
+++ b/skills/ppt-master/scripts/project_specs.py
@@ -129,6 +129,47 @@ def _parse_markdown_sections(
return sections, errors
+def parse_markdown_artifact(
+ markdown_path: Path,
+ *,
+ report_duplicate_fields: bool = False,
+) -> list[dict[str, object]]:
+ """Parse one Markdown planning artifact without changing it.
+
+ This is the public read-only entry point for consumers that need the same
+ heading/data-line grammar as schema validation. Keeping the parser here
+ prevents runtime projections from drifting into their own lock grammar.
+ """
+ text = markdown_path.read_text(encoding="utf-8")
+ sections, errors = _parse_markdown_sections(
+ text,
+ report_duplicate_fields=report_duplicate_fields,
+ )
+ if errors:
+ raise ValueError("; ".join(errors))
+ return sections
+
+
+def default_spec_lock_forbidden() -> frozenset[str]:
+ """Return the versioned scaffold's universal forbidden-item defaults."""
+ sections = parse_markdown_artifact(SCAFFOLD_DIR / "spec_lock.md")
+ section = next(
+ (
+ item
+ for item in sections
+ if str(item.get("heading", "")).strip().casefold() == "forbidden"
+ ),
+ None,
+ )
+ if section is None:
+ raise ValueError("spec-lock scaffold has no forbidden section")
+ return frozenset(
+ re.sub(r"^-[ \t]+", "", line.strip())
+ for line in str(section.get("body", "")).splitlines()
+ if line.strip()
+ )
+
+
def _load_markdown_schema(schema_path: Path) -> dict[str, object]:
"""Load and sanity-check one versioned Markdown schema."""
with schema_path.open("r", encoding="utf-8") as stream:
diff --git a/skills/ppt-master/scripts/template_text_slots.py b/skills/ppt-master/scripts/template_text_slots.py
new file mode 100644
index 00000000..2ffbc235
--- /dev/null
+++ b/skills/ppt-master/scripts/template_text_slots.py
@@ -0,0 +1,175 @@
+"""Shared projection and integrity helpers for mirror-template text slots."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import dataclass
+from xml.etree import ElementTree as ET
+
+
+MODEL_TEXT_SLOT_KEYS = (
+ "selector",
+ "role",
+ "current_text",
+ "text_segments",
+ "tspan_count",
+)
+
+
+def _local_name(tag: str) -> str:
+ return tag.rsplit("}", 1)[-1]
+
+
+def _ancestor_chain(
+ element: ET.Element,
+ parent_by_child: dict[ET.Element, ET.Element],
+) -> list[ET.Element]:
+ chain = [element]
+ while chain[-1] in parent_by_child:
+ chain.append(parent_by_child[chain[-1]])
+ return chain
+
+
+def _nearest_attribute(chain: list[ET.Element], name: str) -> str | None:
+ for element in chain:
+ value = element.get(name)
+ if value is not None:
+ return value
+ return None
+
+
+def _text_selector(
+ element: ET.Element,
+ parent_by_child: dict[ET.Element, ET.Element],
+ *,
+ compact: bool,
+) -> str:
+ segments: list[str] = []
+ current = element
+ while True:
+ element_id = (current.get("id") or "").strip()
+ if element_id:
+ segments.append(f"#{element_id}")
+ break
+ parent = parent_by_child.get(current)
+ tag = _local_name(current.tag)
+ if parent is None:
+ segments.append(tag)
+ break
+ same_tag = [child for child in parent if _local_name(child.tag) == tag]
+ if compact and len(same_tag) == 1:
+ segments.append(tag)
+ else:
+ segments.append(f"{tag}:nth-of-type({same_tag.index(current) + 1})")
+ current = parent
+ separator = ">" if compact else " > "
+ return separator.join(reversed(segments))
+
+
+def _text_topology_sha256(element: ET.Element) -> str:
+ """Hash text/tspan topology and attributes while excluding visible values."""
+ digest = hashlib.sha256()
+
+ def visit(node: ET.Element) -> None:
+ digest.update(_local_name(node.tag).encode("utf-8"))
+ for name, value in sorted(node.attrib.items()):
+ digest.update(b"\0a")
+ digest.update(name.encode("utf-8"))
+ digest.update(b"\0")
+ digest.update(value.encode("utf-8"))
+ for child in node:
+ digest.update(b"\0c")
+ visit(child)
+ digest.update(b"\0e")
+
+ visit(element)
+ return digest.hexdigest()
+
+
+@dataclass(frozen=True)
+class TemplateTextSlot:
+ selector: str
+ legacy_selector: str
+ role: str
+ current_text: str
+ text_segments: tuple[str, ...]
+ tspan_count: int
+ topology_sha256: str
+ editable: bool
+
+ def model_payload(self) -> dict[str, object]:
+ return {
+ "selector": self.selector,
+ "role": self.role,
+ "current_text": self.current_text,
+ "text_segments": list(self.text_segments),
+ "tspan_count": self.tspan_count,
+ }
+
+
+def analyze_template_text_slots(root: ET.Element) -> tuple[TemplateTextSlot, ...]:
+ """Derive the model projection and tool-only integrity facts from one SVG."""
+ parent_by_child = {
+ child: parent
+ for parent in root.iter()
+ for child in parent
+ }
+ slots: list[TemplateTextSlot] = []
+ for text_element in root.iter():
+ if _local_name(text_element.tag) != "text":
+ continue
+ chain = _ancestor_chain(text_element, parent_by_child)
+ placeholder = _nearest_attribute(chain, "data-pptx-placeholder")
+ editable_value = _nearest_attribute(chain, "data-pptx-editable")
+ inherited_layer = _nearest_attribute(chain, "data-pptx-layer")
+ tspans = [
+ child
+ for child in text_element.iter()
+ if child is not text_element and _local_name(child.tag) == "tspan"
+ ]
+ segments = [
+ text_element.text or "",
+ *[(tspan.text or "") for tspan in tspans],
+ ]
+ if tspans and not segments[0].strip():
+ segments = segments[1:]
+ slots.append(TemplateTextSlot(
+ selector=_text_selector(
+ text_element,
+ parent_by_child,
+ compact=True,
+ ),
+ legacy_selector=_text_selector(
+ text_element,
+ parent_by_child,
+ compact=False,
+ ),
+ role=placeholder or "text",
+ current_text="".join(text_element.itertext()),
+ text_segments=tuple(segments),
+ tspan_count=len(tspans),
+ topology_sha256=_text_topology_sha256(text_element),
+ editable=editable_value != "false" and inherited_layer is None,
+ ))
+ selectors = [slot.selector for slot in slots]
+ if len(selectors) != len(set(selectors)):
+ raise ValueError("template text selectors are not unique")
+ return tuple(slots)
+
+
+def text_slot_integrity_sha256(slots: tuple[TemplateTextSlot, ...]) -> str:
+ """Hash selectors plus immutable text/tspan topology and attributes."""
+ payload = [
+ {
+ "selector": slot.selector,
+ "topology_sha256": slot.topology_sha256,
+ }
+ for slot in slots
+ ]
+ serialized = json.dumps(
+ payload,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ return hashlib.sha256(serialized).hexdigest()
diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.md
index 6cfcf5f2..d3834a3c 100644
--- a/skills/ppt-master/workflows/create-template.md
+++ b/skills/ppt-master/workflows/create-template.md
@@ -525,11 +525,15 @@ one operation. It emits source-ordered page SVGs, unused-Layout definition
SVGs, `icons/imported/`, referenced `images/` / `templates/assets/`, and one
deduplicated `templates/native_payloads.json.gz` store when supported native
payload or repeated restoration metadata exists. It also writes
-`templates/template_execution_manifest.json`, a compact model-readable prototype
+`templates/template_execution_manifest.json` with schema
+`ppt-master.template-execution-manifest.v1`, a compact model-readable prototype
roster and grouped source-import warning summary. Each prototype points to one
-`templates/template_execution/*.text-slots.json` sidecar containing its exact
-mirror text selectors, segments, attributes, topology hashes, bounds, and font
-stacks. Template SVGs and imported
+`templates/template_execution/*.text-slots.json` sidecar with schema
+`ppt-master.template-text-slots.v2-min`. Each slot contains only
+`selector`, `role`, `current_text`, `text_segments`, and `tspan_count`; the complete
+prototype remains authoritative. Page-context verifies the top-level tool hash
+and strips it before model output; validators/export own attribute and topology
+checks. Template SVGs and imported
vectors keep content-hash payload references plus short
`data-pptx-native-ref` attribute-record ids. Structural Master/Layout,
placeholder, layer, and editable-object fields remain inline. The command does
@@ -690,7 +694,7 @@ This checker validates the authoring contract, not the compiled OOXML package. T
- [ ] `standard` / `fidelity` output SVGs and their Master/Layout/slot contracts were newly authored without preserving or distilling source topology
- [ ] Every additional authored Master represents a distinct reusable design family, not one Layout or an equivalent duplicate; every declared Master owns at least one emitted Layout and every declared Layout has at least one emitted prototype
- [ ] Mirror output preserves source slide order, Master/Layout identity and parentage, placeholder facts, and ownership; fixed-layer group expansion is mechanical and pixel-equivalent, and the Source Preservation Map lists every source slide
-- [ ] Mirror materialization wrote the compact `templates/template_execution_manifest.json`; each prototype is listed once and links one `template_execution/*.text-slots.json` sidecar, every sidecar slot records selector/current segments/tspan attributes/topology hash/bounds/font stack, and source-import diagnostics are summarized separately from downstream generation issues
+- [ ] Mirror materialization wrote one compact `ppt-master.template-execution-manifest.v1` roster and one linked `ppt-master.template-text-slots.v2-min` sidecar per prototype; each slot has only `selector`, `role`, `current_text`, `text_segments`, and `tspan_count`; page-context verifies and strips the tool hash, while validation/export check the complete prototype
- [ ] Mirror roots preserve source inherited-shape visibility with canonical lowercase `data-pptx-show-master-shapes` and `data-pptx-show-inherited-shapes`; same-key Layouts agree on the former, while each Slide retains its own latter value
- [ ] Mirror preflight covered the complete source graph; each unused Layout has one `layout_<layout_key>.svg` definition prototype and each otherwise-unused Master is retained through at least one such Layout
- [ ] For `standard` / `fidelity`, no duplicate-Layout-contract warning remains; mirror may keep equivalent source Layout identities when the preservation map explains them
diff --git a/skills/ppt-master/workflows/generate-pptx.md b/skills/ppt-master/workflows/generate-pptx.md
index 2645258a..e6b25b96 100644
--- a/skills/ppt-master/workflows/generate-pptx.md
+++ b/skills/ppt-master/workflows/generate-pptx.md
@@ -12,7 +12,7 @@ description: Generate PPTX route authority for source intake, planning, SVG auth
- The current main agent hand-writes every SVG page; never delegate page generation or run a Python, Node, or shell generator over `svg_output/`.
- Generate pages sequentially, one page at a time, in one continuous pass; grouped page batches are forbidden.
-- Before each page, re-read `<project_path>/spec_lock.md` and apply the current communication, design, resource, rhythm, chart, and conditional template mappings.
+- Before each page, generate its canonical page-context bundle and apply the projected communication, design, resource, rhythm, chart, and conditional template mappings.
- `preset_shape_svg.py` may provide one stdout fragment only after the main agent chooses its semantic role, frame, and paint; it cannot choose layout or write a page.
### SVG Page-Design Boundary
@@ -220,7 +220,7 @@ python3 ${SKILL_DIR}/scripts/analyze_images.py <project_path>/images
**Output**:
- `<project_path>/design_spec.md` — human-readable design narrative
-- `<project_path>/spec_lock.md` — machine-readable communication + execution contract; Executor re-reads before every page
+- `<project_path>/spec_lock.md` — machine-readable communication + execution contract; Executor consumes its current-page projection from `page-context`
For a new artifact pair, run these commands once after final confirmation and before filling the files; each refuses to overwrite an existing artifact:
@@ -354,11 +354,17 @@ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --live --daemon
- **Do NOT read or apply submitted annotations during generation.** Users may annotate at any time, but Executor proceeds without touching them. The window to apply annotations opens only after Step 7 completes — see [`workflows/stages/live-preview.md`](stages/live-preview.md).
- The editor also supports **staged direct edits** (text content + SVG element attributes previewed immediately, then written to `svg_output/` only when the user clicks **Apply changes**; `Ctrl+Z` / Undo drops staged edits) alongside annotation; re-export stays chat-driven. Full scope and editor details: see [`workflows/stages/live-preview.md`](stages/live-preview.md) Notes.
-**Conditional pre-generation reads**: on a structured route, follow `executor-structured.md` to read the template execution roster/sidecars and every distinct locked layout SVG; flat routes skip that template read. When `spec_lock.page_charts` or §VII names selected chart templates, follow `executor-chart.md` and batch-read those distinct chart SVGs once before the first affected page. A summary or sidecar never substitutes for the selected full SVG.
+**Conditional pre-generation reads**: On a structured route, follow `executor-structured.md` to read the template capabilities and compact execution roster once; the selected complete layout/mirror prototype arrives in each page bundle. Flat routes skip those template reads. When `spec_lock.page_charts` or §VII names selected chart templates, follow `executor-chart.md` and read those distinct chart SVGs once before the first affected page. A summary or sidecar never substitutes for the selected full SVG.
> 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`; check the global `communication` contract, including `consumption_mode`, against the current §IX `Core message` + `Audience move`, and use only the lock's colors / fonts / icons / images, plus `pptx_structure.mode`, `template_reuse_scope`, and the per-page `page_rhythm` / `page_charts` lookups. Read `page_layouts` / `page_pptx_layouts` / `pptx_masters` / `pptx_layouts` only on a structured `template_reuse_scope: mirror|layout` route; they are absent in flat `style`, free-design, and brand-only projects. Resists purpose and design drift on long decks. See executor-base.md §2.1.
+**Per-page context load (Mandatory)**: before **each** SVG page, run:
+
+```bash
+python3 skills/ppt-master/scripts/project_manager.py page-context <project_path> P<NN> --bundle --record-usage
+```
+
+Use this canonical projection for the global communication contract, current §IX `Core message` + `Audience move`, locked colors/fonts/icons/images, and current-page rhythm/chart/structure assignments. Flat bundles contain only page context; `layout` bundles also contain the selected complete prototype; `mirror` bundles contain that prototype plus its minimal text-slot view. This derived view does not replace `design_spec.md`, `spec_lock.md`, their gates, or any source facts needed by the page. See [`executor-base.md`](../references/executor-base.md) §2.1 and [`executor-structured.md`](../references/executor-structured.md) §1.0.
> ⚠️ **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).
diff --git a/skills/ppt-master/workflows/stages/resume-execute.md b/skills/ppt-master/workflows/stages/resume-execute.md
index 8d603169..b2f62a6b 100644
--- a/skills/ppt-master/workflows/stages/resume-execute.md
+++ b/skills/ppt-master/workflows/stages/resume-execute.md
@@ -28,10 +28,10 @@ Verify the project's planning-session artifacts before doing anything else:
| File / Directory | Required when | Reason |
|---|---|---|
-| `<project_path>/spec_lock.md` | Always | Strategist's execution contract; Executor reads it per page |
-| `<project_path>/design_spec.md` | Always | Section IX page outline; Executor cross-references it |
+| `<project_path>/spec_lock.md` | Always | Strategist's execution contract; `page-context` projects its current-page values |
+| `<project_path>/design_spec.md` | Always | Section IX page outline; `page-context` projects the current page block |
| `<project_path>/images/` plus files whose row status requires existence | `spec_lock images` references any image | `Existing` / `Generated` / `Sourced` / `Rendered` files must exist; an absent `Needs-Manual` file remains allowed until the Step 7 readiness gate |
-| `<project_path>/templates/` | `spec_lock page_layouts` / `page_charts` references any | Layout / chart SVGs needed for batch read |
+| `<project_path>/templates/` | `spec_lock page_layouts` / `page_charts` references any | Layout / mirror prototypes and chart SVGs required by execution |
If any required artifact is missing, report it and stop this stage. Do not enter Step 6 or invent a replacement artifact. Recover by artifact owner:
@@ -51,8 +51,8 @@ Then jump to `### Step 6: Executor Phase` and run the documented pipeline:
- Read the Step 6 flat core (`executor-base`, `shared-standards-core`, and the locked mode / visual-style files), then only the branches selected by its condition table
- Design Parameter Confirmation
-- Pre-generation Batch Read (every layout / chart SVG referenced in `spec_lock`)
-- Per-page `spec_lock` re-read + sequential page generation
+- Pre-generation compact template-roster read when structured, plus each distinct selected chart SVG once
+- Per-page `python3 skills/ppt-master/scripts/project_manager.py page-context <project_path> P<NN> --bundle --record-usage` load + sequential page generation
- Quality Check Gate
- Speaker notes generation
- Step 7: Post-processing & Export (`total_md_split` → `finalize_svg` → `svg_to_pptx`)