Agent-driven creation of editable, tastefully crafted visual artifacts.
Python
feat: add paper-fig v2 and streamline research-figure onboarding
yejy53a14f89e944af
diff --git a/NEWS.md b/NEWS.mdindex 3a1254e..c3b43c7 100644--- a/NEWS.md+++ b/NEWS.md@@ -6,11 +6,17 @@ A concise, date-based record of user-visible project updates. New entries are ad## 2026-09-08+- 🔬 **Paper Fig v2, developed with GPT-6:** turn method descriptions into paper workflow and architecture diagrams in the requested visual style, with editable PowerPoint output. [Install with Codex](./README.md#paper-fig).+- Added drawing-prompt guidance for the full-page composition, region proportions, labels, connections, and meaningful image assets. The Skill saves the prompt before generating the visual draft.+- Featured three Paper Fig results at the [top of the Gallery](./README.md#paper-figures): OmniManip, Compact3D, and ICEdit. These static images use full-resolution lossless WebP previews and link to the original PNGs, without loading additional videos.+- Credited [PaperGallery](https://github.com/LongHZ140516/PaperGallery) and the original papers for the reference cases. The examples illustrate generated results, not a comparative benchmark.+- Moved News and the new Skill entry ahead of Overview, and removed the previous “Attention Is All You Need” academic-poster example.- Added direct links to the [arXiv abstract](https://arxiv.org/abs/2609.04034), [paper PDF](https://arxiv.org/pdf/2609.04034), and [Hugging Face paper page](https://huggingface.co/papers/2609.04034).- Added this News page so ongoing changes can be followed without expanding the main README into a full changelog.## 2026-09-04+- 📢 **Editable Design — Initial Release!** Editable posters, infographics, art posters, and marketing campaigns with real text, independent layers, and Agent Design Replay. [Read the paper](https://arxiv.org/abs/2609.04034).- Added a ready-to-copy BibTeX citation for the Editable Visual Design technical report.## 2026-09-03diff --git a/README.md b/README.mdindex 97011a7..d980906 100644--- a/README.md+++ b/README.md@@ -2,81 +2,56 @@**Coding-agent-driven creation of editable, tastefully crafted visual artifacts.**-Editable Visual Design turns a prompt into a structured design artifact with real text, independent assets, semantic HTML layers, and a replayable creation process—instead of shipping a flattened image.+Turn a brief or method description into an editable visual design. Keep text and visual elements independently editable in HTML or PowerPoint.📄 **Paper:** [Editable Visual Design](https://arxiv.org/abs/2609.04034) · [PDF](https://arxiv.org/pdf/2609.04034) · [Hugging Face](https://huggingface.co/papers/2609.04034) · [Project News](./NEWS.md)-## Overview--<a href="https://yejy53.github.io/Editable-Design/player.html#overview">- <img src="./assets/overview-cover.webp" width="100%" alt="Play the Editable Visual Design overview video">-</a>-## News+- **2026-09-08** — 🔬 **[Paper Fig](#paper-fig), developed with GPT-6:** turn method descriptions into editable paper workflow diagrams in your chosen style. [Install](#paper-fig) · [Gallery](#paper-figures).- **2026-09-04** — 📢 **Editable Design — Initial Release!** Create editable posters, infographics, art posters, and marketing campaigns with real text, independent layers, and Agent Design Replay. 📄 [Read our paper on arXiv](https://arxiv.org/abs/2609.04034).[See all project updates →](./NEWS.md)-## Table of Contents--- [Overview](#overview)-- [Paper](#paper)-- [News](#news)-- [Why Editable Visual Design](#why-editable-visual-design)-- [Three Core Ideas](#three-core-ideas)-- [Toolkit](#toolkit)-- [Quick Start](#quick-start)-- [Gallery](#gallery)- - [🎯 Campaigns](#campaigns)- - [📚 Information Design](#information-design)- - [✍️ Text-led Design](#text-led-design)- - [📰 Poster](#poster)- - [🎓 Academic Posters](#academic-posters)- - [🎨 Art Design](#art-design)-- [Citation](#citation)-- [Acknowledgements](#acknowledgements)-- [License](#license)--## Why Editable Visual Design+[Paper Fig](#paper-fig) · [Overview](#overview) · [Quick Start](#quick-start) · [Gallery](#gallery) · [Citation](#citation) · [Acknowledgements](#acknowledgements)-Image generation can quickly produce beautiful designs, but a local change often means regenerating the whole image. Direct coding provides structure, but its visual finish is inconsistent. Editable Visual Design combines visual direction and editable structure in one artifact.+## Paper Fig-| | Image generation | Direct coding | Editable Visual Design |-|---|---|---|---|-| Art-directed visual quality | Strong | Inconsistent | Strong |-| Real text and semantic layers | No | Yes | Yes |-| Local edits without regeneration | No | Yes | Yes |-| Replayable creation path | No | Partial | Yes |--## Three Core Ideas+<a href="./assets/paper-fig-powerpoint.png">+ <img src="./assets/paper-fig-powerpoint.webp" width="100%" alt="Paper Fig diagram open in PowerPoint, with individual text boxes, shapes, and image elements selected">+</a>-### 1. Coding-Agent-Driven Design+*Editable text, shapes, and image elements in PowerPoint.*-One persistent Coding Agent owns the artifact from intent to repair: understanding the brief, planning the composition, generating assets, implementing HTML, rendering, observing, and fixing the result. Agent Design Replay makes that path visible and traceable.+[View results](#paper-figures) · [Skill guide](./skills/paper-fig/INSTALL.md)-### 2. Visual Prior, Without Pixel Shipping+<details>+<summary><strong>Install and use Paper Fig</strong></summary>-An image model provides art direction—composition, hierarchy, color, and spatial relationships—but its reference pixels never enter the delivered design. The agent generates clean assets and rebuilds typography and layout in HTML.+Copy this request into Codex:-### 3. Editable and Quality-Gated Artifacts+```text+Install the paper-fig Skill from:+https://github.com/yejy53/Editable-Design/tree/main/skills/paper-fig+```-The result contains real text, semantic layers, and independent assets that can be selected, moved, edited, and exported. Deterministic checks cover the canvas, fonts, layer contracts, rendering, and editor round trips.+Then provide a method description and your preferred visual style:-## Toolkit+```text+Use $paper-fig to turn the following method description into a paper workflow diagram in my requested visual style. Deliver an editable PowerPoint.+```-This repository now ships the code behind the workflow as two independent Codex skills:+</details>-| Skill | Purpose | Main outputs |-| --- | --- | --- |-| [`editable-design`](./skills/editable-design/) | Create polished fixed-canvas visual designs from a brief | HTML, PNG, mouse editor, animated layer breakdown, and Agent Design Replay |-| [`html-to-pptx`](./skills/html-to-pptx/) | Convert clean designs, editor pages, or exploded-layer HTML into editable PowerPoint | Editable `.pptx` with independently selectable elements where the source structure permits |+## Overview-`editable-design` is the complete core workflow and does not require PowerPoint support. `html-to-pptx` is a sibling tool that runs only when a PPTX is requested. Installation is covered in [Quick Start](#quick-start); the standalone [Toolkit guide](./TOOLKIT.md) and each skill's README contain the detailed requirements and direct commands.+<a href="https://yejy53.github.io/Editable-Design/player.html#overview">+ <img src="./assets/overview-cover.webp" width="100%" alt="Play the Editable Visual Design overview video">+</a>## Quick Start-### Option 1: Install with Codex+### Posters, infographics, and campaigns1. Open a Codex task and ask Codex to install and initialize the Skill:@@ -95,9 +70,10 @@ This repository now ships the code behind the workflow as two independent Codex3. The Skill will create the finished design together with its editable source: real text, independent imagery, semantic HTML layers, a visual editor, a layer breakdown, and an Agent Design Replay.-> **Recommended:** Use [GPT-5.6](https://developers.openai.com/api/docs/guides/latest-model) with `high` reasoning effort or above for the strongest results.+> **Recommended:** Use `high` reasoning effort or above for complex diagrams and layouts.-### Option 2: Install manually+<details>+<summary><strong>Manual installation without Gallery media</strong></summary>Use a sparse, blob-filtered clone to install only the Skill without downloading the Gallery media:@@ -114,6 +90,10 @@ npm ci --prefix ~/.codex/skills/editable-design/scripts~/.codex/skills/editable-design/scripts/doctor.sh```+For Paper Fig instead, select `skills/paper-fig` in the sparse checkout and follow its [installation guide](./skills/paper-fig/INSTALL.md).++</details>+### Optional: Editable PowerPoint exportFor a one-step Codex installation, ask:@@ -127,18 +107,65 @@ Use it to convert my compatible HTML into an editable PowerPoint file.Codex installs the Skill from that subdirectory. Its first conversion automatically prepares an isolated Python environment and Playwright Chromium; the user does not need to run dependency commands.-For a manual source install:+### Choose a Skill-```bash-git sparse-checkout add skills/html-to-pptx-cp -R skills/html-to-pptx ~/.codex/skills/-```+| Skill | Use it for | Outputs |+| --- | --- | --- |+| **[`paper-fig`](./skills/paper-fig/)** | Generate paper workflow and architecture diagrams from method descriptions | Editable PPTX |+| [`editable-design`](./skills/editable-design/) | Posters, infographics, and marketing campaigns | HTML, PNG, visual editor, layer breakdown, Agent Design Replay |+| [`html-to-pptx`](./skills/html-to-pptx/) | Converting an existing compatible HTML design | Editable PPTX |-See [`editable-design`](./skills/editable-design/README.md) and [`html-to-pptx`](./skills/html-to-pptx/README.md) for detailed requirements and commands. To build a clean source archive containing both Skills, run `./pack.sh`.+Install only the Skill you need. Paper Fig does not depend on either of the other Skills. See the [Toolkit guide](./TOOLKIT.md) for detailed setup and packaging.++<details>+<summary><strong>Design principles behind Editable Visual Design</strong></summary>++- **Coding-agent-driven design.** One persistent agent plans, builds, renders, and repairs the artifact. Agent Design Replay exposes the HTML workflow's creation path.+- **Visual direction with editable structure.** The agent plans a visual composition, then builds it with editable text, layout, and independent image assets.+- **Local editing and verification.** Text and structural elements remain independently editable. Checks cover rendering and format-specific contracts; the output still needs human review for scientific accuracy.++</details>## Gallery-Fourteen prompts across six visual-design categories, with final renderings, editable demonstrations, and Agent Design Replays.+Three Paper Fig results, followed by thirteen visual-design examples. Click a figure to view the full-resolution PNG.++- [🔬 Paper Figures](#paper-figures)+- [🎯 Campaigns](#campaigns)+- [📚 Information Design](#information-design)+- [✍️ Text-led Design](#text-led-design)+- [📰 Poster](#poster)+- [🎨 Art Design](#art-design)++## Paper Figures++Research method pipelines and architecture diagrams generated with [`paper-fig`](./skills/paper-fig/). The reference cases come from [PaperGallery](https://github.com/LongHZ140516/PaperGallery) and the original papers credited below. These are qualitative examples, not a model-performance benchmark.++### OmniManip — Object-Centric Manipulation++<a href="./gallery/paper-figures/omnimanip/final.png">+ <img src="./gallery/paper-figures/omnimanip/preview.webp" width="100%" alt="Paper Fig result: object grounding, interaction constraints, and trajectory planning for robot manipulation">+</a>++Generated with **Paper Fig** · Reference: [PaperGallery](https://longhz140516.github.io/PaperGallery/images/pipeline-Pan_OmniManip_2025/) · [Original paper](https://arxiv.org/abs/2501.03841)++### Compact3D — Gaussian Compression++<a href="./gallery/paper-figures/compact3d/final.png">+ <img src="./gallery/paper-figures/compact3d/preview.webp" width="100%" alt="Paper Fig result: vector quantization, opacity regularization, and Gaussian pruning pipeline">+</a>++Generated with **Paper Fig** · Reference: [PaperGallery](https://longhz140516.github.io/PaperGallery/images/pipeline-Navaneet_Compact3D_2024/) · [Original paper](https://arxiv.org/abs/2311.18159)++### ICEdit — In-Context Image Editing++<a href="./gallery/paper-figures/icedit/final.png">+ <img src="./gallery/paper-figures/icedit/preview.webp" width="100%" alt="Paper Fig result: in-context editing frameworks and the LoRA-MoE module architecture">+</a>++Generated with **Paper Fig** · Reference: [PaperGallery](https://longhz140516.github.io/PaperGallery/images/pipeline-Zhang_ICEdit_2025/) · [Original paper](https://arxiv.org/abs/2504.20690)++[Source attribution and reuse notes](./gallery/paper-figures/NOTICE.md)## Campaigns@@ -642,40 +669,6 @@ Create a vertical editorial travel infographic poster titled “纽约3天旅游----## Academic Posters--### Attention Is All You Need--<table role="presentation" width="100%">- <tr>- <td width="38.39%" align="center" valign="top">- <details open>- <summary align="center"><strong>🖼️ final-coding-design.png</strong></summary>- <a href="./gallery/academic-posters/attention-is-all-you-need/final.png">- <img src="./gallery/academic-posters/attention-is-all-you-need/preview.webp" width="100%" alt="Attention Is All You Need academic poster">- </a>- </details>- </td>- <td width="61.61%" align="center" valign="top">- <video src="https://github.com/user-attachments/assets/6271f81d-a2fd-4115-a16d-54cad4d23b35" width="100%" controls></video>- </td>- </tr>-</table>--<video src="https://github.com/user-attachments/assets/19e5e8c5-40e2-41ae-a609-991df50fb218" width="100%" controls></video>--**Prompt:**--```text-Create a vertical academic research poster from the supplied paper PDF. Read the whole paper before designing. Present the research question, the Transformer method, and the paper's strongest quantitative evidence, preserving all numbers, units, baselines, and comparisons exactly. Use at least one evidence-bearing visual from the paper, retain a clear source caption, and include the limitation needed to avoid overstating the findings. Deliver a fixed 1200 × 1600 editable HTML poster and a 2× PNG render.--Source: Ashish Vaswani et al., “Attention Is All You Need,” arXiv:1706.03762v7.-```--[Third-party content notice](./gallery/academic-posters/attention-is-all-you-need/NOTICE.md)------## Art Design### Sky Archive@@ -806,6 +799,7 @@ If you find Editable Visual Design useful, please consider citing our technicalWe are grateful to the open-source projects that have helped shape the public conversation around AI-native visual creation, including:- [awesome-gpt-image](https://github.com/ZeroLu/awesome-gpt-image), whose clear prompt-and-result gallery helped inspire the presentation of this Gallery.+- [PaperGallery](https://github.com/LongHZ140516/PaperGallery), for providing the research paper workflow diagram reference cases used in our Paper Fig Gallery.- [OpenDesign](https://github.com/EthanGuo2022/OpenDesign), for advancing open, agent-driven, editable visual artifacts and visible design trajectories.- [AutoDesign](https://github.com/Yaxin9Luo/AutoDesign), for advancing reusable DesignHarness optimization and evidence-grounded academic artifact creation through PosterBench.- [taste-skill](https://github.com/leonxlnx/taste-skill), for advancing practical design-taste guidance for agent-built interfaces and visual systems.@@ -815,4 +809,4 @@ And thanks to the broader open-source design and Coding Agent communities for ma## License-This community project is provided under the [Apache License 2.0](./LICENSE) and is not an official OpenAI project. See [Third-party notices](./THIRD_PARTY_NOTICES.md) for dependency attribution.+Original project code is provided under the [Apache License 2.0](./LICENSE). Third-party paper content and external runtime resources retain their respective terms; see [Third-party notices](./THIRD_PARTY_NOTICES.md). This community project is not an official OpenAI project.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 36ae7d0..04906a1 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -4,3 +4,11 @@ Each skill contains its own dependency notices. Dependencies are installed separ- See `skills/editable-design/THIRD_PARTY_NOTICES.md`.- See `skills/html-to-pptx/THIRD_PARTY_NOTICES.md`.++## Paper Fig++Paper Fig v2 adapts Presentations resources (26.905.11957). The maintainer-supplied package includes inherited documentation, helper scripts, and an icon, with their original notices retained. Those resources retain their original rights and are not relicensed under this repository's Apache-2.0 license. `@oai/artifact-tool` and image-generation services are external dependencies, not included in the package. See `skills/paper-fig/NOTICE.md`.++## Research paper figure cases++The Paper Fig Gallery includes generated reconstructions based on cases collected by [PaperGallery](https://github.com/LongHZ140516/PaperGallery). The original paper figures, scientific content, and other third-party imagery retain the original authors' or publishers' rights; the repository's Apache-2.0 license does not relicense them. See [case attribution and reuse notes](gallery/paper-figures/NOTICE.md).diff --git a/TOOLKIT.md b/TOOLKIT.mdindex ef23609..e7461e4 100644--- a/TOOLKIT.md+++ b/TOOLKIT.md@@ -2,7 +2,7 @@Agent-driven creation of editable, tastefully crafted visual artifacts.-This repository packages two independent Codex skills. The main skill turns a visual brief into a fixed-canvas design with real text, semantic HTML layers, independent imagery, rendered output, an editor, an animated layer breakdown, and an evidence-backed Design Replay. The companion skill converts compatible HTML into an editable PowerPoint file when that format is explicitly requested.+This repository packages three Codex skills. Paper Fig creates editable research method and architecture diagrams as PowerPoint. Editable Design turns a visual brief into a fixed-canvas HTML design with real text, independent imagery, an editor, a layer breakdown, and a Design Replay. HTML to PPTX converts compatible HTML into an editable PowerPoint file when that format is requested.See the public [Editable Visual Design Gallery](https://github.com/yejy53/Editable-Design#gallery) for prompts, final renderings, editable demonstrations, and Agent Design Replays.@@ -10,13 +10,25 @@ See the public [Editable Visual Design Gallery](https://github.com/yejy53/Editab| Skill | Purpose | Main outputs || --- | --- | --- |+| [`paper-fig`](skills/paper-fig/) | Generate paper workflow and architecture diagrams from method descriptions | Editable `.pptx` || [`editable-design`](skills/editable-design/) | Create polished posters, covers, campaign graphics, information designs, menus, banners, and social cards | `index.html`, rendered PNG, `editor.html`, `layers.html`, and `replay/index.html` || [`html-to-pptx`](skills/html-to-pptx/) | Convert clean fixed-canvas HTML, Editable Design editor pages, or exploded-layer boards | Editable `.pptx` with independently selectable elements where the source structure permits |-The skills are siblings, not nested dependencies. `editable-design` completes its normal HTML and PNG delivery without PowerPoint support. `html-to-pptx` runs only when the user asks for a PPTX and automatically recognizes clean design HTML, `editor.html`, and `layers.html`; it can also convert compatible HTML produced elsewhere.+Install only the skill you need. `paper-fig` does not require either of the other skills. `editable-design` completes its HTML and PNG delivery without PowerPoint support. `html-to-pptx` runs when a PPTX is requested and recognizes clean design HTML, `editor.html`, and `layers.html`.## Install+### Paper Fig: one request in Codex++```text+Install the paper-fig Skill from:+https://github.com/yejy53/Editable-Design/tree/main/skills/paper-fig+```++Provide a method description and the visual style you want. See the [Paper Fig guide](skills/paper-fig/INSTALL.md) for manual installation and technical details.++### Editable Design: manual source install+Use a sparse, blob-filtered clone so the install checks out the core skill without the Gallery media:```bash@@ -51,11 +63,18 @@ Detailed requirements and direct CLI usage are documented in each skill's README- [`editable-design` setup and capability notes](skills/editable-design/README.md)- [`html-to-pptx` setup and conversion commands](skills/html-to-pptx/README.md)+- [`paper-fig` installation and host requirements](skills/paper-fig/INSTALL.md)## Use in CodexAsk Codex to use the installed skill by name:+```text+Use $paper-fig to turn the following method description into a paper workflow diagram in my requested visual style. Deliver an editable PowerPoint.+```++For a visual design brief:+```textUse $editable-design to create a polished 3:4 campaign poster for ...```@@ -78,8 +97,8 @@ Create a source archive without installed dependencies or temporary files:./pack.sh```-The output path is printed when packaging completes. You can also package either skill independently with its own `pack.sh`.+The output path is printed when packaging completes. See each skill's installation guide for individual packaging options.## License-This community project is provided under the [Apache License 2.0](LICENSE) and is not an official OpenAI project. See [Third-party notices](THIRD_PARTY_NOTICES.md) for dependency attribution.+Original project code is provided under the [Apache License 2.0](LICENSE). External host resources and third-party content retain their respective terms. This is not an official OpenAI project. See [Third-party notices](THIRD_PARTY_NOTICES.md) for attribution and scope.diff --git a/assets/paper-fig-powerpoint.png b/assets/paper-fig-powerpoint.pngnew file mode 100644index 0000000..aa36b55Binary files /dev/null and b/assets/paper-fig-powerpoint.png differdiff --git a/assets/paper-fig-powerpoint.webp b/assets/paper-fig-powerpoint.webpnew file mode 100644index 0000000..8d1da36Binary files /dev/null and b/assets/paper-fig-powerpoint.webp differdiff --git a/gallery/academic-posters/attention-is-all-you-need/NOTICE.md b/gallery/academic-posters/attention-is-all-you-need/NOTICE.mddeleted file mode 100644index cf3f388..0000000--- a/gallery/academic-posters/attention-is-all-you-need/NOTICE.md+++ /dev/null@@ -1,12 +0,0 @@-# Third-party content notice--This gallery image is an independently designed research-poster adaptation of:--Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones,-Aidan N. Gomez, Lukasz Kaiser, and Illia Polosukhin. “Attention Is All You-Need.” arXiv:1706.03762v7 (2017).--The paper and paper-derived figures or tables are not covered by this-repository's Apache-2.0 license. Their inclusion here is for attributed,-non-commercial scholarly demonstration. Users are responsible for reviewing-the source paper's rights terms before redistributing or adapting them.diff --git a/gallery/academic-posters/attention-is-all-you-need/final.png b/gallery/academic-posters/attention-is-all-you-need/final.pngdeleted file mode 100644index ec4751c..0000000Binary files a/gallery/academic-posters/attention-is-all-you-need/final.png and /dev/null differdiff --git a/gallery/academic-posters/attention-is-all-you-need/preview.webp b/gallery/academic-posters/attention-is-all-you-need/preview.webpdeleted file mode 100644index c1002f3..0000000Binary files a/gallery/academic-posters/attention-is-all-you-need/preview.webp and /dev/null differdiff --git a/gallery/academic-posters/attention-is-all-you-need/prompt.md b/gallery/academic-posters/attention-is-all-you-need/prompt.mddeleted file mode 100644index 1ef77c5..0000000--- a/gallery/academic-posters/attention-is-all-you-need/prompt.md+++ /dev/null@@ -1,11 +0,0 @@-# Attention Is All You Need--Create a vertical academic research poster from the supplied paper PDF. Read the-whole paper before designing. Present the research question, the Transformer-method, and the paper's strongest quantitative evidence, preserving all numbers,-units, baselines, and comparisons exactly. Use at least one evidence-bearing-visual from the paper, retain a clear source caption, and include the limitation-needed to avoid overstating the findings. Deliver a fixed 1200 × 1600 editable-HTML poster and a 2× PNG render.--Source: Ashish Vaswani et al., “Attention Is All You Need,” arXiv:1706.03762v7.diff --git a/gallery/paper-figures/NOTICE.md b/gallery/paper-figures/NOTICE.mdnew file mode 100644index 0000000..6e29a92--- /dev/null+++ b/gallery/paper-figures/NOTICE.md@@ -0,0 +1,17 @@+# Research paper figure attribution++The three `final.png` files in this directory were supplied by the project maintainer as **Paper Fig-generated results**, not as the original paper figures. `preview.webp` is a lossless, full-resolution re-encoding of each supplied PNG. These examples show figure reconstruction, not the reproduction of a paper's experiments or a controlled model benchmark.++The reference cases were discovered through [PaperGallery](https://github.com/LongHZ140516/PaperGallery), whose [Pipeline / FlowChart collection](https://longhz140516.github.io/PaperGallery/) credits the underlying papers.++| Case | Original research | Reference entry |+| --- | --- | --- |+| `omnimanip` | [OmniManip: Towards General Robotic Manipulation via Object-Centric Interaction Primitives as Spatial Constraints](https://arxiv.org/abs/2501.03841) | [PaperGallery: OmniManip](https://longhz140516.github.io/PaperGallery/images/pipeline-Pan_OmniManip_2025/) |+| `compact3d` | [CompGS: Smaller and Faster Gaussian Splatting with Vector Quantization](https://arxiv.org/abs/2311.18159) | [PaperGallery: Compact3D](https://longhz140516.github.io/PaperGallery/images/pipeline-Navaneet_Compact3D_2024/) |+| `icedit` | [In-Context Edit: Enabling Instructional Image Editing with In-Context Generation in Large Scale Diffusion Transformer](https://arxiv.org/abs/2504.20690) | [PaperGallery: ICEdit](https://longhz140516.github.io/PaperGallery/images/pipeline-Zhang_ICEdit_2025/) |++Original figures, paper content, and third-party imagery remain the property of their authors or publishers. Their rights are not covered by this repository's Apache-2.0 license. Consult each paper and the applicable rights holder before redistributing or adapting the figures. Attribution to PaperGallery does not itself grant permission to reuse the underlying paper content.++Only rendered result images are included here. Paired original-reference images and verified matching PPTX files are not included in this gallery update.++The maintainer-supplied PowerPoint screenshot at `assets/paper-fig-powerpoint.png` (with a lossless WebP preview) shows the OmniManip reconstruction selected as separate editing objects. The same paper-content attribution applies to that screenshot; PowerPoint's interface belongs to Microsoft.diff --git a/gallery/paper-figures/compact3d/final.png b/gallery/paper-figures/compact3d/final.pngnew file mode 100644index 0000000..58721ceBinary files /dev/null and b/gallery/paper-figures/compact3d/final.png differdiff --git a/gallery/paper-figures/compact3d/preview.webp b/gallery/paper-figures/compact3d/preview.webpnew file mode 100644index 0000000..cc9defeBinary files /dev/null and b/gallery/paper-figures/compact3d/preview.webp differdiff --git a/gallery/paper-figures/icedit/final.png b/gallery/paper-figures/icedit/final.pngnew file mode 100644index 0000000..735adb2Binary files /dev/null and b/gallery/paper-figures/icedit/final.png differdiff --git a/gallery/paper-figures/icedit/preview.webp b/gallery/paper-figures/icedit/preview.webpnew file mode 100644index 0000000..f86d025Binary files /dev/null and b/gallery/paper-figures/icedit/preview.webp differdiff --git a/gallery/paper-figures/omnimanip/final.png b/gallery/paper-figures/omnimanip/final.pngnew file mode 100644index 0000000..cde3368Binary files /dev/null and b/gallery/paper-figures/omnimanip/final.png differdiff --git a/gallery/paper-figures/omnimanip/preview.webp b/gallery/paper-figures/omnimanip/preview.webpnew file mode 100644index 0000000..04c65deBinary files /dev/null and b/gallery/paper-figures/omnimanip/preview.webp differdiff --git a/pack.sh b/pack.shindex c61a3a1..294e4fb 100755--- a/pack.sh+++ b/pack.sh@@ -14,6 +14,7 @@ donecp -p "$toolkit_dir/TOOLKIT.md" "$stage/$name/README.md"cp -R "$toolkit_dir/skills/editable-design" "$stage/$name/skills/"cp -R "$toolkit_dir/skills/html-to-pptx" "$stage/$name/skills/"+cp -R "$toolkit_dir/skills/paper-fig" "$stage/$name/skills/"find "$stage/$name" -name '.DS_Store' -deletefind "$stage/$name" -name '._*' -deletediff --git a/skills/paper-fig/INSTALL.md b/skills/paper-fig/INSTALL.mdnew file mode 100644index 0000000..34e4de5--- /dev/null+++ b/skills/paper-fig/INSTALL.md@@ -0,0 +1,39 @@+# Paper Fig 使用说明++这是从 Presentations 复制并轻量修改的独立技能,用于论文 pipeline、方法框架图、系统架构图及其他可编辑学术插图。技能名称为 `paper-fig`,默认输出单页 PPTX。++## 安装与调用++解压 ZIP,将整个 `paper-fig` 文件夹放入目标 Codex 环境的个人技能目录:设置了 `CODEX_HOME` 时使用其下的 `skills/`,否则使用 `~/.codex/skills/`。保留所有子目录;不要只复制 `SKILL.md`,也不要覆盖原有的 Presentations。由宿主重新发现技能后,在任务中调用 `$paper-fig`。++例如:++> 使用 $paper-fig,根据以下方法描述制作一页可编辑的论文 pipeline。先生成完整设计预览,再参考预览构建 PPTX。方法描述:……++生成预览前会参考 `references/preview_prompt.md`,将画布、布局比例、配色、文字、连线以及各区域所需的图像素材整理成完整绘图 prompt,保存到当前任务的 `work/preview-prompt.md`,方便查看和复用。新设计默认包含有助于解释内容的图像素材,用户要求无图设计时除外。++或:++> 使用 $paper-fig,将附图忠实重建为可编辑 PPTX。保留原图的布局、比例、字体、配色、文字和连线路径。++默认遵循用户的模板或设计。已有重建参考图时直接使用;生成预览后,可针对明显的局部留白失衡、拥挤或错位给出最多 3 条具体建议;修复仅在用户已授权的范围内执行,未授权时保留原预览并继续。之后按选定参考完成重建。仅在用户要求的范围内调整设计,可编辑性不会被视为重新设计的理由。++## 运行环境++适用于提供兼容演示文稿运行时的 Codex 环境。需要 Node.js、Python,以及宿主提供的 `@oai/artifact-tool`;生成整页预览或子图时,还需要可用的图像生成工具。提供参考图且不需要生成新素材时,可以直接进行重建。++技能通过 `load_workspace_dependencies` 或宿主已提供的兼容运行时路径定位依赖,不包含作者电脑的固定路径。执行脚本前,将 `RUNTIME_NODE`、`RUNTIME_NODE_MODULES`、`RUNTIME_BIN_DIR`、`RUNTIME_PYTHON` 设置为接收方自己的路径,并让子进程继承这些环境变量。`SKILL_DIR` 指向安装后的 `paper-fig` 文件夹。++ZIP 包含完整技能文档与辅助脚本,不包含 `@oai/artifact-tool` 运行时、字体、图像生成服务或服务凭证。仅将 ZIP 解压到一个没有这些能力的普通聊天环境,并不能直接生成 PPTX。++## 修改范围++- 修改 `SKILL.md` 的名称、适用范围、运行环境说明和模板入口。+- 在制作流程中加入完整预览、参考重建,以及裁切或每批最多并行生成 4 个独立高清素材。+- 新增 `references/preview_prompt.md`,指导整体绘图 prompt 的具体表达和图像素材规划,不包含固定案例或额外检查流程。+- 参考重建默认忠实保留用户设计,移除原改编版中允许自主优化的宽泛措辞。+- 生成预览后增加一次简短的局部修复建议,不自动改动用户提供或已选定的参考图,不新增报告或强制确认。+- 更新 `agents/openai.yaml` 的显示名称与调用提示。+- `style_guidelines.md`、`references/template_following.md`、实现说明、API 文档与验证脚本均沿用原版;没有添加新的审批或检查流程。++参考基础为 Presentations 26.905.11957。本技能为独立改编版,不会随原插件更新自动改变。diff --git a/skills/paper-fig/NOTICE.md b/skills/paper-fig/NOTICE.mdnew file mode 100644index 0000000..e3d2144--- /dev/null+++ b/skills/paper-fig/NOTICE.md@@ -0,0 +1,7 @@+# Paper Fig provenance and third-party notices++This directory contains the maintainer-supplied `paper-fig-v2.skill.zip` contents, with this attribution notice added. The original package files are preserved unchanged.++Paper Fig is an independent adaptation of Presentations 26.905.11957, as documented in `INSTALL.md`. It includes inherited presentation guidance, API documentation, helper scripts, and a presentation icon. Original copyright notices are retained. In particular, several helper scripts state “Copyright (c) OpenAI. All rights reserved.” The repository's Apache-2.0 license does not relicense those third-party materials or imply that OpenAI endorses this project.++The package does not include `@oai/artifact-tool`, a model service, or service credentials. Those dependencies and their usage remain subject to the provider's terms.diff --git a/skills/paper-fig/SKILL.md b/skills/paper-fig/SKILL.mdnew file mode 100644index 0000000..d82321e--- /dev/null+++ b/skills/paper-fig/SKILL.md@@ -0,0 +1,237 @@+---+name: paper-fig+description: Create editable paper figures, method pipelines, and architecture diagrams as PPTX, faithfully following the user's template or design. Use supplied references or generate full-page previews, suggest local refinements, and crop or generate high-resolution assets for editable reconstruction.+---++# Paper Fig++Create academic figures with the presentation workflow below. Default to a single editable PPTX page unless the user specifies another page count or output. Keep scientific labels, equations, modules, and connections editable where practical; use raster assets for the imagery that needs them. This is an independent adaptation of Presentations.++Use this skill in an environment that provides the presentation runtime, including `@oai/artifact-tool`, and an image-generation tool when generation is needed. Resolve runtime paths through `load_workspace_dependencies` when available, or use compatible runtime paths already supplied by the host. Export the resolved `RUNTIME_NODE`, `RUNTIME_NODE_MODULES`, `RUNTIME_BIN_DIR`, and `RUNTIME_PYTHON` variables to the processes that need them. Set `SKILL_DIR` to this installed skill folder. When the loader is unavailable, compatible runtime paths already supplied by the host satisfy the runtime-discovery instructions in the inherited references, including any bundled LibreOffice path needed for rendering. The ZIP contains the skill resources, not the external runtime or image-generation service; if a required capability is missing, state which capability is unavailable.++Read the guidance relevant to each part of the request; a user may ask you to explain, edit and create in the same task. If they only ask questions about a deck, inspect it without making changes. Before editing an existing deck or following a template, read [template following](references/template_following.md). When creating or changing slide layouts, read [visual design guidance](style_guidelines.md). For Google Slides, read [Google Slides routing](routing/google_slides.md) first.++Proceed when the request is clear. Ask only when missing information would change what you make or how you make it.++## Follow the user's template or design++When the user asks to match or reconstruct a template or reference, reproduce its appearance faithfully. Read and follow [template following](references/template_following.md). Preserve the canvas dimensions, layout, positions, proportions, fonts, colors, spacing, imagery, labels, and connection routes unless the user's task calls for changes. The user's wording, scientific notation, and design take precedence over general writing advice and default styling below. For the selected reference, whether supplied or generated, those defaults do not authorize rewriting, adding, removing, or rearranging reference content; scientific content remains grounded in the user's information. Editability is an implementation requirement, not permission to redesign. Limit unrequested changes to small technical fixes needed to reproduce the reference correctly, such as preventing conversion-induced clipping; do not reinterpret its visual style. A reference supplied only for content or inspiration has the role the user assigns to it. When generating a preview, follow the user's design directions; once selected, treat the preview as the design to reconstruct, not an invitation to design the page again.++## Artifact Template Selection++For academic figures, use the supplied reference or the full-page preview workflow below to establish the design; do not open a presentation template picker by default. Read [template selection](references/template-elicitation.md) only when the user explicitly asks to browse or select presentation templates.++## Writing Quality Instructions++Oftentimes, when an AI model makes slides, the writing is poor-quality and/or AI slop. You must instead write in a clear, direct, and professional way for all content you write on the slide, following the instructions below.++The examples below show wording to avoid, why it is slop/bad writing, and how you would want to write that instead. They are non-exhaustive; apply the same judgment to writing quality more generally.++### Taxonomy++#### 1. Awkward/unnatural wording++Wording that seems unfit for the text and should be rephrased to seem more human.++| Don't write | Why it is slop/bad writing | You should instead write like this |+| --- | --- | --- |+| Word: “Shopping has become more deliberate and **value-led**.” | “Value-led” is an awkward and vague phrase that does not carry much substance. It comes off as an empty abstraction. | “Shopping has become more deliberate and focused on **value**” |+| Word: “Contributions **waned** over the period.” | “Waned” is unnecessary. It is more direct and intuitive to simply say “decreased”. | “Contributions **decreased** over the period” |+| Word: “A **closer** 2021 **step-up** from a small **base**” | The word “closer” followed by “step-up” makes it unclear what the increase is ‘closer’ to. The comparison sounds unnatural and can be made more explicit by replacing it with “increased”. Baseline is a more natural phrasing of “base”. | “A **larger increase** in 2021 from a **low baseline**” |+| Phrase: “A **five-question pulse** uses simple 0-10 scores and one **verbatim follow-up** to reveal what matters most.” | The “five-question pulse” and “verbatim follow-up” are unnatural phrasings that are difficult to parse. | “The **five-question survey** uses a 0-10 scale and one **open-ended question**.” |+| Phrase: “Sony calculates Adjusted OIBDA as operating income plus depreciation and amortization expense, **less profit and loss amounts** that Sony **deems non-recurring**.” | This phrasing is clunky and hard to read because it stacks multiple awkward phrases together. The phrase “deems non-recurring” is also awkward given that you could simply use non-recurring as an adjective (Sony’s involvement implied earlier in the sentence).<br><br>The phrase “less profit and loss amounts” is also an awkward way to communicate the financial impact. | “Sony calculates Adjusted OIBDA as operating income plus depreciation and amortization expenses, **less non-recurring profits and losses**” |+| Phrase: “Evidence from the early COVID-19 through the inflationary aftermath shows consumers are **thinking harder before they buy.**” | “Thinking harder before they buy” is a very strange phrasing that should be rephrased to be more aligned with the text. | “Since COVID-19, consumers have become more **deliberate about purchases**” |+| Label: “Immediate demand shock” | The word “immediate” unnecessarily repeats the suddenness of “shock,” which makes the statement feel awkward and redundant. | “Sharp decline in demand” |+| Label: “VERBATIM FOLLOW-UP” | What is “verbatim follow-up”? That is an awkward/unnatural phrase that makes the underlying meaning unclear. | “OPEN-ENDED QUESTION” |+| Label: “POST-COVID CONSUMER” | This is supposed to mean consumers after COVID-19, but it's expressed awkwardly as an adjective. | “Consumers after COVID-19” |++#### 2. Excessive/flowery wording++Wording that is excessively elaborate, sophisticated-sounding, or slogan-like.++| Don't write | Why it is slop/bad writing | You should instead write like this |+| --- | --- | --- |+| Word: “Introduced Snapdragon 8 Elite, pairing the custom Oryon CPU with stronger AI performance for **next-generation** flagship smartphones.” | “Next-generation” is excessive and flowery because ‘flagship’ already conveys that smartphones are advanced. | Omit the word entirely. |+| Phrase: “A **five-question pulse** uses simple 0-10 scores and one **verbatim follow-up** to reveal what matters most.” | The ‘five-question pulse’ and ‘verbatim follow-up’ are also unnecessarily wordy, and can be simplified to a less sophisticated-sounding phrase. | “The **five-question survey** uses a 0-10 scale and one **open-ended follow-up.**” |+| Phrase: “Translate priorities into **coordinated execution**.” | This phrase is flowery because it sounds action-oriented and polished but conveys little meaning. The words “coordinated execution” are overly abstract and excessive. | “Translate priorities into **a clear execution plan**” |+| Phrase: “A **structurally lower** commute base.” | “Structurally lower” is inflated and overly elaborate, which obscures the intended meaning of the sentence. | “A **permanent** drop in commuting” |+| Phrase: “The organization seeks to **holistically cultivate a multifaceted ecosystem of synergistic capabilities** that meaningfully facilitates the **realization of enhanced outcomes**.” | “Holistically cultivate a multifaceted ecosystem of synergistic capabilities” and “realization of enhanced outcomes” are excessively verbose and elaborate. It can be streamlined to convey the phrase’s underlying message in a less sophisticated-sounding way. | “The organization seeks to build a **cohesive set of capabilities** that will **improve its outcomes**” |+| Phrase: “Reduced overhead through **scalable spans and layers**” | “Scalable spans and layers” is jargon-filled and adds little meaning. From the phrase, it is also unclear what “scalable” is referring to. | “Reduced overhead through **streamlined** **management structures**” |+| Label: “Catalyzing Transformative Excellence” | “Catalyzing transformative excellence” inflates a simple concept and makes the label sound overly sophisticated. | “Performance Improvement” |++#### 3. Vague/empty wording++Wording that is unclear, abstract, or general in a way that does not convey any real substance.++| Don't write | Why it is slop/bad writing | You should instead write like this |+| --- | --- | --- |+| Word: “FY24 revenue $2.68B (+26%), with **broad-based** usage across products.” | “Broad-based” is vague because it does not identify which products saw the increase in usage. It should be replaced with a more specific metric of growth to reflect the increase in usage. | “FY24 revenue $2.68B (+26%), with usage **increasing** across products.” |+| Phrase: “Execution depends on teams that deliver reliably, **sustain the core** and continuously improve operations” | “Sustain the core” is vague phrasing that makes little sense. The jargon-heavy language needs to be replaced with a more specific representation of what the intended message is, clarifying that it is the core business. | “Execution depends on teams that deliver reliably, **sustain the core business**, and continuously improve operations.” |+| Phrase: “**Progressive promotion** improves trust and usability” | “Progressive promotion” is vague and ambiguous, with no discernible meaning. To make the phrase less abstract and slogan-like, it needs to mention exactly what is improving “trust and usability”. | “**Customer rewards** programs improve trust and usability” |+| Phrase: “**More consistent coverage** and **stronger transparency**” | “More consistent” and “stronger transparency” are vague and abstract phrases.<br><br>Given the slide’s focus on operational improvements, the phrase should specify the concrete outcome, like more consistent staffing coverage and clearer scheduling visibility. | “**Improved staffing coverage and scheduling visibility**” |+| Phrase: “**Price and availability** lead **transportation adoption**” | Both “price and availability” and “transportation adoption” are clear, but taken together convey no meaning. A specific causal relationship should be added to relay the two. | “Price and availability are **the main drivers of** transport adoption” |+| Label: “Strategic Value Drivers” | “Strategic Value Drivers” is too abstract to identify what the section actually conveys. Given the slide’s focus on revenue metrics, it should be more tailored to that. | “Revenue Metrics” |++#### 4. Unnecessary wording++Wording that is wholly unnecessary and would be best to remove.++| Don't write | Why it is slop/bad writing | You should instead write like this |+| --- | --- | --- |+| Word: “**Practical** consumer needs consistently outweigh broader supporting factors across Germany, the US, and China.” | “Practical” is unnecessary because “consumer needs” already suggests that they are concrete needs. Removing the word helps clarify the sentence’s intended meaning. | “Consumer needs consistently outweigh broader supporting factors across Germany, the US, and China” |+| Word: “Operating earnings after **defined** non-GAAP adjustments” | “Defined” does not clarify anything. It makes the sentence more formal and obscures its initial meaning. | “Operating earnings after the non-GAAP adjustments” |+| Phrase: “A five-question pulse uses simple 0-10 scores and one verbatim follow-up to **reveal what matters most.**” | The “reveal what matters most” is empty phrasing that does not affect the phrase’s meaning when removed. | “The five-question survey uses a 0-10 scale and one open-ended follow-up.” |+| Label: “A NEW ERA” | Has no clear connection to the slide’s discussion of employee survey results and does not communicate a specific point. | Omit the phrase entirely. |+| Label: “MOMENTUM AHEAD” | Arbitrary positive-sounding phrase that is not supported by or relevant to the refinancing information on the slide. | Omit the phrase entirely. |+| Label: “UNLOCKING POTENTIAL” | Generic promotional language that adds nothing to a slide showing transit recovery trends. | Omit the phrase entirely. |++#### 5. Illogical wording++Wording that is not coherent or logical and does not make sense.++| Don't write | Why it is slop/bad writing | You should instead write like this |+| --- | --- | --- |+| Word: “Test, **learn**, and scale the most promising ideas with disciplined investment” | While “testing” and “scaling” promising ideas is coherent, “learning” promising ideas makes no sense. The context implies that this may instead be “development” of these ideas. | “**Develop**, test, and scale the most promising ideas with disciplined investment” |+| Phrase: “Transit & **ground passenger** jobs” | “Transit & ground passenger jobs” is incomprehensible, especially because “ground passenger jobs” makes no logical sense. Fixing the linkage makes this coherent again. | “Transit and passenger transportation jobs” |+| Phrase: “**Incubate adjacent offerings** and business models that can **expand the core.**” | The dense phrasing of “incubate adjacent offerings” carries no meaning. The phrase “expand the core” also not coherent because it doesn’t specify what the ‘core’ is referring to. | “Develop **related products and business models** that expand the core business.” |+| Phrase: “**New mobility concepts** and changing behavior in cities.” | “New mobility concepts” is incoherent and does not make sense in the context of this sentence. The underlying message revolves around new transportation options, not novel “mobility concepts”. | “New transportation options and changing travel behavior in cities.” |+| Phrase: “79% Transit use **back to pre-pandemic**” | The phrasing is not parseable. It could mean that transit use has returned to 79% of its pre-pandemic level, or that 79% represents the pre-pandemic transit-use rate. To make the relationship logical, it should state what the current level is and how it compares with the previous pre-pandemic levels. | “Transit use is at 79%, matching pre-pandemic levels”<br><br>or<br><br>“Transit use has recovered to 79% of its pre-pandemic level.” |+| Label: “Revenue Growth Decline Expansion” | “Revenue growth decline expansion” is illogical because it combines contradictory ideas without explaining how they relate. “Growth” and “decline” point in different directions. | “Revenue Decline” |++| | Words | Phrases | Labels |+| --- | --- | --- | --- |+| Awkward/unnatural wording | ✅ | ✅ | ✅ |+| Excessive/flowery wording | ✅ | ✅ | ✅ |+| Vague/empty wording | ✅ | ✅ | ✅ |+| Unnecessary wording | ✅ | ✅ | ✅ |+| Illogical wording | ✅ | ✅ | ✅ |++### AI-isms++Avoid the following patterns of AI-generated wording in slide copy.++#### 1. Punctuation++| Don't write | Why it is slop/bad writing |+| --- | --- |+| Em dash: “Jobs fell 38% from February to April 2020, then climbed back gradually—ending 2024 still just below the pre-shock level.” | Em dashes are always slop. |+| Semicolon: “Travel demand and employment fell within weeks; persistent behavior shifts are shaping the path back.” | Semicolons are always slop. |+| Dot notation: “Faster growth • Better efficiency • Stronger outcomes” | ASCII dots are always slop. |+| Vertical bar: “Strategy \| Execution \| Impact” | Vertical bars are always slop. |+| Arrows: “Crisis-led and repetitive → one trusted plan → flexible, coordinated support → confident step-down with a route back” | Arrows are always slop. |++#### 2. “It’s not X, it’s Y” / “Do Y, not X”++| Don't write | Why it is slop/bad writing |+| --- | --- |+| “Humidity **is an** exposure trajectory, **not** a setpoint” | “Is / is not” sentence structures are always slop. |+| “This **isn’t just** a calendar - **it’s** a gateway to a more intentional life.” | “Is / is not” sentence structures are always slop. |+| “Data access **is not** a background detail. **It’s** the heart of the user experience.” | “Is / is not” sentence structures are always slop. |++#### 3. Passive Voice++| Don't write | Why it is slop/bad writing |+| --- | --- |+| “The proposal was approved by the team” | Passive voice is always slop. Write instead: “The team approved the proposal.” |+| “The launch was delayed” | Passive voice is always slop. Write instead: “The team delayed the launch.” |++#### 4. Imperative Title++| Don't write | Why it is slop/bad writing |+| --- | --- |+| Slide title: “Define the integration perimeter before designing the workplan” | Imperative slide titles are always slop. |+| Slide title: “Screen the energy credit, not the headline retail tariff” | Imperative slide titles are always slop. |++#### 5. Slogan-like Phrasing++| Don't write | Why it is slop/bad writing |+| --- | --- |+| Phrase: “Usage-based models turn customer activity into a direct revenue expansion path” | Slogan-like wording, particularly the use of “direct revenue expansion path” |+| Phrase: “Provided scale, speed and certainty by anchoring the club refinancing.” | Formulaic statement with the “scale, speed and certainty”. The statement is also unclear about how anchoring the club refinancing leads to scale, speed, and certainty. This is slogan-like with the buzzwords used in the formulaic statement. |++#### 6. Formulaic three-part lists++Avoid using three-part lists of actions, situations, or examples as a default sentence pattern. Repeated "X, Y, and Z" constructions make slide copy sound formulaic. State the main point directly. If each item matters, explain how the ideas relate or present them separately. Do not add filler to complete a trio or lose useful detail merely to avoid one.++| Don't write | Why it is slop/bad writing |+| --- | --- |+| “Partners can act **before a crisis, during daily strain and when care becomes difficult**.” | Packages overlapping situations into a three-part rhythm without clearly explaining when or how partners can help. |+| “Residents help **choose priorities, design services and judge whether access improves**.” | Bundles distinct responsibilities into a predictable three-action sequence instead of explaining how residents influence the services they receive. |+| “Example proposal: connect a housing area with **food, care and the library**.” | Compresses different services and destinations into a tidy trio, leaving the proposed connection unclear. |+| “Outreach staff **listen, map existing services and document gaps**.” | Lists three actions without explaining how listening and service mapping help staff identify gaps. |++#### 7. Unnecessary hyphenated compounds++Avoid hyphenated compounds that make ordinary ideas sound awkward or unnecessarily technical. Prefer a plain phrase when it expresses the same meaning more naturally. Use natural wording instead of simply deleting hyphens. Preserve exact official names and necessary distinctions.++| Don't write | Why it is slop/bad writing |+| --- | --- |+| “Use overnight shelters or **violence-against-women** shelters.” | Packs a description of the people served into a long modifier. Write instead: “Use overnight shelters or shelters for women experiencing violence.” |+| “People in the **Point-in-Time** Count” | Repeats a technical name where a simple reference may suffice. After identifying the count, write instead: “People in the count”. Preserve the official name where needed. |+| “**Time-limited** accommodation” | A plain phrase can explain the duration more naturally. Write instead: “Accommodation for a limited period”. |+| “**Owner-occupied** housing” | For a general audience, a plain phrase can explain who lives in the home. Write instead: “Homes where the owners live”. |+| “A **one-night** snapshot misses hidden homelessness.” | The duration reads naturally as a separate phrase. Write instead: “A count on a single night misses hidden homelessness.” |++## Important instructions++- Visual assets: DO NOT use Python to draw any images; DO NOT use programmatic vector shapes for visuals; DO NOT use programmatic drawings of any sort. Use image search or imagegen instead! By default, DO NOT reuse the same image more than once (unless it's a background). Not only do you need to prepare visuals for the main concept, you also need to get decorative visuals. Before sourcing or generating visuals, be mindful of the desired aspect ratio, placement, and cropping options on the slide. For example, if you intend to place text to the left of the image containing a person, you should ask imagegen to put the person on the right side of the image.+- Default styling: use one composition instead of a collection of UI panels. UI-like styling typically includes card grids, pills, badges, button-like text boxes, tab or navigation patterns, repeated modular panels, dense dashboard-style layouts, and other component-library aesthetics that imply interactivity. Use stylized text boxes less, favoring a flat structure on the canvas.+- Font size: When a template is provided, match its font sizes. Avoid overly small text. When no template or style guidance is given, a good rule of thumb is at least 42pt for deck titles, 32pt for slide titles, and 17pt for body text. If you see overflow/overlap, try cutting content before shrinking text further to improve text layout.+- Title slide: Keep the title slide minimal and simple. Avoid cramming in too much information.++### Scope clarification for editable evidence++The prohibition on programmatic drawings applies to illustrative and decorative visual assets. Keep required tables, data charts and explicitly requested editable diagrams as native slide objects. Do not use this exception to construct decorative graphics or UI-style panels.++## Requirements++**Follow the requested design.** Use the user's template, reference, branding and layout instructions before any defaults in this skill. Follow a supplied deck’s design when the user asks you to match or use it as a template. If the user supplies a deck only as a source of text, data or images, do not assume they want you to copy its design. Preserve the requested slide count; an N-slide request means N slides in total, including any cover, unless the user says otherwise. Do not add a cover to a one-slide deliverable by default.++**Write for the audience.** Keep commentary about creating or checking the deck out of slides, speaker notes and requested explanations. Keep validation records private unless requested.++**Keep facts accurate.** Base factual claims on supplied materials or sources gathered for the task. Do not invent facts, numbers or citations. Clearly identify assumptions and hypotheses. Keep caveats that affect the conclusion, and point out disagreements between sources when they affect the answer. When summarizing or calculating, preserve the units, comparison being made and meaning.++**Keep content editable and complete.** Keep required tables, charts and diagrams editable. Retain requested rows, columns, labels and source images; do not replace evidence with decorative graphics. Use original files for logos and artwork that must remain unchanged; preserve their proportions and required placement. Cite external facts and images in the relevant slide's speaker notes. Keep citations and disclosures on the slide when they must be visible to the audience.++## Titles++**Name the subject directly.** For process, overview, definition, and setup slides, prefer a concise noun phrase that identifies the actual subject. Make plain topic titles the default for these slides. A clear topic label can be more useful than a full sentence, question, or takeaway. Choose the form that best describes what the slide actually shows. Avoid turning setup or background slides into claims, slogans, or announcements about the presentation.++For each title, consider whether a short noun phrase, an explanatory title, or a supported factual takeaway would serve the reader best. A noun phrase is an option to use - we don't always need to use noun phrases over sentences. Keep a good existing title when it already does the job.++Name the actual subject or distinction in plain language. Remove presenter narration such as "Start simple" and replace vague announcements such as "Two different questions" with the subjects being discussed. Do not force a title to sound like an insight. A setup slide can simply identify the information or assumptions it establishes.++Reconsider the title's framing before polishing its wording. Avoid generic narrative frames such as "From X to Y," "Two questions about...," or "Start with..." when a direct subject label is clearer. Replacing words within the same frame may leave the underlying problem intact.++| Don't write | You should instead write like this | Why it fits the slide |+| --- | --- | --- |+| "Start simple: a withdrawal reflex" | "The withdrawal reflex" | Names the mechanism explained by the diagram and removes the presenter's instruction. |+| "Two different questions about one behavior" | "Mechanism and evolution of behavior" | Names the two explanations that the slide compares. |+| "Same paycheck. Different purchasing power." or "The same take-home pay buys different amounts" | "Income and household assumptions" | Names the income and household setup used for the comparison. This slide establishes the baseline; it does not yet show a purchasing-power comparison. |+| "From first signal to verified recovery" or "From detection to post-incident review" | "Major incident response process" | Names the process being explained. The numbered steps already communicate the progression. |++Use a takeaway title when the slide establishes a specific finding. Use a range or progression when that progression itself is the subject. Do not force either form onto a slide that simply explains a topic.++Apply the writing quality instructions above and the punctuation rules below to whichever form you choose.++**Periods in titles and headings:** Remove trailing periods from short slide titles and section headings. Keep a terminal period only when the title or heading is a longer, complete sentence. A short complete sentence does not need a trailing period. Do not lengthen or otherwise rewrite a good title just to retain a period. Use normal punctuation in body text and preserve periods within abbreviations and numbers.++## Create or edit the deck++1. Read `references/implementation.md` and the [API quick start](artifact_tool_docs/API_QUICK_START.md) before coding. Use JavaScript ES modules with `@oai/artifact-tool`; do not use `python-pptx` or the obsolete Python API.+2. Follow the user’s requested order; otherwise, choose an order that covers the request without repetition. Give each slide a clear purpose. A factual summary, comparison or explanation is enough when the evidence does not support a recommendation.+3. **Generate a full-page design preview.** If the user supplies a reference for reconstruction, use it directly without generating another preview. Otherwise, after organizing the page content, scientific structure, and overall layout according to the user's design directions, read [drawing prompt guidance](references/preview_prompt.md). Write a complete, ready-to-use image-generation prompt covering the canvas, layout and region proportions, typography, palette, connections, and concrete image assets in each region. Include meaningful image assets by default unless the user requests an image-free design, and describe their subjects, counts, viewpoints, placement, and consistency across related states. Save the finished prompt as `work/preview-prompt.md` in the task workspace, then use it to generate the full-page design reference. The preview may contain text, titles, equations, arrows, and diagrams to communicate the entire design. Scientific content and connections remain grounded in the information supplied by the user.+4. **Suggest local preview refinements.** After generating a full-page preview, briefly look for visibly unbalanced empty areas, crowding, misalignment, or overlaps. When a material issue is present, offer up to three concrete local suggestions naming the affected area and adjustment; otherwise continue. Preserve useful whitespace and scientific content rather than adding elements just to fill space. Apply a repair only when requested or already authorized, limiting it to the affected area while preserving the rest of the design. Otherwise continue with the unmodified preview and leave the suggestions optional. Skip this step for supplied or already selected references unless feedback or repair is requested. This short design pass adds no separate report, repeated review loop, or mandatory approval pause.+5. **Faithfully reconstruct the reference and obtain high-resolution assets.** Follow [template following](references/template_following.md) for inspecting the reference, rebuilding editable objects, and comparing appearance, together with the fidelity rule above. Match the selected reference closely; apply design changes only within the scope requested by the user. During construction, crop visual assets directly from the selected reference (supplied image or generated preview) when its resolution is sufficient. When new assets are needed, use that selected full-page reference as an image reference and specify each asset's content, aspect ratio, and resolution needs while preserving its appearance, viewpoint, and visual style. Independent assets may be generated in parallel in batches of at most four, sharing the same reference and style direction; use sequential calls if the available tool requires them. Continue with native editable construction and the existing export workflow. No additional approval checkpoint or separate checklist is required by these preview and asset steps.+6. Read additional guidance only when needed: [cover design](references/cover_art_direction.md) for a new cover; [editable tables and charts](references/native_evidence.md); [bullet formatting](references/native_bullets.md) for new lists; [finance](domain_guidance/finance.md) for financial presentations. Use the [API reference map](artifact_tool_docs/api/API_DOCS.md#reference-map) for other objects.+7. Export a draft PPTX in the private build directory, then follow [validation and delivery](references/finalization.md). Inspect the rendered slides and fix problems. Do not change the user's design just to satisfy an automated style suggestion.++## Review and handoff++Check content coverage, slide count, factual accuracy, template match, text fit and editability. Read titles and body text together: remove unsupported conclusions, repeated points, filler subtitles and comments about creating the deck. Inspect the slides to decide whether style warnings need a fix. Passing automated checks does not prove the writing or design is good.++Return the deck and any explanation the user requested. Do not add a recap of your edits or successful validation checks unless asked. Mention problems or limitations that affect use of the deck. Do not rate your own work or list every instruction you followed. Do not deliver temporary files unless requested. For read-only questions, answer directly and cite the source you inspected.++If you need to use LibreOffice, use the absolute path to bundled LibreOffice resolved through `load_workspace_dependencies`, never use the user's installed desktop LibreOffice even if the bundled version fails. Include this instruction and the bundled path in every subagent handoff.++If the app supports it, link the final deck once with `:codex-file-citation{path="/abs/path/deck.pptx" purpose="output"}`. Otherwise use the app's normal file link. Say you checked the deck in PowerPoint only if you opened and inspected it there.diff --git a/skills/paper-fig/agents/openai.yaml b/skills/paper-fig/agents/openai.yamlnew file mode 100644index 0000000..a5ca617--- /dev/null+++ b/skills/paper-fig/agents/openai.yaml@@ -0,0 +1,7 @@+interface:+ display_name: "Paper Fig"+ short_description: "Create editable paper figures from visual references"+ icon_small: "./assets/file-presentation.png"+ icon_large: "./assets/file-presentation.png"+ brand_color: "#C43E1C"+ default_prompt: "Use $paper-fig to create an editable paper figure from my content or faithfully reconstruct my reference image as PPTX."diff --git a/skills/paper-fig/artifact_tool_docs/API_QUICK_START.md b/skills/paper-fig/artifact_tool_docs/API_QUICK_START.mdnew file mode 100644index 0000000..4f53d1d--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/API_QUICK_START.md@@ -0,0 +1,77 @@+# Presentation quick start (JavaScript)++Read `references/implementation.md` in the installed skill for runtime setup. Save the example as a `.mjs` file in the private build directory, with its `node_modules` link pointing to the supplied runtime packages. Set `SKILL_DIR` and `TMP_DIR` to absolute paths and run with `RUNTIME_NODE`.++This example shows how to use the API. Its data is made up; do not use it as a factual source or copy its design by default. Use the user's content, design and sources for real tasks. The script writes a draft PPTX and preview, not a checked final deck.++```js+import fs from "node:fs/promises";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { Presentation, PresentationFile } from "@oai/artifact-tool";++const { SKILL_DIR, TMP_DIR } = process.env;+if (!path.isAbsolute(SKILL_DIR ?? "") || !path.isAbsolute(TMP_DIR ?? "")) {+ throw new Error("Set absolute SKILL_DIR and TMP_DIR");+}+const { resolvePresentationFont, applyPresentationChartFont } = await import(+ pathToFileURL(path.join(SKILL_DIR, "container_tools/artifact_tool_utils.mjs")).href,+);+await fs.mkdir(TMP_DIR, { recursive: true });+const family = resolvePresentationFont();+const presentation = Presentation.create({+ slideSize: { width: 1280, height: 720 },+});+const slide = presentation.slides.add();+slide.background.fill = "#FFFFFF";++const title = slide.shapes.add({+ geometry: "textbox",+ position: { left: 72, top: 48, width: 1136, height: 80 },+ fill: "none",+ line: { fill: "none", width: 0 },+});+title.text = "Monthly order volume";+title.text.style = {+ typeface: family, fontSize: 40, bold: true,+ color: "#142735", autoFit: "none",+};++const chart = slide.charts.add("bar", {+ position: { left: 100, top: 180, width: 1080, height: 400 },+ categories: ["Jan", "Feb", "Mar"],+ series: [{ name: "Orders", values: [120, 145, 160], fill: "#285E8E" }],+ barOptions: { direction: "column", grouping: "clustered" },+ hasLegend: false,+ dataLabels: { showValue: true, position: "outEnd" },+});+applyPresentationChartFont(chart, { fontFamily: family });+slide.speakerNotes.textFrame.setText("Illustrative data for this API example only.");++const candidatePath = path.join(TMP_DIR, "candidate.pptx");+await (await PresentationFile.exportPptx(presentation)).save(candidatePath);+const preview = await presentation.export({ slide, format: "png", scale: 1 });+await fs.writeFile(path.join(TMP_DIR, "slide-1.png"),+ new Uint8Array(await preview.arrayBuffer()));+const layout = await slide.export({ format: "layout" });+await fs.writeFile(path.join(TMP_DIR, "slide-1.layout.json"), await layout.text());+```++Next, follow [validation and delivery](../references/finalization.md) and inspect the rendered final file. Also check that charts and tables are editable; preview images cannot show this.++## Existing decks++```js+import { FileBlob, PresentationFile } from "@oai/artifact-tool";+const presentation = await PresentationFile.importPptx(await FileBlob.load(sourcePath));+const snapshot = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes,layout",+ maxChars: 8000,+});+console.log(snapshot.ndjson);+// Resolve only an id found in the snapshot, then edit the existing object.+const target = presentation.resolve(verifiedObjectId);+target.text.replace(oldText, newText);+```++For user templates, read [template following](../references/template_following.md) before editing. Use the [API reference map](api/API_DOCS.md#reference-map) to look up objects and the methods for finding and editing them. Other API examples use TypeScript or JSX, which need additional build tools. Do not paste those examples into plain `.mjs` files.diff --git a/skills/paper-fig/artifact_tool_docs/api/API_DOCS.md b/skills/paper-fig/artifact_tool_docs/api/API_DOCS.mdnew file mode 100644index 0000000..a9abd19--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/API_DOCS.md@@ -0,0 +1,247 @@+# Presentation API Docs++Use these APIs to create and edit presentations. Examples show how the APIs work; they do not prescribe a design. For runnable JavaScript, start with [the quick start](../API_QUICK_START.md). TypeScript declarations and JSX require additional build tools and cannot be pasted into plain `.mjs` files.++## Conventions (units + presets)++- **Units**: slide geometry, line widths and numeric text `fontSize` use CSS pixels (`px`) at 96 DPI. Structured paragraph `marginLeft`/`indent` use EMU, and `spaceBefore`/`spaceAfter` use hundredths of a point in the verified runtime; see [native bullets](../../references/native_bullets.md).+- **Default canvas for examples**: use `1280 x 720` unless the task or source deck says otherwise. A useful full-slide content frame is `{ left: 72, top: 64, width: 1136, height: 592 }`.+- **Angles**: rotations use degrees.+- **Preset geometry**: `geometry` uses preset shape-name strings. Use standard shape presets and `geometry: "custom"` for bespoke paths.+- **Gradients**: stop `offset` ranges from `0` to `100000`.+- **Configuration objects**: pass settings together to create/add methods and grouped setters when the API supports them.+- **String values**: options such as geometry, fit, alignment, chart type, line style and connector kind are strings. References list allowed values or tell you how to search larger lists.+- **Type examples**: `type ... = { ... }` blocks describe the expected data structure. They are explanations, not types to import.+- **Layout methods**: use `slide.compose(...)` for rows, columns, grids and layers. Use object APIs for exact positioning, repeated slide elements, editable charts/tables/images and edits to imported decks.++## Find the right reference++- Rows, columns, grids, overlays, and 12-column spans: [`references/cookbook/layout.md`](./references/cookbook/layout.md).+- JSX node props and sizing mechanics: [`references/jsx.md`](./references/jsx.md).+- Tailwind-like visual strings: [`references/tokens.md`](./references/tokens.md).+- Inspect, resolve, edit, preview, and re-inspect loops: [`references/cookbook/imported-deck.md`](./references/cookbook/imported-deck.md).++## Quick start++```ts+const presentation = Presentation.create({+ slideSize: { width: 1280, height: 720 },+});++const slide = presentation.slides.add();+slide.background.fill = "slate-50";++const headline = slide.shapes.add({+ geometry: "textbox",+ name: "headline",+ position: { left: 72, top: 64, width: 720, height: 96 },+ fill: "none",+ line: { style: "solid", fill: "none", width: 0 },+});+headline.text = "Editable headline";+headline.text.style = { fontSize: 44, bold: true, color: "slate-950" };++const shape = slide.shapes.add({+ geometry: "roundRect",+ name: "summary-surface",+ position: { left: 72, top: 188, width: 520, height: 300 },+ fill: "white",+ line: { style: "solid", fill: "slate-200", width: 1 },+ borderRadius: "rounded-2xl",+});++const previewBlob = await presentation.export({+ slide,+ format: "png",+ scale: 2,+});+const layoutBlob = await slide.export({ format: "layout" });+const montageBlob = await presentation.export({+ format: "webp",+ montage: true,+ scale: 1,+});+const snapshot = await presentation.inspect({+ kind: "slide,textbox,shape",+ maxChars: 4000,+});+const help = presentation.help("*", {+ search: "chart axis labels",+ include: ["index", "notes"],+ maxChars: 4000,+});+const proto = presentation.toProto();+```++## Load Existing Presentation Data++Use `Presentation.load(proto)` when a host adapter gives the library serialized+presentation data. The loaded object exposes the same inspect, resolve, edit,+render, and serialize APIs as a newly created presentation.++```ts+const presentation = Presentation.load(proto);++const before = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",+ search: "Revenue",+ maxChars: 8000,+});++const slide = presentation.resolve(slideAnchorIdFromInspect);+const previewBefore = await presentation.export({+ slide,+ format: "png",+ scale: 1,+});+const layoutBefore = await slide.export({ format: "layout" });++const target = presentation.resolve(anchorIdFromInspect);+target.text.replace("Revenue", "Revenue outlook");+target.text.style = { fontSize: 24, color: "slate-950", bold: true };++const previewAfter = await presentation.export({+ slide,+ format: "png",+ scale: 1,+});+const layoutAfter = await slide.export({ format: "layout" });+const after = await presentation.inspect({+ target: { id: anchorIdFromInspect, beforeLines: 2, afterLines: 2 },+ kind: "textbox,shape,image,table,chart",+ maxChars: 3000,+});+const nextProto = presentation.toProto();+```++## Compose-first layout++```tsx+/** @jsxRuntime automatic */++const presentation = Presentation.create();+const slide = presentation.slides.add();++slide.compose(+ <column width="fill" height="fill" gap={16}>+ <paragraph+ name="headline"+ className="text-slate-950 text-3xl leading-tight"+ >+ <run textStyle={{ bold: true }}>Quarterly</run>+ <run> readiness</run>+ </paragraph>+ <rule stroke="#0f172a" width={160} weight={2} />+ </column>,+ {+ frame: { left: 48, top: 40, width: 864, height: 460 },+ baseUnit: 8,+ },+);+```++Use `name` for stable inspect and layout-export targeting. JSX materializing+tags default `width` to `"fill"` when you omit it.++## Core API Sequence++- Create presentations with `Presentation.create({ slideSize })` to control default slide dimensions.+- Add slides with `presentation.slides.add({ layout, layoutId })` or `presentation.slides.insert({ after, ... })`.+- Use `slide.compose(nodeOrJsx, { frame, baseUnit })` for compose-first layouts. JSX lowers into the same compose runtime as the helper-based API.+- Author content with config-first calls: `slide.shapes.add({ geometry, position, fill, line })`, `slide.images.add({ ... })`, `slide.tables.add({ ... })`, and `slide.charts.add(chartType, { ... })`.+- Format whole-shape text with grouped configs such as `shape.text.style = { fontSize, bold, color, alignment }`.+- Edit imported decks with `presentation.inspect({ kind, search, maxChars })`, `presentation.resolve(anchorId)`, and focused facade edits.+- Export previews with `presentation.export({ slide, format, scale })`.+- Export deck montages with `presentation.export({ format: "webp", montage: true, scale: 1 })`.+- Export layout JSON with `slide.export({ format: "layout" })`.+- Control editor gridlines and imported guides with `presentation.view`.+- Search API help with `presentation.help(query, { search, include, maxChars })`.+- Run high-level edits with `presentation.scripts.run(kind, options)`; see [`references/presentation.spec.md`](./references/presentation.spec.md) for the script surface.++## Output Map++| Output | API | Result |+| ------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------ |+| Slide PNG | `presentation.export({ slide, format: "png", scale })` | One preview image for one slide |+| Deck montage | `presentation.export({ format: "webp", montage: true, scale })` | One overview image containing the deck slides |+| Layout JSON | `slide.export({ format: "layout" })` | Structural JSON with bounds, ids, text, names, and object metadata |+| Searchable snapshot | `presentation.inspect({ kind, search, maxChars })` | NDJSON records for locating and resolving objects |+| Runtime handoff | `presentation.toProto()` | Serializable presentation data for host adapters |++## Minimal Patterns++Use these as the first API patterns to reach for:++```ts+// Create, preview, inspect, then serialize.+const presentation = Presentation.create({+ slideSize: { width: 1280, height: 720 },+});+const slide = presentation.slides.add();+const preview = await presentation.export({ slide, format: "png", scale: 1 });+const montage = await presentation.export({+ format: "webp",+ montage: true,+ scale: 1,+});+const snapshot = await presentation.inspect({+ kind: "slide,textbox,shape,image,chart,table",+ maxChars: 4000,+});+const proto = presentation.toProto();+```++```tsx+// Compose structure with first-principles rows/columns.+slide.compose(+ <row width="fill" height="fill" gap={28}>+ <column width={420} height="fill" gap={16}>+ <paragraph className="text-slate-950 text-5xl font-bold leading-tight">+ Title+ </paragraph>+ <paragraph className="text-slate-600 text-xl leading-relaxed">+ Editable copy in a fixed text column.+ </paragraph>+ </column>+ <box+ width="fill"+ height="fill"+ className="bg-slate-50 rounded-2xl shadow-sm"+ />+ </row>,+ { frame: { left: 56, top: 56, width: 1168, height: 608 }, baseUnit: 8 },+);+```++For 3-column and 12-column layouts, use [`references/cookbook/layout.md`](./references/cookbook/layout.md); keep spans local with `{ mode: "fr", value: 1 }` track objects.++Use `className` only for visual/text tokens such as `bg-*`, `rounded-*`,+`shadow-*`, `text-*`, `font-*`, and `leading-*`. Use layout props for+`width`, `height`, `gap`, `padding`, `align`, and `justify`.++## Reference Map++Open these references as needed:++- [`references/jsx.md`](./references/jsx.md) — compact JSX node surface and layout mechanics.+- [`references/tokens.md`](./references/tokens.md) — Tailwind-like token reference for colors, text, radius, shadows, and `className`.+- [`references/cookbook/layout.md`](./references/cookbook/layout.md) — first-principles layout recipes for rows, columns, 12-column grids, alignment, masks, and overlays.+- [`references/cookbook/imported-deck.md`](./references/cookbook/imported-deck.md) — safe inspect, resolve, edit, preview, and re-inspect loops for existing decks.+- [`references/presentation.spec.md`](./references/presentation.spec.md) — `Presentation` facade, slide collection, view controls, export/toProto, scripts.+- [`references/slide.spec.md`](./references/slide.spec.md) — `Slide` API, backgrounds, placeholders, notes, export, auto-layout.+- [`references/inspect.md`](./references/inspect.md) — grep-first snapshot (`inspect → rg → resolve/edit → re-inspect`) for loaded presentation data and templates.+- [`references/help.md`](./references/help.md) — grep-first API and template lookup (`help → build/edit → inspect`) for presentation JS workflows.+- [`references/layout.spec.md`](./references/layout.spec.md) — layouts, placeholders, and slide layout assignment.+- [`references/master.spec.md`](./references/master.spec.md) — masters, layout linking, background refs, color maps.+- [`references/theme.spec.md`](./references/theme.spec.md) — theme color schemes and hex maps.+- [`references/styles.spec.md`](./references/styles.spec.md) — named text styles and flow through text.+- [`references/rich-text.spec.md`](./references/rich-text.spec.md) — text blocks, ranges, links, list presets.+- [`references/shapes.spec.md`](./references/shapes.spec.md) — shape geometry, fills, strokes, rounded corners, shadows, and z-ordering.+- [`references/connectors.md`](./references/connectors.md) — connected lines, arrows, side anchors, direct connection sites, and rerouting behavior.+- [`references/fill.spec.md`](./references/fill.spec.md) — fill/stroke config shapes and color shorthands, solid, gradient, pattern.+- [`references/images.spec.md`](./references/images.spec.md) — images, cropping, contain/cover framing, prompt placeholders.+- [`references/tables.spec.md`](./references/tables.spec.md) — tables, merges, and cell text.+- [`references/charts.spec.md`](./references/charts.spec.md) — charts, series, axes, legends, mini-chart YAML.+- [`references/comments.md`](./references/comments.md) — comment authors, threads, replies, reactions, and resolving imported review threads.+- [`references/auto-layout.spec.md`](./references/auto-layout.spec.md) — deterministic layout helpers for arranging shapes within frames.+- [`references/speaker-notes.spec.md`](./references/speaker-notes.spec.md) — speaker notes surface and visibility toggles.diff --git a/skills/paper-fig/artifact_tool_docs/api/references/auto-layout.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/auto-layout.spec.mdnew file mode 100644index 0000000..baa538a--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/auto-layout.spec.md@@ -0,0 +1,100 @@+# Auto Layout++`slide.autoLayout(...)` places shapes within a frame using deterministic spacing.+Use `slide.compose(<row>/<column>/<grid>)` for new structured JSX layouts. Use+`slide.autoLayout(...)` when repositioning existing facade shapes, especially+imported or generated shapes.++## Pattern++```ts+slide.autoLayout(shapes, {+ direction,+ frame,+ align,+ horizontalGap,+ verticalGap,+ horizontalPadding,+ verticalPadding,+});+```++## Inputs++- `direction`: horizontal or vertical flow.+- `frame`: `"slide"`, container `Shape`, or explicit `{ left, top, width, height }`.+- `align`: 3x3 group alignment within the frame.+- Gap and padding values use pixels.++## Inline Types++```ts+type AutoLayoutOptions = {+ direction?: "horizontal" | "vertical";+ frame?:+ | "slide"+ | Shape+ | { left: number; top: number; width: number; height: number };+ align?:+ | "center"+ | "topLeft"+ | "topCenter"+ | "topRight"+ | "left"+ | "right"+ | "bottomLeft"+ | "bottomCenter"+ | "bottomRight";+ horizontalGap?: number | "auto";+ verticalGap?: number | "auto";+ horizontalPadding?: number;+ verticalPadding?: number;+};+```++## Shape Prep++```ts+for (const shape of shapes) {+ shape.position = {+ width: shapeWidthPx,+ height: shapeHeightPx,+ };+}++slide.autoLayout(shapes, layoutConfig);+```++## Cookbook++```ts+// Equal KPI row.+const kpiShapes = metrics.map((metric) =>+ slide.shapes.add({+ geometry: "roundRect",+ position: { width: 240, height: 132 },+ fill: "white",+ line: { style: "solid", fill: "slate-200", width: 1 },+ borderRadius: "rounded-xl",+ }),+);++slide.autoLayout(kpiShapes, {+ direction: "horizontal",+ frame: { left: 80, top: 160, width: 1120, height: 160 },+ horizontalGap: "auto",+ align: "center",+});+```++```ts+// Vertical callout stack inside an existing shape frame.+slide.autoLayout(callouts, {+ direction: "vertical",+ frame: frameShape,+ verticalGap: 14,+ horizontalPadding: 24,+ verticalPadding: 24,+ align: "topLeft",+});+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/charts.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/charts.spec.mdnew file mode 100644index 0000000..002f3d0--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/charts.spec.md@@ -0,0 +1,270 @@+# Charts++`slide.charts` creates chart elements with slide placement and chart configuration.++## Resolved From Inspect++```ts+const chart = presentation.resolve("ch/b2c3d4e5");+chart.title = "Updated chart title";+chart.yAxis = { numberFormatCode: "$#,##0M" };+chart.series.getItemAt(0).values = [3.1, 3.7, 4.2, 4.8];+```++Use `presentation.inspect({ kind: "chart", search })` to find the `ch/...`+anchor id. If an imported chart resolves as an image, preserve it as an image or+rebuild it as a native chart intentionally.++## Add Chart++```ts+const chart = slide.charts.add(chartType, {+ position,+ title,+ titleTextStyle,+ categories,+ series,+ hasLegend,+ legend,+ barOptions,+ lineOptions,+ areaOptions,+ pieOptions,+ doughnutOptions,+ treemapOptions,+ mapOptions,+ funnelOptions,+ boxWhiskerOptions,+ histogramOptions,+ view3d,+ scatterOptions,+ xAxis,+ yAxis,+ dataLabels,+ dataTable,+ chartFill,+ chartLine,+ plotAreaFill,+ plotAreaLine,+});+```++Small chart option enums are listed below.++## Chart Inline Types++```ts+type ChartTypeName =+ | "line" | "pie" | "bar" | "doughnut" | "scatter" | "bubble" | "radar"+ | "treemap" | "sunburst" | "map" | "waterfall" | "line3D" | "pie3D"+ | "area3D" | "bar3D" | "funnel" | "histogram" | "boxWhisker" | "stock"+ | "surface3D" | "ofPie" | "surface" | "pareto" | "combo" | "area";++type ChartConfig = {+ position?: { left?: number; top?: number; width?: number; height?: number };+ title?: string;+ titlePlacement?: "none" | "aboveChart" | "centeredOverlay";+ titleTextStyle?: ChartTextStyleConfig;+ categories?: string[];+ series?: ChartSeriesConfig[];+ hasLegend?: boolean;+ legend?: ChartLegendConfig;+ barOptions?: { direction?: "bar" | "column"; grouping?: "clustered" | "stacked" | "percentStacked"; varyColors?: boolean; gapWidth?: number; gapDepth?: number; overlap?: number; bar3dShape?: number };+ lineOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; smooth?: boolean; varyColors?: boolean };+ areaOptions?: { grouping?: "standard" | "stacked" | "percentStacked"; varyColors?: boolean };+ pieOptions?: { firstSliceAngle?: number };+ doughnutOptions?: { holeSize?: number; firstSliceAngle?: number };+ treemapOptions?: { parentLabelLayout?: "none" | "overlapping" | "banner" };+ mapOptions?: { mapArea?: "world" | "auto" | "dataOnly" | "region"; projection?: "mercator" | "auto" | "miller" | "albers"; labelLayout?: "none" | "bestFit" | "showAll"; dataLevel?: "auto" | "county" | "postalCode" | "countryOrRegion" | "stateOrProvince" | "stateCode" | "countyCode" | "countryOrRegionCode"; showUnknown?: boolean; onlyRegionsWithData?: boolean };+ funnelOptions?: { gapWidth?: number };+ boxWhiskerOptions?: { showMeanLine?: boolean; showMeanMarker?: boolean; showNonOutliers?: boolean; showOutliers?: boolean; quartileMethod?: "inclusive" | "exclusive" };+ histogramOptions?: { binWidth?: number; intervalClosed?: number; aggregated?: boolean };+ view3d?: { rotX?: number; rotY?: number; perspective?: number; rightAngleAxes?: boolean };+ scatterOptions?: { style?: "line" | "lineWithMarkers" | "marker" | "smooth" | "smoothWithMarkers"; varyColors?: boolean };+ xAxis?: ChartAxisConfig;+ yAxis?: ChartAxisConfig;+ dataLabels?: ChartDataLabelsConfig;+ dataTable?: ChartDataTableConfig;+ chartFill?: FillConfig;+ chartLine?: LineConfig;+ plotAreaFill?: FillConfig;+ plotAreaLine?: LineConfig;+ displayBlanksAs?: "zero" | "gap" | "span";+ styleIndex?: number;+};+```++## Grouped Edits++```ts+chart.xAxis = axisConfig;+chart.yAxis = axisConfig;+chart.legend = legendConfig;+chart.dataLabels = dataLabelsConfig;+chart.dataTable = dataTableConfig;+```++## Series++```ts+const chart = slide.charts.add(chartType, {+ categories,+ series: [+ {+ name: seriesName,+ categories,+ values,+ xValues,+ categoryPaths,+ fill: fillConfig,+ line: lineConfig,+ marker: markerConfig,+ points,+ dataLabelOverrides,+ trendlines,+ errorBars,+ },+ ],+});+```++## Series Inline Type++```ts+type ChartSeriesConfig = {+ name: string;+ categories?: string[];+ values?: number[];+ xValues?: number[];+ categoryPaths?: string[][];+ bubbleSizes?: number[];+ explosion?: number;+ fill?: FillConfig;+ line?: LineConfig;+ stroke?: LineConfig;+ marker?: { symbol?: "circle" | "diamond" | "dot" | "none" | "plus" | "square" | "star" | "triangle" | "x"; size?: number };+ points?: Array<{ idx: number; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig }>;+ dataLabelOverrides?: Array<{ idx: number; text?: string; position?: string; fill?: FillConfig; line?: LineConfig; stroke?: LineConfig; showValue?: boolean; showSeriesName?: boolean; showCategoryName?: boolean; showPercent?: boolean; textStyle?: ChartTextStyleConfig }>;+ trendlines?: Array<{ type: string; name?: string }>;+ errorBars?: { type?: "standardError" | "percentage" | "standardDeviation" | "none"; value?: number; endStyle?: "cap" | "noCap"; line?: LineConfig };+ valuesFormatCode?: string;+ xValuesFormatCode?: string;+};+```++## Data Label Overrides++```ts+const override = chart.series+ .getItemAt(seriesIndex)+ .dataLabelOverrides.add(dataPointIdx);+override.text = labelText;+override.position = labelPosition;+override.textStyle.fontSize = fontSizePx;+override.textStyle.fill = textFill;+override.fill = fillConfig;+override.stroke = lineConfig;+```++## Chart Areas++```ts+const chart = slide.charts.add(chartType, {+ chartFill,+ plotAreaFill,+});+```++## Axis, Legend, Label Inline Types++```ts+type ChartTextStyleConfig = {+ typeface?: string;+ fontSize?: number;+ fill?: FillConfig;+ bold?: boolean;+ italic?: boolean;+ underline?: string;+ alignment?: "left" | "center" | "right" | "justify";+};++// Chart fonts are independent of surrounding shape-text fonts. Set typeface on+// the title, axes, legend, and data labels to the same selected family. Existing+// axis-title text has its own style: chart.xAxis.title.textStyle.typeface (and+// yAxis.title.textStyle.typeface); do not create a title solely to set a font.++type ChartLegendConfig = {+ position?: "left" | "top" | "topRight" | "right" | "bottom";+ overlay?: boolean;+ fill?: FillConfig;+ line?: LineConfig;+ textStyle?: ChartTextStyleConfig;+};++type ChartDataLabelsConfig = {+ position?: "center" | "inEnd" | "outEnd";+ showValue?: boolean;+ showSeriesName?: boolean;+ showCategoryName?: boolean;+ showPercent?: boolean;+ showLeaderLines?: boolean;+ textStyle?: ChartTextStyleConfig;+ fill?: FillConfig;+ line?: LineConfig;+};++type ChartAxisConfig = {+ visible?: boolean;+ title?: string | { text?: string; textStyle?: ChartTextStyleConfig };+ numberFormatCode?: string;+ min?: number;+ max?: number;+ majorUnit?: number;+ minorUnit?: number;+ position?: "bottom" | "left" | "right" | "top";+ tickLabelPosition?: "nextTo" | "high" | "low" | "none" | string;+ textStyle?: ChartTextStyleConfig;+ line?: LineConfig;+ majorGridlines?: LineConfig | null;+ minorGridlines?: LineConfig | null;+};+```++## Cookbook++Label positions depend on chart family. For stacked or percent-stacked bar/column charts use a compatible `inEnd` or `center`, never `outEnd`; hide labels and outlines on invisible offset series. The non-stacked examples below may use `outEnd`. Preserve source data, and verify the exported file rather than inferring compatibility from the API accepting an enum.++```ts+// Executive horizontal bar chart.+slide.charts.add("bar", {+ position: { left: 96, top: 160, width: 720, height: 360 },+ categories: ["Enterprise", "Mid-market", "SMB"],+ series: [{ name: "ARR", values: [42, 28, 17], fill: "#2563eb" }],+ barOptions: { direction: "bar", grouping: "clustered", gapWidth: 44 },+ hasLegend: false,+ xAxis: { visible: false, majorGridlines: null },+ yAxis: { textStyle: { fill: "#475569", fontSize: 13 }, line: { style: "solid", fill: "#e2e8f0", width: 1 } },+ dataLabels: { showValue: true, position: "outEnd", textStyle: { fill: "#0f172a", fontSize: 13, bold: true } },+});+```++```ts+// Compact trend line with muted grid.+slide.charts.add("line", {+ position: { left: 96, top: 150, width: 880, height: 280 },+ categories: ["Jan", "Feb", "Mar", "Apr"],+ series: [{ name: "Conversion", values: [0.31, 0.34, 0.37, 0.43], line: { style: "solid", fill: "#0f766e", width: 3 } }],+ legend: { position: "bottom", overlay: false },+ yAxis: { numberFormatCode: "0%", majorGridlines: { style: "solid", fill: "#e2e8f0", width: 1 } },+});+```++```ts+// Doughnut chart with labels outside.+slide.charts.add("doughnut", {+ categories: ["Product", "Sales", "Support"],+ series: [{ name: "Share", values: [52, 31, 17] }],+ dataLabels: { showPercent: true, showCategoryName: true, position: "outEnd" },+ legend: { position: "right" },+});+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/comments.md b/skills/paper-fig/artifact_tool_docs/api/references/comments.mdnew file mode 100644index 0000000..4761943--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/comments.md@@ -0,0 +1,103 @@+# Comments++Presentation comments use people, threads, replies, reactions, and thread state.++## Current Author++```ts+presentation.comments.setSelf({+ displayName,+ initials,+ email,+});+```++## Person Inline Type++```ts+type PersonConfig = {+ id?: string;+ displayName: string;+ initials?: string;+ email?: string;+ avatarUrl?: string;+ userId?: string;+ providerId?: string;+};+```++## Element Thread++```ts+const thread = presentation.comments.addThread({ element }, bodyText, {+ position,+});++const reply = thread.addReply(replyText);+reply.toggleReaction(reactionText);+thread.resolve();+thread.reopen();+```++## Thread Inline Types++```ts+type CommentTarget =+ | { slide: Slide }+ | { element: Shape | ImageElement | Table | ChartElement }+ | { textRange: TextRange }+ | { textMatch: { element: Shape; query: string; occurrence?: number } };++type ThreadAddOptions = {+ author?: Person | PersonConfig | { id: string };+ createdAt?: string;+ position?: { x: number; y: number; unit?: "px" | "emu" };+};+```++## Slide And Text Threads++```ts+presentation.comments.addThread({ slide }, bodyText, { position });++presentation.comments.addThread(+ { textMatch: { element, query, occurrence } },+ bodyText,+);+```++## Cookbook++```ts+// Add a review comment to exact text.+presentation.comments.setSelf({+ displayName: "Presentation Reviewer",+ initials: "PR",+ email: "[email protected]",+});++const thread = presentation.comments.addThread(+ { textMatch: { element: titleShape, query: "Q4", occurrence: 0 } },+ "Check whether this should be FY2026 Q1.",+);+thread.addReply("Leaving this unresolved for owner review.");+```++```ts+// Resolve an imported thread after an edit.+const self = presentation.comments.setSelf({+ displayName: "Presentation Editor",+ initials: "PE",+ email: "[email protected]",+});++const thread = presentation.resolve(threadAnchorId);+thread.addReply("Updated the chart title and source note.", { author: self });+thread.resolve(self);++const verified = await presentation.inspect({+ kind: "thread",+ target: { id: threadAnchorId, beforeLines: 0, afterLines: 2 },+ maxChars: 2000,+});+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/connectors.md b/skills/paper-fig/artifact_tool_docs/api/references/connectors.mdnew file mode 100644index 0000000..fc00dcb--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/connectors.md@@ -0,0 +1,206 @@+# Connectors++`slide.shapes.connect` creates connector lines that stay attached to slide+shapes. Use it for arrows, flow links, callouts, dependency lines, and other+relationships between positioned shapes.++Use direct `geometry: "connector"` creation only when you need exact connection+site indexes.++## Connect Shapes++```ts+const connector = slide.shapes.connect(sourceShape, targetShape, {+ kind: "elbow",+ fromSide: "right",+ toSide: "left",+ line: { style: "solid", fill: "slate-500", width: 2 },+ head: { type: "arrow", width: "med", length: "med" },+});+```++Endpoints accept shape facades or shape ids. `fromSide` and `toSide` accept+`"top"`, `"left"`, `"bottom"`, or `"right"` and resolve to the nearest+connection site for that shape geometry. When you omit side and index options,+the API chooses a connection pair from the relative shape positions.++`kind` defaults to `"elbow"` for `slide.shapes.connect(...)`.++## Connect Inline Types++```ts+type ConnectorSide = "top" | "left" | "bottom" | "right";++type ShapeConnectOptions = {+ kind?:+ | "straight"+ | "elbow"+ | "elbow2"+ | "elbow3"+ | "elbow4"+ | "elbow5"+ | "curved";+ fromSide?: ConnectorSide;+ toSide?: ConnectorSide;+ fromIdx?: number;+ toIdx?: number;+ line?: LineConfig;+ head?: LineEndConfig;+ tail?: LineEndConfig;+ cap?: "flat" | "round" | "square";+ join?: "round" | "bevel" | "miter";+};++type LineEndConfig = {+ type?: "none" | "triangle" | "stealth" | "diamond" | "oval" | "arrow";+ width?: "sm" | "med" | "lg";+ length?: "sm" | "med" | "lg";+};+```++## Anchor Choice++Use side anchors for readable authoring:++```ts+slide.shapes.connect(sourceShape, targetShape, {+ fromSide: "bottom",+ toSide: "top",+ kind: "elbow",+ line: { style: "dashed", fill: "accent1", width: 2 },+});+```++Use explicit connection site indexes when you need an exact preset-geometry site:++```ts+const fromIdx = slide.shapes.getConnectionSiteIndex(sourceShape, "right");+const toIdx = slide.shapes.getConnectionSiteIndex(targetShape, "left");++slide.shapes.connect(sourceShape.id, targetShape.id, {+ fromIdx,+ toIdx,+ kind: "straight",+ line: { style: "solid", fill: "slate-700", width: 2 },+});+```++Connection site indexes are PowerPoint preset geometry connection points. Side+anchors map to the closest useful preset site for rectangles, ellipses, and+other shapes.++## Direct Connector Shape++```ts+const connector = slide.shapes.add({+ geometry: "connector",+ kind: "curved",+ from: sourceShape,+ fromIdx: 3,+ to: targetShape,+ toIdx: 1,+ line: { style: "solid", fill: "accent1", width: 2 },+ tail: { type: "triangle", width: "med", length: "med" },+});+```++Direct connector creation requires `from`, `to`, `fromIdx`, and `toIdx`. Prefer+`slide.shapes.connect(...)` unless exact connection site indexes are already+known.++## Direct Connector Inline Type++```ts+type ConnectorConfig = {+ geometry: "connector";+ from: Shape | string;+ fromIdx: number;+ to: Shape | string;+ toIdx: number;+ kind?:+ | "straight"+ | "elbow"+ | "elbow2"+ | "elbow3"+ | "elbow4"+ | "elbow5"+ | "curved";+ line?: LineConfig;+ head?: LineEndConfig;+ tail?: LineEndConfig;+ cap?: "flat" | "round" | "square";+ join?: "round" | "bevel" | "miter";+};+```++Connectors support line styling and line ends, but not `borderRadius` or+`shadow`.++## Edit Existing Connectors++```ts+const connector = presentation.resolve(connectorAnchorId);+const nextFromIdx = slide.shapes.getConnectionSiteIndex(+ nextSourceShape,+ "right",+);+const nextToIdx = slide.shapes.getConnectionSiteIndex(nextTargetShape, "left");++connector.setConnectorFrom(nextSourceShape, nextFromIdx);+connector.setConnectorTo(nextTargetShape.id, nextToIdx);+connector.line = { style: "solid", fill: "slate-800", width: 2 };+connector.bringToFront();+```++Use `presentation.inspect({ kind: "shape", search })` to find connector anchor+ids. Connector facades expose `connector`, `connectorLineStyle`,+`connectorHead`, and `connectorTail` for readback.++## Routing And Ordering++New connectors are sent behind shapes by default so boxes and labels remain+readable. Call `connector.bringToFront()` when the connector should sit above+other elements.++Connected routes update when an endpoint shape moves or previews a move. Render+and export paths recompute the connector bounds and route from the current+endpoint geometry.++## Cookbook++```ts+// Arrow from one card to another.+slide.shapes.connect(sourceCard, targetCard, {+ kind: "elbow",+ fromSide: "right",+ toSide: "left",+ line: { style: "solid", fill: "slate-500", width: 2 },+ head: { type: "arrow", width: "med", length: "med" },+});+```++```ts+// Bidirectional relationship line.+slide.shapes.connect(leftShape, rightShape, {+ kind: "straight",+ fromSide: "right",+ toSide: "left",+ line: { style: "dashed", fill: "accent2", width: 2 },+ head: { type: "arrow", width: "sm", length: "sm" },+ tail: { type: "arrow", width: "sm", length: "sm" },+});+```++```ts+// Curved connector with explicit preset connection sites.+slide.shapes.add({+ geometry: "connector",+ kind: "curved",+ from: sourceShape,+ fromIdx: slide.shapes.getConnectionSiteIndex(sourceShape, "bottom"),+ to: targetShape,+ toIdx: slide.shapes.getConnectionSiteIndex(targetShape, "top"),+ line: { style: "solid", fill: "accent1", width: 2 },+ tail: { type: "triangle", width: "med", length: "med" },+});+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/cookbook/imported-deck.md b/skills/paper-fig/artifact_tool_docs/api/references/cookbook/imported-deck.mdnew file mode 100644index 0000000..2d98b4b--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/cookbook/imported-deck.md@@ -0,0 +1,181 @@+# Imported Deck Cookbook++Use these recipes when editing an existing presentation. The goal is targeted,+type-aware edits with a preview and a small verification snapshot.++For imported decks, render the affected slide before and after focused edits,+export layout JSON before and after when object placement matters, and use a+deck montage before/after when a change may affect multiple slides.++## Edit Loop++```ts+const before = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",+ search: "Revenue",+ maxChars: 8000,+});++// Pick an exact anchor id from `before`; use inspect ids instead of slide indexes.+const target = presentation.resolve(anchorId);++// slideAnchorId is the `sl/...` id from inspect for the affected slide.+const slide = presentation.resolve(slideAnchorId);+const previewBefore = await slide.export({ format: "png", scale: 2 });+const layoutBefore = await slide.export({ format: "layout" });+const montageBefore = await presentation.export({+ format: "webp",+ montage: true,+ scale: 1,+});++target.text.replace("Revenue", "Revenue outlook");++const previewAfter = await slide.export({ format: "png", scale: 2 });+const layoutAfter = await slide.export({ format: "layout" });+const montageAfter = await presentation.export({+ format: "webp",+ montage: true,+ scale: 1,+});++const after = await presentation.inspect({+ target: { id: anchorId, beforeLines: 2, afterLines: 2 },+ kind: "textbox,shape",+ maxChars: 2000,+});+```++## Placeholder Edit++```ts+const layoutSnapshot = await presentation.inspect({+ kind: "slide,layout,textbox,shape",+ search: "Click to add title",+ maxChars: 6000,+});++// slideAnchorId is the `sl/...` id from inspect for this slide.+const slide = presentation.resolve(slideAnchorId);+const title = slide.placeholders.getItem("title");+title.text = "Updated executive summary";+```++Edit a slide placeholder for a local content change. Edit a layout or master+only when the intended change is global.+Inspect records use 1-based `slide` numbers for display; `slides.getItem(index)`+is 0-based. Prefer resolving the `sl/...` anchor from inspect.++## Master/Layout Blast Radius++```ts+// layoutId comes from inspect/layout export metadata; use it for search and comparison.+const affected = await presentation.inspect({+ kind: "slide,layout",+ search: layoutId,+ maxChars: 6000,+});+```++Inspect affected layouts and slides before changing a master, layout, theme+color, or placeholder geometry. Use layout ids for comparison/search, then+resolve affected slides through their `sl/...` ids before editing. These edits+can update many slides.++## Preserve Imported Image Placement++```ts+const image = presentation.resolve(imageAnchorId);+const oldFrame = image.frame;+const oldCrop = image.crop;+const oldFit = image.fit;+const oldAlt = image.alt;+const oldPrompt = image.prompt;+const oldGeometry = image.geometry;+const oldBorderRadius = image.borderRadius;+const oldRotation = image.rotation;+const oldFlipHorizontal = image.flipHorizontal;+const oldFlipVertical = image.flipVertical;+const oldLockAspectRatio = image.lockAspectRatio;++image.replace({+ blob: replacementBytes,+ contentType: "image/png",+ alt: oldAlt ?? "Updated product screenshot",+ ...(oldFit ? { fit: oldFit } : {}),+ ...(oldPrompt ? { prompt: oldPrompt } : {}),+});+image.frame = oldFrame;+image.crop = oldCrop;+image.geometry = oldGeometry;+image.borderRadius = oldBorderRadius;+image.rotation = oldRotation;+image.flipHorizontal = oldFlipHorizontal;+image.flipVertical = oldFlipVertical;+image.lockAspectRatio = oldLockAspectRatio;+```++Render the slide after replacement and verify subject crop, aspect ratio,+rounded mask, and legibility. Preserve placement-affecting properties unless the+edit explicitly changes them. Concrete source replacements produce concrete+images; pass `prompt` when it should remain available as regeneration metadata.++## Existing Table And Chart Edits++```ts+const table = presentation.resolve(tableAnchorId);+table.cells.set(1, 2, "$4.2M");+table.getCell(1, 2).text.style = "Body Small";++const chart = presentation.resolve(chartAnchorId);+chart.xAxis = { title: "Quarter" };+chart.yAxis = { numberFormatCode: "$#,##0M" };+chart.series.getItemAt(0).values = [3.1, 3.7, 4.2, 4.8];++await presentation.inspect({+ kind: "table,chart",+ target: { id: chartAnchorId, beforeLines: 3, afterLines: 3 },+ maxChars: 3000,+});+```++If an imported chart or table resolves as an image, preserve it as an image or+rebuild it as a native chart/table intentionally.++## Comments And Speaker Notes++```ts+const review = await presentation.inspect({+ kind: "thread,notes,slide,textbox",+ search: "TODO",+ maxChars: 8000,+});++const self = presentation.comments.setSelf({+ displayName: "Presentation Editor",+ initials: "PE",+ email: "[email protected]",+});++const thread = presentation.resolve(commentThreadAnchorId);+thread.addReply("Addressed in this revision.", { author: self });+thread.resolve(self);++const notes = presentation.resolve(notesAnchorId);+const existing = notes.text.trim();+notes.setText([+ existing,+ "Opening: summarize the revised revenue outlook.",+ "Call out risk on enterprise timing.",+].filter(Boolean).join("\n"));+notes.setVisible(true);++const verified = await presentation.inspect({+ kind: "thread,notes",+ target: { id: slideAnchorId, beforeLines: 1, afterLines: 4 },+ maxChars: 3000,+});+```++Keep unrelated threads and speaker notes intact unless the task explicitly asks+to clear them.diff --git a/skills/paper-fig/artifact_tool_docs/api/references/cookbook/layout.md b/skills/paper-fig/artifact_tool_docs/api/references/cookbook/layout.mdnew file mode 100644index 0000000..d0de176--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/cookbook/layout.md@@ -0,0 +1,419 @@+# Presentation Layout Cookbook++First-principles recipes for arranging editable presentation JSX. These are+layout mechanics, not deck archetypes.++Examples start after `presentation` and `slide` exist. Prefer string sizing+(`"fill"`, `"hug"`) and local track values over helper imports.++Use `1280 x 720` as the default canvas unless the task or source deck requires+another size:++```ts+const SLIDE_W = 1280;+const SLIDE_H = 720;+const PAGE = { left: 72, top: 64, width: 1136, height: 592 };+```++## Choose The Primitive++| Need | Use |+| --- | --- |+| Horizontal flow | `row` |+| Vertical flow | `column` |+| Column/row spans | `grid` |+| Overlays or background plates | `layers` |+| Surface plus child content | `box` |+| Fixed placement on a slide | `slide.compose(node, { frame })` or facade `position` |++Use `frame` for the outer composed region. Inside the region, use `row`,+`column`, `grid`, and `layers` so content stays resizable and inspectable. Use+`layers` plus image `geometry`/`borderRadius` for overlays, scrims, and masked+image compositions inside a region.++## Sizing Vocabulary++```tsx+<box width="fill" height="fill" /> // claim available space+<box width="hug" height="hug" /> // fit its children+<box width={320} height={180} /> // fixed pixels+```++Equal siblings fill equally:++```tsx+<row width="fill" height={160} gap={24} align="stretch">+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+</row>+```++One fixed sibling plus one flexible sibling:++```tsx+<row width="fill" height="fill" gap={32} align="stretch">+ <column width={360} height="fill" gap={16}>+ <paragraph className="text-slate-950 text-4xl font-bold">Fixed rail</paragraph>+ <paragraph className="text-slate-600 text-lg">This column stays 360px wide.</paragraph>+ </column>+ <box width="fill" height="fill" className="bg-slate-100 rounded-2xl" />+</row>+```++## Padding And Gutters++Use object padding for asymmetric page gutters. Use numeric padding for all+sides.++Use an 8px spacing scale unless matching a source deck: common gaps are `16`,+`24`, `28`, and `32`. Common page gutters use `PAGE`; pass `baseUnit: 8` to+`slide.compose` when examples rely on this scale.++```tsx+<column+ width="fill"+ height="fill"+ padding={{ top: 64, right: 80, bottom: 56, left: 80 }}+ gap={28}+>+ <paragraph className="text-slate-950 text-5xl font-bold">Page title</paragraph>+ <box width="fill" height="fill" className="bg-white rounded-xl" />+</column>+```++```tsx+<box width="fill" height="hug" padding={{ x: 28, y: 18 }} className="bg-sky-50 rounded-xl">+ <paragraph className="text-sky-950 text-xl font-bold">Compact padded box</paragraph>+</box>+```++## Rows++`row` lays out children left to right. `justify` distributes along the+horizontal axis. `align` controls vertical alignment.++```tsx+<row width="fill" height={72} align="center" justify="between">+ <paragraph className="text-slate-950 text-2xl font-bold">Left</paragraph>+ <paragraph className="text-slate-500 text-sm">Right</paragraph>+</row>+```++Center a child:++```tsx+<row width="fill" height={220} align="center" justify="center">+ <box width={360} height={120} className="bg-white rounded-xl shadow-sm" />+</row>+```++Stretch all children to the row height:++```tsx+<row width="fill" height={240} gap={20} align="stretch">+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+</row>+```++## Columns++`column` lays out children top to bottom. `justify` distributes along the+vertical axis. `align` controls horizontal alignment.++```tsx+<column width="fill" height="fill" justify="between" gap={24}>+ <paragraph className="text-slate-950 text-4xl font-bold">Top block</paragraph>+ <paragraph className="text-slate-600 text-lg">Bottom block</paragraph>+</column>+```++Metadata row, content region, and closing rule:++```tsx+<column width="fill" height="fill" gap={24}>+ <row width="fill" height={72} align="center" justify="between">+ <paragraph className="text-slate-500 text-sm font-bold">HEADER</paragraph>+ <paragraph className="text-slate-400 text-sm">Source</paragraph>+ </row>+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <rule stroke="slate-200" weight={1} />+</column>+```++## Three Columns++Use a `row` when all columns are equal or only one side is fixed.++```tsx+slide.compose(+ <row name="three-column-layout" width="fill" height="fill" gap={24} align="stretch">+ <column name="column-a" width="fill" height="fill" gap={12}>+ <paragraph className="text-slate-950 text-2xl font-bold">Column A</paragraph>+ <paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>+ </column>+ <column name="column-b" width="fill" height="fill" gap={12}>+ <paragraph className="text-slate-950 text-2xl font-bold">Column B</paragraph>+ <paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>+ </column>+ <column name="column-c" width="fill" height="fill" gap={12}>+ <paragraph className="text-slate-950 text-2xl font-bold">Column C</paragraph>+ <paragraph className="text-slate-600 text-base">Editable body copy.</paragraph>+ </column>+ </row>,+ { frame: PAGE, baseUnit: 8 },+);+```++Use fixed rails when the center should absorb resize:++```tsx+<row width="fill" height="fill" gap={24} align="stretch">+ <box width={240} height="fill" className="bg-slate-50 rounded-xl" />+ <box width="fill" height="fill" className="bg-white rounded-xl" />+ <box width={240} height="fill" className="bg-slate-50 rounded-xl" />+</row>+```++## Twelve-Column Grid++Use `grid` when child spans matter. Keep `fr` and fixed track objects local and+obvious; use the literal `"auto"` for auto tracks:++```tsx+const GRID_12 = Array.from(+ { length: 12 },+ () => ({ mode: "fr", value: 1 }) as const,+);+```++Use a 12-column grid when spans communicate structure. Spans in a row usually+add to 12, such as `4/4/4`, `3/6/3`, or `4/8`. Put vertical content inside+`column` children and surfaces inside `box` children. Use a simple `row` when+every column is equal and no span semantics are needed.++Full-width heading plus three equal columns:++```tsx+<grid+ width="fill"+ height="fill"+ columns={GRID_12}+ rows={["auto", { mode: "fr", value: 1 }]}+ columnGap={24}+ rowGap={28}+>+ <paragraph columnSpan={12} className="text-slate-950 text-5xl font-bold">+ Full-width heading+ </paragraph>+ <box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box columnSpan={4} width="fill" height="fill" className="bg-slate-50 rounded-xl" />+</grid>+```++Four/eight split:++```tsx+<grid width="fill" height="fill" columns={GRID_12} columnGap={28}>+ <column columnSpan={4} width="fill" height="fill" gap={16}>+ <paragraph className="text-slate-950 text-4xl font-bold">Left span</paragraph>+ <paragraph className="text-slate-600 text-lg">Uses 4 of 12 columns.</paragraph>+ </column>+ <box columnSpan={8} width="fill" height="fill" className="bg-sky-50 rounded-2xl" />+</grid>+```++Three/six/three split:++```tsx+<grid width="fill" height="fill" columns={GRID_12} columnGap={20}>+ <box columnSpan={3} width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box columnSpan={6} width="fill" height="fill" className="bg-white rounded-xl shadow-sm" />+ <box columnSpan={3} width="fill" height="fill" className="bg-slate-50 rounded-xl" />+</grid>+```++Rows plus row spans:++```tsx+<grid+ width="fill"+ height="fill"+ columns={GRID_12}+ rows={["auto", { mode: "fr", value: 1 }, { mode: "fr", value: 1 }]}+ columnGap={24}+ rowGap={24}+>+ <paragraph columnSpan={12} className="text-slate-950 text-4xl font-bold">+ Heading+ </paragraph>+ <box columnSpan={8} rowSpan={2} width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box columnSpan={4} width="fill" height="fill" className="bg-sky-50 rounded-xl" />+ <box columnSpan={4} width="fill" height="fill" className="bg-emerald-50 rounded-xl" />+</grid>+```++Mixed fixed and flexible tracks:++```tsx+<grid+ width="fill"+ height="fill"+ columns={[+ { mode: "fixed", value: 280 },+ { mode: "fr", value: 1 },+ { mode: "fixed", value: 220 },+ ]}+ columnGap={24}+>+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+ <box width="fill" height="fill" className="bg-white rounded-xl shadow-sm" />+ <box width="fill" height="fill" className="bg-slate-50 rounded-xl" />+</grid>+```++## Grid Alignment++Use `alignItems` and `justifyItems` for grid child alignment. If one child+needs different alignment, wrap it in a `row`, `column`, or `box`.++| Node | Main axis | Cross axis | Distribution prop | Cross-axis prop | Defaults |+| --- | --- | --- | --- | --- | --- |+| `row` | horizontal | vertical | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `start` / `start` |+| `column` | vertical | horizontal | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `start` / `start` |+| `grid` | tracks | cells | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | `stretch` / `stretch` |+| `layers` | shared frame | shared frame | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | `stretch` / `stretch` |++```tsx+<grid+ width="fill"+ height={260}+ columns={[{ mode: "fr", value: 1 }, { mode: "fr", value: 1 }]}+ rows={[{ mode: "fr", value: 1 }]}+ columnGap={24}+ alignItems="center"+ justifyItems="stretch"+>+ <box height={120} className="bg-slate-50 rounded-xl" />+ <box height="fill" className="bg-sky-50 rounded-xl" />+</grid>+```++## Layers++`layers` gives every child the same parent frame. Put visual backgrounds first,+then overlays, then editable text.++```tsx+<layers width="fill" height="fill">+ <image+ blob={backgroundBytes}+ contentType="image/jpeg"+ fit="cover"+ alt="Background"+ width="fill"+ height="fill"+ />+ <shape geometry="rect" width="fill" height="fill" fill="black/45" />+ <column width={620} height="fill" padding={64} justify="end" gap={18}>+ <paragraph className="text-white text-5xl font-bold leading-tight">+ Editable headline+ </paragraph>+ <paragraph className="text-white/80 text-xl leading-relaxed">+ Editable supporting copy.+ </paragraph>+ </column>+</layers>+```++## Image Masks++Use image `geometry` for real clipping. Use `crop` plus `fit="cover"` when the+subject should fill the mask.++Quick reference:++| Need | Use |+| --- | --- |+| Preserve the full image | `fit="contain"` |+| Fill the frame and allow crop | `fit="cover"` |+| Clip to a shape | `geometry="ellipse"` or `geometry="roundRect"` |+| Rounded rectangle mask | `borderRadius="rounded-2xl"` |+| Manual crop | `crop={{ left, top, right, bottom }}` with normalized `0..1` insets |++`crop` values are fractions removed from each source-image edge and are clamped.+Overlays do not clip images; use image `geometry` or `borderRadius` for masks.++```tsx+<image+ blob={portraitBytes}+ contentType="image/jpeg"+ alt="Portrait"+ geometry="ellipse"+ fit="cover"+ crop={{ left: 0.1, top: 0, right: 0.08, bottom: 0 }}+ width={240}+ height={240}+/>+```++Rounded rectangle image:++```tsx+<image+ blob={photoBytes}+ contentType="image/jpeg"+ alt="Photo"+ fit="cover"+ width="fill"+ height={320}+ borderRadius="rounded-2xl"+/>+```++## Flow Versus Absolute Placement++Use flow for related content:++```tsx+slide.compose(+ <column width="fill" height="fill" gap={20}>+ <paragraph className="text-slate-950 text-4xl font-bold">Title</paragraph>+ <row width="fill" height="fill" gap={24} align="stretch">+ <box width="fill" className="bg-slate-50 rounded-xl" />+ <box width="fill" className="bg-slate-50 rounded-xl" />+ </row>+ </column>,+ { frame: PAGE, baseUnit: 8 },+);+```++Use absolute positions for elements that must land at exact slide coordinates:++```ts+slide.shapes.add({+ geometry: "rect",+ name: "fixed-accent-bar",+ position: { left: 0, top: 0, width: 12, height: 720 },+ fill: "accent1",+ line: { style: "solid", fill: "none", width: 0 },+});+```++## Verify Layout++Inspect the layout tree when spans or wrapping matter:++```ts+const layout = await slide.export({ format: "layout" });+const png = await slide.export({ format: "png", scale: 1 });+const snapshot = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart",+ maxChars: 8000,+});+```++Check the rendered PNG for clipping, overlap, broken image crops, and text+that should have stayed editable.diff --git a/skills/paper-fig/artifact_tool_docs/api/references/fill.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/fill.spec.mdnew file mode 100644index 0000000..219583c--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/fill.spec.md@@ -0,0 +1,186 @@+# Fill And Line Configs++Fill configs style shapes, chart regions, table cells, slide backgrounds, lines,+and text fills. Text outlines use `LineConfig`, so their `fill`/`color` fields+accept the same fill forms.++## Fill Forms++```ts+shape.fill = fillConfig;+shape.line = lineConfig;+```++Supported fill forms:++- Theme, hex, RGB/RGBA, Tailwind-like color, and transformed color strings.+- `"none"` and `"transparent"`.+- Gradient strings such as `linear(...)` and `radial(...)`.+- `{ type: "none" }`.+- `{ type: "solid", color, pattern }`.+- `{ type: "gradient", gradientKind, angleDeg, stops }`.+- `{ type: "image", imageReference, srcRect, fillRect, stretchFillRect }`.++## String Fill Shortcuts++Use string fills for compact JSX and facade setters:++```tsx+<shape geometry="rect" fill="none" line={{ style: "solid", fill: "slate-300", width: 1 }} />+<box fill="black/45" />+<box fill="transparent" />+<box fill="accent1+18/90" />+<box fill="linear(135deg, #ffffff 0%, sky-100 58%, #ffffff/0 100%)" />+<shape geometry="ellipse" fill="radial(white/80 0%, emerald-200/45 48%, emerald-700/0 100%)" />+```++Use `fill="none"` when the object should have no fill. Use+`fill="transparent"` when the object should keep an editable transparent solid+fill.++`+` lightens theme/RGB colors, `-` darkens, and `/` sets opacity. Tailwind-like+color tokens, theme aliases, gradients, shadows, and text style strings are+summarized in `tokens.md`.++## Fill Inline Types++```ts+type ThemeColorName =+ | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"+ | "bg1" | "bg2" | "tx1" | "tx2" | "dk1" | "lt1" | "dk2" | "lt2"+ | "hlink" | "folHlink";++type ColorConfig =+ | string+ | { type: "rgb"; value: string; transform?: ColorTransform }+ | { type: "theme"; value: ThemeColorName; transform?: ColorTransform };++type ColorTransform = {+ opacity?: number; // 0..1 or 0..100+ lighten?: number; // 0..1 or 0..100+ darken?: number; // 0..1 or 0..100+};++type FillConfig =+ | string+ | { type: "none" }+ | { type: "solid"; color: ColorConfig; pattern?: PatternConfig }+ | {+ type: "gradient";+ stops: Array<{ offset: number; color: ColorConfig }>; // offset 0..100000+ angleDeg?: number;+ gradientKind?: "linear" | "path";+ }+ | {+ type: "image";+ imageReference: { id: string };+ alphaModFix?: number;+ stretchFillRect?: { l?: number; t?: number; r?: number; b?: number };+ fillRect?: { l?: number; t?: number; r?: number; b?: number };+ srcRect?: { l?: number; t?: number; r?: number; b?: number };+ };+```++## Gradient++```ts+const fillConfig = {+ type: "gradient",+ gradientKind,+ angleDeg,+ stops: [+ { offset: startOffset, color: startColor },+ { offset: endOffset, color: endColor },+ ],+};+```++Gradient offsets use `0` to `100000`.++## Pattern Fills++Patterns are available through object fill configs:++```ts+shape.fill = {+ type: "solid",+ color: "white",+ pattern: { type: "diagonalCross", color: "slate-300/70" },+};+```++Common compact pattern names:++```text+percent10, percent20, lightHorizontal, lightVertical, smallGrid, dotGrid,+diagonalCross, narrowVertical, wave, smallCheck+```++Supported pattern names:++```text+none, solid, mediumGray, darkGray, lightGray, darkHorizontal, darkVertical,+darkDown, darkUp, darkGrid, darkTrellis, lightHorizontal, lightVertical,+lightDown, lightUp, lightGrid, lightTrellis, gray125, gray0625, percent5,+percent10, percent20, percent25, percent30, percent40, percent50, percent60,+percent70, percent75, percent80, percent90, horizontal, vertical,+narrowHorizontal, narrowVertical, dashedHorizontal, dashedVertical, cross,+largeGrid, smallGrid, dotGrid, downwardDiagonal, upwardDiagonal,+wideDownwardDiagonal, wideUpwardDiagonal, dashedDownwardDiagonal,+dashedUpwardDiagonal, diagonalCross, smallCheck, largeCheck, smallConfetti,+largeConfetti, horizontalBrick, diagonalBrick, solidDiamond, openDiamond,+dottedDiamond, plaid, sphere, weave, divot, shingle, wave, trellis, zigZag+```++## Line++```ts+const lineConfig = {+ style: lineStyle,+ fill: lineFill,+ width: lineWidthPx,+};+```++## Line Inline Type++```ts+type LineConfig = {+ style: "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot" | string;+ fill?: FillConfig;+ width?: number;+ color?: FillConfig; // alias for fill+ weight?: number; // alias for width+};+```++## Cookbook++```ts+// Linear background wash.+slide.background.fill = "linear(0deg, #020617 0%, #2563eb 100%)";+```++```ts+// Soft radial spotlight behind a chart.+chart.plotAreaFill = "radial(#dbeafe/90 0%, #ffffff/0 100%)";+```++```ts+// Exact gradient object.+shape.fill = {+ type: "gradient",+ gradientKind: "linear",+ angleDeg: 35,+ stops: [+ { offset: 0, color: "#ffffff" },+ { offset: 100000, color: "sky-100" },+ ],+};+```++```ts+// Hairline rule and muted border.+shape.line = { style: "solid", fill: "slate-200", width: 1 };+ruleShape.line = { style: "dashed", fill: "#94a3b8", width: 1 };+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/help.md b/skills/paper-fig/artifact_tool_docs/api/references/help.mdnew file mode 100644index 0000000..db0c40b--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/help.md@@ -0,0 +1,223 @@+# Help++Use `presentation.help(...)` to search the presentation JS API and template+catalog. Help emits bounded NDJSON records for quick lookup during create, edit,+and review workflows.++## Query++```ts+const result = presentation.help(query, {+ search,+ include,+ maxChars,+});+console.log(result.ndjson);+```++Example output for `query = "*"` with `include = ["index", "examples"]`:++```text+{"kind":"api","name":"presentation.help","summary":"Search the presentation JS API and template catalog.","tags":["help","docs","examples","presentation.help"],"examples":[{"summary":"Find shape editing APIs","code":"const result = presentation.help('*', {\n search: 'slide.shapes.delete|shape.delete|slide.shapes.add|deleteAll',\n include: ['index', 'examples', 'notes'],\n maxChars: 12000,\n});\nconsole.log(result.ndjson);"}]}+{"kind":"api","name":"slide.shapes.add","summary":"Add a preset/custom/connector shape to a slide.","tags":["shape","shapes.add","rectangle","ellipse","connector","slide.shapes.add"],"examples":[{"summary":"Create a styled rectangle","code":"const shape = slide.shapes.add({\n geometry: 'roundRect',\n position: { left: 72, top: 96, width: 320, height: 120 },\n fill: { type: 'solid', color: 'accent1' },\n line: { style: 'solid', fill: 'accent2', width: 2 },\n});\nshape.text = 'Launch plan';"}]}+{"kind":"template","name":"agenda","summary":"Agenda slide with a title and list body.","examples":[{"summary":"Apply the agenda template","code":"presentation.apply(presentation.template('agenda'));"}]}+```++Use API records to find facade names and examples; use template records with+`presentation.template(name)`.++Common queries:++```text+*, shape*, slide.shapes.add, chart xAxis, template*+```++Query behavior:++```text+* lists all matching API and template records+shape* uses glob matching+slide.shapes.add matches the exact dotted API name+chart xAxis matches entries containing either word token+template* lists template records only+```++Use `search` as a case-insensitive regular expression over the JSON lines after+the primary query has selected records:++```ts+const focused = presentation.help("*", {+ search:+ "slide\\.shapes\\.delete|shape\\.delete|slide\\.shapes\\.add|deleteAll",+ include: ["index", "examples", "notes"],+ maxChars: 12000,+});+console.log(focused.ndjson);+```++## Include++Default output includes index fields such as:++```text+kind, name, summary, tags+```++Useful include tokens:++```text+index, examples, notes+```++`include` accepts either an array or a comma-separated string:++```ts+const shapeExamples = presentation.help("slide.shapes.add", {+ include: ["examples", "notes"],+});++const templateExamples = presentation.help("template*", {+ include: "index,examples",+});+```++## Inline Type++```ts+type PresentationHelpOptions = {+ include?: string[] | string;+ search?: string;+ maxChars?: number;+};++type PresentationHelpResult = {+ ndjson: string;+ truncated: boolean;+ metadata: {+ revision: string;+ query: string;+ include: {+ requested?: string[] | string;+ tokens: string[];+ };+ search?: string;+ notices?: string[];+ };+};+```++## Record Kinds++API records describe public JS facades and methods:++```text+{"kind":"api","name":"slide.shapes.add","summary":"Add a preset/custom/connector shape to a slide.","tags":["shape","shapes.add","rectangle","ellipse","connector","slide.shapes.add"]}+{"kind":"api","name":"shape.delete","summary":"Delete this shape from its slide.","tags":["shape","delete shape","remove shape","shape.delete"]}+```++When examples are included, records focus on usage snippets:++```text+{"kind":"api","name":"slide.shapes.add","examples":[{"summary":"Create a styled rectangle","code":"const shape = slide.shapes.add({\n geometry: 'roundRect',\n position: { left: 72, top: 96, width: 320, height: 120 },\n fill: { type: 'solid', color: 'accent1' },\n line: { style: 'solid', fill: 'accent2', width: 2 },\n});\nshape.text = 'Launch plan';"}],"notes":["Preset geometry values include rect, roundRect, ellipse, triangle, rightArrow, and many other PowerPoint shape names."]}+```++Template records describe named template patches for+`presentation.template(name)`:++```text+{"kind":"template","name":"title-slide","summary":"Title + subtitle slide with centered text boxes."}+{"kind":"template","name":"two-up","summary":"Two-column slide with left/right content boxes."}+{"kind":"template","name":"agenda","summary":"Agenda slide with a title and list body."}+```++If output exceeds `maxChars`, the final line is a notice record and+`result.truncated` is `true`:++```text+{"kind":"notice","message":"Truncated: omitted 93 lines. Increase maxChars or narrow query."}+```++## Create/Edit Loop++```ts+// Find the public API surface for the edit.+const shapeHelp = presentation.help("shape*", {+ include: ["index", "examples", "notes"],+ maxChars: 8000,+});++// Build with the documented JS facade.+const slide = presentation.slides.add();+const shape = slide.shapes.add({+ geometry: "roundRect",+ position: { left: 72, top: 96, width: 320, height: 120 },+ fill: { type: "solid", color: "accent1" },+});+shape.text = "Launch plan";++// Inspect the live deck after editing.+const snapshot = await presentation.inspect({+ kind: "slide,textbox,shape",+ maxChars: 4000,+});+```++## Imported Templates++```ts+const templates = presentation.help("template*", {+ include: ["index", "examples"],+ maxChars: 4000,+});++presentation.apply(presentation.template("agenda"));+```++Use template help to discover the available names before calling+`presentation.template(name)`.++## Cookbook++```ts+// List the top-level deck APIs.+const deckApis = presentation.help("presentation*", {+ include: "index",+ maxChars: 6000,+});+```++```ts+// Search broadly, then filter by regex.+const hits = presentation.help("*", {+ search: "chart|axis|legend",+ include: ["index", "examples"],+ maxChars: 8000,+});+```++```ts+// Pull examples for one exact API.+const examples = presentation.help("slide.charts.add", {+ include: ["examples", "notes"],+ maxChars: 4000,+});+```++```ts+// Pair help with inspect for focused edits.+const help = presentation.help("shape.text.replace", {+ include: ["examples", "notes"],+});+const before = await presentation.inspect({+ kind: "textbox,shape",+ search: "Placeholder",+ maxChars: 4000,+});+const target = presentation.resolve(anchorId);+target.text.replace("Placeholder", "Updated text");+const after = await presentation.inspect({+ target: { id: anchorId, beforeLines: 2, afterLines: 2 },+ kind: "textbox,shape",+ maxChars: 2000,+});+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/images.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/images.spec.mdnew file mode 100644index 0000000..6257b32--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/images.spec.md@@ -0,0 +1,248 @@+# Images++`slide.images` inserts image elements from bytes, data URLs, URIs, and prompts.++For embedded image output, use `blob={imageBytes}` with `contentType`. Use+`uri` for references the host resolves.++## Add Image++```ts+const image = slide.images.add({+ blob: imageBytes,+ contentType: "image/png",+ alt: "Product screenshot",+ fit: "cover",+ position: { left: 72, top: 120, width: 520, height: 320 },+ crop: { left: 0.02, top: 0, right: 0.04, bottom: 0 },+ geometry: "roundRect",+ borderRadius: "rounded-2xl",+});+```++Choose exactly one primary source: `blob`, `dataUrl`, `uri`, or `prompt`.+Concrete sources may carry `prompt` as metadata for later regeneration.++## Image Inline Types++```ts+type ImageSource =+ | { blob: ArrayBuffer | Uint8Array; prompt?: string }+ | { dataUrl: string; prompt?: string }+ | { uri: string; prompt?: string }+ | { prompt: string };++type ImageAddOptions = ImageSource & {+ alt?: string;+ fit?: "contain" | "cover";+ contentType?: string;+ position?: { left?: number; top?: number; width?: number; height?: number };+ frame?: { left?: number; top?: number; width?: number; height?: number };+ crop?: { left: number; top: number; right: number; bottom: number }; // normalized 0..1 insets removed from source image+ geometry?: string; // common: "rect", "roundRect", "ellipse"; full list is the shape preset list+ borderRadius?: number | string; // number = pixels; string = supported rounded-* token+};+```++`position` and `frame` use the same pixel shape. Use either spelling; prefer+`position` in add calls and `frame` when preserving imported placement.++## Resolved From Inspect++```ts+const image = presentation.resolve("im/c3d4e5f6");+const oldFrame = image.frame;+const oldCrop = image.crop;+const oldFit = image.fit;+const oldAlt = image.alt;+const oldPrompt = image.prompt;+const oldGeometry = image.geometry;+const oldBorderRadius = image.borderRadius;+const oldRotation = image.rotation;+const oldFlipHorizontal = image.flipHorizontal;+const oldFlipVertical = image.flipVertical;+const oldLockAspectRatio = image.lockAspectRatio;++image.replace({+ blob: nextBytes,+ contentType: "image/png",+ alt: oldAlt ?? "Updated screenshot",+ ...(oldFit ? { fit: oldFit } : {}),+ ...(oldPrompt ? { prompt: oldPrompt } : {}),+});+image.frame = oldFrame;+image.crop = oldCrop;+image.geometry = oldGeometry;+image.borderRadius = oldBorderRadius;+image.rotation = oldRotation;+image.flipHorizontal = oldFlipHorizontal;+image.flipVertical = oldFlipVertical;+image.lockAspectRatio = oldLockAspectRatio;+```++Use `presentation.inspect({ kind: "image", search })` to find the `im/...`+anchor id. Preserve frame, crop, fit, alt text, mask geometry, and border radius+unless the edit explicitly changes them.+Concrete source replacements produce concrete images; pass `prompt` when it+should remain available as regeneration metadata.++## Edit Placement And Fit++```ts+image.position = position;+image.frame = frame;+image.fit = fit;+image.crop = crop;+image.geometry = "roundRect";+image.borderRadius = "rounded-xl";+image.rotation = rotationDeg;+image.flipHorizontal = flipHorizontal;+image.flipVertical = flipVertical;+image.lockAspectRatio = true;+image.width = 320;+image.height = 180;+image.alt = altText;+```++`crop` edges are normalized `0..1` fractions removed from the source image and+are clamped. `fit="cover"` fills the frame and may crop; `fit="contain"`+preserves the full image. `geometry="ellipse"` or `geometry="roundRect"` clips+the image. `borderRadius` is for rect/roundRect masks; numbers are pixels and+strings use supported `rounded-*` tokens.++## Replace Source++```ts+image.replace({+ blob,+ contentType,+ dataUrl,+ uri,+ prompt,+ alt,+ fit,+});+```++`replace` swaps the source and common source metadata. Choose one primary source+field as with `add`. Preserve or set placement, crop, mask geometry, and border+radius on the image facade itself.++## Replace And Regenerate Inline Types++```ts+type ImageReplaceOptions =+ {+ alt?: string;+ fit?: "contain" | "cover";+ contentType?: string;+ blob?: ArrayBuffer | Uint8Array;+ dataUrl?: string;+ uri?: string;+ prompt?: string;+ };++type ImageRegenerateOptions = {+ prompt?: string;+ kind?: "sticker" | "layout" | "content" | "infographic";+ fit?: "contain" | "cover";+ size?: "1024x1024" | "1536x1024" | "1024x1536";+ quality?: "low" | "medium" | "high";+ background?: "auto" | "transparent" | "opaque";+ outputFormat?: "png" | "jpeg" | "webp";+};+```++## Prompt Images++```ts+const promptImage = slide.images.add({+ prompt,+ alt,+ position,+ fit,+});++promptImage.regenerate({ kind });+```++Prompt placeholders are optional. Use concrete sources when asset bytes or+references are already available.++## Concrete Image Sources++```ts+const imageBytes = assetBytes;+const imageUri = assetUri;+const imageDataUrl = assetDataUrl;+```++## JSX Declarative Image++```tsx+/** @jsxRuntime automatic */++slide.compose(+ <row width="fill" height="fill" gap={16}>+ <image blob={imageBytes} alt="Embedded bytes" fit="cover" width={320} height={180} />+ <image uri={imageUri} alt="Host-resolved reference" fit="contain" width={320} height={180} />+ </row>,+ {+ frame: { left: 48, top: 40, width: 864, height: 240 },+ baseUnit: 8,+ },+);++```++## Cookbook++```ts+// Full-frame image crop.+slide.images.add({+ blob: imageBytes,+ contentType: "image/jpeg",+ alt: "Workspace image",+ fit: "cover",+ position: { left: 0, top: 0, width: 1280, height: 720 },+});+```++```ts+// Rounded image mask.+slide.images.add({+ blob: imageBytes,+ contentType: "image/jpeg",+ alt: "Customer interview",+ fit: "cover",+ geometry: "roundRect",+ borderRadius: "rounded-3xl",+ position: { left: 720, top: 96, width: 448, height: 512 },+});+```++```tsx+// Circular avatar mask in JSX.+<image blob={avatarBytes} contentType="image/png" alt="Speaker" fit="cover" geometry="ellipse" width={96} height={96} />+```++```tsx+// Rounded crop/mask in JSX.+<image+ blob={portraitBytes}+ contentType="image/jpeg"+ alt="Customer portrait"+ fit="cover"+ geometry="roundRect"+ borderRadius="rounded-2xl"+ crop={{ left: 0.08, top: 0.02, right: 0.14, bottom: 0 }}+ width={320}+ height={420}+/>+```++```ts+// Manual crop when the subject is off-center.+image.fit = "cover";+image.crop = { left: 0.08, top: 0.02, right: 0.18, bottom: 0.06 };+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/inspect.md b/skills/paper-fig/artifact_tool_docs/api/references/inspect.mdnew file mode 100644index 0000000..566e74a--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/inspect.md@@ -0,0 +1,176 @@+# Inspect++Use `presentation.inspect(...)` to read compact deck snapshots for create, edit,+and review workflows. Inspect emits NDJSON records with stable anchor ids; pass+those ids to `presentation.resolve(id)` for follow-up edits.++## Snapshot++```ts+const snapshot = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",+ search,+ maxChars,+});+console.log(snapshot.ndjson);+```++Example output:++```text+{"kind":"slide","id":"sl/b2c3d4e5","slide":1,"title":"Revenue outlook","textShapes":4}+{"kind":"textbox","id":"sh/c3d4e5f6","slide":1,"name":"headline","text":"Revenue outlook","textPreview":"Revenue outlook","textChars":15,"textLines":1,"bbox":[72,64,520,96],"bboxUnit":"px"}+{"kind":"chart","id":"ch/d4e5f6a7","slide":1,"name":"arr-chart","chartType":"bar","title":"ARR","bbox":[620,180,520,320],"bboxUnit":"px"}+```++Common `kind` tokens:++```text+deck, slide, textbox, textrange, shape, table, chart, image, notes, thread, layout+```++`comments` is accepted as an alias for the canonical `thread` kind.++Useful `include`/`exclude` tokens:++```text+id, slide, name, title, text, textPreview, textChars, textLines,+bbox, bboxUnit, rows, cols, preview, chartType, alt, prompt,+isPlaceholder, comments, placeholders+```++Use comma-separated strings for `include` and `exclude`:++```ts+const focused = await presentation.inspect({+ kind: "textbox,shape",+ include: "id,slide,name,bbox,textPreview",+ exclude: "preview,comments",+ maxChars: 4000,+});+```++Anchor prefixes:++```text+pr/ deck, sl/ slide, sh/ shape/textbox, ch/ chart, im/ image,+tb/ table, nt/ notes, th/ thread, tr/ text range+```++Only `pr/`, `sl/`, `sh/`, `im/`, `tb/`, `ch/`, `nt/`, `th/`, and `tr/`+anchors are valid for `presentation.resolve(...)`. Layout ids and template ids+from layout exports are for inspection, comparison, and intentional layout+collection edits.++`slide` in inspect records is 1-based for display. `presentation.slides.getItem(index)`+uses 0-based indexes. Prefer resolving anchor ids over converting slide numbers.+Element anchor ids are compact stable ids such as `sh/a1b2c3d4`,+`im/c3d4e5f6`, `tb/d4e5f6a7`, and `ch/b2c3d4e5`. Copy ids from inspect output+and pass them to+`presentation.resolve(id)`.++## Inline Type++```ts+type PresentationInspectOptions = {+ target?: { id: string; beforeLines?: number; afterLines?: number };+ kind?: string;+ include?: string;+ exclude?: string;+ search?: string;+ maxChars?: number;+};+```++## Focused Edit Loop++```ts+const before = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",+ search: "Revenue",+ maxChars: 8000,+});++const target = presentation.resolve(anchorId);++// slideAnchorId is the `sl/...` id from inspect for the affected slide.+const slide = presentation.resolve(slideAnchorId);+const previewBefore = await slide.export({ format: "png", scale: 2 });+const layoutBefore = await slide.export({ format: "layout" });+const montageBefore = await presentation.export({+ format: "webp",+ montage: true,+ scale: 1,+});++target.text.replace("Revenue", "Revenue outlook");++const previewAfter = await slide.export({ format: "png", scale: 2 });+const layoutAfter = await slide.export({ format: "layout" });+const montageAfter = await presentation.export({+ format: "webp",+ montage: true,+ scale: 1,+});++const after = await presentation.inspect({+ target: { id: anchorId, beforeLines: 2, afterLines: 2 },+ kind: "textbox,shape",+ maxChars: 2000,+});+```++## Example Records++```jsonl+{"kind":"slide","id":"sl/a1b2c3d4","slide":1,"title":"Revenue outlook","textShapes":4}+{"kind":"textbox","id":"sh/a1b2c3d4","slide":1,"name":"headline","textPreview":"Revenue outlook","textChars":15,"bbox":[72,64,520,96],"bboxUnit":"px"}+{"kind":"chart","id":"ch/b2c3d4e5","slide":1,"name":"arr-chart","chartType":"bar","title":"ARR","bbox":[620,180,520,320],"bboxUnit":"px"}+{"kind":"thread","id":"th/e5f6a7b8","slide":1,"target":"sh/a1b2c3d4","status":"open","comments":[{"text":"TODO tighten copy"}]}+```++## Imported Templates++```ts+const layoutSnapshot = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,layout",+ maxChars: 8000,+});+```++Use the snapshot to find slide titles, visible text, object names, positions,+and ids before editing imported content.++## Cookbook++```ts+// Search narrowly first.+const hits = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",+ search: "Q4",+ maxChars: 6000,+});+```++```ts+// Then focus around the chosen anchor.+const focused = await presentation.inspect({+ target: { id: "sh/a1b2c3d4", beforeLines: 2, afterLines: 4 },+ kind: "textbox,shape",+ maxChars: 2000,+});+```++```ts+// Preserve evidence before and after an edit.+const before = await presentation.inspect({ kind: "chart,table", search: "ARR", maxChars: 4000 });+presentation.resolve(chartAnchorId).series.getItemAt(0).values = [12, 16, 21, 28];+const after = await presentation.inspect({ target: { id: chartAnchorId }, kind: "chart", maxChars: 2000 });+```++```ts+// Verify one slide visually and structurally.+const slide = presentation.resolve(slideAnchorId);+const preview = await slide.export({ format: "png", scale: 1 });+const layout = await slide.export({ format: "layout" });+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/jsx.md b/skills/paper-fig/artifact_tool_docs/api/references/jsx.mdnew file mode 100644index 0000000..52aff3f--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/jsx.md@@ -0,0 +1,231 @@+# Presentation JSX Reference++This is the compact API reference for authoring editable presentations with+presentation JSX. It describes the node vocabulary and layout mechanics. For+first-principles row, column, grid, alignment, mask, and overlay recipes, read+`cookbook/layout.md`.++Examples start after `presentation` and `slide` exist.++## Authoring Defaults++- Use JSX for structured slide layout: `slide.compose(<row ... />, { frame })`.+- Use string sizing where supported: `width="fill"`, `height="hug"`,+ `height="fill"`.+- Use raw pixel numbers for fixed sizes: `width={420}`, `gap={24}`,+ `padding={{ x: 48, y: 40 }}`.+- Use Tailwind-like tokens for common styling: `fill="slate-950"`,+ `borderRadius="rounded-xl"`, `shadow="shadow-md"`,+ `className="bg-white rounded-xl shadow-sm"`.+- Use `row`, `column`, `grid`, `layers`, and `box` for layout. Use absolute+ slide frames only for the outer composed region, fixed chrome, and+ imported-template details. For overlays, scrims, and masked image+ compositions inside a region, use `layers` and image `geometry`/`borderRadius`.+- Put text in `paragraph` and inline emphasis in child `run` nodes.+- Put real data in native `table` and `chart` nodes.+- Model-facing examples use string sizing and local track objects instead of+ imported sizing helpers such as `wrap(...)`, `grow(...)`, and `fr(...)`.++## JSX Usage Rules++Use JSX props for layout and token strings for common visual styling:++| Need | Use |+| --- | --- |+| Layout sizing | `width="fill"`, `height={320}`, `gap={24}`, `padding={{ x: 32, y: 24 }}` |+| Flex flow | `<row align="center" justify="between">` and `<column gap={16}>` |+| Grid tracks | local arrays such as `[{ mode: "fr", value: 1 }]` |+| Visual tokens | `className="bg-white rounded-xl shadow-sm"` |+| Exact text | `style="font: 700 28px Inter; color: #0f172a; leading: 1.1"` |+| Gradients | `fill="linear(135deg, #fff 0%, sky-100 100%)"` |+| Image masks | `<image geometry="ellipse" crop={...} fit="cover" />` |++## Canonical Node Set++### Slide Roots++| Node | Purpose | Common props |+| --- | --- | --- |+| `slide` | Whole-slide JSX root | `id`, `name`, `width`, `height`, `padding`, `gap`, `align`, `justify`, `background`, `backgroundRef` |+| `background` | Slide background metadata | `fill`, `ref` |++Most code composes directly into an existing `slide` facade rather than using a+`<slide>` root.++### Layout Nodes++| Node | Purpose | Common props |+| --- | --- | --- |+| `row` | Horizontal flex-like layout | `width`, `height`, `gap`, `align`, `justify`, `padding` |+| `column` | Vertical flex-like layout | `width`, `height`, `gap`, `align`, `justify`, `padding` |+| `grid` | Track layout with spans | `columns`, `rows`, `autoRows`, `columnGap`, `rowGap`, `alignItems`, `justifyItems`, `padding` |+| `layers` | Overlay children in one frame | `width`, `height`, `padding`, `alignItems`, `justifyItems` |+| `box` | Surface/container with one child region | `width`, `height`, `padding`, `align`, `justify`, `fill`, `line`, `borderRadius`, `shadow`, `className` |++`align` controls the cross axis. `justify` controls the main axis. Supported+values are `"start"`, `"center"`, `"end"`, `"stretch"` for alignment and+`"start"`, `"center"`, `"end"`, `"between"` for distribution.++All direct grid children support `columnSpan` and `rowSpan`, including+`row`, `column`, `box`, `paragraph`, `shape`, `image`, `table`, and `chart`.++### Content Nodes++| Node | Purpose | Common props |+| --- | --- | --- |+| `paragraph` | Text block | `width`, `height`, `style`, `className`, `transform`, `bulletCharacter`, `marginLeft`, `indent`, `spaceBefore`, `spaceAfter`, `styleId`, `paragraphStyle` |+| `run` | Inline text run | children, `textStyle`, `className`, `link` |+| `shape` | Primitive drawing | `geometry`, `width`, `height`, `fill`, `line`, `borderRadius`, `shadow`, `className` |+| `image` | Raster/vector image | `blob`, `dataUrl`, `uri`, `prompt`, `contentType`, `fit`, `alt`, `geometry`, `borderRadius`, `crop`, `rotation`, `flipHorizontal`, `flipVertical`, `lockAspectRatio`, `width`, `height` |+| `rule` | Divider line | `stroke`, `weight`, `opacity`, `width`, `height` |+| `table` | Native table | `rows`, `columns`, `values`, `style`, `styleOptions`, `width`, `height` |+| `chart` | Native chart | `chartType`, `title`, `categories`, `series`, `legend`, `xAxis`, `yAxis`, `width`, `height` |++`id` and `name` are supported on materialized nodes. Use deterministic+kebab-case `name` values on composed roots and important descendants:+`content-frame`, `primary-heading`, `metrics-grid`, `chart-frame`, `revenue-chart`.+Names should describe role, not visual position. Use `id` when the calling code+controls stability across edits.++### Chart Child Nodes++Use a compact chart config when it is clearest. Use nested chart nodes when the+JSX tree should expose structure.++| Node | Purpose |+| --- | --- |+| `bar`, `line`, `area`, `scatter`, `bubble`, `radar`, `pie`, `doughnut`, `treemap`, `sunburst`, `map`, `waterfall`, `funnel`, `histogram`, `boxWhisker`, `stock`, `surface`, `surface3D`, `pareto`, `combo`, `line3D`, `pie3D`, `area3D`, `bar3D`, `ofPie` | Chart family selector/options |+| `legend`, `data-labels`, `data-table`, `x-axis`, `y-axis`, `axis`, `major-gridlines`, `minor-gridlines` | Chart chrome and axes |+| `series`, `marker`, `point`, `data-label`, `trendline`, `trendline-label`, `error-bars` | Series and point-level options |+| `view-3d` | 3D camera options |++## Sizing And Frames++Use these forms first:++| Intent | JSX |+| --- | --- |+| Fill parent | `width="fill"` or `height="fill"` |+| Fit content | `width="hug"` or `height="hug"` |+| Fixed pixels | `width={320}` or `height={180}` |+| Equal children in a row/column | give each child `width="fill"` or `height="fill"` |+| One fixed region plus remaining space | one child `width={520}`, sibling `width="fill"` |+| Fixed slide region | `slide.compose(node, { frame: { left, top, width, height } })` |++`frame` uses numeric pixels. JSX size props accept strings for `"fill"` and+`"hug"` plus raw pixel numbers.++Use `1280 x 720` as the default canvas unless the task or source deck requires+another size. A common content frame is:++```ts+const PAGE = { left: 72, top: 64, width: 1136, height: 592 };+```++## Alignment Matrix++| Node | Main axis | Cross axis | Distribution prop | Cross-axis prop | Defaults |+| --- | --- | --- | --- | --- | --- |+| `row` | horizontal | vertical | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `justify="start"`, `align="start"` |+| `column` | vertical | horizontal | `justify`: `start`, `center`, `end`, `between` | `align`: `start`, `center`, `end`, `stretch` | `justify="start"`, `align="start"` |+| `grid` | tracks | cells | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | both `stretch` |+| `layers` | shared frame | shared frame | `justifyItems`: `start`, `center`, `end`, `stretch` | `alignItems`: `start`, `center`, `end`, `stretch` | both `stretch` |++## Layout Recipes++This top-level reference stays close to the JSX API. For copy-paste row,+column, 3-column, 12-grid, alignment, mask, overlay, and gradient recipes, use+[`cookbook/layout.md`](./cookbook/layout.md).++## Text Examples++```tsx+<paragraph className="text-slate-950 text-4xl font-bold leading-tight">+ A paragraph can contain plain text.+</paragraph>++<paragraph className="text-slate-600 text-lg leading-relaxed">+ Use <run textStyle={{ bold: true, color: "sky-600" }}>runs</run> for inline+ emphasis or links.+</paragraph>++<column width="fill" height="hug" gap={8}>+ <paragraph+ width="fill"+ className="text-slate-700 text-lg leading-relaxed"+ >+ First paragraph.+ </paragraph>+ <paragraph bulletCharacter="•" marginLeft={18 * 12700} indent={-10 * 12700}>+ Bulleted paragraph with native list metadata.+ </paragraph>+</column>+```++Paragraph indentation uses EMU, not pixels; the example converts points with+12,700 EMU per point. Paragraph spacing uses hundredths of a point. See+[native bullets](../../../references/native_bullets.md).++Use `style={{ ... }}` for exact text config and `className` for tokenized+common text styling. A string `style` containing `:` or `;` is parsed as a+compact text declaration; any other string is treated as a named presentation+style id.++```tsx+<paragraph style="font: 700 22px Inter; color: #334155; leading: 1.25; wrap: none">+ Exact style string+</paragraph>+```++## Tables And Charts++Prefer compact config for data objects.++```tsx+<table+ rows={3}+ columns={3}+ values={[+ ["Metric", "Q1", "Q2"],+ ["Revenue", 12, 18],+ ["Margin", "42%", "45%"],+ ]}+ style="TableStyleMedium2"+ styleOptions={{ headerRow: true, bandedRows: true }}+ width="fill"+ height={220}+/>++<chart+ chartType="bar"+ title="Pipeline"+ categories={["Q1", "Q2", "Q3"]}+ series={[{ name: "Revenue", values: [12, 18, 24], fill: "sky-500" }]}+ xAxis={{ textStyle: { fontSize: 10, fill: "slate-600" } }}+ yAxis={{ majorGridlines: { style: "solid", fill: "slate-200", width: 1 } }}+ width="fill"+ height={280}+/>+```++Use nested chart nodes when the chart needs explicit series, point, trendline,+axis, or label structure in the JSX tree.++## Image Sources++| Source prop | Use when |+| --- | --- |+| `blob={bytes}` | Export must embed the actual image bytes. |+| `dataUrl="data:image/..."` | Bytes are already encoded inline. |+| `uri="https://..."` | Host or adapter will hydrate the image reference. |+| `prompt="..."` | The slide should contain an image-generation placeholder. |++Use `fit="contain"` when the full image must remain visible. Use `fit="cover"`+when cropping is deliberate. Keep labels and data as editable slide text layered+with the image.++## Reference Tests++- `tests/presentation/jsx.spec.tsx`: JSX normalization and compose behavior.+- `tests/presentation/jsx-style-language.spec.tsx`: compact style strings.+- `tests/presentation/tailwind-tokens.sanity.spec.ts`: token coverage.diff --git a/skills/paper-fig/artifact_tool_docs/api/references/layout.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/layout.spec.mdnew file mode 100644index 0000000..52597cc--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/layout.spec.md@@ -0,0 +1,98 @@+# Layouts++Layouts define reusable placeholder structure for slides.++## Create A Layout++```ts+const layout = presentation.layouts.add(layoutName);+layout.placeholders.add({+ type: placeholderType,+ index: placeholderIndex,+ text: placeholderText,+ geometry: "textbox",+});+```++## Placeholder Inline Type++```ts+type PlaceholderConfig = {+ type?:+ | "title"+ | "subtitle"+ | "body"+ | "picture"+ | "chart"+ | "table"+ | "content";+ index?: number;+ text?: TextValue;+ geometry?: "textbox" | "rect" | "roundRect" | string;+ position?: { left?: number; top?: number; width?: number; height?: number };+ fill?: FillConfig;+ line?: LineConfig;+};+```++## Shape-Based Placeholders++```ts+const placeholder = layout.shapes.addPlaceholder(placeholderName);+placeholder.placeholder.type = placeholderType;+placeholder.placeholder.index = placeholderIndex;+placeholder.text = placeholderText;+```++## Use A Layout++```ts+slide.setLayout(layout);++const target = slide.placeholders.getItem(placeholderType);+target.text = textValue;+```++## Discover++```ts+const layoutSummary = layout.placeholders.summary();+const resolved = presentation.layouts.getById(layout.id);+```++Imported layouts and masters expose their preserved PowerPoint guide metadata+through the read-only `slideGuides` collection. Use `presentation.view` to+control whether imported guides are visible.++```ts+const importedGuides = presentation.layouts.items[0].slideGuides;+```++## Cookbook++```ts+// Branded title/body layout.+const layout = presentation.layouts.add("Title Body");+layout.placeholders.add({+ type: "title",+ index: 0,+ geometry: "textbox",+ position: { left: 72, top: 64, width: 920, height: 88 },+ text: "Title",+});+layout.placeholders.add({+ type: "body",+ index: 0,+ geometry: "roundRect",+ position: { left: 72, top: 180, width: 760, height: 360 },+ fill: "slate-50",+ line: { style: "solid", fill: "slate-200", width: 1 },+});+```++```ts+// Use placeholders for repeated structure; override slide content locally.+const slide = presentation.slides.add({ layout: "Title Body" });+slide.placeholders.getItem("title").text = "Market overview";+slide.placeholders.getItem("body").text = "Three editable points go here.";+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/master.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/master.spec.mdnew file mode 100644index 0000000..f97013b--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/master.spec.md@@ -0,0 +1,57 @@+# Masters++Masters share theme, background, and color-map structure with child layouts.++## Create And Link++```ts+const master = presentation.masters.add(masterName);+const layout = presentation.layouts.add(layoutName);++layout.setParentLayoutId(master.id);+```++## Color Map And Background++```ts+master.setColorMap(colorMapConfig);+master.background.ref = backgroundRef;++const slide = presentation.slides.add();+slide.setLayout(layout);+```++## Master Inline Types++```ts+type ColorMapConfig = Partial<Record<+ "bg1" | "tx1" | "bg2" | "tx2" | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6" | "hlink" | "folHlink",+ "bg1" | "tx1" | "bg2" | "tx2" | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6" | "hlink" | "folHlink"+>>;+```++## Resolve++```ts+const resolved = presentation.layouts.getById(master.id);+```++## Cookbook++```ts+// Shared brand master with inherited layout.+const master = presentation.masters.add("Brand Master");+master.setColorMap({ bg1: "bg1", tx1: "tx1", accent1: "accent1" });+master.background.ref = "bg1";++const layout = presentation.layouts.add("Brand Title");+layout.setParentLayoutId(master.id);+layout.placeholders.add({+ type: "title",+ geometry: "textbox",+ position: { left: 72, top: 72, width: 1000, height: 96 },+});+```++Before editing a master in an imported deck, inspect affected layouts and+slides; master edits have intentional global blast radius.diff --git a/skills/paper-fig/artifact_tool_docs/api/references/presentation.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/presentation.spec.mdnew file mode 100644index 0000000..b1bf26b--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/presentation.spec.md@@ -0,0 +1,213 @@+# Presentation Facade++## Create And Load++```ts+const presentation = Presentation.create({ slideSize });+const imported = Presentation.load(proto);+```++## Create Inline Type++```ts+type PresentationCreateOptions = {+ slideSize?: { width: number; height: number };+};+```++## Presentation Slide Collection++```ts+const slide = presentation.slides.add({ layout, layoutId });+const inserted = presentation.slides.insert({ after, layout, layoutId });+const byIndex = presentation.slides.getItem(slideIndex);+```++## Presentation Slide Collection Inline Types++```ts+type SlideAddOptions = {+ layout?: string;+ layoutId?: string;+ width?: number;+ height?: number;+};++type SlideInsertOptions = SlideAddOptions & {+ after?: Slide | number | null;+};+```++## Discover And Edit++```ts+const snapshot = await presentation.inspect({+ kind,+ search,+ maxChars,+});++const target = presentation.resolve(anchorId);+```++`inspect` returns stable anchor ids for slides, shapes, images, tables, charts, text ranges, speaker notes, and comment threads. `resolve` maps a returned anchor id to the matching facade. Layout records expose `layoutId` for search and comparison; pass only `pr/`, `sl/`, `sh/`, `im/`, `tb/`, `ch/`, `nt/`, `th/`, and `tr/` anchors to `resolve`.++## Inspect Inline Type++```ts+type PresentationInspectOptions = {+ target?: { id: string; beforeLines?: number; afterLines?: number };+ kind?: string; // e.g. "slide,textbox,shape,image,table,chart,notes,thread,layout"+ include?: string;+ exclude?: string;+ search?: string;+ maxChars?: number;+};+```++## Help++```ts+const help = presentation.help(query, {+ search,+ include,+ maxChars,+});+```++## Help Inline Type++```ts+type PresentationHelpOptions = {+ search?: string;+ include?: string[]; // common: ["index", "examples", "notes"]+ maxChars?: number;+};+```++## Presentation View++Use `presentation.view` to control gridlines and imported PowerPoint guides in+an editor preview.++```ts+presentation.view.showGridlines();+presentation.view.showGuides();++const gridlinesVisible = presentation.view.gridlinesVisible;+const guidesVisible = presentation.view.guidesVisible;+const horizontalGridSpacingEmu = presentation.view.gridSpacingCxEmu;+const verticalGridSpacingEmu = presentation.view.gridSpacingCyEmu;++presentation.view.hideGridlines();+presentation.view.hideGuides();++const nextGridlineState = presentation.view.toggleGridlines();+const nextGuideState = presentation.view.toggleGuides();+```++Gridline visibility is local editor state. Guide visibility is also intended+for the editor view; serialized presentation data keeps imported guide+definitions while exporting their visibility as hidden.++## Export And Serialized Data++```ts+const imageBlob = await presentation.export({ slide, format, scale });+const montageBlob = await presentation.export({+ format: "webp",+ montage: true,+ scale: 1,+});+const layoutBlob = await slide.export({ format: "layout", scale });+const proto = presentation.toProto();+```++`toProto()` returns presentation data for host adapters. File export and local+resource resolution belong to host adapter docs.++## Export Inline Type++```ts+type PresentationExportOptions = {+ slide?: Slide;+ format?: "png" | "jpeg" | "webp" | "layout";+ width?: number;+ height?: number;+ scale?: number;+ quality?: number;+ montage?:+ | boolean+ | {+ format?: "png" | "jpeg" | "webp";+ width?: number;+ slideWidth?: number;+ padding?: number;+ gap?: number;+ background?: string;+ columns?: number;+ };+};+```++## Scripts++```ts+const result = presentation.scripts.run(scriptKind, scriptOptions);+```++Scripts provide high-level authoring recipes. Use `presentation.help(...)` to discover available script keys and option shapes.++## Cookbook++```ts+// New deck skeleton: create, set theme, add slides, render checks.+const presentation = Presentation.create({+ slideSize: { width: 1280, height: 720 },+});+presentation.theme.colorScheme = {+ name: "Clean Product",+ themeColors: {+ accent1: "#2563eb",+ accent2: "#0f766e",+ accent3: "#f59e0b",+ accent4: "#dc2626",+ accent5: "#7c3aed",+ accent6: "#16a34a",+ bg1: "#ffffff",+ bg2: "#f8fafc",+ tx1: "#0f172a",+ tx2: "#475569",+ dk1: "#000000",+ dk2: "#1e293b",+ lt1: "#ffffff",+ lt2: "#e2e8f0",+ hlink: "#2563eb",+ folHlink: "#7c3aed",+ },+};++const first = presentation.slides.add();+const second = presentation.slides.add();+const third = presentation.slides.add();++await presentation.export({+ slide: first,+ format: "png",+ scale: 1,+});+const snapshot = await presentation.inspect({+ kind: "deck,slide,textbox,chart,table",+ maxChars: 6000,+});+```++```ts+// Existing deck: inspect first, then resolve exact anchors.+const before = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes,thread,layout",+ search: "Customer growth",+ maxChars: 8000,+});+const target = presentation.resolve(anchorIdFromBefore);+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/rich-text.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/rich-text.spec.mdnew file mode 100644index 0000000..af50b33--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/rich-text.spec.md@@ -0,0 +1,253 @@+# Rich Text++Shape text accepts strings, paragraph arrays, and structured runs.++## Set Text++```ts+shape.text = textValue;+shape.text = paragraphs;+shape.text = structuredRuns;+```++## Text Value Inline Types++```ts+type TextValue = string | string[] | StructuredTextInput | Text;++type StructuredTextInput =+ | ParagraphRunsInput+ | StructuredTextParagraphInput+ | Array<ParagraphRunsInput | StructuredTextParagraphInput>;++type ParagraphRunsInput = Array<string | number | TextRunInput>;++type StructuredTextParagraphInput = {+ runs?: ParagraphRunsInput;+ bulletCharacter?: string;+ marginLeft?: number;+ indent?: number;+ spaceBefore?: number;+ spaceAfter?: number;+ styleId?: string;+ paragraphStyle?: Record<string, unknown>;+};++type TextRunInput = {+ run: string;+ textStyle?: {+ bold?: boolean;+ italic?: boolean;+ underline?: string;+ fontSize?: string;+ typeface?: string;+ color?: FillConfig;+ };+ link?: { uri: string; isExternal: boolean; action?: string };+};+```++Structured run `fontSize` accepts unit strings such as `"20pt"` and `"28px"`.+Shape text style setters use numeric pixels with `fontSize` and numeric points+with `fontSizePt`.++## Structured Paragraphs++```ts+shape.text.set([+ [{ run: "Status", textStyle: { bold: true } }, { run: " review" }],+ {+ bulletCharacter: "•",+ marginLeft: 18 * 12700, // points to EMU+ indent: -10 * 12700,+ runs: [+ "Open the",+ {+ run: " rollout notes",+ textStyle: { underline: "sng", color: "#2563eb" },+ link: { uri: "https://example.com", isExternal: true },+ },+ ],+ },+]);+```++The paragraph-object form is the non-JSX peer of `<paragraph>...</paragraph>`. Use it when the text needs paragraph metadata plus authored runs. In the verified runtime, indentation is EMU and paragraph spacing is hundredths of a point, unlike shape-level pixel sizes. See [native bullets](../../../references/native_bullets.md) for the point-based helper and serialization checks.++## JSX Rich Text++```tsx+/** @jsxRuntime automatic */++slide.compose(+ <column width="fill" height="hug" gap={8}>+ <paragraph width="fill" className="text-slate-950 text-2xl leading-tight">+ <run textStyle={{ bold: true }}>Status</run>+ <run> review</run>+ </paragraph>+ <paragraph+ width="fill"+ className="text-slate-950 text-2xl leading-tight"+ bulletCharacter="•"+ marginLeft={18 * 12700}+ indent={-10 * 12700}+ >+ Open the+ <run+ textStyle={{ underline: "sng", color: "#2563eb" }}+ link={{ uri: "https://example.com", isExternal: true }}+ >+ {" rollout notes"}+ </run>+ </paragraph>+ </column>,+ {+ frame: { left: 48, top: 40, width: 864, height: 160 },+ baseUnit: 8,+ },+);+```++## Shape Text Style++```ts+shape.text.style = {+ styleName,+ fontSize: fontSizePx,+ color: colorConfig,+ fill: fillConfig,+ outline: lineConfig,+ alignment,+ verticalAlignment,+ autoFit: autoFitMode,+ wrap: wrapMode,+ insets,+};+```++Use grouped `text.style = { ... }` for whole-shape text formatting. Use single+property setters for focused edits:++```ts+shape.text.fontSize = fontSizePx;+shape.text.color = colorConfig;+shape.text.fill = fillConfig;+shape.text.outline = lineConfig;+shape.text.alignment = alignment;+shape.text.verticalAlignment = verticalAlignment;+shape.text.autoFit = autoFitMode;+shape.text.wrap = wrapMode;+shape.text.insets = insets;+```++`shape.text.color` uses `ColorConfig`. `shape.text.fill`, run `textStyle.fill`,+and text ranges accept the shared `FillConfig`, including linear and path+gradients. `shape.text.outline`, run `textStyle.outline`, and text ranges accept+`LineConfig`; the outline line fill can be a solid, pattern, or gradient fill.++```ts+shape.text.fill = {+ type: "gradient",+ gradientKind: "linear",+ angleDeg: 0,+ stops: [+ { offset: 0, color: "#ff5a5f" },+ { offset: 100000, color: "#4f46e5" },+ ],+};+```++Path gradients use the same fill config with `gradientKind: "path"`, `pathType`, and optional+`fillRect` in Office percentage units.++## Text Style Inline Type++```ts+type TextStyleConfig = {+ styleName?: string;+ className?: string;+ bold?: boolean;+ italic?: boolean;+ fontSize?: number;+ lineSpacing?: number;+ alignment?: "left" | "center" | "right" | "justify";+ verticalAlignment?: "top" | "middle" | "bottom";+ underline?: string;+ fill?: FillConfig;+ color?: ColorConfig;+ outline?: LineConfig;+ wrap?: "square" | "none";+ autoFit?: "none" | "shrinkText" | "resizeShapeToFitText";+ insets?: { top?: number; right?: number; bottom?: number; left?: number };+ typeface?: string;+};+```++## Ranges++```ts+const range = shape.text.get(searchText);+range.bold = isBold;+range.italic = isItalic;+range.fill = fillConfig;+range.outline = lineConfig;+range.link = linkConfig;++const fixedRange = shape.text.getRange(start, length);+fixedRange.style = styleName;+```++## Lists++```ts+shape.text = listParagraphs;+shape.text.style = listStyleName;+shape.text.get(itemText).lineSpacing = lineSpacing;+```++## Links++```ts+shape.text.get(linkText).link = {+ uri,+ isExternal,+};+```++## Link Inline Type++```ts+type LinkConfig = {+ uri: string;+ isExternal: boolean;+ action?: string;+};+```++## Cookbook++```ts+// Title with emphasized suffix.+shape.text.set([+ [+ { run: "Revenue", textStyle: { bold: true, color: "#0f172a" } },+ { run: " momentum", textStyle: { color: "#2563eb" } },+ ],+]);+shape.text.style = { fontSize: 44, lineSpacing: 0.92 };+```++```ts+// Bullets with bold lead-ins.+shape.text.set([+ { bulletCharacter: "•", marginLeft: 22 * 12700, indent: -12 * 12700, runs: [{ run: "Quality:", textStyle: { bold: true } }, " defect rate down 31%"] },+ { bulletCharacter: "•", marginLeft: 22 * 12700, indent: -12 * 12700, runs: [{ run: "Speed:", textStyle: { bold: true } }, " p95 latency under target"] },+]);+```++```ts+// Edit one phrase inside imported text.+const range = shape.text.get("legacy workflow");+range.text = "new workflow";+range.className = "text-emerald-700 font-bold";+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/shapes.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/shapes.spec.mdnew file mode 100644index 0000000..1b962b5--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/shapes.spec.md@@ -0,0 +1,239 @@+# Shapes++`slide.shapes` creates and edits drawable slide elements.++## Preset Shape++```ts+const shape = slide.shapes.add({+ geometry,+ name,+ position,+ fill,+ line,+ adjustmentList,+ borderRadius,+ shadow,+ className,+});++shape.text = textValue;+shape.text.style = {+ styleName: textStyleName,+ fontSize,+ bold,+ color,+};+shape.position = nextPosition;+```++`geometry` is a string preset shape name, `"textbox"`, `"connector"`, or `"custom"`.++## Resolved From Inspect++```ts+const shape = presentation.resolve("sh/a1b2c3d4");+shape.text = "Updated copy";+shape.fill = "accent1+18/90";+shape.line = { style: "solid", fill: "slate-200", width: 1 };+shape.borderRadius = "rounded-2xl";+shape.shadow = "shadow-sm";+```++Use `presentation.inspect({ kind: "shape,textbox", search })` to find the+`sh/...` anchor id. Keep the resolved facade type-aware; do not rebuild an+imported shape unless the task requires a new object.++## Preset Shape Inline Type++```ts+type ShapePresetName = string; // common: "textbox", "rect", "roundRect", "ellipse", "line", "rightArrow"+// Full preset list: rg "SHAPE_GEOMETRY_NAME_TO_PROTO" src/models/presentation src/assets++type PositionConfig = {+ left?: number;+ top?: number;+ width?: number;+ height?: number;+ rotation?: number;+ horizontalFlip?: boolean;+ verticalFlip?: boolean;+};++type PresetShapeConfig = {+ geometry: ShapePresetName;+ name?: string;+ position?: PositionConfig;+ fill?: FillConfig;+ line?: LineConfig;+ adjustmentList?: Array<{ name: string; formula: string }>;+ borderRadius?: number | string; // number = pixels; string = supported rounded-* token+ shadow?: string; // shadow token, "shadow-none", or custom "2px 7px 19px #000000/17"+ className?: string;+ placeholderType?: "title" | "subtitle" | "body" | "picture" | "chart" | "table" | "content";+ placeholderIndex?: number;+};+```++## Rounded Corners++Prefer `borderRadius` for rect-like rounded corners:++```ts+slide.shapes.add({+ geometry: "rect",+ position: { left: 80, top: 120, width: 320, height: 160 },+ fill: "white",+ borderRadius: "rounded-2xl",+});++shape.borderRadius = 24;+```++Numbers are pixels. Strings use supported `rounded-*` tokens. `borderRadius`+requires a shape with width/height and is supported for `rect`, `textbox`, and+`roundRect`-like shapes. Use `adjustmentList` only when you need exact OpenXML+preset adjustment formulas.++## Rounded Rect Adjustment++```ts+const rounded = slide.shapes.add({+ geometry: "roundRect",+ position,+ fill,+ line,+ adjustmentList: [{ name: "adj", formula: adjustmentFormula }],+});+```++The `adj` value uses the OpenXML shape adjustment scale for the corner radius.++## Custom Path++```ts+const custom = slide.shapes.add({+ geometry: "custom",+ position,+ fill,+ line,+ customPaths: [+ {+ width,+ height,+ commands,+ },+ ],+});+```++Custom path coordinates use pixels in the path viewport.++## Custom Path Inline Type++```ts+type CustomShapeConfig = Omit<PresetShapeConfig, "geometry"> & {+ geometry: "custom";+ customPaths: Array<{+ id?: string;+ width: number;+ height: number;+ commands: Array<+ | { moveTo: { x: number; y: number } }+ | { lineTo: { x: number; y: number } }+ | { close: Record<string, never> }+ >;+ }>;+};+```++## Connector++```ts+const connector = slide.shapes.connect(sourceShape, targetShape, {+ kind: "elbow",+ fromSide: "right",+ toSide: "left",+ line: { style: "solid", fill: "slate-400", width: 2 },+ head: { type: "arrow", width: "med", length: "med" },+});+```++Use [`connectors.md`](./connectors.md) for connector routing, side anchors,+direct `geometry: "connector"` creation, arrowheads, and endpoint edits.++## Line Primitive Decision++| Need | Use |+| --- | --- |+| Divider inside compose JSX | `<rule stroke="slate-200" weight={1} />` |+| Free-positioned line | `slide.shapes.add({ geometry: "line", position, fill: "none", line })` |+| Arrow connected to shapes | `slide.shapes.connect(fromShape, toShape, { line, head })` |+| Border around a surface | shape or box `line={{ style: "solid", fill: "slate-200", width: 1 }}` |++## Shadows++Supported shadow tokens:++```text+shadow-none, shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl+```++Custom shadow strings are also supported when the presentation has a theme+context:++```ts+shape.shadow = "shadow-md";+shape.shadow = "2px 7px 19px #000000/17";+shape.shadow = "shadow-none";+```++## Ordering++```ts+shape.bringToFront();+shape.sendToBack();+```++## Cookbook++```ts+// KPI metric surface.+const metricSurface = slide.shapes.add({+ geometry: "roundRect",+ name: "kpi-surface",+ position: { left: 64, top: 132, width: 260, height: 148 },+ fill: "white",+ line: { style: "solid", fill: "slate-200", width: 1 },+ borderRadius: "rounded-2xl",+ shadow: "shadow-md",+});+metricSurface.text = "Revenue\n$12.4M";+metricSurface.text.style = {+ className: "text-slate-950 text-2xl font-bold leading-tight",+};+```++```ts+// Pill label.+const pill = slide.shapes.add({+ geometry: "roundRect",+ position: { left: 64, top: 64, width: 148, height: 34 },+ fill: "emerald-50",+ line: { style: "solid", fill: "emerald-200", width: 1 },+ borderRadius: "rounded-full",+});+pill.text = "ON TRACK";+pill.text.style = { className: "text-emerald-800 text-sm font-bold" };+```++```ts+// Directional connector between two shapes.+slide.shapes.connect(sourceShape, targetShape, {+ kind: "elbow",+ fromSide: "right",+ toSide: "left",+ line: { style: "solid", fill: "slate-400", width: 2 },+ head: { type: "triangle", width: "sm", length: "sm" },+});+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/slide.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/slide.spec.mdnew file mode 100644index 0000000..60a6e91--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/slide.spec.md@@ -0,0 +1,187 @@+# Slide Facade++## Content Collections++```ts+const shape = slide.shapes.add(shapeConfig);+const image = slide.images.add(imageConfig);+const table = slide.tables.add(tableConfig);+const chart = slide.charts.add(chartType, chartConfig);+```++## Content Config Pointers++```ts+type ShapeConfig = PresetShapeConfig | CustomShapeConfig | ConnectorConfig; // see shapes.spec.md+type ImageConfig = ImageAddOptions; // see images.spec.md+type TableConfig = TableAddOptions | TableCellValue[][]; // see tables.spec.md+type ChartConfig = {+ position?: { left?: number; top?: number; width?: number; height?: number };+ title?: string;+ categories?: string[];+ series?: Array<{ name: string; values?: number[] }>;+}; // see charts.spec.md for axes, legend, labels, and series styling+```++## Background++```ts+slide.background.fill = fillConfig;+```++`fillConfig` accepts theme color strings, hex strings, solid configs, gradient configs, pattern configs, and image-fill configs.++## Layouts And Placeholders++```ts+slide.setLayout(layout);++const placeholder = slide.placeholders.getItem(placeholderName);+placeholder.text = placeholderText;+placeholder.text.style = placeholderStyleName;+```++## Frame And Export++```ts+const frame = slide.frame;+const preview = await slide.export({ format, scale });+```++## Compose Layout++```tsx+/** @jsxRuntime automatic */++slide.compose(+ <row width="fill" height="fill" gap={20}>+ <column width={340} height="fill" gap={12}>+ <paragraph name="summary" className="text-slate-950 text-3xl font-bold">+ Summary+ </paragraph>+ <paragraph className="text-slate-600 text-sm">+ Compose-first layouts stay readable and export cleanly.+ </paragraph>+ </column>+ <box+ name="surface"+ width="fill"+ height="fill"+ padding={16}+ fill="#ffffff"+ >+ <column height="fill" gap={10}>+ <rule stroke="#0f172a" weight={2} />+ </column>+ </box>+ </row>,+ {+ frame: { left: 48, top: 40, width: 864, height: 460 },+ baseUnit: 8,+ },+);+```++`slide.compose(...)` accepts either compose helper nodes or a JSX-authored tree.+It still returns the materialized elements. Use `name` on materializing nodes+when the slide needs stable inspect or layout-export anchors.++## Export Inline Type++```ts+type SlideExportOptions = {+ format?: "png" | "jpeg" | "webp" | "layout";+ width?: number;+ height?: number;+ scale?: number;+ quality?: number;+};+```++`format: "layout"` exports the composed layout tree alongside the materialized slide elements. That is the most useful export when you need stable names, hierarchy paths, and resolved text for follow-up targeting.++## Auto Layout++```ts+slide.autoLayout(shapes, {+ direction,+ frame,+ align,+ horizontalGap,+ verticalGap,+ horizontalPadding,+ verticalPadding,+});+```++## Auto Layout Inline Type++```ts+type AutoLayoutOptions = {+ direction?: "horizontal" | "vertical";+ frame?:+ | "slide"+ | Shape+ | { left: number; top: number; width: number; height: number };+ align?:+ | "center"+ | "topLeft"+ | "topCenter"+ | "topRight"+ | "left"+ | "right"+ | "bottomLeft"+ | "bottomCenter"+ | "bottomRight";+ horizontalGap?: number | "auto";+ verticalGap?: number | "auto";+ horizontalPadding?: number;+ verticalPadding?: number;+};+```++## Speaker Notes++```ts+slide.speakerNotes.textFrame.setText(notesText);+slide.speakerNotes.setVisible(visible);+```++## Visual QA Loop++```ts+const preview = await slide.export({ format: "png", scale: 2 });+const layout = await slide.export({ format: "layout" });+const after = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart,notes",+ target: { id: slideAnchorId, beforeLines: 2, afterLines: 8 },+ maxChars: 4000,+});+```++Check the PNG for clipping, overlap, weak contrast, illegible text, bad image+crops, accidental rasterized labels, and off-canvas elements. Check the layout+export or inspect output for stable `name` values on important nodes.++## Cookbook++```ts+// Gradient background plus editable content.+slide.background.fill = "linear(180deg, slate-950 0%, blue-950 100%)";+const title = slide.shapes.add({+ geometry: "textbox",+ name: "title",+ position: { left: 72, top: 72, width: 760, height: 120 },+ fill: "none",+ line: { style: "solid", fill: "none", width: 0 },+});+title.text = "Editable headline";+title.text.style = { fontSize: 44, bold: true, color: "white" };+```++```ts+// Clone rhythm from another slide, then change content.+const next = sourceSlide.duplicate();+next.moveTo(3);+next.placeholders.getItem("title").text = "Updated section title";+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/speaker-notes.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/speaker-notes.spec.mdnew file mode 100644index 0000000..32d1e45--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/speaker-notes.spec.md@@ -0,0 +1,49 @@+# Speaker Notes++Speaker notes live on `slide.speakerNotes`.++## Set Text++```ts+const speakerNotes = slide.speakerNotes;+speakerNotes.textFrame.setText(notesText);++const paragraph = speakerNotes.textFrame.paragraphs.add();+paragraph.addRun(runText);+```++## Notes Text Inline Type++```ts+type NotesTextValue = string | string[] | StructuredTextInput;++type TextRunInput = {+ run: string;+ textStyle?: { bold?: boolean; italic?: boolean; fontSize?: number; color?: FillConfig };+};+```++## Visibility And Clearing++```ts+speakerNotes.setVisible(visible);+const visibleState = speakerNotes.isVisible();+speakerNotes.clear();+```++## Cookbook++```ts+// Structured presenter notes.+slide.speakerNotes.textFrame.setText([+ "Open with the customer problem, not the feature list.",+ "Call out the chart source before discussing the slope.",+ "Pause for questions before the implementation timeline.",+]);+slide.speakerNotes.setVisible(true);+```++```ts+// Append without deleting imported notes.+slide.speakerNotes.append("\nFollow-up: confirm launch date with PM.");+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/styles.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/styles.spec.mdnew file mode 100644index 0000000..d08a58b--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/styles.spec.md@@ -0,0 +1,85 @@+# Named Text Styles++`presentation.styles` stores reusable text styles for shapes and text ranges.++## Style Surface Map++| Need | API |+| --- | --- |+| Deck-level tokenized text style ids | `presentation.theme.textStyles({...})` |+| Slide-scoped generated text style ids | `slide.theme.textStyles({...})` |+| Explicit named styles by facade | `presentation.styles.add(name)` |++## Built-In Styles++```ts+const styles = presentation.styles;+const style = styles.get(styleName);+const summary = styles.describe(styleName);+const allStyles = styles.describe();+```++## Custom Style++```ts+const custom = presentation.styles.add(styleName);+custom.description = styleDescription;+custom.color = styleColor;+custom.bold = isBold;+custom.italic = isItalic;+custom.fontSize = fontSizePx;+custom.alignment = alignment;+```++## Named Style Facade Fields++```ts+type NamedStyleFacade = {+ description?: string;+ usageHint?: string;+ bold?: boolean;+ italic?: boolean;+ fontSize?: number;+ alignment?: "left" | "center" | "right" | "justify";+ underline?: string;+ color?: ColorConfig;+};+```++Use broader `TextStyleConfig` objects on `shape.text.style = { ... }`,+`presentation.theme.textStyles(...)`, and `slide.theme.textStyles(...)`.++## Use A Style++```ts+shape.text = textValue;+shape.text.style = styleName;++const range = shape.text.get(rangeText);+range.style = styleName;+```++Named styles are block-level for paragraph style assignments and range-level for selected text ranges.++## Cookbook++```ts+// Deck-level type scale.+const display = presentation.styles.add("Display");+display.fontSize = 52;+display.bold = true;+display.color = "#0f172a";+display.usageHint = "Hero and section titles";++const body = presentation.styles.add("Body");+body.fontSize = 20;+body.color = "#475569";+body.usageHint = "Readable body copy";+```++```ts+// Apply a style, then emphasize one range.+shape.text = "Revenue accelerated across enterprise accounts.";+shape.text.style = "Body";+shape.text.get("Revenue").style = "Display";+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/tables.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/tables.spec.mdnew file mode 100644index 0000000..985c34d--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/tables.spec.md@@ -0,0 +1,187 @@+# Tables++`slide.tables` creates and edits PowerPoint-style tables.++## Resolved From Inspect++```ts+const table = presentation.resolve("tb/d4e5f6a7");+table.cells.set(1, 2, "$4.2M");+table.getCell(1, 2).text.style = "Body Small";+table.borders.assign({ style: "solid", fill: "slate-200", width: 1 });+```++Use `presentation.inspect({ kind: "table", search })` to find the `tb/...`+anchor id. If an imported table resolves as an image, preserve it as an image or+rebuild it as a native table intentionally.++## Add Table++```ts+const table = slide.tables.add({+ rows,+ columns,+ left,+ top,+ width,+ height,+ columnTracks: [fr(2), fr(1), fixed(120)],+ values,+});+```++Primitive matrices and structured text runs are accepted for `values`. Use `columnTracks` with `fr(...)` and `fixed(...)` when a table should fill its frame with proportional columns. Use `columnWidths` only for explicit pixel widths.++## Table Inline Types++```ts+type TableAddOptions = {+ rows: number;+ columns: number;+ left?: number;+ top?: number;+ width?: number;+ height?: number;+ values?: TableCellValue[][];+ columnTracks?: TableColumnTrack[];+ columnWidths?: number[];+};++type TableColumnTrack =+ | { mode: "fr"; value: number }+ | { mode: "fixed"; value: number };++type TableCellValue = string | number | string[] | StructuredTextInput | Text;+```++## Cells++```ts+const cell = table.getCell(rowIndex, columnIndex);+cell.value = cellValue;+cell.fill = fillConfig;+cell.text.style = textStyleName;++table.cells.set(rowIndex, columnIndex, textObjectOrValue);+```++## Ranges And Merges++```ts+table.merge({+ startRow,+ endRow,+ startColumn,+ endColumn,+});++const range = table.cells.block(rangeConfig);+range.fill = fillConfig;+range.textStyle.bold = isBold;+range.textStyle.color = textColor;+range.textStyle.fontSize = fontSizePx;+range.borders = borderConfig;+```++## Range And Merge Inline Types++```ts+type TableMergeRange = {+ startRow: number;+ endRow: number;+ startColumn: number;+ endColumn: number;+};++type TableCellRangeConfig = {+ row: number;+ column: number;+ rowCount: number;+ columnCount: number;+};+```++## Style++```ts+table.style = tableStyleId;+table.styleOptions = tableStyleOptions;+table.columnTracks = [fr(2), fr(1), fixed(120)];+table.rows[0].height = headerHeightPx;+table.columns.get(columnIndex).width = columnWidthPx;+table.borders.assign(borderConfig);++table.cells.block({ row, column, rowCount, columnCount }).assign({+ fill,+ textStyle,+ borders,+ margins,+ anchor,+ horizontalOverflow,+});+```++## Style Inline Types++```ts+type TableStyleOptions = {+ headerRow?: boolean;+ totalRow?: boolean;+ firstColumn?: boolean;+ lastColumn?: boolean;+ bandedRows?: boolean;+ bandedColumns?: boolean;+};++type TableBorderLineConfig = {+ style?: "solid" | "dashed" | "dotted" | "dash-dot" | "dash-dot-dot" | string;+ width?: number;+ fill?: FillConfig;+ color?: FillConfig;+};+```++## Cookbook++```ts+// Compact KPI table.+const table = slide.tables.add({+ rows: 4,+ columns: 3,+ left: 96,+ top: 168,+ width: 680,+ height: 220,+ values: [+ ["Metric", "Current", "Delta"],+ ["Revenue", "$12.4M", "+18%"],+ ["Retention", "94%", "+3 pts"],+ ["Latency", "182 ms", "-22 ms"],+ ],+});+table.styleOptions = { headerRow: true, bandedRows: true };+table.getCell(0, 0).fill = "slate-950";+table.getCell(0, 1).fill = "slate-950";+table.getCell(0, 2).fill = "slate-950";+table.borders.assign({ style: "solid", fill: "slate-200", width: 1 });+```++```ts+// Spanning title row.+table.merge({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 });+table.getCell(0, 0).value = "Regional performance";+table.getCell(0, 0).text.style = "title";+```++```ts+// Highlight a cell range.+const riskRange = table.cells.block({+ row: 2,+ column: 2,+ rowCount: 2,+ columnCount: 1,+});+riskRange.fill = "amber-50";+riskRange.textStyle.color = "#92400e";+riskRange.textStyle.bold = true;+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/theme.spec.md b/skills/paper-fig/artifact_tool_docs/api/references/theme.spec.mdnew file mode 100644index 0000000..bc6bc38--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/theme.spec.md@@ -0,0 +1,85 @@+# Theme++Themes provide named colors and text style tokens.++## Color Scheme++```ts+presentation.theme.colorScheme = {+ name: themeName,+ themeColors,+};++const hexMap = presentation.theme.hexColorMap;+```++`themeColors` maps every theme color name to a color config value. Assigning+`presentation.theme.colorScheme` replaces the active scheme, so provide the+full map.++## Color Scheme Inline Type++```ts+type ThemeColorName =+ | "accent1" | "accent2" | "accent3" | "accent4" | "accent5" | "accent6"+ | "bg1" | "bg2" | "tx1" | "tx2" | "dk1" | "lt1" | "dk2" | "lt2"+ | "hlink" | "folHlink";++type ColorSchemeConfig = {+ name: string;+ themeColors: Record<ThemeColorName, ColorConfig>;+};+```++## Theme Colors In Content++```ts+const shape = slide.shapes.add({+ geometry,+ position,+ fill: themeColorName,+ line: { style: lineStyle, fill: lineColor, width: lineWidthPx },+});+```++## Text Styles++```ts+const styles = slide.theme.textStyles({+ [styleName]: textStyleConfig,+});+```++## Cookbook++```ts+// Business/product palette.+presentation.theme.colorScheme = {+ name: "Product Editorial",+ themeColors: {+ accent1: "#2563eb",+ accent2: "#0f766e",+ accent3: "#f59e0b",+ accent4: "#dc2626",+ accent5: "#7c3aed",+ accent6: "#16a34a",+ bg1: "#ffffff",+ bg2: "#f8fafc",+ tx1: "#0f172a",+ tx2: "#475569",+ dk1: "#000000",+ dk2: "#1e293b",+ lt1: "#ffffff",+ lt2: "#e2e8f0",+ hlink: "#2563eb",+ folHlink: "#7c3aed",+ },+};+```++```ts+// Use theme tokens in content so later theme changes flow through.+slide.background.fill = "bg1";+shape.fill = "accent1";+shape.text.style = { color: "tx1" };+```diff --git a/skills/paper-fig/artifact_tool_docs/api/references/tokens.md b/skills/paper-fig/artifact_tool_docs/api/references/tokens.mdnew file mode 100644index 0000000..0e31742--- /dev/null+++ b/skills/paper-fig/artifact_tool_docs/api/references/tokens.md@@ -0,0 +1,447 @@+# Presentation Token Reference++This reference covers the Tailwind-like tokens supported by presentation+shapes, text, and JSX. These are presentation tokens, not browser CSS.++## Where Tokens Work++| Surface | Token entry |+| --- | --- |+| Shape/box fill | `fill="sky-500"`, `fill="rose-500/80"` |+| Shape/box line | `line={{ style: "solid", fill: "slate-200", width: 1 }}` |+| Shape/box radius | `borderRadius="rounded-xl"` |+| Image radius | `borderRadius="rounded-2xl"` |+| Shape shadow | `shadow="shadow-md"` |+| Shape/box className | `className="bg-white rounded-xl shadow-sm"` |+| Text className | `className="text-slate-700 text-lg font-bold leading-tight"` |+| Imperative shape | `shape.className = "bg-sky-50 rounded-lg shadow"` |+| Imperative text | `shape.text.style = { className: "text-slate-800 text-xl leading-relaxed" }` |+| Text range | `shape.text.get("Total").className = "text-emerald-600 font-bold"` |++Explicit props override `className` on JSX nodes. For example,+`<box className="bg-slate-900" fill="white" />` uses the explicit `fill`.+`className` is only for visual/text tokens. Use real JSX props for layout:+`width`, `height`, `gap`, `padding`, `align`, and `justify`.++## Decision Table++| Need | Use |+| --- | --- |+| Common shape styling | `className="bg-white rounded-xl shadow-sm"` |+| Exact fill or gradient | `fill="#0f172a"` or `fill="linear(135deg, #fff 0%, sky-100 100%)"` |+| Exact line | `line={{ style: "solid", fill: "slate-200", width: 1 }}` |+| Common text styling | `className="text-slate-700 text-lg font-bold leading-tight"` |+| Exact text style | `style="font: 700 22px Inter; color: #334155; leading: 1.25; wrap: none"` |+| Inline emphasis | `<run textStyle={{ bold: true, color: "sky-600" }}>...</run>` |+| Layout | real props such as `gap={24}`, `padding={{ x: 32, y: 24 }}`, `align="center"` |++## Token Cookbook++Transparent overlay:++```tsx+<shape geometry="rect" width="fill" height="fill" fill="black/45" />+<paragraph className="text-white/80 text-xl">Readable over an image</paragraph>+```++Theme color with a transform:++```tsx+<box fill="accent1+18/90" />+<paragraph style="font: 700 18px Inter; color: tx1-10/85; wrap: none">+ Theme-aware text+</paragraph>+```++`+` lightens, `-` darkens, and `/` sets opacity. The suffix accepts unit+fractions, numbers, or percentages: `accent1+0.18/0.9`, `accent1+18/90`, and+`accent1+18%/90%` are equivalent.++Soft surface with exact line:++```tsx+<box+ fill="slate-50"+ line={{ style: "solid", fill: "slate-200", width: 1 }}+ borderRadius="rounded-2xl"+ shadow="shadow-sm"+/>+```++No fill, visible stroke:++```tsx+<shape+ geometry="ellipse"+ fill="none"+ line={{ style: "dashed", fill: "sky-500/70", width: 2 }}+ width={96}+ height={96}+/>+```++Gradient background plus transparent edge:++```tsx+<box fill="linear(135deg, #ffffff 0%, sky-100 58%, #ffffff/0 100%)" />+```++Radial highlight:++```tsx+<shape+ geometry="ellipse"+ fill="radial(white/80 0%, emerald-200/45 48%, emerald-700/0 100%)"+ width={420}+ height={260}+/>+```++Custom shadow:++```tsx+<box fill="white" borderRadius="rounded-2xl" shadow="2px 7px 19px #000000/17" />+```++Exact text style string:++```tsx+<paragraph style="font: 700 24px Inter; color: #334155; leading: 1.2; wrap: none">+ One-line label+</paragraph>+```++Tokenized text with arbitrary size and leading:++```tsx+<paragraph className="text-slate-950 text-[32px] font-bold leading-[1.12]">+ Precise headline+</paragraph>+```++## Color Tokens++Color tokens can be used directly as fill/color strings or through `bg-*` and+`text-*` class names.++```tsx+<box fill="slate-950" line={{ style: "solid", fill: "slate-700", width: 1 }} />+<box className="bg-sky-50 rounded-xl shadow-sm" />+<paragraph className="text-slate-700 text-lg">Readable text</paragraph>+```++Alpha suffixes are supported:++```tsx+<shape geometry="rect" fill="black/45" width="fill" height="fill" />+<paragraph className="text-white/80 text-xl">Muted overlay text</paragraph>+<box className="bg-rose-500/75 rounded-full" />+```++Theme colors and aliases are supported as color strings:++```tsx+<box fill="accent1" />+<box fill="accent2+20/80" />+<paragraph style="font: 600 18px Inter; color: text1/80; wrap: none">+ Uses the presentation theme text color+</paragraph>+```++Theme names:++```text+accent1, accent2, accent3, accent4, accent5, accent6,+bg1, bg2, tx1, tx2, dk1, dk2, lt1, lt2, hlink, folHlink+```++Aliases:++```text+background1 -> bg1+background2 -> bg2+text1 -> tx1+text2 -> tx2+dark1 -> dk1+dark2 -> dk2+light1 -> lt1+light2 -> lt2+```++Supported color names:++| Family | Tokens |+| --- | --- |+| Neutrals | `slate`, `gray`, `zinc`, `neutral`, `stone` |+| Warm | `red`, `orange`, `amber`, `yellow`, `lime` |+| Green/blue | `green`, `emerald`, `teal`, `cyan`, `sky`, `blue` |+| Violet/pink | `indigo`, `violet`, `purple`, `fuchsia`, `pink`, `rose` |+| Additional muted sets | `mauve`, `mist`, `olive`, `taupe` |+| Singletons | `black`, `white` |++For palette families, supported shades are:++```text+50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950+```++Use `family-shade`, for example `slate-50`, `slate-900`, `sky-500`,+`emerald-700`, or `rose-950`.++Alpha values accept percent-like numbers, percentages, or unit fractions:++```text+sky-500/80+sky-500/80%+sky-500/0.8+black/10+white/65+```++Hex, short hex, RGB, RGBA, and `transparent` are accepted:++```tsx+<box fill="#0F172A/12" />+<box fill="#0F172A1F" />+<box fill="rgb(15 23 42 / 12%)" />+<box fill="rgba(15, 23, 42, 0.12)" />+<shape geometry="rect" fill="transparent" />+```++Use `fill="none"` when the object should have no fill. Use+`fill="transparent"` or `#00000000` when the object should keep an editable+transparent solid fill. Express transparent and no-fill cases with the explicit+`fill` prop.++## Gradient Strings++Gradient fill strings are supported wherever `FillConfig` strings are accepted.+Use them for editable vector backgrounds and surfaces:++```tsx+<box fill="linear(135deg, #ffffff 0%, sky-100 55%, #ffffff/0 100%)" />+<shape geometry="ellipse" fill="radial(#ffffff 0%, emerald-200 48%, emerald-700 100%)" />+```++`linear(...)` accepts an optional angle first. `radial(...)` is a path gradient.+Stops use color plus optional offset percentages.++Offsets are optional; when omitted, stops are distributed evenly:++```tsx+<box fill="linear(slate-950, blue-800, sky-400)" />+```++Use explicit offsets when a narrow band or fade matters:++```tsx+<box fill="linear(90deg, black/80 0%, black/36 42%, black/0 100%)" />+<shape geometry="ellipse" fill="radial(accent1+35/55 0%, accent1/12 58%, accent1/0 100%)" />+```++## Shape Class Tokens++Shape and box `className` supports:++```text+bg-*+rounded+rounded-none+rounded-sm+rounded-md+rounded-lg+rounded-xl+rounded-2xl+rounded-3xl+rounded-full+shadow-none+shadow-sm+shadow+shadow-md+shadow-lg+shadow-xl+shadow-2xl+```++Example:++```tsx+<box+ width="fill"+ height={180}+ className="bg-white rounded-xl shadow-md"+ line={{ style: "solid", fill: "slate-200", width: 1 }}+/>+```++Radius values:++| Token | Radius |+| --- | ---: |+| `rounded-none` | `0px` |+| `rounded-sm` | `2px` |+| `rounded` | `4px` |+| `rounded-md` | `6px` |+| `rounded-lg` | `8px` |+| `rounded-xl` | `12px` |+| `rounded-2xl` | `16px` |+| `rounded-3xl` | `24px` |+| `rounded-full` | `9999px` |++Shadow tokens:++```text+shadow-none, shadow-sm, shadow, shadow-md, shadow-lg, shadow-xl, shadow-2xl+```++Custom shadow strings are also supported on `shadow`:++```tsx+<box shadow="2px 7px 19px #000000/17" />+```++## Text Class Tokens++Text `className` supports color, size, weight, italic, and leading:++```tsx+<paragraph className="text-slate-950 text-5xl font-bold leading-tight">+ Large headline+</paragraph>+<paragraph className="text-slate-600 text-lg leading-relaxed">+ Body copy with looser line spacing.+</paragraph>+```++Text sizes:++| Token | Size |+| --- | ---: |+| `text-xs` | `12px` |+| `text-sm` | `14px` |+| `text-base` | `16px` |+| `text-lg` | `18px` |+| `text-xl` | `20px` |+| `text-2xl` | `24px` |+| `text-3xl` | `30px` |+| `text-4xl` | `36px` |+| `text-5xl` | `48px` |+| `text-6xl` | `60px` |+| `text-[32px]` | arbitrary positive pixel size |++Font weight tokens:++| Bold flag | Tokens |+| --- | --- |+| `true` | `font-semibold`, `font-bold`, `font-black` |+| `false` | `font-thin`, `font-extralight`, `font-light`, `font-normal`, `font-medium`, `font-extrabold` |++Font weight maps to a boolean bold flag, not numeric weights. Use only+`font-semibold`, `font-bold`, or `font-black` when the text should be bold. Use+`font-normal` when the text should not be bold. `font-extrabold` maps to the+non-bold side because exact `500`/`600`/`700`/`800` differences are not+preserved.++`italic` sets italic text.++Leading tokens:++| Token | Line spacing |+| --- | ---: |+| `leading-none` | `1` |+| `leading-tight` | `1.25` |+| `leading-snug` | `1.375` |+| `leading-normal` | `1.5` |+| `leading-relaxed` | `1.625` |+| `leading-loose` | `2` |+| `leading-3` through `leading-10` | `12px` through `40px`, converted against current font size |+| `leading-[1.35]` | arbitrary multiplier |+| `leading-[150%]` | percentage multiplier |+| `leading-[28px]` | absolute pixels, converted against current font size |++When using absolute leading such as `leading-7` or `leading-[28px]`, put the+text size token before the leading token in the class string so conversion uses+the intended font size:++```tsx+<paragraph className="text-2xl leading-8">24px text with 32px leading</paragraph>+```++## Direct Props Versus Class Names++Use direct props when a value is part of the object schema:++```tsx+<shape+ geometry="rect"+ fill="emerald-500"+ line={{ style: "solid", fill: "emerald-700", width: 1 }}+ borderRadius="rounded-lg"+ shadow="shadow-sm"+ width={160}+ height={96}+/>+```++Use `className` when grouping common style tokens:++```tsx+<box className="bg-emerald-50 rounded-xl shadow-sm">+ <paragraph className="text-emerald-900 text-xl font-bold leading-tight">+ Compact token styling+ </paragraph>+</box>+```++Use object `style` for exact text settings that tokens do not cover:++```tsx+<paragraph+ style={{+ typeface: "Aptos",+ fontSize: 22,+ color: "slate-700",+ alignment: "center",+ lineSpacing: 1.2,+ }}+>+ Exact text config+</paragraph>+```++Use a compact style string when the exact settings fit on one line:++```tsx+<paragraph style="font: italic 600 20px Aptos; color: slate-700; leading: 1.25; align: center">+ Compact exact text config+</paragraph>+```++Supported text style declarations:++```text+font, size, font-size, family, font-family, typeface,+weight, font-weight, italic, font-style, color, fill,+leading, align, alignment, wrap, underline, inset, insets,+padding, autofit, auto-fit+```++Use `leading`, not `line-height`, in style strings.++## ClassName Scope++The token parser covers visual and text styling. JSX layout props represent+layout utilities such as padding, gap, width, height, flex flow, grid flow,+alignment, and distribution:++```tsx+<row width="fill" height="fill" gap={24} align="center" justify="between" />+<box padding={{ x: 32, y: 24 }} line={{ style: "solid", fill: "slate-200", width: 1 }} />+```++## Source References++- `src/models/presentation/utils/tailwind/*.ts`: token parsers.+- `src/models/presentation/utils/tailwind/tailwind-colors.generated.ts`: full+ color token map.+- `tests/presentation/tailwind-tokens.sanity.spec.ts`: visual token coverage.diff --git a/skills/paper-fig/assets/file-presentation.png b/skills/paper-fig/assets/file-presentation.pngnew file mode 100644index 0000000..5fce543Binary files /dev/null and b/skills/paper-fig/assets/file-presentation.png differdiff --git a/skills/paper-fig/container_tools/artifact_tool_utils.mjs b/skills/paper-fig/container_tools/artifact_tool_utils.mjsnew file mode 100644index 0000000..c2d5e34--- /dev/null+++ b/skills/paper-fig/container_tools/artifact_tool_utils.mjs@@ -0,0 +1,1077 @@+import { spawnSync } from "node:child_process";+import { createHash, randomUUID } from "node:crypto";+import { constants as fsConstants } from "node:fs";+import fs from "node:fs/promises";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { requireRuntimeModule } from "./runtime_helpers.mjs";++export const PREFERRED_PRESENTATION_FONTS = Object.freeze([+ "Helvetica Neue", "Helvetica", "Arial", "Aptos",+]);++// Keep the public font registries, not a snapshot of their families. Registration+// may happen after this helper is imported. Codex App supplies @napi-rs/canvas;+// other runtimes also expose skia-canvas directly.+const runtimeFontLibraries = await Promise.all([+ requireRuntimeModule("skia-canvas")+ .then(({ FontLibrary }) => ({ families: () => FontLibrary?.families }))+ .catch((error) => ({ error })),+ requireRuntimeModule("@napi-rs/canvas")+ .then(({ GlobalFonts }) => ({+ families: () => GlobalFonts?.families?.map((entry) => entry?.family),+ }))+ .catch((error) => ({ error })),+]);++function runtimePresentationFonts() {+ const families = [];+ const errors = [];+ let discovered = false;+ for (const library of runtimeFontLibraries) {+ try {+ const inventory = library.families?.();+ if (Array.isArray(inventory)) {+ discovered = true;+ families.push(...inventory);+ } else if (library.error) errors.push(library.error);+ } catch (error) { errors.push(error); }+ }+ if (discovered) return families;+ throw new Error(+ "Cannot discover presentation fonts from the supplied runtime. Preserve the source/user font with sourceFont or fontFamily, or supply actual availableFonts.",+ { cause: new AggregateError(errors, "Runtime font inventory unavailable") },+ );+}++export function resolvePresentationFont(options = {}) {+ const explicitFont = options.sourceFont ?? options.fontFamily;+ if (explicitFont !== undefined) return fontFamily(explicitFont);+ const candidates = options.availableFonts ?? runtimePresentationFonts();+ if (!Array.isArray(candidates)) {+ throw new Error("availableFonts must be an array of installed font family names.");+ }+ const available = new Map(candidates+ .filter((family) => typeof family === "string" && family.trim())+ .map((family) => [family.trim().toLowerCase(), family.trim()]));+ const preferred = PREFERRED_PRESENTATION_FONTS.find((family) =>+ available.has(family.toLowerCase()));+ if (preferred) return available.get(preferred.toLowerCase());+ const other = [...available.values()].sort()[0];+ if (other) return other;+ throw new Error("No available presentation font families were reported. Supply an installed family or preserve the source/user font explicitly.");+}++/** Chart text does not inherit the font assigned to surrounding slide shapes. */+export function applyPresentationChartFont(chart, options = {}) {+ if (!chart || typeof chart !== "object") throw new Error("A native chart is required");+ const family = resolvePresentationFont(options);+ const styles = [chart.legend?.textStyle, chart.dataLabels?.textStyle,+ chart.xAxis?.textStyle, chart.yAxis?.textStyle];+ if (typeof chart.title === "string" && chart.title.trim()) {+ styles.push(chart.titleTextStyle);+ }+ for (const axis of [chart.xAxis, chart.yAxis]) {+ if (typeof axis?.title?.text === "string" && axis.title.text.trim()) {+ styles.push(axis.title.textStyle);+ }+ }+ if (!styles.some(Boolean)) throw new Error("Chart has no supported text-style facade");+ for (const style of styles) {+ if (style) style.typeface = family;+ }+ return chart;+}++/** Paragraph-object indentation uses EMU; paragraph spacing uses 1/100 pt. */+export function makeNativeBulletParagraphs(items, options = {}) {+ if (!Array.isArray(items) || items.length === 0 ||+ items.some((item) => typeof item !== "string" || !item.trim())) {+ throw new Error("Native bullet items must be nonempty source-backed strings");+ }+ const allowed = new Set(["marginLeftPoints", "hangingPoints", "spaceAfterPoints", "bulletCharacter"]);+ if (!options || typeof options !== "object" || Array.isArray(options) ||+ Object.keys(options).some((key) => !allowed.has(key))) {+ throw new Error("Use explicit point-based native bullet options");+ }+ const { marginLeftPoints = 18, hangingPoints = 9, spaceAfterPoints = 8,+ bulletCharacter = "•" } = options;+ if (![marginLeftPoints, hangingPoints, spaceAfterPoints].every((value) =>+ typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1000) ||+ hangingPoints <= 0 || marginLeftPoints < hangingPoints ||+ typeof bulletCharacter !== "string" || [...bulletCharacter].length !== 1 || !bulletCharacter.trim()) {+ throw new Error("Invalid native bullet geometry or marker");+ }+ return items.map((item) => ({+ bulletCharacter,+ marginLeft: Math.round(marginLeftPoints * 12700),+ indent: -Math.round(hangingPoints * 12700),+ spaceAfter: Math.round(spaceAfterPoints * 100),+ runs: [item],+ }));+}++/** Ordinary requests use explicitTotalSlideCount; content-plus-cover is opt-in. */+export function resolvePresentationSlideCount(options = {}) {+ const kinds = [+ ["requestedContentSlideCount", "Requested content slide count"],+ ["explicitTotalSlideCount", "Explicit total slide count"],+ ["approvedFixedTemplateSlideCount", "Approved fixed-template slide count"],+ ];+ for (const [key, label] of kinds) {+ const value = options[key];+ if (value !== undefined &&+ (!Number.isSafeInteger(value) || value < 1 || value > 9999)) {+ throw new Error(`${label} must be a bounded positive integer`);+ }+ }+ if (options.explicitTotalSlideCount !== undefined &&+ options.approvedFixedTemplateSlideCount !== undefined &&+ options.explicitTotalSlideCount !== options.approvedFixedTemplateSlideCount) {+ throw new Error("Explicit total conflicts with the approved fixed-template slide count");+ }+ if (options.approvedFixedTemplateSlideCount !== undefined) {+ return options.approvedFixedTemplateSlideCount;+ }+ if (options.explicitTotalSlideCount !== undefined) return options.explicitTotalSlideCount;+ if (options.requestedContentSlideCount === undefined) return undefined;+ if (options.requestedContentSlideCount >= 9999) {+ throw new Error("Requested content slides and dedicated cover exceed the safe count limit");+ }+ return options.requestedContentSlideCount + 1;+}++const MAX_PRESENTATION_BYTES = 250 * 1024 * 1024;+const VALUE_FLAGS = new Map([+ ["--expected-aspect", /^\d{1,4}:\d{1,4}$/],+ ["--expected-slide-size-emu", /^\d{1,12},\d{1,12}$/],+ ["--expected-slide-count", /^[1-9]\d{0,3}$/],+ ["--require-native-table-slide", /^[1-9]\d{0,3}$/],+ ["--require-editorial-slide", /^[1-9]\d{0,3}$/],+ ["--approved-heading-slide", /^[1-9]\d{0,3}$/],+ ["--approved-bullet-slide", /^[1-9]\d{0,3}$/],+ ["--cover-role", /^(none|cover|explicit_hybrid)$/],+ ["--cover-word-limit", /^[1-9]\d{0,4}$/],+ ["--max-redundant-table-charts", /^\d{1,3}$/],+ ["--approved-redundant-chart-slide", /^[1-9]\d{0,3}$/],+ ["--max-content-prose-words", /^[1-9]\d{0,4}$/],+ ["--approved-dense-slide", /^[1-9]\d{0,3}$/],+ ["--approved-image-sha256", /^[a-fA-F0-9]{64}$/],+ ["--approved-icon-slide", /^[1-9]\d{0,3}$/],+ ["--approved-logo-sha256", /^[a-fA-F0-9]{64}$/],+ ["--max-logo-area", /^(?:0(?:\.\d{1,8})?|1(?:\.0{1,8})?)$/],+ ["--approved-logo-placement-slide", /^[1-9]\d{0,3}$/],+ ["--folio-mode", /^(none|actual_unpadded)$/],+]);+const BOOLEAN_FLAGS = new Set([+ "--allow-cover-chart",+ "--allow-cover-table",+ "--forbid-unapproved-decorative-icons",+ "--require-uniform-font-family",+ "--validate-bullet-geometry",+ "--validate-heading-fit",+ "--validate-heading-punctuation",+ "--require-logo-bottom-left",+]);++function requireAbsolute(value, label) {+ if (typeof value !== "string" || !path.isAbsolute(value)) {+ throw new Error(`${label} must be an absolute path`);+ }+ return path.resolve(value);+}++function isInside(root, child) {+ const relative = path.relative(root, child);+ return relative !== "" && !relative.startsWith(".." + path.sep) && relative !== ".." && !path.isAbsolute(relative);+}++async function inspectRegularFile(file, label, { executable = false } = {}) {+ const stat = await fs.lstat(file).catch(() => undefined);+ if (!stat || stat.isSymbolicLink() || !stat.isFile()) {+ throw new Error(`${label} must be an existing regular non-symlink file`);+ }+ if (executable && process.platform !== "win32") await fs.access(file, fsConstants.X_OK);+ return stat;+}++function fontFamily(value) {+ if (typeof value !== "string" || !value.trim() || value.trim().startsWith("-") ||+ value.length > 128 || /[\u0000-\u001f\u007f]/u.test(value)) {+ throw new Error("A font family must be a bounded, nonempty name");+ }+ return value.trim();+}++/** Freeze actual task typography; a source exception is never inferred from output. */+export async function normalizePresentationFontPolicy(value, runtime = {}) {+ if (value === undefined) return { basis: "unspecified", families: [], scriptFonts: {} };+ const input = value;+ if (!input || typeof input !== "object" || Array.isArray(input)) {+ throw new Error("Font policy must be an explicit object");+ }+ const keys = new Set(["basis", "families", "referencePath", "referenceSha256", "scriptFonts"]);+ if (Object.keys(input).some((key) => !keys.has(key))) {+ throw new Error("Unknown font-policy property");+ }+ const basis = input.basis ?? "default";+ if (!["default", "design", "user_request", "reference"].includes(basis)) {+ throw new Error("Font policy must name default, design, user_request, or reference basis");+ }+ let families;+ if (basis === "default") {+ if (input.families !== undefined) throw new Error("Default font must use the ordered installed-font resolver");+ families = [resolvePresentationFont()];+ } else {+ if (!Array.isArray(input.families) || input.families.length < 1 || input.families.length > 16) {+ throw new Error("Chosen typography needs explicit bounded font families");+ }+ families = [...new Set(input.families.map(fontFamily))];+ }+ let reference;+ if (basis === "reference") {+ const source = requireAbsolute(input.referencePath, "Typography reference");+ if (!/\.(pptx|pdf)$/iu.test(source) || !/^[a-f0-9]{64}$/u.test(input.referenceSha256 ?? "")) {+ throw new Error("Typography reference must be a SHA-bound PPTX or PDF");+ }+ const stat = await inspectRegularFile(source, "Typography reference");+ if (stat.size < 5 || stat.size > MAX_PRESENTATION_BYTES) throw new Error("Typography reference is not bounded");+ const bytes = await fs.readFile(source);+ const signatureValid = source.toLowerCase().endsWith(".pdf")+ ? bytes.subarray(0, 5).toString("ascii") === "%PDF-"+ : bytes[0] === 0x50 && bytes[1] === 0x4b;+ if (!signatureValid || createHash("sha256").update(bytes).digest("hex") !== input.referenceSha256) {+ throw new Error("Typography reference bytes differ from the approved source hash/type");+ }+ reference = { path: await fs.realpath(source), sha256: input.referenceSha256 };+ const python = requireAbsolute(runtime.pythonExecutable, "Reference-font inspection Python");+ await inspectRegularFile(await fs.realpath(python), "Reference-font inspection Python", { executable: true });+ const inspector = path.join(path.dirname(fileURLToPath(import.meta.url)), "inspect_presentation_layout_geometry.py");+ const checked = spawnSync(python, ["-B", inspector, reference.path, "--inspect-font-families"], {+ shell: false, encoding: "utf8", maxBuffer: 1024 * 1024, timeout: 60_000,+ env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" },+ });+ if (checked.error || checked.signal || checked.status !== 0) {+ throw processFailure("reference-fonts", checked, "Cannot verify font families in the supplied PPTX/PDF reference");+ }+ let sourceFonts;+ try { sourceFonts = JSON.parse(checked.stdout); } catch {+ throw processFailure("reference-fonts", checked, "Invalid reference-font inspection result");+ }+ const normalized = (family) => {+ const name = family.trim().replace(/^[A-Z]{6}\+/u, "")+ .replace(/-(?:BoldItalic|BoldOblique|Bold|Italic|Oblique|Regular|Roman)(?:MT)?$/iu, "")+ .replace(/[\s_-]+/gu, " ").toLowerCase();+ return ({ arialmt: "arial", helveticaneue: "helvetica neue" })[name] ?? name;+ };+ if (!Array.isArray(sourceFonts.normalized_font_families) ||+ families.some((family) => !sourceFonts.normalized_font_families.includes(normalized(family)))) {+ throw new Error("An approved font family is not used in the supplied typography reference");+ }+ reference.fontsVerifiedInEncodedText = true;+ } else if (input.referencePath !== undefined || input.referenceSha256 !== undefined) {+ throw new Error("Only reference typography may declare a source file");+ }+ const scripts = input.scriptFonts ?? {};+ if (!scripts || typeof scripts !== "object" || Array.isArray(scripts) ||+ Object.keys(scripts).some((script) => !["ea", "cs", "symbol"].includes(script))) {+ throw new Error("Script fallback is limited to ea, cs, or symbol glyphs");+ }+ const scriptFonts = Object.fromEntries(Object.entries(scripts).map(([script, family]) => [script, fontFamily(family)]));+ return { basis, families, scriptFonts, ...(reference ? { reference } : {}) };+}++function applyPresentationFontPolicy(policy, fontPolicy) {+ if (fontPolicy.basis === "unspecified") return;+ // Callers cannot bypass this with layoutArgs; only the validated task policy+ // supplies these flags. Script/source exceptions replace the old one-family test.+ if (fontPolicy.basis !== "default" || Object.keys(fontPolicy.scriptFonts).length) {+ for (let index = policy.length - 1; index >= 0; index -= 1) {+ if (policy[index] === "--require-uniform-font-family") policy.splice(index, 1);+ }+ }+ if (fontPolicy.basis === "default") {+ policy.push("--required-default-font-family", fontPolicy.families[0]);+ } else {+ for (const family of fontPolicy.families) policy.push("--approved-font-family", family);+ }+ for (const [script, family] of Object.entries(fontPolicy.scriptFonts)) {+ policy.push("--approved-script-font", `${script}=${family}`);+ }+}++function validateLayoutArgs(args) {+ if (!Array.isArray(args) || args.length > 96) {+ throw new Error("Layout policy must contain a bounded array of approved arguments");+ }+ const normalized = [];+ for (let index = 0; index < args.length; index += 1) {+ const flag = args[index];+ if (typeof flag !== "string") throw new Error("Layout policy arguments must be strings");+ if (BOOLEAN_FLAGS.has(flag)) {+ normalized.push(flag);+ continue;+ }+ const format = VALUE_FLAGS.get(flag);+ const value = args[index + 1];+ if (!format || typeof value !== "string" || !format.test(value)) {+ throw new Error(`Invalid or unsupported source-derived layout policy: ${flag}`);+ }+ normalized.push(flag, value);+ index += 1;+ }+ return normalized;+}++function normalizeCoverAndSlideCountPolicy(policy, options) {+ const roleIndexes = [];+ const countIndexes = [];+ for (let index = 0; index < policy.length; index += 1) {+ if (policy[index] === "--cover-role") roleIndexes.push(index);+ if (policy[index] === "--expected-slide-count") countIndexes.push(index);+ }+ if (roleIndexes.length > 1 || countIndexes.length > 1) {+ throw new Error("Cover role and expected slide count must not be declared more than once");+ }+ const role = roleIndexes.length ? policy[roleIndexes[0] + 1] : "none";+ if (roleIndexes.length === 0) policy.push("--cover-role", role);+ if ((policy.includes("--allow-cover-chart") || policy.includes("--allow-cover-table")) &&+ role !== "explicit_hybrid") {+ throw new Error("Cover charts and tables require an explicitly approved hybrid cover");+ }+ const count = resolvePresentationSlideCount(options);+ if (count !== undefined) {+ if (countIndexes.length && Number(policy[countIndexes[0] + 1]) !== count) {+ throw new Error("Expected slide count conflicts with content-plus-cover or explicit source total");+ }+ if (countIndexes.length === 0) policy.push("--expected-slide-count", String(count));+ }+ return policy;+}++function verifyRequiredNativeTableOwners(owners, layoutArgs) {+ if (owners === undefined) return;+ if (!Array.isArray(owners) || owners.length > 256 ||+ owners.some((owner) => !Number.isSafeInteger(owner) || owner < 1 || owner > 9999)) {+ throw new Error("Source-derived native-table owners must be bounded positive slide numbers");+ }+ const expected = new Set(owners);+ if (expected.size !== owners.length) {+ throw new Error("Source-derived native-table owners must not contain duplicate slides");+ }+ const declared = [];+ for (let index = 0; index < layoutArgs.length; index += 1) {+ if (layoutArgs[index] === "--require-native-table-slide") {+ declared.push(Number(layoutArgs[index + 1]));+ index += 1;+ }+ }+ if (declared.length !== expected.size || declared.some((owner) => !expected.has(owner)) ||+ new Set(declared).size !== expected.size) {+ throw new Error("Every source-required native-table owner must have exactly one validation policy");+ }+}++function normalizeRequiredSlideOwners(owners, label, { allowEmpty = false } = {}) {+ if (!Array.isArray(owners) || owners.length > 256 || (!allowEmpty && owners.length === 0) ||+ owners.some((owner) => !Number.isSafeInteger(owner) || owner < 1 || owner > 9999)) {+ throw new Error(`${label} must contain bounded positive slide numbers`);+ }+ if (new Set(owners).size !== owners.length) {+ throw new Error(`${label} must not contain duplicate slide numbers`);+ }+ return [...owners];+}++function normalizeNativeChartPolicy(options) {+ const declared = options.requiredNativeChartOwnerSlides !== undefined;+ const exceptionsDeclared = options.approvedSourceFigureExceptionSlides !== undefined;+ const targetDeclared = options.nativeChartTargetApplication !== undefined;+ const durableDeclared = options.requiredEmbeddedWorkbookChartOwnerSlides !== undefined;+ if (!declared) {+ if (exceptionsDeclared || targetDeclared || durableDeclared) {+ throw new Error("Native-chart target, durability, and exceptions require explicit chart owners");+ }+ return undefined;+ }+ const owners = normalizeRequiredSlideOwners(+ options.requiredNativeChartOwnerSlides,+ "Source-approved native-chart owners",+ { allowEmpty: true },+ );+ const exceptions = exceptionsDeclared+ ? normalizeRequiredSlideOwners(+ options.approvedSourceFigureExceptionSlides,+ "Explicit user-approved source-figure exceptions",+ { allowEmpty: true },+ )+ : [];+ if (exceptions.some((slide) => !owners.includes(slide))) {+ throw new Error("An approved source-figure exception must target a declared native-chart owner");+ }+ let targetApplication;+ if (targetDeclared) {+ targetApplication = options.nativeChartTargetApplication;+ if (typeof targetApplication !== "string" ||+ !["portable", "powerpoint"].includes(targetApplication)) {+ throw new Error("Native-chart target must be explicitly portable or PowerPoint");+ }+ }+ const durableOwners = durableDeclared+ ? normalizeRequiredSlideOwners(+ options.requiredEmbeddedWorkbookChartOwnerSlides,+ "Explicit durable embedded-workbook chart owners",+ { allowEmpty: true },+ )+ : [];+ if (durableOwners.some((slide) => !owners.includes(slide))) {+ throw new Error("A durable embedded-workbook owner must target a declared native-chart slide");+ }+ return { owners, exceptions, targetApplication, durableOwners };+}++function normalizeTemplateSourcePolicy(options) {+ const sourceDeclared = options.sourceTemplatePath !== undefined;+ const referencesDeclared = options.requiredTemplateReferenceSlides !== undefined;+ const ratioDeclared = options.minimumTemplateCoverageRatio !== undefined;+ const flags = [+ ["requireExactTemplateDimensions", "--require-exact-dimensions"],+ ["requireTemplatePlaceholderGeometry", "--require-placeholder-geometry"],+ ["requirePhotographicBackground", "--require-photographic-background"],+ ];+ const explicitFlags = [];+ for (const [option, flag] of flags) {+ if (options[option] !== undefined) {+ if (typeof options[option] !== "boolean") {+ throw new Error("Source-derived template requirements must be explicit boolean values");+ }+ if (options[option]) explicitFlags.push(flag);+ }+ }+ const explicitCoverage = referencesDeclared || ratioDeclared;+ if (!explicitCoverage && explicitFlags.length === 0) return undefined;+ if (!sourceDeclared || !referencesDeclared || !ratioDeclared) {+ throw new Error("Template fidelity requires an approved source, reference slides, and an explicit ratio");+ }+ const references = referencesDeclared+ ? normalizeRequiredSlideOwners(+ options.requiredTemplateReferenceSlides,+ "Source-approved template reference slides",+ )+ : [];+ let ratio;+ if (ratioDeclared) {+ ratio = options.minimumTemplateCoverageRatio;+ if (typeof ratio !== "number" || !Number.isFinite(ratio) || ratio < 0 || ratio > 1 ||+ references.length === 0) {+ throw new Error("Template coverage requires an explicit ratio from zero to one and reference slides");+ }+ }+ return {+ source: requireAbsolute(options.sourceTemplatePath, "Approved source template"),+ references,+ ratio,+ flags: explicitFlags,+ };+}++function processFailure(name, result, message = `${name} validator did not pass`) {+ let report;+ try { report = JSON.parse(result.stdout); } catch { /* Preserve non-JSON output below. */ }+ const details = [result.error?.message, result.stderr?.trim(), result.stdout?.trim()]+ .filter(Boolean).join("\n");+ const error = new Error(`${message}${details ? `\n${details.slice(0, 8000)}` : ""}`, {+ cause: result.error,+ });+ error.code = "PRESENTATION_VALIDATION_FAILED";+ error.validator = name;+ error.exitCode = result.status;+ error.signal = result.signal;+ error.stdout = result.stdout ?? "";+ error.stderr = result.stderr ?? "";+ error.report = report;+ return error;+}++function reportFailure(name, report, message) {+ return processFailure(name, { status: 0, stdout: JSON.stringify(report) }, message);+}++function executeValidator(python, validator, candidate, args, name) {+ const result = spawnSync(python, ["-B", validator, candidate, "--fail-on-findings", ...args], {+ shell: false,+ encoding: "utf8",+ maxBuffer: 2 * 1024 * 1024,+ timeout: 90_000,+ windowsHide: true,+ env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" },+ });+ if (result.error || result.signal || result.status !== 0) {+ throw processFailure(name, result);+ }+ let report;+ try {+ report = JSON.parse(result.stdout);+ } catch {+ throw processFailure(name, result, `${name} validator returned an invalid report`);+ }+ if (report.finding_count !== 0 || !Array.isArray(report.findings) || report.findings.length !== 0) {+ throw reportFailure(name, report, `${name} validator returned unresolved findings`);+ }+ const warnings = report.warnings ?? [];+ if (!Array.isArray(warnings) || warnings.some((warning) =>+ !warning || typeof warning !== "object" || typeof warning.kind !== "string")) {+ throw reportFailure(name, report, `${name} validator returned invalid review warnings`);+ }+ return { ...report, exitCode: result.status, findingCount: report.finding_count,+ warnings,+ ...(report.font_policy ? { fontPolicy: report.font_policy } : {}) };+}++function executeOptionalValidator(python, validator, args, name) {+ const result = spawnSync(python, ["-B", validator, ...args], {+ shell: false,+ encoding: "utf8",+ maxBuffer: 2 * 1024 * 1024,+ timeout: 90_000,+ windowsHide: true,+ env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" },+ });+ if (result.error || result.signal || result.status !== 0) {+ throw processFailure(name, result);+ }+ try {+ return { exitCode: result.status, report: JSON.parse(result.stdout) };+ } catch {+ throw processFailure(name, result, `${name} validator returned an invalid report`);+ }+}++function normalizeTableArithmeticContracts(value) {+ if (value === undefined) return [];+ if (!Array.isArray(value) || value.length > 200) {+ throw new Error("Table arithmetic contracts must be a bounded array");+ }+ const keys = ["slide", "table", "label_column", "total_row", "value_columns", "component_rows"];+ return value.map((contract) => {+ if (!contract || typeof contract !== "object" || Array.isArray(contract) ||+ Object.keys(contract).length !== keys.length ||+ Object.keys(contract).some((key) => !keys.includes(key))) {+ throw new Error("Table arithmetic contracts must declare exactly the supported coordinates");+ }+ for (const [key, minimum, maximum] of [+ ["slide", 1, 10000], ["table", 1, 100], ["label_column", 0, 99], ["total_row", 0, 1999],+ ]) {+ if (!Number.isSafeInteger(contract[key]) || contract[key] < minimum || contract[key] > maximum) {+ throw new Error("Invalid table arithmetic coordinates");+ }+ }+ for (const [key, minimum, maximum, bound] of [+ ["value_columns", 1, 100, 99], ["component_rows", 2, 2000, 1999],+ ]) {+ const values = contract[key];+ if (!Array.isArray(values) || values.length < minimum || values.length > maximum ||+ values.some((index) => !Number.isSafeInteger(index) || index < 0 || index > bound) ||+ new Set(values).size !== values.length) {+ throw new Error("Invalid table arithmetic row or column list");+ }+ }+ if (contract.value_columns.includes(contract.label_column) ||+ contract.component_rows.some((row) => row >= contract.total_row)) {+ throw new Error("Arithmetic components must precede the total and exclude the label column");+ }+ return { ...contract, value_columns: [...contract.value_columns], component_rows: [...contract.component_rows] };+ });+}++function executeNativeTableArithmeticValidator(python, validator, candidate, contracts, slideCount) {+ const args = [candidate];+ for (const contract of contracts) args.push("--contract-json", JSON.stringify(contract));+ const { report } = executeOptionalValidator(python, validator, args, "native-table-arithmetic");+ const count = (value) => Number.isSafeInteger(value) && value >= 0;+ if (report.schema_version !== "presentation-native-table-arithmetic.v1" || report.passed !== true ||+ report.slide_count !== slideCount || !count(report.native_table_count) ||+ !count(report.eligible_table_count) || report.eligible_table_count > report.native_table_count ||+ !count(report.checked_column_count) || !Array.isArray(report.checks) ||+ report.checks.length !== report.checked_column_count ||+ report.checks.some((check) => typeof check.passed !== "boolean" ||+ (check.explicit_contract === true && check.passed !== true) || !count(check.component_count) ||+ check.component_count < 2 || !count(check.slide) || check.slide < 1 || check.slide > slideCount) ||+ !Array.isArray(report.skipped_tables) || report.finding_count !== 0 ||+ !Array.isArray(report.findings) || report.findings.length !== 0) {+ throw reportFailure("native-table-arithmetic", report,+ "Native-table arithmetic validator returned inconsistent coverage or unresolved totals");+ }+ return { performed: true, ...report };+}++function executeNativeChartTitleValidator(python, validator, candidate, discovered) {+ const { report } = executeOptionalValidator(python, validator, [candidate], "native-chart-titles");+ if (report.schema_version !== "presentation-native-chart-titles.v1" || report.passed !== true ||+ report.slide_count !== discovered.slideCount || report.native_chart_count !== discovered.count ||+ !/^[a-f0-9]{64}$/u.test(report.presentation_sha256 ?? "") ||+ !Array.isArray(report.checks) || report.checks.length !== discovered.count ||+ report.checks.some((check) => !["absent", "present", "linked_title_unresolved", "explicitly_suppressed"].includes(check.status)) ||+ report.finding_count !== 0 || !Array.isArray(report.findings) || report.findings.length !== 0 ||+ report.native_powerpoint_verified !== false || report.source_text_emitted !== false) {+ throw reportFailure("native-chart-titles", report,+ "Native chart-title validator returned inconsistent coverage or unresolved placeholders");+ }+ return { performed: true, ...report };+}++function executeNativeChartValidator(python, validator, candidate, policy) {+ const args = [candidate, "--expected-chart-slides", policy.owners.join(",")];+ if (policy.targetApplication !== undefined) {+ args.push("--target-application", policy.targetApplication);+ }+ for (const slide of policy.durableOwners) {+ args.push("--require-embedded-workbook-slide", String(slide));+ }+ for (const slide of policy.exceptions) {+ args.push("--approved-source-figure", String(slide));+ }+ const { exitCode, report } = executeOptionalValidator(+ python, validator, args, "native-quantitative-chart",+ );+ const expected = [...policy.owners].sort((left, right) => left - right);+ const actual = report.expected_quantitative_chart_slides;+ if (report.passed !== true || report.failed_slide_count !== 0 ||+ report.validated_slide_count !== expected.length || !Array.isArray(actual) ||+ actual.length !== expected.length || actual.some((slide, index) => slide !== expected[index]) ||+ !Array.isArray(report.results) || report.results.length !== expected.length ||+ report.results.some((item) => item.approved_source_figure_exception === true &&+ !policy.exceptions.includes(item.slide_number)) ||+ (policy.targetApplication === "powerpoint" &&+ report.target_application !== policy.targetApplication) ||+ (policy.durableOwners.length > 0 && (!Array.isArray(report.required_embedded_workbook_slides) ||+ report.required_embedded_workbook_slides.length !== policy.durableOwners.length ||+ report.required_embedded_workbook_slides.some((slide, index) =>+ slide !== [...policy.durableOwners].sort((left, right) => left - right)[index])))) {+ throw reportFailure("native-quantitative-chart", report,+ "native-quantitative-chart validator returned unresolved source-owner findings");+ }+ return {+ report,+ exitCode,+ validatedSlideCount: expected.length,+ requiredOwnerSlides: expected,+ approvedSourceFigureExceptionSlides: [...policy.exceptions].sort((left, right) => left - right),+ ...(policy.targetApplication === undefined+ ? {}+ : { targetApplication: policy.targetApplication }),+ ...(policy.durableOwners.length === 0+ ? {}+ : { requiredEmbeddedWorkbookChartOwnerSlides: [...policy.durableOwners].sort(+ (left, right) => left - right,+ ) }),+ };+}++function discoverActualNativeCharts(python, validator, candidate) {+ const { exitCode, report } = executeOptionalValidator(+ python, validator, [candidate, "--discover-chart-slides"],+ "actual-native-chart-discovery",+ );+ const owners = report.chart_owner_slides;+ const counts = report.chart_counts;+ if (exitCode !== 0 || report.schema_version !== "owner-private.actual-native-chart-discovery.v1" ||+ !Array.isArray(owners) || typeof counts !== "object" || counts === null ||+ !Number.isSafeInteger(report.chart_count) || report.chart_count < 0 ||+ owners.some((owner) => !Number.isSafeInteger(owner) || owner < 1) ||+ new Set(owners).size !== owners.length ||+ owners.some((owner, index) => index > 0 && owners[index - 1] >= owner) ||+ Object.keys(counts).length !== owners.length ||+ owners.some((owner) => !Number.isSafeInteger(counts[String(owner)]) ||+ counts[String(owner)] < 1) ||+ owners.reduce((sum, owner) => sum + counts[String(owner)], 0) !== report.chart_count ||+ report.source_attachments_accessed !== false ||+ report.source_required_chart_owners_inferred !== false) {+ throw reportFailure("actual-native-chart-discovery", report,+ "actual-native-chart-discovery returned malformed or unsafe findings");+ }+ if (!Number.isSafeInteger(report.slide_count) || report.slide_count < 1) {+ throw reportFailure("actual-native-chart-discovery", report, "Actual presentation slide count is missing");+ }+ return { owners, count: report.chart_count, slideCount: report.slide_count };+}++function verifyFirstPartyImport(candidate, expectedSlideCount) {+ const helperUrl = new URL("./runtime_helpers.mjs", import.meta.url).href;+ const script = `+ import fs from "node:fs/promises";+ import { createHash } from "node:crypto";+ const [helperUrl, source] = process.argv.slice(1);+ const { importRuntimeModule } = await import(helperUrl);+ const before = createHash("sha256").update(await fs.readFile(source)).digest("hex");+ const { PresentationFile, FileBlob } = await importRuntimeModule("@oai/artifact-tool");+ const presentation = await PresentationFile.importPptx(await FileBlob.load(source));+ const after = createHash("sha256").update(await fs.readFile(source)).digest("hex");+ if (before !== after) throw new Error("Staged input changed during first-party import");+ process.stdout.write(JSON.stringify({ passed: true, slideCount: presentation.slides.items.length, sha256: after }));+ `;+ const result = spawnSync(process.execPath, ["--input-type=module", "-e", script, helperUrl, candidate], {+ shell: false, encoding: "utf8", maxBuffer: 2 * 1024 * 1024, timeout: 90_000,+ windowsHide: true, env: process.env,+ });+ if (result.error || result.signal || result.status !== 0) {+ throw processFailure("first-party-import", result,+ "Exact staged presentation failed first-party Artifact Tool import");+ }+ let report;+ try { report = JSON.parse(result.stdout); } catch {+ throw processFailure("first-party-import", result, "First-party importer returned an invalid report");+ }+ if (report.passed !== true || report.slideCount !== expectedSlideCount ||+ typeof report.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(report.sha256)) {+ throw reportFailure("first-party-import", report, "First-party import changed the expected slide inventory");+ }+ return { performed: true, ...report, runtimeNodeModules: process.env.RUNTIME_NODE_MODULES,+ nodeExecutable: process.execPath };+}++async function preparePortableChartData(python, packageDirectory, candidate, workspace, discovered, policy) {+ const helper = path.join(packageDirectory, "materialize_literal_chart_workbooks.py");+ await inspectRegularFile(helper, "Packaged literal-chart snapshot adapter");+ const staging = await fs.mkdtemp(path.join(workspace, ".chart-data-"));+ if (process.platform !== "win32") await fs.chmod(staging, 0o700);+ const prepared = path.join(staging, "candidate.pptx");+ const receiptPath = path.join(staging, "chart-data-snapshot.json");+ const args = [candidate, prepared, "--workspace", workspace, "--receipt", receiptPath];+ for (const slide of policy.durableOwners) {+ // An explicitly source-required workbook/formula cannot be replaced by a snapshot.+ args.push("--require-source-workbook-slide", String(slide));+ args.push("--require-source-formulas-slide", String(slide));+ }+ const { report } = executeOptionalValidator(python, helper, args, "chart-data-snapshot");+ const preparedStat = await inspectRegularFile(prepared, "Prepared chart-data presentation");+ const inputHash = createHash("sha256").update(await fs.readFile(candidate)).digest("hex");+ const preparedHash = createHash("sha256").update(await fs.readFile(prepared)).digest("hex");+ if (report.schema_version !== "experimental.literal-chart-workbook-snapshot.v1" ||+ report.conversion !== "chart_data_snapshot" || report.experimental !== true ||+ report.source_formulas_preserved !== false || report.source_workbook_preserved !== false ||+ report.new_formulas_describe_snapshot_only !== true ||+ report.input_sha256 !== inputHash || report.output_sha256 !== preparedHash ||+ report.output_bytes !== preparedStat.size || report.portable_chart_validation_passed !== true ||+ !Number.isSafeInteger(report.converted_chart_count) || report.converted_chart_count < 0 ||+ !Number.isSafeInteger(report.preserved_existing_workbook_chart_count) ||+ report.preserved_existing_workbook_chart_count < 0 ||+ report.converted_chart_count + report.preserved_existing_workbook_chart_count !== discovered.count ||+ JSON.stringify(report.detected_chart_owner_slides) !== JSON.stringify(discovered.owners) ||+ JSON.stringify(report.portable_validated_owner_slides) !== JSON.stringify(discovered.owners)) {+ throw reportFailure("chart-data-snapshot", report,+ "Chart-data snapshot did not preserve its exact data and provenance contract");+ }+ return { candidate: prepared, candidateStat: preparedStat, report };+}++function executeTemplateSourceValidator(python, validator, candidate, policy) {+ const args = [policy.source, candidate];+ for (const slide of policy.references) {+ args.push("--reference-slide", String(slide));+ }+ if (policy.ratio !== undefined) {+ args.push("--minimum-ratio", String(policy.ratio));+ }+ args.push(...policy.flags);+ const { exitCode, report } = executeOptionalValidator(+ python, validator, args, "template-source-fidelity",+ );+ if (report.schema_version !== "template_source_fidelity.v1" || report.passed !== true ||+ report.status !== "passed" || !Array.isArray(report.issue_codes) ||+ report.issue_codes.length !== 0 ||+ (policy.references.length > 0 && (!Number.isSafeInteger(report.reference_family_count) ||+ report.reference_family_count < 1 || report.reference_family_count > policy.references.length)) ||+ (policy.ratio !== undefined && (report.minimum_coverage_ratio !== policy.ratio ||+ typeof report.coverage_ratio !== "number" || report.coverage_ratio < policy.ratio))) {+ throw reportFailure("template-source-fidelity", report,+ "template-source-fidelity validator returned unresolved source-template findings");+ }+ return {+ report,+ exitCode,+ referenceFamilyCount: report.reference_family_count,+ matchedFamilyCount: report.matched_family_count,+ coverageRatio: report.coverage_ratio,+ minimumCoverageRatio: report.minimum_coverage_ratio,+ };+}++/**+ * Validate one staged presentation and atomically publish it without overwrite.+ * Paths, source-derived policies, and immutable validator locations are explicit.+ */+export async function finalizePresentation(options = {}) {+ for (const key of ["motionPolicy", "explanatoryMotion", "realWorldMotion", "verifiedStrokeMotion"]) {+ if (options[key] !== undefined) {+ throw new Error(`${key} is not supported by this presentation finalizer. Motion requires a separate supported workflow and validation.`);+ }+ }+ const workspacePath = requireAbsolute(options.workspaceDir, "Workspace");+ const workspaceStat = await fs.lstat(workspacePath).catch(() => undefined);+ if (!workspaceStat || !workspaceStat.isDirectory() || workspaceStat.isSymbolicLink()) {+ throw new Error("Workspace must be an existing non-symlink directory");+ }+ const workspace = await fs.realpath(workspacePath);+ const candidatePath = requireAbsolute(options.candidatePath, "Candidate presentation");+ const finalPath = requireAbsolute(options.finalPath, "Final presentation");+ if (!candidatePath.toLowerCase().endsWith(".pptx") || !finalPath.toLowerCase().endsWith(".pptx")) {+ throw new Error("Candidate and final presentation must both use the .pptx extension");+ }+ let candidateStat = await inspectRegularFile(candidatePath, "Candidate presentation");+ let candidate = await fs.realpath(candidatePath);+ if (!isInside(workspace, candidate) || candidateStat.size < 1 || candidateStat.size > MAX_PRESENTATION_BYTES) {+ throw new Error("Candidate presentation must be a bounded regular file inside its task workspace");+ }+ const parent = await fs.realpath(path.dirname(finalPath)).catch(() => undefined);+ const canonicalFinal = parent ? path.join(parent, path.basename(finalPath)) : undefined;+ if (!parent || !(parent === workspace || isInside(workspace, parent)) ||+ !canonicalFinal || !isInside(workspace, canonicalFinal)) {+ throw new Error("Final presentation must remain inside the real task workspace");+ }+ if (candidate === canonicalFinal) throw new Error("Candidate presentation must be staged separately");+ const originalCandidate = candidate;+ const originalCandidateStat = candidateStat;+ const originalCandidateHash = createHash("sha256").update(await fs.readFile(candidate)).digest("hex");+ if (await fs.lstat(finalPath).then(() => true).catch((error) => {+ if (error?.code === "ENOENT") return false;+ throw error;+ })) {+ throw new Error("Final presentation already exists and cannot be overwritten");+ }++ const integrity = requireAbsolute(options.integrityValidatorPath, "Package-integrity validator");+ const layout = requireAbsolute(options.layoutValidatorPath, "Presentation-layout validator");+ if (path.basename(integrity) !== "inspect_presentation_package_integrity.py" ||+ path.basename(layout) !== "inspect_presentation_layout_geometry.py") {+ throw new Error("Unexpected presentation validator filenames");+ }+ await inspectRegularFile(integrity, "Package-integrity validator");+ await inspectRegularFile(layout, "Presentation-layout validator");+ if (path.dirname(await fs.realpath(integrity)) !== path.dirname(await fs.realpath(layout))) {+ throw new Error("Presentation validators must come from the same immutable package");+ }+ const pythonPath = requireAbsolute(options.pythonExecutable, "Python executable");+ // Resolving the invocation path would bypass virtualenv/bundled environments.+ const python = pythonPath;+ await inspectRegularFile(await fs.realpath(python), "Python executable", { executable: true });+ const policy = normalizeCoverAndSlideCountPolicy(+ validateLayoutArgs(options.layoutArgs ?? []), options,+ );+ const fontPolicy = await normalizePresentationFontPolicy(options.fontPolicy, { pythonExecutable: python });+ if (fontPolicy.reference && [candidate, canonicalFinal].includes(fontPolicy.reference.path)) {+ throw new Error("A generated presentation cannot approve its own typography");+ }+ applyPresentationFontPolicy(policy, fontPolicy);+ verifyRequiredNativeTableOwners(options.requiredNativeTableOwnerSlides, policy);+ let chartPolicy = normalizeNativeChartPolicy(options);+ const sourceChartOwnersDeclared = chartPolicy !== undefined;+ const templatePolicy = normalizeTemplateSourcePolicy(options);+ const packageDirectory = path.dirname(await fs.realpath(integrity));+ const ownPackageDirectory = await fs.realpath(path.dirname(fileURLToPath(import.meta.url)));+ if (packageDirectory !== ownPackageDirectory) {+ throw new Error("Finalizer and validators must come from the same immutable skill package");+ }+ const chartValidator = path.join(packageDirectory, "native_quantitative_chart_gate.py");+ const chartTitleValidator = path.join(packageDirectory, "native_chart_title_gate.py");+ await inspectRegularFile(chartTitleValidator, "Packaged native-chart title validator");+ const tableArithmeticValidator = path.join(packageDirectory, "native_table_arithmetic_gate.py");+ await inspectRegularFile(tableArithmeticValidator, "Packaged native-table arithmetic validator");+ const tableArithmeticContracts = normalizeTableArithmeticContracts(options.tableArithmeticContracts);+ if (options.materializeLiteralChartWorkbooks !== undefined &&+ typeof options.materializeLiteralChartWorkbooks !== "boolean") {+ throw new Error("Literal-chart snapshot setting must be an explicit boolean");+ }+ if (options.verifyArtifactToolImport !== undefined && typeof options.verifyArtifactToolImport !== "boolean") {+ throw new Error("First-party import setting must be an explicit boolean");+ }+ let templateValidator;+ await inspectRegularFile(chartValidator, "Packaged native-quantitative-chart validator");+ if (templatePolicy !== undefined) {+ if (!templatePolicy.source.toLowerCase().endsWith(".pptx")) {+ throw new Error("The approved source template must be an existing PowerPoint file");+ }+ await inspectRegularFile(templatePolicy.source, "Approved source template");+ templatePolicy.source = await fs.realpath(templatePolicy.source);+ if ([candidate, canonicalFinal].includes(templatePolicy.source)) {+ throw new Error("A generated presentation cannot approve its own template fidelity");+ }+ templatePolicy.sha256 = createHash("sha256").update(await fs.readFile(templatePolicy.source)).digest("hex");+ templateValidator = path.join(packageDirectory, "template_source_fidelity_gate.py");+ await inspectRegularFile(templateValidator, "Packaged template-source-fidelity validator");+ }++ // Reject malformed packages before chart traversal or any opt-in conversion.+ let integrityResult = executeValidator(python, integrity, candidate, [], "package-integrity");+ const discoveredCharts = discoverActualNativeCharts(python, chartValidator, candidate);+ if (chartPolicy === undefined && discoveredCharts.owners.length > 0) {+ chartPolicy = {+ owners: discoveredCharts.owners,+ exceptions: [],+ targetApplication: undefined,+ durableOwners: [],+ };+ }+ if (chartPolicy !== undefined) {+ // A source-owner subset must never exempt other charts actually present in the file.+ chartPolicy.owners = [...new Set([...chartPolicy.owners, ...discoveredCharts.owners])]+ .sort((left, right) => left - right);+ }+ let chartDataPackaging;+ let chartResult;+ if (discoveredCharts.count > 0 && chartPolicy?.targetApplication !== "powerpoint" &&+ options.materializeLiteralChartWorkbooks === true) {+ try {+ // Healthy workbook-backed charts need neither repackaging nor changed bytes.+ chartResult = executeNativeChartValidator(python, chartValidator, candidate, chartPolicy);+ } catch (error) {+ if (error.code !== "PRESENTATION_VALIDATION_FAILED" || error.validator !== "native-quantitative-chart") {+ throw error;+ }+ // The adapter itself rejects broken references and source-required lineage;+ // only complete literal data can be converted into an honest new snapshot.+ const prepared = await preparePortableChartData(+ python, packageDirectory, candidate, workspace, discoveredCharts, chartPolicy,+ );+ candidate = prepared.candidate;+ candidateStat = prepared.candidateStat;+ chartDataPackaging = prepared.report;+ }+ }+ if (chartDataPackaging !== undefined) {+ integrityResult = executeValidator(python, integrity, candidate, [], "package-integrity");+ }+ const validationHash = createHash("sha256").update(await fs.readFile(candidate)).digest("hex");+ const chartTitleResult = executeNativeChartTitleValidator(python, chartTitleValidator, candidate, discoveredCharts);+ const layoutResult = executeValidator(python, layout, candidate, policy, "presentation-layout");+ if (fontPolicy.basis !== "unspecified" &&+ (layoutResult.fontPolicy?.performed !== true || layoutResult.fontPolicy?.passed !== true)) {+ throw reportFailure("presentation-layout", layoutResult, "Delivered typography was not validated");+ }+ // Unconditional: source-declared contracts add coverage, never replace the+ // discovery of plainly additive totals in the actual delivered native tables.+ const tableArithmeticResult = executeNativeTableArithmeticValidator(+ python, tableArithmeticValidator, candidate, tableArithmeticContracts, discoveredCharts.slideCount,+ );+ if (chartResult === undefined && chartPolicy !== undefined && chartPolicy.owners.length > 0) {+ chartResult = executeNativeChartValidator(python, chartValidator, candidate, chartPolicy);+ }+ const templateResult = templatePolicy === undefined+ ? undefined+ : executeTemplateSourceValidator(python, templateValidator, candidate, templatePolicy);+ const firstPartyImport = options.verifyArtifactToolImport === false+ ? { performed: false, passed: null, reason: "explicitly_not_requested" }+ : verifyFirstPartyImport(candidate, discoveredCharts.slideCount);+ if (fontPolicy.reference && createHash("sha256").update(+ await fs.readFile(fontPolicy.reference.path),+ ).digest("hex") !== fontPolicy.reference.sha256) {+ throw new Error("Approved typography reference changed during finalization");+ }+ if (templatePolicy && createHash("sha256").update(+ await fs.readFile(templatePolicy.source),+ ).digest("hex") !== templatePolicy.sha256) {+ throw new Error("Approved source template changed during finalization");+ }+ const originalAfter = await fs.lstat(originalCandidate);+ if (!originalAfter.isFile() || originalAfter.isSymbolicLink() ||+ originalAfter.ino !== originalCandidateStat.ino || originalAfter.size !== originalCandidateStat.size ||+ originalAfter.mtimeMs !== originalCandidateStat.mtimeMs ||+ createHash("sha256").update(await fs.readFile(originalCandidate)).digest("hex") !== originalCandidateHash) {+ throw new Error("Original presentation changed during finalization");+ }+ const beforePublish = await fs.lstat(candidate);+ if (!beforePublish.isFile() || beforePublish.isSymbolicLink() ||+ beforePublish.ino !== candidateStat.ino || beforePublish.size !== candidateStat.size ||+ beforePublish.mtimeMs !== candidateStat.mtimeMs ||+ createHash("sha256").update(await fs.readFile(candidate)).digest("hex") !== validationHash) {+ throw new Error("Candidate presentation changed during validation");+ }+ const stage = path.join(parent, `.${path.basename(finalPath)}.${randomUUID()}.validated`);+ const receiptRequested = options.receiptPath+ ? requireAbsolute(options.receiptPath, "Private validation receipt")+ : path.join(path.dirname(candidate), `.${path.basename(finalPath)}.validation.json`);+ const receiptParent = await fs.realpath(path.dirname(receiptRequested)).catch(() => undefined);+ const receiptPath = receiptParent+ ? path.join(receiptParent, path.basename(receiptRequested))+ : undefined;+ if (!receiptParent || !receiptPath || !isInside(workspace, receiptPath) ||+ receiptParent === parent || isInside(parent, receiptParent)) {+ throw new Error("Private validation receipt must stay inside the task workspace and outside final output");+ }+ let published = false;+ let stagedIdentity;+ try {+ await fs.copyFile(candidate, stage, fsConstants.COPYFILE_EXCL);+ if (process.platform !== "win32") await fs.chmod(stage, 0o600);+ stagedIdentity = await fs.lstat(stage);+ const bytes = await fs.readFile(stage);+ const sha256 = createHash("sha256").update(bytes).digest("hex");+ if (sha256 !== validationHash) {+ throw new Error("Prepared presentation differs from its validated bytes");+ }+ if (firstPartyImport.performed && firstPartyImport.sha256 !== sha256) {+ throw new Error("Prepared presentation differs from the first-party imported bytes");+ }+ if (chartTitleResult.presentation_sha256 !== sha256) {+ throw new Error("Prepared presentation differs from its chart-title validated bytes");+ }+ await fs.link(stage, finalPath);+ published = true;+ const finalBytes = await fs.readFile(finalPath);+ if (createHash("sha256").update(finalBytes).digest("hex") !== sha256) {+ throw new Error("Published presentation hash differs from its validated staged bytes");+ }+ const receipt = {+ schemaVersion: "presentation-finalization.v1",+ finalSha256: sha256,+ byteCount: bytes.byteLength,+ packageIntegrity: integrityResult,+ presentationLayout: layoutResult,+ fontSelection: {+ basis: fontPolicy.basis,+ approvedFamilies: fontPolicy.families,+ scriptFonts: fontPolicy.scriptFonts,+ referenceSha256: fontPolicy.reference?.sha256 ?? null,+ referenceFontsVerifiedInEncodedText: fontPolicy.reference?.fontsVerifiedInEncodedText ?? false,+ ...layoutResult.fontPolicy,+ },+ firstPartyImport,+ nativeTableArithmetic: tableArithmeticResult,+ nativeChartTitles: chartTitleResult,+ sourceDerivedPolicyFlags: policy,+ nativeChartValidation: {+ detectedOwnerSlides: discoveredCharts.owners,+ detectedChartCount: discoveredCharts.count,+ targetApplication: chartPolicy === undefined+ ? null+ : chartPolicy.targetApplication ?? "portable",+ sourceChartOwnersExplicitlyDeclared: sourceChartOwnersDeclared,+ validatorRan: chartResult !== undefined,+ passed: chartResult === undefined ? discoveredCharts.count === 0 : chartResult.exitCode === 0,+ },+ ...(chartResult === undefined ? {} : { nativeQuantitativeCharts: chartResult }),+ ...(chartDataPackaging === undefined ? {} : { chartDataPackaging }),+ ...(templateResult === undefined ? {} : { sourceTemplateFidelity: {+ ...templateResult, sourceSha256: templatePolicy.sha256,+ } }),+ };+ await fs.writeFile(receiptPath, JSON.stringify(receipt, null, 2) + "\n", {+ encoding: "utf8",+ mode: 0o600,+ flag: "wx",+ });+ return { finalPath, receiptPath, ...receipt };+ } catch (error) {+ if (published) {+ const current = await fs.lstat(finalPath).catch(() => undefined);+ // Do not remove a user save or other file that replaced our published link.+ if (current?.isFile() && !current.isSymbolicLink() &&+ current.dev === stagedIdentity.dev && current.ino === stagedIdentity.ino) {+ await fs.unlink(finalPath).catch(() => {});+ }+ }+ throw error;+ } finally {+ await fs.unlink(stage).catch(() => {});+ }+}diff --git a/skills/paper-fig/container_tools/create_montage.py b/skills/paper-fig/container_tools/create_montage.pynew file mode 100644index 0000000..c8e6d10--- /dev/null+++ b/skills/paper-fig/container_tools/create_montage.py@@ -0,0 +1,300 @@+#!/usr/bin/env python3+# Copyright (c) OpenAI. All rights reserved.+import argparse+import re+import sys+import tempfile+from math import ceil+from os import listdir+from os.path import basename, dirname, expanduser, isfile, join, splitext+from typing import Literal++SCRIPT_DIR = dirname(__file__)+if SCRIPT_DIR not in sys.path:+ sys.path.insert(0, SCRIPT_DIR)++from ensure_raster_image import SUPPORTED_EXTS, ensure_raster_image # type: ignore+from PIL import Image, ImageDraw, ImageFont, ImageOps+++def _make_placeholder(w: int, h: int) -> Image.Image:+ """Create a visible placeholder tile with a light gray fill and a red X cross."""+ ph = Image.new("RGBA", (w, h), (220, 220, 220, 255))+ ph_draw = ImageDraw.Draw(ph)+ line_color = (180, 0, 0, 255)+ ph_draw.line([(0, 0), (ph.width - 1, ph.height - 1)], fill=line_color, width=3)+ ph_draw.line([(ph.width - 1, 0), (0, ph.height - 1)], fill=line_color, width=3)+ return ph+++def _load_images_with_placeholders(+ input_files: list[str], retain_converted_files: bool, fail_on_image_error: bool = False+) -> tuple[list[str], list[Image.Image | None]]:+ labels = [basename(p) for p in input_files]+ images: list[Image.Image | None] = []+ if retain_converted_files:+ for p in input_files:+ try:+ images.append(Image.open(ensure_raster_image(p)))+ except Exception as e:+ if fail_on_image_error:+ raise+ print(f'Warning: Failed to convert or load image "{p}": {e}')+ images.append(None)+ else:+ with tempfile.TemporaryDirectory(prefix="montage_convert_") as tmp_conv:+ for p in input_files:+ try:+ with Image.open(ensure_raster_image(p, tmp_conv)) as image:+ images.append(image.copy())+ except Exception as e:+ if fail_on_image_error:+ raise+ print(f'Warning: Failed to convert or load image "{p}": {e}')+ images.append(None)+ return labels, images+++def _natural_key(s: str) -> list:+ """Key function for natural sorting (e.g., Slide2 before Slide10)."""+ return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", s)]+++def create_montage(+ input_files: list[str],+ output_file: str,+ num_col: int,+ cell_w: int,+ cell_h: int,+ gap: int,+ label_mode: Literal["number", "filename", "none"],+ retain_converted_files: bool = False,+ fail_on_image_error: bool = False,+) -> None:+ """Build a montage with a fixed number of columns.++ Each cell has size `cell_w` x `cell_h`. Every input image is resized isotropically to fit inside+ the cell. `gap` controls spacing around and between cells (outer margin equals gap).+ Label behavior is controlled by `label_mode` which can be one of:+ - "none": no labels are drawn+ - "number": draw a 1-based index beneath each image+ - "filename": draw the filename (no directory) beneath each image+ """++ if num_col <= 0:+ raise ValueError("num_col must be positive")+ if cell_w <= 0 or cell_h <= 0:+ raise ValueError("cell_w and cell_h must be positive")++ labels, images = _load_images_with_placeholders(+ input_files=input_files,+ retain_converted_files=retain_converted_files,+ fail_on_image_error=fail_on_image_error,+ )++ num_images = len(images)+ num_valid = sum(1 for im in images if im is not None)+ if num_valid == 0:+ raise ValueError("No valid images to render.")+ if num_valid < num_images:+ cell_size = round(min(cell_w, cell_h) * 0.6)+ placeholder = _make_placeholder(cell_size, cell_size)+ else:+ placeholder = None+ cols = num_col+ rows = ceil(num_images / cols)++ temp_canvas = Image.new("RGB", (10, 10), (255, 255, 255))+ temp_draw = ImageDraw.Draw(temp_canvas)++ # Choose a readable default font size relative to cell height+ font: ImageFont.FreeTypeFont | ImageFont.ImageFont+ try:+ # Attempt to use a common system font for clarity; fallback to default+ font_size = max(12, min(36, int(cell_h * 0.12)))+ font = ImageFont.truetype("arial.ttf", font_size)+ except Exception:+ font = ImageFont.load_default()+ # Adjust default font effect size estimate+ font_size = 12++ draw_labels = label_mode != "none"+ label_height = 0+ if draw_labels:+ # Height is approximately constant across strings for a given font+ # Use 'Ag' to approximate ascent ('A') and descender ('g') for filename text+ sample_text = "1" if label_mode == "number" else "Ag"+ lbbox = temp_draw.textbbox((0, 0), sample_text, font=font)+ label_height = ceil(lbbox[3] - lbbox[1]) + 6++ row_h = cell_h + label_height++ canvas_w = cols * cell_w + (cols + 1) * gap+ canvas_h = rows * row_h + (rows + 1) * gap+ # Light grey canvas background as in typical slide sorter view+ canvas = Image.new("RGB", (canvas_w, canvas_h), (242, 242, 242))+ draw = ImageDraw.Draw(canvas)++ for idx, img in enumerate(images):+ col = idx % cols+ row = idx // cols++ # Top-left corner of the cell including outer margin and gaps+ x0 = gap + col * (cell_w + gap)+ y0 = gap + row * (row_h + gap)++ # Fit the image within the cell while preserving aspect ratio+ if label_mode == "number":+ label = str(idx + 1)+ elif label_mode == "filename":+ label = labels[idx]+ else:+ label = ""++ if draw_labels:+ bbox = draw.textbbox((0, 0), label, font=font)+ text_w = bbox[2] - bbox[0]+ else:+ text_w = 0++ if img:+ resized = ImageOps.contain(+ img.convert("RGBA"),+ (cell_w, cell_h),+ method=Image.Resampling.LANCZOS,+ )+ else:+ print(f"Warning: Using placeholder for invalid image at row={row + 1}, col={col + 1}")+ assert placeholder is not None+ resized = placeholder++ paste_x = x0 + (cell_w - resized.width) // 2+ paste_y = y0 + (cell_h - resized.height) // 2+ canvas.paste(+ resized,+ (paste_x, paste_y),+ mask=resized.split()[3] if resized.mode == "RGBA" else None,+ )++ border_color = (160, 160, 160)+ bw = 1+ draw.rectangle(+ [+ paste_x - bw,+ paste_y - bw,+ paste_x + resized.width,+ paste_y + resized.height,+ ],+ outline=border_color,+ width=bw,+ )++ if draw_labels:+ tx = x0 + round((cell_w - text_w) / 2)+ ty = y0 + cell_h + 3+ draw.text((tx, ty), label, font=font, fill=(0, 0, 0))++ canvas.save(output_file)+ print(f"Montage saved to {output_file}")+++def main() -> None:+ parser = argparse.ArgumentParser(+ description=(+ "Create a montage with a fixed number of columns. "+ "Each image is resized isotropically to fit inside a cell of size (cell_width x cell_height)."+ )+ )+ group = parser.add_mutually_exclusive_group(required=True)+ group.add_argument("--input_files", nargs="+", help="List of input image file paths")+ group.add_argument("--input_dir", help="Directory containing input images")+ parser.add_argument(+ "--output_file",+ required=True,+ help=(+ "Path to save the output montage image. The format is inferred from the file extension."+ ),+ )+ parser.add_argument(+ "--num_col",+ type=int,+ default=5,+ help="Number of images per row (default: 5)",+ )+ parser.add_argument(+ "--cell_width",+ type=int,+ default=400,+ help="Container width in pixels for each image (default: 400)",+ )+ parser.add_argument(+ "--cell_height",+ type=int,+ default=225,+ help="Container height in pixels for each image (default: 225)",+ )+ parser.add_argument(+ "--gap",+ type=int,+ default=16,+ help="Gap in pixels between images and canvas margins (default: 16)",+ )+ parser.add_argument(+ "--label_mode",+ choices=["number", "filename", "none"],+ default="number",+ help=(+ "Label mode: 'number' to draw 1-based indices (default), 'filename' to use the "+ "image's filename (no directory), or 'none' for no labels"+ ),+ )+ parser.add_argument(+ "--retain_converted_files",+ action="store_true",+ default=False,+ help=(+ "If set, write converted images (e.g., SVG->PNG, WDP->PNG) next to the original files "+ "instead of a temporary directory."+ ),+ )+ parser.add_argument(+ "--fail_on_image_error",+ action="store_true",+ default=False,+ help=(+ "If set, fail immediately when any image conversion/loading fails (no placeholders). "+ "By default, failures are tolerated and placeholders are used."+ ),+ )+ args = parser.parse_args()++ output_path = expanduser(args.output_file)+ if args.input_files:+ input_files = [expanduser(p) for p in args.input_files]+ else:+ input_dir = expanduser(args.input_dir)+ names = sorted(listdir(input_dir), key=_natural_key)+ dir_entries = [join(input_dir, f) for f in names]+ input_files = [+ p for p in dir_entries if isfile(p) and splitext(p)[1].lower() in SUPPORTED_EXTS+ ]+ if not input_files:+ raise ValueError(+ "No image files with supported extensions were found in the specified directory."+ )++ create_montage(+ input_files=input_files,+ output_file=output_path,+ num_col=args.num_col,+ cell_w=args.cell_width,+ cell_h=args.cell_height,+ gap=args.gap,+ label_mode=args.label_mode,+ retain_converted_files=args.retain_converted_files,+ fail_on_image_error=args.fail_on_image_error,+ )+++if __name__ == "__main__":+ main()diff --git a/skills/paper-fig/container_tools/ensure_raster_image.py b/skills/paper-fig/container_tools/ensure_raster_image.pynew file mode 100644index 0000000..82b6641--- /dev/null+++ b/skills/paper-fig/container_tools/ensure_raster_image.py@@ -0,0 +1,224 @@+#!/usr/bin/env python3+"""Copyright (c) OpenAI. All rights reserved.++Ensures input images are rasterized, converting to PNG when needed. Primarily used to+preview image assets extracted from PowerPoint files.+++Dependencies used by this tool:+- Codex runtime Node + sharp: SVG/SVGZ rasterization+- Codex runtime Poppler + pdf2image: PDF rasterization (first page)+- Codex runtime Pillow: TIFF/JPEG XR output bridging+- libheif-examples: heif-convert for HEIC/HEIF -> PNG+- jxr-tools (or libjxr-tools on older distros): JxrDecApp for JPEG XR (JXR/WDP)+"""++import argparse+import gzip+import sys+import tempfile+from os import listdir+from os.path import basename, dirname, expanduser, isfile, join, splitext+from subprocess import run++from pdf2image import convert_from_path+from PIL import Image++SCRIPT_DIR = dirname(__file__)+if SCRIPT_DIR not in sys.path:+ sys.path.insert(0, SCRIPT_DIR)++from runtime_helpers import runtime_bin_dir, runtime_binary, runtime_node # noqa: E402++RASTER_EXTS = {+ ".png",+ ".jpg",+ ".jpeg",+ ".bmp",+ ".gif",+ ".tif",+ ".tiff",+ ".webp",+}++CONVERTIBLE_EXTS = {+ # Windows metafiles (and compressed variants)+ ".emf",+ ".wmf",+ ".emz",+ ".wmz",+ # SVG+ ".svg",+ ".svgz",+ # JPEG XR / HD Photo+ ".wdp",+ ".jxr",+ # HEIF family+ ".heic",+ ".heif",+ # Page-description formats (rasterize first page)+ ".pdf",+ ".eps",+ ".ps",+}++SUPPORTED_EXTS = RASTER_EXTS | CONVERTIBLE_EXTS+++def _pillow_convert(src_path: str, dst_path: str) -> None:+ with Image.open(src_path) as img:+ img.seek(0)+ if img.mode not in ("1", "L", "LA", "P", "RGB", "RGBA"):+ img = img.convert("RGBA")+ img.save(dst_path, format="PNG")+++def _run_node_helper(helper_name: str, args: list[str]) -> None:+ run(+ [runtime_node(), join(SCRIPT_DIR, helper_name), *args],+ check=True,+ )+++def _rasterize_svg(src_path: str, dst_path: str) -> None:+ _run_node_helper("rasterize_svg.mjs", ["--input", src_path, "--output", dst_path])+++def _rasterize_svgz(src_path: str, dst_path: str) -> None:+ with tempfile.TemporaryDirectory(prefix="svgz_raster_") as tmpdir:+ decompressed = join(tmpdir, basename(splitext(src_path)[0]) + ".svg")+ with gzip.open(src_path, "rb") as zin, open(decompressed, "wb") as zout:+ zout.write(zin.read())+ _rasterize_svg(decompressed, dst_path)+++def _rasterize_pdf_first_page(src_path: str, dst_path: str) -> None:+ pages = convert_from_path(+ src_path,+ dpi=200,+ first_page=1,+ last_page=1,+ fmt="png",+ poppler_path=runtime_bin_dir("pdfinfo", "pdftoppm"),+ )+ if not pages:+ raise RuntimeError("No PDF pages were rendered: " + src_path)+ pages[0].save(dst_path, format="PNG")+++def _unsupported_format(path: str, reason: str) -> None:+ raise RuntimeError(f"Unsupported image format for rasterization: {path}. {reason}")+++def ensure_raster_image(path: str, out_dir: str | None = None) -> str:+ """Return a raster image path for the given input, converting when needed.++ - SVG/SVGZ are rasterized via the bundled Node runtime and sharp+ - PDFs are rasterized via bundled Poppler through pdf2image+ - WDP/JXR are decoded via JxrDecApp and bridged to PNG via Pillow+ - Known raster formats are returned as-is++ Raises ValueError if the extension is not supported.+ """+ base, ext = splitext(path)+ ext_lower = ext.lower()+ out_dir = out_dir or dirname(path)+ out_path = join(out_dir, basename(base) + ".png")++ # Convertible formats+ if ext_lower in (".emf", ".wmf"):+ _unsupported_format(+ path, "No equivalent standalone EMF/WMF converter exists in the Codex runtime bundle."+ )++ if ext_lower in (".emz", ".wmz"):+ _unsupported_format(+ path, "No equivalent standalone EMF/WMF converter exists in the Codex runtime bundle."+ )++ if ext_lower == ".svg":+ _rasterize_svg(path, out_path)+ if isfile(out_path):+ return out_path+ raise RuntimeError("SVG rasterization succeeded but output file not found: " + out_path)++ if ext_lower == ".svgz":+ _rasterize_svgz(path, out_path)+ if isfile(out_path):+ return out_path+ raise RuntimeError("SVGZ rasterization succeeded but output file not found: " + out_path)++ if ext_lower in (".wdp", ".jxr"):+ tmp_tiff = join(out_dir, basename(base) + ".tiff")+ run([runtime_binary("JxrDecApp"), "-i", path, "-o", tmp_tiff], check=True)+ _pillow_convert(tmp_tiff, out_path)+ if isfile(out_path):+ return out_path+ raise RuntimeError("JPEG XR decode succeeded but PNG not found: " + out_path)++ if ext_lower in (".heic", ".heif"):+ # Use libheif's CLI for robust conversion+ heif_convert = runtime_binary("heif-convert")+ run([heif_convert, path, out_path], check=True)+ if isfile(out_path):+ return out_path+ raise RuntimeError("heif-convert reported success but output file not found: " + out_path)++ if ext_lower == ".pdf":+ _rasterize_pdf_first_page(path, out_path)+ if isfile(out_path):+ return out_path+ raise RuntimeError("PDF rasterization succeeded but output file not found: " + out_path)++ if ext_lower in (".eps", ".ps"):+ _unsupported_format(+ path, "No equivalent EPS/PS converter exists in the Codex runtime bundle."+ )++ if ext_lower in RASTER_EXTS:+ return path++ raise ValueError(f"Unsupported image format for montage: {path}")+++def main() -> None:+ parser = argparse.ArgumentParser(+ description=("Ensure input images are rasterized; convert to PNG if needed.")+ )+ group = parser.add_mutually_exclusive_group(required=True)+ group.add_argument("--input_files", nargs="+", help="List of input image file paths")+ group.add_argument("--input_dir", help="Directory containing input images")+ parser.add_argument(+ "--output_dir",+ default=None,+ help=(+ "Directory to write converted PNGs. If omitted, converted files are written next to inputs."+ ),+ )+ args = parser.parse_args()++ if args.input_files:+ paths = [expanduser(p) for p in args.input_files]+ else:+ input_dir = expanduser(args.input_dir)+ names = listdir(input_dir)+ paths = [+ join(input_dir, f)+ for f in names+ if isfile(join(input_dir, f)) and splitext(f)[1].lower() in SUPPORTED_EXTS+ ]+ if not paths:+ raise SystemExit("No files with supported extensions in input_dir")++ out_dir = expanduser(args.output_dir) if args.output_dir else None+ converted_paths = []+ for p in paths:+ if ensure_raster_image(p, out_dir) != p:+ converted_paths.append(p)++ if converted_paths:+ print("Converted the following files to PNG:\n" + "\n".join(converted_paths))+++if __name__ == "__main__":+ main()diff --git a/skills/paper-fig/container_tools/inspect_presentation_layout_geometry.py b/skills/paper-fig/container_tools/inspect_presentation_layout_geometry.pynew file mode 100644index 0000000..42bb308--- /dev/null+++ b/skills/paper-fig/container_tools/inspect_presentation_layout_geometry.py@@ -0,0 +1,2659 @@+#!/usr/bin/env python3+"""Read-only, source-free OOXML checks for connectors and native table fit."""++from __future__ import annotations++import argparse+import hashlib+import itertools+import json+import math+import posixpath+import re+import struct+import sys+import unicodedata+import zipfile+import zlib+from dataclasses import dataclass+from decimal import Decimal, InvalidOperation+from pathlib import Path+from typing import Any+from xml.etree import ElementTree as ET++# Also used by the lazy font-inspection import under Python safe-path mode.+SCRIPT_DIR = str(Path(__file__).resolve().parent)+if SCRIPT_DIR not in sys.path:+ sys.path.insert(0, SCRIPT_DIR)++NS = {+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+ "pr": "http://schemas.openxmlformats.org/package/2006/relationships",+ "c": "http://schemas.openxmlformats.org/drawingml/2006/chart",+}+EMU_PER_INCH = 914400+EMU_PER_POINT = 12700+DEFAULT_VERTICAL_MARGIN = 45720+FOOTER_REGION = 0.20+# These heuristics suggest review, not that the user's design is invalid.+# Keep structural and explicitly declared requirements in the blocking findings.+STYLE_REVIEW_KINDS = frozenset(+ {+ "connector_over_text",+ "wrapped_presentation_title_subtitle_overlap",+ "single_line_text_overflow",+ "substantial_text_frame_overlap",+ "repeated_wrapped_body_heading_overlap",+ "object_outside_slide_boundary",+ "native_table_overflow",+ "redundant_charts_duplicate_table",+ "zero_padded_slide_folio",+ "incorrect_or_missing_actual_slide_folio",+ "malformed_native_bullet_geometry",+ "primary_bullet_wall_on_editorial_slide",+ "presentation_heading_trailing_full_stop",+ "decorative_bullet_in_presentation_heading",+ "dense_bold_paragraphs_without_spacing",+ "unapproved_decorative_cover_icon",+ "unapproved_decorative_icon_cluster",+ "repeated_unapproved_decorative_icons",+ }+)+_ARIAL_ASCII_ADVANCES = (+ 278,+ 278,+ 355,+ 556,+ 556,+ 889,+ 667,+ 191,+ 333,+ 333,+ 389,+ 584,+ 278,+ 333,+ 278,+ 278,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 278,+ 278,+ 584,+ 584,+ 584,+ 556,+ 1015,+ 667,+ 667,+ 722,+ 722,+ 667,+ 611,+ 778,+ 722,+ 278,+ 500,+ 667,+ 556,+ 833,+ 722,+ 778,+ 667,+ 778,+ 722,+ 667,+ 611,+ 722,+ 667,+ 944,+ 667,+ 667,+ 611,+ 278,+ 278,+ 278,+ 469,+ 556,+ 333,+ 556,+ 556,+ 500,+ 556,+ 556,+ 278,+ 556,+ 556,+ 222,+ 222,+ 500,+ 222,+ 833,+ 556,+ 556,+ 556,+ 556,+ 333,+ 500,+ 278,+ 556,+ 500,+ 722,+ 500,+ 500,+ 500,+ 334,+ 260,+ 334,+ 584,+)+_ARIAL_BOLD_ASCII_ADVANCES = (+ 278,+ 333,+ 474,+ 556,+ 556,+ 889,+ 722,+ 238,+ 333,+ 333,+ 389,+ 584,+ 278,+ 333,+ 278,+ 278,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 333,+ 333,+ 584,+ 584,+ 584,+ 611,+ 975,+ 722,+ 722,+ 722,+ 722,+ 667,+ 611,+ 778,+ 722,+ 278,+ 556,+ 722,+ 611,+ 833,+ 722,+ 778,+ 667,+ 778,+ 722,+ 667,+ 611,+ 722,+ 667,+ 944,+ 667,+ 667,+ 611,+ 333,+ 278,+ 333,+ 584,+ 556,+ 333,+ 556,+ 611,+ 556,+ 611,+ 556,+ 333,+ 611,+ 611,+ 278,+ 278,+ 556,+ 278,+ 889,+ 611,+ 611,+ 611,+ 611,+ 389,+ 556,+ 333,+ 611,+ 556,+ 778,+ 556,+ 556,+ 500,+ 389,+ 280,+ 389,+ 584,+)+_HELVETICA_NEUE_BOLD_ASCII_ADVANCES = (+ 278,+ 278,+ 463,+ 556,+ 556,+ 1000,+ 685,+ 278,+ 296,+ 296,+ 407,+ 600,+ 278,+ 407,+ 278,+ 371,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 556,+ 278,+ 278,+ 600,+ 600,+ 600,+ 556,+ 800,+ 685,+ 704,+ 741,+ 741,+ 648,+ 593,+ 759,+ 741,+ 295,+ 556,+ 722,+ 593,+ 907,+ 741,+ 778,+ 667,+ 778,+ 722,+ 649,+ 611,+ 741,+ 630,+ 944,+ 667,+ 667,+ 648,+ 333,+ 371,+ 333,+ 600,+ 500,+ 259,+ 574,+ 611,+ 574,+ 611,+ 574,+ 333,+ 611,+ 593,+ 258,+ 278,+ 574,+ 258,+ 906,+ 593,+ 611,+ 611,+ 611,+ 389,+ 537,+ 352,+ 593,+ 520,+ 814,+ 537,+ 519,+ 519,+ 333,+ 223,+ 333,+ 600,+)+++@dataclass(frozen=True)+class Box:+ x: float+ y: float+ width: float+ height: float++ @property+ def right(self) -> float:+ return self.x + self.width++ @property+ def bottom(self) -> float:+ return self.y + self.height+++@dataclass(frozen=True)+class SlideObject:+ object_id: str+ kind: str+ box: Box+ z: int+ element: ET.Element+ has_text: bool = False+++def _local(element: ET.Element) -> str:+ return element.tag.rsplit("}", 1)[-1]+++def _box(element: ET.Element) -> Box | None:+ transform = (+ element.find("p:xfrm", NS)+ if _local(element) == "graphicFrame"+ else element.find("p:spPr/a:xfrm", NS)+ )+ if transform is None:+ return None+ offset = transform.find("a:off", NS)+ extent = transform.find("a:ext", NS)+ if offset is None or extent is None:+ return None+ return Box(+ float(offset.get("x", "0")),+ float(offset.get("y", "0")),+ float(extent.get("cx", "0")),+ float(extent.get("cy", "0")),+ )+++def _object_id(element: ET.Element) -> str:+ for path in (+ "p:nvSpPr/p:cNvPr",+ "p:nvCxnSpPr/p:cNvPr",+ "p:nvGraphicFramePr/p:cNvPr",+ "p:nvPicPr/p:cNvPr",+ ):+ properties = element.find(path, NS)+ if properties is not None:+ return properties.get("id", "")+ return ""+++def _slide_objects(root: ET.Element) -> list[SlideObject]:+ tree = root.find("p:cSld/p:spTree", NS)+ if tree is None:+ raise ValueError("slide has no shape tree")+ objects = []+ for z, element in enumerate(tree):+ kind = _local(element)+ if kind not in {"sp", "pic", "cxnSp", "graphicFrame"}:+ continue+ bounds = _box(element)+ if bounds is None:+ continue+ objects.append(+ SlideObject(+ object_id=_object_id(element),+ kind=kind,+ box=bounds,+ z=z,+ element=element,+ has_text=any(+ bool((run.text or "").strip()) for run in element.findall(".//a:t", NS)+ ),+ )+ )+ return objects+++def _connector_points(connector: SlideObject) -> list[tuple[float, float]]:+ transform = connector.element.find("p:spPr/a:xfrm", NS)+ geometry = connector.element.find("p:spPr/a:prstGeom", NS)+ preset = (+ geometry.get("prst", "straightConnector1") if geometry is not None else "straightConnector1"+ )+ flip_h = transform is not None and transform.get("flipH") == "1"+ flip_v = transform is not None and transform.get("flipV") == "1"+ x1, x2 = connector.box.x, connector.box.right+ y1, y2 = connector.box.y, connector.box.bottom+ if flip_h:+ x1, x2 = x2, x1+ if flip_v:+ y1, y2 = y2, y1+ if preset == "bentConnector2":+ return [(x1, y1), (x2, y1), (x2, y2)]+ if preset in {"bentConnector3", "bentConnector4", "bentConnector5"}:+ midpoint = (x1 + x2) / 2+ return [(x1, y1), (midpoint, y1), (midpoint, y2), (x2, y2)]+ return [(x1, y1), (x2, y2)]+++def _is_connector_like(item: SlideObject) -> bool:+ if item.kind == "cxnSp":+ return True+ if item.kind != "sp" or item.has_text:+ return False+ line = item.element.find("p:spPr/a:ln", NS)+ if line is None:+ return False+ return line.find("a:headEnd", NS) is not None or line.find("a:tailEnd", NS) is not None+++def _segment_crosses_interior(+ start: tuple[float, float], end: tuple[float, float], box: Box+) -> bool:+ """Liang-Barsky clipping; exclude endpoint-only and boundary-only contact."""+ inset = min(EMU_PER_INCH * 0.015, box.width / 4, box.height / 4)+ if inset <= 0:+ return False+ left, right = box.x + inset, box.right - inset+ top, bottom = box.y + inset, box.bottom - inset+ dx, dy = end[0] - start[0], end[1] - start[1]+ low, high = 0.0, 1.0+ for direction, distance in (+ (-dx, start[0] - left),+ (dx, right - start[0]),+ (-dy, start[1] - top),+ (dy, bottom - start[1]),+ ):+ if direction == 0:+ if distance < 0:+ return False+ continue+ ratio = distance / direction+ if direction < 0:+ low = max(low, ratio)+ else:+ high = min(high, ratio)+ if low > high:+ return False+ return high - low > 1e-8+++def _endpoint_ids(connector: SlideObject) -> set[str]:+ properties = connector.element.find("p:nvCxnSpPr/p:cNvCxnSpPr", NS)+ return (+ {child.get("id", "") for child in properties if child.get("id")}+ if properties is not None+ else set()+ )+++def _connector_findings(slide_number: int, objects: list[SlideObject]) -> list[dict[str, Any]]:+ findings = []+ for connector in (item for item in objects if _is_connector_like(item)):+ endpoints = _endpoint_ids(connector)+ points = _connector_points(connector)+ for text_object in objects:+ if (+ text_object.kind != "sp"+ or not text_object.has_text+ or text_object.object_id in endpoints+ or connector.z < text_object.z+ ):+ continue+ if any(+ _segment_crosses_interior(start, end, text_object.box)+ for start, end in itertools.pairwise(points)+ ):+ findings.append(+ {+ "kind": "connector_over_text",+ "slide": slide_number,+ "connector_id": connector.object_id,+ "text_object_id": text_object.object_id,+ "connector_z": connector.z,+ "text_z": text_object.z,+ }+ )+ return findings+++def _occupied_text_vertical_band(item: SlideObject) -> tuple[float, float]:+ body = item.element.find("p:txBody/a:bodyPr", NS)+ properties = body.attrib if body is not None else {}+ top = float(properties.get("tIns", DEFAULT_VERTICAL_MARGIN))+ bottom = float(properties.get("bIns", DEFAULT_VERTICAL_MARGIN))+ left = float(properties.get("lIns", 91440))+ right = float(properties.get("rIns", 91440))+ usable_width = max(1.0, item.box.width - left - right)+ usable_height = max(0.0, item.box.height - top - bottom)+ occupied = min(+ usable_height,+ sum(+ _paragraph_lines(paragraph, usable_width)+ * _font_size(paragraph)+ * EMU_PER_POINT+ * _paragraph_line_spacing(paragraph)+ for paragraph in item.element.findall("p:txBody/a:p", NS)+ ),+ )+ anchor = properties.get("anchor", "t")+ if anchor == "ctr":+ start = item.box.y + top + max(0.0, usable_height - occupied) / 2+ elif anchor == "b":+ start = item.box.bottom - bottom - occupied+ else:+ start = item.box.y + top+ return start, start + occupied+++def _occupied_text_horizontal_band(item: SlideObject) -> tuple[float, float]:+ """Estimate painted text, not the often deliberately oversized frame."""++ body = item.element.find("p:txBody/a:bodyPr", NS)+ properties = body.attrib if body is not None else {}+ left = float(properties.get("lIns", 91440))+ right = float(properties.get("rIns", 91440))+ usable_width = max(1.0, item.box.width - left - right)+ occupied_bands = []+ for paragraph in item.element.findall("p:txBody/a:p", NS):+ text = "".join(node.text or "" for node in paragraph.findall(".//a:t", NS))+ size = _font_size(paragraph) * EMU_PER_POINT+ occupied = min(+ usable_width,+ max(size * 0.6, max((len(line) for line in text.split("\n")), default=0) * size * 0.62),+ )+ paragraph_properties = paragraph.find("a:pPr", NS)+ alignment = (+ paragraph_properties.get("algn", "l") if paragraph_properties is not None else "l"+ )+ if alignment == "r":+ start = item.box.right - right - occupied+ elif alignment == "ctr":+ start = item.box.x + left + (usable_width - occupied) / 2+ else:+ start = item.box.x + left+ occupied_bands.append((start, start + occupied))+ if not occupied_bands:+ return item.box.x + left, item.box.right - right+ return min(band[0] for band in occupied_bands), max(band[1] for band in occupied_bands)+++def _presentation_heading_pair(+ objects: list[SlideObject], slide_width: float, slide_height: float+) -> tuple[SlideObject, SlideObject | None] | None:+ """Identify an actual title/subtitle pair without treating body copy as headings."""++ candidates = []+ for item in objects:+ if (+ item.kind != "sp"+ or not item.has_text+ or item.box.width < slide_width * 0.35+ or item.box.y > slide_height * 0.58+ ):+ continue+ paragraphs = item.element.findall("p:txBody/a:p", NS)+ if len(paragraphs) == 1:+ candidates.append((item, _font_size(paragraphs[0])))+ titles = [(item, size) for item, size in candidates if size >= 20.0]+ if not titles:+ return None+ title, title_size = min(titles, key=lambda entry: entry[0].box.y)+ subtitles = []+ for item, size in candidates:+ if item.object_id == title.object_id or not 10.0 <= size < title_size * 0.83:+ continue+ if item.box.y <= title.box.y or item.box.y - title.box.bottom > slide_height * 0.13:+ continue+ overlap_width = min(title.box.right, item.box.right) - max(title.box.x, item.box.x)+ if overlap_width < min(title.box.width, item.box.width) * 0.68:+ continue+ subtitles.append(item)+ return title, min(subtitles, key=lambda item: item.box.y) if subtitles else None+++def _heading_punctuation_findings(+ slide_number: int, objects: list[SlideObject], slide_width: float, slide_height: float+) -> list[dict[str, Any]]:+ headings = _presentation_heading_pair(objects, slide_width, slide_height)+ if headings is None:+ return []+ findings = []+ for role, item in (("title", headings[0]), ("subtitle", headings[1])):+ if item is None:+ continue+ paragraph = item.element.find("p:txBody/a:p", NS)+ assert paragraph is not None+ content = "".join(node.text or "" for node in paragraph.findall(".//a:t", NS)).strip()+ properties = paragraph.find("a:pPr", NS)+ decorative_bullet = content.startswith(("•", "▪", "●", "◦", "‣", "⁃", "·"))+ if properties is not None:+ decorative_bullet = decorative_bullet or any(+ properties.find(f"a:{kind}", NS) is not None+ for kind in ("buChar", "buAutoNum", "buBlip")+ )+ if decorative_bullet:+ findings.append(+ {+ "kind": "decorative_bullet_in_presentation_heading",+ "slide": slide_number,+ "object_id": item.object_id,+ "heading_role": role,+ }+ )+ abbreviation = re.search(+ r"(?:\b(?:[A-Za-z]\.){2,}|\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|Inc|Ltd|Co|etc|vs)\.)$",+ content,+ flags=re.IGNORECASE,+ )+ if content.endswith(".") and abbreviation is None:+ findings.append(+ {+ "kind": "presentation_heading_trailing_full_stop",+ "slide": slide_number,+ "object_id": item.object_id,+ "heading_role": role,+ "character_count": len(content),+ }+ )+ return findings+++def _heading_fit_findings(+ slide_number: int, objects: list[SlideObject], slide_width: float, slide_height: float+) -> list[dict[str, Any]]:+ """Reject only proven bold-font title wrapping into an actual subtitle."""++ headings = _presentation_heading_pair(objects, slide_width, slide_height)+ if headings is None or headings[1] is None:+ return []+ title, subtitle = headings+ body = title.element.find("p:txBody/a:bodyPr", NS)+ if body is None or body.find("a:noAutofit", NS) is None or body.get("wrap", "square") == "none":+ return []+ paragraph = title.element.find("p:txBody/a:p", NS)+ assert paragraph is not None+ if paragraph.find("a:br", NS) is not None:+ return []+ runs = paragraph.findall("a:r", NS)+ if len(runs) != 1:+ return []+ properties = runs[0].find("a:rPr", NS)+ node = runs[0].find("a:t", NS)+ latin = properties.find("a:latin", NS) if properties is not None else None+ if (+ properties is None+ or node is None+ or latin is None+ or properties.get("b") != "1"+ or not properties.get("sz")+ ):+ return []+ family = latin.get("typeface", "").casefold().replace(" ", "")+ if family in {"arial", "arialmt"}:+ advances = _ARIAL_BOLD_ASCII_ADVANCES+ elif family in {"helveticaneue", "helveticaneue-bold"}:+ advances = _HELVETICA_NEUE_BOLD_ASCII_ADVANCES+ else:+ return []+ content = node.text or ""+ if len(content) < 30 or any(ord(value) < 32 or ord(value) > 126 for value in content):+ return []+ point_size = float(properties.get("sz", "0")) / 100.0+ usable_width = (+ title.box.width - float(body.get("lIns", 91440)) - float(body.get("rIns", 91440))+ ) / EMU_PER_POINT+ measured_width = sum(advances[ord(value) - 32] for value in content) * point_size / 1000.0+ if usable_width <= 0 or measured_width <= usable_width + 0.25:+ return []+ # A normal native word wrap needs at least two full lines. Only fail when+ # those actual font-aware lines physically enter the subtitle glyph band.+ actual_bottom = (+ title.box.y+ + float(body.get("tIns", DEFAULT_VERTICAL_MARGIN))+ + 2 * point_size * _paragraph_line_spacing(paragraph) * EMU_PER_POINT+ )+ subtitle_body = subtitle.element.find("p:txBody/a:bodyPr", NS)+ subtitle_top = subtitle.box.y + float(+ subtitle_body.get("tIns", DEFAULT_VERTICAL_MARGIN)+ if subtitle_body is not None+ else DEFAULT_VERTICAL_MARGIN+ )+ overlap = (actual_bottom - subtitle_top) / EMU_PER_POINT+ if overlap < 2.0:+ return []+ return [+ {+ "kind": "wrapped_presentation_title_subtitle_overlap",+ "slide": slide_number,+ "title_object_id": title.object_id,+ "subtitle_object_id": subtitle.object_id,+ "font_family": latin.get("typeface", ""),+ "font_size_pt": round(point_size, 2),+ "usable_width_pt": round(usable_width, 2),+ "measured_width_pt": round(measured_width, 2),+ "predicted_subtitle_overlap_pt": round(overlap, 2),+ }+ ]+++def _text_overflow_findings(slide_number: int, objects: list[SlideObject]) -> list[dict[str, Any]]:+ """Reject proven one-line Arial overflow without exposing slide text."""++ findings = []+ for item in objects:+ if item.kind != "sp" or not item.has_text:+ continue+ body = item.element.find("p:txBody/a:bodyPr", NS)+ if (+ body is None+ or body.find("a:noAutofit", NS) is None+ or body.get("wrap", "square") == "none"+ ):+ continue+ paragraphs = item.element.findall("p:txBody/a:p", NS)+ if len(paragraphs) != 1 or paragraphs[0].find("a:br", NS) is not None:+ continue+ runs = paragraphs[0].findall("a:r", NS)+ if len(runs) != 1:+ continue+ properties = runs[0].find("a:rPr", NS)+ node = runs[0].find("a:t", NS)+ latin = properties.find("a:latin", NS) if properties is not None else None+ if (+ properties is None+ or node is None+ or latin is None+ or not properties.get("sz")+ or properties.get("b") == "1"+ or latin.get("typeface", "").casefold() not in {"arial", "arialmt"}+ ):+ continue+ content = node.text or ""+ if len(content) < 40 or any(ord(value) < 32 or ord(value) > 126 for value in content):+ continue+ font_size = float(properties.get("sz", "0")) / 100.0+ left = float(body.get("lIns", 91440))+ right = float(body.get("rIns", 91440))+ top = float(body.get("tIns", DEFAULT_VERTICAL_MARGIN))+ bottom = float(body.get("bIns", DEFAULT_VERTICAL_MARGIN))+ usable_width = (item.box.width - left - right) / EMU_PER_POINT+ usable_height = (item.box.height - top - bottom) / EMU_PER_POINT+ line_height = font_size * _paragraph_line_spacing(paragraphs[0])+ if (+ usable_width <= 0+ or usable_height < font_size * 0.9+ or usable_height >= line_height * 1.8+ ):+ continue+ measured_width = (+ sum(_ARIAL_ASCII_ADVANCES[ord(value) - 32] for value in content) * font_size / 1000.0+ )+ if measured_width <= usable_width * 1.03 + 1.0:+ continue+ findings.append(+ {+ "kind": "single_line_text_overflow",+ "slide": slide_number,+ "object_id": item.object_id,+ "font_family": "Arial",+ "font_size_pt": round(font_size, 2),+ "character_count": len(content),+ "usable_width_pt": round(usable_width, 2),+ "measured_width_pt": round(measured_width, 2),+ "usable_height_pt": round(usable_height, 2),+ "required_two_line_height_pt": round(line_height * 2, 2),+ }+ )+ return findings+++def _dense_bold_paragraph_findings(+ slide_number: int, objects: list[SlideObject]+) -> list[dict[str, Any]]:+ """Find crowded multi-paragraph callouts without exposing their contents."""++ findings = []+ for item in objects:+ if item.kind != "sp" or not item.has_text:+ continue+ body = item.element.find("p:txBody/a:bodyPr", NS)+ if (+ body is None+ or body.find("a:noAutofit", NS) is None+ or body.get("wrap", "square") == "none"+ ):+ continue+ paragraphs = item.element.findall("p:txBody/a:p", NS)+ if not 2 <= len(paragraphs) <= 4:+ continue+ lengths = []+ sizes = []+ explicit_spacing = False+ for paragraph in paragraphs:+ runs = paragraph.findall("a:r", NS)+ if len(runs) != 1:+ break+ properties = runs[0].find("a:rPr", NS)+ node = runs[0].find("a:t", NS)+ if (+ properties is None+ or node is None+ or properties.get("b") != "1"+ or not properties.get("sz")+ ):+ break+ lengths.append(len(node.text or ""))+ sizes.append(float(properties.get("sz", "0")) / 100.0)+ paragraph_properties = paragraph.find("a:pPr", NS)+ explicit_spacing = explicit_spacing or (+ paragraph_properties is not None+ and (+ paragraph_properties.find("a:spcAft", NS) is not None+ or paragraph_properties.find("a:spcBef", NS) is not None+ )+ )+ if (+ len(lengths) != len(paragraphs)+ or sum(lengths) < 120+ or min(lengths) < 35+ or explicit_spacing+ ):+ continue+ usable_height = (+ item.box.height+ - float(body.get("tIns", DEFAULT_VERTICAL_MARGIN))+ - float(body.get("bIns", DEFAULT_VERTICAL_MARGIN))+ ) / EMU_PER_POINT+ if usable_height / sum(sizes) > 1.65:+ continue+ findings.append(+ {+ "kind": "dense_bold_paragraphs_without_spacing",+ "slide": slide_number,+ "object_id": item.object_id,+ "paragraph_count": len(paragraphs),+ "character_count": sum(lengths),+ "usable_height_pt": round(usable_height, 2),+ }+ )+ return findings+++def _text_overlap_findings(slide_number: int, objects: list[SlideObject]) -> list[dict[str, Any]]:+ """Flag substantial sibling text-frame intersections without exporting text."""++ findings = []+ text_objects = [item for item in objects if item.kind == "sp" and item.has_text]+ for index, left in enumerate(text_objects):+ left_area = left.box.width * left.box.height+ if left_area <= 0:+ continue+ for right in text_objects[index + 1 :]:+ right_area = right.box.width * right.box.height+ if right_area <= 0:+ continue+ overlap_width = min(left.box.right, right.box.right) - max(left.box.x, right.box.x)+ overlap_height = min(left.box.bottom, right.box.bottom) - max(left.box.y, right.box.y)+ if overlap_width <= 0 or overlap_height <= 0:+ continue+ left_top, left_bottom = _occupied_text_vertical_band(left)+ right_top, right_bottom = _occupied_text_vertical_band(right)+ if min(left_bottom, right_bottom) <= max(left_top, right_top):+ continue+ left_start, left_end = _occupied_text_horizontal_band(left)+ right_start, right_end = _occupied_text_horizontal_band(right)+ if min(left_end, right_end) <= max(left_start, right_start):+ continue+ intersection = overlap_width * overlap_height+ if (+ intersection / min(left_area, right_area) < 0.42+ or intersection / max(left_area, right_area) < 0.16+ ):+ continue+ findings.append(+ {+ "kind": "substantial_text_frame_overlap",+ "slide": slide_number,+ "left_object_id": left.object_id,+ "right_object_id": right.object_id,+ "overlap_height_in": round(overlap_height / EMU_PER_INCH, 4),+ "overlap_width_in": round(overlap_width / EMU_PER_INCH, 4),+ }+ )+ return findings+++def _repeated_wrapped_body_heading_overlap_findings(+ slide_number: int, objects: list[SlideObject]+) -> list[dict[str, Any]]:+ """Detect repeated wrapped-description collisions with following headings."""++ pairs = []+ text_objects = [item for item in objects if item.kind == "sp" and item.has_text]+ for body_item in text_objects:+ body = body_item.element.find("p:txBody/a:bodyPr", NS)+ if body is None or body.get("wrap", "square") == "none":+ continue+ paragraphs = body_item.element.findall("p:txBody/a:p", NS)+ if len(paragraphs) != 1:+ continue+ usable_width = (+ body_item.box.width - float(body.get("lIns", 91440)) - float(body.get("rIns", 91440))+ )+ if usable_width <= 0 or _paragraph_lines(paragraphs[0], usable_width) < 2:+ continue+ for heading_item in text_objects:+ if heading_item.object_id == body_item.object_id:+ continue+ if heading_item.box.y <= body_item.box.y:+ continue+ if abs(heading_item.box.x - body_item.box.x) > 2 * EMU_PER_POINT:+ continue+ overlap_height = body_item.box.bottom - heading_item.box.y+ if overlap_height < EMU_PER_POINT:+ continue+ overlap_width = min(body_item.box.right, heading_item.box.right) - max(+ body_item.box.x, heading_item.box.x+ )+ if overlap_width < min(body_item.box.width, heading_item.box.width) * 0.8:+ continue+ heading_body = heading_item.element.find("p:txBody/a:bodyPr", NS)+ if heading_body is None or heading_body.get("wrap", "square") != "none":+ continue+ heading_paragraphs = heading_item.element.findall("p:txBody/a:p", NS)+ if len(heading_paragraphs) != 1:+ continue+ properties = [run.find("a:rPr", NS) for run in heading_paragraphs[0].findall("a:r", NS)]+ if not properties or not all(+ value is not None and value.get("b") == "1" for value in properties+ ):+ continue+ pairs.append(+ {+ "kind": "repeated_wrapped_body_heading_overlap",+ "slide": slide_number,+ "body_object_id": body_item.object_id,+ "heading_object_id": heading_item.object_id,+ "overlap_height_pt": round(overlap_height / EMU_PER_POINT, 2),+ }+ )+ return pairs if len(pairs) >= 2 else []+++def _slide_boundary_findings(+ slide_number: int,+ objects: list[SlideObject],+ slide_width: float,+ slide_height: float,+) -> list[dict[str, Any]]:+ findings = []+ tolerance = EMU_PER_INCH * 0.005+ for item in objects:+ if (+ item.box.x < -tolerance+ or item.box.y < -tolerance+ or item.box.right > slide_width + tolerance+ or item.box.bottom > slide_height + tolerance+ ):+ findings.append(+ {+ "kind": "object_outside_slide_boundary",+ "slide": slide_number,+ "object_id": item.object_id,+ "object_kind": item.kind,+ }+ )+ return findings+++def _font_size(paragraph: ET.Element) -> float:+ sizes = []+ for properties in paragraph.findall("a:r/a:rPr", NS):+ value = properties.get("sz")+ if value:+ sizes.append(float(value) / 100)+ default = paragraph.find("a:pPr/a:defRPr", NS)+ if default is not None and default.get("sz"):+ sizes.append(float(default.get("sz", "0")) / 100)+ return max(sizes, default=12.0)+++def _paragraph_line_spacing(paragraph: ET.Element) -> float:+ spacing = paragraph.find("a:pPr/a:lnSpc/a:spcPct", NS)+ if spacing is not None and spacing.get("val"):+ return max(1.0, float(spacing.get("val", "100000")) / 100000)+ return 1.2+++def _paragraph_lines(paragraph: ET.Element, usable_width: float) -> int:+ text = "".join(node.text or "" for node in paragraph.findall(".//a:t", NS))+ if not text:+ return 1+ size = _font_size(paragraph)+ average_glyph_width = max(1.0, size * EMU_PER_POINT * 0.54)+ characters_per_line = max(1, int(usable_width // average_glyph_width))+ return sum(max(1, math.ceil(len(line) / characters_per_line)) for line in text.split("\n"))+++def _effective_row_height(row: ET.Element, columns: list[float]) -> float:+ declared = float(row.get("h", "0"))+ required = declared+ for index, cell in enumerate(row.findall("a:tc", NS)):+ properties = cell.find("a:tcPr", NS)+ margins = properties.attrib if properties is not None else {}+ top = float(margins.get("marT", DEFAULT_VERTICAL_MARGIN))+ bottom = float(margins.get("marB", DEFAULT_VERTICAL_MARGIN))+ left = float(margins.get("marL", 91440))+ right = float(margins.get("marR", 91440))+ width = columns[index] if index < len(columns) else EMU_PER_INCH+ usable_width = max(1.0, width - left - right)+ line_height = 0.0+ for paragraph in cell.findall("a:txBody/a:p", NS):+ line_height += (+ _paragraph_lines(paragraph, usable_width)+ * _font_size(paragraph)+ * EMU_PER_POINT+ * _paragraph_line_spacing(paragraph)+ )+ # Native PowerPoint's table engine reserves caret/baseline breathing+ # room beyond line-height plus margins; extrema are not hard clips.+ native_leading = max(EMU_PER_INCH * 0.07, line_height * 0.14)+ required = max(required, top + bottom + line_height + native_leading)+ return required+++def _table_findings(+ slide_number: int, objects: list[SlideObject], slide_height: float+) -> list[dict[str, Any]]:+ findings = []+ for table_object in (+ item+ for item in objects+ if item.kind == "graphicFrame" and item.element.find(".//a:tbl", NS) is not None+ ):+ table = table_object.element.find(".//a:tbl", NS)+ assert table is not None+ rows = table.findall("a:tr", NS)+ columns = [+ float(column.get("w", "0")) for column in table.findall("a:tblGrid/a:gridCol", NS)+ ]+ declared_bottom = table_object.box.y + sum(float(row.get("h", "0")) for row in rows)+ estimated_bottom = table_object.box.y + sum(+ _effective_row_height(row, columns) for row in rows+ )+ lower_furniture = [+ item+ for item in objects+ if item.object_id != table_object.object_id+ and item.kind in {"sp", "pic"}+ and item.box.y >= slide_height * (1 - FOOTER_REGION)+ and item.box.y >= table_object.box.y+ and item.box.right > table_object.box.x+ and item.box.x < table_object.box.right+ ]+ boundary = min([slide_height] + [item.box.y for item in lower_furniture])+ if estimated_bottom > boundary:+ findings.append(+ {+ "kind": "native_table_overflow",+ "slide": slide_number,+ "table_id": table_object.object_id,+ "rows": len(rows),+ "columns": len(columns),+ "declared_bottom_in": round(declared_bottom / EMU_PER_INCH, 4),+ "estimated_native_bottom_in": round(estimated_bottom / EMU_PER_INCH, 4),+ "available_bottom_in": round(boundary / EMU_PER_INCH, 4),+ "overflow_in": round((estimated_bottom - boundary) / EMU_PER_INCH, 4),+ "footer_object_ids": [+ item.object_id for item in lower_furniture if item.box.y < estimated_bottom+ ],+ }+ )+ return findings+++def _slide_parts(package: zipfile.ZipFile, presentation: ET.Element) -> list[str]:+ try:+ relationships = ET.fromstring(package.read("ppt/_rels/presentation.xml.rels"))+ except KeyError:+ return sorted(+ (+ name+ for name in package.namelist()+ if name.startswith("ppt/slides/slide")+ and name.endswith(".xml")+ and "/_rels/" not in name+ ),+ key=lambda name: int(name.removeprefix("ppt/slides/slide").removesuffix(".xml")),+ )+ by_id = {+ item.get("Id", ""): item.get("Target", "")+ for item in relationships.findall("pr:Relationship", NS)+ }+ result = []+ for slide in presentation.findall("p:sldIdLst/p:sldId", NS):+ relation_id = slide.get(f"{{{NS['r']}}}id", "")+ target = by_id.get(relation_id)+ if not target:+ raise ValueError("presentation slide relationship is missing")+ if target.startswith("/"):+ part = posixpath.normpath(target.lstrip("/"))+ else:+ part = posixpath.normpath(posixpath.join("ppt", target))+ result.append(part)+ return result+++def _presentation_policy_findings(+ package: zipfile.ZipFile,+ presentation: ET.Element,+ parts: list[str],+ policy: dict[str, Any],+) -> list[dict[str, Any]]:+ """Apply only explicitly frozen task/template geometry and cover rules."""++ findings = []+ size = presentation.find("p:sldSz", NS)+ if size is None:+ raise ValueError("presentation has no slide dimensions")+ width = int(size.get("cx", "0"))+ height = int(size.get("cy", "0"))+ if width <= 0 or height <= 0:+ raise ValueError("presentation slide dimensions must be positive")++ aspect = policy.get("expected_aspect")+ if aspect:+ try:+ numerator, denominator = (int(value) for value in aspect.split(":"))+ except (TypeError, ValueError) as exc:+ raise ValueError("expected aspect must use positive N:D") from exc+ if numerator <= 0 or denominator <= 0:+ raise ValueError("expected aspect must use positive N:D")+ if abs(width / height - numerator / denominator) > 0.02:+ findings.append(+ {+ "kind": "unexpected_slide_aspect_ratio",+ "expected_aspect": aspect,+ "actual_cx_emu": width,+ "actual_cy_emu": height,+ }+ )++ expected_size = policy.get("expected_slide_size_emu")+ if expected_size:+ try:+ expected_width, expected_height = (int(value) for value in expected_size.split(","))+ except (TypeError, ValueError) as exc:+ raise ValueError("expected slide size must use positive CX,CY") from exc+ if expected_width <= 0 or expected_height <= 0:+ raise ValueError("expected slide size must use positive CX,CY")+ if (width, height) != (expected_width, expected_height):+ findings.append(+ {+ "kind": "approved_template_slide_size_changed",+ "expected_cx_emu": expected_width,+ "expected_cy_emu": expected_height,+ "actual_cx_emu": width,+ "actual_cy_emu": height,+ }+ )++ expected_count = policy.get("expected_slide_count")+ if expected_count is not None and len(parts) != expected_count:+ findings.append(+ {+ "kind": "requested_slide_count_changed",+ "expected_slide_count": expected_count,+ "actual_slide_count": len(parts),+ }+ )++ required_table_slides = policy.get("require_native_table_slides", [])+ if any(number < 1 or number > len(parts) for number in required_table_slides):+ raise ValueError("required native table slide numbers must identify actual slides")+ for number in sorted(set(required_table_slides)):+ required_slide = ET.fromstring(package.read(parts[number - 1]))+ if required_slide.find(".//a:tbl", NS) is None:+ findings.append(+ {+ "kind": "required_native_table_missing",+ "slide": number,+ }+ )++ editorial_slides = policy.get("require_editorial_slides", [])+ if any(number < 1 or number > len(parts) for number in editorial_slides):+ raise ValueError("required editorial slide numbers must identify actual slides")+ approved_bullet_slides = policy.get("approved_bullet_slides", [])+ if any(number < 1 or number > len(parts) for number in approved_bullet_slides):+ raise ValueError("approved bullet slide numbers must identify actual slides")+ approved_heading_slides = policy.get("approved_heading_slides", [])+ if any(number < 1 or number > len(parts) for number in approved_heading_slides):+ raise ValueError("approved heading slide numbers must identify actual slides")++ role = policy.get("cover_role", "none")+ if role not in {"cover", "explicit_hybrid"} or not parts:+ return findings+ root = ET.fromstring(package.read(parts[0]))+ word_count = sum(+ len(+ re.findall(+ r"\b[\w’'-]+\b",+ " ".join(node.text or "" for node in shape.findall(".//a:t", NS)),+ )+ )+ for shape in root.findall(".//p:sp", NS)+ )+ limit = policy.get("cover_word_limit")+ if limit is None:+ limit = 45 if role == "cover" else 75+ if word_count > limit:+ findings.append(+ {+ "kind": "cover_prose_density_exceeded",+ "slide": 1,+ "role": role,+ "word_count": word_count,+ "word_limit": limit,+ }+ )+ if not policy.get("allow_cover_table") and root.find(".//a:tbl", NS) is not None:+ findings.append({"kind": "unapproved_cover_table", "slide": 1})+ if not policy.get("allow_cover_chart") and root.find(".//c:chart", NS) is not None:+ findings.append({"kind": "unapproved_cover_chart", "slide": 1})+ return findings+++def _uniform_presentation_font_findings(+ package: zipfile.ZipFile, parts: list[str]+) -> list[dict[str, Any]]:+ """Compare only typefaces actually declared in audience-facing content."""++ theme_families: dict[str, str] = {}+ theme_parts = sorted(+ name+ for name in package.namelist()+ if name.startswith("ppt/theme/theme") and name.endswith(".xml")+ )+ if len(theme_parts) == 1:+ theme = ET.fromstring(package.read(theme_parts[0]))+ for alias, path in (+ ("+mj-lt", ".//a:majorFont/a:latin"),+ ("+mn-lt", ".//a:minorFont/a:latin"),+ ):+ element = theme.find(path, NS)+ if element is not None and element.get("typeface", "").strip():+ theme_families[alias] = element.get("typeface", "").strip()++ observed: dict[str, str] = {}+ audience_parts = [+ *parts,+ *sorted(+ name+ for name in package.namelist()+ if name.startswith("ppt/")+ and "/charts/" in name+ and name.endswith(".xml")+ and "/_rels/" not in name+ ),+ ]+ for part in audience_parts:+ root = ET.fromstring(package.read(part))+ for element in root.findall(".//a:latin", NS):+ family = element.get("typeface", "").strip()+ if not family:+ continue+ if family.startswith("+"):+ family = theme_families.get(family, "")+ if not family:+ continue+ normalized = re.sub(r"[\s_-]+", " ", family).strip().casefold()+ if normalized == "arialmt":+ normalized = "arial"+ observed.setdefault(normalized, family)++ if len(observed) <= 1:+ return []+ return [+ {+ "kind": "inconsistent_presentation_font_family",+ "font_family_count": len(observed),+ "font_families": sorted(observed.values(), key=str.casefold),+ }+ ]+++def _font_key(family: str) -> str:+ value = re.sub(r"^[A-Z]{6}\+", "", family.strip())+ value = re.sub(+ r"-(?:BoldItalic|BoldOblique|Bold|Italic|Oblique|Regular|Roman)(?:MT)?$",+ "",+ value,+ flags=re.I,+ )+ value = re.sub(r"[\s_-]+", " ", value).casefold()+ return {"arialmt": "arial", "helveticaneue": "helvetica neue"}.get(value, value)+++def _text_scripts(text: str) -> set[str]:+ """A non-Latin fallback never exempts ordinary Latin text or numbers."""+ scripts: set[str] = set()+ for character in text:+ if character.isspace():+ continue+ code = ord(character)+ if (+ 0x2E80 <= code <= 0xA4CF+ or 0xAC00 <= code <= 0xD7AF+ or 0xF900 <= code <= 0xFAFF+ or 0xFF01 <= code <= 0xFF60+ or 0x20000 <= code <= 0x323AF+ ):+ scripts.add("ea")+ elif 0x0590 <= code <= 0x109F or 0xFB1D <= code <= 0xFEFF:+ scripts.add("cs")+ elif code >= 0x1F000 or (code > 0x7F and unicodedata.category(character) == "So"):+ scripts.add("symbol")+ elif unicodedata.category(character)[0] in {"L", "N"} or code < 0x80:+ scripts.add("latin")+ return scripts or ({"latin"} if text.strip() else set())+++def inspect_presentation_font_policy(+ package: zipfile.ZipFile, parts: list[str], policy: dict[str, Any]+) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ """Check used editable text, resolving its own slide/layout/master theme.++ No text, prompts or source contents are emitted. A reference inventory uses+ encoded, non-hidden text, not a generated file or an unused theme family.+ """+ from native_quantitative_chart_gate import _relationships, _safe_xml++ inventory_only = policy.get("font_inventory_only") is True+ required = policy.get("required_default_font_family")+ approved = policy.get("approved_font_families", [])+ if required and approved:+ raise ValueError("Default and source font policies cannot be mixed")+ families = [required] if required else approved+ if (+ (not families and not inventory_only)+ or len(families) > 16+ or any(+ not isinstance(name, str)+ or not name.strip()+ or len(name) > 128+ or re.search(r"[\x00-\x1f\x7f]", name)+ for name in families+ )+ ):+ raise ValueError("Font policy needs bounded explicit families")+ allowed = {_font_key(name) for name in families}+ script_fonts: dict[str, str] = {}+ for entry in policy.get("approved_script_fonts", []):+ script, separator, family = entry.partition("=")+ if (+ separator != "="+ or script not in {"ea", "cs", "symbol"}+ or script in script_fonts+ or not family.strip()+ or len(family) > 128+ ):+ raise ValueError("Invalid or repeated script-specific font approval")+ script_fonts[script] = _font_key(family)+ roots: dict[str, ET.Element] = {}+ relations: dict[str, dict[str, Any]] = {}+ visible_by_part: dict[str, list[ET.Element]] = {}++ def root(part: str) -> ET.Element:+ if part not in roots:+ roots[part] = _safe_xml(package, part)+ return roots[part]++ def rels(part: str) -> dict[str, Any]:+ if part not in relations:+ relations[part] = _relationships(package, part)+ return relations[part]++ def related(part: str, kind: str) -> str | None:+ selected = [value for value in rels(part).values() if value["type"].endswith("/" + kind)]+ if len(selected) > 1 or any(value["mode"] != "Internal" for value in selected):+ raise ValueError("Ambiguous or external font inheritance relationship")+ if not selected:+ return None+ target = selected[0]["target"]+ root(target) # Missing or malformed inheritance cannot silently pass.+ return target++ def visible_elements(part: str) -> list[ET.Element]:+ # Hidden shapes and entire hidden groups are not audience-facing text.+ # Their stored typography must neither block output nor approve a font+ # that the supplied reference never actually shows.+ if part not in visible_by_part:+ visible: list[ET.Element] = []+ stack = [root(part)]+ containers = {+ "sp": "nvSpPr",+ "cxnSp": "nvCxnSpPr",+ "grpSp": "nvGrpSpPr",+ "graphicFrame": "nvGraphicFramePr",+ "pic": "nvPicPr",+ }+ while stack:+ element = stack.pop()+ container = containers.get(_local(element))+ properties = element.find(f"p:{container}/p:cNvPr", NS) if container else None+ if properties is not None and properties.get("hidden", "0").lower() in {+ "1",+ "true",+ }:+ continue+ visible.append(element)+ stack.extend(reversed(list(element)))+ visible_by_part[part] = visible+ return visible_by_part[part]++ def font_element(properties: ET.Element | None, script: str) -> str | None:+ if properties is None:+ return None+ tag = "sym" if script == "symbol" else script+ element = properties.find("a:" + tag, NS)+ if element is None or not element.get("typeface", "").strip():+ return None+ return element.get("typeface", "").strip()++ findings: list[dict[str, Any]] = []+ observed: dict[str, int] = {}+ checked = 0+ for slide_number, slide_part in enumerate(parts, 1):+ slide = root(slide_part)+ layout_part = related(slide_part, "slideLayout")+ master_part = related(layout_part, "slideMaster") if layout_part else None+ chain = [+ part for part in (slide_part, layout_part, master_part, "ppt/presentation.xml") if part+ ]+ theme_part = next((theme for part in chain if (theme := related(part, "theme"))), None)+ theme = root(theme_part) if theme_part else None+ master = root(master_part) if master_part else None+ presentation = root("ppt/presentation.xml")++ def resolve(+ family: str | None, script: str, language: str = "", *, theme: ET.Element | None = theme+ ) -> str | None:+ if family and not family.startswith("+"):+ return family+ if family and not re.fullmatch(r"\+m[jn]-(lt|ea|cs)", family):+ return None+ if theme is None:+ return None+ role = "majorFont" if family and family.startswith("+mj") else "minorFont"+ tag = {"lt": "latin", "ea": "ea", "cs": "cs"}.get(+ family.rsplit("-", 1)[-1] if family else "",+ {"latin": "latin", "ea": "ea", "cs": "cs", "symbol": "latin"}[script],+ )+ scheme = theme.find(f".//a:fontScheme/a:{role}", NS)+ element = scheme.find(f"a:{tag}", NS) if scheme is not None else None+ if element is not None and element.get("typeface", "").strip():+ return element.get("typeface", "").strip()+ # A theme often leaves ea/cs empty and uses script-specific entries.+ # Resolve only a unique applicable family; never guess among scripts.+ scripts = (+ {"Jpan", "Hans", "Hant", "Hang"}+ if tag == "ea"+ else {+ "Arab",+ "Hebr",+ "Deva",+ "Beng",+ "Guru",+ "Gujr",+ "Orya",+ "Taml",+ "Telu",+ "Knda",+ "Mlym",+ "Thai",+ "Laoo",+ "Mymr",+ }+ if tag == "cs"+ else set()+ )+ language = language.lower()+ if tag == "ea":+ if language.startswith("ja"):+ scripts = {"Jpan"}+ elif language.startswith("ko"):+ scripts = {"Hang"}+ elif language.startswith("zh"):+ scripts = {+ "Hant"+ if any(value in language for value in ("tw", "hk", "hant"))+ else "Hans"+ }+ elif tag == "cs":+ mapped_script = {+ "ar": "Arab",+ "he": "Hebr",+ "hi": "Deva",+ "bn": "Beng",+ "th": "Thai",+ }.get(language.split("-")[0])+ if mapped_script:+ scripts = {mapped_script}+ mapped = (+ {+ entry.get("typeface", "").strip()+ for entry in scheme.findall("a:font", NS)+ if entry.get("script") in scripts and entry.get("typeface", "").strip()+ }+ if scheme is not None+ else set()+ )+ return next(iter(mapped)) if len(mapped) == 1 else None++ def check(+ properties: list[ET.Element | None],+ scripts: set[str],+ object_id: str,+ reference: str | None = None,+ *,+ slide_number: int = slide_number,+ ) -> None:+ nonlocal checked+ for script in sorted(scripts):+ checked += 1+ family = next(+ (name for item in properties if (name := font_element(item, script))), None+ )+ if family is None and reference in {"major", "minor"}:+ # A Latin font declaration does not define East Asian or+ # complex-script glyphs governed by this shape's theme.+ suffix = {"latin": "lt", "ea": "ea", "cs": "cs", "symbol": "lt"}[script]+ family = f"+m{'j' if reference == 'major' else 'n'}-{suffix}"+ elif family is None and script != "latin":+ family = next(+ (name for item in properties if (name := font_element(item, "latin"))), None+ )+ language = next(+ (+ item.get("lang")+ for item in properties+ if item is not None and item.get("lang")+ ),+ "",+ )+ effective = resolve(family, script, language)+ if effective:+ observed[effective] = observed.get(effective, 0) + 1+ valid = bool(effective) and (+ inventory_only+ or _font_key(effective) in allowed+ or (script != "latin" and _font_key(effective) == script_fonts.get(script))+ )+ if not valid:+ findings.append(+ {+ "kind": "unapproved_presentation_font"+ if effective+ else "unresolved_presentation_font",+ "slide": slide_number,+ "object_id": object_id,+ "script": script,+ "font_family": effective,+ }+ )++ def paragraphs(+ body: ET.Element,+ shape: ET.Element | None,+ inherited: list[ET.Element],+ object_id: str,+ extra_defaults: list[ET.Element | None] | None = None,+ *,+ master: ET.Element | None = master,+ presentation: ET.Element = presentation,+ ) -> None:+ placeholder = shape.find("p:nvSpPr/p:nvPr/p:ph", NS) if shape is not None else None+ placeholder_type = (+ placeholder.get("type", "body") if placeholder is not None else "other"+ )+ style_role = (+ "titleStyle"+ if placeholder_type in {"title", "ctrTitle"}+ else "bodyStyle"+ if placeholder_type == "body"+ else "otherStyle"+ )+ font_ref = shape.find("p:style/a:fontRef", NS) if shape is not None else None+ reference = (+ font_ref.get("idx")+ if font_ref is not None and font_ref.get("idx") in {"major", "minor"}+ else None+ )+ for paragraph in body.findall("a:p", NS):+ paragraph_properties = paragraph.find("a:pPr", NS)+ level = (+ int(paragraph_properties.get("lvl", "0")) + 1+ if paragraph_properties is not None+ else 1+ )+ if not 1 <= level <= 9:+ raise ValueError("Invalid paragraph font inheritance level")+ base = [+ paragraph.find("a:pPr/a:defRPr", NS),+ body.find(f"a:lstStyle/a:lvl{level}pPr/a:defRPr", NS),+ body.find("a:lstStyle/a:defPPr/a:defRPr", NS),+ ]+ for ancestor in inherited:+ base.extend(+ [+ ancestor.find("p:txBody/a:p/a:pPr/a:defRPr", NS),+ ancestor.find(f"p:txBody/a:lstStyle/a:lvl{level}pPr/a:defRPr", NS),+ ]+ )+ base.extend(extra_defaults or [])+ if master is not None:+ base.append(+ master.find(f"p:txStyles/p:{style_role}/a:lvl{level}pPr/a:defRPr", NS)+ )+ base.append(presentation.find(f"p:defaultTextStyle/a:lvl{level}pPr/a:defRPr", NS))+ for run in list(paragraph):+ if _local(run) not in {"r", "fld"}:+ continue+ text = "".join(node.text or "" for node in run.findall("a:t", NS))+ scripts = _text_scripts(text)+ if scripts:+ check([run.find("a:rPr", NS), *base], scripts, object_id, reference)++ displayed_parts = [slide_part]+ if slide.get("showMasterSp", "1").lower() not in {"0", "false"}:+ for part in (layout_part, master_part):+ if part and not (+ part == master_part+ and layout_part+ and root(layout_part).get("showMasterSp", "1").lower() in {"0", "false"}+ ):+ displayed_parts.append(part)+ visible_shapes = [+ shape+ for part in displayed_parts+ for shape in visible_elements(part)+ if shape.tag in {f"{{{NS['p']}}}sp", f"{{{NS['p']}}}cxnSp"}+ and (part == slide_part or shape.find("p:nvSpPr/p:nvPr/p:ph", NS) is None)+ ]+ for shape in visible_shapes:+ body = shape.find("p:txBody", NS)+ if body is None:+ continue+ inherited: list[ET.Element] = []+ placeholder = shape.find("p:nvSpPr/p:nvPr/p:ph", NS)+ if placeholder is not None:+ for part in (layout_part, master_part):+ if not part:+ continue+ matches = []+ for ancestor in root(part).findall(".//p:sp", NS):+ ph = ancestor.find("p:nvSpPr/p:nvPr/p:ph", NS)++ def role(element: ET.Element) -> str:+ value = element.get("type", "body")+ return "title" if value in {"title", "ctrTitle"} else value++ if (+ ph is not None+ and ph.get("idx", "0") == placeholder.get("idx", "0")+ and role(ph) == role(placeholder)+ ):+ matches.append(ancestor)+ if len(matches) > 1:+ raise ValueError("Ambiguous placeholder font inheritance")+ inherited.extend(matches)+ paragraphs(body, shape, inherited, _object_id(shape))+ table_bodies = [+ body+ for part in displayed_parts+ for element in visible_elements(part)+ if element.tag == f"{{{NS['a']}}}tc"+ and (body := element.find("a:txBody", NS)) is not None+ ]+ for cell_number, body in enumerate(table_bodies, 1):+ paragraphs(body, None, [], f"table-cell-{cell_number}")+ chart_references = [+ (part, element)+ for part in displayed_parts+ for element in visible_elements(part)+ if element.tag == f"{{{NS['c']}}}chart"+ ]+ for owner_part, chart_reference in chart_references:+ relation = rels(owner_part).get(chart_reference.get("{" + NS["r"] + "}id", ""))+ if (+ not relation+ or relation["mode"] != "Internal"+ or not relation["type"].endswith("/chart")+ ):+ raise ValueError("Missing or external chart font relationship")+ chart = root(relation["target"])++ def chart_defaults(style: ET.Element | None) -> list[ET.Element | None]:+ if style is None:+ return []+ return [+ style.find("a:p/a:pPr/a:defRPr", NS),+ style.find("a:lstStyle/a:lvl1pPr/a:defRPr", NS),+ style.find("a:lstStyle/a:defPPr/a:defRPr", NS),+ ]++ global_defaults = chart_defaults(chart.find("c:txPr", NS))+ for rich in chart.findall(".//c:rich", NS):+ paragraphs(rich, None, [], "chart-rich-text", global_defaults)+ label_styles = chart.findall(".//c:txPr", NS)+ if not label_styles:+ check([], {"latin"}, "chart-label-default")+ for style in label_styles:+ paragraphs(style, None, [], "chart-label-text", global_defaults)+ check([*chart_defaults(style), *global_defaults], {"latin"}, "chart-label-style")++ return findings, {+ "performed": True,+ "passed": not findings,+ "checked_text_script_count": checked,+ "observed_font_families": sorted(observed, key=str.casefold),+ "observed_font_use_counts": observed,+ "native_font_rendering_verified": False,+ }+++def inspect_reference_font_families(path: Path) -> dict[str, Any]:+ """Read fonts used by editable PPTX text or actual PDF text-show content."""+ if path.suffix.lower() == ".pptx":+ with zipfile.ZipFile(path) as package:+ presentation = ET.fromstring(package.read("ppt/presentation.xml"))+ parts = _slide_parts(package, presentation)+ findings, report = inspect_presentation_font_policy(+ package, parts, {"font_inventory_only": True}+ )+ if findings:+ raise ValueError(+ "Source typography has unresolved font inheritance; inspect it before declaring an exception"+ )+ fonts = report["observed_font_families"]+ elif path.suffix.lower() == ".pdf":+ from pypdf import PdfReader++ reader = PdfReader(path, strict=True)+ if reader.is_encrypted or not 0 < len(reader.pages) <= 9999:+ raise ValueError("Typography reference PDF must be readable and bounded")+ used: set[str] = set()+ render_mode = 0+ modes: list[int] = []++ def operand(operator, arguments, _cm, _tm):+ nonlocal render_mode+ if operator == b"q":+ modes.append(render_mode)+ elif operator == b"Q" and modes:+ render_mode = modes.pop()+ elif operator == b"Tr" and arguments:+ render_mode = int(arguments[0])++ def visitor(text, _cm, _tm, font, _size):+ if not text.strip() or render_mode in {3, 7}:+ return+ if not font:+ raise ValueError("PDF text has no resolvable font dictionary")+ descriptor = font.get("/FontDescriptor", {})+ if hasattr(descriptor, "get_object"):+ descriptor = descriptor.get_object()+ family = str(descriptor.get("/FontFamily") or font.get("/BaseFont") or "").lstrip("/")+ if not family:+ raise ValueError("PDF text has no resolvable font family")+ used.add(family)++ for page in reader.pages:+ render_mode = 0+ modes.clear()+ page.extract_text(visitor_operand_before=operand, visitor_text=visitor)+ fonts = sorted(used, key=str.casefold)+ else:+ raise ValueError("Typography reference must be PPTX or PDF")+ if not fonts:+ raise ValueError(+ "Reference has no inspectable text fonts; image-only font identity needs explicit user confirmation"+ )+ return {+ "font_families": fonts,+ "normalized_font_families": sorted({_font_key(font) for font in fonts}),+ "reference_type": path.suffix.lower()[1:],+ "native_rendering_verified": False,+ }+++def _redundant_chart_findings(+ package: zipfile.ZipFile,+ slide_part: str,+ root: ET.Element,+ slide_number: int,+ allowed_count: int,+) -> list[dict[str, Any]]:+ """Find multiple native charts whose complete evidence repeats a native table."""++ tables = root.findall(".//a:tbl", NS)+ charts = root.findall(".//p:graphicFrame//c:chart", NS)+ if not tables or len(charts) <= allowed_count:+ return []+ values = set()+ for table in tables:+ for cell in table.findall(".//a:tc", NS):+ content = "".join(node.text or "" for node in cell.findall(".//a:t", NS)).strip()+ match = re.fullmatch(+ r"\s*\$?\(?[-−+]?(\d[\d,]*(?:\.\d+)?)\)?\s*(%)?\s*",+ content,+ )+ if match is None:+ continue+ try:+ value = Decimal(match.group(1).replace(",", ""))+ except InvalidOperation:+ continue+ values.add(value)+ if match.group(2):+ values.add(value / 100)+ if not values:+ return []+ relations_path = posixpath.join(+ posixpath.dirname(slide_part),+ "_rels",+ posixpath.basename(slide_part) + ".rels",+ )+ try:+ relationships = ET.fromstring(package.read(relations_path))+ except (KeyError, ET.ParseError):+ return []+ targets = {+ relation.get("Id", ""): relation.get("Target", "")+ for relation in relationships.findall("pr:Relationship", NS)+ }+ redundant = 0+ for chart in charts:+ target = targets.get(chart.get(f"{{{NS['r']}}}id", ""))+ if not target:+ continue+ part = (+ posixpath.normpath(target.lstrip("/"))+ if target.startswith("/")+ else posixpath.normpath(posixpath.join(posixpath.dirname(slide_part), target))+ )+ if not part.startswith("ppt/"):+ continue+ try:+ chart_root = ET.fromstring(package.read(part))+ except (KeyError, ET.ParseError):+ continue+ points = []+ for series in chart_root.findall(".//c:ser", NS):+ for value in series.findall("c:val//c:numCache/c:pt/c:v", NS):+ try:+ points.append(Decimal(value.text))+ except (InvalidOperation, TypeError):+ continue+ if len(points) >= 3 and all(point in values for point in points):+ redundant += 1+ if redundant <= allowed_count:+ return []+ return [+ {+ "kind": "redundant_charts_duplicate_table",+ "slide": slide_number,+ "duplicate_chart_count": redundant,+ "allowed_duplicate_count": allowed_count,+ }+ ]+++def _folio_findings(+ slide_number: int,+ objects: list[SlideObject],+ slide_height: float,+) -> list[dict[str, Any]]:+ """Validate actual-index content folios only under an explicit task policy."""++ if slide_number == 1:+ return []+ candidates = []+ for item in objects:+ if not item.has_text or item.box.bottom < slide_height * (1 - FOOTER_REGION):+ continue+ value = " ".join(+ (node.text or "").strip() for node in item.element.findall(".//a:t", NS)+ ).strip()+ match = re.fullmatch(r"(?:page\s*)?(\d{1,4})(?:\s*/\s*\d{1,4})?", value, re.I)+ if match is None:+ continue+ raw = match.group(1)+ candidates.append((raw, int(raw), item.object_id))+ if int(raw) == slide_number:+ if len(raw) > 1 and raw.startswith("0"):+ return [+ {+ "kind": "zero_padded_slide_folio",+ "slide": slide_number,+ "object_id": item.object_id,+ }+ ]+ return []+ return [+ {+ "kind": "incorrect_or_missing_actual_slide_folio",+ "slide": slide_number,+ "numeric_footer_candidate_count": len(candidates),+ }+ ]+++def _monochrome_transparent_png(blob: bytes) -> bool:+ """Conservatively classify small alpha icon bitmaps without Pillow."""++ if len(blob) < 33 or blob[:8] != b"\x89PNG\r\n\x1a\n" or blob[12:16] != b"IHDR":+ return False+ width, height, depth, color = struct.unpack(">IIBB", blob[16:26])+ if not (+ 1 <= width <= 256+ and 1 <= height <= 256+ and width * height <= 65536+ and depth == 8+ and color == 6+ ):+ return False+ cursor = 8+ compressed = []+ while cursor + 12 <= len(blob):+ length = struct.unpack(">I", blob[cursor : cursor + 4])[0]+ kind = blob[cursor + 4 : cursor + 8]+ if length > 1048576 or cursor + 12 + length > len(blob):+ return False+ if kind == b"IDAT":+ compressed.append(blob[cursor + 8 : cursor + 8 + length])+ cursor += 12 + length+ if kind == b"IEND":+ break+ expected_length = height * (1 + 4 * width)+ try:+ decompressor = zlib.decompressobj()+ raw = decompressor.decompress(b"".join(compressed), expected_length + 1)+ except zlib.error:+ return False+ if len(raw) != expected_length or decompressor.unconsumed_tail:+ return False+ previous = bytearray(4 * width)+ colors = set()+ transparent = 0+ stride = 1 + 4 * width+ for row in range(height):+ filter_type = raw[row * stride]+ current = bytearray(raw[row * stride + 1 : (row + 1) * stride])+ if filter_type > 4:+ return False+ for index in range(len(current)):+ left = current[index - 4] if index >= 4 else 0+ above = previous[index]+ diagonal = previous[index - 4] if index >= 4 else 0+ if filter_type == 1:+ predicted = left+ elif filter_type == 2:+ predicted = above+ elif filter_type == 3:+ predicted = (left + above) // 2+ elif filter_type == 4:+ estimate = left + above - diagonal+ pa, pb, pc = (+ abs(estimate - left),+ abs(estimate - above),+ abs(estimate - diagonal),+ )+ predicted = left if pa <= pb and pa <= pc else above if pb <= pc else diagonal+ else:+ predicted = 0+ current[index] = (current[index] + predicted) & 255+ for index in range(0, len(current), 4):+ alpha = current[index + 3]+ if alpha <= 5:+ transparent += 1+ elif alpha >= 128:+ colors.add(bytes(current[index : index + 3]))+ if len(colors) > 3:+ return False+ previous = current+ return bool(colors) and transparent >= width * height * 0.12+++def _slide_relationship_targets(package: zipfile.ZipFile, slide_part: str) -> dict[str, str]:+ path = posixpath.join(+ posixpath.dirname(slide_part),+ "_rels",+ posixpath.basename(slide_part) + ".rels",+ )+ try:+ root = ET.fromstring(package.read(path))+ except (KeyError, ET.ParseError):+ return {}+ return {+ entry.get("Id", ""): entry.get("Target", "")+ for entry in root.findall("pr:Relationship", NS)+ }+++def _decorative_icon_findings(+ package: zipfile.ZipFile,+ parts: list[str],+ slide_width: float,+ slide_height: float,+ policy: dict[str, Any],+) -> list[dict[str, Any]]:+ """Reject invented pictogram programs while preserving authorized assets."""++ approved_hashes = {value.lower() for value in policy.get("approved_image_sha256", [])}+ if any(re.fullmatch(r"[0-9a-f]{64}", value) is None for value in approved_hashes):+ raise ValueError("approved image hashes must be exact SHA-256 values")+ approved_slides = set(policy.get("approved_icon_slides", []))+ if any(number < 1 for number in approved_slides):+ raise ValueError("approved icon slide numbers must be positive")+ findings = []+ zones: dict[str, set[int]] = {+ "header": set(),+ "body_gutter": set(),+ "left_body_gutter": set(),+ }+ explicitly_named_native_icon_slides: set[int] = set()+ explicitly_named_native_cover_icon: str | None = None+ cache: dict[str, bool] = {}+ pending_native_cover: str | None = None+ for slide_number, part in enumerate(parts, start=1):+ if slide_number in approved_slides:+ continue+ root = ET.fromstring(package.read(part))+ targets = _slide_relationship_targets(package, part)+ monochrome_count = 0+ cover_flagged = False+ native_header_candidates: list[SlideObject] = []+ for item in _slide_objects(root):+ if item.has_text or item.kind not in {"pic", "sp"}:+ continue+ is_picture = item.kind == "pic"+ if not is_picture:+ properties = item.element.find("p:nvSpPr/p:cNvPr", NS)+ object_name = (+ properties.get("name", "").strip().casefold() if properties is not None else ""+ )+ if object_name.startswith("icon-"):+ if slide_number == 1:+ explicitly_named_native_cover_icon = item.object_id+ else:+ explicitly_named_native_icon_slides.add(slide_number)+ if is_picture:+ blip = item.element.find("p:blipFill/a:blip", NS)+ if blip is None:+ continue+ target = targets.get(blip.get(f"{{{NS['r']}}}embed", ""))+ if not target:+ continue+ media_part = (+ posixpath.normpath(target.lstrip("/"))+ if target.startswith("/")+ else posixpath.normpath(posixpath.join(posixpath.dirname(part), target))+ )+ if not media_part.startswith("ppt/media/"):+ continue+ try:+ blob = package.read(media_part)+ except KeyError:+ continue+ digest = hashlib.sha256(blob).hexdigest()+ if digest in approved_hashes:+ continue+ if digest not in cache:+ cache[digest] = _monochrome_transparent_png(blob)+ if not cache[digest]:+ continue+ else:+ custom = item.element.find("p:spPr/a:custGeom", NS)+ preset = item.element.find("p:spPr/a:prstGeom", NS)+ if custom is None and (+ preset is None or preset.get("prst") not in {"ellipse", "donut"}+ ):+ continue++ x = item.box.x / slide_width+ y = item.box.y / slide_height+ area = item.box.width * item.box.height / (slide_width * slide_height)+ if is_picture and 0.0005 <= area <= 0.05:+ monochrome_count += 1+ if slide_number == 1:+ if not cover_flagged:+ if is_picture and x >= 0.65 and y <= 0.55 and 0.008 <= area <= 0.06:+ findings.append(+ {+ "kind": "unapproved_decorative_cover_icon",+ "slide": 1,+ "object_id": item.object_id,+ }+ )+ cover_flagged = True+ elif (+ not is_picture+ and (x <= 0.30 or x >= 0.65)+ and 0.08 <= y <= 0.65+ and 0.0015 <= area <= 0.06+ ):+ pending_native_cover = item.object_id+ cover_flagged = True+ continue+ if x >= 0.74 and y <= 0.22 and 0.0012 <= area <= 0.04:+ if is_picture:+ zones["header"].add(slide_number)+ else:+ native_header_candidates.append(item)+ elif is_picture and x >= 0.72 and 0.22 <= y <= 0.48 and 0.008 <= area <= 0.05:+ zones["body_gutter"].add(slide_number)+ elif is_picture and x <= 0.16 and 0.24 <= y <= 0.55 and 0.0008 <= area <= 0.012:+ # A recurring tiny monochrome pictogram in the left body gutter+ # is decorative even when its peer is not in the right header.+ # Authentic photographs, approved hashes/slides, native diagrams,+ # isolated icons, and meaningful rating rows remain unaffected.+ zones["left_body_gutter"].add(slide_number)+ if native_header_candidates:+ disjoint = []+ for item in sorted(native_header_candidates, key=lambda value: value.box.x):+ if not disjoint or item.box.x >= disjoint[-1].box.right - EMU_PER_POINT:+ disjoint.append(item)+ widths = [item.box.width for item in disjoint]+ functional_scorecard = (+ len(disjoint) >= 3+ and all(+ abs(item.box.y - disjoint[0].box.y) <= 2 * EMU_PER_POINT for item in disjoint+ )+ and min(widths) > 0+ and max(widths) / min(widths) <= 1.25+ )+ if not functional_scorecard:+ zones["header"].add(slide_number)+ if slide_number != 1 and monochrome_count >= 3:+ findings.append(+ {+ "kind": "unapproved_decorative_icon_cluster",+ "slide": slide_number,+ "icon_count": monochrome_count,+ }+ )+ for zone, slides in zones.items():+ if len(slides) >= 3:+ findings.append(+ {+ "kind": "repeated_unapproved_decorative_icons",+ "zone": zone,+ "slides": sorted(slides),+ "slide_count": len(slides),+ }+ )+ if pending_native_cover is not None and len(zones["header"]) >= 3:+ findings.append(+ {+ "kind": "unapproved_decorative_cover_icon",+ "slide": 1,+ "object_id": pending_native_cover,+ }+ )+ if len(explicitly_named_native_icon_slides) >= 3:+ findings.append(+ {+ "kind": "repeated_unapproved_decorative_icons",+ "zone": "explicitly_named_native_icons",+ "slides": sorted(explicitly_named_native_icon_slides),+ "slide_count": len(explicitly_named_native_icon_slides),+ }+ )+ if explicitly_named_native_cover_icon is not None and not any(+ entry["kind"] == "unapproved_decorative_cover_icon" for entry in findings+ ):+ findings.append(+ {+ "kind": "unapproved_decorative_cover_icon",+ "slide": 1,+ "object_id": explicitly_named_native_cover_icon,+ }+ )+ return findings+++def _approved_logo_findings(+ package: zipfile.ZipFile,+ parts: list[str],+ slide_width: float,+ slide_height: float,+ policy: dict[str, Any],+) -> list[dict[str, Any]]:+ """Measure only logo assets independently authenticated by the caller."""++ hashes = {value.lower() for value in policy.get("approved_logo_sha256", [])}+ if any(re.fullmatch(r"[0-9a-f]{64}", value) is None for value in hashes):+ raise ValueError("approved logo hashes must be exact SHA-256 values")+ maximum = policy.get("max_logo_area")+ require_bottom_left = bool(policy.get("require_logo_bottom_left"))+ if (maximum is not None or require_bottom_left) and not hashes:+ raise ValueError("logo geometry rules require an independently approved logo hash")+ if maximum is not None and not 0 < maximum <= 1:+ raise ValueError("maximum logo area must be greater than zero and at most one")+ if not hashes:+ return []+ exceptions = set(policy.get("approved_logo_placement_slides", []))+ if any(number < 1 for number in exceptions):+ raise ValueError("approved logo placement slide numbers must be positive")+ findings = []+ for number, part in enumerate(parts, start=1):+ root = ET.fromstring(package.read(part))+ targets = _slide_relationship_targets(package, part)+ for item in _slide_objects(root):+ if item.kind != "pic":+ continue+ blip = item.element.find("p:blipFill/a:blip", NS)+ target = targets.get(blip.get(f"{{{NS['r']}}}embed", "")) if blip is not None else None+ if not target:+ continue+ media_part = (+ posixpath.normpath(target.lstrip("/"))+ if target.startswith("/")+ else posixpath.normpath(posixpath.join(posixpath.dirname(part), target))+ )+ if not media_part.startswith("ppt/media/"):+ continue+ try:+ digest = hashlib.sha256(package.read(media_part)).hexdigest()+ except KeyError:+ continue+ if digest not in hashes:+ continue+ area = item.box.width * item.box.height / (slide_width * slide_height)+ if maximum is not None and area > maximum:+ findings.append(+ {+ "kind": "approved_logo_area_exceeded",+ "slide": number,+ "object_id": item.object_id,+ "actual_area_ratio": round(area, 5),+ "maximum_area_ratio": maximum,+ }+ )+ if (+ require_bottom_left+ and number not in exceptions+ and not (+ item.box.x / slide_width <= 0.25+ and item.box.right / slide_width <= 0.40+ and item.box.y / slide_height >= 0.65+ and item.box.bottom / slide_height <= 0.97+ )+ ):+ findings.append(+ {+ "kind": "approved_logo_not_bottom_left",+ "slide": number,+ "object_id": item.object_id,+ }+ )+ return findings+++def _content_prose_findings(+ slide_number: int, objects: list[SlideObject], max_words: int+) -> list[dict[str, Any]]:+ """Count editable explanatory shapes, excluding native table/chart values."""++ if slide_number == 1:+ return []+ word_count = sum(+ len(+ re.findall(+ r"\b[\w’'-]+\b",+ " ".join(node.text or "" for node in item.element.findall(".//a:t", NS)),+ )+ )+ for item in objects+ if item.kind == "sp" and item.has_text+ )+ if word_count <= max_words:+ return []+ return [+ {+ "kind": "content_prose_density_exceeded",+ "slide": slide_number,+ "word_count": word_count,+ "word_limit": max_words,+ }+ ]+++def _native_bullet_findings(+ slide_number: int,+ objects: list[SlideObject],+ slide_width: float,+ *,+ validate_geometry: bool,+ require_editorial: bool,+) -> list[dict[str, Any]]:+ """Inspect real bullet geometry and explicitly designated editorial roles."""++ findings: list[dict[str, Any]] = []+ primary_bullets: list[SlideObject] = []+ for item in objects:+ if item.kind != "sp" or not item.has_text:+ continue+ for paragraph_index, paragraph in enumerate(+ item.element.findall("p:txBody/a:p", NS), start=1+ ):+ properties = paragraph.find("a:pPr", NS)+ if properties is None or not (+ properties.find("a:buChar", NS) is not None+ or properties.find("a:buAutoNum", NS) is not None+ ):+ continue+ if require_editorial and item.box.width >= slide_width * 0.50:+ primary_bullets.append(item)+ if not validate_geometry:+ continue+ malformed = {}+ for attribute in ("marL", "indent"):+ raw = properties.get(attribute)+ if raw is None:+ continue+ try:+ value = int(raw)+ except ValueError:+ continue+ if 0 < abs(value) < 1000:+ malformed[attribute] = value+ if malformed:+ findings.append(+ {+ "kind": "malformed_native_bullet_geometry",+ "slide": slide_number,+ "object_id": item.object_id,+ "paragraph_index": paragraph_index,+ "actual_emu": malformed,+ "emu_per_point": EMU_PER_POINT,+ }+ )++ if not require_editorial or len(primary_bullets) < 4:+ return findings++ tolerance = slide_width * 0.035+ groups: list[list[SlideObject]] = []+ for item in sorted(primary_bullets, key=lambda value: value.box.x):+ for group in groups:+ if abs(item.box.x - group[0].box.x) <= tolerance:+ group.append(item)+ break+ else:+ groups.append([item])+ dominant = max(groups, key=len, default=[])+ if len(dominant) >= 4:+ findings.append(+ {+ "kind": "primary_bullet_wall_on_editorial_slide",+ "slide": slide_number,+ "native_bullet_count": len(dominant),+ "distinct_text_shape_count": len({item.object_id for item in dominant}),+ "maximum_region_width_ratio": round(+ max(item.box.width for item in dominant) / slide_width, 4+ ),+ }+ )+ return findings+++def inspect_presentation(+ path: str | Path, *, policy: dict[str, Any] | None = None+) -> dict[str, Any]:+ with zipfile.ZipFile(path) as package:+ presentation = ET.fromstring(package.read("ppt/presentation.xml"))+ size = presentation.find("p:sldSz", NS)+ if size is None:+ raise ValueError("presentation has no slide dimensions")+ width, height = float(size.get("cx", "0")), float(size.get("cy", "0"))+ parts = _slide_parts(package, presentation)+ findings = (+ _presentation_policy_findings(package, presentation, parts, policy) if policy else []+ )+ font_policy_report = None+ if policy and (+ policy.get("required_default_font_family") or policy.get("approved_font_families")+ ):+ font_findings, font_policy_report = inspect_presentation_font_policy(+ package, parts, policy+ )+ findings.extend(font_findings)+ if (+ policy+ and policy.get("require_uniform_font_family")+ and not policy.get("required_default_font_family")+ and not policy.get("approved_font_families")+ ):+ findings.extend(_uniform_presentation_font_findings(package, parts))+ if policy and policy.get("forbid_unapproved_decorative_icons"):+ findings.extend(_decorative_icon_findings(package, parts, width, height, policy))+ if policy and (+ policy.get("approved_logo_sha256")+ or policy.get("max_logo_area") is not None+ or policy.get("require_logo_bottom_left")+ ):+ findings.extend(_approved_logo_findings(package, parts, width, height, policy))+ for number, part in enumerate(parts, start=1):+ root = ET.fromstring(package.read(part))+ objects = _slide_objects(root)+ findings.extend(_connector_findings(number, objects))+ findings.extend(_text_overlap_findings(number, objects))+ findings.extend(_repeated_wrapped_body_heading_overlap_findings(number, objects))+ findings.extend(_text_overflow_findings(number, objects))+ findings.extend(_dense_bold_paragraph_findings(number, objects))+ if policy:+ approved_heading_slides = policy.get("approved_heading_slides", [])+ if policy.get("validate_heading_fit"):+ findings.extend(_heading_fit_findings(number, objects, width, height))+ if (+ policy.get("validate_heading_punctuation")+ and number not in approved_heading_slides+ ):+ findings.extend(_heading_punctuation_findings(number, objects, width, height))+ approved_bullet_slides = policy.get("approved_bullet_slides", [])+ validate_bullet_geometry = bool(policy.get("validate_bullet_geometry"))+ require_editorial = (+ number in policy.get("require_editorial_slides", [])+ and number not in approved_bullet_slides+ )+ if validate_bullet_geometry or require_editorial:+ findings.extend(+ _native_bullet_findings(+ number,+ objects,+ width,+ validate_geometry=validate_bullet_geometry,+ require_editorial=require_editorial,+ )+ )+ allowed_redundant = policy.get("max_redundant_table_charts")+ exemptions = policy.get("approved_redundant_chart_slides", [])+ if allowed_redundant is not None and number not in exemptions:+ findings.extend(+ _redundant_chart_findings(package, part, root, number, allowed_redundant)+ )+ if policy.get("folio_mode") == "actual_unpadded":+ findings.extend(_folio_findings(number, objects, height))+ max_words = policy.get("max_content_prose_words")+ approved_dense = policy.get("approved_dense_slides", [])+ if max_words is not None and number not in approved_dense:+ findings.extend(_content_prose_findings(number, objects, max_words))+ findings.extend(_slide_boundary_findings(number, objects, width, height))+ findings.extend(_table_findings(number, objects, height))++ # Estimated text metrics and inferred object roles cannot establish a broken+ # layout. Background bleed, deliberate layering, and grouped objects need+ # rendered review. Only independently declared, measurable requirements block.+ def diagnostic(finding: dict[str, Any]) -> bool:+ return finding["kind"] in STYLE_REVIEW_KINDS or (+ finding["kind"] == "cover_prose_density_exceeded"+ and (policy or {}).get("cover_word_limit") is None+ )++ warnings = [finding for finding in findings if diagnostic(finding)]+ findings = [finding for finding in findings if not diagnostic(finding)]+ return {+ "slide_count": len(parts),+ "slide_size_in": [+ round(width / EMU_PER_INCH, 4),+ round(height / EMU_PER_INCH, 4),+ ],+ "finding_count": len(findings),+ "findings": findings,+ "warning_count": len(warnings),+ "warnings": warnings,+ **({"font_policy": font_policy_report} if font_policy_report is not None else {}),+ }+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description="Inspect PPTX connector layering and native table fit."+ )+ parser.add_argument("pptx", type=Path, help="PowerPoint file to inspect")+ parser.add_argument(+ "--inspect-font-families",+ action="store_true",+ help="Inspect only used text font families in a PPTX or PDF reference",+ )+ parser.add_argument(+ "--fail-on-findings",+ action="store_true",+ help="Exit nonzero when one or more layout defects are detected",+ )+ parser.add_argument("--expected-aspect", help="Explicit task aspect ratio as N:D")+ parser.add_argument(+ "--expected-slide-size-emu",+ help="Approved template's exact physical slide dimensions as CX,CY",+ )+ parser.add_argument("--expected-slide-count", type=int)+ parser.add_argument("--require-native-table-slide", action="append", type=int, default=[])+ parser.add_argument("--require-editorial-slide", action="append", type=int, default=[])+ parser.add_argument("--require-uniform-font-family", action="store_true")+ parser.add_argument("--required-default-font-family")+ parser.add_argument("--approved-font-family", action="append", default=[])+ parser.add_argument("--approved-script-font", action="append", default=[])+ parser.add_argument("--validate-bullet-geometry", action="store_true")+ parser.add_argument("--validate-heading-fit", action="store_true")+ parser.add_argument("--validate-heading-punctuation", action="store_true")+ parser.add_argument("--approved-heading-slide", action="append", type=int, default=[])+ parser.add_argument("--approved-bullet-slide", action="append", type=int, default=[])+ parser.add_argument(+ "--cover-role", choices=("none", "cover", "explicit_hybrid"), default="none"+ )+ parser.add_argument("--cover-word-limit", type=int)+ parser.add_argument("--allow-cover-chart", action="store_true")+ parser.add_argument("--allow-cover-table", action="store_true")+ parser.add_argument("--max-redundant-table-charts", type=int)+ parser.add_argument("--approved-redundant-chart-slide", action="append", type=int, default=[])+ parser.add_argument("--max-content-prose-words", type=int)+ parser.add_argument("--approved-dense-slide", action="append", type=int, default=[])+ parser.add_argument("--forbid-unapproved-decorative-icons", action="store_true")+ parser.add_argument("--approved-image-sha256", action="append", default=[])+ parser.add_argument("--approved-icon-slide", action="append", type=int, default=[])+ parser.add_argument("--approved-logo-sha256", action="append", default=[])+ parser.add_argument("--max-logo-area", type=float)+ parser.add_argument("--require-logo-bottom-left", action="store_true")+ parser.add_argument("--approved-logo-placement-slide", action="append", type=int, default=[])+ parser.add_argument("--folio-mode", choices=("none", "actual_unpadded"), default="none")+ arguments = parser.parse_args(argv)+ if arguments.inspect_font_families:+ try:+ print(json.dumps(inspect_reference_font_families(arguments.pptx), sort_keys=True))+ except Exception as exc:+ print(+ json.dumps(+ {"error": "reference_font_inspection_failed", "error_type": type(exc).__name__}+ ),+ file=sys.stderr,+ )+ return 2+ return 0+ policy = {+ "expected_aspect": arguments.expected_aspect,+ "expected_slide_size_emu": arguments.expected_slide_size_emu,+ "expected_slide_count": arguments.expected_slide_count,+ "require_native_table_slides": arguments.require_native_table_slide,+ "require_editorial_slides": arguments.require_editorial_slide,+ "require_uniform_font_family": arguments.require_uniform_font_family,+ "required_default_font_family": arguments.required_default_font_family,+ "approved_font_families": arguments.approved_font_family,+ "approved_script_fonts": arguments.approved_script_font,+ "validate_bullet_geometry": arguments.validate_bullet_geometry,+ "validate_heading_fit": arguments.validate_heading_fit,+ "validate_heading_punctuation": arguments.validate_heading_punctuation,+ "approved_heading_slides": arguments.approved_heading_slide,+ "approved_bullet_slides": arguments.approved_bullet_slide,+ "cover_role": arguments.cover_role,+ "cover_word_limit": arguments.cover_word_limit,+ "allow_cover_chart": arguments.allow_cover_chart,+ "allow_cover_table": arguments.allow_cover_table,+ "max_redundant_table_charts": arguments.max_redundant_table_charts,+ "approved_redundant_chart_slides": arguments.approved_redundant_chart_slide,+ "max_content_prose_words": arguments.max_content_prose_words,+ "approved_dense_slides": arguments.approved_dense_slide,+ "forbid_unapproved_decorative_icons": arguments.forbid_unapproved_decorative_icons,+ "approved_image_sha256": arguments.approved_image_sha256,+ "approved_icon_slides": arguments.approved_icon_slide,+ "approved_logo_sha256": arguments.approved_logo_sha256,+ "max_logo_area": arguments.max_logo_area,+ "require_logo_bottom_left": arguments.require_logo_bottom_left,+ "approved_logo_placement_slides": arguments.approved_logo_placement_slide,+ "folio_mode": arguments.folio_mode,+ }+ enabled = any(value not in (None, False, "none", []) for value in policy.values())+ try:+ report = inspect_presentation(arguments.pptx, policy=policy if enabled else None)+ except (OSError, KeyError, ValueError, zipfile.BadZipFile, ET.ParseError) as exc:+ print(json.dumps({"error": str(exc)}), file=sys.stderr)+ return 2+ print(json.dumps(report, indent=2, sort_keys=True))+ return int(arguments.fail_on_findings and bool(report["findings"]))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/paper-fig/container_tools/inspect_presentation_package_integrity.py b/skills/paper-fig/container_tools/inspect_presentation_package_integrity.pynew file mode 100644index 0000000..311126d--- /dev/null+++ b/skills/paper-fig/container_tools/inspect_presentation_package_integrity.py@@ -0,0 +1,710 @@+#!/usr/bin/env python3+"""Inspect PPTX structure without reading slide text, notes, formulas, or values.++This is a conservative structural diagnostic, not complete ECMA-376 schema+validation or proof that Microsoft PowerPoint opens a presentation successfully.+The XML parser deliberately installs no character-data handler. Notes and+embedded workbooks are never parsed.+"""++from __future__ import annotations++import argparse+import json+import posixpath+import sys+import zipfile+from dataclasses import dataclass+from pathlib import Path, PurePosixPath+from typing import Any+from xml.parsers import expat++P = "http://schemas.openxmlformats.org/presentationml/2006/main"+A = "http://schemas.openxmlformats.org/drawingml/2006/main"+C = "http://schemas.openxmlformats.org/drawingml/2006/chart"+R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+PR = "http://schemas.openxmlformats.org/package/2006/relationships"+CT = "http://schemas.openxmlformats.org/package/2006/content-types"+XSI = "http://www.w3.org/2001/XMLSchema-instance"+MC = "http://schemas.openxmlformats.org/markup-compatibility/2006"+REL_SLIDE = R + "/slide"+REL_CHART = R + "/chart"+REL_NOTES = R + "/notesSlide"+REL_OFFICE = R + "/officeDocument"+MAX_PARTS = 10_000+MAX_UNCOMPRESSED_BYTES = 512 * 1024 * 1024++# These sequences are narrowly selected, well-established Office XML particles.+DLBL_ORDER = {+ "idx": 0,+ "delete": 1,+ "layout": 2,+ "tx": 3,+ "numFmt": 4,+ "spPr": 5,+ "txPr": 6,+ "dLblPos": 7,+ "showLegendKey": 8,+ "showVal": 9,+ "showCatName": 10,+ "showSerName": 11,+ "showPercent": 12,+ "showBubbleSize": 13,+ "separator": 14,+ "extLst": 15,+}+RUN_FILL = {"noFill", "solidFill", "gradFill", "blipFill", "pattFill", "grpFill"}+RUN_FONT = {"latin", "ea", "cs", "sym"}+DRAWABLE = {"sp", "pic", "cxnSp", "graphicFrame", "grpSp"}+REL_ATTRIBUTES = {"id", "embed", "link"}+++@dataclass(frozen=True)+class Relationship:+ identifier: str+ relationship_type: str+ target: str+ external: bool+++@dataclass(frozen=True)+class Element:+ uri: str+ local: str+ attributes: dict[tuple[str, str], str]+ namespaces: dict[str, str]+ children: list["Element"]++ def attribute(self, name: str, namespace: str = "") -> str | None:+ return self.attributes.get((namespace, name))+++class PackageIntegrityError(ValueError):+ """The input is unsafe or cannot be inspected as a PPTX package."""+++def _expanded(name: str) -> tuple[str, str]:+ return tuple(name.split(" ", 1)) if " " in name else ("", name)+++def _parse_xml(payload: bytes, part: str) -> tuple[Element, list[dict[str, Any]]]:+ """Parse element/attribute events only; character data is never collected."""++ parser = expat.ParserCreate(namespace_separator=" ")+ parser.buffer_text = False+ parser.ordered_attributes = False+ parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)+ stack: list[Element] = []+ pending_namespaces: dict[str, str] = {}+ issues: list[dict[str, Any]] = []+ root: Element | None = None++ def forbidden(*_: object) -> None:+ raise PackageIntegrityError(f"DTD or entity declarations are forbidden in {part}")++ def namespace(prefix: str | None, uri: str | None) -> None:+ pending_namespaces[prefix or ""] = uri or ""++ def start(name: str, raw_attributes: dict[str, str]) -> None:+ nonlocal root+ inherited = (+ dict(stack[-1].namespaces) if stack else {"xml": "http://www.w3.org/XML/1998/namespace"}+ )+ inherited.update(pending_namespaces)+ pending_namespaces.clear()+ uri, local = _expanded(name)+ attributes = {_expanded(key): value for key, value in raw_attributes.items()}+ element = Element(uri, local, attributes, inherited, [])+ if stack:+ stack[-1].children.append(element)+ elif root is None:+ root = element+ else:+ raise PackageIntegrityError(f"multiple document roots in {part}")++ qname = element.attribute("type", XSI)+ if qname and ":" in qname and qname.split(":", 1)[0] not in inherited:+ issues.append(_finding("undefined_qname_prefix", part, prefix=qname.split(":", 1)[0]))+ for attribute in ("Ignorable", "ProcessContent", "PreserveElements", "PreserveAttributes"):+ prefixes = element.attribute(attribute, MC)+ if prefixes:+ for prefix in prefixes.split():+ if prefix.split(":", 1)[0] not in inherited:+ issues.append(+ _finding("undefined_qname_prefix", part, prefix=prefix.split(":", 1)[0])+ )+ stack.append(element)++ def end(_: str) -> None:+ stack.pop()++ parser.StartDoctypeDeclHandler = forbidden+ parser.EntityDeclHandler = forbidden+ parser.ExternalEntityRefHandler = lambda *_: 0+ parser.StartNamespaceDeclHandler = namespace+ parser.StartElementHandler = start+ parser.EndElementHandler = end+ # Intentionally do not install CharacterDataHandler or DefaultHandler.+ try:+ parser.Parse(payload, True)+ except expat.ExpatError as exc:+ raise PackageIntegrityError(f"invalid XML in {part}: {exc}") from exc+ if root is None:+ raise PackageIntegrityError(f"XML document has no root: {part}")+ return root, issues+++def _finding(code: str, part: str, **attributes: object) -> dict[str, Any]:+ return {"code": code, "part": part, **attributes}+++def _descendants(element: Element):+ for child in element.children:+ yield child+ yield from _descendants(child)+++def _relationship_part(source: str) -> str:+ directory, filename = posixpath.split(source)+ return posixpath.join(directory, "_rels", filename + ".rels")+++def _source_part(relationships: str) -> str:+ if relationships == "_rels/.rels":+ return ""+ directory, filename = posixpath.split(relationships)+ if not directory.endswith("/_rels") or not filename.endswith(".rels"):+ raise PackageIntegrityError(f"invalid relationships part path: {relationships}")+ return posixpath.join(directory[:-6], filename[:-5])+++def _target(source: str, target: str) -> str:+ normalized = (+ posixpath.normpath(target.lstrip("/"))+ if target.startswith("/")+ else posixpath.normpath(posixpath.join(posixpath.dirname(source), target))+ )+ if normalized in {"", ".", ".."} or normalized.startswith("../"):+ raise PackageIntegrityError(f"relationship target escapes package: {source}")+ return normalized+++def _content_types(root: Element) -> tuple[dict[str, str], dict[str, str]]:+ if (root.uri, root.local) != (CT, "Types"):+ raise PackageIntegrityError("[Content_Types].xml has an invalid root")+ defaults: dict[str, str] = {}+ overrides: dict[str, str] = {}+ for item in root.children:+ if item.uri != CT or item.local not in {"Default", "Override"}:+ continue+ content_type = item.attribute("ContentType")+ key = item.attribute("Extension" if item.local == "Default" else "PartName")+ if not key or not content_type:+ raise PackageIntegrityError("content-types entry is incomplete")+ if item.local == "Default":+ if key.casefold() in defaults:+ raise PackageIntegrityError("duplicate content-type default")+ defaults[key.casefold()] = content_type+ else:+ normalized = key.lstrip("/")+ if normalized in overrides:+ raise PackageIntegrityError("duplicate content-type override")+ overrides[normalized] = content_type+ return defaults, overrides+++def _content_types_namespace_findings(payload: bytes) -> list[dict[str, Any]]:+ """Reject prefixed OPC manifest tags that the first-party .NET reader rejects."""++ parser = expat.ParserCreate()+ parser.buffer_text = False+ parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_NEVER)+ depth = 0+ child_reported = False+ issues: list[dict[str, Any]] = []++ def start(name: str, attributes: dict[str, str]) -> None:+ nonlocal depth, child_reported+ if depth == 0 and (name != "Types" or attributes.get("xmlns") != CT):+ issues.append(+ _finding("content_types_default_namespace_required", "[Content_Types].xml")+ )+ elif depth == 1 and name not in {"Default", "Override"} and not child_reported:+ issues.append(+ _finding("content_types_unqualified_child_required", "[Content_Types].xml")+ )+ child_reported = True+ depth += 1++ def end(_: str) -> None:+ nonlocal depth+ depth -= 1++ def forbidden(*_: object) -> None:+ raise PackageIntegrityError(+ "DTD or entity declarations are forbidden in [Content_Types].xml"+ )++ parser.StartDoctypeDeclHandler = forbidden+ parser.EntityDeclHandler = forbidden+ parser.ExternalEntityRefHandler = lambda *_: 0+ parser.StartElementHandler = start+ parser.EndElementHandler = end+ try:+ parser.Parse(payload, True)+ except expat.ExpatError as exc:+ raise PackageIntegrityError(f"invalid XML in [Content_Types].xml: {exc}") from exc+ return issues+++def _has_content_type(part: str, defaults: dict[str, str], overrides: dict[str, str]) -> bool:+ if part in overrides:+ return True+ suffix = "rels" if part.endswith(".rels") else PurePosixPath(part).suffix.lstrip(".").casefold()+ return bool(suffix and suffix in defaults)+++def _relationships(root: Element, part: str) -> dict[str, Relationship]:+ if (root.uri, root.local) != (PR, "Relationships"):+ raise PackageIntegrityError(f"invalid relationships root in {part}")+ result = {}+ for item in root.children:+ if (item.uri, item.local) != (PR, "Relationship"):+ continue+ identifier = item.attribute("Id")+ kind = item.attribute("Type")+ target = item.attribute("Target")+ if not identifier or not kind or not target:+ raise PackageIntegrityError(f"incomplete relationship in {part}")+ if identifier in result:+ raise PackageIntegrityError(f"duplicate relationship id {identifier} in {part}")+ result[identifier] = Relationship(+ identifier, kind, target, item.attribute("TargetMode") == "External"+ )+ return result+++def _choice_findings(root: Element, part: str) -> list[dict[str, Any]]:+ findings = []+ for item in _descendants(root):+ if item.uri == C and item.local in {"strCache", "strLit"}:+ for child in item.children:+ if (child.uri, child.local) == (C, "formatCode"):+ findings.append(+ _finding(+ "string_cache_format_code_forbidden",+ part,+ element=item.local,+ )+ )+ if item.uri != C or item.local not in {"cat", "val", "xVal", "yVal", "bubbleSize", "tx"}:+ continue+ children = [child.local for child in item.children if child.uri == C]+ for alternatives in ({"numRef", "numLit"}, {"strRef", "strLit"}):+ present = [name for name in children if name in alternatives]+ if len(present) > 1:+ findings.append(+ _finding(+ "chart_source_exclusive_choice",+ part,+ element=item.local,+ alternatives=present,+ )+ )+ return findings+++def _order_findings(root: Element, part: str) -> list[dict[str, Any]]:+ findings = []+ for item in _descendants(root):+ if item.uri == C and item.local == "dLbl":+ children = [+ child.local+ for child in item.children+ if child.uri == C and child.local in DLBL_ORDER+ ]+ positions = [DLBL_ORDER[name] for name in children]+ if positions != sorted(positions):+ findings.append(_finding("chart_dlbl_child_order", part, children=children))+ if item.uri == A and item.local in {"rPr", "defRPr", "endParaRPr"}:+ font_seen = False+ for child in item.children:+ if child.uri != A:+ continue+ if child.local in RUN_FONT:+ font_seen = True+ elif font_seen and child.local in RUN_FILL:+ findings.append(+ _finding("drawing_run_properties_child_order", part, element=item.local)+ )+ break+ return findings+++def _children(element: Element, uri: str, local: str) -> list[Element]:+ return [child for child in element.children if (child.uri, child.local) == (uri, local)]+++def _label_show_value(labels: Element | None) -> bool | None:+ if labels is None:+ return None+ values = _children(labels, C, "showVal")+ if not values:+ return None+ return values[-1].attribute("val") not in {"0", "false"}+++def _invisible_series(element: Element) -> tuple[bool, bool]:+ properties = _children(element, C, "spPr")+ if not properties:+ return False, False+ style = properties[0]+ hidden = bool(_children(style, A, "noFill"))+ lines = _children(style, A, "ln")+ visible_outline = bool(+ lines+ and not _children(lines[0], A, "noFill")+ and (+ _children(lines[0], A, "solidFill")+ or _children(lines[0], A, "gradFill")+ or lines[0].attribute("w") not in {None, "", "0"}+ )+ )+ return hidden, visible_outline+++def _element_index(element: Element) -> str | None:+ indices = _children(element, C, "idx")+ return indices[0].attribute("val") if indices else None+++def _effective_point_labels(+ labels: Element | None,+ inherited: bool | None,+) -> dict[str | None, bool | None]:+ if labels is None:+ return {}+ result: dict[str | None, bool | None] = {}+ for point in _children(labels, C, "dLbl"):+ explicit = _label_show_value(point)+ result[_element_index(point)] = explicit if explicit is not None else inherited+ return result+++def _stacked_chart_findings(root: Element, part: str) -> list[dict[str, Any]]:+ findings: list[dict[str, Any]] = []+ for chart in _descendants(root):+ if (chart.uri, chart.local) != (C, "barChart"):+ continue+ groupings = _children(chart, C, "grouping")+ grouping = groupings[0].attribute("val") if groupings else None+ if grouping not in {"stacked", "percentStacked"}:+ continue++ for position in _descendants(chart):+ if (position.uri, position.local) == (C, "dLblPos") and position.attribute(+ "val"+ ) == "outEnd":+ findings.append(+ _finding(+ "stacked_chart_outside_end_label_forbidden",+ part,+ grouping=grouping,+ )+ )++ chart_labels = _children(chart, C, "dLbls")+ inherited_show_value = _label_show_value(chart_labels[0] if chart_labels else None)+ inherited_point_labels = _effective_point_labels(+ chart_labels[0] if chart_labels else None,+ inherited_show_value,+ )+ for index, series in enumerate(_children(chart, C, "ser")):+ hidden, visible_outline = _invisible_series(series)+ series_labels = _children(series, C, "dLbls")+ explicit_show_value = _label_show_value(series_labels[0] if series_labels else None)+ effective_show_value = (+ explicit_show_value if explicit_show_value is not None else inherited_show_value+ )+ effective_points = {+ **inherited_point_labels,+ **_effective_point_labels(+ series_labels[0] if series_labels else None,+ effective_show_value,+ ),+ }+ if hidden and visible_outline:+ findings.append(+ _finding(+ "stacked_chart_hidden_offset_visible_outline",+ part,+ grouping=grouping,+ series_index=index,+ )+ )+ if hidden and (effective_show_value or any(effective_points.values())):+ findings.append(+ _finding(+ "stacked_chart_hidden_offset_value_label",+ part,+ grouping=grouping,+ series_index=index,+ )+ )+ for point in _children(series, C, "dPt"):+ point_hidden, point_outline = _invisible_series(point)+ point_index = _element_index(point)+ if not hidden and not point_hidden:+ continue+ if point_outline:+ findings.append(+ _finding(+ "stacked_chart_hidden_offset_visible_outline",+ part,+ grouping=grouping,+ series_index=index,+ point_index=point_index,+ )+ )+ if effective_points.get(point_index, effective_show_value) and not hidden:+ findings.append(+ _finding(+ "stacked_chart_hidden_offset_value_label",+ part,+ grouping=grouping,+ series_index=index,+ point_index=point_index,+ )+ )+ return findings+++def inspect_presentation_package(path: str | Path) -> dict[str, Any]:+ source = Path(path)+ if not source.is_file() or source.is_symlink():+ raise PackageIntegrityError("presentation must be a regular local file")+ findings: list[dict[str, Any]] = []+ with zipfile.ZipFile(source) as package:+ members = [item for item in package.infolist() if not item.is_dir()]+ if len(members) > MAX_PARTS:+ raise PackageIntegrityError("presentation contains too many package parts")+ if sum(item.file_size for item in members) > MAX_UNCOMPRESSED_BYTES:+ raise PackageIntegrityError("presentation exceeds the safe uncompressed-size limit")+ names = [item.filename for item in members]+ if len(names) != len(set(names)):+ raise PackageIntegrityError("presentation contains duplicate package parts")+ for name in names:+ pure = PurePosixPath(name)+ if pure.is_absolute() or ".." in pure.parts:+ raise PackageIntegrityError("presentation contains an unsafe package part path")+ corrupt = package.testzip()+ if corrupt:+ raise PackageIntegrityError(f"presentation contains a corrupt package part: {corrupt}")+ name_set = set(names)+ required = {+ "[Content_Types].xml",+ "ppt/presentation.xml",+ "ppt/_rels/presentation.xml.rels",+ }+ missing = sorted(required - name_set)+ if missing:+ raise PackageIntegrityError(+ "presentation is missing required package part: " + missing[0]+ )++ parsed: dict[str, Element] = {}+ notes_parts: set[str] = set()+ for name in names:+ if not name.endswith(".rels"):+ continue+ root, issues = _parse_xml(package.read(name), name)+ findings.extend(issues)+ parsed[name] = root+ owner = _source_part(name)+ if owner and owner not in name_set:+ findings.append(_finding("relationship_owner_missing", name))+ for relationship in _relationships(root, name).values():+ if relationship.external:+ continue+ target = _target(owner, relationship.target)+ if target not in name_set:+ findings.append(+ _finding(+ "relationship_target_missing",+ name,+ relationship_id=relationship.identifier,+ )+ )+ if relationship.relationship_type == REL_NOTES:+ notes_parts.add(target)++ types_payload = package.read("[Content_Types].xml")+ types_root, issues = _parse_xml(types_payload, "[Content_Types].xml")+ findings.extend(issues)+ findings.extend(_content_types_namespace_findings(types_payload))+ defaults, overrides = _content_types(types_root)+ for name in names:+ if name == "[Content_Types].xml":+ continue+ if not _has_content_type(name, defaults, overrides):+ findings.append(_finding("content_type_missing", name))+ for name in overrides:+ if name not in name_set:+ findings.append(_finding("content_type_target_missing", name))++ presentation, issues = _parse_xml(+ package.read("ppt/presentation.xml"), "ppt/presentation.xml"+ )+ findings.extend(issues)+ if (presentation.uri, presentation.local) != (P, "presentation"):+ raise PackageIntegrityError("presentation.xml has an invalid root")+ presentation_relationships = _relationships(+ parsed["ppt/_rels/presentation.xml.rels"], "ppt/_rels/presentation.xml.rels"+ )+ slide_ids: set[str] = set()+ slide_parts: list[str] = []+ for listing in (+ item for item in presentation.children if (item.uri, item.local) == (P, "sldIdLst")+ ):+ for item in listing.children:+ if (item.uri, item.local) != (P, "sldId"):+ continue+ slide_id = item.attribute("id")+ relationship_id = item.attribute("id", R)+ if not slide_id or slide_id in slide_ids:+ findings.append(+ _finding("slide_id_invalid_or_duplicate", "ppt/presentation.xml")+ )+ continue+ slide_ids.add(slide_id)+ relationship = presentation_relationships.get(relationship_id or "")+ if (+ relationship is None+ or relationship.relationship_type != REL_SLIDE+ or relationship.external+ ):+ findings.append(+ _finding(+ "slide_relationship_missing_or_invalid",+ "ppt/presentation.xml",+ relationship_id=relationship_id or "",+ )+ )+ continue+ part = _target("ppt/presentation.xml", relationship.target)+ if part in slide_parts:+ findings.append(_finding("slide_part_duplicate", part))+ elif part in name_set:+ slide_parts.append(part)+ if not slide_parts:+ findings.append(_finding("presentation_has_no_resolved_slides", "ppt/presentation.xml"))++ chart_parts: set[str] = set()+ for part in slide_parts:+ root, issues = _parse_xml(package.read(part), part)+ findings.extend(issues)+ if (root.uri, root.local) != (P, "sld"):+ findings.append(_finding("slide_root_invalid", part))+ continue+ trees = [item for item in _descendants(root) if (item.uri, item.local) == (P, "spTree")]+ if not trees or not any(+ child.uri == P and child.local in DRAWABLE+ for tree in trees+ for child in tree.children+ ):+ findings.append(_finding("slide_has_no_drawable_objects", part))+ relationship_part = _relationship_part(part)+ relationships = (+ _relationships(parsed[relationship_part], relationship_part)+ if relationship_part in parsed+ else {}+ )+ for item in _descendants(root):+ for (namespace, attribute), relationship_id in item.attributes.items():+ if namespace != R or attribute not in REL_ATTRIBUTES:+ continue+ relationship = relationships.get(relationship_id)+ if relationship is None:+ findings.append(+ _finding(+ "referenced_relationship_missing",+ part,+ relationship_id=relationship_id,+ )+ )+ continue+ if (item.uri, item.local) == (C, "chart"):+ if relationship.relationship_type != REL_CHART or relationship.external:+ findings.append(+ _finding(+ "chart_relationship_invalid",+ part,+ relationship_id=relationship_id,+ )+ )+ else:+ chart_parts.add(_target(part, relationship.target))+ findings.extend(_order_findings(root, part))++ for part in sorted(chart_parts):+ if part not in name_set:+ findings.append(_finding("chart_part_missing", part))+ continue+ root, issues = _parse_xml(package.read(part), part)+ findings.extend(issues)+ if (root.uri, root.local) != (C, "chartSpace"):+ findings.append(_finding("chart_root_invalid", part))+ relationship_part = _relationship_part(part)+ relationships = (+ _relationships(parsed[relationship_part], relationship_part)+ if relationship_part in parsed+ else {}+ )+ for item in _descendants(root):+ for (namespace, attribute), relationship_id in item.attributes.items():+ if (+ namespace == R+ and attribute in REL_ATTRIBUTES+ and relationship_id not in relationships+ ):+ findings.append(+ _finding(+ "referenced_relationship_missing",+ part,+ relationship_id=relationship_id,+ )+ )+ findings.extend(_choice_findings(root, part))+ findings.extend(_order_findings(root, part))+ findings.extend(_stacked_chart_findings(root, part))++ return {+ "status": "fail" if findings else "pass",+ "slide_count": len(slide_parts),+ "chart_count": len(chart_parts),+ "relationship_part_count": len(parsed),+ "notes_parts_skipped": len(notes_parts),+ "finding_count": len(findings),+ "findings": findings,+ "claim_boundary": "Structural package checks only; no slide text, notes, formulas, chart values, or native PowerPoint execution were inspected.",+ }+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description="Inspect PPTX structure without reading presentation content."+ )+ parser.add_argument("pptx", type=Path)+ parser.add_argument("--fail-on-findings", action="store_true")+ arguments = parser.parse_args(argv)+ try:+ report = inspect_presentation_package(arguments.pptx)+ except (OSError, zipfile.BadZipFile, PackageIntegrityError) as exc:+ print(json.dumps({"status": "error", "error": str(exc)}), file=sys.stderr)+ return 2+ print(json.dumps(report, indent=2, sort_keys=True))+ return int(arguments.fail_on_findings and bool(report["findings"]))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/paper-fig/container_tools/mark_artifact_operation_started.mjs b/skills/paper-fig/container_tools/mark_artifact_operation_started.mjsnew file mode 100644index 0000000..776722c--- /dev/null+++ b/skills/paper-fig/container_tools/mark_artifact_operation_started.mjs@@ -0,0 +1,22 @@+#!/usr/bin/env node++const args = process.argv.slice(2);+const expectedOutputCount = Number(args[3]);+const validOutputFormats = new Set(["ppt", "pptx"]);+const valid =+ args.length === 6 &&+ args[0] === "--operation-kind" &&+ new Set(["create", "edit"]).has(args[1]) &&+ args[2] === "--expected-output-count" &&+ Number.isSafeInteger(expectedOutputCount) &&+ expectedOutputCount >= 1 &&+ expectedOutputCount <= 100 &&+ args[4] === "--output-format" &&+ validOutputFormats.has(args[5].toLowerCase());++if (!valid) {+ console.error(+ "usage: mark_artifact_operation_started.mjs --operation-kind <create|edit> --expected-output-count <1-100> --output-format <supported format>",+ );+ process.exitCode = 2;+}diff --git a/skills/paper-fig/container_tools/materialize_literal_chart_workbooks.py b/skills/paper-fig/container_tools/materialize_literal_chart_workbooks.pynew file mode 100644index 0000000..0c74986--- /dev/null+++ b/skills/paper-fig/container_tools/materialize_literal_chart_workbooks.py@@ -0,0 +1,849 @@+#!/usr/bin/env python3+"""Experimental: snapshot complete literal chart data into an honest embedded XLSX.++A snapshot creates new chart-owned worksheet formulas. It never recovers,+preserves, or claims lineage to an original source workbook or its formulas.+"""++from __future__ import annotations++import argparse+import hashlib+import importlib.util+import io+import json+import os+import posixpath+import sys+import tempfile+import zipfile+from copy import deepcopy+from decimal import Decimal, InvalidOperation+from pathlib import Path, PurePosixPath+from typing import Any, Iterable+from urllib.parse import urlsplit++try:+ from lxml import etree+except ImportError as error: # pragma: no cover: fail closed on unsupported runtime.+ raise RuntimeError(+ "The experimental chart snapshot requires the bundled lxml parser"+ ) from error++HERE = Path(__file__).resolve().parent+GATE_PATH = HERE / "native_quantitative_chart_gate.py"+SPEC = importlib.util.spec_from_file_location("literal_chart_snapshot_gate", GATE_PATH)+if SPEC is None or SPEC.loader is None:+ raise RuntimeError("The packaged native-chart gate is unavailable")+GATE = importlib.util.module_from_spec(SPEC)+sys.modules[SPEC.name] = GATE+SPEC.loader.exec_module(GATE)++NS = GATE.NS+C = NS["c"]+R = NS["r"]+P = NS["p"]+A = NS["a"]+REL = NS["rel"]+X = NS["x"]+CT = "http://schemas.openxmlformats.org/package/2006/content-types"+OFFICE_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+MAX_PARTS = GATE.MAX_PACKAGE_PARTS+MAX_BYTES = GATE.MAX_PACKAGE_BYTES+MAX_POINTS = 100_000+MAX_TEXT = 2_000+MAX_SERIES = 128+SNAPSHOT_PREFIX = "ppt/embeddings/chart-data-snapshot-"+WORKBOOK_MIME = GATE.WORKBOOK_CONTENT_TYPE+CHART_MIME = GATE.CHART_CONTENT_TYPE+++class SnapshotError(ValueError):+ """Source-safe unsupported chart lineage or invalid native data."""+++def _require(value: bool, message: str) -> None:+ if not value:+ raise SnapshotError(message)+++def _parse(data: bytes, label: str) -> etree._Element:+ _require(+ data and len(data) <= GATE.MAX_PART_BYTES and b"<!DOCTYPE" not in data.upper(),+ f"{label} is unsafe, empty, or exceeds the bounded XML limit",+ )+ try:+ return etree.fromstring(+ data,+ parser=etree.XMLParser(+ resolve_entities=False,+ no_network=True,+ load_dtd=False,+ recover=False,+ huge_tree=False,+ remove_blank_text=False,+ ),+ )+ except (etree.XMLSyntaxError, ValueError) as error:+ raise SnapshotError(f"{label} is malformed") from error+++def _bytes(root: etree._Element, original: bytes | None = None) -> bytes:+ declaration = bool(original and original.lstrip().startswith(b"<?xml"))+ return etree.tostring(+ root, encoding="UTF-8", xml_declaration=declaration, standalone=None, pretty_print=False+ )+++def _q(namespace: str, name: str) -> str:+ return "{" + namespace + "}" + name+++def _with_relationship_namespace(root: etree._Element) -> etree._Element:+ """Preserve every original root namespace and add the missing binding only."""+ if any(uri == R for uri in root.nsmap.values()):+ return root+ namespaces = dict(root.nsmap)+ prefix = "r"+ number = 1+ while prefix in namespaces:+ prefix = f"chartRelationship{number}"+ number += 1+ namespaces[prefix] = R+ rebound = etree.Element(root.tag, nsmap=namespaces)+ rebound.text = root.text+ rebound.tail = root.tail+ for name, value in root.attrib.items():+ rebound.set(name, value)+ for child in root:+ rebound.append(child)+ return rebound+++def _text(value: str, label: str) -> str:+ _require(+ isinstance(value, str) and bool(value.strip()) and len(value) <= MAX_TEXT,+ f"{label} must contain bounded, nonempty text",+ )+ _require(+ not any(ord(character) < 32 and character not in "\t\n\r" for character in value),+ f"{label} contains unsafe XML control characters",+ )+ return value+++def _numeric(value: str) -> str:+ _text(value, "Numeric chart value")+ _require(len(value) <= 100, "Numeric chart value exceeds its bounded precision")+ try:+ decimal = Decimal(value)+ except InvalidOperation as error:+ raise SnapshotError("Numeric chart value is malformed") from error+ _require(decimal.is_finite(), "Numeric chart values must be finite")+ _require(+ len(decimal.normalize().as_tuple().digits) <= 15,+ "Excel cannot preserve the literal chart's numeric precision",+ )+ return value+++def _column(number: int) -> str:+ _require(1 <= number <= 16384, "Chart snapshot exceeds Excel's bounded column capacity")+ result = ""+ while number:+ number, remainder = divmod(number - 1, 26)+ result = chr(65 + remainder) + result+ return result+++def _literal(+ parent: etree._Element, *, numeric: bool, allow_strings: bool+) -> tuple[etree._Element, list[str], str]:+ types = ("numLit",) if numeric else (("strLit", "numLit") if allow_strings else ("numLit",))+ found = [(child, kind) for kind in types for child in parent.findall("c:" + kind, NS)]+ _require(+ len(found) == 1,+ "Every chart category/value series must contain exactly one complete self-contained literal",+ )+ element, kind = found[0]+ _require(+ not any(child.tag in {_q(C, "numRef"), _q(C, "strRef")} for child in parent),+ "Existing workbook references cannot be replaced by a synthetic snapshot",+ )+ count = element.find("c:ptCount", NS)+ points = element.findall("c:pt", NS)+ _require(+ count is not None and isinstance(count.get("val"), str) and count.get("val", "").isdigit(),+ "Literal chart series must provide an exact point count",+ )+ expected = int(count.get("val", "0"))+ _require(+ 0 < expected <= MAX_POINTS and len(points) == expected,+ "Literal chart point count does not match its complete values",+ )+ values: dict[int, str] = {}+ for point in points:+ raw_index = point.get("idx", "")+ _require(+ raw_index.isdigit() and int(raw_index) < expected and int(raw_index) not in values,+ "Literal chart point indices must be unique and contiguous",+ )+ index = int(raw_index)+ item = point.find("c:v", NS)+ _require(+ item is not None and isinstance(item.text, str),+ "Literal chart point is missing its original value",+ )+ values[index] = (+ _numeric(item.text)+ if numeric or kind == "numLit"+ else _text(item.text, "Chart category")+ )+ return element, [values[index] for index in range(expected)], kind+++def _series_name(series: etree._Element, ordinal: int) -> str:+ title = series.find("c:tx", NS)+ if title is None:+ return f"Series {ordinal}"+ _require(+ not title.findall(".//c:f", NS) and not title.findall(".//c:strRef", NS),+ "An original source-bound series title cannot be replaced by snapshot lineage",+ )+ direct = title.find("c:v", NS)+ if direct is not None and isinstance(direct.text, str):+ return _text(direct.text, "Chart series title")+ values = title.findall(".//c:pt/c:v", NS)+ if len(values) == 1 and isinstance(values[0].text, str):+ return _text(values[0].text, "Chart series title")+ return f"Series {ordinal}"+++def _replace_literal(+ parent: etree._Element, element: etree._Element, *, kind: str, formula: str+) -> None:+ reference = etree.Element(_q(C, "strRef" if kind == "strLit" else "numRef"))+ formula_node = etree.SubElement(reference, _q(C, "f"))+ formula_node.text = formula+ cache = etree.SubElement(reference, _q(C, "strCache" if kind == "strLit" else "numCache"))+ for child in element:+ cache.append(deepcopy(child))+ parent.replace(element, reference)+++def _inline_cell(parent: etree._Element, coordinate: str, text: str) -> None:+ cell = etree.SubElement(parent, _q(X, "c"), r=coordinate, t="inlineStr")+ inline = etree.SubElement(cell, _q(X, "is"))+ item = etree.SubElement(inline, _q(X, "t"))+ if text != text.strip():+ item.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")+ # Explicit inlineStr guarantees '=...', '+...', '-', or '@' remain inert text.+ item.text = text+++def _numeric_cell(parent: etree._Element, coordinate: str, value: str) -> None:+ cell = etree.SubElement(parent, _q(X, "c"), r=coordinate)+ etree.SubElement(cell, _q(X, "v")).text = _numeric(value)+++def _workbook(series: list[dict[str, Any]]) -> bytes:+ width = len(series) * 2+ height = max(len(item["categories"]) for item in series) + 1+ _require(height <= 1_048_576, "Chart snapshot exceeds Excel's bounded row capacity")+ worksheet = etree.Element(_q(X, "worksheet"), nsmap={None: X})+ etree.SubElement(worksheet, _q(X, "dimension"), ref=f"A1:{_column(width)}{height}")+ sheet_data = etree.SubElement(worksheet, _q(X, "sheetData"))+ for row_number in range(1, height + 1):+ row = etree.SubElement(sheet_data, _q(X, "row"), r=str(row_number))+ for ordinal, item in enumerate(series):+ category_column = _column(ordinal * 2 + 1)+ value_column = _column(ordinal * 2 + 2)+ if row_number == 1:+ _inline_cell(row, f"{category_column}1", "X" if item["scatter"] else "Category")+ _inline_cell(row, f"{value_column}1", item["name"])+ continue+ index = row_number - 2+ if index >= len(item["categories"]):+ continue+ category = item["categories"][index]+ if item["category_kind"] == "numLit":+ _numeric_cell(row, f"{category_column}{row_number}", category)+ else:+ _inline_cell(row, f"{category_column}{row_number}", category)+ _numeric_cell(row, f"{value_column}{row_number}", item["values"][index])++ workbook = etree.Element(_q(X, "workbook"), nsmap={None: X, "r": R})+ sheets = etree.SubElement(workbook, _q(X, "sheets"))+ sheet = etree.SubElement(sheets, _q(X, "sheet"), name="Chart Data", sheetId="1")+ sheet.set(_q(R, "id"), "rId1")+ package_relations = etree.Element(_q(REL, "Relationships"), nsmap={None: REL})+ etree.SubElement(+ package_relations,+ _q(REL, "Relationship"),+ Id="rId1",+ Type=OFFICE_REL + "/officeDocument",+ Target="xl/workbook.xml",+ )+ workbook_relations = etree.Element(_q(REL, "Relationships"), nsmap={None: REL})+ etree.SubElement(+ workbook_relations,+ _q(REL, "Relationship"),+ Id="rId1",+ Type=OFFICE_REL + "/worksheet",+ Target="worksheets/sheet1.xml",+ )+ types = etree.Element(_q(CT, "Types"), nsmap={None: CT})+ etree.SubElement(+ types,+ _q(CT, "Default"),+ Extension="rels",+ ContentType="application/vnd.openxmlformats-package.relationships+xml",+ )+ etree.SubElement(types, _q(CT, "Default"), Extension="xml", ContentType="application/xml")+ etree.SubElement(+ types,+ _q(CT, "Override"),+ PartName="/xl/workbook.xml",+ ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",+ )+ etree.SubElement(+ types,+ _q(CT, "Override"),+ PartName="/xl/worksheets/sheet1.xml",+ ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",+ )+ out = io.BytesIO()+ with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as package:+ for name, root in (+ ("[Content_Types].xml", types),+ ("_rels/.rels", package_relations),+ ("xl/workbook.xml", workbook),+ ("xl/_rels/workbook.xml.rels", workbook_relations),+ ("xl/worksheets/sheet1.xml", worksheet),+ ):+ package.writestr(name, _bytes(root))+ payload = out.getvalue()+ _require(+ 0 < len(payload) <= GATE.MAX_PART_BYTES,+ "Generated chart data snapshot exceeds its bounded workbook size",+ )+ return payload+++def _source_policies(value: Iterable[int], *, label: str, owners: set[int]) -> set[int]:+ try:+ slides = list(value)+ except TypeError as error:+ raise SnapshotError(f"{label} must list actual native chart-owner slides") from error+ _require(+ all(type(number) is int and number in owners for number in slides)+ and len(slides) == len(set(slides)),+ f"{label} must list unique, actual native chart-owner slides",+ )+ return set(slides)+++def _validate_chart_relationships(root: etree._Element) -> None:+ identities: set[str] = set()+ for item in root.findall("rel:Relationship", NS):+ identifier = item.get("Id", "")+ target = item.get("Target", "")+ _require(+ bool(identifier and target) and identifier not in identities,+ "Chart relationships must have unique identifiers and nonempty targets",+ )+ identities.add(identifier)+ mode = item.get("TargetMode", "Internal").casefold()+ _require(mode in {"internal", "external"}, "Invalid chart relationship mode")+ if mode == "internal":+ continue+ try:+ parsed = urlsplit(target)+ safe_link = (+ item.get("Type") == R + "/hyperlink"+ and not any(ord(character) <= 32 or ord(character) == 127 for character in target)+ and "\\" not in target+ and (+ parsed.scheme.casefold() in {"http", "https"}+ and bool(parsed.hostname)+ or parsed.scheme.casefold() == "mailto"+ and bool(parsed.path)+ and not parsed.netloc+ )+ )+ except ValueError:+ safe_link = False+ # Clickable hyperlinks are inert here and remain byte-for-byte intact on+ # preserved charts. Never fetch them or admit external chart data/media.+ _require(+ safe_link,+ "External chart resources are forbidden; only ordinary HTTP(S) or mailto hyperlinks may be preserved",+ )+++def _validate_paths(+ source: str | Path, destination: str | Path, receipt: str | Path, workspace: str | Path+) -> tuple[Path, Path, Path, Path]:+ values = [Path(item) for item in (source, destination, receipt, workspace)]+ _require(+ all(path.is_absolute() for path in values),+ "Chart snapshot requires exact absolute staged input/output/receipt/workspace paths",+ )+ input_path, output_path, receipt_path, workspace_path = values+ _require(+ workspace_path.is_dir() and not workspace_path.is_symlink(),+ "Chart snapshot workspace must be an existing regular directory",+ )+ canonical = workspace_path.resolve()+ _require(+ input_path.is_file()+ and not input_path.is_symlink()+ and input_path.suffix.lower() == ".pptx"+ and 0 < input_path.stat().st_size <= MAX_BYTES+ and input_path.resolve().is_relative_to(canonical),+ "Chart snapshot input must be an approved bounded staged PPTX",+ )+ _require(+ output_path.suffix.lower() == ".pptx"+ and receipt_path.suffix.lower() == ".json"+ and output_path != input_path+ and output_path != receipt_path+ and output_path.parent.is_dir()+ and receipt_path.parent.is_dir()+ and output_path.parent.resolve().is_relative_to(canonical)+ and receipt_path.parent.resolve().is_relative_to(canonical)+ and not output_path.exists()+ and not output_path.is_symlink()+ and not receipt_path.exists()+ and not receipt_path.is_symlink(),+ "Chart snapshot output and truthful receipt must be new private staged workspace files",+ )+ return input_path, output_path, receipt_path, canonical+++def materialize_literal_chart_workbooks(+ source: str | Path,+ destination: str | Path,+ *,+ receipt: str | Path,+ workspace: str | Path,+ source_formula_required_slides: Iterable[int] = (),+ source_workbook_required_slides: Iterable[int] = (),+) -> dict[str, Any]:+ """Convert only literal charts into explicitly new, self-contained data snapshots."""++ input_path, output_path, receipt_path, _ = _validate_paths(+ source, destination, receipt, workspace+ )+ original_bytes = input_path.read_bytes()+ original_sha = hashlib.sha256(original_bytes).hexdigest()+ try:+ archive = zipfile.ZipFile(io.BytesIO(original_bytes))+ except zipfile.BadZipFile as error:+ raise SnapshotError("Chart snapshot input is not a valid Office ZIP package") from error++ with archive:+ names = archive.namelist()+ _require(+ 0 < len(names) <= MAX_PARTS+ and len(set(names)) == len(names)+ and not any(+ name.startswith("/") or ".." in PurePosixPath(name).parts for name in names+ ),+ "Chart snapshot input contains duplicate, unsafe, or excessive package parts",+ )+ _require(+ archive.testzip() is None,+ "Chart snapshot input has a corrupted compressed package part",+ )+ _require(+ "[Content_Types].xml" in names and "ppt/presentation.xml" in names,+ "Chart snapshot input lacks required Office presentation package parts",+ )+ discovery = GATE.discover_native_chart_owners(input_path)+ owner_slides = set(discovery["chart_owner_slides"])+ _require(owner_slides, "Chart snapshot requires at least one actual native chart")+ formula_required = _source_policies(+ source_formula_required_slides, label="Source-formula obligations", owners=owner_slides+ )+ workbook_required = _source_policies(+ source_workbook_required_slides,+ label="Original source-workbook obligations",+ owners=owner_slides,+ )+ content_original = archive.read("[Content_Types].xml")+ types = _parse(content_original, "Presentation content types")+ _require(+ types.tag == _q(CT, "Types") and types.nsmap.get(None) == CT,+ "Presentation content types must already use the canonical default namespace",+ )+ content = GATE._content_types(archive)+ modifications: dict[str, bytes] = {}+ additions: dict[str, bytes] = {}+ converted = []+ preserved = []+ seen_parts = set()++ for slide in sorted(owner_slides):+ slide_part = discovery["chart_owner_slide_parts"].get(str(slide))+ _require(+ isinstance(slide_part, str) and slide_part in names,+ "Actual logical native chart owner slide is missing",+ )+ slide_root = _parse(archive.read(slide_part), "Native chart owner slide")+ slide_rels = GATE._relationships(archive, slide_part)+ references = []+ for frame in slide_root.findall(".//p:graphicFrame", NS):+ references.extend(frame.findall(".//a:graphic/a:graphicData/c:chart", NS))+ for chart in references:+ identifier = chart.get(_q(R, "id"))+ relation = slide_rels.get(str(identifier or ""))+ _require(+ relation is not None+ and relation.get("type") == GATE.CHART_RELATIONSHIP+ and relation.get("mode") == "Internal",+ "Native chart relationship must be internal and complete",+ )+ chart_part = str(relation["target"])+ _require(+ chart_part not in seen_parts+ and chart_part in names+ and content.get(chart_part) == CHART_MIME,+ "Native chart part is missing, duplicated, or has the wrong content type",+ )+ seen_parts.add(chart_part)+ chart_original = archive.read(chart_part)+ chart_root = _parse(chart_original, "Native chart XML")+ _require(+ chart_root.tag == _q(C, "chartSpace"),+ "Native chart must preserve its original chart namespace",+ )+ external = chart_root.findall("./c:externalData", NS)+ relation_part = str(+ PurePosixPath(chart_part).parent+ / "_rels"+ / (PurePosixPath(chart_part).name + ".rels")+ )+ if relation_part in names:+ relation_original = archive.read(relation_part)+ relation_root = _parse(relation_original, "Native chart relationships")+ _require(+ relation_root.tag == _q(REL, "Relationships")+ and relation_root.nsmap.get(None) == REL,+ "Native chart relationships must retain their default package namespace",+ )+ _validate_chart_relationships(relation_root)+ else:+ relation_original = None+ relation_root = etree.Element(_q(REL, "Relationships"), nsmap={None: REL})++ if external:+ _require(+ len(external) == 1, "An existing chart has duplicate workbook bindings"+ )+ chart_relationships = GATE._relationships(archive, chart_part)+ workbook_relation = chart_relationships.get(+ str(external[0].get(_q(R, "id")) or "")+ )+ _require(+ workbook_relation is not None+ and workbook_relation.get("type") == GATE.WORKBOOK_RELATIONSHIP+ and workbook_relation.get("mode") == "Internal"+ and str(workbook_relation.get("target", "")) in names,+ "An existing original workbook relationship is broken; never synthesize lineage",+ )+ preserved.append({"owner_slide": slide, "chart_part": chart_part})+ continue++ _require(+ slide not in formula_required and slide not in workbook_required,+ "A literal snapshot cannot preserve expressly required original source formulas or workbook",+ )+ _require(+ not chart_root.findall(".//c:f", NS)+ and not chart_root.findall(".//c:numRef", NS)+ and not chart_root.findall(".//c:strRef", NS),+ "An existing referenced chart lacks its source workbook; never fabricate formula provenance",+ )+ _require(+ not chart_root.findall(".//c:bubbleSize", NS),+ "Bubble-size literal charts require an explicitly supported source-preserving adapter",+ )+ chart_root = _with_relationship_namespace(chart_root)+ plot = chart_root.find(".//c:plotArea", NS)+ _require(+ plot is not None+ and any(+ child.tag.rsplit("}", 1)[-1] in GATE.SUPPORTED_CHART_TYPES for child in plot+ ),+ "Only supported genuine native chart families may be snapshotted",+ )+ series_nodes = chart_root.findall(".//c:ser", NS)+ _require(+ 0 < len(series_nodes) <= MAX_SERIES,+ "Native chart must contain a bounded number of complete data series",+ )+ rows = []+ for ordinal, series in enumerate(series_nodes, 1):+ scatter = (+ series.find("c:xVal", NS) is not None+ or series.find("c:yVal", NS) is not None+ )+ category_parent = series.find("c:xVal" if scatter else "c:cat", NS)+ value_parent = series.find("c:yVal" if scatter else "c:val", NS)+ _require(+ category_parent is not None and value_parent is not None,+ "Literal chart series must preserve complete category/value pairs",+ )+ category_lit, categories, category_kind = _literal(+ category_parent, numeric=scatter, allow_strings=not scatter+ )+ value_lit, values, value_kind = _literal(+ value_parent, numeric=True, allow_strings=False+ )+ _require(+ value_kind == "numLit" and len(categories) == len(values),+ "Literal chart category/value point counts are inconsistent",+ )+ first = _column(ordinal * 2 - 1)+ second = _column(ordinal * 2)+ last = len(values) + 1+ _replace_literal(+ category_parent,+ category_lit,+ kind=category_kind,+ formula=f"'Chart Data'!${first}$2:${first}${last}",+ )+ _replace_literal(+ value_parent,+ value_lit,+ kind=value_kind,+ formula=f"'Chart Data'!${second}$2:${second}${last}",+ )+ rows.append(+ {+ "categories": categories,+ "values": values,+ "category_kind": category_kind,+ "name": _series_name(series, ordinal),+ "scatter": scatter,+ }+ )++ suffix = 1+ while (+ workbook_part := f"{SNAPSHOT_PREFIX}{suffix:03d}.xlsx"+ ) in names or workbook_part in additions:+ suffix += 1+ additions[workbook_part] = _workbook(rows)+ existing_ids = {+ item.get("Id") for item in relation_root.findall("rel:Relationship", NS)+ }+ relation_number = 1+ while (relation_id := f"rIdChartSnapshot{relation_number}") in existing_ids:+ relation_number += 1+ target = posixpath.relpath(+ workbook_part, start=str(PurePosixPath(chart_part).parent)+ )+ _require(+ not target.startswith("/") and "://" not in target,+ "Generated chart workbook relationship must remain local and relative",+ )+ etree.SubElement(+ relation_root,+ _q(REL, "Relationship"),+ Id=relation_id,+ Type=GATE.WORKBOOK_RELATIONSHIP,+ Target=target,+ )+ external_data = etree.Element(_q(C, "externalData"))+ external_data.set(_q(R, "id"), relation_id)+ etree.SubElement(external_data, _q(C, "autoUpdate"), val="0")+ following = next(+ (+ index+ for index, child in enumerate(chart_root)+ if child.tag+ in {_q(C, "printSettings"), _q(C, "userShapes"), _q(C, "extLst")}+ ),+ len(chart_root),+ )+ chart_root.insert(following, external_data)+ modifications[chart_part] = _bytes(chart_root, chart_original)+ if relation_original is None:+ additions[relation_part] = _bytes(relation_root)+ else:+ modifications[relation_part] = _bytes(relation_root, relation_original)+ converted.append(+ {+ "owner_slide": slide,+ "chart_part": chart_part,+ "workbook_part": workbook_part,+ "series_count": len(rows),+ "point_count": sum(len(row["values"]) for row in rows),+ }+ )++ _require(+ converted,+ "No eligible self-contained literal native chart requires snapshot materialization",+ )+ defaults = [+ child+ for child in types.findall("{" + CT + "}Default")+ if child.get("Extension", "").lower() == "xlsx"+ ]+ _require(+ len(defaults) <= 1,+ "Presentation content types contain duplicate workbook extension declarations",+ )+ if defaults:+ _require(+ defaults[0].get("ContentType") == WORKBOOK_MIME,+ "Presentation workbook content type conflicts with the real embedded XLSX format",+ )+ else:+ etree.SubElement(types, _q(CT, "Default"), Extension="xlsx", ContentType=WORKBOOK_MIME)+ modifications["[Content_Types].xml"] = _bytes(types, content_original)++ output_bytes = io.BytesIO()+ with zipfile.ZipFile(output_bytes, "w") as rendered:+ for part in archive.infolist():+ rendered.writestr(+ part, modifications.get(part.filename, archive.read(part.filename))+ )+ for name, data in additions.items():+ rendered.writestr(name, data, compress_type=zipfile.ZIP_DEFLATED)+ result_bytes = output_bytes.getvalue()+ _require(+ 0 < len(result_bytes) <= MAX_BYTES,+ "Materialized chart snapshot exceeds its bounded presentation size",+ )++ descriptor, temporary_name = tempfile.mkstemp(+ prefix=".literal-chart-snapshot-", dir=output_path.parent+ )+ temporary = Path(temporary_name)+ receipt_temporary = None+ output_published = receipt_published = False+ try:+ with os.fdopen(descriptor, "wb") as stream:+ # mkstemp is mode 0600 on POSIX. Windows inherits the private staged+ # workspace ACL and does not expose fchmod before Python 3.13.+ if hasattr(os, "fchmod"):+ os.fchmod(stream.fileno(), 0o600)+ stream.write(result_bytes)+ stream.flush()+ os.fsync(stream.fileno())+ portable = GATE.audit_native_quantitative_charts(+ temporary,+ {int(slide): int(count) for slide, count in discovery["chart_counts"].items()},+ target_application="portable",+ )+ _require(+ portable.get("passed") is True and portable.get("failed_slide_count") == 0,+ "Generated chart-data snapshot failed workbook/cache validation: "+ + "; ".join(+ str(result.get("failure_detail", "chart contract failed"))+ for result in portable.get("results", [])+ if result.get("status") == "failed"+ ),+ )+ _require(+ hashlib.sha256(input_path.read_bytes()).hexdigest() == original_sha,+ "Original staged presentation changed during chart snapshot materialization",+ )+ output_sha = hashlib.sha256(result_bytes).hexdigest()+ payload = {+ "schema_version": "experimental.literal-chart-workbook-snapshot.v1",+ "conversion": "chart_data_snapshot",+ "experimental": True,+ "source_formulas_preserved": False,+ "source_workbook_preserved": False,+ "new_formulas_describe_snapshot_only": True,+ "input_sha256": original_sha,+ "output_sha256": output_sha,+ "output_bytes": len(result_bytes),+ "detected_chart_owner_slides": discovery["chart_owner_slides"],+ "converted_chart_count": len(converted),+ "preserved_existing_workbook_chart_count": len(preserved),+ "converted_charts": converted,+ "preserved_existing_workbook_charts": preserved,+ "source_formula_required_slides": sorted(formula_required),+ "source_workbook_required_slides": sorted(workbook_required),+ "portable_chart_validation_passed": True,+ "portable_validated_owner_slides": portable["expected_quantitative_chart_slides"],+ }+ handle, receipt_name = tempfile.mkstemp(+ prefix=".literal-chart-snapshot-receipt-", dir=receipt_path.parent+ )+ receipt_temporary = Path(receipt_name)+ with os.fdopen(handle, "w", encoding="utf-8") as stream:+ if hasattr(os, "fchmod"):+ os.fchmod(stream.fileno(), 0o600)+ json.dump(payload, stream, indent=2, sort_keys=True)+ stream.write("\n")+ stream.flush()+ os.fsync(stream.fileno())+ _require(+ not output_path.exists() and not receipt_path.exists(),+ "A staged snapshot output or receipt already exists",+ )+ os.link(temporary, output_path)+ output_published = True+ os.link(receipt_temporary, receipt_path)+ receipt_published = True+ return payload+ except GATE.ChartGateError as error:+ raise SnapshotError(+ f"Generated chart-data snapshot failed portable workbook validation: {error}"+ ) from error+ finally:+ # If publishing the second hard link fails, do not leave an apparently+ # finished PPTX without its required provenance receipt. Never remove a+ # file that replaced our output in a concurrent operation.+ if (+ output_published+ and not receipt_published+ and output_path.exists()+ and output_path.samefile(temporary)+ ):+ output_path.unlink()+ temporary.unlink(missing_ok=True)+ if receipt_temporary is not None:+ receipt_temporary.unlink(missing_ok=True)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("source", type=Path, help="Exact staged self-contained literal-chart PPTX")+ parser.add_argument("destination", type=Path, help="New private staged PPTX, never overwritten")+ parser.add_argument("--workspace", type=Path, required=True)+ parser.add_argument("--receipt", type=Path, required=True)+ parser.add_argument("--require-source-formulas-slide", action="append", type=int, default=[])+ parser.add_argument("--require-source-workbook-slide", action="append", type=int, default=[])+ args = parser.parse_args(argv)+ try:+ result = materialize_literal_chart_workbooks(+ args.source,+ args.destination,+ receipt=args.receipt,+ workspace=args.workspace,+ source_formula_required_slides=args.require_source_formulas_slide,+ source_workbook_required_slides=args.require_source_workbook_slide,+ )+ print(json.dumps(result, sort_keys=True))+ return 0+ except (SnapshotError, GATE.ChartGateError, OSError, ValueError) as error:+ print(+ json.dumps(+ {"ok": False, "error_category": type(error).__name__, "error": str(error)},+ sort_keys=True,+ ),+ file=sys.stderr,+ )+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/paper-fig/container_tools/native_chart_title_gate.py b/skills/paper-fig/container_tools/native_chart_title_gate.pynew file mode 100644index 0000000..66f5365--- /dev/null+++ b/skills/paper-fig/container_tools/native_chart_title_gate.py@@ -0,0 +1,143 @@+#!/usr/bin/env python3+"""Reject unintended empty native main-chart titles without modifying the deck.++Logical slide relationships are authoritative. Existing rich/link-based titles+and axis titles are preserved; source strings and chart values are never emitted.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import sys+import zipfile+from pathlib import Path++# The bundled Python enables safe-path mode, so sibling modules need an explicit path.+SCRIPT_DIR = str(Path(__file__).resolve().parent)+if SCRIPT_DIR not in sys.path:+ sys.path.insert(0, SCRIPT_DIR)++from native_quantitative_chart_gate import (+ CHART_RELATIONSHIP,+ MAX_PACKAGE_BYTES,+ MAX_PACKAGE_PARTS,+ NS,+ ChartGateError,+ _relationships,+ _safe_xml,+ logical_presentation_slides,+)++SCHEMA = "presentation-native-chart-titles.v1"+++def audit_native_chart_titles(path: Path) -> dict:+ path = Path(path)+ if path.is_symlink() or not path.is_file() or not 0 < path.stat().st_size <= MAX_PACKAGE_BYTES:+ raise ValueError("A bounded regular presentation file is required")+ before = hashlib.sha256(path.read_bytes()).hexdigest()+ checks, findings = [], []+ with zipfile.ZipFile(path) as package:+ names = package.namelist()+ if (+ len(names) > MAX_PACKAGE_PARTS+ or len(names) != len(set(names))+ or sum(item.file_size for item in package.infolist()) > MAX_PACKAGE_BYTES+ ):+ raise ValueError("Presentation has duplicate or excessive package parts")+ slides = logical_presentation_slides(package)+ for slide_number, slide_part in slides.items():+ slide = _safe_xml(package, slide_part)+ relationships = _relationships(package, slide_part)+ for index, chart_reference in enumerate(slide.findall(".//c:chart", NS), 1):+ identifier = chart_reference.get("{" + NS["r"] + "}id")+ relation = relationships.get(identifier)+ if (+ not relation+ or relation["mode"] != "Internal"+ or relation["type"] != CHART_RELATIONSHIP+ ):+ raise ValueError("A native chart has no genuine internal relationship")+ chart_space = _safe_xml(package, relation["target"])+ if chart_space.tag != "{" + NS["c"] + "}chartSpace":+ raise ValueError("A native chart relationship does not resolve to a chart")+ chart = chart_space.find("c:chart", NS)+ if chart is None:+ raise ValueError("A native chart has no chart element")+ titles = chart.findall("c:title", NS)+ if len(titles) > 1:+ raise ValueError("A native chart has duplicate main-title elements")+ status = "absent"+ if titles:+ title = titles[0]+ fragments = [entry.text or "" for entry in title.findall(".//a:t", NS)]+ fragments += [+ entry.text or ""+ for entry in title.findall("c:tx/c:strRef/c:strCache/c:pt/c:v", NS)+ ]+ literal = " ".join(fragments).strip()+ formula = title.find("c:tx/c:strRef/c:f", NS)+ deleted = chart.find("c:autoTitleDeleted", NS)+ suppressed = deleted is not None and deleted.get("val") in {"1", "true"}+ if literal:+ status = "present"+ if " ".join(literal.casefold().split()) == "chart title" and not suppressed:+ status = "default_placeholder"+ elif formula is not None and (formula.text or "").strip():+ # A genuine dynamic reference can be legitimate without a+ # cached value. Do not remove or claim to have resolved it.+ status = "linked_title_unresolved"+ elif suppressed:+ status = "explicitly_suppressed"+ else:+ status = "empty_title"+ check = {"slide": slide_number, "chart": index, "status": status}+ checks.append(check)+ if status in {"empty_title", "default_placeholder"}:+ findings.append(+ {"slide": slide_number, "chart": index, "code": "native_chart_" + status}+ )+ if hashlib.sha256(path.read_bytes()).hexdigest() != before:+ raise ValueError("Presentation changed during chart-title inspection")+ return {+ "schema_version": SCHEMA,+ "passed": not findings,+ "presentation_sha256": before,+ "slide_count": len(slides),+ "native_chart_count": len(checks),+ "checks": checks,+ "unresolved_linked_title_count": sum(+ c["status"] == "linked_title_unresolved" for c in checks+ ),+ "finding_count": len(findings),+ "findings": findings,+ "native_powerpoint_verified": False,+ "source_text_emitted": False,+ }+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("presentation", type=Path)+ args = parser.parse_args()+ try:+ report = audit_native_chart_titles(args.presentation)+ print(json.dumps(report, sort_keys=True, separators=(",", ":")))+ return 0 if report["passed"] else 1+ except (OSError, ValueError, ChartGateError, zipfile.BadZipFile):+ print(+ json.dumps(+ {+ "schema_version": SCHEMA,+ "passed": False,+ "error": "Chart-title inspection could not validate the package",+ }+ )+ )+ return 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/paper-fig/container_tools/native_quantitative_chart_gate.py b/skills/paper-fig/container_tools/native_quantitative_chart_gate.pynew file mode 100644index 0000000..8d91f6b--- /dev/null+++ b/skills/paper-fig/container_tools/native_quantitative_chart_gate.py@@ -0,0 +1,1086 @@+#!/usr/bin/env python3+"""Source-free, slide-specific validation of genuine native PowerPoint charts.++Only explicitly declared quantitative-chart slides are governed. Editable maps,+scientific diagrams, approved source figures, and unrelated slides never become+chart failures merely because they are not Excel-backed PowerPoint charts.+Portable mode retains the original durable embedded-workbook requirement;+explicit PowerPoint mode also accepts complete, editable native literal data.+"""++from __future__ import annotations++import argparse+import hashlib+import io+import json+import os+import re+import sys+import tempfile+import zipfile+from dataclasses import dataclass+from decimal import Decimal, InvalidOperation+from pathlib import Path, PurePosixPath+from typing import Any, Iterable, Mapping+from xml.etree import ElementTree++ROOT = Path(__file__).resolve().parent+MAX_PACKAGE_BYTES = 128 * 1024 * 1024+MAX_PART_BYTES = 16 * 1024 * 1024+MAX_PACKAGE_PARTS = 10_000+MAX_EXPECTED_SLIDES = 500+MAX_CHARTS_PER_SLIDE = 25+CHART_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml"+WORKBOOK_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"+CHART_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart"+WORKBOOK_RELATIONSHIP = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package"+)+NS = {+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+ "c": "http://schemas.openxmlformats.org/drawingml/2006/chart",+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+ "rel": "http://schemas.openxmlformats.org/package/2006/relationships",+ "x": "http://schemas.openxmlformats.org/spreadsheetml/2006/main",+ "ct": "http://schemas.openxmlformats.org/package/2006/content-types",+}+SUPPORTED_CHART_TYPES = frozenset(+ {+ "areaChart",+ "area3DChart",+ "barChart",+ "bar3DChart",+ "bubbleChart",+ "doughnutChart",+ "lineChart",+ "line3DChart",+ "ofPieChart",+ "pieChart",+ "pie3DChart",+ "radarChart",+ "scatterChart",+ "stockChart",+ "surfaceChart",+ "surface3DChart",+ }+)+SAFE_POLICY = "user_approved_unrecoverable_source_figure"+_SLIDE = re.compile(r"ppt/slides/slide([1-9][0-9]*)\.xml\Z")+_DISCLOSURE = re.compile(r"\b(?:non[ -]?editable|not editable|uneditable)\b", re.IGNORECASE)+++class ChartGateError(ValueError):+ """Bounded, content-free structural package validation error."""+++@dataclass(frozen=True)+class SourceFigureException:+ """Explicit per-slide exception; never inferred from an image or source type."""++ user_approved: bool+ policy: str = SAFE_POLICY+++def _require(value: bool, message: str) -> None:+ if not value:+ raise ChartGateError(message)+++def _safe_xml(package: zipfile.ZipFile, name: str) -> ElementTree.Element:+ try:+ info = package.getinfo(name)+ except KeyError as exc:+ raise ChartGateError("Required package relationship or XML part is absent") from exc+ _require(+ 0 < info.file_size <= MAX_PART_BYTES,+ "A required PowerPoint package part exceeds its bounded size",+ )+ material = package.read(info)+ _require(+ b"<!DOCTYPE" not in material.upper(),+ "PowerPoint package XML must not contain a document-type declaration",+ )+ try:+ return ElementTree.fromstring(material)+ except ElementTree.ParseError as exc:+ raise ChartGateError(+ "PowerPoint package contains malformed relationship or chart XML"+ ) from exc+++def _resolved_part(parent: str, target: Any, *, root: str = "ppt") -> str:+ _require(+ isinstance(target, str) and bool(target),+ "A PowerPoint package relationship target is missing",+ )+ _require(+ "\\" not in target and ":" not in target and "?" not in target and "#" not in target,+ "A package relationship target must be an internal part path",+ )+ if target.startswith("/"):+ parts = target.lstrip("/").split("/")+ else:+ parts = parent.split("/")[:-1] + target.split("/")+ normalized: list[str] = []+ for part in parts:+ if part in {"", "."}:+ continue+ if part == "..":+ _require(bool(normalized), "A PowerPoint relationship escapes its package root")+ normalized.pop()+ else:+ normalized.append(part)+ _require(+ bool(normalized) and normalized[0] == root,+ "A PowerPoint relationship escapes its approved presentation package",+ )+ return "/".join(normalized)+++def _relationships(package: zipfile.ZipFile, parent: str) -> dict[str, dict[str, str]]:+ relative = str(PurePosixPath(parent).parent / "_rels" / (PurePosixPath(parent).name + ".rels"))+ if relative not in package.namelist():+ return {}+ root = _safe_xml(package, relative)+ result = {}+ for item in root:+ identifier = item.get("Id")+ _require(+ isinstance(identifier, str) and bool(identifier) and identifier not in result,+ "A PowerPoint package contains duplicate or missing relationship identifiers",+ )+ mode = item.get("TargetMode")+ # Ordinary hyperlinks do not weaken an unrelated real native chart. Keep+ # them inert, but reject an external relationship if the chart selects it.+ result[identifier] = {+ "type": str(item.get("Type") or ""),+ "mode": "Internal" if mode is None or mode == "Internal" else "External",+ "target": _resolved_part(parent, item.get("Target"))+ if mode is None or mode == "Internal"+ else "",+ }+ return result+++def _content_types(package: zipfile.ZipFile) -> dict[str, str]:+ root = _safe_xml(package, "[Content_Types].xml")+ result: dict[str, str] = {}+ defaults: dict[str, str] = {}+ for item in root:+ part = item.get("PartName")+ if part:+ result[part.lstrip("/")] = str(item.get("ContentType") or "")+ else:+ extension = item.get("Extension")+ if extension:+ key = extension.casefold()+ _require(key not in defaults, "A PowerPoint package repeats a default content type")+ defaults[key] = str(item.get("ContentType") or "")+ for part in package.namelist():+ if part not in result and "." in part.rsplit("/", 1)[-1]:+ extension = part.rsplit(".", 1)[-1].casefold()+ if extension in defaults:+ result[part] = defaults[extension]+ return result+++def logical_presentation_slides(package: zipfile.ZipFile) -> dict[int, str]:+ """Resolve actual presentation order, never physical slide filenames."""+ root = _safe_xml(package, "ppt/presentation.xml")+ _require(+ root.tag == "{" + NS["p"] + "}presentation",+ "The presentation slide-order document is invalid",+ )+ lists = root.findall("p:sldIdLst", NS)+ _require(+ len(lists) == 1, "The presentation must declare exactly one authoritative slide-order list"+ )+ entries = lists[0].findall("p:sldId", NS)+ _require(+ 0 < len(entries) <= MAX_EXPECTED_SLIDES,+ "The presentation slide-order list is empty or exceeds its bounded size",+ )+ relationships = _relationships(package, "ppt/presentation.xml")+ names = set(package.namelist())+ ordered: dict[int, str] = {}+ seen_ids: set[str] = set()+ seen_parts: set[str] = set()+ for ordinal, entry in enumerate(entries, 1):+ identifier = entry.get("{" + NS["r"] + "}id")+ _require(+ isinstance(identifier, str) and bool(identifier) and identifier not in seen_ids,+ "The presentation slide-order list contains a missing or repeated relationship",+ )+ seen_ids.add(identifier)+ relation = relationships.get(identifier)+ _require(+ relation is not None+ and relation.get("mode") == "Internal"+ and relation.get("type") == NS["r"] + "/slide",+ "The presentation slide-order relationship must be an internal genuine slide",+ )+ target = str(relation.get("target") or "")+ _require(+ target.startswith("ppt/slides/")+ and target.endswith(".xml")+ and "/_rels/" not in target+ and target in names+ and target not in seen_parts,+ "The presentation slide-order relationship is missing, unsafe, or duplicated",+ )+ slide = _safe_xml(package, target)+ _require(+ slide.tag == "{" + NS["p"] + "}sld",+ "The presentation slide-order relationship does not identify a genuine slide",+ )+ seen_parts.add(target)+ ordered[ordinal] = target+ return ordered+++def _decimal(value: Any) -> Decimal:+ _require(+ isinstance(value, str) and len(value) <= 100,+ "A chart or embedded workbook contains an invalid numeric point",+ )+ try:+ number = Decimal(value)+ except InvalidOperation as exc:+ raise ChartGateError(+ "A chart or embedded workbook contains an invalid numeric point"+ ) from exc+ _require(number.is_finite(), "A chart or embedded workbook contains a non-finite numeric point")+ return number.normalize()+++@dataclass(frozen=True)+class WorkbookCell:+ kind: str+ value: str | Decimal+++@dataclass(frozen=True)+class ChartWorkbook:+ sheets: Mapping[str, Mapping[str, WorkbookCell]]+ numeric_cell_count: int+++def _string_value(element: ElementTree.Element) -> str:+ # Phonetic annotations are not part of the cell's displayed string.+ return "".join(+ item.text or "" for item in element.findall("x:t", NS) + element.findall("x:r/x:t", NS)+ )+++def _workbook_cells(package: zipfile.ZipFile, path: str) -> ChartWorkbook:+ try:+ info = package.getinfo(path)+ except KeyError as exc:+ raise ChartGateError("A native chart references a missing embedded Excel workbook") from exc+ _require(+ 0 < info.file_size <= MAX_PART_BYTES,+ "A native chart embedded Excel workbook exceeds its bounded size",+ )+ try:+ workbook = zipfile.ZipFile(io.BytesIO(package.read(info)))+ except zipfile.BadZipFile as exc:+ raise ChartGateError(+ "A native chart embedded workbook is not a valid XLSX package"+ ) from exc+ with workbook:+ names = workbook.namelist()+ _require(+ 0 < len(names) <= MAX_PACKAGE_PARTS+ and len(set(names)) == len(names)+ and sum(item.file_size for item in workbook.infolist()) <= MAX_PACKAGE_BYTES,+ "An embedded workbook contains duplicate or excessive package data",+ )+ root = _safe_xml(workbook, "xl/workbook.xml")+ _require(+ root.tag == "{" + NS["x"] + "}workbook",+ "An embedded workbook has no genuine workbook document",+ )+ relations = _safe_xml(workbook, "xl/_rels/workbook.xml.rels")+ targets: dict[str, str] = {}+ shared_strings: list[str] = []+ for relation in relations:+ identifier = relation.get("Id")+ _require(+ bool(identifier) and identifier not in targets,+ "An embedded workbook has duplicate or missing relationship identifiers",+ )+ # Other relationships, including hyperlinks, are never followed.+ targets[str(identifier)] = ""+ if relation.get("Type") not in {NS["r"] + "/worksheet", NS["r"] + "/sharedStrings"}:+ continue+ _require(+ relation.get("TargetMode", "Internal") == "Internal",+ "An embedded workbook worksheet or shared-string relationship is external",+ )+ target = _resolved_part("xl/workbook.xml", relation.get("Target"), root="xl")+ if relation.get("Type") == NS["r"] + "/worksheet":+ targets[str(identifier)] = target+ else:+ strings_root = _safe_xml(workbook, target)+ _require(+ strings_root.tag == "{" + NS["x"] + "}sst",+ "An embedded workbook shared-string part is invalid",+ )+ shared_strings = [_string_value(item) for item in strings_root.findall("x:si", NS)]+ sheets: dict[str, dict[str, WorkbookCell]] = {}+ numeric_count = 0+ for sheet in root.findall("x:sheets/x:sheet", NS):+ name = sheet.get("name", "")+ target = targets.get(sheet.get("{" + NS["r"] + "}id", ""))+ _require(+ bool(name) and name.casefold() not in sheets and bool(target),+ "An embedded workbook has a missing or ambiguous sheet relationship",+ )+ worksheet = _safe_xml(workbook, str(target))+ _require(+ worksheet.tag == "{" + NS["x"] + "}worksheet",+ "An embedded workbook sheet relationship does not identify a worksheet",+ )+ cells: dict[str, WorkbookCell] = {}+ for cell in worksheet.findall("x:sheetData/x:row/x:c", NS):+ address = cell.get("r", "").upper()+ _require(+ re.fullmatch(r"[A-Z]{1,3}[1-9][0-9]{0,6}", address) is not None+ and address not in cells,+ "An embedded workbook has a missing or duplicate cell coordinate",+ )+ value = cell.find("x:v", NS)+ kind = cell.get("t", "n")+ if kind == "inlineStr":+ inline = cell.find("x:is", NS)+ cells[address] = WorkbookCell(+ "string", "" if inline is None else _string_value(inline)+ )+ elif kind == "s":+ index = "" if value is None else value.text or ""+ _require(+ index.isdigit() and int(index) < len(shared_strings),+ "An embedded workbook cell references a missing shared string",+ )+ cells[address] = WorkbookCell("string", shared_strings[int(index)])+ elif kind == "str":+ cells[address] = WorkbookCell(+ "string", "" if value is None else value.text or ""+ )+ elif kind == "n" and value is not None and value.text:+ cells[address] = WorkbookCell("number", _decimal(value.text))+ numeric_count += 1+ else:+ cells[address] = WorkbookCell("unresolved", kind)+ sheets[name.casefold()] = cells+ _require(bool(sheets), "A native chart embedded workbook has no actual worksheet")+ return ChartWorkbook(sheets, numeric_count)+++_RANGE = re.compile(+ r"(?P<sheet>'(?:[^']|'')+'|[^\s'!\[\]():,+*/^&=<>\-]+)!"+ r"\$?(?P<c1>[A-Za-z]{1,3})\$?(?P<r1>[1-9][0-9]{0,6})"+ r"(?::\$?(?P<c2>[A-Za-z]{1,3})\$?(?P<r2>[1-9][0-9]{0,6}))?\Z"+)+++def _column_number(value: str) -> int:+ result = 0+ for character in value.upper():+ result = result * 26 + ord(character) - ord("A") + 1+ return result+++def _column_name(number: int) -> str:+ result = ""+ while number:+ number, remainder = divmod(number - 1, 26)+ result = chr(ord("A") + remainder) + result+ return result+++def _referenced_cells(workbook: ChartWorkbook, formula: str, *, label: str) -> list[WorkbookCell]:+ match = _RANGE.fullmatch(formula.strip().removeprefix("="))+ _require(+ match is not None,+ f"{label}: unsupported chart formula; use one internal sheet-qualified A1 cell or contiguous row/column range and rerun validation",+ )+ assert match is not None+ sheet = match["sheet"]+ if sheet.startswith("'"):+ sheet = sheet[1:-1].replace("''", "'")+ _require(+ not any(character in sheet for character in "[]:\\/?*"),+ f"{label}: external workbook and three-dimensional sheet references require separate validation",+ )+ cells = workbook.sheets.get(sheet.casefold())+ _require(cells is not None, f"{label}: chart formula references a missing worksheet")+ assert cells is not None+ c1, c2 = _column_number(match["c1"]), _column_number(match["c2"] or match["c1"])+ r1, r2 = int(match["r1"]), int(match["r2"] or match["r1"])+ _require(+ c1 <= c2 <= 16384+ and r1 <= r2 <= 1_048_576+ and (c1 == c2 or r1 == r2)+ and max(c2 - c1, r2 - r1) < 100_000,+ f"{label}: chart formula must select a bounded, forward, one-dimensional Excel range",+ )+ selected = []+ for row in range(r1, r2 + 1):+ for column in range(c1, c2 + 1):+ address = f"{_column_name(column)}{row}"+ cell = cells.get(address)+ _require(+ cell is not None and cell.kind != "unresolved",+ f"{label}: referenced cell {address} is missing, blank, an error, or lacks a calculated value; recalculate the source workbook",+ )+ assert cell is not None+ selected.append(cell)+ return selected+++def _chart_point_container(+ series: ElementTree.Element,+ role: str,+ *,+ numeric: bool,+) -> tuple[list[str], str]:+ parent = series.find("c:" + role, NS)+ _require(+ parent is not None,+ "Expected quantitative chart series is missing its category or numeric values",+ )+ branches = (("c:numLit", "literal"), ("c:numRef/c:numCache", "reference_cache"))+ if not numeric:+ branches = (+ ("c:strLit", "literal"),+ ("c:numLit", "literal"),+ ("c:strRef/c:strCache", "reference_cache"),+ ("c:numRef/c:numCache", "reference_cache"),+ )+ matches = [+ (container, kind)+ for expression, kind in branches+ for container in parent.findall(expression, NS)+ ]+ _require(+ len(matches) == 1, "Expected quantitative chart series has no unique literal or cached data"+ )+ container, kind = matches[0]+ if kind == "reference_cache":+ reference = next(+ (child for child in parent if child.tag.rsplit("}", 1)[-1] in {"numRef", "strRef"}),+ None,+ )+ formula = reference.find("c:f", NS) if reference is not None else None+ _require(+ formula is not None and isinstance(formula.text, str) and bool(formula.text.strip()),+ "Expected quantitative chart reference cache lacks its worksheet formula",+ )+ count = container.find("c:ptCount", NS)+ _require(+ count is not None and isinstance(count.get("val"), str) and count.get("val", "").isdigit(),+ "Expected quantitative chart literal/cache point count is missing or invalid",+ )+ declared = int(count.get("val", "0"))+ points = container.findall("c:pt", NS)+ _require(+ 0 < declared <= 100_000 and len(points) == declared,+ "Expected quantitative chart literal/cache point count disagrees with its points",+ )+ seen: set[int] = set()+ values: dict[int, str] = {}+ for point in points:+ raw_index = point.get("idx")+ _require(+ isinstance(raw_index, str) and raw_index.isdigit(),+ "Expected quantitative chart literal/cache has an invalid point index",+ )+ index = int(raw_index)+ _require(+ index < declared and index not in seen,+ "Expected quantitative chart literal/cache repeats or exceeds a point index",+ )+ seen.add(index)+ item = point.find("c:v", NS)+ _require(+ item is not None+ and isinstance(item.text, str)+ and bool(item.text.strip())+ and len(item.text) <= 1000,+ "Expected quantitative chart literal/cache contains an empty point",+ )+ if numeric or container.tag.rsplit("}", 1)[-1] in {"numLit", "numCache"}:+ _decimal(item.text)+ values[index] = item.text+ # XML document order is not data order; DrawingML's pt/@idx is authoritative.+ return [values[index] for index in range(declared)], kind+++def _reconcile_series_range(+ series: ElementTree.Element, role: str, *, numeric: bool, workbook: ChartWorkbook, ordinal: int+) -> int:+ values, kind = _chart_point_container(series, role, numeric=numeric)+ label = f"Chart series {ordinal} {role}"+ _require(+ kind == "reference_cache",+ f"{label}: durable chart data must reference its embedded workbook; literal data has no verified workbook lineage",+ )+ parent = series.find("c:" + role, NS)+ assert parent is not None+ references = parent.findall("c:numRef", NS) + parent.findall("c:strRef", NS)+ _require(len(references) == 1, f"{label}: chart has ambiguous workbook references")+ reference = references[0]+ formulas = reference.findall("c:f", NS)+ _require(+ len(formulas) == 1 and bool(formulas[0].text),+ f"{label}: chart needs exactly one workbook formula",+ )+ cells = _referenced_cells(workbook, formulas[0].text or "", label=label)+ _require(+ len(values) == len(cells),+ f"{label}: cache point count differs from the referenced worksheet range",+ )+ is_number = reference.tag == "{" + NS["c"] + "}numRef"+ for index, (value, cell) in enumerate(zip(values, cells, strict=True)):+ if is_number:+ matches = cell.kind == "number" and _decimal(value) == cell.value+ else:+ matches = cell.kind == "string" and value == cell.value+ _require(+ matches,+ f"{label}: cached point {index} differs from its exact referenced worksheet cell; refresh the chart cache from that range",+ )+ return len(values) if is_number else 0+++def _reconcile_workbook_series(chart: ElementTree.Element, workbook: ChartWorkbook) -> int:+ series = chart.findall(".//c:ser", NS)+ _require(bool(series), "Expected quantitative chart contains no native data series")+ numeric_count = 0+ for ordinal, item in enumerate(series, 1):+ scatter = item.find("c:xVal", NS) is not None or item.find("c:yVal", NS) is not None+ roles = (("xVal", True), ("yVal", True)) if scatter else (("cat", False), ("val", True))+ categories, _ = _chart_point_container(item, roles[0][0], numeric=roles[0][1])+ values, _ = _chart_point_container(item, roles[1][0], numeric=True)+ _require(+ len(categories) == len(values),+ f"Chart series {ordinal}: category and value counts disagree",+ )+ for role, numeric in roles:+ numeric_count += _reconcile_series_range(+ item, role, numeric=numeric, workbook=workbook, ordinal=ordinal+ )+ if item.find("c:bubbleSize", NS) is not None:+ sizes, _ = _chart_point_container(item, "bubbleSize", numeric=True)+ _require(+ len(sizes) == len(values), f"Chart series {ordinal}: bubble-size count disagrees"+ )+ numeric_count += _reconcile_series_range(+ item, "bubbleSize", numeric=True, workbook=workbook, ordinal=ordinal+ )+ if item.find("c:tx/c:strRef", NS) is not None:+ _reconcile_series_range(item, "tx", numeric=False, workbook=workbook, ordinal=ordinal)+ return numeric_count+++def _powerpoint_series(chart: ElementTree.Element) -> dict[str, Any]:+ series = chart.findall(".//c:ser", NS)+ _require(bool(series), "Expected quantitative chart contains no native data series")+ literal_points = cached_points = 0+ for item in series:+ scatter = item.find("c:xVal", NS) is not None or item.find("c:yVal", NS) is not None+ category_role, value_role = ("xVal", "yVal") if scatter else ("cat", "val")+ categories, _ = _chart_point_container(item, category_role, numeric=scatter)+ values, mode = _chart_point_container(item, value_role, numeric=True)+ _require(+ len(categories) == len(values),+ "Expected quantitative chart category and numeric value counts disagree",+ )+ if item.find("c:bubbleSize", NS) is not None:+ sizes, _ = _chart_point_container(item, "bubbleSize", numeric=True)+ _require(+ len(sizes) == len(values),+ "Expected quantitative chart bubble-size and numeric value counts disagree",+ )+ if mode == "literal":+ literal_points += len(values)+ else:+ cached_points += len(values)+ _require(+ literal_points + cached_points > 0,+ "Expected quantitative chart contains no editable native numeric data",+ )+ return {+ "series_count": len(series),+ "literal_numeric_point_count": literal_points,+ "numeric_cache_point_count": cached_points,+ }+++def _native_chart(+ package: zipfile.ZipFile,+ *,+ slide_path: str,+ chart_reference: ElementTree.Element,+ slide_relationships: Mapping[str, Mapping[str, str]],+ content_types: Mapping[str, str],+ target_application: str,+ durable_required: bool,+) -> dict[str, Any]:+ relationship_id = chart_reference.get("{" + NS["r"] + "}id")+ relation = slide_relationships.get(str(relationship_id or ""))+ _require(+ relation is not None+ and relation.get("type") == CHART_RELATIONSHIP+ and relation.get("mode") == "Internal",+ "Expected quantitative chart lacks its exact slide-to-native-chart relationship",+ )+ path = str(relation["target"])+ _require(+ content_types.get(path) == CHART_CONTENT_TYPE,+ "Expected quantitative chart package part has an invalid chart content type",+ )+ chart = _safe_xml(package, path)+ _require(+ chart.tag == "{" + NS["c"] + "}chartSpace",+ "Expected quantitative chart is not a genuine DrawingML chartSpace",+ )+ plot = chart.find(".//c:plotArea", NS)+ _require(plot is not None, "Expected quantitative chart contains no native chart plot area")+ types = [+ element.tag.rsplit("}", 1)[-1]+ for element in plot+ if element.tag.rsplit("}", 1)[-1] in SUPPORTED_CHART_TYPES+ ]+ _require(bool(types), "Expected quantitative chart does not contain a supported native chart")+ native_data = _powerpoint_series(chart)+ formulas = [+ item.text+ for item in chart.findall(".//c:f", NS)+ if isinstance(item.text, str) and item.text.strip()+ ]+ external = chart.findall("./c:externalData", NS)+ if target_application == "powerpoint" and not durable_required and not external:+ _require(+ not formulas+ and not chart.findall(".//c:numRef", NS)+ and not chart.findall(".//c:strRef", NS),+ "Cached-reference chart lacks its embedded workbook; restore the original workbook before claiming editable chart validation",+ )+ return {+ "native_chart_types": sorted(set(types)),+ "embedded_workbook_count": 0,+ "embedded_workbook_sheet_count": 0,+ "series_formula_count": len(formulas),+ "numeric_cache_point_count": native_data["numeric_cache_point_count"],+ "literal_numeric_point_count": native_data["literal_numeric_point_count"],+ "workbook_numeric_cell_count": 0,+ "editability_evidence": "powerpoint_native_literal"+ if native_data["literal_numeric_point_count"]+ else "powerpoint_cached_reference",+ }+ _require(+ len(external) == 1,+ "Expected quantitative chart lacks a unique embedded Excel externalData relationship",+ )+ external_id = external[0].get("{" + NS["r"] + "}id")+ chart_relations = _relationships(package, path)+ workbook = chart_relations.get(str(external_id or ""))+ _require(+ workbook is not None+ and workbook.get("type") == WORKBOOK_RELATIONSHIP+ and workbook.get("mode") == "Internal",+ "Expected quantitative chart does not resolve its embedded Excel package relationship",+ )+ workbook_path = str(workbook["target"])+ _require(+ workbook_path.endswith(".xlsx")+ and content_types.get(workbook_path) == WORKBOOK_CONTENT_TYPE,+ "Expected quantitative chart embedded workbook has an invalid XLSX content type",+ )+ workbook_cells = _workbook_cells(package, workbook_path)+ numeric_point_count = _reconcile_workbook_series(chart, workbook_cells)+ result = {+ "native_chart_types": sorted(set(types)),+ "embedded_workbook_count": 1,+ "embedded_workbook_sheet_count": len(workbook_cells.sheets),+ "series_formula_count": len(formulas),+ "numeric_cache_point_count": numeric_point_count,+ "workbook_numeric_cell_count": workbook_cells.numeric_cell_count,+ "cache_reference_ranges_verified": True,+ }+ if target_application == "powerpoint":+ result["editability_evidence"] = "embedded_workbook"+ result["literal_numeric_point_count"] = (+ native_data["literal_numeric_point_count"] if native_data is not None else 0+ )+ return result+++def _exception_policy(value: Any) -> SourceFigureException:+ if isinstance(value, SourceFigureException):+ result = value+ elif isinstance(value, Mapping) and set(value) == {"user_approved", "policy"}:+ result = SourceFigureException(value["user_approved"], value["policy"])+ else:+ raise ChartGateError(+ "A noneditable source-figure exception must be explicit and slide-specific"+ )+ _require(+ result.user_approved is True and result.policy == SAFE_POLICY,+ "A noneditable source figure requires explicit user approval and the exact safe policy",+ )+ return result+++def _source_figure_disclosed(slide: ElementTree.Element) -> bool:+ text = " ".join((item.text or "") for item in slide.findall(".//a:t", NS))+ return bool(_DISCLOSURE.search(text)) and bool(+ re.search(r"\b(?:source|figure|image)\b", text, re.I)+ )+++def _slide_result(+ package: zipfile.ZipFile,+ slide_number: int,+ path: str,+ *,+ required_charts: int,+ content_types: Mapping[str, str],+ exception: SourceFigureException | None,+ target_application: str,+ durable_required: bool,+) -> dict[str, Any]:+ slide = _safe_xml(package, path)+ pictures = slide.findall(".//p:pic", NS)+ frames = slide.findall(".//p:graphicFrame", NS)+ references = []+ for frame in frames:+ references.extend(frame.findall(".//a:graphic/a:graphicData/c:chart", NS))+ result: dict[str, Any] = {+ "slide_number": slide_number,+ "required_native_chart_count": required_charts,+ "native_chart_count": len(references),+ "raster_picture_count": len(pictures),+ "approved_source_figure_exception": False,+ "failure_codes": [],+ }+ if len(references) < required_charts:+ if exception is not None and pictures and _source_figure_disclosed(slide):+ result["status"] = "approved_source_figure_exception"+ result["approved_source_figure_exception"] = True+ return result+ if exception is not None and pictures:+ result["failure_codes"].append("approved_source_figure_missing_noneditable_disclosure")+ elif pictures:+ result["failure_codes"].append("raster_picture_is_not_native_chart")+ result["failure_codes"].append("required_native_chart_missing")+ result["status"] = "failed"+ return result++ try:+ relationships = _relationships(package, path)+ checks = [+ _native_chart(+ package,+ slide_path=path,+ chart_reference=reference,+ slide_relationships=relationships,+ content_types=content_types,+ target_application=target_application,+ durable_required=durable_required,+ )+ for reference in references+ ]+ except ChartGateError as exc:+ result["status"] = "failed"+ result["failure_codes"].append("native_chart_workbook_contract_failed")+ result["failure_detail"] = str(exc)+ return result+ result["status"] = "passed"+ result["charts"] = checks+ return result+++def discover_native_chart_owners(presentation: str | Path) -> dict[str, Any]:+ """List actual native chart frames only; never infer source-required owners."""++ path = Path(presentation)+ _require(+ path.is_file() and not path.is_symlink() and 0 < path.stat().st_size <= MAX_PACKAGE_BYTES,+ "The selected PowerPoint is not a bounded regular presentation file",+ )+ try:+ package = zipfile.ZipFile(path)+ except zipfile.BadZipFile as exc:+ raise ChartGateError("The selected PowerPoint is not a valid Office package") from exc+ with package:+ names = package.namelist()+ _require(+ 0 < len(names) <= MAX_PACKAGE_PARTS and len(set(names)) == len(names),+ "The selected PowerPoint has unsafe duplicate or excessive package entries",+ )+ _require(+ package.testzip() is None,+ "The selected PowerPoint has a corrupt compressed package part",+ )+ ordered = logical_presentation_slides(package)+ owners: dict[int, int] = {}+ for slide_number, name in ordered.items():+ root = _safe_xml(package, name)+ references = []+ for frame in root.findall(".//p:graphicFrame", NS):+ references.extend(frame.findall(".//a:graphic/a:graphicData/c:chart", NS))+ if references:+ _require(+ len(references) <= MAX_CHARTS_PER_SLIDE,+ "A native chart slide exceeds its bounded chart-owner limit",+ )+ owners[slide_number] = len(references)+ _require(+ len(owners) <= MAX_EXPECTED_SLIDES,+ "The selected PowerPoint exceeds its bounded native-chart owner limit",+ )+ return {+ "schema_version": "owner-private.actual-native-chart-discovery.v1",+ "package_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),+ "slide_count": len(ordered),+ "chart_owner_slides": sorted(owners),+ "chart_owner_slide_parts": {str(slide): ordered[slide] for slide in sorted(owners)},+ "chart_counts": {str(slide): owners[slide] for slide in sorted(owners)},+ "chart_count": sum(owners.values()),+ "source_attachments_accessed": False,+ "source_required_chart_owners_inferred": False,+ }+++def audit_native_quantitative_charts(+ presentation: str | Path,+ expected_chart_slides: Iterable[int] | Mapping[int, int],+ *,+ approved_source_figures: Mapping[int, SourceFigureException | Mapping[str, Any]] | None = None,+ target_application: str = "portable",+ required_embedded_workbook_slides: Iterable[int] = (),+) -> dict[str, Any]:+ """Validate only explicitly expected quantitative charts; never inspect source attachments."""++ _require(+ isinstance(target_application, str) and target_application in {"portable", "powerpoint"},+ "Chart target application must be explicitly portable or PowerPoint",+ )+ path = Path(presentation)+ _require(+ path.is_file() and not path.is_symlink() and 0 < path.stat().st_size <= MAX_PACKAGE_BYTES,+ "The selected PowerPoint is not a bounded regular presentation file",+ )+ if isinstance(expected_chart_slides, Mapping):+ expected = dict(expected_chart_slides)+ else:+ sequence = list(expected_chart_slides)+ _require(+ len(sequence) == len(set(sequence)),+ "Expected quantitative chart slide numbers cannot be duplicated",+ )+ expected = {item: 1 for item in sequence}+ _require(+ 0 < len(expected) <= MAX_EXPECTED_SLIDES,+ "At least one explicitly expected quantitative chart slide is required",+ )+ _require(+ all(+ type(slide) is int+ and slide > 0+ and type(count) is int+ and 1 <= count <= MAX_CHARTS_PER_SLIDE+ for slide, count in expected.items()+ ),+ "Expected quantitative chart slides and chart counts must be bounded positive integers",+ )+ try:+ durable = list(required_embedded_workbook_slides)+ except TypeError as exc:+ raise ChartGateError(+ "Durable embedded-workbook owners must be unique declared chart-owner slides"+ ) from exc+ _require(+ all(type(slide) is int and slide in expected for slide in durable)+ and len(durable) == len(set(durable)),+ "Durable embedded-workbook owners must be unique declared chart-owner slides",+ )+ durable_owners = set(durable)+ exceptions: dict[int, SourceFigureException] = {}+ for slide, policy in (approved_source_figures or {}).items():+ _require(+ type(slide) is int and slide in expected,+ "A source-figure exception must target an explicitly expected quantitative slide",+ )+ exceptions[slide] = _exception_policy(policy)+ try:+ package = zipfile.ZipFile(path)+ except zipfile.BadZipFile as exc:+ raise ChartGateError("The selected PowerPoint is not a valid Office package") from exc+ with package:+ names = package.namelist()+ _require(+ 0 < len(names) <= MAX_PACKAGE_PARTS and len(set(names)) == len(names),+ "The selected PowerPoint has unsafe duplicate or excessive package entries",+ )+ _require(+ package.testzip() is None,+ "The selected PowerPoint has a corrupt compressed package part",+ )+ actual_slides = logical_presentation_slides(package)+ _require(+ all(number in actual_slides for number in expected),+ "An explicitly expected quantitative chart slide is absent from the presentation",+ )+ types = _content_types(package)+ results = [+ _slide_result(+ package,+ slide,+ actual_slides[slide],+ required_charts=expected[slide],+ content_types=types,+ exception=exceptions.get(slide),+ target_application=target_application,+ durable_required=target_application == "portable" or slide in durable_owners,+ )+ for slide in sorted(expected)+ ]+ failures = [entry["slide_number"] for entry in results if entry["status"] == "failed"]+ return {+ "schema_version": "owner-private.quantitative-chart-native-gate.v1",+ "package_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),+ "slide_count": len(actual_slides),+ "expected_quantitative_chart_slides": sorted(expected),+ "validated_slide_count": len(results),+ "failed_slide_count": len(failures),+ "failed_slides": failures,+ "passed": not failures,+ "results": results,+ "source_attachments_accessed": False,+ "native_application_open_verified": False,+ "formal_human_reviewed": False,+ "claim_boundary": "OOXML/workbook structural validation only; source provenance and native PowerPoint opening remain separate checks.",+ **(+ {+ "target_application": target_application,+ "required_embedded_workbook_slides": sorted(durable_owners),+ }+ if target_application != "portable" or durable_owners+ else {}+ ),+ }+++def write_private_receipt(path: str | Path, payload: Mapping[str, Any]) -> Path:+ destination = Path(path)+ _require(+ destination.parent.resolve() == ROOT.resolve(),+ "Source-free chart receipts must remain inside the owner-private enforcement directory",+ )+ ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)+ ROOT.chmod(0o700)+ descriptor, temporary_name = tempfile.mkstemp(prefix=".chart-gate-", dir=ROOT)+ temporary = Path(temporary_name)+ try:+ with os.fdopen(descriptor, "wb") as handle:+ # mkstemp creates a private POSIX file. Windows Python 3.12 has no+ # fchmod and uses the selected workspace's inherited ACL instead.+ if hasattr(os, "fchmod"):+ os.fchmod(handle.fileno(), 0o600)+ handle.write(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode())+ handle.flush()+ os.fsync(handle.fileno())+ temporary.replace(destination)+ destination.chmod(0o600)+ finally:+ temporary.unlink(missing_ok=True)+ return destination+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("presentation", type=Path)+ parser.add_argument(+ "--expected-chart-slides", help="Comma-separated one-based quantitative-chart slide numbers"+ )+ parser.add_argument(+ "--discover-chart-slides",+ action="store_true",+ help="Report actual native chart owners without inventing source requirements",+ )+ parser.add_argument(+ "--approved-source-figure",+ action="append",+ default=[],+ type=int,+ help="Explicit user-approved slide-specific source-figure exception",+ )+ parser.add_argument(+ "--target-application",+ choices=("portable", "powerpoint"),+ default="portable",+ help="Only explicit PowerPoint targeting permits native literal chart data",+ )+ parser.add_argument(+ "--require-embedded-workbook-slide",+ action="append",+ default=[],+ type=int,+ help="Explicit source-approved chart slide requiring a durable embedded workbook",+ )+ parser.add_argument("--receipt", type=Path)+ args = parser.parse_args(argv)+ if args.discover_chart_slides:+ _require(+ args.expected_chart_slides is None+ and not args.approved_source_figure+ and not args.require_embedded_workbook_slide+ and args.receipt is None,+ "Chart discovery cannot include source-owner, exception, durability, or receipt options",+ )+ print(+ json.dumps(+ discover_native_chart_owners(args.presentation),+ sort_keys=True,+ separators=(",", ":"),+ )+ )+ return 0+ _require(+ args.expected_chart_slides is not None,+ "Declare expected chart owners or explicitly request actual chart discovery",+ )+ try:+ expected = [int(item) for item in args.expected_chart_slides.split(",")]+ except ValueError as exc:+ raise ChartGateError(+ "Expected quantitative chart slides must be positive integers"+ ) from exc+ exceptions = {+ number: SourceFigureException(user_approved=True) for number in args.approved_source_figure+ }+ payload = audit_native_quantitative_charts(+ args.presentation,+ expected,+ approved_source_figures=exceptions,+ target_application=args.target_application,+ required_embedded_workbook_slides=(args.require_embedded_workbook_slide),+ )+ if args.receipt is not None:+ write_private_receipt(args.receipt, payload)+ print(json.dumps(payload, sort_keys=True, separators=(",", ":")))+ return 0 if payload["passed"] else 1+++if __name__ == "__main__":+ try:+ raise SystemExit(main())+ except ChartGateError as exc:+ print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)+ raise SystemExit(2) from excdiff --git a/skills/paper-fig/container_tools/native_table_arithmetic_gate.py b/skills/paper-fig/container_tools/native_table_arithmetic_gate.pynew file mode 100644index 0000000..10e83aa--- /dev/null+++ b/skills/paper-fig/container_tools/native_table_arithmetic_gate.py@@ -0,0 +1,519 @@+#!/usr/bin/env python3+"""Review displayed table totals; enforce only explicitly declared arithmetic contracts.++Auto-discovered totals are diagnostics. Comparisons allow for displayed rounding+and do not establish equality of the underlying source values. Unsupported number+formats are reported as skipped, never silently treated as zero.+"""++from __future__ import annotations++import argparse+import json+import re+import sys+import zipfile+from dataclasses import dataclass+from decimal import Decimal, InvalidOperation, localcontext+from pathlib import Path+from typing import Any, Iterable, Mapping+from xml.etree import ElementTree++# The bundled Python enables safe-path mode, so sibling modules need an explicit path.+SCRIPT_DIR = str(Path(__file__).resolve().parent)+if SCRIPT_DIR not in sys.path:+ sys.path.insert(0, SCRIPT_DIR)++from native_quantitative_chart_gate import (+ MAX_PACKAGE_BYTES,+ MAX_PACKAGE_PARTS,+ NS,+ _safe_xml,+ logical_presentation_slides,+)++SCHEMA_VERSION = "presentation-native-table-arithmetic.v1"+MAX_TABLES_PER_SLIDE = 100+MAX_TABLE_ROWS = 2_000+MAX_TABLE_COLUMNS = 100+MAX_CELL_CHARACTERS = 2_048+MAX_CONTRACTS = 200+_TOTAL = re.compile(r"\btotal\b", re.IGNORECASE)+_SUBTOTAL = re.compile(r"\bsub[\s-]?total\b", re.IGNORECASE)+_SEMANTIC_EXCLUSION = re.compile(+ r"\b(?:percent(?:age)?|ratio|rate|yield|ytd|qtd|mtd|net|margin|growth|"+ r"weighted|average|mean|median|multiple|variance|delta|index|wacc|irr|share|"+ r"stock|flow|cashflow|balance|opening|closing|beginning|ending)\b|%|‰|/",+ re.IGNORECASE,+)+_NON_ADDITIVE_HEADER = re.compile(+ r"\b(?:unit[\s-]+(?:price|cost|rate|value)|price|per[\s-]+unit|per[\s-]+share)\b",+ re.IGNORECASE,+)+_NUMBER = re.compile(+ r"^\s*(?P<open>\()?\s*(?P<sign>[+\-−])?\s*"+ r"(?P<currency>[$€£¥]|USD|EUR|GBP|JPY)?\s*"+ r"(?P<number>(?:[0-9]{1,3}(?:,[0-9]{3})+|[0-9]+)(?:\.[0-9]{1,12})?)"+ r"\s*(?P<magnitude>[kKmMbB])?\s*"+ r"(?P<suffix_currency>USD|EUR|GBP|JPY)?\s*(?P<close>\))?\s*$"+)+++class ArithmeticGateError(ValueError):+ """Reject malformed packages/contracts without leaking document text."""+++@dataclass(frozen=True)+class _Amount:+ value: Decimal+ places: int+ currency: str+ magnitude: str+++def _require(condition: bool, message: str) -> None:+ if not condition:+ raise ArithmeticGateError(message)+++def _local(element: ElementTree.Element) -> str:+ return element.tag.rsplit("}", 1)[-1]+++def _visible_tables(root: ElementTree.Element) -> list[ElementTree.Element]:+ """Traverse only visible group/frame descendants; never include pasted images."""+ containers = {+ "sp": "nvSpPr",+ "cxnSp": "nvCxnSpPr",+ "grpSp": "nvGrpSpPr",+ "graphicFrame": "nvGraphicFramePr",+ "pic": "nvPicPr",+ }+ tables: list[ElementTree.Element] = []+ stack: list[tuple[ElementTree.Element, bool]] = [(root, False)]+ while stack:+ element, within_frame = stack.pop()+ kind = _local(element)+ container = containers.get(kind)+ properties = element.find(f"p:{container}/p:cNvPr", NS) if container else None+ if properties is not None and properties.get("hidden", "0").casefold() in {"1", "true"}:+ continue+ within_frame = within_frame or kind == "graphicFrame"+ if element.tag == "{" + NS["a"] + "}tbl" and within_frame:+ tables.append(element)+ _require(+ len(tables) <= MAX_TABLES_PER_SLIDE,+ "A slide exceeds its bounded native-table count",+ )+ continue+ stack.extend((child, within_frame) for child in reversed(list(element)))+ return tables+++def _rows(table: ElementTree.Element) -> tuple[list[list[str]], bool, bool]:+ rows = table.findall("a:tr", NS)+ _require(len(rows) <= MAX_TABLE_ROWS, "A native table exceeds its bounded row count")+ properties = table.find("a:tblPr", NS)+ first_row_header = properties is not None and properties.get("firstRow", "0").casefold() in {+ "1",+ "true",+ }+ result: list[list[str]] = []+ merged = False+ for row in rows:+ cells = row.findall("a:tc", NS)+ _require(len(cells) <= MAX_TABLE_COLUMNS, "A native table exceeds its bounded column count")+ values = []+ for cell in cells:+ if any(+ cell.get(key) not in {None, "0", "1" if key in {"gridSpan", "rowSpan"} else None}+ for key in ("gridSpan", "rowSpan", "hMerge", "vMerge")+ ):+ merged = True+ text = " ".join((part.text or "") for part in cell.findall(".//a:t", NS)).strip()+ _require(+ len(text) <= MAX_CELL_CHARACTERS,+ "A native-table cell exceeds its bounded text size",+ )+ values.append(text)+ result.append(values)+ return result, merged, first_row_header+++def _amount(value: str) -> _Amount | None:+ if not isinstance(value, str) or len(value) > 96:+ return None+ match = _NUMBER.fullmatch(value)+ if not match or bool(match.group("open")) != bool(match.group("close")):+ return None+ if match.group("open") and match.group("sign"):+ return None+ prefix, suffix = match.group("currency") or "", match.group("suffix_currency") or ""+ if prefix and suffix and prefix != suffix:+ return None+ raw = match.group("number")+ try:+ number = Decimal(raw.replace(",", ""))+ except (InvalidOperation, ValueError):+ return None+ if not number.is_finite() or len(number.as_tuple().digits) > 40:+ return None+ if match.group("open") or match.group("sign") in {"-", "−"}:+ number = number.copy_negate()+ return _Amount(+ number,+ len(raw.partition(".")[2]),+ (prefix or suffix).upper(),+ (match.group("magnitude") or "").casefold(),+ )+++def _consistent_units(amounts: list[_Amount]) -> bool:+ currencies = {item.currency for item in amounts if item.currency}+ magnitudes = {item.magnitude for item in amounts}+ return len(currencies) <= 1 and len(magnitudes) <= 1+++def _rounding_tolerance(amounts: list[_Amount]) -> Decimal:+ return sum((Decimal(1).scaleb(-item.places) / 2 for item in amounts), Decimal(0))+++def _table_reason(reason: str, slide: int, table: int) -> dict[str, Any]:+ return {"slide": slide, "table": table, "reason": reason}+++def _auto_plan(+ rows: list[list[str]], merged: bool, first_row_header: bool+) -> tuple[dict[str, Any] | None, str | None]:+ if merged:+ return None, "merged_cell_geometry"+ if len(rows) < 3:+ return None, "insufficient_rows"+ numeric_rows = [index for index, row in enumerate(rows) if any(_amount(value) for value in row)]+ if not numeric_rows:+ return None, "no_numeric_amounts"+ total_row = numeric_rows[-1]+ last = rows[total_row]+ labels = [+ (index, value) for index, value in enumerate(last) if value and _amount(value) is None+ ]+ if len(labels) != 1 or not _TOTAL.search(labels[0][1]) or _SUBTOTAL.search(labels[0][1]):+ return None, "no_unambiguous_bottom_total"+ label_column, total_label = labels[0]+ if _SEMANTIC_EXCLUSION.search(total_label):+ return None, "ambiguous_financial_semantics"+ candidates = [+ index+ for index, value in enumerate(last)+ if index != label_column and _amount(value) is not None+ ]+ if not candidates:+ return None, "no_total_amount_column"+ total_words = []+ for _index, row in enumerate(rows[:total_row]):+ label = row[label_column] if label_column < len(row) else ""+ if _SUBTOTAL.search(label) or _TOTAL.search(label):+ return None, "intermediate_subtotal_or_total"+ if label:+ total_words.append(label)+ if _SEMANTIC_EXCLUSION.search(" ".join(total_words)):+ return None, "ambiguous_financial_semantics"+ return {+ "label_column": label_column,+ "total_row": total_row,+ "value_columns": candidates,+ "first_row_header": first_row_header,+ }, None+++def _column_components(+ rows: list[list[str]], plan: Mapping[str, Any], column: int, explicit: bool+) -> tuple[list[int] | None, str | None]:+ total_row = int(plan["total_row"])+ if explicit:+ indices = list(plan["component_rows"])+ if any(+ column >= len(rows[index]) or _amount(rows[index][column]) is None for index in indices+ ):+ return None, "missing_or_nonnumeric_component"+ return indices, None+ started = False+ indices: list[int] = []+ label_column = int(plan["label_column"])+ declared_header = bool(plan.get("first_row_header"))+ for index, row in enumerate(rows[:total_row]):+ value = row[column] if column < len(row) else ""+ parsed = _amount(value)+ if index == 0 and declared_header:+ if _SEMANTIC_EXCLUSION.search(value) or _NON_ADDITIVE_HEADER.search(value):+ return None, "non_additive_column_header"+ continue+ if not started and parsed is None and value:+ if _SEMANTIC_EXCLUSION.search(value) or _NON_ADDITIVE_HEADER.search(value):+ return None, "non_additive_column_header"+ if index == 0 and not declared_header and parsed is not None:+ label = row[label_column] if label_column < len(row) else ""+ if label and re.fullmatch(r"(?:19|20)[0-9]{2}", value.strip()):+ return None, "ambiguous_numeric_column_header"+ if parsed is not None:+ label = row[label_column] if label_column < len(row) else ""+ if not label or re.fullmatch(r"(?:19|20)[0-9]{2}", label.strip()):+ return None, "ambiguous_component_label"+ indices.append(index)+ started = True+ elif started and any(value.strip() for value in row):+ return None, "missing_or_nonnumeric_component"+ if len(indices) < 2:+ return None, "insufficient_additive_components"+ return indices, None+++def _check_column(+ rows: list[list[str]],+ plan: Mapping[str, Any],+ slide: int,+ table: int,+ column: int,+ *,+ explicit: bool,+) -> tuple[dict[str, Any] | None, str | None]:+ total_row = int(plan["total_row"])+ if column >= len(rows[total_row]):+ return None, "missing_total_amount"+ total = _amount(rows[total_row][column])+ if total is None:+ return None, "missing_total_amount"+ components, reason = _column_components(rows, plan, column, explicit)+ if reason:+ return None, reason+ assert components is not None+ parsed = [_amount(rows[index][column]) for index in components]+ if any(value is None for value in parsed):+ return None, "missing_or_nonnumeric_component"+ amounts: list[_Amount] = [value for value in parsed if value is not None]+ if not _consistent_units([*amounts, total]):+ return None, "mixed_amount_units"+ with localcontext() as arithmetic:+ arithmetic.prec = max(+ 64,+ max(len(value.value.as_tuple().digits) for value in [*amounts, total])+ + max(value.places for value in [*amounts, total])+ + len(str(len(amounts)))+ + 8,+ )+ difference = abs(sum((value.value for value in amounts), Decimal(0)) - total.value)+ tolerance = _rounding_tolerance([*amounts, total])+ return {+ "slide": slide,+ "table": table,+ "column": column,+ "component_count": len(amounts),+ "rounding_places": total.places,+ "explicit_contract": explicit,+ "comparison": "displayed_values_with_rounding_tolerance",+ "passed": difference <= tolerance,+ }, None+++def _normalize_contracts(contracts: Iterable[Mapping[str, Any]] | None) -> list[dict[str, Any]]:+ if contracts is None:+ return []+ _require(+ not isinstance(contracts, (str, bytes, Mapping)),+ "Arithmetic contracts must be a bounded list of objects",+ )+ result = []+ for contract in contracts:+ _require(+ len(result) < MAX_CONTRACTS and isinstance(contract, Mapping),+ "Arithmetic contracts must contain bounded objects",+ )+ keys = {"slide", "table", "label_column", "total_row", "value_columns", "component_rows"}+ _require(+ set(contract) == keys,+ "Arithmetic contracts must declare exactly the supported coordinates",+ )+ for field in ("slide", "table", "label_column", "total_row"):+ _require(+ isinstance(contract[field], int)+ and not isinstance(contract[field], bool)+ and contract[field] >= (1 if field in {"slide", "table"} else 0),+ "Arithmetic contracts contain an invalid row, table, or slide index",+ )+ normalized = dict(contract)+ for field, minimum in (("value_columns", 1), ("component_rows", 2)):+ values = contract[field]+ _require(+ isinstance(values, list)+ and minimum <= len(values) <= MAX_TABLE_ROWS+ and all(+ isinstance(value, int) and not isinstance(value, bool) and value >= 0+ for value in values+ )+ and len(set(values)) == len(values),+ "Arithmetic contracts contain repeated or invalid row/column coordinates",+ )+ normalized[field] = list(values)+ _require(+ all(index < contract["total_row"] for index in contract["component_rows"]),+ "Arithmetic-contract component rows must precede the total",+ )+ _require(+ contract["label_column"] not in contract["value_columns"],+ "Arithmetic-contract labels and amount columns must be distinct",+ )+ result.append(normalized)+ return result+++def audit_native_table_arithmetic(+ presentation: str | Path, *, contracts: Iterable[Mapping[str, Any]] | None = None+) -> dict[str, Any]:+ """Review auto-discovered totals and enforce caller-supplied contracts."""+ selected = Path(presentation)+ _require(+ selected.is_file()+ and not selected.is_symlink()+ and 0 < selected.stat().st_size <= MAX_PACKAGE_BYTES,+ "Presentation must be a bounded regular PowerPoint package",+ )+ requested = _normalize_contracts(contracts)+ checks: list[dict[str, Any]] = []+ findings: list[dict[str, Any]] = []+ warnings: list[dict[str, Any]] = []+ skipped: list[dict[str, Any]] = []+ seen_contracts: set[int] = set()+ native_count = 0+ eligible_count = 0+ try:+ with zipfile.ZipFile(selected) as package:+ names = package.namelist()+ _require(+ 0 < len(names) <= MAX_PACKAGE_PARTS and len(names) == len(set(names)),+ "Presentation contains duplicate or excessive package parts",+ )+ _require(+ sum(item.file_size for item in package.infolist()) <= MAX_PACKAGE_BYTES,+ "Presentation exceeds its bounded uncompressed package size",+ )+ _require(package.testzip() is None, "Presentation contains a corrupt package part")+ slides = logical_presentation_slides(package)+ for slide, part in slides.items():+ tables = _visible_tables(_safe_xml(package, part))+ native_count += len(tables)+ for index, table in enumerate(tables, 1):+ rows, merged, first_row_header = _rows(table)+ plan, reason = _auto_plan(rows, merged, first_row_header)+ auto_checked = 0+ if plan is not None:+ for column in plan["value_columns"]:+ result, column_reason = _check_column(+ rows,+ plan,+ slide,+ index,+ column,+ explicit=False,+ )+ if result is None:+ if auto_checked == 0:+ reason = column_reason+ continue+ checks.append(result)+ auto_checked += 1+ if auto_checked:+ eligible_count += 1+ if auto_checked == 0:+ skipped.append(+ _table_reason(reason or "no_unambiguous_amount_column", slide, index)+ )+ for position, contract in enumerate(requested):+ if contract["slide"] != slide or contract["table"] != index:+ continue+ seen_contracts.add(position)+ _require(+ contract["total_row"] < len(rows)+ and all(row < len(rows) for row in contract["component_rows"]),+ "Arithmetic contract references a missing native-table row",+ )+ for column in contract["value_columns"]:+ result, contract_reason = _check_column(+ rows,+ contract,+ slide,+ index,+ column,+ explicit=True,+ )+ _require(+ result is not None,+ "Arithmetic contract cannot resolve a nonnumeric or inconsistent amount column",+ )+ assert result is not None+ checks.append(result)+ _require(+ len(seen_contracts) == len(requested),+ "Arithmetic contract references an absent or hidden native table",+ )+ except zipfile.BadZipFile as exc:+ raise ArithmeticGateError("Presentation is not a valid Office package") from exc+ for check in checks:+ if not check["passed"]:+ target = findings if check["explicit_contract"] else warnings+ target.append(+ {+ "kind": "native_table_total_mismatch",+ "slide": check["slide"],+ "table": check["table"],+ "column": check["column"],+ "component_count": check["component_count"],+ "explicit_contract": check["explicit_contract"],+ }+ )+ return {+ "schema_version": SCHEMA_VERSION,+ "passed": not findings,+ "slide_count": len(slides),+ "native_table_count": native_count,+ "eligible_table_count": eligible_count,+ "checked_column_count": len(checks),+ "checks": checks,+ "skipped_tables": skipped,+ "finding_count": len(findings),+ "findings": findings,+ "warning_count": len(warnings),+ "warnings": warnings,+ "claim_boundary": "Displayed-value arithmetic with rounding tolerance; not source-data verification.",+ }+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(+ description="Audit clearly additive native PowerPoint table totals"+ )+ parser.add_argument("presentation", type=Path)+ parser.add_argument("--contract-json", action="append", default=[])+ parser.add_argument("--fail-on-findings", action="store_true")+ arguments = parser.parse_args(argv)+ try:+ contracts = [json.loads(value) for value in arguments.contract_json]+ result = audit_native_table_arithmetic(arguments.presentation, contracts=contracts)+ except (ArithmeticGateError, ValueError, OSError, RuntimeError) as exc:+ print(+ json.dumps(+ {+ "schema_version": SCHEMA_VERSION,+ "passed": False,+ "error": "native_table_arithmetic_audit_failed",+ "error_type": type(exc).__name__,+ },+ sort_keys=True,+ )+ )+ return 2+ print(json.dumps(result, sort_keys=True))+ return 0 if result["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/paper-fig/container_tools/rasterize_svg.mjs b/skills/paper-fig/container_tools/rasterize_svg.mjsnew file mode 100644index 0000000..d307805--- /dev/null+++ b/skills/paper-fig/container_tools/rasterize_svg.mjs@@ -0,0 +1,51 @@+#!/usr/bin/env node++// Helper used by ensure_raster_image.py to rasterize SVG/SVGZ through the+// bundled Node + sharp runtime instead of requiring Inkscape.++import fs from "node:fs/promises";+import path from "node:path";+import { parseArgs as parseNodeArgs } from "node:util";++import { requireRuntimeModule } from "./runtime_helpers.mjs";++function parseArgs(argv) {+ return parseNodeArgs({+ args: argv,+ options: {+ input: { type: "string" },+ output: { type: "string" },+ },+ allowPositionals: false,+ strict: true,+ }).values;+}++function requireArg(args, key) {+ const value = args[key];+ if (typeof value !== "string" || value.length === 0) {+ throw new Error(`Missing required --${key}`);+ }+ return value;+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ const input = path.resolve(requireArg(args, "input"));+ const output = path.resolve(requireArg(args, "output"));+ const sharp = await requireRuntimeModule("sharp");++ // Sharp sniffs input bytes, so a .svg filename can otherwise reach native+ // raster decoders. This dedicated subprocess should only load SVG content.+ sharp.block({ operation: ["VipsForeignLoad"] });+ sharp.unblock({ operation: ["VipsForeignLoadSvg"] });++ await fs.mkdir(path.dirname(output), { recursive: true });+ await sharp(input, { limitInputPixels: false }).png().toFile(output);+ console.log(JSON.stringify({ input, output }));+}++main().catch((error) => {+ console.error(error.stack || error.message || String(error));+ process.exit(1);+});diff --git a/skills/paper-fig/container_tools/render_presentation.mjs b/skills/paper-fig/container_tools/render_presentation.mjsnew file mode 100644index 0000000..07ba167--- /dev/null+++ b/skills/paper-fig/container_tools/render_presentation.mjs@@ -0,0 +1,97 @@+#!/usr/bin/env node++// Helper used by render_slides.py to render PowerPoint decks through+// @oai/artifact-tool instead of calling LibreOffice/soffice directly.++import fs from "node:fs/promises";+import path from "node:path";+import { parseArgs as parseNodeArgs } from "node:util";++import { importRuntimeModule } from "./runtime_helpers.mjs";++function parseArgs(argv) {+ return parseNodeArgs({+ args: argv,+ options: {+ help: { type: "boolean" },+ input: { type: "string" },+ output_dir: { type: "string" },+ scale: { type: "string" },+ },+ allowPositionals: false,+ strict: true,+ }).values;+}++function requireArg(args, key) {+ const value = args[key];+ if (typeof value !== "string" || value.length === 0) {+ throw new Error(`Missing required --${key}`);+ }+ return value;+}++async function saveBlobToFile(blob, outputPath) {+ await fs.mkdir(path.dirname(outputPath), { recursive: true });+ if (blob && typeof blob.arrayBuffer === "function") {+ await fs.writeFile(outputPath, Buffer.from(await blob.arrayBuffer()));+ return;+ }+ if (blob instanceof Uint8Array || Buffer.isBuffer(blob)) {+ await fs.writeFile(outputPath, Buffer.from(blob));+ return;+ }+ throw new Error("Expected a Blob or Uint8Array.");+}++function usage() {+ return [+ "Usage:",+ " $RUNTIME_NODE container_tools/render_presentation.mjs --input <deck.pptx> --output_dir <dir> [options]",+ "",+ "Options:",+ " --scale <number> Render scale. Defaults to 1.",+ ].join("\n");+}++function slidesFromPresentation(presentation) {+ if (Array.isArray(presentation.slides?.items)) return presentation.slides.items;+ if (Number.isInteger(presentation.slides?.count) && typeof presentation.slides.getItem === "function") {+ return Array.from({ length: presentation.slides.count }, (_, index) => presentation.slides.getItem(index));+ }+ throw new Error("Could not enumerate imported presentation slides.");+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(usage());+ return;+ }++ const input = path.resolve(requireArg(args, "input"));+ const outputDir = path.resolve(requireArg(args, "output_dir"));+ const scale = args.scale ? Number.parseFloat(args.scale) : 1;+ if (!Number.isFinite(scale) || scale <= 0) throw new Error("--scale must be a positive number.");++ await fs.mkdir(outputDir, { recursive: true });+ const { FileBlob, PresentationFile } = await importRuntimeModule("@oai/artifact-tool");+ const presentation = await PresentationFile.importPptx(await FileBlob.load(input));+ const slides = slidesFromPresentation(presentation);+ const paths = [];++ for (let index = 0; index < slides.length; index += 1) {+ const output = path.join(outputDir, `slide-${index + 1}.png`);+ const preview = await presentation.export({ slide: slides[index], format: "png", scale });+ await saveBlobToFile(preview, output);+ paths.push(output);+ }++ console.log(JSON.stringify({ input, outputDir, slideCount: slides.length, paths }, null, 2));+}++main().catch((error) => {+ console.error(error.stack || error.message || String(error));+ console.error(usage());+ process.exit(1);+});diff --git a/skills/paper-fig/container_tools/render_slides.py b/skills/paper-fig/container_tools/render_slides.pynew file mode 100644index 0000000..9e231ee--- /dev/null+++ b/skills/paper-fig/container_tools/render_slides.py@@ -0,0 +1,250 @@+#!/usr/bin/env python3+# Copyright (c) OpenAI. All rights reserved.+import argparse+import json+import re+import subprocess+import sys+import xml.etree.ElementTree as ET+from os import makedirs, replace+from os.path import abspath, basename, dirname, exists, expanduser, join, splitext+from typing import Sequence, cast+from zipfile import ZipFile++from pdf2image import convert_from_path, pdfinfo_from_path+from PIL import Image++SCRIPT_DIR = dirname(__file__)+if SCRIPT_DIR not in sys.path:+ sys.path.insert(0, SCRIPT_DIR)++from runtime_helpers import runtime_bin_dir, runtime_node # noqa: E402++EMU_PER_INCH: int = 914_400+PRESENTATION_EXTS = (".pptx", ".ppsx", ".potx", ".pptm", ".ppsm", ".potm")+++def calc_dpi_via_ooxml(input_path: str, max_w_px: int, max_h_px: int) -> int:+ """Calculate DPI from OOXML `ppt/presentation.xml` slide size (cx/cy in EMUs)."""+ with ZipFile(input_path, "r") as zf:+ xml = zf.read("ppt/presentation.xml")+ root = ET.fromstring(xml)+ ns = {"p": "http://schemas.openxmlformats.org/presentationml/2006/main"}+ sld_sz = root.find("p:sldSz", ns)+ if sld_sz is None:+ raise RuntimeError("Slide size not found in presentation.xml")+ cx = int(sld_sz.get("cx") or 0)+ cy = int(sld_sz.get("cy") or 0)+ if cx <= 0 or cy <= 0:+ raise RuntimeError("Invalid slide size values in presentation.xml")+ width_in = cx / EMU_PER_INCH+ height_in = cy / EMU_PER_INCH+ return round(min(max_w_px / width_in, max_h_px / height_in))+++def calc_dpi_via_pdf(input_path: str, max_w_px: int, max_h_px: int) -> int:+ """Compute DPI from PDF page size.++ For OOXML presentation inputs, use the presentation slide size directly.+ For PDFs, use the PDF directly.+ """+ is_pdf = input_path.lower().endswith(".pdf")+ if not is_pdf:+ if input_path.lower().endswith(PRESENTATION_EXTS):+ return calc_dpi_via_ooxml(input_path, max_w_px, max_h_px)+ raise RuntimeError("DPI computation is supported for PDF and OOXML presentation inputs.")++ info = pdfinfo_from_path(+ input_path,+ poppler_path=runtime_bin_dir("pdfinfo", "pdftoppm"),+ )+ size_val = info.get("Page size")+ if not size_val:+ for k, v in info.items():+ if isinstance(v, str) and "size" in k.lower() and "pts" in v:+ size_val = v+ break+ if not isinstance(size_val, str):+ raise RuntimeError("Failed to read PDF page size for DPI computation.")++ def _parse_page_size_to_pts(s: str) -> tuple[float, float]:+ # Common formats from poppler/pdfinfo:+ # - "612 x 792 pts (letter)"+ # - "595.276 x 841.89 pts (A4)"+ # - sometimes inches: "8.5 x 11 in"+ m_pts = re.search(+ r"([0-9]+(?:\.[0-9]+)?)\s*x\s*([0-9]+(?:\.[0-9]+)?)\s*pts\b",+ s,+ )+ if m_pts:+ return float(m_pts.group(1)), float(m_pts.group(2))+ m_in = re.search(+ r"([0-9]+(?:\.[0-9]+)?)\s*x\s*([0-9]+(?:\.[0-9]+)?)\s*in\b",+ s,+ )+ if m_in:+ w_in = float(m_in.group(1))+ h_in = float(m_in.group(2))+ return w_in * 72.0, h_in * 72.0+ # Sometimes poppler returns without an explicit unit; treat as points.+ m = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*x\s*([0-9]+(?:\.[0-9]+)?)\b", s)+ if m:+ return float(m.group(1)), float(m.group(2))+ raise RuntimeError(f"Unrecognized PDF page size format: {s!r}")++ width_pts, height_pts = _parse_page_size_to_pts(size_val)+ width_in = width_pts / 72.0+ height_in = height_pts / 72.0+ if width_in <= 0 or height_in <= 0:+ raise RuntimeError("Invalid PDF page size values.")+ return round(min(max_w_px / width_in, max_h_px / height_in))+++def _render_presentation_with_artifact_tool(+ input_path: str, out_dir: str, dpi: int+) -> Sequence[str]:+ scale = max(dpi / 96.0, 0.01)+ proc = subprocess.run(+ [+ runtime_node(),+ join(SCRIPT_DIR, "render_presentation.mjs"),+ "--input",+ input_path,+ "--output_dir",+ out_dir,+ "--scale",+ f"{scale:.6f}",+ ],+ capture_output=True,+ text=True,+ check=False,+ )+ if proc.returncode != 0:+ details = (proc.stderr or proc.stdout or "").strip()+ raise RuntimeError(+ "Failed to render presentation with artifact-tool."+ + (f"\n{details}" if details else "")+ )+ payload = json.loads(proc.stdout)+ return cast(Sequence[str], payload["paths"])+++def convert_to_pdf(+ pptx_path: str,+ user_profile: str,+ convert_tmp_dir: str,+ stem: str,+) -> str:+ pdf_path = join(convert_tmp_dir, f"{stem}.pdf")+ if pptx_path.lower().endswith(".pdf"):+ return pptx_path+ if not pptx_path.lower().endswith(PRESENTATION_EXTS):+ return ""++ image_dir = join(convert_tmp_dir, stem + "_pdf_pages")+ paths = list(_render_presentation_with_artifact_tool(pptx_path, image_dir, dpi=96))+ if not paths:+ return ""++ images = []+ try:+ for path in paths:+ images.append(Image.open(path).convert("RGB"))+ first, *rest = images+ first.save(pdf_path, "PDF", save_all=True, append_images=rest)+ finally:+ for image in images:+ image.close()+ return pdf_path if exists(pdf_path) else ""+++def rasterize(+ input_path: str,+ out_dir: str,+ dpi: int,+) -> Sequence[str]:+ """Rasterise PPTX/PDF to PNG files placed in out_dir and return the image paths."""+ makedirs(out_dir, exist_ok=True)+ input_path = abspath(input_path)++ if input_path.lower().endswith(PRESENTATION_EXTS):+ return _render_presentation_with_artifact_tool(input_path, out_dir, dpi)++ if not input_path.lower().endswith(".pdf"):+ raise RuntimeError("Rasterization is supported for PDF and OOXML presentation inputs.")++ paths_raw = cast(+ list[str],+ convert_from_path(+ input_path,+ dpi=dpi,+ fmt="png",+ thread_count=8,+ output_folder=out_dir,+ paths_only=True,+ output_file="slide",+ poppler_path=runtime_bin_dir("pdfinfo", "pdftoppm"),+ ),+ )+ # Rename convert_from_path's output format f'slide{thread_id:04d}-{page_num:02d}.png'+ slides = []+ for src_path in paths_raw:+ base = splitext(basename(src_path))[0]+ slide_num_str = base.split("-")[-1]+ slide_num = int(slide_num_str)+ dst_path = join(out_dir, f"slide-{slide_num}.png")+ replace(src_path, dst_path)+ slides.append((slide_num, dst_path))+ slides.sort(key=lambda t: t[0])+ final_paths = [path for _, path in slides]+ return final_paths+++def main() -> None:+ parser = argparse.ArgumentParser(description="Render slides to images.")+ parser.add_argument(+ "input_path",+ type=str,+ help="Path to the input PowerPoint or PDF file.",+ )+ parser.add_argument(+ "--output_dir",+ type=str,+ default=None,+ help=(+ "Output directory for the rendered images. "+ "Defaults to a folder next to the input named after the input file (without extension)."+ ),+ )+ parser.add_argument(+ "--width",+ type=int,+ default=1600,+ help=(+ "Approximate maximum width in pixels after isotropic scaling (default 1600). "+ "The actual value may exceed slightly."+ ),+ )+ parser.add_argument(+ "--height",+ type=int,+ default=900,+ help=(+ "Approximate maximum height in pixels after isotropic scaling (default 900). "+ "The actual value may exceed slightly."+ ),+ )+ args = parser.parse_args()++ input_path = abspath(expanduser(args.input_path))+ out_dir = abspath(expanduser(args.output_dir)) if args.output_dir else splitext(input_path)[0]+ if input_path.lower().endswith((".pptx", ".ppsx", ".potx", ".pptm", ".ppsm", ".potm")):+ dpi = calc_dpi_via_ooxml(input_path, args.width, args.height)+ else:+ dpi = calc_dpi_via_pdf(input_path, args.width, args.height)+ rasterize(input_path, out_dir, dpi)+ print("Slides rendered to " + out_dir)+++if __name__ == "__main__":+ main()diff --git a/skills/paper-fig/container_tools/runtime_helpers.mjs b/skills/paper-fig/container_tools/runtime_helpers.mjsnew file mode 100644index 0000000..84975aa--- /dev/null+++ b/skills/paper-fig/container_tools/runtime_helpers.mjs@@ -0,0 +1,49 @@+import fs from "node:fs/promises";+import { createRequire } from "node:module";+import path from "node:path";+import { pathToFileURL } from "node:url";++export async function runtimeNodeModules() {+ const nodeModules = process.env.RUNTIME_NODE_MODULES;+ if (!nodeModules) throw new Error("RUNTIME_NODE_MODULES is required.");+ if (!path.isAbsolute(nodeModules)) {+ throw new Error("RUNTIME_NODE_MODULES must be an absolute path.");+ }+ const stat = await fs.stat(nodeModules).catch(() => undefined);+ if (!stat?.isDirectory()) {+ throw new Error(`RUNTIME_NODE_MODULES is not a directory: ${nodeModules}`);+ }+ return nodeModules;+}++async function runtimeRequire() {+ const nodeModules = await runtimeNodeModules();+ return {+ nodeModules,+ requireFromRuntime: createRequire(path.join(nodeModules, "__runtime__.cjs")),+ };+}++export async function requireRuntimeModule(packageName) {+ const { nodeModules, requireFromRuntime } = await runtimeRequire();+ try {+ return requireFromRuntime(packageName);+ } catch (error) {+ throw new Error(`Could not resolve ${packageName} from RUNTIME_NODE_MODULES: ${nodeModules}`, {+ cause: error,+ });+ }+}++export async function importRuntimeModule(packageName) {+ const { nodeModules, requireFromRuntime } = await runtimeRequire();+ let entrypoint;+ try {+ entrypoint = requireFromRuntime.resolve(packageName);+ } catch (error) {+ throw new Error(`Could not resolve ${packageName} from RUNTIME_NODE_MODULES: ${nodeModules}`, {+ cause: error,+ });+ }+ return import(pathToFileURL(entrypoint).href);+}diff --git a/skills/paper-fig/container_tools/runtime_helpers.py b/skills/paper-fig/container_tools/runtime_helpers.pynew file mode 100644index 0000000..5f763c0--- /dev/null+++ b/skills/paper-fig/container_tools/runtime_helpers.py@@ -0,0 +1,87 @@+import json+import os+from pathlib import Path+++def _required_runtime_path(env_name: str, *, directory: bool) -> Path:+ raw_value = os.environ.get(env_name)+ if not raw_value:+ raise RuntimeError(f"{env_name} is required.")+ value = Path(raw_value)+ if not value.is_absolute():+ raise RuntimeError(f"{env_name} must be an absolute path.")+ if directory and not value.is_dir():+ raise RuntimeError(f"{env_name} is not a directory: {value}")+ if not directory and not value.is_file():+ raise RuntimeError(f"{env_name} is not a file: {value}")+ return value+++def _binary_candidates(bin_dir: Path, name: str) -> tuple[Path, ...]:+ suffixes = (".exe", "") if os.name == "nt" else ("",)+ return tuple(bin_dir / f"{name}{suffix}" for suffix in suffixes)+++def runtime_node() -> str:+ node = _required_runtime_path("RUNTIME_NODE", directory=False)+ if os.name != "nt" and not os.access(node, os.X_OK):+ raise RuntimeError(f"RUNTIME_NODE is not executable: {node}")+ return str(node)+++def runtime_binary(name: str) -> str:+ bin_dir = _required_runtime_path("RUNTIME_BIN_DIR", directory=True)+ if os.name == "nt":+ manifest_path = bin_dir / "native-executables.json"+ try:+ executable_paths = json.loads(manifest_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as error:+ raise RuntimeError(+ f"RUNTIME_BIN_DIR native executable manifest is unavailable: {manifest_path}"+ ) from error++ relative_path = executable_paths.get(name) if isinstance(executable_paths, dict) else None+ if not isinstance(relative_path, str) or Path(relative_path).is_absolute():+ raise RuntimeError(f"RUNTIME_BIN_DIR native executable is missing for {name}")++ native_root = (bin_dir.parent.parent / "native").resolve()+ executable_path = (bin_dir / relative_path).resolve()+ if executable_path.suffix.lower() != ".exe" or not executable_path.is_relative_to(+ native_root+ ):+ raise RuntimeError(+ f"RUNTIME_BIN_DIR native executable for {name} must be a packaged .exe: "+ f"{executable_path}"+ )+ if not executable_path.is_file():+ raise RuntimeError(+ f"RUNTIME_BIN_DIR native executable is not a file for {name}: {executable_path}"+ )+ return str(executable_path)++ for candidate in _binary_candidates(bin_dir, name):+ if candidate.is_file():+ return str(candidate)+ raise RuntimeError(f"RUNTIME_BIN_DIR is missing required binary {name}: {bin_dir}")+++def runtime_bin_dir(*required_binaries: str) -> str:+ bin_dir = _required_runtime_path("RUNTIME_BIN_DIR", directory=True)+ if os.name == "nt" and required_binaries:+ native_directories = [Path(runtime_binary(name)).parent for name in required_binaries]+ if len(set(native_directories)) != 1:+ raise RuntimeError(+ "RUNTIME_BIN_DIR required binaries must share the same native directory."+ )+ return str(native_directories[0])++ missing = [+ name+ for name in required_binaries+ if not any(candidate.is_file() for candidate in _binary_candidates(bin_dir, name))+ ]+ if missing:+ raise RuntimeError(+ f"RUNTIME_BIN_DIR is missing required binaries {', '.join(missing)}: {bin_dir}"+ )+ return str(bin_dir)diff --git a/skills/paper-fig/container_tools/slides_test.py b/skills/paper-fig/container_tools/slides_test.pynew file mode 100644index 0000000..fd2b045--- /dev/null+++ b/skills/paper-fig/container_tools/slides_test.py@@ -0,0 +1,200 @@+#!/usr/bin/env python3+# Copyright (c) OpenAI. All rights reserved.+import argparse+import sys+import tempfile+from os.path import abspath, dirname, expanduser, join+from typing import Sequence, cast++import numpy as np++SCRIPT_DIR = dirname(__file__)+if SCRIPT_DIR not in sys.path:+ sys.path.insert(0, SCRIPT_DIR)++import render_slides # type: ignore+from PIL import Image+from pptx import Presentation+from pptx.dml.color import RGBColor+from pptx.enum.shapes import MSO_AUTO_SHAPE_TYPE+from pptx.util import Emu++# Configuration specific to overflow checking+PAD_PX: int = 100 # fixed padding on every side in pixels+PAD_RGB = (200, 200, 200)+EMU_PER_INCH: int = 914_400+++def px_to_emu(px: int, dpi: int) -> Emu:+ return Emu(int(px * EMU_PER_INCH // dpi))+++def calc_tol(dpi: int) -> int:+ """Calculate per-channel colour tolerance appropriate for *dpi* (anti-aliasing tolerance)."""+ if dpi >= 300:+ return 0+ # 1 at 250 DPI, 5 at 150 DPI, capped to 10.+ tol = round((300 - dpi) / 25)+ return min(max(tol, 1), 10)+++def enlarge_deck(src: str, dst: str, pad_emu: Emu) -> tuple[int, int]:+ """Enlarge the input PPTX with a fixed grey padding and return the new page size."""+ prs = Presentation(src)+ w0 = cast(Emu, prs.slide_width)+ h0 = cast(Emu, prs.slide_height)+ w1 = Emu(w0 + 2 * pad_emu)+ h1 = Emu(h0 + 2 * pad_emu)+ prs.slide_width = w1+ prs.slide_height = h1++ for slide in prs.slides:+ # Shift all shapes so the original canvas sits centred in the new deck.+ for shp in list(slide.shapes):+ shp.left = Emu(int(shp.left) + pad_emu)+ shp.top = Emu(int(shp.top) + pad_emu)++ pads = (+ (Emu(0), Emu(0), pad_emu, h1), # left+ (Emu(int(w1) - int(pad_emu)), Emu(0), pad_emu, h1), # right+ (Emu(0), Emu(0), w1, pad_emu), # top+ (Emu(0), Emu(int(h1) - int(pad_emu)), w1, pad_emu), # bottom+ )++ sp_tree = slide.shapes._spTree # pylint: disable=protected-access++ for left, top, width, height in pads:+ pad_shape = slide.shapes.add_shape(+ MSO_AUTO_SHAPE_TYPE.RECTANGLE, left, top, width, height+ )+ pad_shape.fill.solid()+ pad_shape.fill.fore_color.rgb = RGBColor(*PAD_RGB)+ pad_shape.line.fill.background()++ # Send pad behind all other shapes (index 2 after mandatory nodes)+ sp_tree.remove(pad_shape._element)+ sp_tree.insert(2, pad_shape._element)++ prs.save(dst)+ return int(w1), int(h1)+++def inspect_images(+ paths: Sequence[str],+ pad_ratio_w: float,+ pad_ratio_h: float,+ dpi: int,+) -> list[int]:+ """Return 1-based indices of slides that contain pixels outside the pad."""++ tol = calc_tol(dpi)+ failures: list[int] = []+ pad_colour = np.array(PAD_RGB, dtype=np.uint8)++ for idx, img_path in enumerate(paths, start=1):+ with Image.open(img_path) as img:+ rgb = img.convert("RGB")+ arr = np.asarray(rgb)++ h, w, _ = arr.shape+ # Exclude the innermost 1-pixel band+ pad_x = int(w * pad_ratio_w) - 1+ pad_y = int(h * pad_ratio_h) - 1++ left_margin = arr[:, :pad_x, :]+ right_margin = arr[:, w - pad_x :, :]+ top_margin = arr[:pad_y, :, :]+ bottom_margin = arr[h - pad_y :, :, :]++ def _is_clean(margin: np.ndarray) -> bool:+ diff = np.abs(margin.astype(np.int16) - pad_colour)+ matches = np.all(diff <= tol, axis=-1)+ mismatch_fraction = 1.0 - (np.count_nonzero(matches) / matches.size)+ if dpi >= 300:+ max_mismatch = 0.01+ elif dpi >= 200:+ max_mismatch = 0.02+ else:+ max_mismatch = 0.03+ return mismatch_fraction <= max_mismatch++ if not (+ _is_clean(left_margin)+ and _is_clean(right_margin)+ and _is_clean(top_margin)+ and _is_clean(bottom_margin)+ ):+ failures.append(idx)++ return failures+++def main() -> None:+ parser = argparse.ArgumentParser(+ description=(+ "Check a PPTX for content overflowing the original canvas by rendering with padding "+ "and inspecting the margins."+ )+ )+ parser.add_argument(+ "input_path",+ type=str,+ help="Path to the input PPTX file.",+ )+ parser.add_argument(+ "--width",+ type=int,+ default=1600,+ help=(+ "Approximate maximum width in pixels after isotropic scaling (default 1600). "+ "The actual value may exceed slightly."+ ),+ )+ parser.add_argument(+ "--height",+ type=int,+ default=900,+ help=(+ "Approximate maximum height in pixels after isotropic scaling (default 900). "+ "The actual value may exceed slightly."+ ),+ )+ parser.add_argument(+ "--pad_px",+ type=int,+ default=PAD_PX,+ help="Padding in pixels to add on each side before rasterization.",+ )+ args = parser.parse_args()++ input_path = abspath(expanduser(args.input_path))+ # Width and height refer to the original, unaltered slide dimensions.+ dpi = render_slides.calc_dpi_via_ooxml(input_path, args.width, args.height)++ # Not using ``tempfile.TemporaryDirectory(delete=False)`` for Python 3.11 compatibility.+ tmpdir = tempfile.mkdtemp()+ enlarged_pptx = join(tmpdir, "enlarged.pptx")+ pad_emu = px_to_emu(args.pad_px, dpi)+ w1, h1 = enlarge_deck(input_path, enlarged_pptx, pad_emu=pad_emu)+ pad_ratio_w = pad_emu / w1+ pad_ratio_h = pad_emu / h1++ img_dir = join(tmpdir, "imgs")+ img_paths = render_slides.rasterize(enlarged_pptx, img_dir, dpi)+ failing = inspect_images(img_paths, pad_ratio_w, pad_ratio_h, dpi)++ if failing:+ print(+ "ERROR: Slides with content overflowing original canvas (1-based indexing): "+ + ", ".join(map(str, failing))+ + "\n"+ + "Rendered images with grey paddings for problematic slides are available at: "+ )+ for i in failing:+ print(img_paths[i - 1])+ else:+ print("Test passed. No overflow detected.")+++if __name__ == "__main__":+ main()diff --git a/skills/paper-fig/container_tools/template_source_fidelity_gate.py b/skills/paper-fig/container_tools/template_source_fidelity_gate.pynew file mode 100644index 0000000..10cea0d--- /dev/null+++ b/skills/paper-fig/container_tools/template_source_fidelity_gate.py@@ -0,0 +1,532 @@+#!/usr/bin/env python3+"""Validate only explicitly requested, source-approved presentation template rules.++No prompt wording, slide text, source-image bytes, or universal coverage+threshold is returned. Supplying no explicit requirement is a neutral no-op.+"""++from __future__ import annotations++import argparse+import io+import json+import math+import posixpath+import sys+import zipfile+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Mapping+from urllib.parse import urlsplit+from xml.etree import ElementTree++P = "http://schemas.openxmlformats.org/presentationml/2006/main"+A = "http://schemas.openxmlformats.org/drawingml/2006/main"+R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+PR = "http://schemas.openxmlformats.org/package/2006/relationships"+NS = {"p": P, "a": A, "r": R, "pr": PR}+MAX_PART_BYTES = 100 * 1024 * 1024+MAX_PARTS = 2500+MAX_PACKAGE_BYTES = 512 * 1024 * 1024+++class TemplateGateError(ValueError):+ """A caller configuration or approved package is unsafe or malformed."""+++@dataclass(frozen=True)+class TemplateFidelityRequirements:+ reference_slide_indices: tuple[int, ...] = ()+ minimum_coverage_ratio: float | None = None+ require_exact_dimensions: bool = False+ require_placeholder_geometry: bool = False+ require_photographic_background: bool = False+ geometry_tolerance_emu: int = 0++ @property+ def enabled(self) -> bool:+ return bool(+ self.reference_slide_indices+ or self.minimum_coverage_ratio is not None+ or self.require_exact_dimensions+ or self.require_placeholder_geometry+ or self.require_photographic_background+ )+++@dataclass(frozen=True)+class _SlideProfile:+ family: tuple[Any, ...]+ placeholders: tuple[tuple[str, str, tuple[int, int, int, int] | None], ...]+ photographic_background: bool+++@dataclass(frozen=True)+class _Presentation:+ dimensions: tuple[int, int]+ slides: tuple[_SlideProfile, ...]+++def _require(condition: bool, code: str) -> None:+ if not condition:+ raise TemplateGateError(code)+++def _xml(package: zipfile.ZipFile, name: str) -> ElementTree.Element:+ try:+ info = package.getinfo(name)+ except KeyError as exc:+ raise TemplateGateError("missing_required_package_part") from exc+ _require(info.file_size <= MAX_PART_BYTES, "oversized_package_part")+ payload = package.read(info)+ _require(+ b"<!doctype" not in payload.lower() and b"<!entity" not in payload.lower(),+ "unsafe_package_xml",+ )+ try:+ return ElementTree.fromstring(payload)+ except ElementTree.ParseError as exc:+ raise TemplateGateError("malformed_package_xml") from exc+++def _resolved(parent: str, target: str) -> str:+ _require(isinstance(target, str) and bool(target), "invalid_relationship_target")+ parsed = urlsplit(target)+ _require(+ not parsed.scheme and not parsed.netloc and "\\" not in target,+ "external_relationship_rejected",+ )+ if target.startswith("/"):+ result = posixpath.normpath(target.lstrip("/"))+ else:+ result = posixpath.normpath(posixpath.join(posixpath.dirname(parent), target))+ _require(result != ".." and not result.startswith("../"), "unsafe_relationship_target")+ return result+++def _relationships(package: zipfile.ZipFile, part: str) -> dict[str, dict[str, str]]:+ rel_path = posixpath.join(posixpath.dirname(part), "_rels", posixpath.basename(part) + ".rels")+ if rel_path not in package.namelist():+ return {}+ result: dict[str, dict[str, str]] = {}+ identities: set[str] = set()+ for item in _xml(package, rel_path).findall("pr:Relationship", NS):+ identity = item.get("Id", "")+ target = item.get("Target", "")+ _require(bool(identity and target), "invalid_relationship")+ _require(identity not in identities, "duplicate_relationship_id")+ identities.add(identity)+ mode = item.get("TargetMode", "Internal").casefold()+ _require(mode in {"internal", "external"}, "invalid_relationship_mode")+ if mode == "external":+ # A normal clickable link is not an externally loaded resource.+ # Permit it only with the genuine hyperlink relationship type, never+ # image, workbook, OLE, or other package relationships.+ parsed = urlsplit(target)+ _require(+ item.get("Type") == R + "/hyperlink"+ and not any(ord(character) <= 32 or ord(character) == 127 for character in target)+ and "\\" not in target+ and (+ parsed.scheme.casefold() in {"http", "https"}+ and bool(parsed.hostname)+ or parsed.scheme.casefold() == "mailto"+ and bool(parsed.path)+ and not parsed.netloc+ ),+ "external_relationship_rejected",+ )+ continue+ _resolved(part, target)+ result[identity] = {"target": target, "type": item.get("Type", "")}+ return result+++def _relationship_of_type(+ relationships: Mapping[str, Mapping[str, str]], suffix: str+) -> str | None:+ values = [+ item["target"] for item in relationships.values() if item.get("type", "").endswith(suffix)+ ]+ _require(len(values) <= 1, "ambiguous_layout_relationship")+ return values[0] if values else None+++def _geometry(shape: ElementTree.Element) -> tuple[int, int, int, int] | None:+ transform = shape.find("./p:spPr/a:xfrm", NS)+ if transform is None:+ return None+ offset = transform.find("a:off", NS)+ extent = transform.find("a:ext", NS)+ if offset is None or extent is None:+ return None+ try:+ return (+ int(offset.get("x", "0")),+ int(offset.get("y", "0")),+ int(extent.get("cx", "0")),+ int(extent.get("cy", "0")),+ )+ except ValueError as exc:+ raise TemplateGateError("invalid_placeholder_geometry") from exc+++def _placeholder_map(+ root: ElementTree.Element,+) -> dict[tuple[str, str], tuple[int, int, int, int] | None]:+ result = {}+ for shape in root.findall(".//p:sp", NS):+ placeholder = shape.find("./p:nvSpPr/p:nvPr/p:ph", NS)+ if placeholder is None:+ continue+ key = (placeholder.get("type", "obj"), placeholder.get("idx", ""))+ _require(key not in result, "duplicate_placeholder_identity")+ result[key] = _geometry(shape)+ return result+++def _fallback_geometry(+ key: tuple[str, str], *layers: Mapping[tuple[str, str], tuple[int, int, int, int] | None]+) -> tuple[int, int, int, int] | None:+ for layer in layers:+ if key in layer and layer[key] is not None:+ return layer[key]+ matches = [+ value for (kind, _), value in layer.items() if kind == key[0] and value is not None+ ]+ if len(matches) == 1:+ return matches[0]+ return None+++def _photographic_background(+ package: zipfile.ZipFile, layers: tuple[tuple[str, ElementTree.Element], ...]+) -> bool:+ for part, node in layers:+ background = node.find("./p:cSld/p:bg", NS)+ if background is None:+ continue+ fill = background.find(".//a:blipFill", NS)+ if fill is None:+ # An explicit non-photo background replaces inherited backgrounds.+ return False+ blip = fill.find("a:blip", NS)+ _require(blip is not None, "invalid_photographic_background")+ _require(blip.get("{" + R + "}link") is None, "external_relationship_rejected")+ identity = blip.get("{" + R + "}embed", "")+ relationship = _relationships(package, part).get(identity)+ _require(+ relationship is not None and relationship.get("type", "").endswith("/image"),+ "missing_background_image_relationship",+ )+ image_part = _resolved(part, relationship["target"])+ _require(image_part in package.namelist(), "missing_background_image_part")+ _require(+ posixpath.splitext(image_part)[1].casefold()+ in {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tif", ".tiff", ".webp"},+ "invalid_background_image_type",+ )+ return True+ return False+++def _slide_profile(package: zipfile.ZipFile, part: str) -> _SlideProfile:+ slide = _xml(package, part)+ slide_rels = _relationships(package, part)+ layout_target = _relationship_of_type(slide_rels, "/slideLayout")+ layout_part = _resolved(part, layout_target) if layout_target else None+ layout = _xml(package, layout_part) if layout_part else None+ layout_rels = _relationships(package, layout_part) if layout_part else {}+ master_target = _relationship_of_type(layout_rels, "/slideMaster")+ master_part = _resolved(layout_part, master_target) if layout_part and master_target else None+ master = _xml(package, master_part) if master_part else None++ source_placeholders = _placeholder_map(slide)+ layout_placeholders = _placeholder_map(layout) if layout is not None else {}+ master_placeholders = _placeholder_map(master) if master is not None else {}+ identities = set(source_placeholders) | set(layout_placeholders)+ if not identities:+ identities = set(master_placeholders)+ resolved = tuple(+ sorted(+ (+ kind,+ index,+ _fallback_geometry(+ (kind, index), source_placeholders, layout_placeholders, master_placeholders+ ),+ )+ for kind, index in identities+ )+ )+ layout_type = layout.get("type", "custom") if layout is not None else "unassigned"+ family = (+ layout_type,+ tuple(sorted((kind, index) for kind, index in identities)),+ tuple(sorted((kind, index) for kind, index in master_placeholders)),+ )+ layers: list[tuple[str, ElementTree.Element]] = [(part, slide)]+ if layout_part and layout is not None:+ layers.append((layout_part, layout))+ if master_part and master is not None:+ layers.append((master_part, master))+ return _SlideProfile(+ family=family,+ placeholders=resolved,+ photographic_background=_photographic_background(package, tuple(layers)),+ )+++def _read_presentation(value: str | Path | bytes) -> _Presentation:+ handle: io.BytesIO | str | Path = io.BytesIO(value) if isinstance(value, bytes) else value+ try:+ with zipfile.ZipFile(handle) as package:+ _require(len(package.infolist()) <= MAX_PARTS, "excessive_package_parts")+ _require(+ len(package.namelist()) == len(set(package.namelist())), "duplicate_package_parts"+ )+ _require(+ sum(item.file_size for item in package.infolist()) <= MAX_PACKAGE_BYTES,+ "oversized_package",+ )+ for item in package.infolist():+ _require(+ not item.filename.startswith("/")+ and ".." not in item.filename.split("/")+ and "\\" not in item.filename,+ "unsafe_package_part",+ )+ if item.filename.endswith(".rels"):+ directory, filename = posixpath.split(item.filename)+ if item.filename == "_rels/.rels":+ owner = ""+ else:+ _require(directory.endswith("/_rels"), "invalid_relationship_part")+ owner = posixpath.join(directory[:-6], filename[:-5])+ _relationships(package, owner)+ presentation = _xml(package, "ppt/presentation.xml")+ size = presentation.find("p:sldSz", NS)+ _require(size is not None, "missing_presentation_dimensions")+ try:+ dimensions = (int(size.get("cx", "")), int(size.get("cy", "")))+ except ValueError as exc:+ raise TemplateGateError("invalid_presentation_dimensions") from exc+ _require(all(x > 0 for x in dimensions), "invalid_presentation_dimensions")+ relationships = _relationships(package, "ppt/presentation.xml")+ slides = []+ for item in presentation.findall("./p:sldIdLst/p:sldId", NS):+ relationship = relationships.get(item.get("{" + R + "}id", ""))+ _require(+ relationship is not None and relationship.get("type", "").endswith("/slide"),+ "missing_slide_relationship",+ )+ slides.append(+ _slide_profile(+ package, _resolved("ppt/presentation.xml", relationship["target"])+ )+ )+ return _Presentation(dimensions=dimensions, slides=tuple(slides))+ except zipfile.BadZipFile as exc:+ raise TemplateGateError("invalid_powerpoint_package") from exc+++def _valid_requirements(value: TemplateFidelityRequirements) -> None:+ _require(isinstance(value, TemplateFidelityRequirements), "invalid_template_requirements")+ indices = value.reference_slide_indices+ _require(+ isinstance(indices, tuple)+ and all(isinstance(x, int) and not isinstance(x, bool) and x > 0 for x in indices),+ "invalid_reference_slide_indices",+ )+ _require(len(set(indices)) == len(indices), "duplicate_reference_slide_indices")+ if value.minimum_coverage_ratio is not None:+ ratio = value.minimum_coverage_ratio+ _require(+ isinstance(ratio, (int, float))+ and not isinstance(ratio, bool)+ and math.isfinite(float(ratio))+ and 0 <= float(ratio) <= 1,+ "invalid_explicit_minimum_ratio",+ )+ _require(bool(indices), "minimum_ratio_requires_explicit_reference_slides")+ if indices:+ _require(+ value.minimum_coverage_ratio is not None,+ "reference_slides_require_explicit_minimum_ratio",+ )+ if value.require_placeholder_geometry or value.require_photographic_background:+ _require(bool(indices), "explicit_requirement_needs_reference_slides")+ _require(+ isinstance(value.geometry_tolerance_emu, int)+ and not isinstance(value.geometry_tolerance_emu, bool)+ and value.geometry_tolerance_emu >= 0,+ "invalid_geometry_tolerance",+ )+++def _geometry_equal(source: _SlideProfile, generated: _SlideProfile, tolerance: int) -> bool:+ a = {(kind, index): geometry for kind, index, geometry in source.placeholders}+ b = {(kind, index): geometry for kind, index, geometry in generated.placeholders}+ if set(a) != set(b):+ return False+ for key, left in a.items():+ right = b[key]+ if left is None or right is None:+ if left != right:+ return False+ continue+ if any(abs(x - y) > tolerance for x, y in zip(left, right)):+ return False+ return True+++def validate_template_source_fidelity(+ source_template: str | Path | bytes,+ generated_presentation: str | Path | bytes,+ requirements: TemplateFidelityRequirements,+) -> dict[str, Any]:+ _valid_requirements(requirements)+ result: dict[str, Any] = {+ "schema_version": "template_source_fidelity.v1",+ "status": "not_applicable",+ "passed": True,+ "reference_family_count": 0,+ "matched_family_count": 0,+ "generated_slide_count": 0,+ "matched_generated_slide_count": 0,+ "coverage_ratio": None,+ "minimum_coverage_ratio": requirements.minimum_coverage_ratio,+ "dimensions_match": None,+ "geometry_match": None,+ "photographic_background_required": requirements.require_photographic_background,+ "photographic_background_matched": None,+ "issue_codes": [],+ "prompt_or_slide_text_included": False,+ }+ if not requirements.enabled:+ return result++ source = _read_presentation(source_template)+ generated = _read_presentation(generated_presentation)+ _require(bool(generated.slides), "generated_presentation_has_no_slides")+ result["generated_slide_count"] = len(generated.slides)+ issues: set[str] = set()+ if requirements.require_exact_dimensions:+ result["dimensions_match"] = source.dimensions == generated.dimensions+ if not result["dimensions_match"]:+ issues.add("template_dimensions_mismatch")++ references: dict[tuple[Any, ...], list[_SlideProfile]] = {}+ for index in requirements.reference_slide_indices:+ _require(index <= len(source.slides), "reference_slide_out_of_range")+ profile = source.slides[index - 1]+ profiles = references.setdefault(profile.family, [])+ if profile not in profiles:+ profiles.append(profile)+ result["reference_family_count"] = len(references)++ matched_families: set[tuple[Any, ...]] = set()+ matched_generated_slides = 0+ geometry_valid = True+ required_photo_families = {+ family+ for family, profiles in references.items()+ if any(profile.photographic_background for profile in profiles)+ }+ matched_photo_families: set[tuple[Any, ...]] = set()+ photo_mismatch = False+ for slide in generated.slides:+ profiles = references.get(slide.family)+ if not profiles:+ continue+ if requirements.require_placeholder_geometry:+ profiles = [+ profile+ for profile in profiles+ if _geometry_equal(profile, slide, requirements.geometry_tolerance_emu)+ ]+ if not profiles:+ geometry_valid = False+ continue+ if requirements.require_photographic_background:+ photographic_profiles = [+ profile for profile in profiles if profile.photographic_background+ ]+ if photographic_profiles and not slide.photographic_background:+ photo_mismatch = True+ continue+ if photographic_profiles and slide.photographic_background:+ matched_photo_families.add(slide.family)+ matched_generated_slides += 1+ matched_families.add(slide.family)++ result["matched_family_count"] = len(matched_families)+ result["matched_generated_slide_count"] = matched_generated_slides+ if references:+ result["coverage_ratio"] = matched_generated_slides / len(generated.slides)+ if float(result["coverage_ratio"]) < float(requirements.minimum_coverage_ratio):+ issues.add("explicit_template_family_coverage_not_met")+ if requirements.require_placeholder_geometry:+ result["geometry_match"] = geometry_valid+ if not geometry_valid:+ issues.add("template_placeholder_geometry_mismatch")+ if requirements.require_photographic_background:+ if not required_photo_families:+ issues.add("source_photographic_background_not_found")+ result["photographic_background_matched"] = (+ bool(required_photo_families)+ and matched_photo_families == required_photo_families+ and not photo_mismatch+ )+ if not result["photographic_background_matched"]:+ issues.add("template_photographic_background_missing")++ result["issue_codes"] = sorted(issues)+ result["passed"] = not issues+ result["status"] = "passed" if result["passed"] else "failed"+ return result+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("source_template", type=Path)+ parser.add_argument("generated_presentation", type=Path)+ parser.add_argument("--reference-slide", action="append", default=[], type=int)+ parser.add_argument("--minimum-ratio", type=float)+ parser.add_argument("--require-exact-dimensions", action="store_true")+ parser.add_argument("--require-placeholder-geometry", action="store_true")+ parser.add_argument("--require-photographic-background", action="store_true")+ parser.add_argument("--geometry-tolerance-emu", type=int, default=0)+ args = parser.parse_args(argv)+ try:+ requirements = TemplateFidelityRequirements(+ reference_slide_indices=tuple(args.reference_slide),+ minimum_coverage_ratio=args.minimum_ratio,+ require_exact_dimensions=args.require_exact_dimensions,+ require_placeholder_geometry=args.require_placeholder_geometry,+ require_photographic_background=args.require_photographic_background,+ geometry_tolerance_emu=args.geometry_tolerance_emu,+ )+ result = validate_template_source_fidelity(+ args.source_template, args.generated_presentation, requirements+ )+ except (TemplateGateError, OSError) as exc:+ code = str(exc) if isinstance(exc, TemplateGateError) else "approved_package_unavailable"+ print(+ json.dumps(+ {+ "schema_version": "template_source_fidelity.v1",+ "status": "error",+ "passed": False,+ "issue_codes": [code],+ },+ sort_keys=True,+ )+ )+ return 2+ print(json.dumps(result, sort_keys=True))+ return 0 if result["passed"] else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/paper-fig/domain_guidance/finance.md b/skills/paper-fig/domain_guidance/finance.mdnew file mode 100644index 0000000..5fd3848--- /dev/null+++ b/skills/paper-fig/domain_guidance/finance.md@@ -0,0 +1,12 @@+# Finance presentations++Use for financial reporting, planning, valuation and investment decisions. Other decks do not need this guidance just because they contain numbers. Follow the user's terminology and template.++- State the result, outlook or decision and the evidence supporting it. Make clear which figures are actual results, forecasts or assumptions, and which statements are recommendations. Do not describe a prepared proposal as approved, or an approved plan as completed.+- When making a point with numbers, include the period, what is being compared and the amount needed to understand it. Explain a cause only when the evidence supports it; a target alone does not explain how it will be reached. A factual result does not need an added slogan or recommendation.+- Name the actual result, constraint, risk or action. Preserve precise technical terms and quotations. There is no universal banned-word list.+- Show currency, scale, percentages and multiples correctly. Do not attach currency to counts, years or ratios, or switch between millions and billions just for appearance. Keep positive and negative signs correct. An increase is not necessarily good news.+- Check that totals and numbers in the text agree with the same calculations. Keep assumptions and uncertainty on the slide when they affect a decision; put supporting detail and citations in notes where appropriate.+- Keep subtitles and short annotations only when they add information. Do not describe the process of making the deck, repeat the headline or invent a conclusion to fill space.++For chart labels, workbooks and arithmetic checks, use [editable tables and charts](../references/native_evidence.md). For layout, use [visual design guidance](../style_guidelines.md); for writing, follow [SKILL.md](../SKILL.md#writing).diff --git a/skills/paper-fig/references/cover_art_direction.md b/skills/paper-fig/references/cover_art_direction.mdnew file mode 100644index 0000000..05b9d6b--- /dev/null+++ b/skills/paper-fig/references/cover_art_direction.md@@ -0,0 +1,11 @@+# Cover design++Use this when creating or redesigning a cover. Keep an existing cover unchanged unless the edit requires changing it. A cover counts toward the requested slide total; do not add one if it is unnecessary.++When no supplied design dictates otherwise, keep the title slide minimal and simple; do not cram it with information.++Start with the user's design, audience and available images. A simple title on a solid background, a source photograph or a relevant illustration can all work. Make the main subject clear and the title readable against its background. Design the cover itself; do not use a miniature webpage or slide as the entire design.++Match the reference's layout, including uneven spacing or images surrounded by margins when those are part of the design. Otherwise, give images and text the space they need; no fixed ratio or full-height panel is required. Use original logos and artwork without changing their proportions. Use `cover` cropping only when it will not remove required detail; otherwise fit the whole image inside its frame.++Keep titles and other foreground text editable. Put source credits in notes unless the user, license or audience needs them on the slide. Do not add comments about generating the images or how good the design is. Do not present generated scenes as records of real events or objects.diff --git a/skills/paper-fig/references/finalization.md b/skills/paper-fig/references/finalization.mdnew file mode 100644index 0000000..7cadf8c--- /dev/null+++ b/skills/paper-fig/references/finalization.md@@ -0,0 +1,68 @@+# Validate and deliver++Use when creating or editing a local PPTX. Set runtime paths and fonts before starting, as described in `references/implementation.md` in the installed skill. The finalizer reads a draft file, checks it and writes a separate final file. Keep the source and draft unchanged; use a new filename for the output.++## Declare task requirements++Build `requirements` from the actual request and source deck. Omit options that do not apply:++- `explicitTotalSlideCount`: an ordinary N-slide request means N total. Use `requestedContentSlideCount` only when the user explicitly requests N content slides **plus** one cover. Keep the template's slide count when the user requires it.+- `requiredNativeTableOwnerSlides` and `requiredNativeChartOwnerSlides`: slide numbers that must contain editable tables or charts. Use empty arrays when none are required; slide numbers start at 1. The finalizer still checks every chart in the deck.+- `requiredEmbeddedWorkbookChartOwnerSlides`: use only when the original workbook or its formulas must be kept. See [editable tables and charts](native_evidence.md) for use across applications and cases where the user requires an image instead.+- Template coverage options (`sourceTemplatePath`, `requiredTemplateReferenceSlides`, `minimumTemplateCoverageRatio` and associated flags) apply only when the task requires them. Do not invent a percentage of slides to reuse as proof that you followed the template. Always check the source slide dimensions and compare the source and output visually.+- `tableArithmeticContracts`: sums explicitly required by the task. Row and column numbers start at 0; slide and table numbers start at 1. These are required checks. Automatically inferred totals are diagnostics because labels, units and rounding can be ambiguous.+- `materializeLiteralChartWorkbooks`: defaults to `false`. Set it to `true` only when intentionally creating a new workbook snapshot from complete literal chart data. This can be part of authoring a new chart from the supplied data. For an existing chart, make this an explicit repair decision consistent with the user's request, not an automatic response to a failed check. Never substitute a snapshot when source workbook formulas or lineage must be preserved.++Set `fontPolicy` to describe where the fonts came from: `{basis:"design", families:[...]}` for fonts you chose, `{basis:"user_request", families:[...]}` for fonts the user requested, or `{basis:"reference", families:[...], referencePath, referenceSha256}` for fonts from the PPTX/PDF you must match. The reference must actually use those fonts in its text. Use `scriptFonts` for additional fonts needed by other writing systems. Do not claim the user requested fonts you chose. Omitting the policy imposes no default font requirement; it does not verify font availability or authorize replacing template fonts.++## Check the draft and write the final file++This pattern assumes the builder has defined `presentation`, `PresentationFile`, the absolute runtime/task paths, `requirements`, `fontPolicy`, and `expectedSlideSizeEmu` (`"CX,CY"` from the source for template work, or from the intended new canvas). Create the output directory separately from the private build directory.++```js+import fs from "node:fs/promises";+import path from "node:path";+import { pathToFileURL } from "node:url";++const { finalizePresentation } = await import(pathToFileURL(+ path.join(SKILL_DIR, "container_tools/artifact_tool_utils.mjs"),+).href);+const stagingDir = path.join(workspaceDir, ".codex-finalizer");+await fs.mkdir(stagingDir, { recursive: true });+await fs.mkdir(path.dirname(FINAL_PPTX), { recursive: true });+const candidatePath = path.join(stagingDir, "candidate.pptx");+await (await PresentationFile.exportPptx(presentation)).save(candidatePath);++const tableOwners = requirements.requiredNativeTableOwnerSlides ?? [];+const result = await finalizePresentation({+ ...requirements,+ workspaceDir,+ candidatePath,+ finalPath: FINAL_PPTX,+ pythonExecutable: RUNTIME_PYTHON,+ integrityValidatorPath: path.join(SKILL_DIR, "container_tools/inspect_presentation_package_integrity.py"),+ layoutValidatorPath: path.join(SKILL_DIR, "container_tools/inspect_presentation_layout_geometry.py"),+ layoutArgs: [+ "--expected-slide-size-emu", expectedSlideSizeEmu,+ "--validate-bullet-geometry",+ "--validate-heading-fit",+ ...tableOwners.flatMap(number => ["--require-native-table-slide", String(number)]),+ ],+ requiredNativeTableOwnerSlides: tableOwners,+ fontPolicy,+ verifyArtifactToolImport: true,+ receiptPath: path.join(stagingDir, `${path.basename(FINAL_PPTX)}.validation.json`),+});+```++The finalizer checks the PPTX file structure, declared layout and font requirements, editable chart titles and data, and explicit table arithmetic contracts. It also checks that Artifact Tool can import the file before writing the final output. Workbook snapshot creation requires the explicit option above. A private validation report identifies the final file and records checks and warnings. These checks do not prove the slides look good, the facts are correct or the deck works in PowerPoint or Google Slides.++## Review and repair++Before delivery:++1. Render every final slide.+2. Inspect each slide individually at full size; use a contact sheet only for deck-level flow and consistency. For a small edit, compare changed slides with the originals and scan the whole deck for unintended changes. For template work, compare against the reference, not this skill's design defaults.+3. Fix unintended overlap, clipping, wrapping, broken connectors, unresolved placeholders, inconsistent footers or page markers, and chart/data mismatches. If repairs are needed, update the code that builds the deck, export a new draft and finalize to a new filename.+4. Confirm the deck satisfies the user request and the narrative remains coherent.+5. Verify researched claims and sourced assets are traceable and cite sources when research informed the deck.diff --git a/skills/paper-fig/references/implementation.md b/skills/paper-fig/references/implementation.mdnew file mode 100644index 0000000..771e135--- /dev/null+++ b/skills/paper-fig/references/implementation.md@@ -0,0 +1,27 @@+# Local presentation implementation++Read before creating or editing a local PPTX. Do not modify this skill's files while making a deck.+++## Runtime and paths++Call `load_workspace_dependencies`. Use its Node.js executable, Node.js packages, override binaries and Python executable as `RUNTIME_NODE`, `RUNTIME_NODE_MODULES`, `RUNTIME_BIN_DIR` and `RUNTIME_PYTHON`. Do not install substitutes or modify the bundled dependencies.++Set `SKILL_DIR` to this skill's absolute directory, `workspaceDir` to the task directory, `TMP_DIR` to a private build subdirectory, and `FINAL_PPTX` to a new file in a separate output subdirectory. Create both directories before export. For bare imports in authored `.mjs` files, link `node_modules` inside the build directory to `RUNTIME_NODE_MODULES`. Run modules with `RUNTIME_NODE`; plain `.mjs` files cannot contain TypeScript annotations or JSX syntax.++The finalizer checks the draft and writes the final PPTX. Both files must be inside `workspaceDir`. It will not overwrite an existing output, and its validation report must stay outside the output directory. Use a new output filename for each revision. If the user requests another destination you have permission to write to, validate locally first, then copy the file there unchanged. Never overwrite the source unless explicitly requested.++- Immediately before the first create/edit authoring command, run `mark_artifact_operation_started.mjs` successfully exactly once using the command below. Do not run it for read-only work. For edits, replace `create` with `edit`; adjust the expected count and output format to match the requested outputs. Run from the skill directory as a standalone command, without shell-variable expansion.+ ```bash+ node container_tools/mark_artifact_operation_started.mjs --operation-kind create --expected-output-count 1 --output-format pptx+ ```++## Typography and geometry++Keep template fonts and slide dimensions. Otherwise choose suitable available fonts and a 16:9 slide size. `resolvePresentationFont()` uses fonts discovered in the supplied runtime; pass `fontFamily` for an explicit choice or `availableFonts` for an independently verified list. It does not assume a fallback font is installed. Before creating the deck, list the fonts in the finalization font policy: `reference` for fonts from a PPTX/PDF reference, `user_request` for fonts the user named, or `design` for fonts you chose. Without a policy, the finalizer imposes no default font requirement.++Set fonts for shape and table text, and separately for chart titles, axes, legends and data labels. `applyPresentationChartFont(chart, {fontFamily})` sets chart defaults without adding a title. Keep intended font pairings and any additional fonts needed for other writing systems.++Geometry and numeric `fontSize` use CSS pixels at 96 DPI; `fontSizePt` uses points. Structured run sizes accept strings such as `"20pt"`. Native paragraph indentation is a documented exception: follow `references/native_bullets.md` in the installed skill. Do not copy small raw indentation numbers from older examples.++Use `artifact_tool_docs/API_QUICK_START.md` for runnable JavaScript and `artifact_tool_docs/api/API_DOCS.md` for the objects you need. These paths are relative to the installed skill. Put source citations in the relevant slide's speaker notes. Export a draft in the private build directory, then follow `references/finalization.md` for validation and delivery.diff --git a/skills/paper-fig/references/native_bullets.md b/skills/paper-fig/references/native_bullets.mdnew file mode 100644index 0000000..331701c--- /dev/null+++ b/skills/paper-fig/references/native_bullets.md@@ -0,0 +1,23 @@+# Editable bullet lists++Keep the template's paragraph and numbering settings. For new plain-text lists, use `makeNativeBulletParagraphs` from `container_tools/artifact_tool_utils.mjs`:++```js+shape.text = makeNativeBulletParagraphs(sourceItems, {+ marginLeftPoints: 18,+ hangingPoints: 9,+ spaceAfterPoints: 8,+});+shape.text.style = {+ typeface: selectedFamily,+ fontSize: 28, // CSS pixels, not points+ color: "#142735",+ autoFit: "none",+};+```++Choose spacing to suit the font and layout; these values are examples, not a required style. Set text styles separately. Use structured text runs for bold phrases or links so their formatting and link targets are preserved.++The paragraph-object API in the verified Artifact Tool 2.8.43 and 2.8.51 runtimes writes `marginLeft`/`indent` as EMU (12,700 per point), and `spaceBefore`/`spaceAfter` as hundredths of a point. For rich or numbered paragraphs, apply the same conversions. This differs from shape-level pixel geometry. Recheck serialization if the runtime changes; do not double-convert imported paragraphs.++Check exported `a:pPr@marL`, negative hanging `indent`, `a:buChar` or `a:buAutoNum`, and paragraph spacing. Run the bullet-geometry check and inspect items that wrap onto another line. Wrapped lines should align with the text above them, not with the bullet. Leave a clear gap between bullet and text. Do not imitate lists with repeated spaces, typed bullet characters or extra text boxes. The number of bullets alone does not make a slide poorly designed.diff --git a/skills/paper-fig/references/native_evidence.md b/skills/paper-fig/references/native_evidence.mdnew file mode 100644index 0000000..cf8d78c--- /dev/null+++ b/skills/paper-fig/references/native_evidence.md@@ -0,0 +1,19 @@+# Editable tables and charts++Build required tables, data charts and editable diagrams as slide objects, not screenshots. Keep a supplied image unchanged when the user explicitly asks to use that image. Do not turn every short list into a table.++## Tables++Keep required rows, columns, periods and headers on the relevant slides. Calculate each total once and reuse it in tables, titles and notes. Set column widths, row heights and padding from the actual text; preserve template alignment. Use the [table API](../artifact_tool_docs/api/references/tables.spec.md).++The arithmetic checker checks declared simple sums with displayed-rounding tolerance and reports automatically inferred totals as diagnostics. It is not proof of exact arithmetic or full support for localized numbers. Manually check ratios, subtotals and tables with different units when the checker skips them. Also compare source data and numbers in the slide text with the calculations; passing the checker does not verify those.++## Charts++Keep categories, data series, units, dates, positive/negative signs and precision. Choose a chart that answers the audience's question. Set axis and label formats explicitly; spreadsheet formatting may not carry over. To display 31% with a percentage format, use `0.31`, not `31`.++Use the chart's own labels instead of separate text boxes. Do not duplicate labels or titles, and remove the placeholder “Chart Title.” Keep labels and annotations the audience needs or the user requested. For stacked bar/column charts, use `inEnd` or `center`, not `outEnd`. If an invisible data series positions the visible bars, hide its outlines and labels too. If bar positioning requires positive magnitudes, keep the original positive/negative signs in the data shown to the audience. If the API cannot place a label as required, explain the limitation. See the [chart API](../artifact_tool_docs/api/references/charts.spec.md).++The finalizer finds editable charts and checks supported cell-range references against the corresponding workbook cells, including category and value order. Unsupported or broken references cannot be reported as verified. To support use across applications, explicitly set `materializeLiteralChartWorkbooks: true` when a new workbook snapshot from complete literal chart data is appropriate for the task. This preserves values, not the original workbook's formulas or links to source data. It is off by default. Keep original workbooks when required; never invent formulas or data. Use `nativeChartTargetApplication: "powerpoint"` only when the requested output is explicitly for PowerPoint alone; this does not excuse broken workbook references.++Inspect the rendered slides: check that labels identify the right data, signs and units are correct, and text is readable. If you can open the deck in its target application, edit and resize representative charts in a test copy, then save and reopen it. Record unavailable application tests without implying that previews verify application behavior. Follow the handoff rules in [SKILL.md](../SKILL.md) for what to report. A chart working in PowerPoint does not prove it works in Google Slides.diff --git a/skills/paper-fig/references/preview_prompt.md b/skills/paper-fig/references/preview_prompt.mdnew file mode 100644index 0000000..6b0bfe0--- /dev/null+++ b/skills/paper-fig/references/preview_prompt.md@@ -0,0 +1,48 @@+# Write the full-page drawing prompt++Read this before generating a new full-page preview. Write a complete prompt that an image model can draw directly, rather than a summary of the research. The preview establishes the composition and the visual assets for subsequent faithful PPTX reconstruction. If the user supplies a reference to reconstruct directly, skip preview generation and preserve that design.++## Describe the drawing from the whole page to each region++Start with the figure's subject and visual medium, then specify the canvas dimensions or aspect ratio, background, typography, palette, border and arrow styles, and intended visual density. Follow the user's design directions; do not turn example fonts, ratios, or colors into fixed defaults.++State the overall layout before describing details: rows or columns, approximate relative widths and heights, panel positions, main reading direction, and alignment. Assign enough space to both the scientific structure and its images. Describe balanced use of the available area and useful spacing, rather than simply asking for a "clean" or "publication-quality" figure.++For each region, use a spatial heading such as TOP ROW, LEFT PANEL, or RIGHT DETAIL. Describe what appears there and how it is arranged: exact title and labels, module order, images, grouping, and arrows. Write relationships explicitly, including the source and destination of branches, feedback loops, and cross-panel connections. Distinguish data flow from callouts or visual explanations. Use quoted text and equations where needed; text, formulas, arrows, and diagrams are all welcome in the preview.++## Plan the image assets explicitly++For newly designed previews, include meaningful image assets by default unless the user asks for a text-only, purely schematic, or other image-free design. A supplied reference also determines whether imagery belongs in the figure. Do not silently reduce an image-rich method into boxes and labels, or add unrelated decoration just to occupy space.++Specify each image where it belongs in the layout: its subject and action, scene or background, number of instances or sequence frames, viewpoint, crop or aspect ratio, relative size, and medium. Relevant assets may include photographic input/output examples, experimental scenes, isolated objects, softly shaded 3D models, or a short sequence of manipulation poses. Describe the actual visual content, rather than writing only "add an image" or "robot illustration".++For repeated subjects or successive states, say what stays the same and what changes. Keep subject identity, scene, viewpoint, object scale, lighting, and material treatment consistent when the method requires it. Allocate visible room for the images, not tiny placeholders. These same descriptions can later guide high-resolution asset generation or cropping from the preview.++Use user-supplied evidence for measured results, experimental images, data plots, and comparisons. Generated illustrative examples must not be presented as real experimental evidence. Preserve the supplied scientific modules and connections; do not invent methods or findings to complete the composition.++## Produce one ready-to-use prompt++Use direct drawing instructions such as "Place...", "Arrange...", "Show...", and "Connect...". Replace vague adjectives with specific visual choices. Keep the prompt as long as the figure requires, without adding an entire example case or a second planning report. English is useful when appropriate for the selected image tool; preserve the user's label language and exact wording.++A compact structure is:++```text+Create [figure subject and visual medium]. Use [canvas, background,+typography, palette, outlines, arrows, and density].++LAYOUT+[Major regions, proportions, reading direction, and alignment.]++[REGION POSITION — TITLE]+[Place and arrange the scientific modules, quoted labels, and image assets.+Describe asset subjects, counts, views, sizes, and repeated-state consistency.+Specify the arrows, branches, groups, and connections to other regions.]++[Repeat only for the regions this figure needs.]++VISUAL CONSISTENCY+[Color meanings, shared typography and imagery treatment, readable labels,+balanced spacing, full visibility, and scientific relationships to preserve.]+```++Replace every bracket with the actual figure specification. Save the finished prompt as `work/preview-prompt.md` in the task workspace (use a figure-specific filename for multiple figures), then submit that prompt with any relevant reference images to the image-generation tool. The file is the drawing prompt itself, not an approval form. Continue into the existing preview refinement and reconstruction steps without adding a mandatory pause.diff --git a/skills/paper-fig/references/template-elicitation.md b/skills/paper-fig/references/template-elicitation.mdnew file mode 100644index 0000000..3841c48--- /dev/null+++ b/skills/paper-fig/references/template-elicitation.md@@ -0,0 +1,9 @@+# Artifact Template Selection++Open the template selection picker for creating new presentations when the user has not provided a template, reference, or visual direction. Also open the picker when the user asks to browse or upload templates. Do not open it if the user declines templates, requests a connected-source design search, or if `list_artifact_templates` is unavailable this turn. Subject matter, audience, tone, company names, and source files do not by themselves specify a template or visual direction.++Call `list_artifact_templates({artifactKind, request})` with `artifactKind: "presentation"`, or `"google-slides"` for Google Slides requests. Include compatible Office and Google templates without changing the requested output format.++Rank templates by relevance, breaking ties in favor of personal or shared templates. Include a mix of styles. Pass their `skillName` values unchanged to `choose_artifact_template({artifactKind, request, templates})` and call it once. Set `includeAllTemplates: true` only when the user requests the full catalog. The picker displays at most ten templates.++Follow the selected template or uploaded reference. Save an uploaded reference only when `saveForFutureUse` is true. Use Template Creator with the returned `displayName`. Continue without a template if the picker is declined, cancelled, unavailable, or fails. Do not replace the picker with `request_user_input` or a chat list. Browsing templates does not authorize artifact creation.diff --git a/skills/paper-fig/references/template_following.md b/skills/paper-fig/references/template_following.mdnew file mode 100644index 0000000..4cbd7a3--- /dev/null+++ b/skills/paper-fig/references/template_following.md@@ -0,0 +1,23 @@+# Follow the user's template or design++Read this when editing an existing deck or matching a supplied design.++## Determine how to use the supplied deck++Determine whether the user wants to edit the deck, match its design, use it for inspiration or take content from it. Follow its design when asked to match it or use it as a template. If the user supplies a deck only as a source of text, data or images, do not assume they want you to copy its design.++## Inspect before changing++Render the source slides relevant to the task. Check slide dimensions, layouts, title and body positions, fonts, colors, logos, image crops and repeated elements such as footers. When adapting a whole deck, inspect every source slide before choosing layouts. Use the actual reference; do not rely on memory or assume a 16:9 slide size.++For PPTX, read the API references for [imported decks](../artifact_tool_docs/api/references/cookbook/imported-deck.md), [masters](../artifact_tool_docs/api/references/master.spec.md), [layouts](../artifact_tool_docs/api/references/layout.spec.md) and [inspection](../artifact_tool_docs/api/references/inspect.md). Use `presentation.inspect({kind:"layout"})`, `presentation.masters.items` and placeholder summaries to see which elements and styles come from shared masters and layouts.++## Reuse the structure++Work on a copy. Import and reuse or duplicate source slides, fill existing placeholders, and edit existing elements in place. Keep dimensions, masters, layouts, theme, fonts, spacing, image styles and repeated elements unless the task calls for changes. Edit individual slides when possible. Change a shared master or layout only when the change should apply to all slides that use it.++Fit new content into the existing layout instead of covering it with a new design. Remove unused placeholders, but keep required template elements. If the slide count is fixed, fit the content without adding slides. A PDF or image reference may need to be rebuilt as editable objects. Match its appearance and explain any differences that affect the result; do not claim its underlying structure is identical.++## Verify the match++After export, compare changed slides with the originals side by side. Include every slide that uses a master or layout you changed. Check appearance and editability. A successful import or render does not prove the template was preserved. If the tool loses required elements or styles, investigate and try to restore them. Ask about an alternative only if the loss prevents the requested result.diff --git a/skills/paper-fig/routing/google_slides.md b/skills/paper-fig/routing/google_slides.mdnew file mode 100644index 0000000..7878807--- /dev/null+++ b/skills/paper-fig/routing/google_slides.md@@ -0,0 +1,15 @@+# Google Slides++## Existing decks++Use the Google Drive plugin's Google Slides skill to inspect and edit an existing Google Slides deck. Do not export it to PowerPoint and import it back unless requested.++## New decks++Create and check a local PPTX with this skill, then convert it to an editable Google Slides deck with the Google Drive plugin's presentation import action using `upload_mode: "native_google_slides"`. Keep the user's requested output format. Use a different creation method only when requested.++Find the available import action and read its parameters before calling it. If Google Drive or import is unavailable, explain what is missing and ask about an alternative. Do not substitute a local file without asking.++After import, use the Google Slides skill's inspection and preview tools to check the slide count, design, text, images, and required tables and charts. Fix problems caused by conversion where the tools allow it. If you cannot inspect the deck, say it has not been checked in Google Slides. A successful upload does not prove the design or editability was preserved.++Return the Google Slides link. Include the local PPTX only if requested or agreed as an alternative.diff --git a/skills/paper-fig/style_guidelines.md b/skills/paper-fig/style_guidelines.mdnew file mode 100644index 0000000..07c2da4--- /dev/null+++ b/skills/paper-fig/style_guidelines.md@@ -0,0 +1,20 @@+# Visual design++Use this guidance when creating or changing slide layouts. Follow the user’s template and design instructions first.++## Design for the content++Keep the template's fonts, colors, spacing, images and repeated elements. When the user has not specified a design, choose consistent styles and layouts that suit the content. Use bullets, rows of text, diagrams, tables or columns as needed; no single layout is required.++Use editable tables for data arranged in rows and columns, and charts to show relationships in data. Align related items, place labels near what they describe and keep connecting lines clear of text. Use emphasis to draw attention to important information. Follow the default-styling rules in [SKILL.md's Important instructions](SKILL.md#important-instructions). Only use UI-like elements when the user explicitly requests them or when matching a supplied template requires them; otherwise use a flat slide composition rather than repeated UI panels.++Make text readable at the size the audience will see it. Use one font familywith sizes and weights that distinguish headings from body text. Use available fonts that contain all required characters. Match reference fonts where specified instead of replacing them with defaults. Check line wrapping, padding inside text boxes and the space bold text needs. Before shrinking crowded text, try clearer wording or a better arrangement without dropping required evidence.++Use images that accurately represent the subject. By default, do not reuse the same image more than once, except for backgrounds. Preserve repetition explicitly required by the user or a supplied template. Crop decorative images to fit the layout, but do not crop away evidence or distort logos. Do not present generated illustrations as photos of real events or images of real objects.++Use diagrams when they help explain or reinforce the narrative of the slide. If using arrows, orient shapes such that you can avoid diagonal or curved connections.++Use the fewest distinct text groups the content needs. It is unacceptable to clutter slides with unnecessary kickers, section labels, and footer fragments. e.g. instead of a textbox that says "The supplement requires separate authority", "FY2027 inflation sensitivity: 2% gives $3578m, 4% gives $364.2," on one line, then "02 FY2027 Planning Estimate" and "Reporting through 2025" in opposite corners of the footer, just have ONE footnote saying "2% inflation rate assumption in FY2027 drives up operating cost to $357.8M and 4% inflation rate yields $364.2M. Note reporting is through 2025 and actual budget approval requires separate approval from leadership." Kill any extraneous elements that are obvious from the deck context++## Visual review+Review the slide order and the balance of dense and simple slides. Then inspect each slide at a consistent readable size. Check that required content is present, the main point is easy to find, text is readable, and images, labels and other objects fit without unintended overlap. For template work, compare source and output side by side. Keep the original style when the user asked to preserve it.diff --git a/skills/paper-fig/template_following_scripts/check_template_fidelity.mjs b/skills/paper-fig/template_following_scripts/check_template_fidelity.mjsnew file mode 100644index 0000000..bd355a7--- /dev/null+++ b/skills/paper-fig/template_following_scripts/check_template_fidelity.mjs@@ -0,0 +1,502 @@+#!/usr/bin/env node++import fs from "node:fs/promises";+import path from "node:path";+import { spawnSync } from "node:child_process";+import { parseArgs as parseNodeArgs } from "node:util";+import { fileURLToPath } from "node:url";++const DEFAULT_SLIDE_SIZE = { width: 1280, height: 720 };++function parseArgs(argv) {+ return parseNodeArgs({+ args: argv,+ options: {+ help: { type: "boolean" },+ workspace: { type: "string" },+ "final-pptx": { type: "string" },+ map: { type: "string" },+ "starter-pptx": { type: "string" },+ "starter-layout-dir": { type: "string" },+ "final-layout-dir": { type: "string" },+ "edit-dir": { type: "string" },+ "agent-log": { type: "string" },+ "no-report": { type: "boolean" },+ },+ allowPositionals: false,+ strict: true,+ }).values;+}++function requireArg(args, key) {+ const value = args[key];+ if (typeof value !== "string" || value.length === 0) throw new Error(`Missing required --${key}`);+ return value;+}++const PLACEHOLDER_PATTERNS = [+ /^slide number$/i,+ /^date$/i,+ /^footer$/i,+ /^click to add (title|subtitle|text)$/i,+ /^(title|subtitle|name|text|body) goes here$/i,+ /^lorem ipsum\b/i,+ /\btemplate instruction\b/i,+];+const SCAN_EXTENSIONS = new Set([".mjs", ".js", ".cjs", ".ts", ".py", ".sh", ".txt", ".md", ".jsonl"]);+const SKIP_SCAN_DIRS = new Set([+ ".git",+ "node_modules",+ "assets",+ "preview",+ "template-starter-preview",+ "template-inspect",+ "template-starter-layout",+ "layout",+ "qa",+ "output",+]);++function usage() {+ return [+ "Usage:",+ " $RUNTIME_NODE template_following_scripts/check_template_fidelity.mjs --workspace <dir> --final-pptx <deck.pptx> [options]",+ "",+ "Options:",+ " --map <path> template-frame-map.json.",+ " --starter-pptx <path> Starter PPTX path for report provenance.",+ " --starter-layout-dir <dir> Starter layout JSON directory.",+ " --final-layout-dir <dir> Final layout JSON directory.",+ " --edit-dir <dir> Scripts/logs directory to scan. Defaults to <workspace>.",+ " --agent-log <path> Additional child-agent log to scan.",+ " --no-report Validate without writing qa/template-fidelity-check.*.",+ "",+ "Checks final template-following decks for overlays, unresolved placeholders,",+ "fresh-slide rebuilds, and deck-affecting Python/OOXML bypasses.",+ ].join("\n");+}++function issue(severity, id, message, context = {}) {+ return { severity, id, message, ...context };+}++async function exists(filePath) {+ return fs+ .stat(filePath)+ .then((stat) => stat.isFile() || stat.isDirectory())+ .catch(() => false);+}++async function writeJson(filePath, value) {+ await fs.mkdir(path.dirname(filePath), { recursive: true });+ await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");+}++function runCapture(command, args, options = {}) {+ const result = spawnSync(command, args, {+ encoding: options.encoding,+ maxBuffer: options.maxBuffer || 80 * 1024 * 1024,+ });+ if (result.status !== 0) return undefined;+ return result.stdout;+}++function zipNames(pptxPath) {+ const output = runCapture("unzip", ["-Z1", pptxPath], { encoding: "utf8" });+ if (!output) return [];+ return String(output)+ .split(/\r?\n/)+ .filter(Boolean);+}++function readZipText(pptxPath, entryName) {+ const output = runCapture("unzip", ["-p", pptxPath, entryName]);+ return output ? Buffer.from(output).toString("utf8") : "";+}++function decodeXmlText(value) {+ return String(value)+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .trim();+}++function decodeXmlAttr(value) {+ return decodeXmlText(value || "");+}++function placeholderLike(text) {+ return PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(text.trim()));+}++function xmlAttr(xml, attrName) {+ const match = xml.match(new RegExp(`\\b${attrName}="([^"]*)"`, "i"));+ return match ? decodeXmlAttr(match[1]) : undefined;+}++function shapeBlocks(xml) {+ return [...xml.matchAll(/<p:sp\b[\s\S]*?<\/p:sp>/g)].map((match) => match[0]);+}++function textRuns(block) {+ return [...block.matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((match) => decodeXmlText(match[1]));+}++function structuralPlaceholderContext(block) {+ const placeholderTag = block.match(/<p:ph\b([^>]*)\/?>/);+ if (!placeholderTag) return undefined;+ const cNvPrTag = block.match(/<p:cNvPr\b[^>]*>/)?.[0] || "";+ return {+ shapeId: xmlAttr(cNvPrTag, "id"),+ name: xmlAttr(cNvPrTag, "name"),+ placeholderType: xmlAttr(placeholderTag[0], "type"),+ placeholderIdx: xmlAttr(placeholderTag[0], "idx"),+ };+}++async function walkFiles(root, options = {}) {+ const files = [];+ const resolvedRoot = path.resolve(root);+ async function visit(current) {+ const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ const entryPath = path.join(current, entry.name);+ if (entry.isDirectory()) {+ if (!options.includeSkippedDirs && SKIP_SCAN_DIRS.has(entry.name)) continue;+ await visit(entryPath);+ } else if (!options.extensions || options.extensions.has(path.extname(entry.name))) {+ files.push(entryPath);+ }+ }+ }+ if (await exists(resolvedRoot)) await visit(resolvedRoot);+ return files;+}++async function scanAuthoringFiles(editDir, agentLog) {+ const issues = [];+ const files = await walkFiles(editDir, { extensions: SCAN_EXTENSIONS });+ if (agentLog && (await exists(agentLog))) files.push(path.resolve(agentLog));++ let combined = "";+ for (const file of [...new Set(files)]) {+ const ext = path.extname(file);+ const text = await fs.readFile(file, "utf8").catch(() => "");+ if (!text) continue;+ combined += `\n/* ${file} */\n${text}`;++ if (ext === ".py" && /\b(from\s+pptx\s+import|import\s+pptx|Presentation\s*\()/m.test(text)) {+ issues.push(issue("fail", "deck-affecting-python", "Python script appears to use python-pptx.", { file }));+ }+ if (ext === ".py" && /\.save\s*\([^)]*\.pptx/i.test(text)) {+ issues.push(issue("fail", "deck-affecting-python", "Python script appears to save a PPTX.", { file }));+ }+ if (/\bzipfile\b|\bZipFile\b/.test(text) && /\b(write|writestr|append|ppt\/slides\/|_rels\/|\[Content_Types\]\.xml)/.test(text)) {+ issues.push(issue("fail", "direct-ooxml-mutation", "Script/log suggests direct OOXML package mutation.", { file }));+ }+ if (/\bsoffice\b[\s\S]{0,120}--convert-to[\s\S]{0,80}pptx/i.test(text)) {+ issues.push(issue("fail", "libreoffice-pptx-mutation", "Script/log suggests LibreOffice PPTX mutation.", { file }));+ }+ if (/\bPresentation\.create\s*\(/.test(text)) {+ issues.push(issue("fail", "fresh-slide-rebuild", "Template-following final authoring must not create a fresh presentation.", { file }));+ }+ if (/presentation\.slides\.add\s*\(/.test(text)) {+ issues.push(issue("fail", "fresh-slide-rebuild", "Template-following final authoring must not add fresh slides.", { file }));+ }+ }++ if (!/PresentationFile\.importPptx\s*\(/.test(combined) || !/(template-starter\.pptx|starterPptx|starterPptxPath)/.test(combined)) {+ issues.push(+ issue(+ "fail",+ "missing-starter-import-evidence",+ "Could not find evidence that final authoring imports template-starter.pptx with PresentationFile.importPptx.",+ ),+ );+ }+ if (!/PresentationFile\.exportPptx\s*\(/.test(combined)) {+ issues.push(+ issue("fail", "missing-artifact-export-evidence", "Could not find evidence that final authoring exports with PresentationFile.exportPptx."),+ );+ }+ return issues;+}++function flattenObjects(value, out = []) {+ if (!value || typeof value !== "object") return out;+ const text = String(value.textPreview ?? value.text ?? value.plainText ?? value.rawText ?? value.value ?? "").trim();+ const box = bboxOf(value);+ if (box || text || value.type || value.kind) out.push({ ...value, __text: text, __bbox: box });+ for (const child of Object.values(value)) {+ if (Array.isArray(child)) {+ for (const item of child) flattenObjects(item, out);+ } else if (child && typeof child === "object") {+ flattenObjects(child, out);+ }+ }+ return out;+}++function bboxOf(value) {+ const raw = value?.bbox || value?.bounds || value?.box;+ if (Array.isArray(raw) && raw.length === 4) {+ const [x, y, w, h] = raw.map(Number);+ if ([x, y, w, h].every(Number.isFinite)) return { x, y, w, h, x2: x + w, y2: y + h };+ }+ const x = Number(value?.left ?? value?.x);+ const y = Number(value?.top ?? value?.y);+ const w = Number(value?.width ?? value?.w);+ const h = Number(value?.height ?? value?.h);+ if ([x, y, w, h].every(Number.isFinite)) return { x, y, w, h, x2: x + w, y2: y + h };+ return undefined;+}++function area(box) {+ return Math.max(0, box?.w || 0) * Math.max(0, box?.h || 0);+}++function intersection(a, b) {+ const x = Math.max(a.x, b.x);+ const y = Math.max(a.y, b.y);+ const x2 = Math.min(a.x2, b.x2);+ const y2 = Math.min(a.y2, b.y2);+ return { x, y, w: Math.max(0, x2 - x), h: Math.max(0, y2 - y), x2, y2 };+}++function centerInside(outer, inner) {+ const cx = inner.x + inner.w / 2;+ const cy = inner.y + inner.h / 2;+ return cx >= outer.x && cx <= outer.x2 && cy >= outer.y && cy <= outer.y2;+}++function fillValue(value) {+ return String(value.fillColor ?? value.fill ?? value.backgroundColor ?? value.color ?? "").toLowerCase();+}++function isTransparent(fill) {+ return !fill || fill === "none" || fill === "transparent" || fill.includes("rgba(0, 0, 0, 0)") || fill.includes("opacity:0");+}++function isLikelyOpaquePanel(element, slideArea) {+ const box = element.__bbox;+ if (!box) return false;+ if (area(box) < slideArea * 0.02) return false;+ if (element.__text) return false;+ const type = String(element.type ?? element.kind ?? element.shapeType ?? "").toLowerCase();+ const fill = fillValue(element);+ return (type.includes("shape") || type.includes("rect") || fill) && !isTransparent(fill);+}++function isContentElement(element) {+ const type = String(element.type ?? element.kind ?? "").toLowerCase();+ return Boolean(element.__bbox) && (Boolean(element.__text) || /image|table|chart|text/.test(type));+}++function layoutSlideNumber(filePath) {+ const match = path.basename(filePath).match(/(\d+)/);+ return match ? Number.parseInt(match[1], 10) : undefined;+}++async function readLayouts(layoutDir) {+ if (!layoutDir || !(await exists(layoutDir))) return new Map();+ const files = (await walkFiles(layoutDir, { includeSkippedDirs: true })).filter((file) => file.endsWith(".json"));+ const layouts = new Map();+ for (const file of files) {+ const slide = layoutSlideNumber(file);+ if (!Number.isInteger(slide)) continue;+ const json = JSON.parse(await fs.readFile(file, "utf8"));+ layouts.set(slide, { file, json, elements: flattenObjects(json) });+ }+ return layouts;+}++function bestIoU(box, candidates) {+ let best = 0;+ for (const candidate of candidates) {+ const other = candidate.__bbox;+ if (!other) continue;+ const interArea = area(intersection(box, other));+ const union = area(box) + area(other) - interArea;+ if (union > 0) best = Math.max(best, interArea / union);+ }+ return best;+}++async function scanFinalLayouts(finalLayoutDir) {+ const issues = [];+ const layouts = await readLayouts(finalLayoutDir);+ for (const [slide, layout] of layouts) {+ for (const element of layout.elements) {+ const text = element.__text;+ if (text && placeholderLike(text)) {+ issues.push(+ issue("fail", "unresolved-placeholder", `Placeholder text remains in final layout: "${text}".`, {+ slide,+ file: layout.file,+ }),+ );+ }+ }+ }+ return { issues, layouts };+}++async function scanPptxPlaceholders(finalPptx) {+ const issues = [];+ for (const entry of zipNames(finalPptx).filter((name) => /^ppt\/slides\/slide\d+\.xml$/.test(name))) {+ const xml = readZipText(finalPptx, entry);+ const slide = Number(entry.match(/slide(\d+)\.xml$/)?.[1]);+ for (const block of shapeBlocks(xml)) {+ const placeholder = structuralPlaceholderContext(block);+ if (!placeholder) continue;+ if (textRuns(block).join("").trim()) continue;+ issues.push(+ issue("fail", "empty-structural-placeholder", "Empty structural PowerPoint placeholder remains in final PPTX XML.", {+ slide,+ entry,+ ...placeholder,+ }),+ );+ }+ for (const match of xml.matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)) {+ const text = decodeXmlText(match[1]);+ if (text && placeholderLike(text)) {+ issues.push(issue("fail", "unresolved-placeholder", `Placeholder text remains in final PPTX XML: "${text}".`, { slide, entry }));+ }+ }+ }+ return issues;+}++async function scanOverlays(starterLayoutDir, finalLayoutDir) {+ const issues = [];+ const starterLayouts = await readLayouts(starterLayoutDir);+ const finalLayouts = await readLayouts(finalLayoutDir);+ const slideArea = DEFAULT_SLIDE_SIZE.width * DEFAULT_SLIDE_SIZE.height;+ for (const [slide, finalLayout] of finalLayouts) {+ const starterLayout = starterLayouts.get(slide);+ if (!starterLayout) continue;+ const starterContent = starterLayout.elements.filter(isContentElement);+ const starterAll = starterLayout.elements.filter((element) => element.__bbox);+ for (const element of finalLayout.elements) {+ const box = element.__bbox;+ if (!isLikelyOpaquePanel(element, slideArea)) continue;+ if (bestIoU(box, starterAll) > 0.92) continue;+ for (const inherited of starterContent) {+ const inheritedBox = inherited.__bbox;+ if (!inheritedBox) continue;+ const overlap = area(intersection(box, inheritedBox));+ if (overlap > area(inheritedBox) * 0.35 || centerInside(box, inheritedBox)) {+ issues.push(+ issue("fail", "mask-cover-overlay", "Large new opaque shape appears to cover inherited template content.", {+ slide,+ finalLayout: finalLayout.file,+ starterLayout: starterLayout.file,+ inheritedText: inherited.__text || undefined,+ }),+ );+ break;+ }+ }+ }+ }+ return issues;+}++export async function checkTemplateFidelity(options) {+ const workspace = path.resolve(options.workspace);+ const finalPptx = path.resolve(options.finalPptx);+ const editDir = path.resolve(options.editDir || workspace);+ const starterLayoutDir = options.starterLayoutDir ? path.resolve(options.starterLayoutDir) : undefined;+ const finalLayoutDir = options.finalLayoutDir ? path.resolve(options.finalLayoutDir) : undefined;+ const writeReport = options.writeReport !== false;+ const issues = [];++ if (!(await exists(finalPptx))) {+ issues.push(issue("fail", "missing-final-pptx", `Missing final PPTX: ${finalPptx}`));+ }+ issues.push(...(await scanAuthoringFiles(editDir, options.agentLog)));++ if (finalLayoutDir) {+ const layoutScan = await scanFinalLayouts(finalLayoutDir);+ issues.push(...layoutScan.issues);+ }+ if (await exists(finalPptx)) {+ issues.push(...(await scanPptxPlaceholders(finalPptx)));+ }+ if (starterLayoutDir && finalLayoutDir) {+ issues.push(...(await scanOverlays(starterLayoutDir, finalLayoutDir)));+ }++ const status = issues.some((item) => item.severity === "fail")+ ? "fail"+ : issues.length > 0+ ? "warning"+ : "pass";+ const report = {+ status,+ checkedAt: new Date().toISOString(),+ workspace,+ finalPptx,+ starterPptx: options.starterPptx ? path.resolve(options.starterPptx) : undefined,+ mapPath: options.mapPath ? path.resolve(options.mapPath) : undefined,+ starterLayoutDir,+ finalLayoutDir,+ editDir,+ issueCount: issues.length,+ issues,+ };++ if (writeReport) {+ const qaDir = path.join(workspace, "qa");+ await fs.mkdir(qaDir, { recursive: true });+ await writeJson(path.join(qaDir, "template-fidelity-check.json"), report);+ await fs.writeFile(+ path.join(qaDir, "template-fidelity-check.txt"),+ [+ `Template fidelity check: ${status}`,+ ...issues.map((item) =>+ `${item.severity.toUpperCase()} ${item.id}: ${item.message}` ++ (item.slide ? ` slide=${item.slide}` : "") ++ (item.file ? ` file=${item.file}` : ""),+ ),+ "",+ ].join("\n"),+ "utf8",+ );+ }++ return report;+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(usage());+ return;+ }+ const report = await checkTemplateFidelity({+ workspace: requireArg(args, "workspace"),+ finalPptx: requireArg(args, "final-pptx"),+ starterPptx: args["starter-pptx"],+ mapPath: args.map,+ starterLayoutDir: args["starter-layout-dir"],+ finalLayoutDir: args["final-layout-dir"],+ editDir: args["edit-dir"],+ agentLog: args["agent-log"],+ writeReport: !args["no-report"],+ });+ console.log(JSON.stringify(report, null, 2));+ if (report.status === "fail") process.exit(1);+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ main().catch((error) => {+ console.error(error.stack || error.message || String(error));+ console.error(usage());+ process.exit(1);+ });+}diff --git a/skills/paper-fig/template_following_scripts/inspect_template_deck.mjs b/skills/paper-fig/template_following_scripts/inspect_template_deck.mjsnew file mode 100644index 0000000..b1afb20--- /dev/null+++ b/skills/paper-fig/template_following_scripts/inspect_template_deck.mjs@@ -0,0 +1,244 @@+#!/usr/bin/env node++import fs from "node:fs/promises";+import path from "node:path";+import { spawnSync } from "node:child_process";+import { parseArgs as parseNodeArgs } from "node:util";++import { importRuntimeModule } from "../container_tools/runtime_helpers.mjs";++function parseArgs(argv) {+ return parseNodeArgs({+ args: argv,+ options: {+ help: { type: "boolean" },+ workspace: { type: "string" },+ pptx: { type: "string" },+ "out-dir": { type: "string" },+ scale: { type: "string" },+ },+ allowPositionals: false,+ strict: true,+ }).values;+}++function requireArg(args, key) {+ const value = args[key];+ if (typeof value !== "string" || value.length === 0) throw new Error(`Missing required --${key}`);+ return value;+}++async function saveBlobToFile(blob, outputPath) {+ await fs.mkdir(path.dirname(outputPath), { recursive: true });+ if (blob && typeof blob.arrayBuffer === "function") {+ await fs.writeFile(outputPath, Buffer.from(await blob.arrayBuffer()));+ return;+ }+ if (blob instanceof Uint8Array || Buffer.isBuffer(blob)) {+ await fs.writeFile(outputPath, Buffer.from(blob));+ return;+ }+ throw new Error("Expected a Blob or Uint8Array.");+}++function usage() {+ return [+ "Usage:",+ " $RUNTIME_NODE template_following_scripts/inspect_template_deck.mjs --workspace <dir> --pptx <source.pptx> [options]",+ "",+ "Options:",+ " --out-dir <dir> Output directory under workspace. Defaults to <workspace>/template-inspect.",+ " --scale <n> Render scale. Defaults to 1.",+ "",+ "Imports a source PPTX with artifact-tool, renders source slide PNGs/layouts,",+ "extracts package media, scans font names, writes template-inspect.ndjson,",+ "and writes template-manifest.json.",+ ].join("\n");+}++function runCapture(command, args, options = {}) {+ const result = spawnSync(command, args, {+ encoding: options.encoding,+ maxBuffer: options.maxBuffer || 80 * 1024 * 1024,+ });+ if (result.status !== 0) {+ const stderr = Buffer.isBuffer(result.stderr) ? result.stderr.toString("utf8") : result.stderr;+ const stdout = Buffer.isBuffer(result.stdout) ? result.stdout.toString("utf8") : result.stdout;+ throw new Error((stderr || stdout || `${command} ${args.join(" ")} failed`).trim());+ }+ return result.stdout;+}++function isWithin(child, parent) {+ const relative = path.relative(parent, child);+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));+}++function zipNames(pptxPath) {+ return String(runCapture("unzip", ["-Z1", pptxPath], { encoding: "utf8" }))+ .split(/\r?\n/)+ .filter(Boolean);+}++function readZipText(pptxPath, entryName) {+ return Buffer.from(runCapture("unzip", ["-p", pptxPath, entryName])).toString("utf8");+}++async function copyZipEntry(pptxPath, entryName, targetPath) {+ await fs.mkdir(path.dirname(targetPath), { recursive: true });+ await fs.writeFile(targetPath, Buffer.from(runCapture("unzip", ["-p", pptxPath, entryName])));+}++async function writeJson(filePath, value) {+ await fs.mkdir(path.dirname(filePath), { recursive: true });+ await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");+}++function relativeFromWorkspace(workspaceDir, filePath) {+ return path.relative(workspaceDir, filePath).split(path.sep).join("/");+}++function collectFonts(pptxPath, names) {+ const fonts = new Set();+ for (const name of names) {+ if (!/^ppt\/(?:slides|slideMasters|slideLayouts|theme)\/.*\.xml$/.test(name) && !/^ppt\/theme\/.*\.xml$/.test(name)) {+ continue;+ }+ const xml = readZipText(pptxPath, name);+ for (const match of xml.matchAll(/\btypeface="([^"]+)"/g)) fonts.add(match[1]);+ }+ return [...fonts].sort();+}++function slidesFromPresentation(presentation) {+ if (Array.isArray(presentation.slides?.items)) return presentation.slides.items;+ if (Number.isInteger(presentation.slides?.count) && typeof presentation.slides.getItem === "function") {+ return Array.from({ length: presentation.slides.count }, (_, index) => presentation.slides.getItem(index));+ }+ throw new Error("Could not enumerate imported presentation slides.");+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(usage());+ return;+ }++ const workspaceDir = path.resolve(requireArg(args, "workspace"));+ const pptxPath = path.resolve(requireArg(args, "pptx"));+ const scale = args.scale ? Number.parseFloat(args.scale) : 1;+ if (!Number.isFinite(scale) || scale <= 0) {+ throw new Error("--scale must be a positive number");+ }++ const outDir = args["out-dir"]+ ? path.resolve(workspaceDir, args["out-dir"])+ : path.join(workspaceDir, "template-inspect");+ if (!isWithin(outDir, workspaceDir)) {+ throw new Error(`Refusing to write template inspection outside workspace: ${outDir}`);+ }+ if (path.resolve(outDir) === workspaceDir) {+ throw new Error(+ [+ `Refusing to use the workspace root as template inspection output: ${outDir}`,+ "Omit --out-dir or use a dedicated subdirectory such as --out-dir template-inspect.",+ ].join("\n"),+ );+ }++ const sourceStat = await fs.stat(pptxPath).catch(() => undefined);+ if (!sourceStat?.isFile()) {+ throw new Error(`Missing source PPTX: ${pptxPath}`);+ }++ const { FileBlob, PresentationFile } = await importRuntimeModule("@oai/artifact-tool");++ await fs.rm(outDir, { recursive: true, force: true });+ const slidesDir = path.join(outDir, "source-slides");+ const layoutsDir = path.join(outDir, "layouts");+ const mediaDir = path.join(outDir, "assets", "ppt", "media");+ const inspectPath = path.join(outDir, "template-inspect.ndjson");+ const manifestPath = path.join(outDir, "template-manifest.json");+ await fs.mkdir(slidesDir, { recursive: true });+ await fs.mkdir(layoutsDir, { recursive: true });++ const presentation = await PresentationFile.importPptx(await FileBlob.load(pptxPath));+ const slides = slidesFromPresentation(presentation);+ const names = zipNames(pptxPath);+ const media = names.filter((name) => name.startsWith("ppt/media/"));+ const slideXmlNames = names.filter((name) => /^ppt\/slides\/slide\d+\.xml$/.test(name));+ const chartNames = names.filter((name) => /^ppt\/(?:charts|embeddings\/charts)\/chart\d+\.xml$/.test(name));++ const slideArtifacts = [];+ for (let index = 0; index < slides.length; index += 1) {+ const slide = slides[index];+ const slideNumber = index + 1;+ const padded = String(slideNumber).padStart(2, "0");+ const pngPath = path.join(slidesDir, `source-slide-${padded}.png`);+ const layoutPath = path.join(layoutsDir, `source-slide-${padded}.layout.json`);++ const preview = await presentation.export({ slide, format: "png", scale });+ await saveBlobToFile(preview, pngPath);++ const layout = await presentation.export({ slide, format: "layout" });+ await saveBlobToFile(layout, layoutPath);++ slideArtifacts.push({+ slide: slideNumber,+ previewPath: pngPath,+ previewRelativePath: relativeFromWorkspace(workspaceDir, pngPath),+ layoutPath,+ layoutRelativePath: relativeFromWorkspace(workspaceDir, layoutPath),+ });+ }++ const extractedMedia = [];+ for (const entry of media) {+ const target = path.join(mediaDir, path.basename(entry));+ await copyZipEntry(pptxPath, entry, target);+ const stat = await fs.stat(target);+ extractedMedia.push({+ entry,+ path: target,+ relativePath: relativeFromWorkspace(workspaceDir, target),+ bytes: stat.size,+ });+ }++ const inspect = await presentation.inspect({+ kind: "slide,textbox,shape,image,table,chart",+ max_chars: 200000,+ });+ await fs.writeFile(inspectPath, inspect.ndjson || "", "utf8");++ const tableSlideCount = slideXmlNames.filter((name) => readZipText(pptxPath, name).includes("<a:tbl>")).length;+ const manifest = {+ sourcePptx: pptxPath,+ workspace: workspaceDir,+ outDir,+ generatedAt: new Date().toISOString(),+ slideCount: slides.length,+ slideArtifacts,+ inspectPath,+ inspectRelativePath: relativeFromWorkspace(workspaceDir, inspectPath),+ inspectTruncated: Boolean(inspect.truncated),+ inspectMetadata: inspect.metadata || {},+ extractedMedia,+ fonts: collectFonts(pptxPath, names),+ packageParts: {+ mediaCount: media.length,+ slideXmlCount: slideXmlNames.length,+ chartCount: chartNames.length,+ tableSlideCount,+ },+ };+ await writeJson(manifestPath, manifest);+ console.log(manifestPath);+}++main().catch((error) => {+ console.error(error.stack || error.message || String(error));+ console.error(usage());+ process.exit(1);+});diff --git a/skills/paper-fig/template_following_scripts/make_contact_sheet.py b/skills/paper-fig/template_following_scripts/make_contact_sheet.pynew file mode 100644index 0000000..25bded2--- /dev/null+++ b/skills/paper-fig/template_following_scripts/make_contact_sheet.py@@ -0,0 +1,58 @@+#!/usr/bin/env python3++from __future__ import annotations++import argparse+import math+from pathlib import Path++from PIL import Image, ImageDraw+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser()+ parser.add_argument("images", nargs="+", help="Preview images to include.")+ parser.add_argument("--output", required=True, help="Output PNG path.")+ parser.add_argument("--cols", type=int, default=3)+ return parser.parse_args()+++def main() -> int:+ args = parse_args()+ image_paths = [Path(value).expanduser().resolve() for value in args.images]+ for image_path in image_paths:+ if not image_path.exists():+ raise FileNotFoundError(image_path)++ thumbs = [Image.open(path).convert("RGB") for path in image_paths]+ tile_w = max(image.width for image in thumbs)+ tile_h = max(image.height for image in thumbs)+ label_h = 48+ pad = 18+ cols = max(1, args.cols)+ rows = math.ceil(len(thumbs) / cols)++ sheet = Image.new(+ "RGB",+ (cols * tile_w + (cols + 1) * pad, rows * (tile_h + label_h) + (rows + 1) * pad),+ "white",+ )+ draw = ImageDraw.Draw(sheet)++ for idx, image in enumerate(thumbs):+ row, col = divmod(idx, cols)+ x = pad + col * (tile_w + pad)+ y = pad + row * (tile_h + label_h + pad)+ sheet.paste(image, (x, y))+ draw.text((x + 8, y + tile_h + 14), f"Slide {idx + 1:02d}", fill=(20, 30, 50))+ image.close()++ output_path = Path(args.output).expanduser().resolve()+ output_path.parent.mkdir(parents=True, exist_ok=True)+ sheet.save(output_path)+ print(output_path)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/paper-fig/template_following_scripts/prepare_template_starter_deck.mjs b/skills/paper-fig/template_following_scripts/prepare_template_starter_deck.mjsnew file mode 100644index 0000000..54650e9--- /dev/null+++ b/skills/paper-fig/template_following_scripts/prepare_template_starter_deck.mjs@@ -0,0 +1,292 @@+#!/usr/bin/env node++import fs from "node:fs/promises";+import path from "node:path";+import { spawnSync } from "node:child_process";+import { parseArgs as parseNodeArgs } from "node:util";+import { fileURLToPath } from "node:url";++import { importRuntimeModule } from "../container_tools/runtime_helpers.mjs";+import { validateTemplatePlan } from "./validate_template_plan.mjs";++function parseArgs(argv) {+ return parseNodeArgs({+ args: argv,+ options: {+ help: { type: "boolean" },+ workspace: { type: "string" },+ pptx: { type: "string" },+ map: { type: "string" },+ out: { type: "string" },+ "preview-dir": { type: "string" },+ "layout-dir": { type: "string" },+ inspect: { type: "string" },+ "contact-sheet": { type: "string" },+ scale: { type: "string" },+ },+ allowPositionals: false,+ strict: true,+ }).values;+}++function requireArg(args, key) {+ const value = args[key];+ if (typeof value !== "string" || value.length === 0) throw new Error(`Missing required --${key}`);+ return value;+}++function padSlideNumber(value) {+ return String(value).padStart(2, "0");+}++async function saveBlobToFile(blob, outputPath) {+ await fs.mkdir(path.dirname(outputPath), { recursive: true });+ if (blob && typeof blob.arrayBuffer === "function") {+ await fs.writeFile(outputPath, Buffer.from(await blob.arrayBuffer()));+ return;+ }+ if (blob instanceof Uint8Array || Buffer.isBuffer(blob)) {+ await fs.writeFile(outputPath, Buffer.from(blob));+ return;+ }+ throw new Error("Expected a Blob or Uint8Array.");+}++function usage() {+ return [+ "Usage:",+ " $RUNTIME_NODE template_following_scripts/prepare_template_starter_deck.mjs --workspace <dir> --pptx <source.pptx> --map <template-frame-map.json> --out <starter.pptx> [options]",+ "",+ "Options:",+ " --preview-dir <dir> Render starter slide PNGs. Defaults to <workspace>/template-starter-preview.",+ " --layout-dir <dir> Write starter layout JSON. Defaults to <workspace>/template-starter-layout.",+ " --inspect <path> template-inspect.ndjson. Defaults to <workspace>/template-inspect/template-inspect.ndjson.",+ " --contact-sheet <path> Optional PNG contact sheet path.",+ " --scale <n> Render scale. Defaults to 1.",+ "",+ "Reads template-frame-map.json outputSlides[] and builds an editable starter",+ "deck by duplicating selected source slides in output order.",+ ].join("\n");+}++function isWithin(child, parent) {+ const relative = path.relative(parent, child);+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));+}++async function readJson(filePath) {+ return JSON.parse(await fs.readFile(filePath, "utf8"));+}++async function writeJson(filePath, value) {+ await fs.mkdir(path.dirname(filePath), { recursive: true });+ await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");+}++function relativeFromWorkspace(workspaceDir, filePath) {+ return path.relative(workspaceDir, filePath).split(path.sep).join("/");+}++function slidesFromPresentation(presentation) {+ if (Array.isArray(presentation.slides?.items)) return presentation.slides.items;+ if (Number.isInteger(presentation.slides?.count) && typeof presentation.slides.getItem === "function") {+ return Array.from({ length: presentation.slides.count }, (_, index) => presentation.slides.getItem(index));+ }+ throw new Error("Could not enumerate imported presentation slides.");+}++function validateOutputSlides(map, sourceSlideCount) {+ if (!Array.isArray(map.outputSlides) || map.outputSlides.length === 0) {+ throw new Error("template-frame-map.json must include a non-empty outputSlides array.");+ }++ const sorted = [...map.outputSlides].sort((a, b) => a.outputSlide - b.outputSlide);+ for (let index = 0; index < sorted.length; index += 1) {+ const entry = sorted[index];+ const expectedOutputSlide = index + 1;+ if (!Number.isInteger(entry.outputSlide) || entry.outputSlide !== expectedOutputSlide) {+ throw new Error(`outputSlides must be sequential from 1; expected outputSlide ${expectedOutputSlide}.`);+ }+ if (!Number.isInteger(entry.sourceSlide) || entry.sourceSlide < 1 || entry.sourceSlide > sourceSlideCount) {+ throw new Error(+ `outputSlide ${entry.outputSlide} must reference sourceSlide 1-${sourceSlideCount}; got ${entry.sourceSlide}.`,+ );+ }+ if (entry.reuseMode !== "duplicate-slide") {+ throw new Error(+ `outputSlide ${entry.outputSlide} must use reuseMode "duplicate-slide"; got ${JSON.stringify(entry.reuseMode)}.`,+ );+ }+ if (typeof entry.narrativeRole !== "string" || entry.narrativeRole.trim().length === 0) {+ throw new Error(`outputSlide ${entry.outputSlide} must include a non-empty narrativeRole.`);+ }+ if (!Array.isArray(entry.editTargets)) {+ throw new Error(`outputSlide ${entry.outputSlide} must include editTargets as an array.`);+ }+ }+ return sorted;+}++function runContactSheet(previewPaths, outputPath) {+ if (!outputPath) return undefined;+ const scriptPath = path.join(path.dirname(fileURLToPath(import.meta.url)), "make_contact_sheet.py");+ const python = process.env.PYTHON || "python3";+ const result = spawnSync(python, [scriptPath, "--output", outputPath, ...previewPaths], { encoding: "utf8" });+ if (result.status !== 0) {+ throw new Error(+ [+ `Contact sheet generation failed with ${python}.`,+ result.stdout.trim(),+ result.stderr.trim(),+ ]+ .filter(Boolean)+ .join("\n"),+ );+ }+ return outputPath;+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(usage());+ return;+ }++ const workspaceDir = path.resolve(requireArg(args, "workspace"));+ const pptxPath = path.resolve(requireArg(args, "pptx"));+ const mapPath = path.resolve(requireArg(args, "map"));+ const out = path.resolve(requireArg(args, "out"));+ const previewDir = args["preview-dir"]+ ? path.resolve(args["preview-dir"])+ : path.join(workspaceDir, "template-starter-preview");+ const layoutDir = args["layout-dir"]+ ? path.resolve(args["layout-dir"])+ : path.join(workspaceDir, "template-starter-layout");+ const inspectPath = args.inspect+ ? path.resolve(args.inspect)+ : path.join(workspaceDir, "template-inspect", "template-inspect.ndjson");+ const contactSheetPath = args["contact-sheet"] ? path.resolve(args["contact-sheet"]) : undefined;+ const scale = args.scale ? Number.parseFloat(args.scale) : 1;++ if (!Number.isFinite(scale) || scale <= 0) {+ throw new Error("--scale must be a positive number");+ }+ for (const writePath of [previewDir, layoutDir, contactSheetPath].filter(Boolean)) {+ if (!isWithin(writePath, workspaceDir)) {+ throw new Error(`Refusing to write starter artifacts outside workspace: ${writePath}`);+ }+ }++ const sourceStat = await fs.stat(pptxPath).catch(() => undefined);+ if (!sourceStat?.isFile()) {+ throw new Error(`Missing source PPTX: ${pptxPath}`);+ }++ const { FileBlob, PresentationFile } = await importRuntimeModule("@oai/artifact-tool");+ const map = await readJson(mapPath);+ const presentation = await PresentationFile.importPptx(await FileBlob.load(pptxPath));+ const sourceSlides = slidesFromPresentation(presentation);+ const outputSlides = validateOutputSlides(map, sourceSlides.length);+ const planCheck = await validateTemplatePlan({+ workspace: workspaceDir,+ mapPath,+ inspectPath,+ sourceSlideCount: sourceSlides.length,+ });+ if (planCheck.status === "fail") {+ const summary = planCheck.issues+ .filter((item) => item.severity === "fail")+ .slice(0, 8)+ .map((item) => `- ${item.id}: ${item.message}`)+ .join("\n");+ throw new Error(+ [+ "template-frame-map.json failed template plan validation.",+ `Report: ${path.join(workspaceDir, "qa", "template-plan-check.json")}`,+ summary,+ ]+ .filter(Boolean)+ .join("\n"),+ );+ }++ const originals = [...sourceSlides];+ const starterSlides = [];+ for (const entry of outputSlides) {+ const sourceSlide = originals[entry.sourceSlide - 1];+ const duplicate = sourceSlide.duplicate();+ starterSlides.push({ entry, slide: duplicate });+ }++ for (const slide of originals) {+ slide.delete();+ }++ for (let index = 0; index < starterSlides.length; index += 1) {+ starterSlides[index].slide.moveTo(index);+ }++ await fs.mkdir(previewDir, { recursive: true });+ await fs.mkdir(layoutDir, { recursive: true });+ const previewPaths = [];+ const layoutPaths = [];+ for (let index = 0; index < starterSlides.length; index += 1) {+ const slideNumber = index + 1;+ const padded = padSlideNumber(slideNumber);+ const slide = starterSlides[index].slide;++ const previewPath = path.join(previewDir, `starter-slide-${padded}.png`);+ const preview = await presentation.export({ slide, format: "png", scale });+ await saveBlobToFile(preview, previewPath);+ previewPaths.push(previewPath);++ const layoutPath = path.join(layoutDir, `starter-slide-${padded}.layout.json`);+ const layout = await presentation.export({ slide, format: "layout" });+ await saveBlobToFile(layout, layoutPath);+ layoutPaths.push(layoutPath);+ }++ await fs.mkdir(path.dirname(out), { recursive: true });+ const pptx = await PresentationFile.exportPptx(presentation);+ await pptx.save(out);+ const outputStat = await fs.stat(out);+ if (outputStat.size <= 0) {+ throw new Error(`Exported starter deck is empty: ${out}`);+ }++ const contactSheet = runContactSheet(previewPaths, contactSheetPath);+ const manifestPath = out.toLowerCase().endsWith(".pptx")+ ? `${out.slice(0, -5)}.manifest.json`+ : `${out}.manifest.json`;+ const manifest = {+ sourcePptx: pptxPath,+ mapPath,+ output: out,+ outputBytes: outputStat.size,+ sourceSlideCount: originals.length,+ slideCount: starterSlides.length,+ previewDir,+ layoutDir,+ contactSheet,+ slides: starterSlides.map(({ entry }, index) => ({+ outputSlide: index + 1,+ sourceSlide: entry.sourceSlide,+ narrativeRole: entry.narrativeRole,+ reuseMode: entry.reuseMode,+ editTargetCount: entry.editTargets.length,+ previewPath: previewPaths[index],+ previewRelativePath: relativeFromWorkspace(workspaceDir, previewPaths[index]),+ layoutPath: layoutPaths[index],+ layoutRelativePath: relativeFromWorkspace(workspaceDir, layoutPaths[index]),+ })),+ };+ await writeJson(manifestPath, manifest);+ console.log(JSON.stringify({ ...manifest, manifestPath }, null, 2));+}++main().catch((error) => {+ console.error(error.stack || error.message || String(error));+ console.error(usage());+ process.exit(1);+});diff --git a/skills/paper-fig/template_following_scripts/validate_template_plan.mjs b/skills/paper-fig/template_following_scripts/validate_template_plan.mjsnew file mode 100644index 0000000..86c3331--- /dev/null+++ b/skills/paper-fig/template_following_scripts/validate_template_plan.mjs@@ -0,0 +1,549 @@+#!/usr/bin/env node++import fs from "node:fs/promises";+import path from "node:path";+import { parseArgs as parseNodeArgs } from "node:util";+import { fileURLToPath } from "node:url";++function parseArgs(argv) {+ return parseNodeArgs({+ args: argv,+ options: {+ help: { type: "boolean" },+ workspace: { type: "string" },+ map: { type: "string" },+ inspect: { type: "string" },+ "source-slide-count": { type: "string" },+ "no-report": { type: "boolean" },+ },+ allowPositionals: false,+ strict: true,+ }).values;+}++function requireArg(args, key) {+ const value = args[key];+ if (typeof value !== "string" || value.length === 0) throw new Error(`Missing required --${key}`);+ return value;+}++const ALLOWED_ACTIONS = new Set(["rewrite", "rewrite-and-reposition", "replace", "delete", "keep", "fill-placeholder"]);+const PLACEHOLDER_HANDLING_ACTIONS = new Set([+ "rewrite",+ "rewrite-and-reposition",+ "replace",+ "delete",+ "fill-placeholder",+]);+const CONTENT_ROLE_PATTERN =+ /\b(synthesis|timeline|proof|summary|map|analysis|evidence|body|content|callout|comparison|metric|chart|table|arc|engine|expansion|technology|standards|portfolio|purpose|thesis)\b/i;+const PRESERVE_ONLY_ROLE_PATTERN = /\b(brand|logo|bumper|divider|separator|section|chrome|blank)\b/i;+const PLACEHOLDER_PATTERNS = [+ /^slide number$/i,+ /^date$/i,+ /^footer$/i,+ /^click to add (title|subtitle|text)$/i,+ /^(title|subtitle|name|text|body) goes here$/i,+ /^lorem ipsum\b/i,+ /\btemplate instruction\b/i,+];++function usage() {+ return [+ "Usage:",+ " $RUNTIME_NODE template_following_scripts/validate_template_plan.mjs --workspace <dir> --map <template-frame-map.json> [options]",+ "",+ "Options:",+ " --inspect <path> template-inspect.ndjson. Defaults to <workspace>/template-inspect/template-inspect.ndjson.",+ " --source-slide-count <n> Optional source slide count check.",+ " --no-report Validate without writing qa/template-plan-check.*.",+ "",+ "Validates a template-following frame map before starter deck creation.",+ ].join("\n");+}++function normalizeId(value) {+ if (value === undefined || value === null) return undefined;+ const normalized = String(value).trim();+ return normalized ? normalized : undefined;+}++function asArray(value) {+ if (Array.isArray(value)) return value;+ return value === undefined || value === null ? [] : [value];+}++async function readJson(filePath) {+ return JSON.parse(await fs.readFile(filePath, "utf8"));+}++async function writeJson(filePath, value) {+ await fs.mkdir(path.dirname(filePath), { recursive: true });+ await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");+}++function textOf(value) {+ if (!value || typeof value !== "object") return "";+ return String(+ value.textPreview ??+ value.text ??+ value.plainText ??+ value.rawText ??+ value.value ??+ value.content ??+ "",+ ).trim();+}++function firstString(value, keys) {+ if (!value || typeof value !== "object") return "";+ for (const key of keys) {+ const item = value[key];+ if (typeof item === "string" && item.trim()) return item.trim();+ }+ return "";+}++function nameOf(value) {+ const keys = ["name", "shapeName", "shape_name", "label", "title", "objectName", "object_name"];+ return firstString(value, keys) || firstString(value?.raw, keys);+}++function placeholderLike(text) {+ return PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(text.trim()));+}++function placeholderMetadataOf(value) {+ if (!value || typeof value !== "object") return undefined;+ const candidates = [value, value.raw].filter((candidate) => candidate && typeof candidate === "object");+ for (const candidate of candidates) {+ const explicitKeys = [+ "placeholder",+ "placeholderType",+ "placeholder_type",+ "placeholderKind",+ "placeholder_kind",+ "placeholderRole",+ "placeholder_role",+ "ph",+ "phType",+ "ph_type",+ ];+ for (const key of explicitKeys) {+ const item = candidate[key];+ if (item === undefined || item === null || item === false) continue;+ return { source: key, value: item === true ? "true" : item };+ }++ const type = firstString(candidate, ["type", "kind", "shapeType", "shape_type"]);+ if (/\bplaceholder\b/i.test(type)) return { source: "type", value: type };+ }++ const name = nameOf(value);+ if (/\bplaceholder\b/i.test(name)) return { source: "name", value: name };+ return undefined;+}++function placeholderDescription(record) {+ if (record.text) return `source text "${record.text}"`;+ const placeholder = record.placeholder;+ const name = record.name ? ` name="${record.name}"` : "";+ if (placeholder?.value && typeof placeholder.value === "object") {+ const type = placeholder.value.type || placeholder.value.placeholderType || placeholder.value.placeholder_type;+ const idx = placeholder.value.idx || placeholder.value.index || placeholder.value.placeholderIndex;+ return `structural placeholder${name}${type ? ` type="${type}"` : ""}${idx ? ` idx="${idx}"` : ""}`;+ }+ if (placeholder?.value) return `structural placeholder${name} ${placeholder.source}="${String(placeholder.value)}"`;+ return `structural placeholder${name}`;+}++function slideNumberFromObject(value, inherited) {+ if (!value || typeof value !== "object") return inherited;+ const directKeys = ["slide", "slideNumber", "slide_number", "sourceSlide", "page", "pageNumber"];+ for (const key of directKeys) {+ const n = Number(value[key]);+ if (Number.isInteger(n) && n > 0) return n;+ }+ const indexKeys = ["slideIndex", "slide_index", "pageIndex", "page_index"];+ for (const key of indexKeys) {+ const n = Number(value[key]);+ if (Number.isInteger(n) && n >= 0) return n + 1;+ }+ return inherited;+}++function idsFromObject(value) {+ if (!value || typeof value !== "object") return [];+ return [+ value.shapeId,+ value.shape_id,+ value.sourceElementId,+ value.source_element_id,+ value.elementId,+ value.element_id,+ value.objectId,+ value.object_id,+ value.id,+ ]+ .map(normalizeId)+ .filter(Boolean);+}++function flattenObjects(value, inheritedSlide, out) {+ if (!value || typeof value !== "object") return;+ const slide = slideNumberFromObject(value, inheritedSlide);+ const ids = idsFromObject(value);+ const text = textOf(value);+ const name = nameOf(value);+ const placeholder = placeholderMetadataOf(value);+ if (ids.length || text || placeholder) {+ out.push({ slide, ids, text, name, placeholder, raw: value });+ }+ for (const child of Object.values(value)) {+ if (Array.isArray(child)) {+ for (const item of child) flattenObjects(item, slide, out);+ } else if (child && typeof child === "object") {+ flattenObjects(child, slide, out);+ }+ }+}++async function readInspectInventory(inspectPath) {+ const text = await fs.readFile(inspectPath, "utf8");+ const records = [];+ for (const [index, line] of text.split(/\r?\n/).entries()) {+ if (!line.trim()) continue;+ try {+ flattenObjects(JSON.parse(line), undefined, records);+ } catch (error) {+ records.push({ slide: undefined, ids: [], text: "", parseError: `line ${index + 1}: ${error.message}` });+ }+ }++ const bySlide = new Map();+ const parseErrors = [];+ for (const record of records) {+ if (record.parseError) {+ parseErrors.push(record.parseError);+ continue;+ }+ if (!Number.isInteger(record.slide) || record.slide < 1) continue;+ if (!bySlide.has(record.slide)) bySlide.set(record.slide, { ids: new Set(), placeholders: [] });+ const slide = bySlide.get(record.slide);+ for (const id of record.ids) slide.ids.add(id);+ if (record.placeholder || (record.text && placeholderLike(record.text))) {+ slide.placeholders.push({+ ids: record.ids,+ text: record.text,+ name: record.name,+ placeholder: record.placeholder,+ description: placeholderDescription(record),+ });+ }+ }+ return { bySlide, parseErrors };+}++function targetIds(target) {+ return [+ ...asArray(target.shapeId),+ ...asArray(target.shapeIds),+ ...asArray(target.sourceElementId),+ ...asArray(target.sourceElementIds),+ ...asArray(target.elementId),+ ...asArray(target.elementIds),+ ]+ .map(normalizeId)+ .filter(Boolean);+}++function hasNewPrimitivePermission(target) {+ const zone = target.zone || target.bbox || target.bounds;+ const hasZone =+ zone &&+ typeof zone === "object" &&+ (["left", "top", "width", "height"].every((key) => Number.isFinite(Number(zone[key]))) ||+ ["x", "y", "w", "h"].every((key) => Number.isFinite(Number(zone[key]))));+ return (+ (target.newPrimitiveAllowed === true || target.newPrimitivesAllowed === true || target.allowed === true) &&+ target.mustNotOverlapInherited === true &&+ typeof target.reason === "string" &&+ target.reason.trim().length > 0 &&+ hasZone+ );+}++function issue(severity, id, message, context = {}) {+ return { severity, id, message, ...context };+}++export async function validateTemplatePlan(options) {+ const workspace = path.resolve(options.workspace);+ const mapPath = path.resolve(options.mapPath);+ const inspectPath = path.resolve(options.inspectPath || path.join(workspace, "template-inspect", "template-inspect.ndjson"));+ const sourceSlideCount =+ options.sourceSlideCount === undefined || options.sourceSlideCount === null+ ? undefined+ : Number(options.sourceSlideCount);+ const writeReport = options.writeReport !== false;+ const issues = [];++ const map = await readJson(mapPath);+ const inspectExists = await fs+ .stat(inspectPath)+ .then((stat) => stat.isFile())+ .catch(() => false);+ if (!inspectExists) {+ issues.push(+ issue(+ "fail",+ "missing-template-inspect",+ `Missing template inspection file: ${inspectPath}. Run inspect_template_deck.mjs before preparing the starter deck.`,+ ),+ );+ }++ const inventory = inspectExists ? await readInspectInventory(inspectPath) : { bySlide: new Map(), parseErrors: [] };+ for (const parseError of inventory.parseErrors) {+ issues.push(issue("fail", "invalid-template-inspect", `Could not parse ${parseError}.`, { inspectPath }));+ }++ if (!Array.isArray(map.outputSlides) || map.outputSlides.length === 0) {+ issues.push(issue("fail", "missing-output-slides", "template-frame-map.json must include a non-empty outputSlides array."));+ }++ const outputSlides = Array.isArray(map.outputSlides)+ ? [...map.outputSlides].sort((a, b) => Number(a.outputSlide) - Number(b.outputSlide))+ : [];++ for (let index = 0; index < outputSlides.length; index += 1) {+ const entry = outputSlides[index];+ const expectedOutputSlide = index + 1;+ const outputSlide = Number(entry.outputSlide);+ const sourceSlide = Number(entry.sourceSlide);+ const context = { outputSlide: entry.outputSlide, sourceSlide: entry.sourceSlide };++ if (!Number.isInteger(outputSlide) || outputSlide !== expectedOutputSlide) {+ issues.push(+ issue("fail", "nonsequential-output-slide", `Expected outputSlide ${expectedOutputSlide}.`, context),+ );+ }+ if (!Number.isInteger(sourceSlide) || sourceSlide < 1) {+ issues.push(issue("fail", "invalid-source-slide", "Each output slide must reference a positive sourceSlide.", context));+ } else if (Number.isInteger(sourceSlideCount) && sourceSlide > sourceSlideCount) {+ issues.push(+ issue("fail", "invalid-source-slide", `sourceSlide must be 1-${sourceSlideCount}; got ${sourceSlide}.`, context),+ );+ }+ if (entry.reuseMode !== "duplicate-slide") {+ issues.push(+ issue(+ "fail",+ "invalid-reuse-mode",+ `outputSlide ${outputSlide || expectedOutputSlide} must use reuseMode "duplicate-slide".`,+ context,+ ),+ );+ }+ if (typeof entry.narrativeRole !== "string" || entry.narrativeRole.trim().length === 0) {+ issues.push(issue("fail", "missing-narrative-role", "Each output slide must include narrativeRole.", context));+ }+ if (!Array.isArray(entry.editTargets)) {+ issues.push(issue("fail", "missing-edit-targets", "Each output slide must include editTargets as an array.", context));+ continue;+ }++ const handledIds = new Map();+ let addTargetCount = 0;+ let inheritedTargetCount = 0;+ const slideInventory = inventory.bySlide.get(sourceSlide);+ const role = entry.narrativeRole || "";+ if (+ entry.editTargets.length === 0 &&+ CONTENT_ROLE_PATTERN.test(role) &&+ !PRESERVE_ONLY_ROLE_PATTERN.test(role)+ ) {+ issues.push(+ issue(+ "fail",+ "preserve-only-content-role",+ `editTargets: [] means preserve-only, but narrativeRole "${role}" appears content-bearing.`,+ context,+ ),+ );+ }++ for (const [targetIndex, target] of entry.editTargets.entries()) {+ const targetContext = { ...context, targetIndex, target };+ if (!target || typeof target !== "object" || Array.isArray(target)) {+ issues.push(issue("fail", "invalid-edit-target", "Each edit target must be an object.", targetContext));+ continue;+ }+ const action = String(target.action || "").trim();+ if (!action) {+ issues.push(issue("fail", "missing-edit-action", "Each edit target must include action.", targetContext));+ continue;+ }+ if (action === "add") {+ addTargetCount += 1;+ if (!hasNewPrimitivePermission(target)) {+ issues.push(+ issue(+ "fail",+ "unresolved-add-target",+ 'action: "add" is rejected by default. Map content to inherited shapeId/shapeIds or provide explicit newPrimitiveAllowed, zone, reason, and mustNotOverlapInherited.',+ targetContext,+ ),+ );+ }+ continue;+ }+ if (!ALLOWED_ACTIONS.has(action)) {+ issues.push(issue("fail", "unsupported-edit-action", `Unsupported edit action "${action}".`, targetContext));+ }++ const ids = targetIds(target);+ if (ids.length === 0) {+ issues.push(+ issue(+ "fail",+ "unresolved-edit-target",+ "Template edit targets must resolve to inherited shapeId/shapeIds or sourceElementId/sourceElementIds.",+ targetContext,+ ),+ );+ continue;+ }++ inheritedTargetCount += 1;+ for (const id of ids) {+ if (!handledIds.has(id)) handledIds.set(id, new Set());+ handledIds.get(id).add(action);+ if (slideInventory && slideInventory.ids.size > 0 && !slideInventory.ids.has(id)) {+ issues.push(+ issue("fail", "unknown-shape-id", `Referenced inherited shape id "${id}" was not found on source slide ${sourceSlide}.`, {+ ...targetContext,+ shapeId: id,+ }),+ );+ }+ }+ }++ if (addTargetCount > 0 && inheritedTargetCount === 0) {+ if (CONTENT_ROLE_PATTERN.test(role) && !PRESERVE_ONLY_ROLE_PATTERN.test(role)) {+ issues.push(+ issue(+ "fail",+ "add-only-content-slide",+ `narrativeRole "${role}" uses only action: "add"; map content to inherited template elements instead of building over a copied slide.`,+ context,+ ),+ );+ }+ if (PRESERVE_ONLY_ROLE_PATTERN.test(role)) {+ issues.push(+ issue(+ "fail",+ "add-on-preserve-only-slide",+ `narrativeRole "${role}" is preserve-only; do not turn brand/bumper/divider/blank slides into content canvases with action: "add".`,+ context,+ ),+ );+ }+ }++ if (slideInventory) {+ for (const placeholder of slideInventory.placeholders) {+ const ids = placeholder.ids.filter(Boolean);+ if (ids.length === 0) {+ issues.push(+ issue(+ "fail",+ "unresolved-template-placeholder",+ `${placeholder.description} was detected but has no resolved inherited shape id in template-inspect.ndjson.`,+ context,+ ),+ );+ continue;+ }+ const hasPlaceholderHandlingAction = ids.some((id) =>+ [...(handledIds.get(id) || [])].some((action) => PLACEHOLDER_HANDLING_ACTIONS.has(action)),+ );+ if (!hasPlaceholderHandlingAction) {+ issues.push(+ issue(+ "fail",+ "unhandled-placeholder",+ `${placeholder.description} must be assigned rewrite/rewrite-and-reposition/replace/delete/fill-placeholder in editTargets; keep and add do not satisfy inherited placeholder handling.`,+ { ...context, shapeIds: ids },+ ),+ );+ }+ }+ }+ }++ const status = issues.some((item) => item.severity === "fail")+ ? "fail"+ : issues.length > 0+ ? "warning"+ : "pass";+ const report = {+ status,+ checkedAt: new Date().toISOString(),+ workspace,+ mapPath,+ inspectPath,+ sourceSlideCount,+ issueCount: issues.length,+ issues,+ };++ if (writeReport) {+ const qaDir = path.join(workspace, "qa");+ await fs.mkdir(qaDir, { recursive: true });+ await writeJson(path.join(qaDir, "template-plan-check.json"), report);+ await fs.writeFile(+ path.join(qaDir, "template-plan-check.txt"),+ [+ `Template plan check: ${status}`,+ ...issues.map((item) =>+ `${item.severity.toUpperCase()} ${item.id}: ${item.message}` ++ (item.outputSlide ? ` outputSlide=${item.outputSlide}` : "") ++ (item.sourceSlide ? ` sourceSlide=${item.sourceSlide}` : ""),+ ),+ "",+ ].join("\n"),+ "utf8",+ );+ }++ return report;+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ if (args.help) {+ console.log(usage());+ return;+ }+ const workspace = path.resolve(requireArg(args, "workspace"));+ const report = await validateTemplatePlan({+ workspace,+ mapPath: requireArg(args, "map"),+ inspectPath: args.inspect,+ sourceSlideCount: args["source-slide-count"],+ writeReport: !args["no-report"],+ });+ console.log(JSON.stringify(report, null, 2));+ if (report.status === "fail") process.exit(1);+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ main().catch((error) => {+ console.error(error.stack || error.message || String(error));+ console.error(usage());+ process.exit(1);+ });+}