Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

[mirror] openJiuwen-ai/jiuwenswarm#1776: feat(ppt-creation): add slide content generation skill

openJiuwen-bot376b70799233
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/SKILL.md
new file mode 100644
index 0000000000..e66af29429
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/SKILL.md
@@ -0,0 +1,239 @@
+---
+name: ppt-creation
+description: "当任务要求创建、读取、解析、提取、编辑、修改、合并、拆分、转换或检查 PPT / 幻灯片 / 演示文稿 / deck / slides / presentation / .pptx 文件时使用。本 skill 以内置模板为版面底座,让 Agent 在内容区自由设计;支持原生 PptxGenJS 绘制、可选组件、用户素材、论文原图和合规网络素材。"
+---
+
+# PPT Creation
+
+## 核心模型
+
+本 skill 生成的 PPT 由三层组成:
+
+1. **模板母版底座**:画布、主题、字体、页脚及框架页。必须遵守。
+2. **Agent 自主设计的内容区**:按内容关系、叙事目的和证据形态自由构图。
+3. **参考与组件工具箱**:帮助判断或加速实现,但不规定页面必须长什么样。
+
+始终遵循:
+
+```text
+slide = template shell + agent-designed content + optional references/components
+```
+
+不要把内容组件配方误认为模板。模板的空白内容区有意保持自由。但标准内容页的底部框架固定:一条主题色一句话总结条、左下页码(密级文字可选)。图文分栏、卡片和系统图等内容结构仍不强制。
+
+新建 deck 默认走 `template-master`:先在 10×5.625 兼容坐标中创作可编辑内容,再用 `scripts/finalize_deck.py` 一条命令合并进模板(内部完成解包、等比放大、挂 `slideLayout7.xml`、清理与打包,无需手工操作拆包目录)。页脚和页码由母版继承,生成代码不得再画第二份;只有明确的兼容场景才使用独立 10×5.625 文件。
+
+## 开始前必须读取
+
+根据任务读取以下文件:
+
+- 所有新建或重设计任务:先读 [base/template-contract.md](base/template-contract.md)。
+- 实际生成 PPTX:再读 [base/pptx-safety.md](base/pptx-safety.md)。
+- 使用外部事实、论文或图片:再读 [base/sourcing.md](base/sourcing.md)。
+- 新建 deck:读 [workflows/create-deck.md](workflows/create-deck.md)。
+- 编辑用户提供的既有 PPTX:读 [workflows/edit-existing.md](workflows/edit-existing.md)。
+- 选择论文图、网络图或自绘路径:读 [workflows/acquire-visuals.md](workflows/acquire-visuals.md)。
+- 交付前:读 [base/quality-gates.md](base/quality-gates.md)。
+
+只在确定要使用某类组件后读取 [components/index.md](components/index.md) 和对应实现说明。先完成页面设计判断,再选择工具。
+
+## 不可违反的边界
+
+### 品牌与模板
+
+- 以 [references/template.pptx](references/template.pptx) 为模板事实来源。它是中性白板模板,由 `scripts/make_blank_template.py` 生成。
+- 保持主题色、字体层级、页脚和页码语义。
+- 每张标准内容页必须且只能出现一次固定底部框架:主题色一句话总结条与左下页码。模板不含 Logo,不得自行添加。
+- 封面主标题必须是主题色 `#4472C4` 且保持单行。自绘或复刻封面时同样适用,不得退回模板占位符的深色默认值。
+- 封面、目录、空白内容页、结束页应继承模板语言;若用户提供自己的模板,以用户模板为准。
+- `template-master` 输出必须保留模板自身的 Master / Layout 数量;`finalize_deck.py` 以模板为基线校验,丢失即判失败。
+
+### 内容与证据
+
+- 不得编造事实、数据、引用、产品能力或论文结论。
+- 数字、图表和外部判断要能回溯到用户材料或可靠来源。
+- 论文原图保持原意和比例;不得为了统一风格篡改图内颜色或内容。
+- 网络素材要记录来源和使用权;无法确认时使用占位或自绘,不假装已验证。
+- **"可回溯"指记录在 `evidence-plan.json` 和交付时的来源说明里,不指在幻灯片上画来源行。** 默认不在页面上放来源文字(论文原图页同样如此),只有用户明确要求时才画。
+
+### 工程质量
+
+- 输出必须可打开、可编辑、无重叠、无越界、无截断、无拉伸图片和占位残留。
+- 文字必须可读;不得用极小字号解决内容过载。
+- 原生 PptxGenJS 形状、图表和表格优先保持可编辑性。
+
+## 明确不是硬规则的事项
+
+以下都由内容决定,不得写成 deck 级默认门禁:
+
+- 默认左图右文或固定 60/40 比例;
+- 每页至少两个区域;
+- 所有内容页套用同一种固定版式;
+- 所有结构内容必须使用 `addSystemDiagram`;
+- 默认至少 10 页;
+- 固定组件使用比例或组件调用次数;
+- 固定字数、卡片数量或系统图节点数量;
+- 一律禁止或一律要求分节页。
+
+## 新建 deck 的主流程
+
+### 1. 理解内容
+
+优先读取用户材料。只有用户没有提供足够事实且任务允许外部调研时才联网补充。
+
+明确:
+
+- 目标受众;
+- 使用场景;
+- 核心结论;
+- 交付用途:阅读型、平衡型或演讲型;
+- 是否需要严格沿用用户结构;
+- 页数或时长约束。
+
+### 2. Strategist:先设计叙事,再设计页面
+
+选择一个主叙事模式:
+
+- `executive-report`:结论先行,证据与建议支撑;
+- `technical-explainer`:概念拆解、机制、边界与实现;
+- `research-review`:问题、方法、证据、局限与启示;
+- `showcase`:一页一个重点,视觉主导;
+- `briefing`:中性、完整、便于扫描。
+
+用户给定的页面顺序和标题优先。模式是组织建议,不得覆盖用户明确结构。
+
+为每页规划:
+
+```yaml
+page: P03
+role: content
+title: 页面标题
+core_message: 本页唯一必须记住的结论
+summary: 放入固定红色总结条的一句话结论
+rhythm: anchor | navigation | dense
+content_blocks:
+ - 完整事实或论证块
+visual_strategy:
+ primary: template | user-material | paper | web | native-drawing | component | svg | hybrid | none
+ reason: 为什么这种表达最适合本页
+ fallback: 首选失败后的替代路径
+component_policy: optional | preferred | avoid
+layout: 从 references/index.yaml 选定的骨架 name
+layout_id: 该骨架的 id
+layout_ref: <skill>/references/<id>.<ext>
+```
+
+`rhythm` 只控制页面节奏,不绑定版式:
+
+- `anchor`:封面、转折、重大结论或核心视觉;
+- `navigation`:目录、路线或结构导航;
+- `dense`:数据、架构、对比、研究证据。
+
+### 3. 生成设计契约
+
+在工作目录保存:
+
+- `design-spec.md`:受众、叙事、页面计划、设计理由和素材计划;每 deck 恰好标记 1-2 页 `Hero: yes`,选最核心的论证页;
+- `evidence-plan.json`:逐项记录图片/图表/截图要证明什么、怎样获取、审核状态和回退;
+- `execution-lock.json`:机器可校验的执行契约,记录模板、品牌固定层、逐页节奏/视觉策略,并通过 `asset_ids` 只允许使用 evidence plan 中的证据。
+
+从 [base/execution-lock-reference.json](base/execution-lock-reference.json) 开始,并使用 [base/execution-lock.schema.json](base/execution-lock.schema.json)。不要锁定单页坐标、固定布局比例或强制组件名;`component_policy` 只表达组件是否适合,不指定必须调用哪个函数。
+
+从 [base/evidence-plan.json](base/evidence-plan.json) 和对应 schema 开始。写完后立即运行:
+
+```bash
+node scripts/validate-evidence-plan.js <project>/evidence-plan.json --phase design
+node scripts/validate-execution-lock.js <project>/execution-lock.json --phase design
+```
+
+校验未通过时不得开始页面生成。不要把 JSON 改写成 YAML 或 Markdown。
+
+### 4. 获取视觉素材
+
+按 [workflows/acquire-visuals.md](workflows/acquire-visuals.md) 逐项处理 evidence plan。优先级不是固定排名,而是证据价值、真实性、可编辑性和表达效率的综合判断。
+
+论文 `paper-figure` 路线必须复用 `scripts/extract_arxiv_visuals_v2_2.py`:准备脚本会读取其 manifest,按 Figure/Table 标签和 Caption 关键词选择;选择不唯一时查看论文 contact sheet 后再批准。不得重新实现一套论文裁图器。
+
+素材状态只使用 `planned / acquiring / ready / used / needs-manual / skipped`。运行 `prepare_evidence.py` 后必须查看 `analysis/evidence-contact-sheet.jpg` 或论文专属 contact sheet,再用 `--approve <id>` 将项目置为 ready。素材实际进入 PPT 后用 `--used <id>` 记录使用状态。视觉方案发生变化时同步修改 `design-spec.md`、`evidence-plan.json` 与 `execution-lock.json`,不允许资源仍标记为 planned 而页面静默改走其他路径。
+
+### 5. Executor:在空白内容母版内逐页生成
+
+- 先实现模板外壳,再设计内容区。
+- 标准内容页完成内容后,调用 `Brand.addContentChrome(...)` 一次性添加固定总结条与页脚;内容必须结束在总结条上方。
+- 逐页顺序生成,保持同一主 Agent 的上下文和跨页一致性。
+- 每页先读取 `execution-lock.json` 中对应的 `core_message`、`rhythm`、`visual_strategy`、`component_policy`、素材状态和候选参考,再决定构图。
+- **写每页代码前,先打开该页 `Layout ref` 指向的参考图**,并对照 `references/index.yaml` 中该骨架的 `skeleton` 与 `rules`,理解它的分区、比例和填满方式。只看骨架名不看图,等于没有版面信息。参考图用来建立版面直觉,不要求逐像素复刻。
+- 骨架给出分区、比例和区域数量的参考方案;`composition` 决定这一页实际怎么摆。两者冲突时以 `composition` 为准——它更贴近本页内容;但要同步更新 `design-spec.md` 里的骨架选择,别让声明的 `layout id` 和实际产出长期不符。
+- 每页只允许引用 `evidence_visual.asset_ids` 列出的证据;AI 插画只能作为 hero/support/background/inline,不能声明为事实 evidence。
+- `composition` 必须明确主视觉、次证据和阅读顺序;`evidence_visual` 必须说明真实截图/论文图/数据图/原生关系图承担什么作用。密集或锚点内容页若不使用参考图,必须写具体 waiver,不能让整套 `reference_ids` 默认为空。
+- 可以使用裸 PptxGenJS、自定义 SVG、原生图表/表格、可选组件或图片组合。
+- 不使用预制小图标库;卡片/列表的识别锚点用 `initial` 首字母徽标或自绘 SVG,不引入装饰性图标。
+- 组件与内容不匹配时立即放弃组件,自己绘制。
+- **每个卡片、区域、节点里写完整陈述句,不是术语加半行注释。** 单词式短语只当表头或标签用,正文要把机制/条件/量级/边界说透——一张卡两三行、一节两三句。参照量级:标准内容页视觉字量 400-700(真实内部 deck 的密度锚点),容器画得足却只填几个词,交付前 `qa_density.py` 会判 EMPTY 硬错误。宁可少放一个空盒子,也不要让盒子半空。内容量达标后若版面仍显空,再靠放大字号/行距(多数组件已内置稀疏时自动放大)、拉开区域间距或补小图铺满——但先过字量,别用大字号给稀薄内容撑门面。
+
+推荐先生成封面和一张最具代表性的复杂内容页,合并到官方模板并渲染验证后再继续整套 deck,避免系统性错误复制到所有页面。通过目录、章节和锚点结论改变阅读节奏,而不是机械插空页。
+
+生成前运行 `--phase generate`;交付前运行 `--phase deliver`。必要素材未就绪时可以按设计稿中的 fallback 更新方案,但必须同步契约后重新校验。
+
+### 6. Hero 页精修
+
+全 deck 构建通过、几何硬错误清零后,对 design-spec 中标记 `Hero: yes` 的 1-2 页按 [workflows/create-deck.md](workflows/create-deck.md) 第 8 步做单页升格精修:打开该页渲染图与 `references/complex-slide.png` 及骨架参考图并排对比,列出差距后重构主区域,至多迭代两轮;改动同步回 `design-spec.md` 的该页 Composition。精修只动 hero 页,不回头重排其他页面。
+
+### 7. QA 与交付
+
+按 [base/quality-gates.md](base/quality-gates.md) 区分硬错误和软建议。硬错误必须清零;软建议由 Agent 结合设计意图判断,不得自动把页面改回固定组件配方。
+
+交付前必须运行 `python3 scripts/qa_geometry.py <output.pptx>` 并清零全部 error。它机械判定重叠、遮挡、重复底部框架和越界——这些缺陷普遍在 0.1 英寸量级,在缩略图总览上根本看不见,只靠人眼 QA 会反复漏掉。
+
+## 版式库使用方式
+
+[references/index.yaml](references/index.yaml) 是版面骨架库,每一项是一种可复用的版面骨架。**它是选型参考,不是强制模板**:用它避免从零构图和自创劣质版面,但页面最终长什么样由内容决定。
+
+建议动作:
+
+1. **通读全部 `name`**,先建立"有哪些骨架可选"的认识。整份文件一次读完,不要只挑几项看。
+2. 阅读 `common_rules`,它对所有版式生效。
+3. 按内容形态为每页选一个骨架,在 `design-spec.md` 中同时记录 `name`、`id` 和 `image` 的完整路径。**只记名字不记路径,Executor 阶段就拿不到版面信息。**
+4. 打开该项的 `image` 确认细节,再对照 `skeleton` 和 `rules` 理解它的分区与比例意图。
+5. 内容与骨架不完全吻合时,先看 `variants` 有没有现成变化;仍不吻合就换骨架,或在 `composition` 里写出自己的分区。
+
+骨架按每页的内容形态选。内容形态不同,自然会落到不同骨架上;如果整份 deck 都用同一个骨架,通常说明这一步被省略了,回头确认各页的内容形态是否真的相同。不要因为某个骨架先跑通就把它套到所有页面。相邻内容页连用「同一骨架 + 同一右栏文本样式」是同类信号——连续三四页都是左边一个视觉区、右边一列 1/2/3 编号条目,阅读节奏就塌了;用骨架 `variants`、错开右栏样式(numbered/sectioned)或换骨架打破重复。论文图、实验数据这类证据页优先评估 `architecture-evidence`(外框内左文右图):论证分节、原图与数据解读、红色结论句在同一个外框里对齐,比「左图 + 右列表」更有表达力。
+
+版式库提供的是:版面分区、区域比例、对齐方式和填满策略的**参考方案**。
+
+版式库不规定:坐标、颜色、区域数量、条目数量和具体内容——这些由 `avoid_when` 之外的内容需求决定。
+
+**松紧边界**:骨架是软的,可以偏离且不需要写 waiver;`common_rules`、品牌固定层和[工程质量要求](#工程质量)是硬的——撑满内容区、对齐轴线、不侵入页脚、不重叠、不越界、不截断,无论选哪个骨架都必须满足。产出好不好看以页面本身判断,不以是否忠实复刻骨架判断。
+
+## 组件使用原则
+
+组件是可选工具。选择顺序:
+
+1. 判断内容关系和证据形态;
+2. 决定页面视觉策略;
+3. 查看是否存在高度匹配的组件;
+4. 匹配则使用或改造,不匹配则裸绘。
+
+品牌框架组件与内容组件分开导入:
+
+```javascript
+const Brand = require("./components/brand.js");
+const Charts = require("./components/charts.js");
+const Diagrams = require("./components/diagrams.js");
+const Content = require("./components/content.js");
+```
+
+原有 `scripts/components.js` 仍保持兼容,可继续整体导入。
+
+## 编辑既有 PPTX
+
+若用户要求编辑已有 `.pptx`,以现有文件的 Master、Layout、主题和内容为事实来源,走 [workflows/edit-existing.md](workflows/edit-existing.md)。不要为了套用新建 deck 的组件系统而破坏原有模板结构。
+
+## 输出要求
+
+最终至少交付:
+
+- `.pptx` 文件;
+- QA 模式和结果;
+- 使用外部素材时的来源说明;
+- 未能获取的素材、占位或已采用的回退方案。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/design-spec-reference.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/design-spec-reference.md
new file mode 100644
index 0000000000..f1c851491b
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/design-spec-reference.md
@@ -0,0 +1,86 @@
+# Design Spec Reference
+
+复制本结构到任务工作区的 `design-spec.md`,用实际内容替换说明。只写已确认或可追溯的信息。**每个字段都必须填**:一行装不下就写多行;确实不适用的字段显式写 `none` 并给一句原因,不许删字段。冒号后的斜体说明是填写要求,落笔时替换成实际内容,不要保留。
+
+## I. Project
+
+- Project:
+- Audience: *具体到职能与决策层级(如「企业 AI / Agent 架构、研发与技术管理人员」),不写「相关人员」*
+- Scenario: *使用场合 + 演讲/阅读比重*
+- Language:
+- Delivery purpose: `text | balanced | presentation`
+- Page count / duration: *页数与预计讲述时长*
+- Confidentiality:
+- User structure authority: *用户指定了什么(主题/页数/素材)、授权重组什么——后续页面取舍以此为据*
+
+## II. Narrative
+
+- Narrative mode: `executive-report | technical-explainer | research-review | showcase | briefing`
+- Core conclusion: *一两句**可辩护的完整判断**(含关键机制或数字),整套 deck 都在论证它;主题复述(「介绍 X 的原理与应用」)视为未填*
+- Story/argument outline: *用「→」串出完整论证链,一步对应一到两页,能看出每章回答什么问题*
+- Source fidelity: *按事实类别写来源边界:哪类事实只采用哪个来源的哪个版本,哪些是本报告自行整理并须标注*
+
+## III. Template
+
+- Template source:
+- Canvas mode: `official-master | 10x5.625-compatible`
+- Authoring / merge mode: `10x5.625-scaled + template-layout | official-size | source-layout`
+- Content layout / footer mode:
+- Cover / TOC / content / ending treatment: *四类页各怎么处理;省掉某类(如不设目录)要写原因*
+- Fixed content-page summary/footer treatment:
+
+## IV. Cross-page Design System
+
+- Color behavior: *写「什么颜色承担什么语义」(强调色只用于哪里、辅助色区分什么、背景基调),不是罗列色值*
+- Typography roles: *各文字角色的字号区间:标题 / 正文 / 来源 / 大数字*
+- Readability floors: title / body / absolute minimum
+- Image treatment: *裁切策略(no-crop / contain)、边框、图注的全 deck 统一做法*
+- Chart/table treatment: *原生可编辑优先;数字逐字引用来源;禁 3D、截断轴等误导手法*
+- Source/credit treatment: **默认不在幻灯片上画来源行**——包括论文原图页。来源一律记录在 `evidence-plan.json` 的 `source_rights` 和交付时的来源说明里,页面保持干净。只有用户明确要求页面显示出处时才画
+
+## V. Evidence Resources
+
+| ID | Page | Claim/Purpose | Kind | Acquire Via | Placement | File/query/paper | Status/Review | Source/license | Fallback |
+|---|---|---|---|---|---|---|---|---|---|
+
+本表解释设计意图,机器事实写入 `evidence-plan.json`。Claim/Purpose 写这份素材**支撑哪句论断**,不是写素材是什么。Status 只使用:`planned | acquiring | ready | used | needs-manual | skipped`。外部图片达到 `ready/used` 前必须是 `review.status: approved`。执行过程中改变视觉方案时,同步修改本表、evidence plan 和 execution lock。
+
+## VI. Page Plan
+
+### P01 — <title>
+
+- Role: `fixed-cover | toc | section | standard-content | fixed-closing` — *首页用 `fixed-cover`、末页用 `fixed-closing`(模板结尾页),两者默认都要有,用官方模板页不在 content.pptx 里生成;中间是 standard-content,toc/section 按需*
+- Hero: `yes | no` — *每 deck 恰好标 1-2 页 yes,选最核心的论证页;hero 页在构建通过后按工作流第 8 步做单页精修,其 Composition 必须写到元素级*
+- Core message: *一句有主谓的完整判断——Executor 不看其他材料也知道本页要证明什么;不是标题换写*
+- Summary banner: 本页一句话结论;标准内容页必填。*是结论句,不是标题重复*
+- Rhythm: `anchor | navigation | dense`
+- Content blocks: *列出真实信息点:数字、机制、对照关系、边界条件,Executor 可直接上版;「三个要点」「若干案例」这类占位视为未填。标准内容页的 blocks 合计要能支撑 400-700 视觉字的版面(quality-gates 密度锚点,交付前 `qa_density.py` 机检 <300 硬错误)——每个卡片/区域是 2-3 行完整陈述句,不是一个术语加半行注释;只够两三行话说明本字段没写完,回内容分析阶段补料*
+ -
+- Visual strategy:
+ - Primary: `template | user-material | paper | web | native-drawing | component | svg | hybrid | none`
+ - Reason:
+ - Fallback:
+- Layout: 从 `references/index.yaml` 选定的骨架 `name`
+- Layout id: 该骨架的 `id`
+- Layout ref: `<skill>/references/<id>.<ext>` — 写代码前必须打开这张图
+- Layout variant: 使用了 `variants` 中的哪一条;未使用写 none
+- Component policy: `optional | preferred | avoid`
+- Composition: 这一页实际怎么摆。**这是决定产出的字段,标准内容页必须写到元素级**:分区比例 + 每区元素清单(组件/图/文本样式)+ 关键实文(区域标题、图题、KPI 数字、结论句的原文)。合格样例:「整页大圆角外框,框内副标题『性价比、延迟与两条修正路线』;左 50% 三节论证(红方块小标题:成本优势 / TTFT 局限 / 演进方向),节内箭头符号列论点;右 45% 上部 Figure 5 原图(contain,图题『性能-成本 Pareto 前沿』),下方 3 条数据解读,末行红色结论句『从最小聚合配置起步,按增益再扩』」。只有一句「左 X% 图、右 Y% 文」视为未填完——元素内容留白,Executor 就会现场发挥,声明的骨架也会落地走样。与骨架冲突时以本字段为准,但要回头把 `Layout` / `Layout id` 换成更贴合的那个
+- Evidence visual: 类型、素材 ID 及在论证中的作用
+- Layout waiver: 确实无骨架适用时写具体原因(骨架可自由偏离,此项只用于完全不参考版式库的情况)
+- Sources: *具体到文档名/章节/表号(如「MoA 论文 Table 2/3/4」「官方 README」),不写「官网」「网络资料」*
+- Speaker-note intent: *讲者备注要传达的一句话:澄清什么误解、强调什么边界*
+
+为每页重复本节,**每页所有字段齐全**。不要只写占位式提纲;`content blocks` 应包含 Executor 能直接使用的真实信息。
+
+`Layout ref` 是给 Executor 用的:写该页代码前打开这张图,对照 `index.yaml` 中该骨架的 `skeleton` 和 `rules` 落实分区。只写骨架名不写路径,等于没有传递版面信息——名字本身推不出几个区域、什么比例、有没有通栏带。
+
+每页都必须在 `execution-lock.json.pages` 中有对应机器条目。设计稿解释为什么,execution lock 只保存最终决定;两者冲突时必须先同步,不能让 Executor 猜测。
+
+## VII. QA Intent
+
+- Representative content page: *选信息密度最高、素材类型最全的一页作视觉 QA 代表,并说明为什么*
+- Known layout risks: *逐页点名可预见的拥挤、字号、图注风险(如「P03 矩阵六格文字易挤」)*
+- Known sourcing risks: *数据时效、口径与快照限制(如「论文数据为 2024 模型快照,不能表述为当前排行榜」)*
+- Required preservation checks:
+- FULL / TEXT-ONLY expectations:
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/evidence-plan.json b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/evidence-plan.json
new file mode 100644
index 0000000000..b99e7aa238
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/evidence-plan.json
@@ -0,0 +1,7 @@
+{
+ "$schema": "./evidence-plan.schema.json",
+ "version": 1,
+ "asset_root": "assets",
+ "analysis_root": "analysis",
+ "items": []
+}
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/evidence-plan.schema.json b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/evidence-plan.schema.json
new file mode 100644
index 0000000000..1cc72e01f5
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/evidence-plan.schema.json
@@ -0,0 +1,85 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://jiuwenswarm.local/schemas/ppt-evidence-plan.schema.json",
+ "title": "PPT evidence plan",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["version", "asset_root", "analysis_root", "items"],
+ "properties": {
+ "$schema": { "type": "string" },
+ "version": { "const": 1 },
+ "asset_root": { "type": "string", "minLength": 1 },
+ "analysis_root": { "type": "string", "minLength": 1 },
+ "items": {
+ "type": "array",
+ "items": { "$ref": "#/$defs/item" }
+ }
+ },
+ "$defs": {
+ "item": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id", "page", "claim", "purpose", "kind", "acquire_via",
+ "required", "placement_role", "status", "path", "source_path",
+ "source_url", "source", "license", "reference", "query",
+ "crop_policy", "review", "fallback"
+ ],
+ "properties": {
+ "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$" },
+ "page": { "type": "string", "pattern": "^P[0-9]{2,3}$" },
+ "claim": { "type": "string", "minLength": 1 },
+ "purpose": { "type": "string", "minLength": 1 },
+ "kind": {
+ "enum": [
+ "user-material", "paper-figure", "paper-table", "product-screenshot",
+ "code-screenshot", "official-logo", "data-chart", "web-image",
+ "ai-illustration", "formula", "native-diagram", "other"
+ ]
+ },
+ "acquire_via": {
+ "enum": [
+ "user", "source-extracted", "paper-figure", "product-screenshot",
+ "code-screenshot", "official-logo", "native-chart", "web",
+ "ai-illustration", "formula", "native-drawing", "manual"
+ ]
+ },
+ "required": { "type": "boolean" },
+ "placement_role": { "enum": ["hero", "evidence", "support", "background", "inline"] },
+ "status": { "enum": ["planned", "acquiring", "ready", "used", "needs-manual", "skipped"] },
+ "path": { "type": ["string", "null"] },
+ "source_path": { "type": ["string", "null"] },
+ "source_url": { "type": ["string", "null"] },
+ "source": { "type": ["string", "null"] },
+ "license": { "type": ["string", "null"] },
+ "reference": { "type": "string", "minLength": 1 },
+ "query": { "type": ["string", "null"] },
+ "crop_policy": { "enum": ["contain", "crop", "no-crop"] },
+ "paper_selector": {
+ "type": ["object", "null"],
+ "additionalProperties": false,
+ "properties": {
+ "label": { "type": ["string", "null"] },
+ "caption_keywords": { "type": "array", "items": { "type": "string", "minLength": 1 } },
+ "include_caption": { "type": "boolean" },
+ "min_confidence": { "type": "number", "minimum": 0, "maximum": 1 }
+ }
+ },
+ "review": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["status", "notes"],
+ "properties": {
+ "status": { "enum": ["pending", "approved", "rejected", "not-required"] },
+ "notes": { "type": ["string", "null"] }
+ }
+ },
+ "result": {
+ "type": ["object", "null"],
+ "additionalProperties": true
+ },
+ "fallback": { "type": "string", "minLength": 1 }
+ }
+ }
+ }
+}
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/execution-lock-reference.json b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/execution-lock-reference.json
new file mode 100644
index 0000000000..08b9117ad4
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/execution-lock-reference.json
@@ -0,0 +1,87 @@
+{
+ "$schema": "./execution-lock.schema.json",
+ "version": 2,
+ "evidence_plan": "evidence-plan.json",
+ "template": {
+ "source": "references/template.pptx",
+ "canvas_mode": "template-master",
+ "authoring_canvas": "10x5.625-scaled",
+ "merge_mode": "template-layout",
+ "content_layout": "slideLayout7.xml",
+ "content_shell": "blank-content",
+ "footer_mode": "master"
+ },
+ "brand": {
+ "colors": {
+ "primary": "4472C4",
+ "secondary": "8FAADC",
+ "text": "1D1D1A",
+ "secondary_text": "666666",
+ "background": "FFFFFF"
+ },
+ "typography": {
+ "cjk": "Microsoft YaHei",
+ "latin": "Arial"
+ },
+ "footer": {
+ "required_on": "standard-content"
+ },
+ "summary_banner": {
+ "required_on": "standard-content",
+ "fill": "4472C4",
+ "text_color": "FFFFFF",
+ "position": "above-footer"
+ }
+ },
+ "deck": {
+ "narrative_mode": "briefing",
+ "typography_policy": {
+ "title_min_pt": 24,
+ "body_min_pt": 10,
+ "absolute_min_pt": 7
+ },
+ "image_treatment": "rectangular-documentary"
+ },
+ "pages": [
+ {
+ "id": "P01",
+ "role": "fixed-cover",
+ "rhythm": "anchor",
+ "core_message": "Replace with the confirmed cover message.",
+ "summary": null,
+ "visual_strategy": {
+ "primary": "template",
+ "fallback": "none"
+ },
+ "component_policy": "avoid",
+ "composition": "Use the official fixed-cover page without rebuilding its geometry.",
+ "evidence_visual": {
+ "kind": "template",
+ "asset_ids": []
+ },
+ "reference_ids": [],
+ "reference_waiver": "The official cover is itself the governing reference."
+ },
+ {
+ "id": "P02",
+ "role": "standard-content",
+ "rhythm": "dense",
+ "core_message": "Replace with the one conclusion this page must establish.",
+ "summary": "Replace with the one-sentence takeaway rendered in the fixed red banner.",
+ "visual_strategy": {
+ "primary": "native-drawing",
+ "fallback": "component"
+ },
+ "component_policy": "optional",
+ "composition": "Use one dominant relationship diagram plus a concise evidence column; avoid equal gray cards.",
+ "evidence_visual": {
+ "kind": "native-diagram",
+ "asset_ids": []
+ },
+ "reference_ids": [
+ "problem-diagram-analysis"
+ ],
+ "reference_waiver": null
+ }
+ ]
+}
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/execution-lock.schema.json b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/execution-lock.schema.json
new file mode 100644
index 0000000000..a9f75d1c7b
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/execution-lock.schema.json
@@ -0,0 +1,493 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://jiuwenswarm.local/schemas/ppt-execution-lock.schema.json",
+ "title": "PPT execution lock",
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "version",
+ "template",
+ "brand",
+ "deck",
+ "pages"
+ ],
+ "anyOf": [
+ {
+ "properties": {
+ "version": {
+ "const": 1
+ }
+ },
+ "required": [
+ "assets"
+ ]
+ },
+ {
+ "properties": {
+ "version": {
+ "const": 2
+ }
+ },
+ "required": [
+ "evidence_plan"
+ ]
+ }
+ ],
+ "properties": {
+ "$schema": {
+ "type": "string"
+ },
+ "version": {
+ "enum": [
+ 1,
+ 2
+ ]
+ },
+ "evidence_plan": {
+ "type": "string",
+ "minLength": 1
+ },
+ "template": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source",
+ "canvas_mode",
+ "authoring_canvas",
+ "merge_mode",
+ "content_layout",
+ "content_shell",
+ "footer_mode"
+ ],
+ "properties": {
+ "source": {
+ "type": "string",
+ "minLength": 1
+ },
+ "canvas_mode": {
+ "enum": [
+ "template-master",
+ "10x5.625-compatible"
+ ]
+ },
+ "authoring_canvas": {
+ "enum": [
+ "10x5.625-scaled",
+ "template-size"
+ ]
+ },
+ "merge_mode": {
+ "enum": [
+ "template-layout",
+ "source-layout"
+ ]
+ },
+ "content_layout": {
+ "type": "string",
+ "pattern": "^slideLayout[0-9]+\\.xml$"
+ },
+ "content_shell": {
+ "const": "blank-content"
+ },
+ "footer_mode": {
+ "enum": [
+ "master",
+ "drawn"
+ ]
+ }
+ }
+ },
+ "brand": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "colors",
+ "typography",
+ "footer",
+ "summary_banner"
+ ],
+ "properties": {
+ "colors": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "primary",
+ "secondary",
+ "text",
+ "secondary_text",
+ "background"
+ ],
+ "properties": {
+ "primary": {
+ "const": "4472C4"
+ },
+ "secondary": {
+ "const": "8FAADC"
+ },
+ "text": {
+ "const": "1D1D1A"
+ },
+ "secondary_text": {
+ "const": "666666"
+ },
+ "background": {
+ "const": "FFFFFF"
+ }
+ }
+ },
+ "typography": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "cjk",
+ "latin"
+ ],
+ "properties": {
+ "cjk": {
+ "const": "Microsoft YaHei"
+ },
+ "latin": {
+ "const": "Arial"
+ }
+ }
+ },
+ "footer": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "required_on"
+ ],
+ "properties": {
+ "required_on": {
+ "const": "standard-content"
+ },
+ "classification": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ },
+ "summary_banner": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "required_on",
+ "fill",
+ "text_color",
+ "position"
+ ],
+ "properties": {
+ "required_on": {
+ "const": "standard-content"
+ },
+ "fill": {
+ "const": "4472C4"
+ },
+ "text_color": {
+ "const": "FFFFFF"
+ },
+ "position": {
+ "const": "above-footer"
+ }
+ }
+ }
+ }
+ },
+ "deck": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "narrative_mode",
+ "typography_policy",
+ "image_treatment"
+ ],
+ "properties": {
+ "narrative_mode": {
+ "enum": [
+ "executive-report",
+ "technical-explainer",
+ "research-review",
+ "showcase",
+ "briefing"
+ ]
+ },
+ "typography_policy": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "title_min_pt",
+ "body_min_pt",
+ "absolute_min_pt"
+ ],
+ "properties": {
+ "title_min_pt": {
+ "type": "number",
+ "minimum": 20
+ },
+ "body_min_pt": {
+ "type": "number",
+ "minimum": 9
+ },
+ "absolute_min_pt": {
+ "type": "number",
+ "minimum": 7
+ }
+ }
+ },
+ "icons": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "library"
+ ],
+ "properties": {
+ "library": {
+ "const": "none"
+ },
+ "stroke_width": {
+ "type": "null"
+ },
+ "inventory": {
+ "type": "array",
+ "maxItems": 0
+ }
+ }
+ },
+ "image_treatment": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ },
+ "pages": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#/$defs/page"
+ }
+ },
+ "assets": {
+ "type": "array",
+ "description": "Deprecated v1 compatibility projection. Version 2 uses evidence_plan.",
+ "items": {
+ "$ref": "#/$defs/asset"
+ }
+ }
+ },
+ "$defs": {
+ "page": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id",
+ "role",
+ "rhythm",
+ "core_message",
+ "summary",
+ "visual_strategy",
+ "component_policy",
+ "composition",
+ "evidence_visual",
+ "reference_ids",
+ "reference_waiver"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^P[0-9]{2,3}$"
+ },
+ "role": {
+ "enum": [
+ "fixed-cover",
+ "toc",
+ "standard-content",
+ "section",
+ "fixed-closing"
+ ]
+ },
+ "rhythm": {
+ "enum": [
+ "anchor",
+ "navigation",
+ "dense"
+ ]
+ },
+ "core_message": {
+ "type": "string",
+ "minLength": 1
+ },
+ "summary": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "visual_strategy": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "primary",
+ "fallback"
+ ],
+ "properties": {
+ "primary": {
+ "enum": [
+ "template",
+ "user-material",
+ "paper",
+ "web",
+ "native-drawing",
+ "component",
+ "svg",
+ "hybrid",
+ "none"
+ ]
+ },
+ "fallback": {
+ "enum": [
+ "template",
+ "user-material",
+ "paper",
+ "web",
+ "native-drawing",
+ "component",
+ "svg",
+ "none"
+ ]
+ }
+ }
+ },
+ "component_policy": {
+ "enum": [
+ "optional",
+ "preferred",
+ "avoid"
+ ]
+ },
+ "composition": {
+ "type": "string",
+ "minLength": 1
+ },
+ "evidence_visual": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "asset_ids"
+ ],
+ "properties": {
+ "kind": {
+ "enum": [
+ "template",
+ "user-material",
+ "paper",
+ "product-screenshot",
+ "code-screenshot",
+ "official-diagram",
+ "data-chart",
+ "native-diagram",
+ "none"
+ ]
+ },
+ "asset_ids": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ }
+ },
+ "reference_ids": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "minLength": 1
+ }
+ },
+ "reference_waiver": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ }
+ },
+ "asset": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id",
+ "page",
+ "kind",
+ "required",
+ "status",
+ "path",
+ "source",
+ "license",
+ "fallback"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1
+ },
+ "page": {
+ "type": "string",
+ "pattern": "^P[0-9]{2,3}$"
+ },
+ "kind": {
+ "enum": [
+ "user",
+ "paper",
+ "web",
+ "ai",
+ "icon",
+ "diagram",
+ "screenshot",
+ "code",
+ "logo",
+ "other"
+ ]
+ },
+ "required": {
+ "type": "boolean"
+ },
+ "status": {
+ "enum": [
+ "planned",
+ "acquiring",
+ "ready",
+ "used",
+ "needs-manual",
+ "skipped"
+ ]
+ },
+ "path": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "source": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "license": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "fallback": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ }
+ }
+}
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/pptx-safety.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/pptx-safety.md
new file mode 100644
index 0000000000..2d152d852d
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/pptx-safety.md
@@ -0,0 +1,83 @@
+# PptxGenJS 与 PPTX 安全边界
+
+## 画布与坐标
+
+- 现有兼容组件按 10 × 5.625 英寸创作;使用前设置 `pres.layout = "LAYOUT_16x9"`。
+- 官方模板原始画布为 12196750 × 6858000 EMU(约 13.34 × 7.50 英寸)。默认合并流程会等比放大坐标与字号,并把内容页挂到官方 `slideLayout6.xml`;不要手工再缩放一次。
+- 标准内容页必须预留固定总结条与页脚区;10 × 5.625 兼容坐标中,正文/图表/图片必须在 `y=4.65` 以上结束。
+- 官方母版合并模式不得绘制独立页脚/Logo;使用 `footerMode: "master"`。兼容独立文件才使用默认 `footerMode: "drawn"`。
+- 总结条与页码的坐标和样式不得由单页构图覆盖;模板不含 Logo,不得自行添加。
+
+## 文本
+
+- 为文本框预留真实换行高度,尤其是中文、长英文单词和混排内容。
+- 优先重写、重排、扩大容器或拆页,不用极小字号挽救过载。
+- 同一结构角色的字号和字体在全 deck 保持一致;局部大数字、引语和标签可建立独立角色。
+- `addSlideTitle` 的 `subtitle` 是本页第二句话,不是文献条目:不得以 `Wang et al., 2024` 这类
+ 作者引用开头,要提论文就写全名;出处放页脚的 `addSourceNote`。详见
+ `template-contract.md` 的「内容页副标题」,由 `audit_pptx.py --lock` 强制。
+- 项目列表使用 PptxGenJS 的列表格式,不用 Unicode 圆点模拟列表。
+
+## 图片
+
+- 始终保持原始宽高比;明确选择 contain 或 crop,不直接拉伸。
+- 论文图、公式、Logo 和信息图默认 contain;照片可在不损害主体的前提下 crop。
+- 使用图片前确认路径存在、分辨率足够、方向正确。
+- 不把整页内容栅格化为一张图;需要可编辑的图表、表格、形状和文本应保留原生对象。
+- **嵌入 `assets/papers/` 下论文原图的页面,必须同页调用 `addSourceNote(pres, slide, { source })`。**
+ 来源文字取 `evidence-plan.json` 对应条目 `source` 字段的精简形式,例如
+ `Wang et al., arXiv:2406.04692, Fig.1`;组件自动加 `来源:` 前缀,画在官方页脚行右端、
+ 页脚右端。一页多图时合并成一条引用,组件每页只允许调用一次。
+- 同时传 `url`(取该条目的 `source_url`)可让引用可点击:只有引用正文带下划线和超链接,
+ `来源:` 标签保持纯文本,颜色仍是页脚灰而非主题的超链接蓝——页脚 chrome 不应该比旁边
+ 的密级文字更抢眼。url 必须是绝对 http(s) 地址,否则组件直接报错。
+- 该规则由 `audit_pptx.py --evidence-plan evidence-plan.json` 强制:它按图片字节哈希匹配
+ 论文图资产,命中却找不到来源文本的页面直接判为硬错误。自绘图/原生图表页不受此约束。
+
+## 图表与表格
+
+- 数值必须来自用户材料或可靠来源。
+- 图表类型必须匹配数据关系;不为视觉效果选择会误导的轴、比例或形状。
+- 表格行列、图表标签、图例和来源必须在最终文件中可读。
+- 不用示例数据、组件 demo 数字或模板配色示意页的数据填充正式 deck。
+
+## 形状与 SVG
+
+- PptxGenJS 颜色使用不带 `#` 的 6 位 HEX;SVG 内使用带 `#` 的标准 HEX。
+- 避免依赖 PowerPoint 版本不稳定的滤镜、复杂 mask 和不可预测的字体替换。
+- 自绘 SVG 要有明确 viewBox、足够描边宽度和可嵌入字体策略。
+
+## 选项对象不可复用(PptxGenJS 会就地改写)
+
+PptxGenJS 生成 XML 时**直接修改传入的 options 对象**,而不是先拷贝。`shadow` 最典型:
+`blur ×12700`、`offset ×12700`、`angle ×60000`、`opacity ×100000`。
+
+所以**任何 options 子对象都不能在多个 `addShape` / `addText` / `addImage` 之间共享引用**。
+共享会让第 2 个形状的数值被二次换算、第 3 个被三次换算,很快越过
+`ST_PositiveFixedAngle`(上限 21600000)等类型上限;PowerPoint 打开时报
+"found a problem with content",修复时把整段属性删掉。
+
+```js
+// ✗ 单例常量:第 2 个卡片起数值成倍炸开
+const CARD_SHADOW = { type: "outer", blur: 3, offset: 1, angle: 90, opacity: 0.3 };
+cards.forEach(c => slide.addShape(SHAPE, { ..., shadow: CARD_SHADOW }));
+
+// ✓ 每次新建
+const cardShadow = () => ({ type: "outer", blur: 3, offset: 1, angle: 90, opacity: 0.3 });
+cards.forEach(c => slide.addShape(SHAPE, { ..., shadow: cardShadow() }));
+```
+
+同样适用于被复用的 `line`、`fill`、`glow` 等配置对象——用工厂函数或 `{ ...PRESET }`
+展开,不要直接传共享引用。
+
+## 构建检查
+
+- 非法参数、缺失资源、悬空关系、重复 ID、无效数值应立即报错。
+- **打包必须走 `pack.py --original <模板>` 且不得使用 `--validate false`。** 这是唯一会对
+ `ppt/slides/*.xml` 做 XSD 校验并自动修正 PptxGenJS 已知产物的关卡;绕过它,越界数值和
+ 段内重复 `<a:pPr>` 会一路带进交付文件,只有 PowerPoint 会告诉你。
+- 交付前用 `validate.py <产物>.pptx` 复核一次,输出必须是 `All validations PASSED!`,且
+ `-v` 下 `Skipped (no schema)` 应为 0——不为 0 说明有部件根本没被校验。
+- 元素重叠、越界、图片变形、文本截断属于硬问题。
+- 页面空白、密度和构图相似度属于设计判断,只作为软建议。
+- 交付前运行 `audit_pptx.py`;官方模式少于模板的 4 个 Master / 7 个 Layout、画布不一致、显式字号低于 absolute floor 或标准内容页缺总结条都属于硬错误。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/quality-gates.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/quality-gates.md
new file mode 100644
index 0000000000..91dccdcde4
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/quality-gates.md
@@ -0,0 +1,126 @@
+# 质量门禁
+
+QA 检查结果是否合格,不替 Agent 决定页面必须采用哪种构图。
+
+## 模式
+
+先检测:
+
+```bash
+soffice --version >/dev/null 2>&1 && pdftoppm -v >/dev/null 2>&1 && echo FULL || echo TEXT-ONLY
+```
+
+- `FULL`:结构检查、文本检查、渲染检查。
+- `TEXT-ONLY`:结构和文本检查;交付时声明未完成渲染视觉核查。
+
+## 硬错误:必须清零
+
+### 文件与结构
+
+- PPTX 无法打开或页面数量错误;
+- `execution-lock.json` 无法解析、未通过当前阶段校验,或页面计划与实际页数不一致;
+- `evidence-plan.json` 缺失、存在 Pending/Failed 式未收敛状态、必需项未 ready/used、外部视觉未审核批准,或页面引用计划外证据;
+- 资源、关系或媒体缺失;
+- 占位符、Lorem、XXXX、示例数据或模板教学页残留;
+- 用户要求保留的 Master/Layout、备注或批注被破坏。
+- `official-master` 输出没有继承官方画布,或少于模板的 4 个 Master / 7 个 Layout;内容页仍挂在独立 PptxGenJS 空母版上。
+- deck 缺少模板封面或模板结尾页(末页不是 Thank You 结尾页)——用户明确要求无结尾页时除外。`finalize_deck.py` 默认顺序已挂结尾页;手工指定 `--order` 时不要漏掉 `t5`。
+- 封面主标题为空。官方模板的 `ctrTitle` 占位符出厂即为空且不渲染任何提示文字,漏填的封面看上去"完整"却没有标题。用 `finalize_deck.py --cover-title "..."` 填入设计阶段定下的主标题;该脚本收尾会做 cover-title 硬门禁,为空直接判失败。
+
+### 几何与可读性
+
+**几何缺陷由 `scripts/qa_geometry.py` 机械判定,不靠肉眼。** 它报出的每一条 error 都是硬错误,必须清零:
+
+- `text-collision`:两处文字的实际墨迹重叠;
+- `occlusion`:后画的不透明形状压住先画的文字(Z 序错误);
+- `duplicate-chrome`:页面自绘元素与母版继承的页脚/密级/Logo 位置重合,底部框架画了两遍;
+- `out-of-bounds`:元素越出画布。
+
+`axis-drift` 与 `summary-intrusion` 是 warning,结合设计意图判断:前者提示各区域各写各的魔数而没有共用轴线常量,后者提示内容压到总结条区域。
+
+**这一步不能用缩略图总览代替。** 0.1 英寸级的重叠和错位在 contact sheet 分辨率下不可见,历史上多次通过人眼 QA 后仍然带着叠字交付。
+
+**文字量由 `scripts/qa_density.py` 机械判定**(视觉字量:中文 1、英文/数字 0.5;`--lock` 读取页面角色,只判 standard-content 页):
+
+- 标准内容页视觉字量 <300 是硬错误——这种页渲染出来就是半空的;
+- 300-400 为 warning,需结合版面说明或补料;
+- 校准锚点来自真实内部 deck:内容页 400-700,中位约 480。生成时按这个量级规划内容,不要等 QA 兜底。
+
+**字量不足和版面显空是两件事,处置不同。** `qa_density` 抓的是内容量本身不够(词不成句、盒子里只有术语加半行注释)——这只能靠补料,回内容分析阶段把机制/条件/量级/边界写成完整陈述句。而当内容量已经达标、只是视觉上还偏空时,再用版面手段填充:**放大字号与行距**(多数结构组件已内置内容稀疏时自动放大字号,也可显式调大,但不得超出模板字号上限、不得同页同类区域字号不一)、拉开区域间距撑满内容区、或补相关小图。次序是先保证内容量(过 qa_density),再用字号/版面把它铺满——不能反过来用大字号给稀薄内容撑门面,那种页字量仍低、仍判 EMPTY。
+
+其余几何与可读性问题仍需人工判断:
+
+- 标准内容页未填满内容区,出现大块空白(字量达标但堆在一角同样算);
+- 文字截断、不可读或依赖异常小字号;
+- 显式字号低于 execution lock 的 absolute floor;标准内容标题低于 title floor;
+- 图片、Logo、论文图被拉伸;
+- 表格、图表标签无法阅读。
+
+### 品牌与事实
+
+- Logo、品牌色、字体、页脚或密级不符合模板契约;
+- 标准内容页缺少或重复红色一句话总结条;总结条位置、颜色、文字样式被改变;
+- 标准内容页缺少右下官方横版 Logo,Logo 位于右上角、被替换、变形或改变固定位置;
+- 页面自绘了母版已经继承的页脚、密级、页码或 Logo,导致同一元素出现两次(`qa_geometry.py` 的 `duplicate-chrome`)。封面同样适用:挂在带页脚的内容版式上又自绘一套,就会叠字;
+- 使用预制图标库或 `deck.icons.library` 声明非 `none`(内置图标库已移除;识别锚点只用 `initial` 首字母徽标或自绘 SVG);
+- 数据、引用、图表或结论与来源不一致;
+- 需要署名的素材未署名;
+- 用 AI/占位视觉冒充真实证据。
+
+## 软建议:结合设计意图判断
+
+- 页面视觉重心不明确;
+- 连续多页构图过于相似;
+- 红色强调过多、层级失效;
+- 图片与文字没有共同支持核心信息;
+- 参考图被机械照抄或完全没有吸收其设计原则;
+- 组件虽然技术正确,但不适合本页内容。
+
+软建议不得自动转化成固定字数、固定区域数量或固定内容组件配方。固定总结条与右下页脚 Logo 属于模板硬约束,不在此例。
+
+## 推荐检查顺序
+
+1. `validate-execution-lock.js --phase design`;
+2. `validate-evidence-plan.js --phase design`,运行 `prepare_evidence.py`;
+3. 查看 evidence contact sheet,批准合格项并执行两个 `--phase generate` 校验;
+4. 生成固定封面和一张代表性复杂内容页;
+5. 构建并处理所有硬错误;
+6. FULL 模式下渲染这两页,确认模板与视觉方向;
+7. 顺序生成剩余页面;
+8. 运行完整结构/文本检查并生成缩略图总览;
+9. 运行 `qa_geometry.py`,清零全部 error;它负责机械可判的几何缺陷,人眼不必也不可能在缩略图上完成这件事;随后运行 `qa_density.py --lock execution-lock.json`,清零全部 EMPTY;
+10. 主 Agent 必须打开缩略图总览,逐页检查标题截断、视觉重心、构图重复、证据可读性和底部框架;只生成图片但不查看不算视觉 QA;
+11. 几何 error 清零后,代表性页面还需单页高清渲染确认(`pdftoppm -r 130`);缩略图只用于看整体节奏,不用于判断单页质量;
+12. 修复硬错误,再处理真正影响表达的软建议;
+13. 用 `python3 scripts/prepare_evidence.py . --used <id>` 将实际使用的证据标为 used,执行两个 `--phase deliver` 校验。
+
+## 常用命令
+
+```bash
+node slides.js
+python3 scripts/finalize_deck.py output/content.pptx output/final.pptx # 合并官方模板一条命令
+node scripts/validate-evidence-plan.js evidence-plan.json --phase deliver
+python -m markitdown output.pptx
+python scripts/audit_pptx.py output.pptx \
+ --template references/template.pptx \
+ --lock execution-lock.json \
+ --evidence-plan evidence-plan.json \
+ --report qa/structure.json
+# --evidence-plan 打开论文图来源硬校验:按图片字节哈希找出嵌入了论文原图的页面,
+# 该页若没有 addSourceNote 画出的“来源:…”文本,报 error 并以退出码 1 结束。
+python scripts/opc/thumbnail.py output.pptx qa/contact --cols 4
+
+# 几何自检:重叠 / 遮挡 / 重复底部框架 / 越界 / 轴线漂移
+# 坐标已换算回 10×5.625,可直接对照 slides.js;有 error 时退出码为 1
+python3 scripts/qa_geometry.py output.pptx
+
+# 文字量自检:标准内容页 <300 视觉字为 EMPTY 硬错误,目标带 400-700
+python3 scripts/qa_density.py output.pptx --lock execution-lock.json
+python3 scripts/qa_geometry.py output.pptx --slide 6 # 只看某一页
+python3 scripts/qa_geometry.py output.pptx --json # 机器可读
+
+soffice --headless --convert-to pdf output.pptx
+pdftoppm -jpeg -r 150 output.pdf slide
+```
+
+最终说明 QA 模式、硬错误状态、未处理的实质性软风险和素材回退情况。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/sourcing.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/sourcing.md
new file mode 100644
index 0000000000..a7470ad33e
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/sourcing.md
@@ -0,0 +1,50 @@
+# 内容、图片与引用
+
+## 事实优先级
+
+1. 用户提供的文件、数据、图表和明确陈述;
+2. 用户指定的权威来源;
+3. 官方文档、论文原文、标准和一手数据;
+4. 可靠的二手研究与新闻;
+5. 仅用于气氛或场景的视觉素材。
+
+用户要求只基于内部材料时,不联网补充外部事实。
+
+## 数据与结论
+
+- 记录数字、日期、定义和结论的来源。
+- 不把来源的推测写成事实,不把相关性写成因果。
+- 图表旁或页脚附近放简洁来源;详细链接可写入备注或交付清单。
+- 对存在口径、样本、时间范围或可比性限制的数据,保留必要边界说明。
+
+## 论文视觉
+
+- 页面在解释一篇具体论文的机制或结果时,可优先考虑论文原图。
+- 原图只有在可读、直接支持核心信息且版面允许时才使用;否则自绘简化关系图并注明“根据论文整理”。
+- 原图保持比例、颜色、标签和内容,不为了统一风格改造图内信息。
+- 页面或备注中标明论文题目、作者/机构、年份或链接中的必要部分。
+
+## 网络图片
+
+- 真实人物、地点、产品、事件和新闻场景优先使用可验证的真实图片。
+- 保存来源页、作者/机构、许可和下载时间。
+- 明确需要署名的图片,在使用该图片的页面内提供简洁署名。
+- 许可未知、禁止演绎或不适合商业使用时不要自动采用。
+
+## AI 图片
+
+- 仅在用户允许且真实素材、自绘或抽象几何无法满足表达时考虑。
+- 不用 AI 图片伪装真实产品、人物、实验结果、论文图或新闻现场。
+- 保持全 deck 的生成风格一致,并在交付时说明使用情况。
+
+## 占位与回退
+
+视觉素材获取失败不应导致编造。按页面设计选择:
+
+- 改为原生自绘;
+- 改为文字或数据表达;
+- 使用清晰命名的占位;
+- 向用户索要素材;
+- 拆分或调整页面论点。
+
+最终交付列出仍存在的占位和回退方案。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/template-contract.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/template-contract.md
new file mode 100644
index 0000000000..3677ac3f6d
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/base/template-contract.md
@@ -0,0 +1,144 @@
+# 版面契约
+
+## 权威来源
+
+`../references/template.pptx` 是本 skill 当前的模板事实来源。它是一个中性白板模板:
+Office 默认主题,无 Logo、无背景装饰、无密级框架。若用户提供自己的模板,以用户文件为准,
+并重新提取本契约。
+
+当前模板包含:
+
+- 16:9 画布,原始尺寸 13.333 × 7.50 英寸;
+- 1 个 Slide Master;
+- 11 个 Slide Layout(Office 标准版式,空白版式是 `slideLayout7.xml`);
+- 5 张骨架页:封面、目录、两张空白内容页、结束页。
+
+模板由 `../scripts/make_blank_template.py` 生成,可随时重新生成。
+
+空白内容页揭示核心边界:模板固定页面身份与外围框架,内容区域有意开放给设计者。
+
+## 必须继承
+
+### 页面身份
+
+- 使用 16:9 画布;合并进模板或复用原始 Master/Layout 时使用模板的原始画布尺寸。
+- 保持封面、目录、内容页、结束页之间的视觉家族关系。
+- 标准内容页保留固定底部框架:主题色一句话总结条、左下页码。
+
+### 封面固定元素
+
+封面无论使用组件、模板原页还是自绘复刻,都必须满足:
+
+- 主标题使用主题色 `#4472C4`,不得使用深灰、黑色或模板占位符的默认颜色;
+- 主标题保持单行,过长时缩小字号或改写,不折行、不缩到不可读;
+- 部门、汇报人、日期使用深色正文,只承担次级信息,不与主标题争夺层级。
+
+### 内容页副标题
+
+`addSlideTitle` 的 `subtitle` 是这一页的第二句话,不是参考文献条目。
+
+- **不得以作者引用开头。** `Wang et al., 2024(arXiv:2406.04692)` 这种写法把版面最显眼的
+ 第二行让给了出处,而出处读者并不需要在这里知道——它已经由页脚的 `addSourceNote` 承担。
+- **要提作品就写全名。** 写 `Mixture-of-Agents Enhances Large Language Model Capabilities`,
+ 不写 `Wang et al., 2024`。全名本身就说明了这一页依据什么,作者缩写不说明任何事。
+- **副标题要有实质内容**:交代这一页的范围、口径、机制或结论前提。
+ 剥掉 `et al.` / `arXiv:xxxx.xxxxx` / 年份 / `§x.x` 之后,剩下的实质文字不得少于 6 个视觉字。
+- **宽度是硬约束**:框宽 9.0"、10.5pt、单行高 0.24",正文区从 `y=0.95"` 起,只有 0.03" 余量。
+ 按 CJK 记 1em、ASCII 记 0.55em 计算,单行容量约 61 em,超出会压到正文。
+ 论文全名本身就占约 33 em,所以中文说明尾巴要相应精简。
+
+```
+✗ Wang et al., 2024(arXiv:2406.04692)—— 每个 agent 把上一层全部输出当作辅助信息,逐层精炼直至聚合
+✓ Mixture-of-Agents Enhances Large Language Model Capabilities(arXiv:2406.04692)—— 逐层精炼直至聚合
+```
+
+该规则由 `audit_pptx.py --lock execution-lock.json` 强制,作用于 `role: "standard-content"` 的页面。
+
+### 目录页
+
+**必须调用 `addTocSlide(pres, { title, sections })`,不得自绘。** 目录只有三层文字:
+22pt 页面标题、13pt 编号徽标、16pt 章节标题。
+
+- **不得加第四层。** 反复出现的偏差是照抄 `addTocSlide` 的几何、再在每条标题下补一行
+ ~10pt 灰色描述。组件的 `sections` 只接受 `{num, title}`,多余字段会被丢弃——这是设计如此,
+ 不是缺陷;不要为了加描述行而改组件或改成自绘。
+- **章节标题写成描述性短语,不是四字标签。** 目录是全篇唯一的结构预告,标题本身就要交代
+ 这一章讲什么:写「核心架构设计与 MOA 编排机制」「技术栈与多模型推理配置」,
+ 不写「架构」「技术栈」。10–18 字为宜。正因为标题已经承载了信息,才不需要描述行。
+- 最多 7 条;超出时在 `slides.js` 里合并章节,不改组件。
+
+该规则由 `audit_pptx.py --lock execution-lock.json` 强制:execution lock 中 `role: "toc"`
+的页面若出现低于编号徽标层级的文字,判硬错误。
+
+### 标准内容页固定底部框架
+
+每张标准内容页必须且只能出现一次以下元素;封面、目录、分节页和结束页使用各自模板,不叠加这一框架:
+
+- 总结条:页面底部页脚上方的通栏主题色块,白色粗体居中,只承载本页一句话结论;
+- 页脚:左下页码。
+
+密级文字是**可选**的:`addSlideFooter` / `addContentChrome` 的 `classification` 参数
+默认不传就不绘制,需要密级标识时才传入(如 `"Internal Use Only"`)。
+
+10 × 5.625 兼容坐标固定为:总结条 `x=0.30, y=4.70, w=9.40, h=0.40`;页码 `x=0.60, y=5.21`;
+密级(如启用)`x=0.90, y=5.21`。内容必须在 `y=4.65` 以上结束。
+
+使用原始 13.333 × 7.5 Master/Layout 时,优先继承母版已有页脚对象;总结条及缺失的底部对象
+按同一相对位置等比实现,不得自行改变层级与位置。当前空白内容版式是 `slideLayout7.xml`。
+
+### 颜色
+
+模板主题的核心色:
+
+| 角色 | 色值 | 用途 |
+|---|---|---|
+| accent | `#4472C4` | 标题、关键结论、关键数据、强调线、总结条 |
+| accent mid | `#8FAADC` | 受控的次级强调,不与主色争夺层级 |
+| accent light | `#B4C7E7` | 弱化的同族填充 |
+| dark text | `#1D1D1A` | 主体文字 |
+| white | `#FFFFFF` | 页面底色与反白文字 |
+| neutral dark | `#232323` | 深色中性元素 |
+| neutral mid | `#666666` | 次级文字、坐标轴、注释 |
+| neutral light | `#919191` / `#C4C4C4` | 分隔、弱化数据、边框 |
+| warning | `#C00000` | 真正的告警语义,不作装饰使用 |
+
+绿、黄、橙等辅助色仅在数据或类别编码有真实语义时使用。不得把主题色理解成每页都要用齐的调色板。
+
+主题色定义在 `../scripts/components.js` 的 `THEME`。改主题色需要同步三处:
+`THEME`、`execution-lock-reference.json` 的 `brand.colors`、
+`../scripts/validate-execution-lock.js` 的 `brandConstants`。
+
+### 字体
+
+- 模板拉丁字体为 Arial。
+- 中文优先使用 Microsoft YaHei;不可用时选择清晰的无衬线 CJK 字体并在交付时说明替代。
+- 标题、正文、注释、来源和页脚维持稳定的 deck 级层级;同一角色不因页面拥挤而随意缩放。
+
+## 内容区自由度
+
+内容页可以根据内容采用:
+
+- 自由文本排版;
+- 非对称或对称分栏;
+- 全幅或局部图表;
+- 架构、流程、关系或因果图;
+- 论文原图、用户图片或合规网络图片;
+- 表格、时间轴、地图、照片叙事;
+- 大数字或强结论主导的版面;
+- 自定义 PptxGenJS/SVG 构图。
+
+除固定底部框架外,模板不要求:左图右文、固定区域数量、固定卡片数量或固定内容组件。
+
+## 实现边界
+
+`../scripts/components.js` 使用 10 × 5.625 英寸坐标系按比例复刻模板语言,适合生成可编辑内容;
+它不是原始 Master/Layout 本身。新建 deck 默认用
+`merge_slides.py --source-layout-mode template --template-layout slideLayout7.xml`
+等比放大并继承模板版式。此模式调用 `addContentChrome(..., { footerMode: "master" })`,
+避免与母版页脚重复。
+
+`--source-layout-mode source` 只作为旧项目兼容开关:它会复制 PptxGenJS 的母版和版式,
+不能被描述为「继承模板母版的输出」。
+
+组件实现与模板冲突时,以模板为准并修正组件。参考图片与模板冲突时,以模板为准,
+参考图只影响内容区设计。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/brand.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/brand.js
new file mode 100644
index 0000000000..85c4b67c68
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/brand.js
@@ -0,0 +1,18 @@
+// Deck shell (cover, TOC, footer, summary banner, closing) and design tokens.
+// This is a compatibility view over the all-in-one component module.
+
+const C = require("../scripts/components.js");
+
+module.exports = {
+ THEME: C.THEME,
+ TY: C.TY,
+ LAYOUT: C.LAYOUT,
+ withHash: C.withHash,
+ addSlideTitle: C.addSlideTitle,
+ addSlideFooter: C.addSlideFooter,
+ addSummaryBanner: C.addSummaryBanner,
+ addContentChrome: C.addContentChrome,
+ addOpeningSlide: C.addOpeningSlide,
+ addTocSlide: C.addTocSlide,
+ addClosingSlide: C.addClosingSlide,
+};
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/charts.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/charts.js
new file mode 100644
index 0000000000..21ef165dcd
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/charts.js
@@ -0,0 +1,12 @@
+// Optional data-visualization components. Select them only after the page's
+// information relationship and evidence source are known.
+
+const C = require("../scripts/components.js");
+
+module.exports = {
+ addDeckChart: C.addDeckChart,
+ addChartWithInsights: C.addChartWithInsights,
+ addComparisonTable: C.addComparisonTable,
+ addKpiRow: C.addKpiRow,
+ addSpectrumAxis: C.addSpectrumAxis,
+};
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/content.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/content.js
new file mode 100644
index 0000000000..8b3ad8a767
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/content.js
@@ -0,0 +1,18 @@
+// Optional content blocks, image panels, and SVG/icon helpers.
+
+const C = require("../scripts/components.js");
+
+module.exports = {
+ cols: C.cols,
+ addPanel: C.addPanel,
+ addCardGrid: C.addCardGrid,
+ addTimeline: C.addTimeline,
+ addPanelList: C.addPanelList,
+ addIconCards: C.addIconCards,
+ addTextBlock: C.addTextBlock,
+ addRegionHeading: C.addRegionHeading,
+ addFigurePanel: C.addFigurePanel,
+ addSourceNote: C.addSourceNote,
+ iconToPng: C.iconToPng,
+ svgToPng: C.svgToPng,
+};
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/diagrams.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/diagrams.js
new file mode 100644
index 0000000000..41ba594031
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/diagrams.js
@@ -0,0 +1,17 @@
+// Optional relationship/diagram components. They are rendering tools, not a
+// mandatory grammar for every process, architecture, or conceptual page.
+
+const C = require("../scripts/components.js");
+
+module.exports = {
+ addSystemDiagram: C.addSystemDiagram,
+ addPipelineDiagram: C.addPipelineDiagram,
+ addHubSpoke: C.addHubSpoke,
+ addTintMatrix: C.addTintMatrix,
+ addConvergeFunnel: C.addConvergeFunnel,
+ addChevronStages: C.addChevronStages,
+ item: C.item,
+ group: C.group,
+ bandNode: C.bandNode,
+ groupBand: C.groupBand,
+};
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/index.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/index.js
new file mode 100644
index 0000000000..6782be498f
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/index.js
@@ -0,0 +1,9 @@
+// Full compatibility surface, organized under components/ for new callers.
+// Prefer importing brand/charts/diagrams/content individually when practical.
+
+module.exports = {
+ ...require("./brand.js"),
+ ...require("./charts.js"),
+ ...require("./diagrams.js"),
+ ...require("./content.js"),
+};
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/index.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/index.md
new file mode 100644
index 0000000000..81545bc5dc
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/components/index.md
@@ -0,0 +1,87 @@
+# 可选组件索引
+
+组件用于加速实现,不负责决定页面设计。先完成页面的 `core_message`、`rhythm` 和 `visual_strategy`,再选择是否加载组件。
+
+## 品牌底座
+
+导入 `brand.js`:
+
+- `HW`、`TY`、`LAYOUT`、`RES`;
+- `addSlideTitle`;
+- `addSlideFooter`;
+- `addSummaryBanner`;
+- `addContentChrome`;
+- `addOpeningSlide`;
+- `addTocSlide`(目录页唯一入口,不得自绘;只有编号徽标 + 章节标题两层,`sections` 只接受 `{num, title}`。章节标题写描述性短语而非四字标签,详见 `../base/template-contract.md`);
+- `addClosingSlide`。
+
+这些函数是当前 10 × 5.625 兼容坐标系中的模板实现。标准内容页优先只调用 `addContentChrome`,由它一次性添加固定总结条、页码、密级和右下 Logo;不要自行覆盖坐标或样式。需要真实 Master/Layout 时使用原始模板工作流。
+
+## 图表与数据
+
+导入 `charts.js`:
+
+- `addDeckChart`:原生柱、线、饼、环图;
+- `addChartWithInsights`:图表配解释区的现成实现;
+- `addComparisonTable`:可编辑对比表;
+- `addKpiRow`:指标行;
+- `addSpectrumAxis`:定位轴。
+
+只有在数据和关系匹配时使用。`addChartWithInsights` 是可选现成构图,不是内容页默认结构。
+
+## 图示
+
+导入 `diagrams.js`:
+
+- `addSystemDiagram`:声明式 band/group 系统图;
+- `addPipelineDiagram`:线性管线;
+- `addHubSpoke`:中心辐射;
+- `addTintMatrix`:淡彩分组头分类矩阵;
+- `addConvergeFunnel`:汇聚漏斗;
+- `addChevronStages`:chevron 阶段带(可挂输出卡);
+- Diagram IR 构造器 `item/group/bandNode/groupBand`。
+
+`addTintMatrix → addConvergeFunnel → addChevronStages` 自上而下组合是参考 deck 的「整页结构大图」页型;demo 第 11 页有成品示例。
+
+这些组件各自表达有限结构。内容超出其模型时,用原生 PptxGenJS 或自定义 SVG 自绘,不要压缩、合并或删减事实迎合组件。
+
+## 内容块与图片
+
+导入 `content.js`:
+
+- `addTextBlock`、`addPanelList`;
+- `addCardGrid`、`addIconCards`;
+- `addTimeline`;
+- `addFigurePanel`;
+- `addSourceNote`(引用论文原图的页必须调用,见下);
+- `addRegionHeading`、`addPanel`;
+- `iconToPng`、`svgToPng`。
+
+凡是嵌入 `assets/papers/` 下论文原图的页面,必须同页调用 `addSourceNote(pres, slide, { source })`,来源文字取 `evidence-plan.json` 对应条目 `source` 字段的精简形式(如 `Wang et al., arXiv:2406.04692, Fig.1`)。再传 `url`(取 `source_url`)即可让引用可点击。它画在页脚行右侧,不与可选的密级文字冲突。漏调用会被 `audit_pptx.py --evidence-plan` 判为硬错误。
+
+卡片和面板只在真实分组关系存在时使用。本技能不内置预制图标库;需要识别锚点时用 `initial` 首字母徽标,或用 `svgToPng` 转自绘 SVG。
+
+## 兼容入口
+
+旧代码可以继续:
+
+```javascript
+const C = require("./scripts/components.js");
+```
+
+新代码建议按需:
+
+```javascript
+const Brand = require("./components/brand.js");
+const Charts = require("./components/charts.js");
+const Diagrams = require("./components/diagrams.js");
+const Content = require("./components/content.js");
+```
+
+或需要全部能力时:
+
+```javascript
+const C = require("./components/index.js");
+```
+
+完整参数说明见 [../pptxgenjs.md](../pptxgenjs.md)。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/pptxgenjs.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/pptxgenjs.md
new file mode 100644
index 0000000000..69c877e9ab
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/pptxgenjs.md
@@ -0,0 +1,153 @@
+# PptxGenJS 与组件 API
+
+先完成页面设计判断,再查本文件选择实现工具。品牌契约见 [base/template-contract.md](base/template-contract.md),工程边界见 [base/pptx-safety.md](base/pptx-safety.md)。
+
+## 导入
+
+按需导入:
+
+```javascript
+const Brand = require("./components/brand.js");
+const Charts = require("./components/charts.js");
+const Diagrams = require("./components/diagrams.js");
+const Content = require("./components/content.js");
+```
+
+完整兼容入口:
+
+```javascript
+const C = require("./components/index.js");
+// 或旧路径:require("./scripts/components.js")
+```
+
+现有组件按 10 × 5.625 英寸坐标系实现。官方母版流程由合并脚本统一等比放大并继承模板版式,不要在生成代码中手工换算到 13.34 英寸。
+
+## 品牌组件
+
+| API | 说明 |
+|---|---|
+| `addSlideTitle(pres, slide, {title, subtitle?, fontSize?})` | 内容页标题 |
+| `addSlideFooter(pres, slide, {pageNum?, confidentialityText?})` | 页脚、页码、Logo |
+| `addSummaryBanner(pres, slide, {text})` | 固定红色一句话总结条 |
+| `addContentChrome(pres, slide, {summary, pageNum?, confidentialityText?, footerMode?})` | 标准内容页固定底部框架;官方母版用 `footerMode:"master"`,独立兼容文件用默认 `drawn` |
+| `addOpeningSlide(pres, opts)` | 当前封面实现 |
+| `addTocSlide(pres, {title, sections})` | 当前目录实现 |
+| `addClosingSlide(pres)` | 当前结束页实现 |
+
+品牌组件负责模板外壳,不决定内容区构图。标准内容页必须调用一次 `addContentChrome`;不要单页改写总结条或右下 Logo 的坐标、颜色与样式。`master` 模式只画总结条,页码/密级/Logo 在合并后由官方版式继承。
+
+## 数据与图表
+
+| API | 适用边界 |
+|---|---|
+| `addDeckChart(pres, slide, {type, data, x, y, w, h, ...})` | 有可靠量化数据的原生图表;多余参数透传 pptxgenjs 并覆盖默认样式 |
+| `addChartWithInsights(pres, slide, {chart, insights, caveats})` | 一个主图表配解释与边界;只是可选现成构图 |
+| `addComparisonTable(pres, slide, {headers, rows, x, y, w, h, ...})` | 真实的多对象/多维度对照 |
+| `addKpiRow(pres, slide, {items, x, y, w, rings?})` | 少量可比较指标 |
+| `addSpectrumAxis(pres, slide, {ticks, x, y, w, ...})` | 连续程度或定位表达 |
+
+图表数据形状:
+
+```javascript
+[{ name: "系列", labels: ["A", "B"], values: [10, 20] }]
+```
+
+不得使用 demo、模板教学页或 skill 文档中的数字作为正式数据。
+
+柱图默认紧凑柱宽(`barGapWidthPct: 140`),且数据全为非负时数值轴锚定 0(`valAxisMinVal: 0`)——放任渲染器自动缩放会把轴起点抬到数据最小值附近,造成截断轴。确需放大差异时显式传 `valAxisMinVal`/`valAxisMaxVal` 覆盖,并保证差异解读仍然诚实。图表区建议放在白色圆角卡上并用 `addRegionHeading` 配黑色居中区域标题(或直接用 `addChartWithInsights`),不要让图表裸浮在一个细灰描边矩形里。
+
+## 图示
+
+| API | 表达模型 |
+|---|---|
+| `addPipelineDiagram` | 少量线性阶段;复杂分支不适用 |
+| `addSystemDiagram` | band/group/item 的声明式系统图;分层/管线/架构/闭环结构做主视觉时先试它,层间关系画成边(含反馈回边),表达不了再自绘 |
+| `addHubSpoke` | 一个中心与多个平级关联面 |
+| `addTintMatrix` | 淡彩分组头三行分类矩阵(族群/子类/条目式层级) |
+| `addConvergeFunnel` | 半透明漏斗+下箭头:上方内容汇聚到下方 |
+| `addChevronStages` | chevron 阶段带,每阶段可挂白色输出卡 |
+
+`addTintMatrix` → `addConvergeFunnel` → `addChevronStages` 自上而下组合,就是参考 deck「整页一张结构大图」的招牌页型(分类版图汇聚为行动路径)。三者也可单用:矩阵单独作分类页主区域、阶段带单独作路线区域。淡彩只出现在矩阵分组头,正文卡片保持白底红强调。
+
+### System Diagram IR
+
+```javascript
+const spec = {
+ title: "",
+ subtitle: "",
+ core_message: "",
+ diagram_type: "process",
+ bands: [
+ Diagrams.bandNode("input", "输入", [
+ Diagrams.item("request", "用户请求"),
+ ], "neutral", "full_width"),
+ ],
+ edges: [],
+};
+
+Diagrams.addSystemDiagram(pres, slide, { spec, x, y, w, h });
+```
+
+IR 支持 `bands`、`groups`、`nodes/items` 和 `edges`。它适合结构能自然映射到这些概念的页面;不匹配时直接使用 PptxGenJS/SVG 自绘。不要为了 IR 合并、删除或改写事实。
+
+## 内容与图片组件
+
+| API | 说明 |
+|---|---|
+| `addTextBlock` | 结构化文字区域 |
+| `addPanelList` | 带标题的列表区域 |
+| `addCardGrid` | 真实平级分组的卡片网格 |
+| `addIconCards` | 图标作为识别锚点的平级内容 |
+| `addTimeline` | 有真实日期/时间的里程碑 |
+| `addFigurePanel` | 1–3 张论文图或证据图的等比排版 |
+| `addRegionHeading` | 可选区域标题 |
+| `addPanel` | 基础矩形容器 |
+
+`addFigurePanel` 的 `figures`:
+
+```javascript
+[
+ { path: "assets/paper/figure.png", label: "方法框架" },
+]
+```
+
+图片保持比例;原图内部不按本 deck 色板重绘。
+
+## SVG 转位图
+
+```javascript
+const imageData = await Content.svgToPng(svgString, 512, 512);
+```
+
+本技能不内置预制图标库。卡片/列表的识别锚点用 `initial` 首字母徽标;确有必要的图形用自绘 SVG 经 `svgToPng` 转入,语义必须准确,不作装饰或页面填充。旧的 `Content.iconToPng` 只用于兼容既有 React icon 代码。
+
+## 裸 PptxGenJS 是正常路径
+
+组件不适合时,直接使用:
+
+- `slide.addText`;
+- `slide.addShape`;
+- `slide.addImage`;
+- `slide.addChart`;
+- `slide.addTable`;
+- 自定义 SVG。
+
+使用 `Brand.HW`、`Brand.TY` 和模板契约保持品牌一致,但构图可以完全自定义。
+
+## 检查行为
+
+始终启用:
+
+- 参数和数据合法性;
+- 缺失资源;
+- 几何重叠提示;
+- 文本/组件明显超限提示;
+- Diagram IR 无效结构。
+
+默认关闭纯审美密度提示。需要探索性建议时:
+
+```bash
+PPT_ADVISORY_QA=1 node slides.js
+```
+
+这些建议不能作为交付门禁,也不能覆盖页面的 `rhythm` 和设计意图。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/architecture-evidence.jpg b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/architecture-evidence.jpg
new file mode 100644
index 0000000000..66aa4952a0
Binary files /dev/null and b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/architecture-evidence.jpg differ
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/conclusion-editorial.jpg b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/conclusion-editorial.jpg
new file mode 100644
index 0000000000..a53b6f5129
Binary files /dev/null and b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/conclusion-editorial.jpg differ
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/evidence-workflow.jpg b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/evidence-workflow.jpg
new file mode 100644
index 0000000000..3f84f6379c
Binary files /dev/null and b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/evidence-workflow.jpg differ
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/evolution-landscape.jpg b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/evolution-landscape.jpg
new file mode 100644
index 0000000000..36d6d10e31
Binary files /dev/null and b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/evolution-landscape.jpg differ
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/index.yaml b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/index.yaml
new file mode 100644
index 0000000000..1c497b8980
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/index.yaml
@@ -0,0 +1,467 @@
+version: 2
+purpose: >-
+ 版面骨架库。每一项是一种可复用的版面骨架。
+ 设计页面前先通读全部 name,建立"有哪些骨架可选"的认识,再按内容挑一个。
+ 带 image 字段的条目可以打开对应图片确认细节;没有 image 的条目只有文字描述,
+ 按 skeleton 的分区图、rules 和 variants 理解即可,不要去找不存在的配图。
+ 骨架是选型参考,不是强制模板:它给出分区、比例和填满方式的参考方案,
+ 不规定坐标、颜色、数量和具体内容。内容需要时可以偏离骨架,
+ 但 common_rules 对所有页面硬性生效。
+
+
+common_rules:
+ - 标准内容页必须填满内容区,不得出现大块空白;内容不足时扩写正文或合并页面,不靠留白撑版面
+ - 所有区域顶端、底端、左右边界对齐到同一组轴线,区域之间只留必要的间距沟
+ - 内容必须结束在底部总结条上方,不得侵入页脚
+ - 骨架只描述空间关系;比例、区域数量和分组数量都随内容变化,不得当作固定模板
+ - 以上五条对所有页面硬性生效;layouts 里各项的 skeleton / rules / variants 是参考,可按内容偏离
+ - 同一 deck 内跨页复用同一套字号角色、颜色角色和对齐轴线
+
+layouts:
+ - id: problem-diagram-analysis
+ name: 左图右文 · 满版
+ image: problem-diagram-analysis.jpg
+ summary: 主图占左侧大半,右侧文字列与之等高,两栏都顶到页面边界
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +----------------------+ +--------------+
+ | | | 小标题 |
+ | | | 正文段 |
+ | 主图 ~55% | | 小标题 |
+ | | | 正文段 |
+ | | | 小标题 |
+ +----------------------+ +--------------+
+ +--------------- 总结条 ---------------+
+ rules:
+ - 左右约 55:40,中间留一条约 5% 的空白沟
+ - 两栏顶端对齐、底端也对齐,共同结束在总结条上方
+ - 主图撑满左栏,宽度不够就压缩图内元素间距,不要在图周围留边
+ - 右栏各段均分栏高,文字不足时把每段写长,而不是让下半栏空着
+ - 右栏写完整论证段(每段 3-4 行),不是短标签
+ - 图内可用有限彩色区分状态类别,连接线一律灰色
+ use_when:
+ - 结构关系和文字判断都要展示,且两边内容量都够撑满
+ avoid_when:
+ - 只有图或只有文字
+ - 文字只有三五个短标签,撑不满右栏
+ variants:
+ - 图文左右互换
+ - 主图换成照片、论文原图或数据图表
+ - 右栏两段或四段,段数由内容定
+
+ - id: evolution-landscape
+ name: 散点版图 · 曲线串联
+ image: evolution-landscape.jpg
+ summary: 多个信息卡自由散布在整版,用曲线串成一条时间或演进主线
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +------+ +------+
+ | 卡片 | +------+ | 卡片 |
+ +------+ | 卡片 | +------+
+ \ +------+ /
+ [节点]-------\ +------+ /
+ \ [节点]-| 卡片 |
+ +------+ \ +------+ +----+
+ | 卡片 | +------+ 图例
+ +------+ | 卡片 |
+ +------+
+ +--------------- 总结条 ---------------+
+ rules:
+ - 卡片位置服从主线走向,不排成栅格;主线可以是曲线而非直线
+ - 卡片大小随条目数变化,不强制等宽等高
+ - 主线上标注时间区间或阶段名,卡片内不重复标注
+ - 卡片之间保持足够间距,但整版四角都要有内容,不留空象限
+ - 需要区分类别时用一两种颜色,右下角配小图例
+ use_when:
+ - 跨时间的技术、机构或产品演进,条目数量多且分布不均
+ - 条目本身(名称、Logo)就是证据
+ avoid_when:
+ - 只有三到五步的简单流程
+ - 事件没有可靠时间顺序
+ variants:
+ - 主线横向、斜向或蛇形
+ - 卡片内用实体 Logo 或纯文字列表
+
+ - id: paper-reproduction
+ name: 左双图 · 右表加长文
+ image: paper-reproduction.jpg
+ summary: 左栏上下叠放两张结构图,右栏上方放数据表、下方放长文说明
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +------------------+ +-------------------+
+ | 结构图 1 | | 数据表 |
+ +------------------+ +-------------------+
+ | 图题(加粗) | | 小标题 |
+ +------------------+ | 正文条目 |
+ | 结构图 2 | | 正文条目 |
+ +------------------+ | 正文条目 |
+ | 图题(加粗) | | 正文条目 |
+ +------------------+ +-------------------+
+ rules:
+ - 左右约 45:52;左栏两图上下等分,各自带一行加粗图题
+ - 图按原始宽高比缩放,宁可左右留窄边也不拉伸
+ - 右栏表格只占上部约三分之一,其余留给长文条目
+ - 长文条目用主题色标签词起头,后接完整句子,逐条撑满右栏高度
+ - 两栏底端对齐
+ use_when:
+ - 同时需要展示原始结构图和量化结果
+ - 有两张同族结构图需要对照
+ avoid_when:
+ - 只有一张图(改用左图右文)
+ - 没有可验证的数据表
+ variants:
+ - 左栏改为一张大图加一张小图
+ - 右栏表格换成数据图表
+
+ - id: evidence-workflow
+ name: 编号流程 · 不等宽多列
+ image: evidence-workflow.jpg
+ summary: 若干带编号的步骤块横向排布,宽度按证据量分配,箭头只负责导读
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +-------------+ > +-------------+ +------+
+ | (1) 步骤名 | | (2) 步骤名 | | (6) |
+ | +---------+ | | +---------+ | +------+
+ | | 截图/码 | | | | 截图/码 | | ^
+ | +---------+ | | +---------+ | |
+ | +---------+ | +-------------+ +------+
+ | | 截图/码 | | +-------------+ | (5) |
+ | +---------+ | | (3) 步骤名 | | |
+ +-------------+ +-------------+ +------+
+ rules:
+ - 列宽按该步的证据体量分配,不等宽是常态
+ - 编号用主题色圆形徽章置于步骤名左侧,编号连续贯穿全页
+ - 截图、代码块按原比例嵌入,暗色截图与白底形成对比,不加装饰边框
+ - 步骤块用浅灰虚线框分组,箭头只做相邻指向,不画长距离连线
+ - 允许折行排布(上排从左到右,下排从右到左),保持阅读连贯
+ use_when:
+ - 有真实的截图、代码或运行结果串成一条处理链路
+ - 步骤数在 4-6 之间
+ avoid_when:
+ - 只有抽象流程,没有真实过程材料
+ - 步骤超过 6 个(拆页或改用管线图)
+ variants:
+ - 单排横向或双排折行
+ - 末尾加一个"结果/入库"终点块
+
+ - id: architecture-evidence
+ name: 外框内左文右图
+ image: architecture-evidence.jpg
+ summary: 整页套一个大圆角外框,框内左侧写论证、右侧放图表与数据解读
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +-----------------------------------------+
+ | 框内居中副标题 |
+ | [] 小标题 | +-------------------+ |
+ | > 论点段落 | | 数据图表 | |
+ | > 论点段落 | +-------------------+ |
+ | [] 小标题 | 数据解读条目 |
+ | 论述段落 | 数据解读条目 |
+ | [] 小标题 | 数据解读条目 |
+ | 论述段落 | 主题色结论句 |
+ +-----------------------------------------+
+ +--------------- 总结条 ---------------+
+ rules:
+ - 大外框包住整个论证,框内不再给每段套小框
+ - 框内左右约 50:45;左文右图,文字与图表权重接近
+ - 左侧用主题色小方块加主题色小标题分节,节内用箭头符号列论点
+ - 右侧图表下方紧跟数据解读条目,末行用主题色写出结论
+ - 术语强调与结论强调各用一种固定处理(如术语加粗、结论用主题色),两者不混用
+ use_when:
+ - 需要机制解释、优劣分析和实验证据同时出现
+ - 一张原始图表是结论的关键证据
+ avoid_when:
+ - 只有架构关系或只有实验图
+ - 内容量撑不满一个整页外框
+ variants:
+ - 左右互换
+ - 左侧分节数量随内容增减
+
+ - id: taxonomy-matrix
+ name: 双栏并列 · 三层嵌套
+ image: taxonomy-matrix.jpg
+ summary: 左右两个大框各承载一个分类体系,框内色块分组,组内白色节点
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +-------------------+ +------------------+
+ | 体系 A 标题 | | 体系 B 标题 |
+ | +---------------+ | | +--------------+ |
+ | | 分组名(色块)| | | | 分组名(色块)| |
+ | | [节点][节点] | | | | [节点][节点] | |
+ | | [节点][节点] | | | +--------------+ |
+ | +---------------+ | | +--------------+ |
+ | +---------------+ | | | 分组名(色块)| |
+ | | 分组名(色块)| | | | [节点][节点] | |
+ | | [节点][节点] | | | +--------------+ |
+ +-------------------+ +------------------+
+ rules:
+ - 左右等宽并列,各自套一个白底细边外框
+ - 框内分组用浅色块承载,组名居中;组内条目用白色小节点
+ - 同一层级的节点等高,一行放 2-3 个,行数随条目数增加
+ - 两栏的分组数量可以不同,但底端必须齐平
+ - 浅色只用于区分分组语义,节点一律白底
+ use_when:
+ - 两个体系需要并列对照,且各自有明确的层级
+ - 条目总数较多但可归入少数分组
+ avoid_when:
+ - 内容只是平级要点或简单对比
+ - 只有一个体系(改用整页单栏分组)
+ variants:
+ - 两栏改三栏
+ - 分组内节点单列排布
+
+ - id: conclusion-editorial
+ name: 通栏双块 · 长文条目
+ image: conclusion-editorial.jpg
+ summary: 两个通栏圆角框上下排布,每框内是主题色标题加数条 2-3 行的长句
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +-----------------------------------------+
+ | 主题色小标题 |
+ | · 加粗引导词:完整长句,占 2-3 行 ..... |
+ | · 加粗引导词:完整长句,占 2-3 行 ..... |
+ | · 加粗引导词:完整长句,占 2-3 行 ..... |
+ +-----------------------------------------+
+ +-----------------------------------------+
+ | 主题色小标题 |
+ | · 加粗引导词:完整长句,占 2-3 行 ..... |
+ | · 加粗引导词:完整长句,占 2-3 行 ..... |
+ +-----------------------------------------+
+ rules:
+ - 两块都是通栏宽度,上下堆叠,块间留一道等距间隙
+ - 每条必须是 2-3 行的完整长句,用加粗引导词起头再接冒号
+ - 块高按条目数分配,两块加起来撑满内容区
+ - 纯文字页,不放图标、卡片和装饰图形
+ - 字号保持正文级,不靠放大字号填充版面
+ use_when:
+ - 章节末整合洞察与机会,视觉证据已在前文建立
+ - 内容以完整判断为主
+ avoid_when:
+ - 仍需展示关键数据、关系或图像证据
+ - 只有短标签,写不出长句
+ variants:
+ - 两块改三块
+ - 每块内条目数随内容增减
+
+ - id: timeline-slide
+ name: 横向时间轴 · 图文三层
+ summary: 顶部导语段,中间一条横向时间轴,下方一排等高照片,底部引语
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ | 导语段落(3-4 行通栏) +------+ |
+ | | 小图 | |
+ | 说明 说明 说明 说明 说明 +------+ |
+ |----o------o------o------o------o------o->|
+ | 日期 日期 日期 日期 日期 日期 |
+ | +----+ +----+ +----+ +----+ +----+ +----+|
+ | |照片| |照片| |照片| |照片| |照片| |照片||
+ | +----+ +----+ +----+ +----+ +----+ +----+|
+ | " 引语段落 ................." |
+ | — 署名 / 来源 |
+ rules:
+ - 时间轴通栏贯穿,节点等距,主题色圆点标注
+ - 节点说明在轴上方、日期在轴下方,两者垂直对齐到同一节点
+ - 照片一排等高等宽,紧贴轴下方,之间留窄缝
+ - 顶部导语通栏 3-4 行,右上角可放一个小配图补足空白
+ - 底部引语用引号符号起止,署名右对齐
+ use_when:
+ - 内容按真实时间演进,且每个节点都有照片或凭证
+ - 里程碑数量在 5-7 个
+ avoid_when:
+ - 只是流程而非时间演进
+ - 没有可用的过程照片
+ variants:
+ - 去掉底部引语,照片放大
+ - 节点数变化,但保持等距
+
+ - id: achievement-slide
+ name: 斜切主图 · 底部指标
+ summary: 上部左图右文以斜切边分割,下部一排图标加大数字
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +------------------\ +------------------+
+ | \ | 小标题 |
+ | 主照片 \ | --- |
+ | \| 大字号陈述句 |
+ | | 占 2 行 |
+ +----------------------+------------------+
+ (icon) (icon) (icon) (icon)
+ 20.8万员工 54%占比 170+国家 30亿+联接
+ rules:
+ - 上部约占内容区三分之二,下部指标带占三分之一
+ - 主图与文字块之间用斜切边分隔,斜边角度全 deck 统一
+ - 右侧文字块只放一个小标题、一条主题色短线和一段大字号陈述
+ - 底部指标等距排布,图标在上、数字加标签在下,数字用主题色
+ - 指标带通栏,左右两端与上部区块对齐
+ use_when:
+ - 有一张高质量主照片,且有 3-5 个真实指标
+ - 需要定性叙述与定量证据同时出现
+ avoid_when:
+ - 没有真实照片或可靠指标
+ - 指标之间有复杂关系(应改用图表)
+ variants:
+ - 斜切改为直切
+ - 图文左右互换
+
+ - id: highlight-slide
+ name: 2x2 卡片 · 卡内图文
+ summary: 四个等大灰底卡片排成两行两列,每张卡内左图右文加底部数字
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ +--------------------+ +------------------+
+ | 主题色卡标题 | | 主题色卡标题 |
+ | +-----+ 说明段落 | | +-----+ 说明段落 |
+ | | 图片| 说明段落 | | | 图片| 说明段落 |
+ | +-----+ --------- | | +-----+ -------- |
+ | 2 场 20+ 场 | | 1 场 1 个 |
+ +--------------------+ +------------------+
+ +--------------------+ +------------------+
+ | 主题色卡标题 | | 主题色卡标题 |
+ | +-----+ 说明段落 | | +-----+ 说明段落 |
+ | | 图片| 说明段落 | | | 图片| 说明段落 |
+ +--------------------+ +------------------+
+ rules:
+ - 四卡等大、严格对齐,卡间留等距缝隙,整体撑满内容区
+ - 卡内左图右文,图片按原比例,宽度约占卡宽三分之一
+ - 卡标题主题色加粗置于卡片左上,说明段落 4-6 行
+ - 卡底用一条细主题色线分隔,线下放主题色大数字加灰色单位标签
+ - 只有内容真正平级时才用;权重不同的内容不要硬塞进等大卡片
+ use_when:
+ - 四个平级主题,各自都有图片、说明和量化结果
+ - 内容确实适合矩阵化扫描
+ avoid_when:
+ - 各项权重明显不同
+ - 内容之间有流程、因果或时间关系
+ - 为凑数量而拆分内容
+ variants:
+ - 改为 1x3 或 1x2
+ - 去掉图片,仅文字加数字
+
+ - id: toc-slide
+ name: 单列目录 · 居中
+ summary: 浅灰底,左上角标题配主题色短线,中央偏左一列主题色方块编号加章节名
+ skeleton: |
+ +-----------------------------------------+
+ | 目录 |
+ | ==== |
+ | |
+ | [1] 章节名称 |
+ | |
+ | [2] 章节名称 |
+ | |
+ | [3] 章节名称 |
+ | |
+ | [4] 章节名称 |
+ +-----------------------------------------+
+ rules:
+ - 整页浅灰底,区别于白底内容页
+ - 标题置左上,下方一条主题色短粗线
+ - 编号用主题色实心方块加白字,方块与章节名基线对齐
+ - 条目整体在页面中央偏左,条目间距均等,随条目数自适应
+ - 不加页码、进度条和装饰图形
+ use_when:
+ - Deck 需要正式目录或章节导航
+ - 一级章节 3-7 个
+ avoid_when:
+ - 页数很少,目录不增加导航价值
+ - 用户模板提供了不同的目录结构
+ variants:
+ - 章节名后加一行灰色小字说明
+ - 当前章节高亮(分节页复用时)
+
+ - id: complex-slide
+ name: 矩阵分组 · 漏斗汇聚 · 路径带
+ summary: 上部行标签加多族群矩阵,中间大箭头汇聚,下部三段横向路径带
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ | 导语句(主题色强调关键词) |
+ |[标签]| 族群A | 族群B |族群C |族群D |
+ |[标签]| 类1|类2| 类3|类4|类5| 类6|类7|类8 |
+ |[标签]| [] | [] | [] | []| []| [] | []|[]|
+ | \___________ ____________/ |
+ | \/ (汇聚箭头) |
+ | ---- 路径带标题 ---- |
+ | [ 阶段一 ] > [ 阶段二 ] > [ 阶段三 ] |
+ | +---------+ +---------+ +---------+ |
+ | | 卡片 | | 卡片 | | 卡片 | |
+ +-----------------------------------------+
+ rules:
+ - 上部用最左一列窄标签列标注每行含义,右侧族群列宽按子类数量分配
+ - 族群表头用浅色块区分,子类和条目一律白底
+ - 中部用一个大号浅灰箭头把上部整体汇聚到下部,箭头跨越多列
+ - 下部路径带用箭头形色块表示阶段,阶段下方挂卡片
+ - 上下两部分左右边界对齐,整页无空白象限
+ use_when:
+ - 需要同时表达分类体系和它导出的路径或结论
+ - 内容量足以填满一个高密度整页
+ avoid_when:
+ - 信息只是简单线性流程
+ - 缺少足够内容支撑两层结构
+ variants:
+ - 去掉汇聚箭头,两部分用细线分隔
+ - 路径带阶段数变化
+
+ - id: explanation-slide
+ name: 顶部阶段带 · 中部因素列 · 底部结论带
+ summary: 顶部箭头形阶段带,中部大框内多列图标加长文,底部箭头形结论带
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ | [ 阶段一 >][ 阶段二 >][ 阶段三 >] |
+ | +-------------------------------------+ |
+ | | (icon) (icon) (icon) (icon) (icon) | |
+ | | 标题 标题 标题 标题 标题 | |
+ | | ----- ----- ----- ----- ----- | |
+ | | 正文段 正文段 正文段 正文段 正文段 | |
+ | | 正文段 正文段 正文段 正文段 正文段 | |
+ | +-------------------------------------+ |
+ | [ ...... 底部结论带(箭头形) ...... ] |
+ +-----------------------------------------+
+ rules:
+ - 顶部阶段带和底部结论带都用箭头形色块,宽度通栏
+ - 中部一个大浅灰框包住所有因素列,列间不再加分隔框
+ - 每列结构固定:圆形图标、主题色标题、一条细主题色线、多行正文
+ - 各列等宽,正文行数尽量接近,共同撑满框高
+ - 图标只作识别锚点,正文承担全部信息
+ use_when:
+ - 多个平级驱动因素共同支持一个结论
+ - 每个因素都能写出 3-5 行完整解释
+ avoid_when:
+ - 因素之间有明确先后或因果链
+ - 各因素权重不平级
+ - 只能写出短标签
+ variants:
+ - 因素列 3-5 列,由内容定
+ - 去掉顶部阶段带,只保留因素区和结论带
+
+ - id: product-slide
+ name: 左版图 · 右侧栏 · 底部指标行
+ summary: 左侧多行分层版图,右侧一条竖向侧栏,底部圆环数字加标签带
+ skeleton: |
+ +---------------- 通栏标题 ----------------+
+ | [层名] | 域名 | [][][][][] |P| +------+ |
+ | | | |M| | 认证 | |
+ | [层名] | 域名 | [][][][] | | +------+ |
+ | | | | | | 认证 | |
+ | [层名] | 域名 | [][][][][] | | +------+ |
+ | | 域名 | [][][] | | | 认证 | |
+ | | 域名 | [][] | | +------+ |
+ | (o) (o) (o) (o) (o) |
+ | 23 110+ 5,000+ 100万+ 37,000+ |
+ | +-------------------------------------+ |
+ | | 标签 标签 标签 标签 标签 | |
+ +-----------------------------------------+
+ rules:
+ - 左侧版图分三列:层名标签列、领域名列、条目块区,层名用主题色
+ - 同层内的领域行数不等,条目块等高不等宽,按名称长度自适应
+ - 右侧窄竖栏承载贯穿性内容,最右侧单独一栏放徽章类图形
+ - 底部指标用浅灰圆环衬底加主题色数字,下方一条通栏浅灰标签带
+ - 数据口径注释放右下角小字斜体
+ use_when:
+ - 展示复杂产品或能力版图,并配套规模指标
+ - 页面核心是体系覆盖范围
+ avoid_when:
+ - 内容只是少数平级要点
+ - 没有真实层级或分类依据
+ variants:
+ - 去掉右侧徽章栏
+ - 底部指标数量随内容变化
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/paper-reproduction.jpg b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/paper-reproduction.jpg
new file mode 100644
index 0000000000..e17f35ca19
Binary files /dev/null and b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/paper-reproduction.jpg differ
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/problem-diagram-analysis.jpg b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/problem-diagram-analysis.jpg
new file mode 100644
index 0000000000..7b8333b4a4
Binary files /dev/null and b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/problem-diagram-analysis.jpg differ
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/taxonomy-matrix.jpg b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/taxonomy-matrix.jpg
new file mode 100644
index 0000000000..2f4e76ab93
Binary files /dev/null and b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/references/taxonomy-matrix.jpg differ
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/audit_pptx.py b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/audit_pptx.py
new file mode 100644
index 0000000000..fd605429b2
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/audit_pptx.py
@@ -0,0 +1,538 @@
+#!/usr/bin/env python3
+"""Structural and readability audit for generated PPTX files.
+
+Checks the package, canvas/master/layout inheritance, slide bounds,
+font floors, page count, and the fixed red summary band declared by an
+execution lock. The visual contact sheet still requires Agent inspection.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import logging
+import posixpath
+import re
+import sys
+import zipfile
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+# Diagnostics go to stderr through logging; the audit report itself is program
+# output and goes to stdout via emit().
+LOGGER = logging.getLogger("audit_pptx")
+
+
+# Program output (report bodies, --json payloads) goes to stdout, diagnostics
+# to stderr. Both travel through logging; this logger owns stdout, keeps a bare
+# "%(message)s" format so the text is unchanged, and does not propagate so the
+# stderr root handler never sees it.
+STDOUT_LOGGER = logging.getLogger("audit_pptx.stdout")
+STDOUT_LOGGER.propagate = False
+STDOUT_LOGGER.setLevel(logging.INFO)
+_stdout_handler = logging.StreamHandler(sys.stdout)
+_stdout_handler.setFormatter(logging.Formatter("%(message)s"))
+STDOUT_LOGGER.addHandler(_stdout_handler)
+
+
+def emit(line: str) -> None:
+ STDOUT_LOGGER.info(line)
+
+
+NS = {
+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",
+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
+ "pr": "http://schemas.openxmlformats.org/package/2006/relationships",
+}
+
+
+def local(tag: str) -> str:
+ return tag.rsplit("}", 1)[-1]
+
+
+def xml(zf: zipfile.ZipFile, name: str) -> ET.Element:
+ return ET.fromstring(zf.read(name))
+
+
+def slide_size(zf: zipfile.ZipFile) -> tuple[int, int]:
+ root = xml(zf, "ppt/presentation.xml")
+ node = root.find("p:sldSz", NS)
+ if node is None:
+ return 12192000, 6858000
+ return int(node.get("cx", 12192000)), int(node.get("cy", 6858000))
+
+
+def slide_order(zf: zipfile.ZipFile) -> list[str]:
+ rels = xml(zf, "ppt/_rels/presentation.xml.rels")
+ by_id = {
+ rel.get("Id"): posixpath.basename(rel.get("Target", ""))
+ for rel in rels.findall("pr:Relationship", NS)
+ if rel.get("Type", "").endswith("/slide")
+ }
+ presentation = xml(zf, "ppt/presentation.xml")
+ return [
+ by_id[node.get(f"{{{NS['r']}}}id")]
+ for node in presentation.findall(".//p:sldId", NS)
+ if node.get(f"{{{NS['r']}}}id") in by_id
+ ]
+
+
+SOURCE_NOTE_RE = re.compile(r"来源\s*[::]|Source\s*:", re.IGNORECASE)
+
+
+def paper_figure_digests(plan_path: Path) -> dict[str, str]:
+ """sha256 -> evidence id, for every paper figure the plan marks as used.
+
+ Matching on image bytes rather than on the plan's page field keeps the check
+ independent of deck ordering and of the renaming merge_slides.py does
+ (assets/papers/x.png becomes ppt/media/image7.png). merge copies with
+ shutil.copy2, so the bytes survive intact.
+ """
+ plan = json.loads(plan_path.read_text(encoding="utf-8"))
+ base = plan_path.parent
+ asset_root = base / plan.get("asset_root", "assets")
+ digests: dict[str, str] = {}
+ for entry in plan.get("items", []):
+ if entry.get("kind") != "paper-figure" or entry.get("status") != "used":
+ continue
+ rel = entry.get("path")
+ if not rel:
+ continue
+ asset = base / rel
+ if not asset.exists():
+ asset = asset_root / "papers" / Path(rel).name
+ if asset.exists():
+ digests[hashlib.sha256(asset.read_bytes()).hexdigest()] = entry.get("id") or rel
+ return digests
+
+
+def slide_media(zf: zipfile.ZipFile, slide_name: str) -> list[str]:
+ rel_name = f"ppt/slides/_rels/{slide_name}.rels"
+ if rel_name not in zf.namelist():
+ return []
+ media = []
+ for rel in xml(zf, rel_name).findall("pr:Relationship", NS):
+ if rel.get("Type", "").endswith("/image"):
+ target = posixpath.normpath(posixpath.join("ppt/slides", rel.get("Target", "")))
+ media.append(target)
+ return media
+
+
+def slide_layout(zf: zipfile.ZipFile, slide_name: str) -> str | None:
+ rel_name = f"ppt/slides/_rels/{slide_name}.rels"
+ if rel_name not in zf.namelist():
+ return None
+ for rel in xml(zf, rel_name).findall("pr:Relationship", NS):
+ if rel.get("Type", "").endswith("/slideLayout"):
+ return posixpath.basename(rel.get("Target", ""))
+ return None
+
+
+def explicit_font_sizes(root: ET.Element) -> list[float]:
+ sizes = []
+ for node in root.iter():
+ if local(node.tag) in {"rPr", "defRPr", "endParaRPr"} and node.get("sz"):
+ sizes.append(int(node.get("sz")) / 100)
+ return sizes
+
+
+# Footer chrome starts here, as a fraction of canvas height. The official master
+# puts its footer row at 6.95" on a 7.50" canvas (92.7%).
+FOOTER_BAND_TOP = 0.90
+
+# Components author at 10 x 5.625in; merge_slides scales the page (and its font
+# sizes) up to the official canvas. Sizes below are expressed in authoring
+# points and rescaled by width / COMPAT_CANVAS_W, so the same threshold works
+# for merged decks and for standalone 10in files.
+COMPAT_CANVAS_W = 9144000
+COMPAT_CANVAS_H = 5143500
+TOC_ROLES = {"toc", "fixed-toc", "contents"}
+# Sits between addTocSlide's smallest sanctioned tier (13pt badge numbers) and
+# the ~10pt description lines hand-drawn variants add, so neither rounding in
+# the scale nor a point of tuning in either tier flips the verdict.
+TOC_MIN_TIER_PT = 12
+
+
+def compat_scale(width: int, height: int) -> float:
+ """The factor merge_slides applied to authoring coordinates and font sizes."""
+ return min(width / COMPAT_CANVAS_W, height / COMPAT_CANVAS_H)
+
+
+# addSlideTitle draws the title at y=0.18 and the subtitle at y=0.68 h=0.24, so
+# the subtitle is the only sanctioned text in this authoring-inch band.
+SUBTITLE_BAND = (0.60, 0.95)
+# "Wang et al., 2024" / "Li & Chen et al." -- an author citation used as the
+# opening of the line, which is what turns a subtitle into a reference entry.
+AUTHOR_LEAD_RE = re.compile(
+ r"^\s*[A-Z][A-Za-z\-']+(?:\s*(?:&|and|,)\s*[A-Z][A-Za-z\-']+)*\s+et\s+al\.?",
+)
+# Reference furniture that carries no information about what the page argues.
+CITATION_TOKEN_RE = re.compile(
+ r"et\s+al\.?|arXiv\s*:\s*\d{4}\.\d{4,5}(?:v\d+)?|doi\s*:\s*\S+|"
+ r"https?://\S+|[Ss]ection\s*\d+(?:\.\d+)*|§\s*\d+(?:\.\d+)*|\b(?:19|20)\d{2}\b",
+ re.IGNORECASE,
+)
+SUBTITLE_MIN_SUBSTANCE = 6 # visual chars left once citation furniture is gone
+
+
+def visual_len(text: str) -> float:
+ """Same width model the components use: CJK 1em, ASCII ~0.55em."""
+ return sum(1 if ord(ch) > 0x2E7F else 0.55 for ch in text)
+
+
+def subtitle_text(root: ET.Element, height: int, scale: float) -> str | None:
+ """Text of the shape sitting in the subtitle band, if any."""
+ tree = root.find("./p:cSld/p:spTree", NS)
+ if tree is None:
+ return None
+ low, high = (v * 914400 * scale for v in SUBTITLE_BAND)
+ for shape in tree:
+ if local(shape.tag) != "sp":
+ continue
+ rect = shape_rect(shape)
+ if rect and low <= rect[1] < high:
+ text = text_of(shape)
+ if text:
+ return text
+ return None
+
+
+def subtitle_defects(text: str) -> list[str]:
+ """Why this subtitle reads as a citation rather than as a statement."""
+ problems = []
+ if AUTHOR_LEAD_RE.match(text):
+ problems.append(
+ "opens with an author citation; lead with the full work title "
+ "(e.g. \"Mixture-of-Agents Enhances Large Language Model Capabilities\") "
+ "and put the reference in the footer via addSourceNote"
+ )
+ substance = CITATION_TOKEN_RE.sub("", text)
+ substance = re.sub(r"[\s,.;:()()\[\]—–\-·/]+", "", substance)
+ if visual_len(substance) < SUBTITLE_MIN_SUBSTANCE:
+ problems.append(
+ "carries only reference furniture; say what the page establishes, "
+ "not where it came from"
+ )
+ return problems
+
+
+def body_font_sizes(root: ET.Element, height: int) -> list[float]:
+ """Font sizes outside the footer band.
+
+ The body-minimum warning is about readability of actual content. Footer
+ chrome -- page number, confidentiality line, source note -- is deliberately
+ ~7pt and the official master's own footer runs at 9.74pt, below the same
+ threshold. Counting it produced a warning on every page of every deck, which
+ is the fastest way to teach everyone to ignore the warning column.
+ """
+ cutoff = height * FOOTER_BAND_TOP
+ tree = root.find("./p:cSld/p:spTree", NS)
+ if tree is None:
+ return explicit_font_sizes(root)
+ sizes = []
+ # Top-level shapes only: sp, pic, graphicFrame (tables/charts) and grpSp all
+ # carry their own transform, so one pass covers table and group text too.
+ for shape in tree:
+ if local(shape.tag) not in {"sp", "pic", "graphicFrame", "grpSp"}:
+ continue
+ rect = shape_rect(shape)
+ if rect and rect[1] >= cutoff:
+ continue
+ for node in shape.iter():
+ if local(node.tag) in {"rPr", "defRPr", "endParaRPr"} and node.get("sz"):
+ sizes.append(int(node.get("sz")) / 100)
+ return sizes
+
+
+def shape_rect(shape: ET.Element) -> tuple[int, int, int, int] | None:
+ transform = shape.find("./p:spPr/a:xfrm", NS)
+ if transform is None:
+ transform = shape.find("./p:picPr/a:xfrm", NS)
+ if transform is None:
+ transform = shape.find("./p:xfrm", NS)
+ if transform is None:
+ return None
+ off = transform.find("a:off", NS)
+ ext = transform.find("a:ext", NS)
+ if off is None or ext is None:
+ return None
+ return tuple(int(node.get(attr, 0)) for node, attr in ((off, "x"), (off, "y"), (ext, "cx"), (ext, "cy")))
+
+
+def text_of(shape: ET.Element) -> str:
+ return "".join(node.text or "" for node in shape.findall(".//a:t", NS)).strip()
+
+
+def summary_band(root: ET.Element, width: int, height: int, fill: str) -> bool:
+ """True if a full-width filled band sits in the footer zone.
+
+ `fill` comes from the lock's brand.summary_banner.fill, so retheming the
+ deck does not require touching this check.
+ """
+ wanted = fill.upper().lstrip("#")
+ for shape in root.findall(".//p:sp", NS):
+ rect = shape_rect(shape)
+ if not rect:
+ continue
+ x, y, w, h = rect
+ color = shape.find("./p:spPr/a:solidFill/a:srgbClr", NS)
+ value = (color.get("val", "").upper() if color is not None else "")
+ if value != wanted:
+ continue
+ sits_in_footer_band = y > height * 0.75
+ spans_page_width = w > width * 0.75
+ thick_enough = h > height * 0.035
+ if sits_in_footer_band and spans_page_width and thick_enough:
+ return True
+ return False
+
+
+def audit(args: argparse.Namespace) -> dict:
+ errors: list[str] = []
+ warnings: list[str] = []
+ pptx = Path(args.pptx).resolve()
+ if not pptx.exists():
+ raise FileNotFoundError(pptx)
+
+ lock = None
+ if args.lock:
+ lock = json.loads(Path(args.lock).read_text(encoding="utf-8"))
+
+ with zipfile.ZipFile(pptx) as zf:
+ names = set(zf.namelist())
+ required = {"[Content_Types].xml", "ppt/presentation.xml", "ppt/_rels/presentation.xml.rels"}
+ missing = sorted(required - names)
+ if missing:
+ errors.append(f"missing required package parts: {', '.join(missing)}")
+
+ width, height = slide_size(zf)
+ slides = slide_order(zf)
+ masters = sorted(name for name in names if re.fullmatch(r"ppt/slideMasters/slideMaster\d+\.xml", name))
+ layouts = sorted(name for name in names if re.fullmatch(r"ppt/slideLayouts/slideLayout\d+\.xml", name))
+
+ template_layout_names: set[str] = set()
+ if args.template:
+ with zipfile.ZipFile(Path(args.template).resolve()) as tz:
+ template_size = slide_size(tz)
+ template_masters = [
+ name for name in tz.namelist()
+ if re.fullmatch(r"ppt/slideMasters/slideMaster\d+\.xml", name)
+ ]
+ template_layouts = [
+ name for name in tz.namelist()
+ if re.fullmatch(r"ppt/slideLayouts/slideLayout\d+\.xml", name)
+ ]
+ template_layout_names = {posixpath.basename(name) for name in template_layouts}
+ if (width, height) != template_size:
+ errors.append(
+ f"canvas {width}x{height} does not match official template "
+ f"{template_size[0]}x{template_size[1]}"
+ )
+ if len(masters) < len(template_masters):
+ errors.append(f"only {len(masters)} masters; official template has {len(template_masters)}")
+ if len(layouts) < len(template_layouts):
+ errors.append(f"only {len(layouts)} layouts; official template has {len(template_layouts)}")
+
+ if lock and len(slides) != len(lock.get("pages", [])):
+ errors.append(
+ f"slide count {len(slides)} does not match execution lock "
+ f"page count {len(lock.get('pages', []))}"
+ )
+
+ paper_digests: dict[str, str] = {}
+ if args.evidence_plan:
+ paper_digests = paper_figure_digests(Path(args.evidence_plan).resolve())
+ media_digest = {
+ name: hashlib.sha256(zf.read(name)).hexdigest()
+ for name in names
+ if name.startswith("ppt/media/")
+ }
+
+ all_sizes: list[float] = []
+ slide_reports = []
+ for index, slide_name in enumerate(slides, 1):
+ part = f"ppt/slides/{slide_name}"
+ if part not in names:
+ errors.append(f"slide {index} relationship points to missing {part}")
+ continue
+ root = xml(zf, part)
+ slide_text = " ".join(node.text or "" for node in root.findall(".//a:t", NS))
+ layout = slide_layout(zf, slide_name)
+ if not layout:
+ errors.append(f"slide {index} has no slideLayout relationship")
+ elif template_layout_names and layout not in template_layout_names:
+ errors.append(f"slide {index} uses non-template layout {layout}")
+
+ # A pasted paper figure must carry its citation on the page itself.
+ # Only runs when --evidence-plan is supplied, so existing callers
+ # keep their current behaviour.
+ cited = sorted({
+ paper_digests[media_digest[part_name]]
+ for part_name in slide_media(zf, slide_name)
+ if media_digest.get(part_name) in paper_digests
+ })
+ if cited and not SOURCE_NOTE_RE.search(slide_text):
+ errors.append(
+ f"slide {index} embeds paper figure(s) {', '.join(cited)} "
+ f"but carries no source note; call addSourceNote(pres, slide, "
+ f"{{ source: ... }}) with the evidence plan's source field"
+ )
+
+ sizes = explicit_font_sizes(root)
+ all_sizes.extend(sizes)
+ below_absolute = sorted(size for size in sizes if size < args.absolute_min_font)
+ if below_absolute:
+ errors.append(
+ f"slide {index} has explicit font size below "
+ f"{args.absolute_min_font}pt: {below_absolute[0]:g}pt"
+ )
+ # Footer chrome is excluded here on purpose -- see body_font_sizes.
+ # The absolute floor above still applies to every run on the page.
+ below_body = [size for size in body_font_sizes(root, height) if size < args.body_min_font]
+ if below_body:
+ warnings.append(f"slide {index} has {len(below_body)} text runs below {args.body_min_font}pt")
+
+ out_of_bounds = 0
+ top_text_sizes = []
+ sp_tree = root.find(".//p:spTree", NS)
+ if sp_tree is not None:
+ for shape in list(sp_tree):
+ rect = shape_rect(shape)
+ if not rect:
+ continue
+ x, y, w, h = rect
+ starts_off_canvas = x < -1000 or y < -1000
+ ends_off_canvas = x + w > width + 1000 or y + h > height + 1000
+ if starts_off_canvas or ends_off_canvas:
+ out_of_bounds += 1
+ if text_of(shape) and y < height * 0.14:
+ top_text_sizes.extend(explicit_font_sizes(shape))
+ if out_of_bounds:
+ errors.append(f"slide {index} has {out_of_bounds} object(s) outside the canvas")
+
+ role = None
+ if lock and index <= len(lock.get("pages", [])):
+ page = lock["pages"][index - 1]
+ role = page.get("role")
+ if role == "standard-content":
+ band_fill = lock.get("brand", {}).get("summary_banner", {}).get("fill", "4472C4")
+ if not summary_band(root, width, height, band_fill):
+ errors.append(f"slide {index} standard-content page is missing the fixed summary band")
+ typography = lock.get("deck", {}).get("typography_policy", {})
+ title_min = typography.get("title_min_pt", args.title_min_font)
+ if not top_text_sizes or max(top_text_sizes) < title_min:
+ errors.append(f"slide {index} content title is missing or below {title_min}pt")
+ # Under footer_mode "master" the page must not draw its own
+ # footer — the inherited master already has one, and two
+ # stacked footers is the classic duplicate-chrome bug.
+ # There is no fixed footer wording to match on, so this only
+ # fires when the lock declares a classification string:
+ # finding it in the slide's own text means the page drew it.
+ # (qa_geometry.py catches the general overlap case.)
+ marking = lock.get("brand", {}).get("footer", {}).get("classification")
+ if (
+ lock.get("template", {}).get("footer_mode") == "master"
+ and marking
+ and marking.lower() in slide_text.lower()
+ ):
+ errors.append(f"slide {index} draws a slide-level footer while footer_mode is master")
+ # The subtitle is the page's second sentence, not its
+ # bibliography. "Wang et al., 2024 (arXiv:2406.04692)" tells
+ # a reader nothing the footer citation does not already say.
+ subtitle = subtitle_text(root, height, compat_scale(width, height))
+ if subtitle:
+ for problem in subtitle_defects(subtitle):
+ errors.append(
+ f"slide {index} subtitle {problem} — got {subtitle[:60]!r}"
+ )
+ elif role in TOC_ROLES:
+ # The official TOC has exactly three text tiers: the 22pt
+ # heading, the 13pt badge numbers and the 16pt section
+ # titles. Hand-drawn variants that copy addTocSlide's
+ # geometry and bolt a ~10pt grey description under each
+ # title are the recurring drift, so anything below the
+ # smallest sanctioned tier is an error.
+ floor = TOC_MIN_TIER_PT * compat_scale(width, height)
+ strays = sorted(
+ size for size in body_font_sizes(root, height) if size < floor
+ )
+ if strays:
+ errors.append(
+ f"slide {index} toc page has text at {strays[0]:g}pt, below the "
+ f"{floor:.1f}pt floor for TOC tiers — the official contents page carries "
+ f"only numbered badges and section titles. Drop the description line and "
+ f"call addTocSlide(pres, {{ title, sections: [{{num, title}}] }})"
+ )
+
+ slide_reports.append({
+ "index": index,
+ "part": slide_name,
+ "layout": layout,
+ "role": role,
+ "explicit_font_min_pt": min(sizes) if sizes else None,
+ "explicit_font_max_pt": max(sizes) if sizes else None,
+ "out_of_bounds": out_of_bounds,
+ })
+
+ report = {
+ "pptx": str(pptx),
+ "canvas_emu": [width, height],
+ "slides": len(slides),
+ "masters": len(masters),
+ "layouts": len(layouts),
+ "font_min_pt": min(all_sizes) if all_sizes else None,
+ "font_median_pt": sorted(all_sizes)[len(all_sizes) // 2] if all_sizes else None,
+ "errors": errors,
+ "warnings": warnings,
+ "slide_reports": slide_reports,
+ }
+ return report
+
+
+def main() -> int:
+ logging.basicConfig(stream=sys.stderr, level=logging.INFO,
+ format="[%(levelname)s] %(message)s")
+ parser = argparse.ArgumentParser()
+ parser.add_argument("pptx")
+ parser.add_argument("--template")
+ parser.add_argument("--lock")
+ parser.add_argument(
+ "--evidence-plan",
+ help="evidence-plan.json; enables the paper-figure source-note check",
+ )
+ parser.add_argument("--report")
+ parser.add_argument("--title-min-font", type=float, default=24)
+ parser.add_argument("--body-min-font", type=float, default=10)
+ parser.add_argument("--absolute-min-font", type=float, default=7)
+ args = parser.parse_args()
+
+ try:
+ report = audit(args)
+ # ValueError already covers json.JSONDecodeError; listing both trips the
+ # "parent and child exception" rule.
+ except (OSError, ValueError, zipfile.BadZipFile, ET.ParseError) as cause:
+ LOGGER.error("audit failed: %s", cause)
+ return 1
+
+ if args.report:
+ report_path = Path(args.report)
+ report_path.parent.mkdir(parents=True, exist_ok=True)
+ report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
+
+ for message in report["warnings"]:
+ emit(f"[WARN] {message}")
+ for message in report["errors"]:
+ LOGGER.error("%s", message)
+ emit(
+ "pptx-audit: "
+ f"{len(report['errors'])} error(s), {len(report['warnings'])} warning(s), "
+ f"slides={report['slides']}, masters={report['masters']}, layouts={report['layouts']}, "
+ f"font_min={report['font_min_pt']}pt"
+ )
+ return 1 if report["errors"] else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/components.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/components.js
new file mode 100644
index 0000000000..4ccf73a0e4
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/components.js
@@ -0,0 +1,2063 @@
+// Deck component library for pptxgenjs.
+// Canvas: LAYOUT_16x9 (10" x 5.625"). Set pres.layout = "LAYOUT_16x9" before adding slides.
+// API conventions:
+// - Framing components: fn(pres, opts) -> slide (they create the slide)
+// - Content components: fn(pres, slide, opts) (they draw on an existing slide)
+// Colors are 6-char hex WITHOUT "#". Never pass "#"-prefixed or 8-char colors to pptxgenjs.
+
+const path = require("path");
+
+// System-diagram engine (declarative IR -> native shapes). Sibling module.
+const { renderSystemDiagram, DEFAULT_THEME, item, group, bandNode, groupBand } = require(path.join(__dirname, "system-diagram.js"));
+// Figure-panel engine (paper figures -> pasted images). Sibling module.
+const { renderFigurePanel } = require(path.join(__dirname, "figure-panel.js"));
+
+// Font bounds per diagram region size: keep text readable in narrow regions by
+// clamping rather than scaling to nothing.
+const DIAGRAM_DENSITY = {
+ full: { fontMin: 7, fontMax: 13 }, // full-width main diagram (w >= 8)
+ split: { fontMin: 6.5, fontMax: 11 }, // left half of an image-text page (4 <= w < 8)
+ compact: { fontMin: 6, fontMax: 9.5 }, // small supporting diagram (w < 4)
+};
+
+// Design tokens. `accent` drives every emphasis in the deck — title, summary
+// banner, KPI numbers, chart series 1 — so changing it here rethemes the whole
+// output. Default is Office theme Accent1, matching references/template.pptx.
+const THEME = {
+ accent: "4472C4",
+ accentMid: "8FAADC",
+ accentLight: "B4C7E7",
+ black: "000000",
+ darkText: "1D1D1A",
+ darkGray: "595757",
+ midGray: "898989",
+ lightGray: "B5B5B5",
+ border: "A6A6A6",
+ paleGray: "DDDDDD",
+ white: "FFFFFF",
+};
+
+const FONT = "Microsoft YaHei";
+
+// Soft outer shadow shared by white cards — reference decks' cards float
+// slightly instead of sitting flat as wireframe boxes.
+//
+// MUST stay a factory, never a shared constant. PptxGenJS rewrites
+// options.shadow IN PLACE while emitting XML (blur ×12700, angle ×60000,
+// opacity ×100000), so one object reused across shapes gets re-converted once
+// per shape: card 2 emits blurRad="483870000", card 3 "6145149000000", and dir
+// blows past the 21600000 ceiling of ST_PositiveFixedAngle. PowerPoint then
+// refuses to open the deck and offers to repair it.
+const cardShadow = () => ({ type: "outer", color: "B8B8B8", opacity: 0.3, blur: 3, offset: 1, angle: 90 });
+
+const TY = {
+ title: { fontFace: FONT, fontSize: 22, bold: true, color: THEME.accent, align: "left" },
+ sectionLbl: { fontFace: FONT, fontSize: 10, bold: true, color: THEME.accent, align: "left" },
+ body: { fontFace: FONT, fontSize: 10, bold: false, color: THEME.darkGray, align: "left" },
+ bodySmall: { fontFace: FONT, fontSize: 8.5, bold: false, color: THEME.midGray, align: "left" },
+ statNumber: { fontFace: FONT, fontSize: 30, bold: true, color: THEME.accent, align: "center" },
+ statLabel: { fontFace: FONT, fontSize: 9, bold: false, color: THEME.midGray, align: "center" },
+ footer: { fontFace: FONT, fontSize: 7, bold: false, color: THEME.midGray, align: "left" },
+};
+
+const LAYOUT = {
+ slideW: 10,
+ slideH: 5.625,
+ marginX: 0.5,
+ contentTop: 0.95,
+ contentBottom: 4.65, // content must end above the summary banner
+ bannerY: 4.70,
+ bannerH: 0.40,
+};
+
+// Fixed content-page shell markers. These prevent accidental duplicate chrome
+// when a caller composes a page from several helpers.
+const FOOTER_MARK = Symbol("deckFooter");
+const SUMMARY_MARK = Symbol("deckSummaryBanner");
+const SOURCE_MARK = Symbol("deckSourceNote");
+
+// Design-density heuristics are intentionally opt-in. They are useful during
+// exploration, but they are not template rules and must not steer every
+// page back toward a full grid. Geometry, argument, and data validation remain
+// enabled independently. Set PPT_ADVISORY_QA=1 to print these hints.
+const ADVISORY_QA_ENABLED = process.env.PPT_ADVISORY_QA === "1";
+
+const withHash = (color) => `#${color}`;
+
+// Split the body width into n columns; returns [{x, w}, ...] — ALL n columns,
+// there is no "get column i" form. weights (e.g. [2, 1]) make unequal
+// columns. Use for multi-region slides:
+// const [left, mid, right] = cols(3);
+// addPanelList(pres, s, { ...left, ... }); addComparisonTable(pres, s, { ...mid, ... });
+function cols(n, opts = {}) {
+ // Real-world failure mode: cols(2, 0) / cols(2, 1), guessing the 2nd arg
+ // selects a single column by index. It doesn't — the 2nd arg is an options
+ // object, so a bare number is silently ignored by default-destructuring
+ // (0..x is undefined, falls back to the default), and the caller ends up
+ // assigning the WHOLE array to what they think is one column's x/w. That
+ // produces geometrically nonsensical positions with no NOTICE anywhere —
+ // the deck renders severely broken with zero diagnostic output. Fail loud.
+ if (opts !== null && typeof opts !== "object") {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] cols(${n}, ${JSON.stringify(opts)}): the 2nd argument ` +
+ "must be an options object like {x, w, gap, weights} (or omitted) — cols() has no \"get column i\" form, " +
+ "it always returns ALL n columns. Destructure the result: `const [left, right] = cols(2);` then spread " +
+ "one column into a component call: `addPanelList(pres, s, { ...left, y: 1.05, h: 3.6, ... })`."
+ );
+ }
+ const { x = 0.5, w = 9.0, gap = 0.18, weights = null } = opts;
+ const ws = weights || Array(n).fill(1);
+ const total = ws.reduce((a, b) => a + b, 0);
+ const avail = w - gap * (ws.length - 1);
+ const out = [];
+ let cx = x;
+ ws.forEach((wt) => {
+ const cw = (avail * wt) / total;
+ out.push({ x: cx, w: cw });
+ cx += cw + gap;
+ });
+ return out;
+}
+
+
+
+// Normalize the many "almost right" chart data shapes LLM callers produce into
+// pptxgenjs's required [{ name, labels, values }] — and fail with instructions
+// (not cryptic library errors) when the data is genuinely unusable.
+function normalizeChartData(fn, data) {
+ let series = data;
+ if (series && !Array.isArray(series)) series = [series]; // single series object → array
+ if (Array.isArray(series) && series.length &&
+ series[0] && series[0].labels === undefined &&
+ (series[0].label !== undefined || series[0].value !== undefined)) {
+ // array of {label, value} points → one series
+ series = [{
+ name: "数据",
+ labels: series.map((pt) => String(pt.label != null ? pt.label : (pt.name != null ? pt.name : ""))),
+ values: series.map((pt) => pt.value),
+ }];
+ }
+ if (!Array.isArray(series) || !series.length) {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] ${fn}: \`data\` must be ` +
+ "an array of series: [{ name: \"系列名\", labels: [\"甲\",\"乙\"], values: [1, 2] }]. " +
+ "Fix the data you pass in; do NOT edit components.js."
+ );
+ }
+ return series.map((s, i) => {
+ const name = String((s && s.name) || `系列${i + 1}`);
+ const labels = ((s && s.labels) || []).map(String);
+ const values = ((s && s.values) || []).map((v) =>
+ typeof v === "string" ? parseFloat(v.replace(/[^0-9.eE+-]/g, "")) : v);
+ if (!labels.length || !values.length) {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] ${fn}: series "${name}" ` +
+ "needs non-empty labels[] AND values[]. Fix the data; do NOT edit components.js."
+ );
+ }
+ if (labels.length !== values.length) {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] ${fn}: series "${name}" has ` +
+ `${labels.length} labels but ${values.length} values — they must match 1:1. ` +
+ "Fix the data; do NOT edit components.js."
+ );
+ }
+ if (values.some((v) => typeof v !== "number" || Number.isNaN(v))) {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] ${fn}: series "${name}" ` +
+ "values must all be numbers (no null/undefined/non-numeric strings). " +
+ "Fix the data; do NOT edit components.js."
+ );
+ }
+ return { name, labels, values };
+ });
+}
+
+
+// Build-time overlap check: when a callout row / summary banner is added,
+// scan elements already on the slide and name the ones that intrude into its
+// band. Uses pptxgenjs private _slideObjects — wrapped in try/catch so a
+// library upgrade degrades to "no check" instead of a crash.
+function warnBandOverlap(fn, slide, bandY, limitY) {
+ try {
+ const objs = slide._slideObjects || [];
+ const offenders = [];
+ objs.forEach((o) => {
+ const opt = o && o.options;
+ if (!opt || typeof opt.y !== "number" || typeof opt.h !== "number") return;
+ const bottom = opt.y + opt.h;
+ if (opt.y < bandY && bottom > bandY + 0.02) {
+ const what = (o._type || o.type || "element") + (opt._name ? `(${opt._name})` : "");
+ offenders.push(`${what} y=${opt.y.toFixed(2)} h=${opt.h.toFixed(2)} bottom=${bottom.toFixed(2)}`);
+ }
+ });
+ if (offenders.length) {
+ console.warn(
+ `[LAYOUT-OVERLAP NOTICE — ${fn} succeeded, but ${offenders.length} element(s) extend into its band (y=${bandY}) ` +
+ `and will be visually covered] ${offenders.slice(0, 4).join("; ")}. ` +
+ `Fix YOUR slides.js geometry: content must end at y<=${limitY} (LAYOUT.contentBottom). ` +
+ "Do NOT edit components.js."
+ );
+ }
+ } catch (e) { /* private API changed — skip the check */ }
+}
+
+// Effective bounding rect of a pptxgenjs slide object. Tables carry no `h`
+// (row heights live in the rowH array) — derive it, or every table would be
+// invisible to the overlap and page-coverage checks.
+function objRect(o) {
+ const t = o && o.options;
+ if (!t || typeof t.x !== "number" || typeof t.y !== "number" || typeof t.w !== "number") return null;
+ // pptxgenjs converts TABLE x/y/w to EMU in-place (914400/inch) while rowH
+ // stays in inches — normalize any suspiciously large value back to inches.
+ const IN = (v) => (v > 100 ? v / 914400 : v);
+ let h = t.h;
+ if (typeof h !== "number" && Array.isArray(t.rowH)) h = t.rowH.reduce((a, b) => a + (b || 0), 0);
+ if (typeof h !== "number") return null;
+ return { x: IN(t.x), y: IN(t.y), w: IN(t.w), h: IN(h), rotate: t.rotate };
+}
+
+// Region-collision check: before a content component draws, scan elements
+// already on the slide and name any that intrude into its rectangle. Catches
+// the "KPI row stamped on top of tall cards" class of bug at build time.
+// Uses pptxgenjs private _slideObjects — wrapped in try/catch so a library
+// upgrade degrades to "no check" instead of a crash. Advisory only.
+function warnRectOverlap(fn, slide, rx, ry, rw, rh) {
+ try {
+ const TOL = 0.08; // require real intrusion on BOTH axes, not mere edge contact
+ const offenders = [];
+ (slide._slideObjects || []).forEach((o) => {
+ const opt = objRect(o);
+ if (!opt) return;
+ if (opt.rotate) return; // rotated boxes report pre-rotation rects
+ const ix = Math.min(rx + rw, opt.x + opt.w) - Math.max(rx, opt.x);
+ const iy = Math.min(ry + rh, opt.y + opt.h) - Math.max(ry, opt.y);
+ if (ix > TOL && iy > TOL) {
+ const what = o._type || o.type || "element";
+ offenders.push(`${what} @(x=${opt.x.toFixed(2)},y=${opt.y.toFixed(2)},w=${opt.w.toFixed(2)},h=${opt.h.toFixed(2)})`);
+ }
+ });
+ if (offenders.length) {
+ console.warn(
+ `[LAYOUT-OVERLAP NOTICE — ${fn} succeeded, but it is being drawn ON TOP of ${offenders.length} existing element(s)] ` +
+ `${fn} occupies (x=${rx.toFixed(2)}, y=${ry.toFixed(2)}, w=${rw.toFixed(2)}, h=${rh.toFixed(2)}); colliding: ` +
+ offenders.slice(0, 4).join("; ") + ". " +
+ "Fix YOUR slides.js geometry — vertically adjacent regions must satisfy prevY + prevH <= nextY " +
+ "(e.g. shrink the earlier region's h, or move this component down). Do NOT edit components.js."
+ );
+ }
+ } catch (e) { /* private API changed — skip the check */ }
+}
+
+// Explicit list-fitting font size. PowerPoint does NOT recompute pptxgenjs's
+// fit:"shrink" until the text box is edited, so overflowing text renders
+// outside its panel. Compute a fitting size up front; fit:"shrink" stays on
+// only as a backstop.
+function fitListFontSize(texts, w, h, base, min) {
+ for (let size = base; size >= min; size -= 0.25) {
+ const charW = (size / 72) * 1.05;
+ const lineH = (size / 72) * 1.45;
+ const perLine = Math.max(Math.floor(w / charW), 1);
+ let lines = 0;
+ texts.forEach((t) => { lines += Math.max(Math.ceil(String(t).length / perLine), 1); });
+ const total = lines * lineH + texts.length * (4 / 72); // paraSpaceAfter 4pt
+ if (total <= h) return size;
+ }
+ return min;
+}
+
+// Page-level coverage audit, run from addSummaryBanner (the mandatory last
+// band on every content slide): split the content zone (x 0.5-9.5, y 1.0-4.65)
+// into a 4x3 grid and flag clusters of cells no element touches — the
+// "one narrow panel + huge blank right half" failure that per-region checks
+// cannot see. Advisory only.
+function warnPageCoverage(slide) {
+ if (!ADVISORY_QA_ENABLED) return;
+ try {
+ const objs = (slide._slideObjects || []).map(objRect).filter(Boolean);
+ if (objs.length < 3) return; // framing-only slide (opening/TOC/closing)
+ const X0 = 0.5, X1 = 9.5, Y0 = 1.0, Y1 = 4.65, COLS = 4, ROWS = 3;
+ const cw = (X1 - X0) / COLS, ch = (Y1 - Y0) / ROWS;
+ const empty = [];
+ for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLS; c++) {
+ const gx = X0 + c * cw, gy = Y0 + r * ch;
+ const hit = objs.some((t) =>
+ Math.min(gx + cw, t.x + t.w) - Math.max(gx, t.x) > 0.15 &&
+ Math.min(gy + ch, t.y + t.h) - Math.max(gy, t.y) > 0.15);
+ if (!hit) empty.push([r, c]);
+ }
+ // Only warn on a cluster: 2+ empty cells sharing an edge.
+ const adj = empty.some(([r, c]) => empty.some(([r2, c2]) =>
+ (r === r2 && Math.abs(c - c2) === 1) || (c === c2 && Math.abs(r - r2) === 1)));
+ if (empty.length >= 2 && adj) {
+ const colName = ["左", "中左", "中右", "右"], rowName = ["上", "中", "下"];
+ const where = [...new Set(empty.map(([r, c]) => `${colName[c]}${rowName[r]}`))].slice(0, 6).join("、");
+ console.warn(
+ `[DESIGN-ADVISORY — page-level. ~${empty.length}/12 of the content zone is untouched (${where})] ` +
+ "Standard content pages must fill the content zone. Expand the regions, extend the body text, " +
+ "or rework the page plan so the whitespace is closed."
+ );
+ }
+ } catch (e) { /* private API changed — skip */ }
+}
+
+// Underfill heuristic: rough CJK capacity (in characters) of a text container.
+// Used by top-anchored content components (cards, icon grids) to nudge the
+// caller to EXPAND content from research when a region would render mostly
+// empty. Advisory only — never fatal, never blocks the build.
+function estCapacityChars(w, h, fontSize) {
+ const charW = (fontSize / 72) * 1.05; // CJK glyph ≈ 1em wide
+ const lineH = (fontSize / 72) * 1.55; // line height + paragraph spacing
+ const lines = Math.max(Math.floor(h / lineH), 1);
+ const perLine = Math.max(Math.floor(w / charW), 1);
+ return lines * perLine;
+}
+
+// Display-width char count: CJK ≈ 1em, ASCII/halfwidth ≈ 0.55em — matches the
+// width model in estCapacityChars, so fill rates stay honest for mixed
+// Chinese/English content (raw .length overstates ASCII-heavy text by ~2x).
+function visLen(s) {
+ let n = 0;
+ for (const ch of String(s || "")) n += ch.charCodeAt(0) < 0x2e80 ? 0.55 : 1;
+ return n;
+}
+
+function warnUnderfill(fn, what, chars, capacity, suggestion) {
+ if (!ADVISORY_QA_ENABLED) return;
+ if (capacity <= 0) return;
+ const fill = chars / capacity;
+ if (fill < 0.7) {
+ console.warn(
+ `[DESIGN-ADVISORY — ${fn}: ${what} uses ~${Math.round(fill * 100)}% of its estimated text capacity] ` +
+ "Keep it when the whitespace is intentional. If the region feels accidental or unfinished, improve the " +
+ `content, reduce the container, or choose another composition (${suggestion}). Never add filler.`
+ );
+ }
+}
+
+// Guard for content components, which all take (pres, slide, opts). The most
+// common caller mistake is omitting `pres`, which shifts every argument and
+// surfaces as confusing errors like "slide.addTable is not a function".
+function assertSlide(fn, pres, slide) {
+ if (!pres || typeof pres.addSlide !== "function") {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] ${fn}(pres, slide, opts): ` +
+ "1st argument must be the pptxgen presentation instance (`pres`)."
+ );
+ }
+ if (!slide || typeof slide.addText !== "function") {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] ${fn}(pres, slide, opts): ` +
+ "2nd argument must be a slide from pres.addSlide(). You most likely omitted `pres` " +
+ `as the 1st argument — call C.${fn}(pres, slide, {...}). Fix the call site; ` +
+ "do NOT edit components.js."
+ );
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Generic building blocks
+// ---------------------------------------------------------------------------
+
+function addSlideTitle(pres, slide, { title, subtitle = null, fontSize = 26 } = {}) {
+ assertSlide("addSlideTitle", pres, slide);
+ // slide titles never carry sequence numbers.
+ // Strip a leading "3." / "3、" / "03:" style prefix defensively and tell the caller.
+ const stripped = String(title || "").replace(/^\s*\d{1,2}\s*[\.、.::]\s*/, "");
+ if (stripped !== String(title || "")) {
+ console.warn(
+ "[STYLE-NOTICE — addSlideTitle succeeded] Removed the sequence-number prefix from " +
+ `"${title}" — Slide titles carry no numbers. Drop the prefix in YOUR slides.js; ` +
+ "do NOT edit components.js."
+ );
+ title = stripped;
+ }
+ // Dynamic title sizing: the title must stay on ONE line inside the 9" box.
+ // CJK glyphs count as 1 em, ASCII roughly half; shrink from the requested
+ // size just enough to fit (floor 15pt), and tell the caller when the title
+ // is so long it should be reworded instead.
+ const effLen = [...String(title)].reduce((s, ch) => s + (ch.charCodeAt(0) > 0x2e7f ? 1 : 0.55), 0);
+ const titleW = LAYOUT.slideW - LAYOUT.marginX * 2;
+ const fitSize = Math.floor((titleW * 72) / (1.15 * Math.max(effLen, 1)) * 2) / 2;
+ const usedSize = Math.max(Math.min(fontSize, fitSize), 15);
+ if (usedSize < fontSize && effLen > 30) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addSlideTitle succeeded] the title is ~${Math.round(effLen)} chars and was ` +
+ `auto-shrunk to ${usedSize}pt to stay on one line. Titles read best at ≤22 chars — consider rewording ` +
+ "it in YOUR slides.js (move detail into the subtitle); do NOT edit components.js."
+ );
+ }
+ slide.addText(title, {
+ x: LAYOUT.marginX, y: 0.18, w: titleW, h: 0.50,
+ fontFace: FONT, fontSize: usedSize, bold: true, color: THEME.accent, align: "left",
+ margin: 0, valign: "middle", fit: "shrink",
+ });
+ // darkGray, not midGray: at 10.5pt the 898989 mid grey reads as disabled text
+ // against the accent title and washes out on a projector. 595757 is the same
+ // weight the hand-written lead-in lines use, so component subtitles and
+ // hand-composed ones match.
+ if (subtitle) {
+ slide.addText(subtitle, {
+ x: LAYOUT.marginX, y: 0.68, w: LAYOUT.slideW - LAYOUT.marginX * 2, h: 0.24,
+ fontFace: FONT, fontSize: 10.5, color: THEME.darkGray, align: "left", margin: 0,
+ });
+ }
+}
+
+function addPanel(pres, slide, { x, y, w, h, fill, border = null } = {}) {
+ assertSlide("addPanel", pres, slide);
+ if (fill === undefined && ADVISORY_QA_ENABLED) {
+ console.warn(
+ "[DESIGN-ADVISORY — addPanel has no explicit fill and will use gray DDDDDD] " +
+ "Confirm that a gray grouping container is intentional; pass fill explicitly to record the decision."
+ );
+ }
+ const usedFill = fill === undefined ? THEME.paleGray : fill;
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x, y, w, h,
+ fill: { color: usedFill },
+ line: border ? { color: border, width: 0.5 } : { color: usedFill, width: 0 },
+ });
+}
+
+// Content-page footer: bare page number at the far left, and an optional
+// classification line next to it. Geometry matches the 13.33"x7.5" template
+// master scaled x0.75 to this 10"x5.625" canvas.
+//
+// `classification` is opt-in and defaults to nothing: a deck that does not need
+// a confidentiality marking should not carry an empty one. Pass a string to
+// draw it (e.g. "Internal Use Only").
+function addSlideFooter(pres, slide, { pageNum = 1, classification = null } = {}) {
+ assertSlide("addSlideFooter", pres, slide);
+ if (slide[FOOTER_MARK]) {
+ throw new Error("[CALL-ERROR] addSlideFooter may be applied only once per content slide.");
+ }
+ slide[FOOTER_MARK] = true;
+ slide.addText(String(pageNum), {
+ x: 0.60, y: 5.21, w: 0.42, h: 0.20,
+ fontFace: FONT, fontSize: 7, color: THEME.black, align: "left", valign: "middle", margin: 0,
+ });
+ const marking = String(classification || "").trim();
+ if (marking) {
+ slide.addText(marking, {
+ x: 0.90, y: 5.21, w: 3.2, h: 0.20,
+ fontFace: FONT, fontSize: 7, color: THEME.darkGray, align: "left", valign: "middle", margin: 0,
+ });
+ }
+}
+
+// Attribution line for pages that paste a paper figure. Required whenever the
+// page embeds an image from assets/papers/ -- audit_pptx.py --evidence-plan
+// turns a missing note into a build error.
+//
+// Sits on the footer row itself, right-aligned against x=8.30 so a longer
+// citation grows leftwards into the empty right end of the row instead of
+// colliding with the optional classification text that ends at x=4.10. The
+// same band is empty under footerMode "master", where the template master draws
+// its footer at y=6.95" on the 13.34" canvas -- which is this y=5.21 once
+// merge_slides.py scales the page up.
+//
+// 7pt matches the rest of the footer and equals audit's absolute font floor,
+// so it never trips the minimum-size check.
+// Pass `url` (the evidence plan's source_url) to make the citation clickable.
+// The "来源:" label stays plain and only the citation carries the link, so the
+// underline marks exactly the clickable span. Colour is pinned to the footer
+// grey rather than the theme's hyperlink blue: this is footer chrome, and a
+// blue link would outrank the black confidentiality line next to it.
+function addSourceNote(pres, slide, { source, url } = {}) {
+ assertSlide("addSourceNote", pres, slide);
+ const cite = String(source || "").trim();
+ if (!cite) {
+ throw new Error("[CALL-ERROR] addSourceNote requires a non-empty source, e.g. \"Wang et al., arXiv:2406.04692, Fig.1\".");
+ }
+ if (slide[SOURCE_MARK]) {
+ throw new Error("[CALL-ERROR] addSourceNote may be applied only once per page. Combine multiple figures into one citation.");
+ }
+ const link = String(url || "").trim();
+ if (link && !/^https?:\/\//i.test(link)) {
+ throw new Error(`[CALL-ERROR] addSourceNote url must be an absolute http(s) URL, got "${link}".`);
+ }
+ slide[SOURCE_MARK] = true;
+
+ const label = /^来源\s*[::]/.test(cite) ? "" : "来源:";
+ const body = label ? cite : cite.replace(/^来源\s*[::]\s*/, "");
+ const box = {
+ x: 4.20, y: 5.21, w: 4.10, h: 0.20,
+ fontFace: FONT, fontSize: 7, color: THEME.midGray,
+ align: "right", valign: "middle", margin: 0, fit: "shrink",
+ };
+
+ if (!link) {
+ slide.addText(`${label}${body}`, box);
+ return;
+ }
+ slide.addText(
+ [
+ { text: label || "来源:", options: {} },
+ { text: body, options: { hyperlink: { url: link, tooltip: body }, underline: true, color: THEME.midGray } },
+ ],
+ box
+ );
+}
+
+// Required content-page takeaway band. Geometry, color, typography and
+// alignment are fixed; callers supply only the page-specific one-sentence
+// conclusion. Cover, TOC, section divider and closing pages use their own shell.
+function addSummaryBanner(pres, slide, { text } = {}) {
+ assertSlide("addSummaryBanner", pres, slide);
+ const summary = String(text || "").trim();
+ if (!summary) {
+ throw new Error("[CALL-ERROR] addSummaryBanner requires a non-empty one-sentence takeaway.");
+ }
+ if (slide[SUMMARY_MARK]) {
+ throw new Error("[CALL-ERROR] addSummaryBanner may be applied only once per content slide.");
+ }
+ slide[SUMMARY_MARK] = true;
+ warnBandOverlap("addSummaryBanner", slide, LAYOUT.bannerY, LAYOUT.contentBottom);
+ warnPageCoverage(slide);
+ const y = LAYOUT.bannerY, h = LAYOUT.bannerH;
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: 0.3, y, w: 9.4, h,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(summary, {
+ x: 0.6, y, w: 8.8, h,
+ fontFace: FONT, fontSize: 11, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+}
+
+// Preferred single entry point for the fixed bottom shell on standard content
+// pages. It deliberately exposes no geometry or style overrides.
+function addContentChrome(pres, slide, {
+ summary,
+ pageNum = 1,
+ classification = null,
+ footerMode = "drawn",
+} = {}) {
+ if (!new Set(["drawn", "master"]).has(footerMode)) {
+ throw new Error('[CALL-ERROR] addContentChrome footerMode must be "drawn" or "master".');
+ }
+ addSummaryBanner(pres, slide, { text: summary });
+ if (footerMode === "drawn") {
+ addSlideFooter(pres, slide, { pageNum, classification });
+ } else if (footerMode === "master") {
+ if (slide[FOOTER_MARK]) {
+ throw new Error("[CALL-ERROR] The content footer may be applied only once per content slide.");
+ }
+ // The generated slide will be relinked to the template's blank-content
+ // layout by merge_slides.py. Mark the footer as accounted for without
+ // drawing a second page number over the inherited master objects.
+ slide[FOOTER_MARK] = true;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Framing slides (opening / TOC / section divider / closing)
+// ---------------------------------------------------------------------------
+
+// Cover page, drawn entirely with vectors — no background art, no logo.
+// Geometry mirrors the cover in references/template.pptx (that canvas is
+// 13.333" wide, this one 10", so every value there is this one x0.75), which
+// keeps a deck built through the template path visually identical to one built
+// purely in PptxGenJS.
+//
+// `classification` is opt-in: omit it and no marking is drawn.
+function addOpeningSlide(pres, {
+ title, department = "", author = "", date = "", classification = null,
+} = {}) {
+ const slide = pres.addSlide();
+ slide.background = { color: THEME.white };
+ slide.addText(title, {
+ x: 0.83, y: 0.75, w: 6.42, h: 0.56,
+ fontFace: FONT, fontSize: 22, bold: true, color: THEME.accent,
+ align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ // Accent rule under the title — the cover's only ornament.
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: 0.83, y: 1.43, w: 0.59, h: 0.017,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(
+ [
+ { text: `部门:${department}`, options: { breakLine: true } },
+ { text: `汇报人:${author}`, options: { breakLine: true } },
+ { text: `日期:${date}` },
+ ],
+ {
+ x: 0.83, y: 1.65, w: 2.6, h: 0.75,
+ fontFace: FONT, fontSize: 10.5, color: THEME.darkText,
+ align: "left", margin: 0, lineSpacingMultiple: 1.25,
+ }
+ );
+ const marking = String(classification || "").trim();
+ if (marking) {
+ slide.addText(marking, {
+ x: 0.83, y: 5.12, w: 2.6, h: 0.23,
+ fontFace: FONT, fontSize: 8, color: THEME.darkText,
+ align: "left", valign: "middle", margin: 0,
+ });
+ }
+ return slide;
+}
+
+function addTocSlide(pres, { title, sections = [] } = {}) {
+ const slide = pres.addSlide();
+ slide.background = { color: THEME.paleGray };
+ slide.addText(title, {
+ x: 0.85, y: 0.30, w: 4.0, h: 0.50,
+ fontFace: FONT, fontSize: 22, bold: true, color: THEME.black, align: "left", margin: 0,
+ });
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: 0.85, y: 0.86, w: 0.78, h: 0.05,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ // 16pt section titles, no description line, whole list centered on the
+ // slide (both axes). Uniform series colors: every badge the same accent, every
+ // title black — no "current section" highlighting. Adaptive step keeps up
+ // to 7 sections inside the canvas — never overflow.
+ if (!Array.isArray(sections)) {
+ throw new Error("addTocSlide sections must be an array of {num, title} objects or numbered title strings");
+ }
+ const normalizedSections = sections.map((section, index) => {
+ if (typeof section === "string") {
+ const text = section.trim();
+ if (!text) throw new Error(`addTocSlide sections[${index}] is empty`);
+ const match = text.match(/^\s*(\d{1,2})\s*[.、.:\-]?\s*(.+)$/);
+ return match
+ ? { num: match[1], title: match[2].trim() }
+ : { num: String(index + 1), title: text };
+ }
+ if (!section || typeof section !== "object") {
+ throw new Error(`addTocSlide sections[${index}] must be an object or string`);
+ }
+ const num = String(section.num == null ? index + 1 : section.num).trim();
+ const sectionTitle = String(section.title == null ? "" : section.title).trim();
+ if (!num || !sectionTitle) {
+ throw new Error(`addTocSlide sections[${index}] requires non-empty num and title`);
+ }
+ return { num, title: sectionTitle };
+ });
+ const n = Math.max(normalizedSections.length, 1);
+ if (normalizedSections.length > 7) {
+ console.warn(
+ "[CONTENT-LIMIT NOTICE — addTocSlide succeeded] TOC has " + normalizedSections.length +
+ " sections; the TOC fits at most 7. Merge sections in YOUR slides.js — " +
+ "do NOT edit components.js. Rendering the first 7 only."
+ );
+ }
+ const shown = normalizedSections.slice(0, 7);
+ const ZONE_TOP = 1.05, ZONE_BOTTOM = 5.35;
+ const BADGE = 0.42;
+ const STEP = Math.min(0.92, (ZONE_BOTTOM - ZONE_TOP) / shown.length);
+ const blockH = STEP * (shown.length - 1) + BADGE;
+ const top = ZONE_TOP + Math.max(0, (ZONE_BOTTOM - ZONE_TOP - blockH) / 2);
+ // Horizontally centered group: badge column + 16pt title column.
+ const BADGE_X = 3.30, TEXT_X = BADGE_X + BADGE + 0.22, TEXT_W = 3.30;
+ shown.forEach((s, i) => {
+ const y = top + i * STEP;
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: BADGE_X, y, w: BADGE, h: BADGE,
+ fill: { color: THEME.accent },
+ line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(s.num, {
+ x: BADGE_X, y, w: BADGE, h: BADGE,
+ fontFace: FONT, fontSize: 13, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ slide.addText(s.title, {
+ x: TEXT_X, y, w: TEXT_W, h: BADGE,
+ fontFace: FONT, fontSize: 16, bold: true,
+ color: THEME.black, align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ });
+ return slide;
+}
+
+// Closing slide. Matches the closing page in references/template.pptx.
+function addClosingSlide(pres, { text = "Thank You" } = {}) {
+ const slide = pres.addSlide();
+ slide.background = { color: THEME.white };
+ slide.addText(text, {
+ x: 0, y: 2.40, w: 10, h: 0.75,
+ fontFace: FONT, fontSize: 27, bold: true, color: THEME.accent,
+ align: "center", valign: "middle", margin: 0,
+ });
+ return slide;
+}
+
+// ---------------------------------------------------------------------------
+// Dense content layouts
+// ---------------------------------------------------------------------------
+
+// Row of big accent numbers with gray labels. Up to 5 items.
+// rings: true draws a pale circular ring behind each number — the circular
+// motif from references/product-slide.png (per-item override: it.ring).
+function addKpiRow(pres, slide, { items = [], x: x0 = 0.5, w: w0 = 9.0, y = 3.55, rings = false } = {}) {
+ assertSlide("addKpiRow", pres, slide);
+ // Optional per-item icon (it.iconData / it.initial + it.color) stacks a small
+ // disc above the number; the band grows accordingly.
+ const hasIcons = items.some((it) => it.iconData || it.initial);
+ const iconH = hasIcons ? 0.34 : 0;
+ warnRectOverlap("addKpiRow", slide, x0, y, w0, 0.87 + iconH);
+ const n = Math.max(items.length, 1);
+ const cellW = w0 / n;
+ items.forEach((it, i) => {
+ const x = x0 + i * cellW;
+ if (hasIcons && (it.iconData || it.initial)) {
+ const D = 0.28, dx = x + cellW / 2 - D / 2;
+ if (it.iconData) {
+ slide.addImage({ data: it.iconData, x: dx, y, w: D, h: D });
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ x: dx, y, w: D, h: D,
+ fill: { color: it.color || THEME.accent }, line: { color: it.color || THEME.accent, width: 0 },
+ });
+ slide.addText(String(it.initial).slice(0, 1), {
+ x: dx, y, w: D, h: D,
+ fontFace: FONT, fontSize: 10, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ }
+ }
+ if (it.ring !== undefined ? it.ring : rings) {
+ const RING = 0.8;
+ // Concentric with the number: text box is y..y+0.55 (valign middle), centered in the cell.
+ slide.addShape(pres.shapes.OVAL, {
+ x: x + cellW / 2 - RING / 2, y: y + iconH + 0.275 - RING / 2, w: RING, h: RING,
+ fill: { color: THEME.white, transparency: 100 },
+ line: { color: THEME.paleGray, width: 1.75 },
+ });
+ }
+ slide.addText(String(it.value), {
+ x, y: y + iconH, w: cellW, h: 0.55,
+ fontFace: FONT, fontSize: 30, bold: true, color: THEME.accent,
+ align: "center", valign: "middle", margin: 0,
+ fit: "shrink", // long values (e.g. "Apache 2.0") shrink to one line instead of wrapping onto the label
+ });
+ slide.addText(String(it.label), {
+ x, y: y + iconH + 0.57, w: cellW, h: 0.30,
+ fontFace: FONT, fontSize: 9, color: THEME.midGray,
+ align: "center", valign: "top", margin: 0,
+ });
+ if (i > 0) {
+ slide.addShape(pres.shapes.LINE, {
+ x, y: y + iconH + 0.06, w: 0, h: 0.72,
+ line: { color: THEME.paleGray, width: 0.75 },
+ });
+ }
+ });
+}
+
+// Grid of pale-gray cards, each with a accent sub-headline, optional body, optional accent-bulleted list.
+// Optional per-card small icon (card.iconData from iconToPng()/svgToPng(), or
+// card.initial as a one-char fallback) renders in a fixed slot left of the
+// title — flat monochrome per the deck style (accent or dark gray), never colorful.
+function addCardGrid(pres, slide, {
+ cards = [], columns = 2, x = 0.5, y = 1.05, w = 9.0, h = 3.5,
+} = {}) {
+ assertSlide("addCardGrid", pres, slide);
+ warnRectOverlap("addCardGrid", slide, x, y, w, h);
+ const gap = 0.18;
+ const rows = Math.ceil(cards.length / columns);
+ const cardW = (w - gap * (columns - 1)) / columns;
+ const cardH = (h - gap * (rows - 1)) / rows;
+ cards.forEach((card, i) => {
+ const cx = x + (i % columns) * (cardW + gap);
+ const cy = y + Math.floor(i / columns) * (cardH + gap);
+ addPanel(pres, slide, { fill: THEME.paleGray, x: cx, y: cy, w: cardW, h: cardH });
+ const hasIcon = !!(card.iconData || card.initial);
+ if (hasIcon) {
+ const D = 0.26;
+ if (card.iconData) {
+ slide.addImage({ data: card.iconData, x: cx + 0.12, y: cy + 0.11, w: D, h: D });
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ x: cx + 0.12, y: cy + 0.11, w: D, h: D,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(card.initial).slice(0, 1), {
+ x: cx + 0.12, y: cy + 0.11, w: D, h: D,
+ fontFace: FONT, fontSize: 10, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ }
+ }
+ // Auto-fill: scale font size UP when this card's content is sparse
+ // relative to its capacity (same sqrt-of-inverse-fill formula as
+ // addTextBlock), so a card with modest content still reads full instead
+ // of leaving visible dead space at a fixed font size.
+ const chars = visLen(card.body) +
+ (card.bullets || []).reduce((s2, b) => s2 + visLen(b) + 4, 0);
+ const cardCapacity = estCapacityChars(cardW - 0.28, cardH - 0.56, 9);
+ const cardFill = chars / Math.max(cardCapacity, 1);
+ const cardScale = cardFill < 1 ? Math.min(1.35, Math.max(1, Math.sqrt(0.8 / Math.max(cardFill, 0.14)))) : 1;
+
+ slide.addText(card.title, {
+ x: cx + (hasIcon ? 0.46 : 0.14), y: cy + 0.10, w: cardW - (hasIcon ? 0.60 : 0.28), h: 0.30,
+ fontFace: FONT, fontSize: 11.5 * Math.min(cardScale, 1.2), bold: true, color: THEME.accent,
+ align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ const runs = [];
+ if (card.body) runs.push({ text: card.body, options: { breakLine: true } });
+ (card.bullets || []).forEach((b) => {
+ runs.push({ text: b, options: { bullet: { code: "2022", color: THEME.accent }, breakLine: true, indentLevel: 0 } });
+ });
+ if (runs.length) {
+ slide.addText(runs, {
+ x: cx + 0.14, y: cy + 0.44, w: cardW - 0.28, h: cardH - 0.56,
+ fontFace: FONT, fontSize: 9 * cardScale, color: THEME.darkGray,
+ align: "left", valign: "top", margin: 0, paraSpaceAfter: 4 * cardScale, fit: "shrink",
+ });
+ }
+ if (cardFill < 0.16) {
+ warnUnderfill("addCardGrid", `card "${String(card.title).slice(0, 12)}"`,
+ chars, cardCapacity,
+ "grow the body to 2-3 sentences and give it 3-4 bullets with concrete mechanisms/numbers/examples, " +
+ "or make the card region shorter / raise fontSize via more columns");
+ }
+ });
+}
+
+// Horizontal accent-axis timeline with 3-6 dated nodes.
+function addTimeline(pres, slide, { events = [], x = 0.5, w = 9.0, axisY = 2.7 } = {}) {
+ assertSlide("addTimeline", pres, slide);
+ warnRectOverlap("addTimeline", slide, x, axisY - 0.42, w, 1.69);
+ events.forEach((ev) => {
+ if (String(ev.desc || "").length > 28) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addTimeline succeeded] node "${String(ev.title).slice(0, 10)}" has a ` +
+ `${String(ev.desc).length}-char desc; node descs longer than ~25 chars bleed into neighbouring columns. ` +
+ "Compress the wording in YOUR slides.js (电报体) — do NOT edit components.js."
+ );
+ }
+ });
+ if (events.length) {
+ const avgDesc = events.reduce((s2, ev) => s2 + visLen(ev.desc), 0) / events.length;
+ if (ADVISORY_QA_ENABLED && avgDesc < 12) {
+ console.warn(
+ `[DESIGN-ADVISORY — addTimeline: node descriptions average ~${Math.round(avgDesc)} chars] ` +
+ "Confirm that the sparse labels are intentional; otherwise add factual context or choose a more compact timeline."
+ );
+ }
+ }
+ slide.addShape(pres.shapes.LINE, {
+ x: x + 0.2, y: axisY, w: w - 0.4, h: 0,
+ line: { color: THEME.accent, width: 1.5 },
+ });
+ const n = events.length;
+ const cellW = Math.min((w - 0.8) / Math.max(n - 1, 1), 1.9);
+ // Inset edge nodes so their centered label boxes stay inside [x, x+w].
+ const inset = Math.max(0.4, cellW / 2);
+ const span = w - inset * 2;
+ events.forEach((ev, i) => {
+ const cx = n === 1 ? x + w / 2 : x + inset + (span / (n - 1)) * i;
+ slide.addShape(pres.shapes.OVAL, {
+ x: cx - 0.06, y: axisY - 0.06, w: 0.12, h: 0.12,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(ev.date), {
+ x: cx - cellW / 2, y: axisY - 0.42, w: cellW, h: 0.24,
+ fontFace: FONT, fontSize: 9, bold: true, color: THEME.accent,
+ align: "center", margin: 0,
+ });
+ slide.addText(String(ev.title), {
+ x: cx - cellW / 2, y: axisY + 0.14, w: cellW, h: 0.26,
+ fontFace: FONT, fontSize: 9, bold: true, color: THEME.black,
+ align: "center", margin: 0,
+ });
+ slide.addText(String(ev.desc || ""), {
+ x: cx - cellW / 2, y: axisY + 0.42, w: cellW, h: 0.85,
+ fontFace: FONT, fontSize: 7.5, color: THEME.midGray, fit: "shrink",
+ align: "center", valign: "top", margin: 0,
+ });
+ });
+}
+
+// Bordered white panel with a accent header and a numbered / check / bullet list.
+// This is the side-column workhorse: place 2-3 of these (or mix with a table,
+// chart, or card region via cols()) to build a dense multi-region slide.
+// items: strings or { title?, text }.
+// Optional header icon (opts.iconData from iconToPng()/svgToPng()) replaces
+// the accent accent bar next to the title — flat monochrome per the deck style.
+function addPanelList(pres, slide, {
+ x = 0.5, y = 1.05, w = 2.94, h = 3.5,
+ title, items = [], style = "numbered", // "numbered" | "check" | "bullet"
+ fontSize = 9, iconData = null,
+} = {}) {
+ assertSlide("addPanelList", pres, slide);
+ warnRectOverlap("addPanelList", slide, x, y, w, h);
+ slide.addShape(pres.shapes.ROUNDED_RECTANGLE, {
+ x, y, w, h, rectRadius: 0.05,
+ fill: { color: THEME.white }, line: { color: "D8D8D8", width: 0.75 },
+ shadow: cardShadow(),
+ });
+ if (iconData) {
+ slide.addImage({ data: iconData, x: x + 0.12, y: y + 0.10, w: 0.26, h: 0.26 });
+ } else {
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: x + 0.14, y: y + 0.13, w: 0.05, h: 0.20,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ }
+ slide.addText(String(title || ""), {
+ x: x + (iconData ? 0.46 : 0.27), y: y + 0.08, w: w - (iconData ? 0.60 : 0.41), h: 0.30,
+ fontFace: FONT, fontSize: 11, bold: true, color: THEME.accent,
+ align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ slide.addShape(pres.shapes.LINE, {
+ x: x + 0.14, y: y + 0.46, w: w - 0.28, h: 0,
+ line: { color: THEME.paleGray, width: 0.75 },
+ });
+ const top = y + 0.58;
+ const n = Math.max(items.length, 1);
+ const rowH = (h - 0.72) / n;
+ if (rowH < 0.32) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addPanelList succeeded, but panel "${String(title).slice(0, 12)}" packs ` +
+ `${n} items into h=${h}" (row height ${rowH.toFixed(2)}") — text will shrink below readable size. ` +
+ "In YOUR slides.js cut to ≤" + Math.max(Math.floor((h - 0.72) / 0.34), 1) + " items or grow the region; " +
+ "do NOT edit components.js."
+ );
+ }
+ const panelChars = items.reduce((s2, it) => {
+ const o = typeof it === "string" ? { text: it } : it;
+ return s2 + visLen(o.title) + visLen(o.text);
+ }, 0);
+ const panelCapacity = estCapacityChars(w - 0.6, h - 0.72, fontSize);
+ const panelFill = panelChars / Math.max(panelCapacity, 1);
+ // Auto-fill: scale the caller's fontSize UP when items are sparse relative
+ // to the panel's capacity (same formula as addTextBlock/addCardGrid) —
+ // `fontSize` stays the floor a caller can still raise explicitly.
+ const panelScale = panelFill < 1 ? Math.min(1.35, Math.max(1, Math.sqrt(0.8 / Math.max(panelFill, 0.14)))) : 1;
+ if (panelFill < 0.16) {
+ warnUnderfill("addPanelList", `panel "${String(title).slice(0, 12)}"`,
+ panelChars, panelCapacity,
+ "make each item a 35-50-char full sentence (fewer items → write each one longer; the only ceiling is fitting " +
+ "the row at default font) and use 5-6 items on tall panels — concrete facts, not labels");
+ }
+ items.forEach((raw, i) => {
+ const it = typeof raw === "string" ? { text: raw } : raw;
+ const iy = top + i * rowH;
+ const D = 0.22 * Math.min(panelScale, 1.2);
+ if (style === "numbered") {
+ slide.addShape(pres.shapes.OVAL, {
+ x: x + 0.14, y: iy + 0.01, w: D, h: D,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(i + 1), {
+ x: x + 0.14, y: iy + 0.01, w: D, h: D,
+ fontFace: FONT, fontSize: 9 * Math.min(panelScale, 1.2), bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ } else if (style === "check") {
+ slide.addShape(pres.shapes.OVAL, {
+ x: x + 0.14, y: iy + 0.01, w: D, h: D,
+ fill: { color: THEME.white }, line: { color: THEME.accent, width: 1.25 },
+ });
+ slide.addText("✓", {
+ x: x + 0.14, y: iy, w: D, h: D,
+ fontFace: FONT, fontSize: 10 * Math.min(panelScale, 1.2), bold: true, color: THEME.accent,
+ align: "center", valign: "middle", margin: 0,
+ });
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ x: x + 0.19, y: iy + 0.07, w: 0.08, h: 0.08,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ }
+ const runs = [];
+ if (it.title) runs.push({ text: it.title, options: { bold: true, color: THEME.black, breakLine: !!it.text } });
+ if (it.text) runs.push({ text: it.text, options: { color: THEME.darkGray } });
+ slide.addText(runs, {
+ x: x + 0.46, y: iy, w: w - 0.60, h: rowH - 0.02,
+ fontFace: FONT, fontSize: fontSize * panelScale, align: "left", valign: "top", margin: 0, fit: "shrink",
+ });
+ if (i < items.length - 1) {
+ slide.addShape(pres.shapes.LINE, {
+ x: x + 0.46, y: top + (i + 1) * rowH - 0.06, w: w - 0.60, h: 0,
+ line: { color: THEME.paleGray, width: 0.5 },
+ });
+ }
+ });
+}
+
+// Editorial table: accent header band, horizontal hairlines only — no vertical
+// grid, no outer frame. Spreadsheet-style full grids read as Excel paste-ins.
+function addComparisonTable(pres, slide, {
+ headers = [], rows = [], x = 0.5, y = 1.05, w = 9.0, colW = null, fontSize = 9, h = null,
+ rowIcons = null, // per-row icon: dataURI string or { initial, color } — needs h (row heights must be known)
+} = {}) {
+ assertSlide("addComparisonTable", pres, slide);
+ if (h) warnRectOverlap("addComparisonTable", slide, x, y, w, h);
+ if (rowIcons && !h) {
+ console.warn(
+ "[CONTENT-LIMIT NOTICE — addComparisonTable succeeded, but rowIcons were skipped] row icons need " +
+ "known row heights — pass `h` (the region height) to this call in YOUR slides.js."
+ );
+ rowIcons = null;
+ }
+ const NO_BORDER = { type: "none" };
+ const HAIRLINE = { pt: 0.5, color: "E5E5E5" };
+ const headerRow = headers.map((hd) => ({
+ text: String(hd),
+ options: {
+ bold: true, color: THEME.white, fill: { color: THEME.accent }, align: "center", valign: "middle",
+ border: [NO_BORDER, NO_BORDER, NO_BORDER, NO_BORDER],
+ },
+ }));
+ const bodyRows = rows.map((r) => r.map((c, ci) => ({
+ text: String(c && typeof c === "object" && c.text !== undefined ? c.text : c),
+ options: {
+ color: THEME.darkGray, fill: { color: THEME.white }, align: "left", valign: "middle",
+ border: [NO_BORDER, NO_BORDER, HAIRLINE, NO_BORDER],
+ margin: rowIcons && ci === 0 ? [0.03, 0.05, 0.03, 0.4] : undefined,
+ },
+ })));
+ // With h set, stretch rows evenly to fill the region (header slightly shorter)
+ // so the table doesn't collapse into a compact strip inside a tall zone.
+ // pptxgenjs tables have NO autofit: text longer than its cell silently
+ // overflows the table region (and bleeds under callouts/banners). So when h
+ // is known, estimate the worst cell's line count and shrink the font until
+ // everything fits its row. CJK chars are ≈ fontSize pt wide — conservative
+ // for Latin, which is fine.
+ let rowH;
+ let fs = fontSize;
+ if (h) {
+ const nRows = Math.max(rows.length, 1);
+ const headerH = Math.min(0.34, h / (nRows + 1));
+ const availPerRow = (h - headerH) / nRows;
+ const nCols = Math.max(headers.length, 1);
+ const widths = Array.isArray(colW) ? colW
+ : (typeof colW === "number" && colW > 0) ? Array(nCols).fill(colW)
+ : Array(nCols).fill(w / nCols);
+ const cellText = (c) => String(c && typeof c === "object" && c.text !== undefined ? c.text : c);
+ let fitted = false;
+ for (;;) {
+ const lineH = (fs * 1.45) / 72;
+ fitted = rows.every((r) => r.every((c, ci) => {
+ const cw = (widths[ci] || widths[0] || w / nCols) - 0.12;
+ const charsPerLine = Math.max(Math.floor(cw / (fs / 72)), 1);
+ const lines = Math.ceil(cellText(c).length / charsPerLine) || 1;
+ return lines * lineH <= availPerRow - 0.05;
+ }));
+ if (fitted || fs <= 7) break;
+ fs = Math.max(fs - 0.5, 7);
+ }
+ if (!fitted) {
+ console.warn(
+ "[CONTENT-LIMIT NOTICE — NOT an API error. The addComparisonTable call succeeded and the deck was generated.] " +
+ "Some table cells hold more text than fits a row even at 7pt. " +
+ "Fix the page content or geometry: shorten each cell to ≤2 lines (~30 CJK chars), widen/reflow the table, " +
+ "or split it across two slides. 这是内容超限提示,不是组件或调用错误。"
+ );
+ }
+ // Underfill: a tall region with too few rows reads as fat empty stripes no
+ // matter how long the cells are — row count is checked before cell fill.
+ if (ADVISORY_QA_ENABLED && h >= 1.4 && rows.length < 4) {
+ console.warn(
+ `[DESIGN-ADVISORY — addComparisonTable: ${rows.length} rows are stretched over h=${h}"] ` +
+ "Confirm the generous row height is intentional; otherwise reduce the table height or choose another composition."
+ );
+ }
+ // Underfill: rows are stretched to fill h, so thin label-like cells read as
+ // empty stripes. Estimate each row's tallest cell text height (display
+ // width: CJK 1em / ASCII 0.55em) against the stretched row height.
+ if (fitted && rows.length) {
+ const lineH = (fs * 1.45) / 72;
+ const fills = rows.map((r) => {
+ const need = Math.max(...r.map((c, ci) => {
+ const cw = (widths[ci] || widths[0] || w / nCols) - 0.12;
+ const charsPerLine = Math.max(cw / (fs / 72), 1);
+ return (Math.ceil(visLen(cellText(c)) / charsPerLine) || 1) * lineH;
+ }));
+ return Math.min(need / availPerRow, 1);
+ });
+ const fill = fills.reduce((a, b) => a + b, 0) / fills.length;
+ if (ADVISORY_QA_ENABLED && fill < 0.4) {
+ console.warn(
+ `[DESIGN-ADVISORY — addComparisonTable: rows use ~${Math.round(fill * 100)}% of their estimated text height] ` +
+ "Keep the spacing when it improves scanning; otherwise reduce the region or use a different comparison treatment."
+ );
+ }
+ }
+ rowH = [headerH, ...rows.map(() => availPerRow)];
+ }
+ slide.addTable([headerRow, ...bodyRows], {
+ x, y, w, colW: colW || undefined, rowH,
+ fontFace: FONT, fontSize: fs, margin: 0.06, autoPage: false,
+ });
+ // Row-head icons (tier-2 enhancement): drawn inside the first column's left
+ // padding; positions derive from the computed row heights.
+ if (rowIcons && rowH) {
+ let ry = y + rowH[0];
+ rows.forEach((r, i) => {
+ const ic = rowIcons[i];
+ const rh = rowH[i + 1];
+ if (ic) {
+ const D = Math.min(0.24, rh - 0.08);
+ const iy = ry + (rh - D) / 2;
+ if (typeof ic === "string") {
+ slide.addImage({ data: ic.replace(/^data:/, ""), x: x + 0.08, y: iy, w: D, h: D });
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ x: x + 0.08, y: iy, w: D, h: D,
+ fill: { color: ic.color || THEME.accent }, line: { color: ic.color || THEME.accent, width: 0 },
+ });
+ slide.addText(String(ic.initial || "").slice(0, 1), {
+ x: x + 0.08, y: iy, w: D, h: D,
+ fontFace: FONT, fontSize: 8.5, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ }
+ }
+ ry += rh;
+ });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Charts
+// ---------------------------------------------------------------------------
+
+// Themed native chart: accent primary series, gray comparison series,
+// value-axis-only grid, flat white plot area, data labels on. Any extra option
+// is passed through to pptxgenjs addChart and overrides the styled defaults —
+// use it for per-page tuning (barGapWidthPct, valAxisMinVal/MaxVal, label
+// sizes …) instead of dropping to slide.addChart and losing the house style.
+function addDeckChart(pres, slide, {
+ type, data, x = 0.5, y = 1.0, w = 5.4, h = 3.4, showLegend = null, ...extra
+} = {}) {
+ assertSlide("addDeckChart", pres, slide);
+ const typeMap = {
+ bar: pres.charts.BAR, line: pres.charts.LINE,
+ pie: pres.charts.PIE, doughnut: pres.charts.DOUGHNUT,
+ };
+ const chartType = typeMap[type];
+ if (!chartType) {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] addDeckChart: type "${type}" ` +
+ 'is not supported. Use one of: "bar", "line", "pie", "doughnut".'
+ );
+ }
+ data = normalizeChartData("addDeckChart", data);
+ const multiSeries = Array.isArray(data) && data.length > 1;
+ const legend = showLegend === null ? multiSeries : showLegend;
+ const opts = {
+ x, y, w, h,
+ chartColors: [THEME.accent, THEME.midGray, THEME.lightGray, THEME.darkGray, THEME.accentMid, THEME.paleGray],
+ chartArea: { fill: { color: THEME.white }, roundedCorners: false },
+ catAxisLabelColor: THEME.midGray, catAxisLabelFontSize: 8, catAxisLabelFontFace: FONT,
+ catAxisLineColor: "C9C9C9",
+ valAxisLabelColor: THEME.midGray, valAxisLabelFontSize: 8, valAxisLabelFontFace: FONT,
+ valAxisLineShow: false,
+ valGridLine: { color: "E8E8E8", size: 0.5 },
+ catGridLine: { style: "none" },
+ showLegend: legend, legendPos: "b", legendFontSize: 8, legendColor: THEME.darkGray,
+ dataLabelColor: THEME.black, dataLabelFontSize: 8, dataLabelFontFace: FONT,
+ };
+ // Data-label precision follows the data: bare defaults round 58.8 → "59" and
+ // 0.7412 → "1", which misreports researched numbers. Pick a format that
+ // preserves the significant digits actually present. Pie/doughnut labels are
+ // percentage fractions — they need a percent format, not the value format.
+ if (type === "pie" || type === "doughnut") {
+ opts.showPercent = true; opts.showLegend = true;
+ opts.dataLabelFormatCode = "0%";
+ } else {
+ const allValues = data.flatMap((s) => s.values);
+ opts.dataLabelFormatCode =
+ allValues.every((v) => Number.isInteger(v)) ? "0" :
+ allValues.every((v) => Math.abs(v) < 1) ? "0.00" : "0.0";
+ }
+ if (type === "bar") {
+ opts.barDir = "col"; opts.showValue = true; opts.dataLabelPosition = "outEnd";
+ // 140 keeps columns slim (gap ≈ 1.4× bar width) — the 60 default rendered
+ // fat, loose bars. A renderer left to auto-scale starts the value axis just
+ // below the data minimum, silently truncating the axis; anchor it at 0
+ // whenever the data allows. Both are per-page overridable via `extra`.
+ opts.barGapWidthPct = 140;
+ const vals = data.flatMap((s) => s.values);
+ if (vals.every((v) => v >= 0)) opts.valAxisMinVal = 0;
+ }
+ if (type === "line") { opts.lineSize = 1.5; opts.lineSmooth = false; opts.showValue = true; }
+ Object.assign(opts, extra);
+ slide.addChart(chartType, data, opts);
+}
+
+// Optional chart-plus-interpretation layout: chart on a white shadow card on
+// the left, numbered insight card + caveat card stacked on the right. All
+// three regions share the cardShadow() white-card shell — no gray boxes.
+function addChartWithInsights(pres, slide, {
+ chart, insights = [], caveats = [],
+ insightsTitle = "关键信号", caveatsTitle = "注意事项",
+} = {}) {
+ assertSlide("addChartWithInsights", pres, slide);
+ const cardShell = (cx2, cy2, cw2, ch2) => slide.addShape(pres.shapes.ROUNDED_RECTANGLE, {
+ x: cx2, y: cy2, w: cw2, h: ch2, rectRadius: 0.05,
+ fill: { color: THEME.white }, line: { color: "D8D8D8", width: 0.75 },
+ shadow: cardShadow(),
+ });
+ const cardTitle = (cx2, cy2, cw2, text) => {
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: cx2 + 0.12, y: cy2 + 0.10, w: 0.05, h: 0.20,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(text), {
+ x: cx2 + 0.25, y: cy2 + 0.08, w: cw2 - 0.37, h: 0.26,
+ fontFace: FONT, fontSize: 10.5, bold: true, color: THEME.accent, align: "left", margin: 0, fit: "shrink",
+ });
+ };
+ cardShell(0.5, 1.00, 5.6, 3.55);
+ addDeckChart(pres, slide, Object.assign({}, chart, { x: 0.65, y: 1.12, w: 5.3, h: 3.3 }));
+
+ const cardX = 6.3, cardW = 3.2;
+ const half = caveats.length ? 1.72 : 3.55;
+ // PowerPoint does not recompute fit:"shrink" until the box is edited, so we
+ // size the list text explicitly to its panel; shrink stays on as a backstop.
+ const warnCardOverflow = (what, fitted, count) => {
+ if (fitted <= 7 || count > 5) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addChartWithInsights succeeded] the ${what} card holds ` +
+ `${count} items and needs ${fitted}pt to fit — text this dense reads badly and can spill outside the panel. ` +
+ "In YOUR slides.js keep 4-5 items of ≤2 short lines each (电报体) — do NOT edit components.js."
+ );
+ }
+ };
+ if (insights.length) {
+ cardShell(cardX, 1.00, cardW, half);
+ cardTitle(cardX, 1.00, cardW, insightsTitle);
+ const insFs = fitListFontSize(insights.map((t, i) => `${i + 1}. ${t}`), cardW - 0.24, half - 0.50, 8.5, 7);
+ warnCardOverflow("insights", insFs, insights.length);
+ warnUnderfill("addChartWithInsights", "the insights card",
+ insights.reduce((s2, t) => s2 + visLen(t) + 3, 0),
+ estCapacityChars(cardW - 0.24, half - 0.50, 8.5),
+ "give 4-5 insights, each a ~20-30-char full sentence that interprets the chart, not a label");
+ slide.addText(
+ insights.map((t, i) => ({ text: `${i + 1}. ${t}`, options: { breakLine: true } })),
+ {
+ x: cardX + 0.12, y: 1.38, w: cardW - 0.24, h: half - 0.46,
+ fontFace: FONT, fontSize: insFs, color: THEME.darkGray,
+ align: "left", valign: "top", margin: 0, paraSpaceAfter: 4, fit: "shrink",
+ }
+ );
+ }
+ if (caveats.length) {
+ const cy = 1.00 + half + 0.12;
+ cardShell(cardX, cy, cardW, 4.55 - cy);
+ cardTitle(cardX, cy, cardW, caveatsTitle);
+ const cavFs = fitListFontSize(caveats.map(String), cardW - 0.44, 4.55 - cy - 0.50, 8.5, 7);
+ warnCardOverflow("caveats", cavFs, caveats.length);
+ warnUnderfill("addChartWithInsights", "the caveats card",
+ caveats.reduce((s2, t) => s2 + visLen(t) + 2, 0),
+ estCapacityChars(cardW - 0.44, 4.55 - cy - 0.50, 8.5),
+ "give 4-5 caveats, each a ~20-30-char full sentence stating a concrete limit or risk");
+ slide.addText(
+ caveats.map((t) => ({ text: t, options: { bullet: { code: "2022", color: THEME.midGray }, breakLine: true } })),
+ {
+ x: cardX + 0.12, y: cy + 0.38, w: cardW - 0.24, h: 4.55 - cy - 0.46,
+ fontFace: FONT, fontSize: cavFs, color: THEME.darkGray,
+ align: "left", valign: "top", margin: 0, paraSpaceAfter: 4, fit: "shrink",
+ }
+ );
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Icons
+// ---------------------------------------------------------------------------
+
+// Rasterize an arbitrary SVG string to a PNG data URI (requires sharp).
+// This is the unlimited-supply path for pipeline hero visuals: draw a custom
+// Flat geometric SVG (geometric shapes, palette the accent color + grays, square
+// corners, stroke-width >= 6 on a 240x240 viewBox) and pass the result as
+// `image` to addPipelineDiagram's glyph stage.
+async function svgToPng(svg, sizePx = 512) {
+ let sharp;
+ try {
+ sharp = require(require.resolve("sharp", { paths: [process.cwd(), __dirname] }));
+ } catch (e) {
+ throw new Error("svgToPng requires the 'sharp' npm package — run: npm install sharp");
+ }
+ const buf = await sharp(Buffer.from(String(svg)), { density: 300 })
+ .resize(sizePx, sizePx, { fit: "inside" }).png().toBuffer();
+ return "image/png;base64," + buf.toString("base64");
+}
+
+// Render a react-icons component to a PNG data URI. Requires react, react-dom, sharp.
+// Only three icon colors are permitted: the accent color, "#000000", "#FFFFFF".
+async function iconToPng(IconComponent, color = "#000000", sizePx = 256) {
+ let React, ReactDOMServer, sharp;
+ try {
+ React = require("react");
+ ReactDOMServer = require("react-dom/server");
+ sharp = require("sharp");
+ } catch (e) {
+ throw new Error(
+ "iconToPng needs react, react-dom and sharp. Install them, or pass `initial` instead of `iconData` to addCardGrid/addPanelList."
+ );
+ }
+ const svg = ReactDOMServer.renderToStaticMarkup(
+ React.createElement(IconComponent, { color, size: String(sizePx) })
+ );
+ const buf = await sharp(Buffer.from(svg)).png().toBuffer();
+ return "image/png;base64," + buf.toString("base64");
+}
+
+
+// Infographic pipeline (the "Hermes MOA 是什么" reference page): N numbered
+// stages, each a bordered column holding icon chips, a supplied hero visual, or badge
+// rows, joined by arrows, with an optional dashed feedback loop underneath.
+// Everything self-sizes to the given rect (chip heights, fonts, visual size),
+// so content never spills — the caller only supplies structure and text.
+//
+// stages: 3-5 of {
+// title, // short column heading (≤8 chars ideal)
+// kind: "chips" | "visual" | "badges",
+// items: [{ iconData?|initial?, color?, label, desc? }], // chips/badges
+// image?, initial?, label, desc, // supplied visual or native fallback + caption
+// }
+// feedback: { from, to, label? } — dashed loop from stage[from] back to stage[to].
+// Chip icon colors may use the secondary palette (soft categorical colors) —
+// the ONE approved colorful-icon context; standalone icon grids stay accent/black/white.
+function addPipelineDiagram(pres, slide, {
+ stages = [], x = 0.5, y = 1.05, w = 9.0, h = 3.6, feedback = null,
+} = {}) {
+ assertSlide("addPipelineDiagram", pres, slide);
+ warnRectOverlap("addPipelineDiagram", slide, x, y, w, h);
+ if (stages.length < 3 || stages.length > 5) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addPipelineDiagram succeeded] ${stages.length} stages given; ` +
+ "the pipeline reads best with 3-5 stages. Merge or split stages in YOUR slides.js — " +
+ "do NOT edit components.js."
+ );
+ }
+ const n = Math.max(stages.length, 1);
+ const GAP = 0.36;
+ const colW = (w - GAP * (n - 1)) / n;
+ const HDR = 0.62;
+ const fbH = feedback ? 0.36 : 0;
+ const bodyY = y + HDR;
+ const bodyH = h - HDR - fbH;
+
+ stages.forEach((st, i) => {
+ const sx = x + i * (colW + GAP);
+ // Numbered accent disc + stage title
+ const D = 0.30;
+ slide.addShape(pres.shapes.OVAL, {
+ x: sx + colW / 2 - D / 2, y, w: D, h: D,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(i + 1), {
+ x: sx + colW / 2 - D / 2, y, w: D, h: D,
+ fontFace: FONT, fontSize: 11, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ slide.addText(String(st.title || ""), {
+ x: sx, y: y + D + 0.03, w: colW, h: 0.24,
+ fontFace: FONT, fontSize: 10, bold: true, color: THEME.black,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ // Column panel
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: sx, y: bodyY, w: colW, h: bodyH,
+ fill: { color: THEME.white }, line: { color: THEME.border, width: 0.75 },
+ });
+ // Inter-stage arrow
+ if (i < n - 1) {
+ slide.addShape(pres.shapes.RIGHT_ARROW, {
+ x: sx + colW + 0.05, y: bodyY + bodyH / 2 - 0.09, w: GAP - 0.10, h: 0.18,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ }
+
+ const PAD = 0.10;
+ if (st.kind === "visual") {
+ const size = Math.min(colW * 0.60, bodyH * 0.50);
+ // Hero visual: caller-supplied image/data URI, or a native initial fallback.
+ const imgOpts = { x: sx + (colW - size) / 2, y: bodyY + PAD + 0.04, w: size, h: size };
+ if (st.image && /^(image\/|data:)/.test(String(st.image))) {
+ slide.addImage(Object.assign({ data: String(st.image).replace(/^data:/, "") }, imgOpts));
+ } else if (st.image) {
+ slide.addImage(Object.assign({ path: st.image }, imgOpts));
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ ...imgOpts,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(st.initial || st.label || st.title || "").slice(0, 1), {
+ ...imgOpts,
+ fontFace: FONT, fontSize: Math.max(16, size * 18), bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ }
+ slide.addText(String(st.label || st.title || ""), {
+ x: sx + PAD, y: bodyY + PAD + size + 0.08, w: colW - PAD * 2, h: 0.24,
+ fontFace: FONT, fontSize: 10, bold: true, color: THEME.accent,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ if (st.desc) {
+ slide.addText(String(st.desc), {
+ x: sx + PAD, y: bodyY + PAD + size + 0.34, w: colW - PAD * 2,
+ h: Math.max(bodyH - PAD * 2 - size - 0.34, 0.2),
+ fontFace: FONT, fontSize: 8, color: THEME.midGray,
+ align: "center", valign: "top", margin: 0, fit: "shrink",
+ });
+ }
+ } else {
+ // chips / badges: vertical stack that self-sizes to the panel
+ const items = st.items || [];
+ const k = Math.max(items.length, 1);
+ if (items.length > 5) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addPipelineDiagram succeeded] stage "${st.title}" holds ` +
+ `${items.length} items; ≤5 fit a column. Merge items in YOUR slides.js — do NOT edit components.js.`
+ );
+ }
+ const IGAP = 0.08;
+ const rowH = Math.min(Math.max((bodyH - PAD * 2 - IGAP * (k - 1)) / k, 0.32), 0.66);
+ const stackH = rowH * k + IGAP * (k - 1);
+ const top = bodyY + Math.max(PAD, (bodyH - stackH) / 2);
+ const withDesc = rowH >= 0.5;
+ items.forEach((it, j) => {
+ const cy = top + j * (rowH + IGAP);
+ if (st.kind === "chips") {
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x: sx + PAD, y: cy, w: colW - PAD * 2, h: rowH,
+ fill: { color: THEME.paleGray }, line: { color: THEME.paleGray, width: 0 },
+ });
+ }
+ const disc = Math.min(rowH - 0.10, 0.34);
+ const dx = sx + PAD + 0.07, dy = cy + (rowH - disc) / 2;
+ if (it.iconData) {
+ slide.addImage({ data: it.iconData, x: dx, y: dy, w: disc, h: disc });
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ x: dx, y: dy, w: disc, h: disc,
+ fill: { color: it.color || THEME.accent }, line: { color: it.color || THEME.accent, width: 0 },
+ });
+ slide.addText(String(it.initial || "").slice(0, 1), {
+ x: dx, y: dy, w: disc, h: disc,
+ fontFace: FONT, fontSize: Math.max(disc * 26, 8), bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ }
+ const runs = [{ text: String(it.label || ""), options: { bold: true, color: THEME.darkText, breakLine: !!(withDesc && it.desc) } }];
+ if (withDesc && it.desc) runs.push({ text: String(it.desc), options: { color: THEME.midGray, fontSize: 7.5 } });
+ slide.addText(runs, {
+ x: dx + disc + 0.09, y: cy, w: colW - PAD * 2 - disc - 0.20, h: rowH,
+ fontFace: FONT, fontSize: withDesc ? 9 : 8.5, align: "left", valign: "middle",
+ margin: 0, fit: "shrink",
+ });
+ });
+ }
+ });
+
+ // Dashed feedback loop along the bottom (e.g. 评估与验证 → 重新聚合)
+ if (feedback && (feedback.from >= n || feedback.to < 0 || feedback.from <= feedback.to)) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addPipelineDiagram succeeded, but the feedback loop was SKIPPED] ` +
+ `feedback {from: ${feedback.from}, to: ${feedback.to}} is invalid for ${n} stages — indexes are 0-based ` +
+ `(0..${n - 1}) and must satisfy from > to. Fix the indexes in YOUR slides.js; do NOT edit components.js.`
+ );
+ feedback = null;
+ }
+ if (feedback && feedback.from > feedback.to) {
+ const cxOf = (i2) => x + i2 * (colW + GAP) + colW / 2;
+ const x1 = cxOf(feedback.from), x2 = cxOf(feedback.to);
+ const ly = y + h - fbH + 0.16;
+ const mk = () => ({ color: THEME.midGray, width: 1, dashType: "dash" });
+ slide.addShape(pres.shapes.LINE, { x: x1, y: bodyY + bodyH, w: 0, h: ly - (bodyY + bodyH), line: mk() });
+ slide.addShape(pres.shapes.LINE, { x: x2, y: ly, w: x1 - x2, h: 0, line: mk() });
+ slide.addShape(pres.shapes.LINE, { x: x2, y: bodyY + bodyH, w: 0, h: ly - (bodyY + bodyH), line: mk() });
+ slide.addShape(pres.shapes.ISOSCELES_TRIANGLE, {
+ x: x2 - 0.05, y: bodyY + bodyH - 0.02, w: 0.10, h: 0.09,
+ fill: { color: THEME.midGray }, line: { color: THEME.midGray, width: 0 },
+ });
+ if (feedback.label) {
+ // Label box spans the full loop width (min 1.6") and shrinks to fit —
+ // narrow adjacent-column loops must not clip the text.
+ const lw = Math.max(Math.abs(x1 - x2) - 0.3, 1.6);
+ slide.addText(String(feedback.label), {
+ x: Math.max((x1 + x2) / 2 - lw / 2, x), y: ly - 0.20, w: Math.min(lw, w - 0.2), h: 0.18,
+ fontFace: FONT, fontSize: 7.5, color: THEME.midGray, align: "center", margin: 0, fit: "shrink",
+ });
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Graphic-first skeletons (tier-1 main-region components)
+// ---------------------------------------------------------------------------
+
+// Feature cards where a BIG icon is the visual anchor (not a caption garnish):
+// pale card, 0.52" icon disc on top, bold title, 2-3 lines of fact text.
+// cards: [{ iconData?|initial?, color?, title, text }] — disc colors may use
+// the soft secondary palette; keep one concept = one color across the deck.
+function addIconCards(pres, slide, {
+ cards = [], columns = 0, x = 0.5, y = 1.05, w = 9.0, h = 3.6,
+} = {}) {
+ assertSlide("addIconCards", pres, slide);
+ warnRectOverlap("addIconCards", slide, x, y, w, h);
+ const n = Math.max(cards.length, 1);
+ const cols = columns || (n <= 3 ? n : Math.ceil(n / 2));
+ const rows = Math.ceil(n / cols);
+ const gap = 0.18;
+ const cardW = (w - gap * (cols - 1)) / cols;
+ const cardH = (h - gap * (rows - 1)) / rows;
+ cards.forEach((card, i) => {
+ const cx = x + (i % cols) * (cardW + gap);
+ const cy = y + Math.floor(i / cols) * (cardH + gap);
+ addPanel(pres, slide, { fill: THEME.paleGray, x: cx, y: cy, w: cardW, h: cardH });
+ const D = Math.min(0.52, cardH * 0.30);
+ const dx = cx + (cardW - D) / 2, dy = cy + 0.14;
+ if (card.iconData) {
+ slide.addImage({ data: card.iconData, x: dx, y: dy, w: D, h: D });
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ x: dx, y: dy, w: D, h: D,
+ fill: { color: card.color || THEME.accent }, line: { color: card.color || THEME.accent, width: 0 },
+ });
+ slide.addText(String(card.initial || "").slice(0, 1), {
+ x: dx, y: dy, w: D, h: D,
+ fontFace: FONT, fontSize: D * 32, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ }
+ slide.addText(String(card.title || ""), {
+ x: cx + 0.10, y: cy + 0.14 + D + 0.06, w: cardW - 0.20, h: 0.28,
+ fontFace: FONT, fontSize: 10.5, bold: true, color: THEME.accent,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ slide.addText(String(card.text || ""), {
+ x: cx + 0.14, y: cy + 0.14 + D + 0.38, w: cardW - 0.28,
+ h: Math.max(cardH - 0.14 - D - 0.48, 0.2),
+ fontFace: FONT, fontSize: 8.5, color: THEME.darkGray,
+ align: "left", valign: "top", margin: 0, fit: "shrink",
+ });
+ warnUnderfill("addIconCards", `card "${String(card.title).slice(0, 12)}"`,
+ visLen(card.text),
+ estCapacityChars(cardW - 0.28, cardH - 0.14 - D - 0.48, 8.5),
+ "give this card ~2-3 sentences of concrete facts, or reduce the region height");
+ });
+}
+
+// Hub-and-spoke: one core concept in the middle, 3-6 related facets around it,
+// dashed connectors. center: { image?, label, desc? }.
+// spokes: [{ iconData?|initial?, color?, label, desc? }].
+function addHubSpoke(pres, slide, {
+ center = {}, spokes = [], x = 0.4, y = 1.05, w = 6.1, h = 3.6,
+} = {}) {
+ assertSlide("addHubSpoke", pres, slide);
+ warnRectOverlap("addHubSpoke", slide, x, y, w, h);
+ if (spokes.length < 3 || spokes.length > 6) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addHubSpoke succeeded] ${spokes.length} spokes given; 3-6 read best. ` +
+ "Merge or split facets in YOUR slides.js — do NOT edit components.js."
+ );
+ }
+ const cx = x + w / 2, cy = y + h / 2;
+ const R = Math.min(0.62, h * 0.17); // hub circle radius
+ const rx = w / 2 - 1.05, ry = h / 2 - 0.62; // spoke orbit
+ const n = Math.max(spokes.length, 1);
+ // Connectors first (under everything)
+ spokes.forEach((sp, i) => {
+ const a = -Math.PI / 2 + (i * 2 * Math.PI) / n;
+ const sx = cx + rx * Math.cos(a), sy = cy + ry * Math.sin(a);
+ slide.addShape(pres.shapes.LINE, {
+ x: Math.min(cx, sx), y: Math.min(cy, sy), w: Math.abs(sx - cx), h: Math.abs(sy - cy),
+ flipH: sx < cx, flipV: (sy < cy) !== (sx < cx),
+ line: { color: THEME.lightGray, width: 1, dashType: "dash" },
+ });
+ });
+ // Hub
+ slide.addShape(pres.shapes.OVAL, {
+ x: cx - R, y: cy - R, w: R * 2, h: R * 2,
+ fill: { color: THEME.white }, line: { color: THEME.accent, width: 1.75 },
+ });
+ const hubImg = center.image || null;
+ if (hubImg) {
+ const G = R * 1.05;
+ const io = /^(image\/|data:)/.test(String(hubImg))
+ ? { data: String(hubImg).replace(/^data:/, "") } : { path: hubImg };
+ slide.addImage(Object.assign(io, { x: cx - G / 2, y: cy - G / 2 - R * 0.18, w: G, h: G }));
+ slide.addText(String(center.label || ""), {
+ x: cx - R, y: cy + R * 0.42, w: R * 2, h: R * 0.5,
+ fontFace: FONT, fontSize: 8.5, bold: true, color: THEME.accent,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ } else {
+ slide.addText(String(center.label || ""), {
+ x: cx - R, y: cy - R, w: R * 2, h: R * 2,
+ fontFace: FONT, fontSize: 11, bold: true, color: THEME.accent,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ }
+ // Spokes
+ const D = 0.4, TW = Math.min(1.85, (w - 1) / 3);
+ spokes.forEach((sp, i) => {
+ const a = -Math.PI / 2 + (i * 2 * Math.PI) / n;
+ const sx = cx + rx * Math.cos(a), sy = cy + ry * Math.sin(a);
+ if (sp.iconData) {
+ slide.addImage({ data: sp.iconData, x: sx - D / 2, y: sy - D / 2, w: D, h: D });
+ } else {
+ slide.addShape(pres.shapes.OVAL, {
+ x: sx - D / 2, y: sy - D / 2, w: D, h: D,
+ fill: { color: sp.color || THEME.accent }, line: { color: sp.color || THEME.accent, width: 0 },
+ });
+ slide.addText(String(sp.initial || "").slice(0, 1), {
+ x: sx - D / 2, y: sy - D / 2, w: D, h: D,
+ fontFace: FONT, fontSize: 12, bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ }
+ const below = sy >= cy; // stack text away from the hub
+ const ty = below ? sy + D / 2 + 0.04 : sy - D / 2 - 0.66;
+ slide.addText(String(sp.label || ""), {
+ x: sx - TW / 2, y: ty, w: TW, h: 0.22,
+ fontFace: FONT, fontSize: 9, bold: true, color: THEME.black,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ slide.addText(String(sp.desc || ""), {
+ x: sx - TW / 2, y: ty + 0.22, w: TW, h: 0.40,
+ fontFace: FONT, fontSize: 7.5, color: THEME.midGray,
+ align: "center", valign: "top", margin: 0, fit: "shrink",
+ });
+ });
+}
+
+// Thin spectrum/positioning axis (低成本 → 高质量): accent arrow baseline with
+// 2-5 tick dots. A thin band — pair it under a table/matrix, never alone.
+// ticks: [{ label, desc?, pos? }] (pos 0-1 optional, defaults to even spread).
+function addSpectrumAxis(pres, slide, {
+ ticks = [], x = 0.5, y = 3.8, w = 9.0, leftLabel = "", rightLabel = "",
+} = {}) {
+ assertSlide("addSpectrumAxis", pres, slide);
+ warnRectOverlap("addSpectrumAxis", slide, x, y, w, 0.85);
+ const pad = leftLabel || rightLabel ? 0.95 : 0.25;
+ const ax = x + pad, aw = w - pad * 2;
+ slide.addShape(pres.shapes.LINE, {
+ x: ax, y: y + 0.10, w: aw, h: 0,
+ line: { color: THEME.accent, width: 2 },
+ });
+ slide.addShape(pres.shapes.ISOSCELES_TRIANGLE, {
+ x: ax + aw - 0.02, y: y + 0.03, w: 0.14, h: 0.14, rotate: 90,
+ fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ if (leftLabel) slide.addText(String(leftLabel), {
+ x, y: y + 0.01, w: pad - 0.08, h: 0.2, fontFace: FONT, fontSize: 8.5,
+ bold: true, color: THEME.darkGray, align: "right", valign: "middle", margin: 0, fit: "shrink",
+ });
+ if (rightLabel) slide.addText(String(rightLabel), {
+ x: ax + aw + 0.12, y: y + 0.01, w: pad - 0.08, h: 0.2, fontFace: FONT, fontSize: 8.5,
+ bold: true, color: THEME.darkGray, align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ const n = Math.max(ticks.length, 1);
+ const TW = Math.min(2.2, aw / n);
+ ticks.forEach((t, i) => {
+ const p = typeof t.pos === "number" ? t.pos : (n === 1 ? 0.5 : i / (n - 1) * 0.84 + 0.08);
+ const tx = ax + aw * p;
+ slide.addShape(pres.shapes.OVAL, {
+ x: tx - 0.055, y: y + 0.045, w: 0.11, h: 0.11,
+ fill: { color: THEME.accent }, line: { color: THEME.white, width: 1 },
+ });
+ slide.addText(String(t.label || ""), {
+ x: tx - TW / 2, y: y + 0.22, w: TW, h: 0.2,
+ fontFace: FONT, fontSize: 8.5, bold: true, color: THEME.black,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ if (t.desc) slide.addText(String(t.desc), {
+ x: tx - TW / 2, y: y + 0.42, w: TW, h: 0.34,
+ fontFace: FONT, fontSize: 7.5, color: THEME.midGray,
+ align: "center", valign: "top", margin: 0, fit: "shrink",
+ });
+ });
+}
+
+
+// Paper-figure visual region — the peer of addSystemDiagram for pages that
+// introduce a specific paper. Figures are the paper's own, extracted verbatim
+// by scripts/extract_arxiv_visuals_v2_2.py; they are pasted as-is (no border,
+// no fill) because they are quotations, not our artwork. `figures` is
+// { path, label }[] — 1-3 of them. Optional `heading` draws a black centered
+// column heading atop the region (see addRegionHeading), exactly as
+// addSystemDiagram/addTextBlock do. Returns the layout descriptor.
+function addFigurePanel(pres, slide, { x = 0.5, y = 1.05, w = 5.4, h = 3.6, heading, figures = [] } = {}) {
+ assertSlide("addFigurePanel", pres, slide);
+ warnRectOverlap("addFigurePanel", slide, x, y, w, h);
+ if (figures.length > 3) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addFigurePanel succeeded] the panel packs ${figures.length} figures; ` +
+ "a visual region reads best with 1-3. Drop the weakest ones in YOUR slides.js, or split the page — " +
+ "do NOT edit components.js."
+ );
+ }
+ let by = y, bh = h;
+ if (heading) { by = addRegionHeading(pres, slide, { text: heading, x, y, w }); bh = h - (by - y); }
+ return renderFigurePanel({ slide, figures, bounds: { x, y: by, w, h: bh } });
+}
+
+
+// Plain black, bold, CENTER-aligned heading drawn just above a region, summarizing
+// what that region shows (e.g. "传统Agent优化流程" over a diagram, "关键问题" over a
+// text column). NOT the accent page title (addSlideTitle) and NOT addTextBlock's
+// accent-bar `title` — it's the black centered label the 图文分栏 recipe puts atop each
+// column. PUBLIC component: call it directly to put ONE shared heading atop a
+// multi-chart / multi-diagram visual region (the sub-figures then start below the
+// returned y), since addDeckChart et al. have no `heading` param of their own. For
+// a single addSystemDiagram / addTextBlock region, pass `heading` to those instead —
+// they call this internally. Returns the y the region's content should start at.
+const REGION_HEADING_H = 0.30;
+const REGION_HEADING_GAP = 0.04;
+function addRegionHeading(pres, slide, { text, x = 0.5, y = 1.05, w = 9.0 } = {}) {
+ assertSlide("addRegionHeading", pres, slide);
+ slide.addText(String(text), {
+ x, y, w, h: REGION_HEADING_H,
+ fontFace: FONT, fontSize: 12.5, bold: true, color: THEME.black,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ return y + REGION_HEADING_H + REGION_HEADING_GAP;
+}
+
+// Declarative system diagram (bands/groups/items/edges) drawn as native shapes
+// into a content-page region. `spec` is a Diagram IR; see system-diagram.js and
+// pptxgenjs.md. `density` auto-selects from region width when omitted. Optional
+// `heading` draws a black centered column heading atop the region (see
+// addRegionHeading) and shrinks the diagram area beneath it. Returns the engine's
+// layout descriptor { bounds, nodes, groups, edgeLabels, warnings }.
+function addSystemDiagram(pres, slide, { spec, x = 0.5, y = 1.05, w = 9.0, h = 3.6, density, heading } = {}) {
+ assertSlide("addSystemDiagram", pres, slide);
+ warnRectOverlap("addSystemDiagram", slide, x, y, w, h);
+ let by = y, bh = h;
+ if (heading) { by = addRegionHeading(pres, slide, { text: heading, x, y, w }); bh = h - (by - y); }
+ const dens = density || (w >= 8 ? "full" : w >= 4 ? "split" : "compact");
+ const d = DIAGRAM_DENSITY[dens] || DIAGRAM_DENSITY.full;
+ const theme = { ...DEFAULT_THEME, fontMin: d.fontMin, fontMax: d.fontMax };
+ return renderSystemDiagram({ pres, slide, spec, bounds: { x, y: by, w, h: bh }, theme });
+}
+
+// Unboxed structured text region — the DEFAULT for text areas (contrast the
+// gray-filled addCardGrid/addPanel). White, NO background fill. Items are
+// { title, body, children[] } (a bare string is treated as { body }). Style only
+// controls presentation; markers are native shapes / safe glyphs, never exotic
+// characters that font substitution mangles.
+// "numbered" — accent disc + white number, title (accent bold), body, bulleted children
+// "sectioned" — accent bar + title (accent bold), body, bulleted children
+// "bullets" — title (accent bold), body + children as gray bullets, no marker
+// Optional `heading` draws a black centered column heading atop the region (see
+// addRegionHeading) and shrinks the text area beneath it — this is the black
+// "关键问题"-style label, distinct from the accent-bar `title`.
+function addTextBlock(pres, slide, { x = 0.5, y = 1.05, w = 3.3, h = 3.5, title, items = [], style = "numbered", heading } = {}) {
+ assertSlide("addTextBlock", pres, slide);
+ warnRectOverlap("addTextBlock", slide, x, y, w, h);
+ if (heading) { const ny = addRegionHeading(pres, slide, { text: heading, x, y, w }); h -= ny - y; y = ny; }
+ let top = y;
+ if (title) {
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x, y: y + 0.04, w: 0.06, h: 0.24, fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(title), {
+ x: x + 0.16, y, w: w - 0.16, h: 0.32, fontFace: FONT, fontSize: 12, bold: true,
+ color: THEME.accent, align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ top = y + 0.44;
+ }
+ const norm = items.map((it) => (typeof it === "string" ? { body: it } : it || {}));
+ const n = Math.max(norm.length, 1);
+ const gap = 0.12;
+ const slotH = (y + h - top - gap * (n - 1)) / n;
+
+ // Auto-fill: scale font size UP when content is sparse relative to the
+ // block's capacity, instead of rendering fixed-size text that leaves the
+ // container looking thin. Capacity/size are inversely related by ~the
+ // square (more chars per line AND more lines as font shrinks), so solving
+ // charsUsed ≈ capacity(fontScale) gives fontScale ≈ sqrt(capacityAtBase /
+ // charsUsed). Floor at 1 (never shrink here — `fit:"shrink"` below is the
+ // separate overflow safety valve for genuinely dense content).
+ const blockChars = norm.reduce((sum, it) =>
+ sum + visLen(it.title) + visLen(it.body) +
+ (it.children || []).reduce((a, c) => a + visLen(c), 0), 0);
+ const capacityAtBase = estCapacityChars(w - 0.5, (y + h) - top, 9.5);
+ const fillRatio = blockChars / Math.max(capacityAtBase, 1);
+ const fontScale = fillRatio < 1 ? Math.min(1.4, Math.max(1, Math.sqrt(0.8 / Math.max(fillRatio, 0.13)))) : 1;
+
+ norm.forEach((it, i) => {
+ const sy = top + i * (slotH + gap);
+ let textX = x;
+ if (style === "numbered") {
+ const D = 0.26 * Math.min(fontScale, 1.25);
+ slide.addShape(pres.shapes.OVAL, {
+ x, y: sy, w: D, h: D, fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ slide.addText(String(i + 1), {
+ x, y: sy, w: D, h: D, fontFace: FONT, fontSize: 11 * Math.min(fontScale, 1.25), bold: true, color: THEME.white,
+ align: "center", valign: "middle", margin: 0,
+ });
+ textX = x + D + 0.12;
+ } else if (style === "sectioned") {
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x, y: sy + 0.03, w: 0.06, h: 0.20, fill: { color: THEME.accent }, line: { color: THEME.accent, width: 0 },
+ });
+ textX = x + 0.18;
+ }
+ const runs = [];
+ if (it.title) runs.push({ text: String(it.title), options: { bold: true, color: THEME.accent, fontSize: 11 * fontScale, breakLine: true } });
+ if (it.body) runs.push({ text: String(it.body), options: { color: THEME.darkGray, fontSize: 9.5 * fontScale, breakLine: true } });
+ (it.children || []).forEach((c) => runs.push({
+ text: String(c), options: { color: THEME.midGray, fontSize: 9 * fontScale, bullet: { code: "2022", indent: 12 }, breakLine: true },
+ }));
+ if (runs.length) {
+ slide.addText(runs, {
+ x: textX, y: sy, w: x + w - textX, h: slotH, fontFace: FONT,
+ align: "left", valign: "top", margin: 0, paraSpaceAfter: 3 * fontScale, fit: "shrink",
+ });
+ }
+ });
+ // Density signal: a very low fill ratio means the container is left mostly
+ // empty. Content pages must be filled, so nudge the caller to write more.
+ if (fillRatio < 0.16) {
+ warnUnderfill("addTextBlock", `text block "${String(title || (norm[0] && norm[0].title) || "").slice(0, 12)}"`,
+ blockChars, capacityAtBase,
+ "每条给 title + 1-2 句完整 body(35-50 字)+ 必要时 2-3 条 children;纯文字页每列 2-4 段、拉满高度");
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Reference-vocabulary structural components — the tinted matrix, converge
+// funnel, and chevron stage band that the reference decks use as their
+// signature "one big structural graphic" page language. Combine top-to-bottom
+// (matrix → funnel → stages) to reproduce that page shape, or use each alone.
+
+// Pastel fills reserved for group headers — the deck-wide "淡彩仅限分组头"
+// palette exception. Body cards stay white; accents stay the accent color.
+const MATRIX_TINTS = [
+ { fill: "EEEAF7", line: "C8BEDF" }, // violet
+ { fill: "FAEEE4", line: "E5C9B3" }, // orange
+ { fill: "E8F1F8", line: "B9D1E2" }, // blue
+ { fill: "F7E9EE", line: "DDBFCC" }, // pink
+ { fill: "EAF3E8", line: "BFD8BC" }, // green
+ { fill: "FFF6DE", line: "E3D3A3" }, // yellow
+];
+
+// Three-row classification matrix: tinted group headers, white sub-headers,
+// white item cards with hairline dividers. Group width follows its sub count.
+// groups: [{ name, subs: [{ name, items: ["...", ...] }] }]
+// rowLabels: e.g. ["族群", "子类", "具体条目"] for the narrow left label column
+// (pass null to omit). Subs without items collapse the matrix to two rows.
+function addTintMatrix(pres, slide, {
+ x = 0.5, y = 1.05, w = 9.0, h = 1.7,
+ rowLabels = null, groups = [],
+} = {}) {
+ assertSlide("addTintMatrix", pres, slide);
+ warnRectOverlap("addTintMatrix", slide, x, y, w, h);
+ const normGroups = groups.map((g) => ({
+ ...g, subs: g.subs && g.subs.length ? g.subs : [{ name: g.name, items: [] }],
+ }));
+ const totalSubs = normGroups.reduce((s, g) => s + g.subs.length, 0);
+ if (!totalSubs) return;
+ if (totalSubs > 9) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addTintMatrix succeeded, but ${totalSubs} sub-columns squeeze below readable ` +
+ `width on w=${w}". In YOUR slides.js merge to ≤9 sub-columns; do NOT edit components.js.`
+ );
+ }
+ const hasItems = normGroups.some((g) => g.subs.some((sb) => (sb.items || []).length));
+ const labelW = rowLabels ? 0.62 : 0;
+ const dataX = x + (rowLabels ? labelW + 0.08 : 0);
+ const dataW = x + w - dataX;
+ const unit = dataW / totalSubs;
+ const headH = 0.30, subH = 0.31, gapY = 0.035;
+ const itemH = hasItems ? Math.max(h - headH - subH - gapY * 2, 0.4) : 0;
+ if (rowLabels) {
+ const rows = [
+ { text: rowLabels[0], ry: y, rh: headH },
+ { text: rowLabels[1], ry: y + headH + gapY, rh: subH },
+ { text: rowLabels[2], ry: y + headH + subH + gapY * 2, rh: itemH },
+ ];
+ rows.forEach((r) => {
+ if (!r.text || !r.rh) return;
+ slide.addShape(pres.shapes.RECTANGLE, {
+ x, y: r.ry, w: labelW, h: r.rh,
+ fill: { color: "F2F2F2" }, line: { color: "E1E1E1", width: 0.55 },
+ });
+ slide.addText(String(r.text), {
+ x, y: r.ry, w: labelW, h: r.rh, fontFace: FONT, fontSize: 8, bold: true,
+ color: THEME.midGray, align: "center", valign: "middle", margin: 0.02, fit: "shrink",
+ });
+ });
+ }
+ let gx = dataX;
+ normGroups.forEach((g, gi) => {
+ const tint = MATRIX_TINTS[gi % MATRIX_TINTS.length];
+ const gw = unit * g.subs.length;
+ slide.addShape(pres.shapes.ROUNDED_RECTANGLE, {
+ x: gx, y, w: gw - 0.05, h: headH, rectRadius: 0.04,
+ fill: { color: tint.fill }, line: { color: tint.line, width: 0.55 },
+ });
+ slide.addText(String(g.name), {
+ x: gx, y, w: gw - 0.05, h: headH, fontFace: FONT, fontSize: 10, bold: true,
+ color: THEME.darkText, align: "center", valign: "middle", margin: 0.02, fit: "shrink",
+ });
+ g.subs.forEach((sub, si) => {
+ const sx = gx + si * unit;
+ const sy = y + headH + gapY;
+ slide.addShape(pres.shapes.ROUNDED_RECTANGLE, {
+ x: sx, y: sy, w: unit - 0.05, h: subH, rectRadius: 0.04,
+ fill: { color: THEME.white }, line: { color: tint.line, width: 0.55 },
+ });
+ slide.addText(String(sub.name), {
+ x: sx, y: sy, w: unit - 0.05, h: subH, fontFace: FONT, fontSize: 9, bold: true,
+ color: THEME.darkText, align: "center", valign: "middle", margin: 0.02, fit: "shrink",
+ });
+ const items = sub.items || [];
+ if (!hasItems) return;
+ const iy = sy + subH + gapY;
+ slide.addShape(pres.shapes.ROUNDED_RECTANGLE, {
+ x: sx, y: iy, w: unit - 0.05, h: itemH, rectRadius: 0.04,
+ fill: { color: THEME.white }, line: { color: "D8D8D8", width: 0.55 },
+ shadow: cardShadow(),
+ });
+ const cellH = itemH / Math.max(items.length, 1);
+ items.forEach((it, ii) => {
+ slide.addText(String(it), {
+ x: sx + 0.06, y: iy + ii * cellH, w: unit - 0.17, h: cellH,
+ fontFace: FONT, fontSize: 8.5, color: THEME.darkText,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ if (ii < items.length - 1) {
+ slide.addShape(pres.shapes.LINE, {
+ x: sx + 0.12, y: iy + (ii + 1) * cellH, w: unit - 0.29, h: 0,
+ line: { color: "E5E5E5", width: 0.5 },
+ });
+ }
+ });
+ });
+ gx += gw;
+ });
+}
+
+// Layered translucent gray funnel + down arrow: "everything above converges
+// into what follows". Optional accent caption below, flanked by hairlines.
+function addConvergeFunnel(pres, slide, { x = 0.5, y = 1.05, w = 9.0, h = 0.62, label } = {}) {
+ assertSlide("addConvergeFunnel", pres, slide);
+ warnRectOverlap("addConvergeFunnel", slide, x, y, w, h);
+ const funnelH = label ? Math.max(h - 0.26, 0.3) : h;
+ slide.addShape(pres.shapes.TRAPEZOID, {
+ x: x + 0.06, y, w: w - 0.12, h: funnelH * 0.58, rotate: 180,
+ fill: { color: "D6D6D6", transparency: 50 }, line: { color: "D6D6D6", transparency: 100 },
+ });
+ slide.addShape(pres.shapes.TRAPEZOID, {
+ x: x + w * 0.12, y: y + funnelH * 0.16, w: w * 0.76, h: funnelH * 0.5, rotate: 180,
+ fill: { color: "C9C9C9", transparency: 65 }, line: { color: "C9C9C9", transparency: 100 },
+ });
+ slide.addShape(pres.shapes.DOWN_ARROW, {
+ x: x + w / 2 - 0.43, y: y + funnelH * 0.36, w: 0.86, h: funnelH * 0.64,
+ fill: { color: "C4C4C4", transparency: 36 }, line: { color: "C4C4C4", transparency: 100 },
+ });
+ if (label) {
+ const ly = y + funnelH + 0.02;
+ const textW = Math.min(Math.max(visLen(label) * 0.16, 1.6), w * 0.5);
+ const lineW = (w - textW) / 2 - 0.15;
+ slide.addShape(pres.shapes.LINE, {
+ x, y: ly + 0.12, w: lineW, h: 0, line: { color: "C7C7C7", width: 0.8 },
+ });
+ slide.addShape(pres.shapes.LINE, {
+ x: x + w - lineW, y: ly + 0.12, w: lineW, h: 0, line: { color: "C7C7C7", width: 0.8 },
+ });
+ slide.addText(String(label), {
+ x: x + (w - textW) / 2, y: ly, w: textW, h: 0.24, fontFace: FONT, fontSize: 10.2,
+ bold: true, color: THEME.accent, align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ }
+}
+
+// Chevron stage band with optional white output cards under each stage.
+// stages: [{ name, card?: { title, items: ["...", "..."] } }] (items ≤3).
+// Band only when no stage has a card; cards get the shared soft shadow and a
+// small tick connecting them to their stage.
+function addChevronStages(pres, slide, {
+ x = 0.5, y = 1.05, w = 9.0, h = 1.3, stages = [],
+} = {}) {
+ assertSlide("addChevronStages", pres, slide);
+ warnRectOverlap("addChevronStages", slide, x, y, w, h);
+ const n = stages.length;
+ if (!n) return;
+ if (n > 5) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addChevronStages succeeded, but ${n} stages crowd w=${w}". ` +
+ "In YOUR slides.js merge to ≤5 stages; do NOT edit components.js."
+ );
+ }
+ const bandH = 0.34;
+ const gap = 0.06;
+ const cellW = (w - gap * (n - 1)) / n;
+ const anyCard = stages.some((st) => st.card);
+ stages.forEach((st, i) => {
+ const sx = x + i * (cellW + gap);
+ slide.addShape(i < n - 1 ? pres.shapes.CHEVRON : pres.shapes.PENTAGON, {
+ x: sx, y, w: cellW, h: bandH,
+ fill: { color: i % 2 ? "EAEAEA" : "F0F0F0" }, line: { color: "D5D5D5", width: 0.55 },
+ });
+ slide.addText(String(st.name), {
+ x: sx + 0.05, y, w: cellW - 0.18, h: bandH, fontFace: FONT, fontSize: 9.7,
+ bold: true, color: THEME.accent, align: "center", valign: "middle", margin: 0.01, fit: "shrink",
+ });
+ if (!anyCard) return;
+ const cardY = y + bandH + 0.12;
+ const cardH = Math.max(h - bandH - 0.12, 0.5);
+ slide.addShape(pres.shapes.LINE, {
+ x: sx + cellW / 2, y: y + bandH - 0.02, w: 0, h: cardY - y - bandH + 0.02,
+ line: { color: "BDBDBD", width: 1.0 },
+ });
+ slide.addShape(pres.shapes.ROUNDED_RECTANGLE, {
+ x: sx, y: cardY, w: cellW, h: cardH, rectRadius: 0.06,
+ fill: { color: THEME.white }, line: { color: "D6D6D6", width: 0.65 },
+ shadow: cardShadow(),
+ });
+ const card = st.card;
+ if (!card) return;
+ const items = card.items || [];
+ if (items.length > 3) {
+ console.warn(
+ `[CONTENT-LIMIT NOTICE — addChevronStages succeeded, but stage "${String(st.name).slice(0, 12)}" ` +
+ "packs " + items.length + " card items (≤3 stay readable). Trim in YOUR slides.js; do NOT edit components.js."
+ );
+ }
+ const titleW = card.title ? Math.min(cellW * 0.34, 1.0) : 0;
+ if (card.title) {
+ slide.addText(String(card.title), {
+ x: sx + 0.14, y: cardY + 0.08, w: titleW, h: 0.22, fontFace: FONT, fontSize: 9.3,
+ bold: true, color: THEME.accent, align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ }
+ const tx0 = sx + 0.14 + (card.title ? titleW + 0.06 : 0);
+ const tw = sx + cellW - 0.12 - tx0;
+ const rowH = (cardH - 0.14) / Math.max(items.length, 1);
+ items.forEach((it, ii) => {
+ slide.addText(String(it), {
+ x: tx0, y: cardY + 0.07 + ii * rowH, w: tw, h: rowH, fontFace: FONT, fontSize: 8.3,
+ color: THEME.darkText, align: "left", valign: "middle", margin: 0, fit: "shrink",
+ });
+ if (ii < items.length - 1) {
+ slide.addShape(pres.shapes.LINE, {
+ x: tx0, y: cardY + 0.07 + (ii + 1) * rowH, w: tw - 0.05, h: 0,
+ line: { color: "E4E4E4", width: 0.55 },
+ });
+ }
+ });
+ });
+}
+
+module.exports = {
+ THEME, TY, LAYOUT, withHash, cols,
+ addSlideTitle, addPanel, addSlideFooter, addSourceNote, addSummaryBanner, addContentChrome,
+ addOpeningSlide, addTocSlide, addClosingSlide,
+ addKpiRow, addCardGrid, addTimeline, addComparisonTable,
+ addPanelList,
+ addDeckChart, addChartWithInsights,
+ iconToPng, svgToPng,
+ addPipelineDiagram, addIconCards, addHubSpoke, addSpectrumAxis,
+ addSystemDiagram, addTextBlock, addRegionHeading, addFigurePanel,
+ addTintMatrix, addConvergeFunnel, addChevronStages,
+ item, group, bandNode, groupBand,
+};
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/demo_components.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/demo_components.js
new file mode 100644
index 0000000000..019ab7d226
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/demo_components.js
@@ -0,0 +1,252 @@
+// scripts/demo_components.js — full-deck demo of components.js.
+// Run from anywhere: node demo_components.js (writes demo.pptx to cwd)
+// Optional component gallery. These pages demonstrate APIs; they are not a
+// recommended deck outline, a layout quota, or a template contract.
+// 内容页以「图文分栏页」为主(P3-P5 是单图/上下双图/并列多图三形态的黄金范例),
+// 其后每种页型各示范一次;不为多样性堆组件。规范:标题无序号、横幅纯文字居中、继承母版页脚。
+// Resolve pptxgenjs from the caller's cwd first (the agent workspace has node_modules),
+// then from this script's own directory.
+const pptxgen = require(require.resolve("pptxgenjs", { paths: [process.cwd(), __dirname] }));
+const C = require(require("path").join(__dirname, "components.js"));
+
+async function main() {
+ const pres = new pptxgen();
+ pres.layout = "LAYOUT_16x9";
+
+ C.addOpeningSlide(pres, { title: "组件库演示", department: "演示部门", author: "演示作者", date: "2026-07-02" });
+ // TOC titles are informative business phrases (8-16 chars), never abstract two-word labels.
+ C.addTocSlide(pres, { title: "目录", sections: [
+ { num: "1", title: "多智能体商业化应用初步涌现" },
+ { num: "2", title: "主流多智能体方案简介" },
+ { num: "3", title: "头部公司 Agent 实践洞察" },
+ { num: "4", title: "技术挑战与趋势总结" },
+ ]});
+
+ const { item, group, bandNode, groupBand } = C;
+ let s;
+
+ // ===== P3 图文分栏·单图(默认黄金页型)=====
+ // 左 addSystemDiagram(分层结构)+ 右 addTextBlock(numbered),两栏各一黑色居中 heading,
+ // 右栏第 N 条逐项对应左图第 N 个 band。这是结构类内容的首选版式。
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "MOA 如何用分层协作突破单模型上限?", subtitle: "左图承载结构、右栏逐层解析,第 N 条对应第 N 层" });
+ C.addSystemDiagram(pres, s, { x: 0.5, y: 1.05, w: 5.4, h: 3.6, heading: "示例 MOA 分层架构", spec: {
+ title: "示例分层", subtitle: "", core_message: "", diagram_type: "layered",
+ bands: [
+ bandNode("input", "输入层", [item("uq", "用户问题 / 任务请求")], "neutral", "full_width"),
+ // 平级 N 项写成一个 group 的 N 个完整 items——4+ 项引擎自动多列(4 项→2×2、6 项→2×3),
+ // 不压扁、不合并、不省略。真实型号名直接用;严禁写成 "Qwen-110B/72B" 或加「等」。
+ // 半宽视觉区放 4 项刚好;项更多且图文分栏装不下时,改系统图整页 w:9 承载,或按
+ // over-capacity 报错引导扩区/换骨架/拆页——绝不靠合并省略。
+ groupBand("ref", "参考模型层", [
+ group("g_ref", "开源模型并行", [
+ "WizardLM-2-8x22B", "Qwen1.5-110B-Chat", "Llama-3-70B-Instruct", "Mixtral-8x22B",
+ ]),
+ ], "secondary"),
+ bandNode("agg", "聚合与输出", [
+ item("ag", "聚合器 Aggregator", "primary"), item("fo", "最终输出", "result"),
+ ], "primary", "row"),
+ ],
+ edges: [
+ { from: "input", to: "ref", relation: "flow", direction: "forward", label: "分发", line_style: "solid", emphasis: "normal", routing: "direct", multiplicity: "single" },
+ { from: "ref", to: "agg", relation: "flow", direction: "forward", label: "候选汇入", line_style: "solid", emphasis: "normal", routing: "direct", multiplicity: "single" },
+ ],
+ } });
+ C.addTextBlock(pres, s, { x: 6.1, y: 1.05, w: 3.4, h: 3.6, heading: "逐层解析", style: "numbered", items: [
+ { title: "输入层", body: "示例:接收用户问题或任务请求,统一规整成可分发的输入,是整条链路的唯一入口。" },
+ { title: "参考模型层", body: "示例:多个异构模型并行产出候选分析,互为参照暴露彼此盲区,异构比排名更能提升质量。" },
+ { title: "聚合与输出", body: "示例:聚合器对候选做筛选、综合与再创作,产出结构化、可追溯、可验证的最终结果,是系统上限所在。" },
+ ]});
+ C.addContentChrome(pres, s, { summary: "示例结论:分层协作把多模型集体智慧转化为一个可控入口的稳定产出。", pageNum: 3 });
+
+ // ===== P4 图文分栏·上下双图 =====
+ // 左视觉区用 addRegionHeading 画一个共用标题,下方摆上下两张 addDeckChart(引入前/引入后),
+ // 右栏 addTextBlock 做总分对应(现状问题 / 干预机制 / 结果提升)。
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "引入 MOA 前后,关键指标怎么变?", subtitle: "视觉区上下双图对比,右栏解释变化来自何处" });
+ {
+ const gy = C.addRegionHeading(pres, s, { text: "示例 · 引入前后指标对比", x: 0.5, y: 1.05, w: 5.4 });
+ C.addDeckChart(pres, s, { x: 0.5, y: gy, w: 5.4, h: 1.5,
+ type: "bar", data: [{ name: "引入前", labels: ["质量", "一致性", "鲁棒性"], values: [22.2, 33.3, 28.8] }] });
+ C.addDeckChart(pres, s, { x: 0.5, y: gy + 1.58, w: 5.4, h: 1.5,
+ type: "bar", data: [{ name: "引入后", labels: ["质量", "一致性", "鲁棒性"], values: [66.6, 71.1, 63.3] }] });
+ C.addTextBlock(pres, s, { x: 6.1, y: 1.05, w: 3.4, h: 3.55, heading: "变化解读", style: "numbered", items: [
+ { title: "现状", body: "示例:单模型在质量、一致性与鲁棒性上都受限于自身知识与推理盲区,难以再靠单点优化突破。" },
+ { title: "机制", body: "示例:引入多模型并行参考 + 强聚合后,候选之间互补纠错,弱项被其他模型补齐。" },
+ { title: "结果", body: "示例:三项指标同步抬升,且提升幅度随任务复杂度扩大,代价是延迟与成本需提前算账。" },
+ ]});
+ }
+ C.addContentChrome(pres, s, { summary: "示例结论:上下双图让「变了多少」和「为什么变」在同一页对齐。", pageNum: 4 });
+
+ // ===== P5 图文分栏·并列双图 =====
+ // 视觉区用 addRegionHeading 共用标题,下方并列两张小 addSystemDiagram(两种协作模式结构),
+ // 右栏 addTextBlock 做多图对应(每条对应一张子图)。
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "路由与聚合,两种协作模式差在哪?", subtitle: "视觉区并列双图,右栏逐图对应其取舍" });
+ {
+ const gy = C.addRegionHeading(pres, s, { text: "示例 · 两套协作模式结构", x: 0.5, y: 1.05, w: 5.4 });
+ C.addSystemDiagram(pres, s, { x: 0.5, y: gy, w: 2.55, h: 3.18, spec: {
+ title: "", subtitle: "", core_message: "", diagram_type: "process",
+ bands: [
+ bandNode("r_in", "路由模式", [item("r_task", "任务请求")], "secondary", "full_width"),
+ bandNode("r_route", "路由器", [item("r_pick", "选一个最合适模型")], "action", "full_width"),
+ bandNode("r_out", "单模型执行", [item("r_done", "低时延产出")], "result", "full_width"),
+ ],
+ edges: [],
+ } });
+ C.addSystemDiagram(pres, s, { x: 3.15, y: gy, w: 2.55, h: 3.18, spec: {
+ title: "", subtitle: "", core_message: "", diagram_type: "process",
+ bands: [
+ bandNode("a_in", "聚合模式", [item("a_task", "任务请求")], "secondary", "full_width"),
+ groupBand("a_ref", "并行参考", [group("a_g", "多模型", ["模型 A", "模型 B"])], "factor_group"),
+ bandNode("a_out", "聚合执行", [item("a_done", "综合后拍板")], "primary", "full_width"),
+ ],
+ edges: [],
+ } });
+ C.addTextBlock(pres, s, { x: 6.1, y: 1.05, w: 3.4, h: 3.55, heading: "两种模式", style: "numbered", items: [
+ { title: "路由模式", body: "示例:按任务把请求分给单一最合适的模型,成本最优、时延最低,但没有多视角互补增益。" },
+ { title: "聚合模式", body: "示例:多个模型先并行给参考,聚合器综合后再拍板,复杂任务质量更高,代价是成本与延迟成倍上升。" },
+ { title: "如何选", body: "示例:高频单点任务走路由,洞察分析、评审研判等高价值复杂任务才启用聚合,按任务价值分流。" },
+ ]});
+ }
+ C.addContentChrome(pres, s, { summary: "示例结论:并列双图把两种结构摆在一起对比,右栏逐图讲清取舍。", pageNum: 5 });
+
+ // ===== P6 系统图整页(单图撑页)=====
+ // 复杂结构(分组网格 + 红色虚线警示框 + 反馈回边)整页承载,配横幅收尾。
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "能力体系、风险约束与业务价值如何闭环?", subtitle: "复杂结构整页承载:构成 → 约束 → 价值 → 反馈" });
+ C.addSystemDiagram(pres, s, { x: 0.5, y: 1.05, w: 9.0, h: 3.6, spec: {
+ title: "示例能力体系", subtitle: "", core_message: "", diagram_type: "closed_loop",
+ bands: [
+ groupBand("caps", "能力构成", [
+ group("g_data", "数据能力", ["采集接入"]),
+ group("g_model", "模型能力", ["训练微调"]),
+ group("g_eng", "工程能力", ["编排调度"]),
+ ], "factor_group"),
+ groupBand("risks", "风险与约束", [
+ group("r1", "数据风险", ["数据孤岛", "口径不一"]),
+ group("r2", "模型风险", ["幻觉未收敛", "长尾漂移"]),
+ group("r3", "工程风险", ["链路耦合重", "回滚成本高"]),
+ ], "warning"),
+ bandNode("value", "业务价值", [
+ item("v1", "效率提升"), item("v2", "质量提升"), item("v3", "成本下降"),
+ ], "result", "row"),
+ ],
+ edges: [
+ { from: "caps", to: "risks", relation: "flow", direction: "forward", label: "落地检验", line_style: "solid", emphasis: "normal", routing: "direct", multiplicity: "single" },
+ { from: "risks", to: "value", relation: "flow", direction: "forward", label: "治理后产出", line_style: "solid", emphasis: "strong", routing: "direct", multiplicity: "single" },
+ { from: "value", to: "caps", relation: "feedback", direction: "forward", label: "", line_style: "dashed", emphasis: "normal", routing: "right_loop", multiplicity: "single" },
+ ],
+ } });
+ C.addContentChrome(pres, s, { summary: "示例结论:系统图把能力构成、风险约束与业务价值一屏说清,且原生可编辑。", pageNum: 6 });
+
+ // ===== P7 表格 + 分析(数据/对比页型)=====
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "四类协作方案,该怎么选?", subtitle: "对比表列机制与场景,右栏给一句辨析" });
+ {
+ const [main, side] = C.cols(2, { weights: [2, 1] });
+ C.addComparisonTable(pres, s, {
+ ...main, y: 1.05, h: 3.6,
+ headers: ["维度", "核心机制", "典型优势", "适合场景"],
+ rows: [
+ ["方案A", "按任务把请求路由给单一最合适的模型", "成本最优、响应低时延", "日常高频、单点明确的任务"],
+ ["方案B", "多模型先各给参考,聚合器综合后拍板", "复杂问题输出质量更高", "洞察分析、评审与综合研判"],
+ ["方案C", "多角色按工序分工,接力完成长链路", "长链路协作、吞吐更高", "开发、测试、交付流水线"],
+ ["方案D", "多智能体半自治协同,边探索边修正", "开放探索与复杂协作强", "仿真推演、研究型开放任务"],
+ ],
+ rowIcons: [
+ { initial: "由", color: "30B5C5" }, { initial: "合", color: "4472C4" },
+ { initial: "编", color: "62B230" }, { initial: "群", color: "ED6D00" },
+ ],
+ });
+ C.addPanelList(pres, s, { ...side, y: 1.05, h: 3.6, title: "一句辨析", style: "bullet", items: [
+ "方案B 更像多人会审加主审拍板的机制,重在提升单次输出的质量与可靠性。",
+ "方案C 更像项目团队按工序分工接力协作,重在长链路任务的吞吐与按期交付。",
+ "方案A 关注的只是选谁来做这一件事,成本最优、时延最低但没有互补增益。",
+ "方案D 强调群体自治与开放式探索,适合仿真推演与研究型的开放性任务。",
+ "没有万能方案:按任务复杂度、容错率与预算三个维度做综合权衡与选型。",
+ ]});
+ }
+ C.addContentChrome(pres, s, { summary: "示例结论:组合方案是位于两个极端之间的关键中间层。", pageNum: 7 });
+
+ // ===== P8 图表 + 洞察(图表页型)=====
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "组合方案的得分增益该怎么解读?", subtitle: "chart with insights:信号在左、边界在右" });
+ C.addChartWithInsights(pres, s, {
+ chart: { type: "bar", data: [{ name: "示例得分", labels: ["方案A", "方案B", "组合方案"], values: [11.1, 22.2, 33.3] }] },
+ insights: [
+ "示例:组合方案得分约为单模型的三倍。",
+ "示例:属高质量模式,按任务价值启用。",
+ "示例:系统级编排正成为能力放大器。",
+ "示例:聚合器质量决定整套系统上限。",
+ "示例:收益随任务复杂度上升而扩大。",
+ ],
+ caveats: [
+ "示例:官方口径为主,需第三方验证。",
+ "示例:不同组合收益差异大,勿按均值。",
+ "示例:延迟与成本成倍增加要先算账。",
+ "示例:轻量问题先路由分流再决定升级。",
+ "示例:候选同质化时组合基本无增益。",
+ ],
+ });
+ C.addContentChrome(pres, s, { summary: "示例结论:增益值得重视,但要放到成本与时延中综合判断。", pageNum: 8 });
+
+ // ===== P9 纯文字页(无结构关系时的合法页型)=====
+ // 双列 addTextBlock(numbered + sectioned),白底结构化,替代灰卡矩阵。
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "落地 MOA,要点与场景各有哪些?", subtitle: "内容无结构关系时用双列文字块,白底不灰" });
+ C.addTextBlock(pres, s, { x: 0.5, y: 1.05, w: 4.4, h: 3.55, style: "numbered", title: "落地要点", items: [
+ { title: "结构化承载", body: "示例:标题 + 解释 + 要点分层,由组件负责格式,不靠手拼字符串,层级清晰便于扫读。", children: ["示例:层级清晰", "示例:便于扫读"] },
+ { title: "去灰盒化", body: "示例:文字直接铺白底,只有表格与个别图示容器用灰,整屏灰盒子矩阵过不了 QA。" },
+ { title: "互补优先", body: "示例:参与模型要有真实能力互补,同质化候选再多也叠加不出增益,先选异构再谈数量。" },
+ ] });
+ C.addTextBlock(pres, s, { x: 5.1, y: 1.05, w: 4.4, h: 3.55, style: "sectioned", title: "适用场景", items: [
+ { title: "复杂研判", body: "示例:洞察分析、方案评审、综合研判等高价值任务,多视角互补能明显抬升输出质量。" },
+ { title: "图文右栏", body: "示例:与系统图配对时,右栏用 numbered 逐条对应左图的每个 band,术语与编号保持一致。" },
+ { title: "成本敏感", body: "示例:高频单点任务不必上聚合,先路由分流控制成本,把组合留给真正需要的复杂问题。" },
+ ] });
+ C.addContentChrome(pres, s, { summary: "示例结论:文字块是文字区默认,白底不灰、按栏分层。", pageNum: 9 });
+
+ // ===== P10 参考词汇三件套(矩阵 → 漏斗 → 阶段带 = 整页结构大图配方)=====
+ s = pres.addSlide(); s.background = { color: C.THEME.white };
+ C.addSlideTitle(pres, s, { title: "复杂分类如何汇聚成行动路径?", subtitle: "淡彩矩阵 + 汇聚漏斗 + 阶段带,整页一张结构大图" });
+ C.addTintMatrix(pres, s, {
+ x: 0.5, y: 1.05, w: 9.0, h: 1.7,
+ rowLabels: ["族群", "子类", "具体条目"],
+ groups: [
+ { name: "示例族群一", subs: [
+ { name: "对象识别", items: ["示例对象", "示例特征"] },
+ { name: "场景拆解", items: ["示例任务", "示例边界"] },
+ ] },
+ { name: "示例族群二", subs: [
+ { name: "基础能力", items: ["示例能力甲", "示例能力乙"] },
+ { name: "核心方法", items: ["示例框架", "示例方法"] },
+ { name: "协同机制", items: ["示例分工", "示例规则"] },
+ ] },
+ { name: "示例族群三", subs: [
+ { name: "资源底座", items: ["示例数据", "示例资产"] },
+ { name: "运营支撑", items: ["示例流程", "示例保障"] },
+ ] },
+ { name: "示例族群四", subs: [
+ { name: "治理闭环", items: ["示例规范", "示例迭代"] },
+ ] },
+ ],
+ });
+ C.addConvergeFunnel(pres, s, { x: 0.5, y: 2.78, w: 9.0, h: 0.60, label: "分类分析导出的行动路径(示例)" });
+ C.addChevronStages(pres, s, {
+ x: 0.5, y: 3.42, w: 9.0, h: 1.23,
+ stages: [
+ { name: "阶段一|识别与聚焦", card: { title: "分类输出", items: ["示例优先级清单", "示例问题地图"] } },
+ { name: "阶段二|方案与编排", card: { title: "方案输出", items: ["示例方案组合", "示例里程碑表"] } },
+ { name: "阶段三|落地与迭代", card: { title: "成果输出", items: ["示例交付物集", "示例评估闭环"] } },
+ ],
+ });
+ C.addContentChrome(pres, s, { summary: "示例结论:分类矩阵经漏斗汇聚为三阶段路径,一张结构大图讲完整页论证。", pageNum: 10 });
+
+ C.addClosingSlide(pres);
+
+ await pres.writeFile({ fileName: "demo.pptx" });
+ console.log("demo.pptx written");
+}
+
+main().catch((e) => { console.error(e); process.exit(1); });
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/extract_arxiv_visuals_v2_2.py b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/extract_arxiv_visuals_v2_2.py
new file mode 100644
index 0000000000..cf0e6ae5e5
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/extract_arxiv_visuals_v2_2.py
@@ -0,0 +1,1475 @@
+#!/usr/bin/env python3
+"""
+Cross-platform paper figure/table extractor.
+
+Input:
+ * arXiv abs/pdf URL
+ * arXiv ID
+ * generic HTTP(S) PDF URL
+ * local PDF path
+
+Output:
+ source/paper.pdf
+ figures/*.png
+ figures_with_caption/*.png
+ tables/*.png
+ tables_with_caption/*.png
+ pages/*.png (optional: --keep-pages)
+ debug/*.png
+ manifest.json
+ contact_sheet.png
+
+The script is intentionally Python-only: no Bash, curl, Java, Git, or WSL is
+required. By default it installs missing Python packages into the current
+Python environment. Use --no-auto-install to disable that behavior.
+"""
+from __future__ import annotations
+
+import argparse
+import contextlib
+import hashlib
+import importlib
+import io
+import json
+import logging
+import math
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any, Iterable, Sequence
+
+SCRIPT_VERSION = "2.2.0"
+DEFAULT_DPI = 300
+DEFAULT_DEBUG_DPI = 120
+DEPENDENCIES = {
+ "pymupdf": "PyMuPDF>=1.24,<2",
+ "PIL": "Pillow>=10,<13",
+}
+
+
+LOGGER = logging.getLogger("extract_arxiv_visuals")
+
+# Configured at import time, not in main(): ensure_dependencies() below runs
+# during module import and logs there. Diagnostics keep their historical stderr
+# destination and exact wording; only the transport changes from print.
+logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="%(message)s")
+
+
+# Program output (report bodies, --json payloads) goes to stdout, diagnostics
+# to stderr. Both travel through logging; this logger owns stdout, keeps a bare
+# "%(message)s" format so the text is unchanged, and does not propagate so the
+# stderr root handler never sees it.
+STDOUT_LOGGER = logging.getLogger("extract_arxiv_visuals.stdout")
+STDOUT_LOGGER.propagate = False
+STDOUT_LOGGER.setLevel(logging.INFO)
+_stdout_handler = logging.StreamHandler(sys.stdout)
+_stdout_handler.setFormatter(logging.Formatter("%(message)s"))
+STDOUT_LOGGER.addHandler(_stdout_handler)
+
+
+def emit(line: str) -> None:
+ """Final summary is program output, not a diagnostic."""
+ STDOUT_LOGGER.info(line)
+
+
+def eprint(*args: object) -> None:
+ LOGGER.info(" ".join(str(arg) for arg in args))
+
+
+def log(message: str) -> None:
+ eprint(f"[extract_arxiv_visuals] {message}")
+
+
+def warn(message: str) -> None:
+ eprint(f"[extract_arxiv_visuals WARNING] {message}")
+
+
+def ensure_dependencies(auto_install: bool) -> None:
+ missing: list[str] = []
+ for module_name, pip_spec in DEPENDENCIES.items():
+ try:
+ importlib.import_module(module_name)
+ except ImportError:
+ missing.append(pip_spec)
+
+ if not missing:
+ return
+
+ if not auto_install:
+ joined = " ".join(missing)
+ raise RuntimeError(
+ "缺少 Python 依赖。请运行:\n"
+ f' "{sys.executable}" -m pip install {joined}'
+ )
+
+ log("检测到缺失依赖,正在安装:" + ", ".join(missing))
+ command = [sys.executable, "-m", "pip", "install", *missing]
+ try:
+ subprocess.check_call(command)
+ except subprocess.CalledProcessError as exc:
+ raise RuntimeError(
+ "自动安装依赖失败。请手动运行:\n " + " ".join(command)
+ ) from exc
+ importlib.invalidate_caches()
+
+
+# Parse this flag before importing third-party packages.
+AUTO_INSTALL = "--no-auto-install" not in sys.argv
+ensure_dependencies(AUTO_INSTALL)
+
+import pymupdf # type: ignore # noqa: E402
+from PIL import Image, ImageDraw, ImageFont # type: ignore # noqa: E402
+
+
+ARXIV_ID_RE = re.compile(r"^(?P<id>\d{4}\.\d{4,5}(?:v\d+)?)$")
+ARXIV_URL_RE = re.compile(
+ r"^https?://(?:www\.)?arxiv\.org/(?:abs|pdf)/"
+ r"(?P<id>\d{4}\.\d{4,5}(?:v\d+)?)(?:\.pdf)?(?:[?#].*)?$",
+ re.IGNORECASE,
+)
+CAPTION_RE = re.compile(
+ r"^\s*(?P<kind>fig(?:ure)?|table)\s*\.?\s*"
+ r"(?P<label>(?:[A-Za-z]?\d+(?:[.\-]\d+)*[A-Za-z]?|[IVXLCDM]+))\b",
+ re.IGNORECASE,
+)
+INLINE_CAPTION_RE = re.compile(
+ r"\b(?P<kind>fig(?:ure)?|table)\s*\.?\s*"
+ r"(?P<label>(?:[A-Za-z]?\d+(?:[.\-]\d+)*[A-Za-z]?|[IVXLCDM]+))"
+ r"\s*(?:\||:)",
+ re.IGNORECASE,
+)
+
+
+@dataclass(frozen=True)
+class InputResource:
+ original_input: str
+ source_kind: str
+ paper_id: str
+ pdf_url: str | None = None
+ local_pdf: Path | None = None
+
+
+@dataclass
+class Candidate:
+ kind: str
+ label: str
+ page_index: int
+ region_bbox: tuple[float, float, float, float]
+ caption_bbox: tuple[float, float, float, float] | None
+ caption: str
+ source: str
+ confidence: float
+
+
+@dataclass
+class ExtractedVisual:
+ id: str
+ type: str
+ label: str
+ page_index: int
+ page_number: int
+ bbox: list[float]
+ caption_bbox: list[float] | None
+ caption: str
+ image_path: str
+ image_with_caption_path: str
+ extraction_method: str
+ confidence: float
+ pixel_width: int
+ pixel_height: int
+
+
+def sanitize_name(value: str, fallback: str = "paper") -> str:
+ clean = re.sub(r"[^A-Za-z0-9._-]+", "_", value.strip()).strip("_")
+ return clean or fallback
+
+
+def safe_label(value: str) -> str:
+ return sanitize_name(value, "unlabeled")
+
+
+def resolve_input(value: str) -> InputResource:
+ value = value.strip().strip('"').strip("'")
+ local = Path(value).expanduser()
+ if local.is_file():
+ if local.suffix.lower() != ".pdf":
+ raise ValueError(f"本地文件不是 PDF:{local}")
+ return InputResource(
+ original_input=value,
+ source_kind="local_pdf",
+ paper_id=sanitize_name(local.stem),
+ local_pdf=local.resolve(),
+ )
+
+ match = ARXIV_ID_RE.match(value)
+ if match:
+ arxiv_id = match.group("id")
+ return InputResource(
+ original_input=value,
+ source_kind="arxiv",
+ paper_id=arxiv_id,
+ pdf_url=f"https://arxiv.org/pdf/{arxiv_id}",
+ )
+
+ match = ARXIV_URL_RE.match(value)
+ if match:
+ arxiv_id = match.group("id")
+ return InputResource(
+ original_input=value,
+ source_kind="arxiv",
+ paper_id=arxiv_id,
+ pdf_url=f"https://arxiv.org/pdf/{arxiv_id}",
+ )
+
+ parsed = urllib.parse.urlparse(value)
+ if parsed.scheme in {"http", "https"} and parsed.netloc:
+ filename = Path(urllib.parse.unquote(parsed.path)).name
+ paper_id = sanitize_name(Path(filename).stem if filename else "paper")
+ return InputResource(
+ original_input=value,
+ source_kind="remote_pdf",
+ paper_id=paper_id,
+ pdf_url=value,
+ )
+
+ raise ValueError(
+ "输入必须是 arXiv ID、arXiv abs/pdf 链接、HTTP(S) PDF 链接或本地 PDF 路径。"
+ )
+
+
+def sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def copy_local_pdf(source: Path, destination: Path) -> None:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, destination)
+
+
+def download_pdf(url: str, destination: Path, retries: int = 3) -> None:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ headers = {
+ "User-Agent": (
+ "paper-visual-extractor/2.0 "
+ "(cross-platform research workflow; contact: local-user)"
+ ),
+ "Accept": "application/pdf,*/*;q=0.8",
+ }
+ request = urllib.request.Request(url, headers=headers)
+ last_error: Exception | None = None
+
+ for attempt in range(1, retries + 1):
+ temp_path = destination.with_suffix(destination.suffix + ".part")
+ try:
+ log(f"下载 PDF(第 {attempt}/{retries} 次):{url}")
+ with urllib.request.urlopen(request, timeout=120) as response:
+ with temp_path.open("wb") as output:
+ shutil.copyfileobj(response, output, length=1024 * 1024)
+ with temp_path.open("rb") as handle:
+ signature = handle.read(5)
+ if signature != b"%PDF-":
+ raise ValueError("下载内容不是 PDF,可能是 HTML 错误页或受限页面。")
+ temp_path.replace(destination)
+ return
+ # OSError already covers urllib.error.URLError and TimeoutError; listing
+ # them alongside it trips the "parent and child exception" rule.
+ except (OSError, ValueError) as exc:
+ last_error = exc
+ temp_path.unlink(missing_ok=True)
+ if attempt < retries:
+ time.sleep(2 * attempt)
+
+ raise RuntimeError(f"PDF 下载失败:{url}\n原因:{last_error}")
+
+
+def prepare_output(output: Path, force: bool, keep_pages: bool) -> None:
+ output = output.resolve()
+ if output.exists():
+ if not force:
+ raise FileExistsError(
+ f"输出目录已经存在:{output}\n请更换 --output,或加入 --force 覆盖。"
+ )
+ log(f"删除已有输出目录:{output}")
+ shutil.rmtree(output)
+
+ directories = [
+ "source",
+ "figures",
+ "figures_with_caption",
+ "tables",
+ "tables_with_caption",
+ "debug",
+ "raw",
+ ]
+ if keep_pages:
+ directories.append("pages")
+ for name in directories:
+ (output / name).mkdir(parents=True, exist_ok=True)
+
+
+def rect_tuple(obj: Any) -> tuple[float, float, float, float] | None:
+ if obj is None:
+ return None
+ if isinstance(obj, pymupdf.Rect):
+ return float(obj.x0), float(obj.y0), float(obj.x1), float(obj.y1)
+ if isinstance(obj, (list, tuple)) and len(obj) == 4:
+ return tuple(float(value) for value in obj) # type: ignore[return-value]
+ if isinstance(obj, dict):
+ variants = [
+ ("x1", "y1", "x2", "y2"),
+ ("x0", "y0", "x1", "y1"),
+ ("left", "top", "right", "bottom"),
+ ]
+ for keys in variants:
+ if all(key in obj for key in keys):
+ return tuple(float(obj[key]) for key in keys) # type: ignore[return-value]
+ return None
+
+
+def normalize_rect(
+ rect: Sequence[float],
+) -> tuple[float, float, float, float]:
+ x0, y0, x1, y1 = map(float, rect)
+ return min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)
+
+
+def union_rect(
+ *rects: tuple[float, float, float, float] | None,
+) -> tuple[float, float, float, float] | None:
+ valid = [normalize_rect(rect) for rect in rects if rect is not None]
+ if not valid:
+ return None
+ return (
+ min(rect[0] for rect in valid),
+ min(rect[1] for rect in valid),
+ max(rect[2] for rect in valid),
+ max(rect[3] for rect in valid),
+ )
+
+
+def area(rect: Sequence[float]) -> float:
+ x0, y0, x1, y1 = normalize_rect(rect)
+ return max(0.0, x1 - x0) * max(0.0, y1 - y0)
+
+
+def intersection_area(a: Sequence[float], b: Sequence[float]) -> float:
+ ax0, ay0, ax1, ay1 = normalize_rect(a)
+ bx0, by0, bx1, by1 = normalize_rect(b)
+ x0, y0 = max(ax0, bx0), max(ay0, by0)
+ x1, y1 = min(ax1, bx1), min(ay1, by1)
+ return max(0.0, x1 - x0) * max(0.0, y1 - y0)
+
+
+def iou(a: Sequence[float], b: Sequence[float]) -> float:
+ inter = intersection_area(a, b)
+ if inter <= 0:
+ return 0.0
+ return inter / max(area(a) + area(b) - inter, 1e-9)
+
+
+def horizontal_overlap_ratio(a: Sequence[float], b: Sequence[float]) -> float:
+ ax0, _, ax1, _ = normalize_rect(a)
+ bx0, _, bx1, _ = normalize_rect(b)
+ overlap = max(0.0, min(ax1, bx1) - max(ax0, bx0))
+ return overlap / max(1.0, min(ax1 - ax0, bx1 - bx0))
+
+
+def axis_gap(a0: float, a1: float, b0: float, b1: float) -> float:
+ """Return the non-overlapping gap between two 1D intervals."""
+ return max(0.0, b0 - a1, a0 - b1)
+
+
+def looks_like_page_margin_stamp(
+ page: pymupdf.Page,
+ rect: pymupdf.Rect,
+ text: str,
+) -> bool:
+ """Detect narrow, tall marginal stamps such as vertical arXiv identifiers.
+
+ These are page decorations, not part of a figure. The proximity check in
+ infer_figure_region still allows legitimate axis labels that sit close to
+ the detected graphics.
+ """
+ page_width = max(page.rect.width, 1.0)
+ page_height = max(page.rect.height, 1.0)
+ near_side = (
+ rect.x0 <= page.rect.x0 + page_width * 0.09
+ or rect.x1 >= page.rect.x1 - page_width * 0.09
+ )
+ narrow_and_tall = (
+ rect.height >= max(70.0, rect.width * 3.0)
+ and rect.width <= page_width * 0.10
+ and rect.height >= page_height * 0.12
+ )
+ stamp_like_text = bool(
+ re.search(r"(?:arxiv|\[[a-z.-]+\]|\d{4}\.\d{4,5}v?\d*)", text, re.I)
+ )
+ return near_side and narrow_and_tall and stamp_like_text
+
+
+def sanitize_margin_artifacts(
+ page: pymupdf.Page,
+ bbox: Sequence[float],
+) -> tuple[float, float, float, float]:
+ """Remove page-edge stamps from a candidate crop before rendering.
+
+ This runs for every detector path, including optional PDFFigures2 JSON.
+ Earlier versions only prevented the caption heuristic from *adding* the
+ arXiv stamp, but did not repair a bbox that already contained it.
+ """
+ rect = pymupdf.Rect(*normalize_rect(bbox))
+ page_width = max(page.rect.width, 1.0)
+ page_height = max(page.rect.height, 1.0)
+
+ for block_rect, text in page_blocks(page):
+ if not looks_like_page_margin_stamp(page, block_rect, text):
+ continue
+
+ # Only alter a crop when the stamp overlaps its vertical span and is
+ # actually included at the corresponding side edge.
+ vertical_overlap = max(
+ 0.0, min(rect.y1, block_rect.y1) - max(rect.y0, block_rect.y0)
+ )
+ if vertical_overlap <= 0:
+ continue
+
+ if block_rect.x0 <= page.rect.x0 + page_width * 0.10:
+ if rect.x0 <= block_rect.x1 + 2.0 and block_rect.x1 < rect.x1:
+ rect.x0 = min(rect.x1 - 2.0, block_rect.x1 + 3.0)
+ elif block_rect.x1 >= page.rect.x1 - page_width * 0.10:
+ if rect.x1 >= block_rect.x0 - 2.0 and block_rect.x0 > rect.x0:
+ rect.x1 = max(rect.x0 + 2.0, block_rect.x0 - 3.0)
+
+ # Safety clamp: a very wide figure crop should not start in the outermost
+ # page gutter when a vertical stamp exists there. This leaves normal
+ # single-column figures unchanged.
+ has_left_stamp = any(
+ looks_like_page_margin_stamp(page, block_rect, text)
+ and block_rect.x0 <= page.rect.x0 + page_width * 0.10
+ and max(0.0, min(rect.y1, block_rect.y1) - max(rect.y0, block_rect.y0)) > 0
+ for block_rect, text in page_blocks(page)
+ )
+ if has_left_stamp and rect.width >= page_width * 0.60:
+ rect.x0 = max(rect.x0, page.rect.x0 + page_width * 0.085)
+
+ rect = rect & page.rect
+ if rect.is_empty or rect.width <= 2 or rect.height <= 2:
+ return normalize_rect(bbox)
+ return normalize_rect(tuple(rect))
+
+
+def trim_white_border(
+ path: Path,
+ threshold: int = 250,
+ border: int = 2,
+) -> tuple[int, int]:
+ """Trim only near-white outer whitespace from a rendered PNG.
+
+ The threshold is deliberately conservative so light-gray table rules and
+ pale panels remain intact. It cannot remove internal white space.
+ """
+ with Image.open(path) as source:
+ image = source.convert("RGB")
+ pixels = image.load()
+ width, height = image.size
+ xs: list[int] = []
+ ys: list[int] = []
+ for y in range(height):
+ for x in range(width):
+ r, g, b = pixels[x, y]
+ if min(r, g, b) < threshold:
+ xs.append(x)
+ ys.append(y)
+ if not xs:
+ return width, height
+ left = max(0, min(xs) - border)
+ top = max(0, min(ys) - border)
+ right = min(width, max(xs) + border + 1)
+ bottom = min(height, max(ys) + border + 1)
+ if (left, top, right, bottom) == (0, 0, width, height):
+ return width, height
+ cropped = image.crop((left, top, right, bottom))
+ cropped.save(path)
+ return cropped.size
+
+
+def page_blocks(page: pymupdf.Page) -> list[tuple[pymupdf.Rect, str]]:
+ blocks: list[tuple[pymupdf.Rect, str]] = []
+ for block in page.get_text("blocks", sort=True):
+ x0, y0, x1, y1, text, *_ = block
+ compact = " ".join(str(text).split())
+ if compact:
+ blocks.append((pymupdf.Rect(x0, y0, x1, y1), compact))
+ return blocks
+
+
+def parse_caption(text: str) -> tuple[str, str] | None:
+ match = CAPTION_RE.match(text) or INLINE_CAPTION_RE.search(text)
+ if not match:
+ return None
+ kind = "table" if match.group("kind").lower().startswith("table") else "figure"
+ return kind, match.group("label")
+
+
+def column_bounds(page: pymupdf.Page, caption: pymupdf.Rect) -> tuple[float, float]:
+ page_width = page.rect.width
+ mid = (page.rect.x0 + page.rect.x1) / 2
+ crosses_mid_substantially = (
+ caption.x0 < mid - page_width * 0.04
+ and caption.x1 > mid + page_width * 0.04
+ )
+ if caption.width >= page_width * 0.68 or crosses_mid_substantially:
+ return page.rect.x0, page.rect.x1
+ center = (caption.x0 + caption.x1) / 2
+ margin = page_width * 0.015
+ if center < mid:
+ return page.rect.x0 + margin, mid - margin
+ return mid + margin, page.rect.x1 - margin
+
+
+def graphical_regions(page: pymupdf.Page) -> list[tuple[float, float, float, float]]:
+ regions: list[tuple[float, float, float, float]] = []
+ # Both probes are best-effort enrichment: PyMuPDF raises on malformed or
+ # unusual content streams, and one failing probe must not lose the other's
+ # regions. Report which one dropped out instead of swallowing it silently.
+ try:
+ regions.extend(normalize_rect(rect) for rect in page.cluster_drawings())
+ except Exception as cause:
+ log(f"page {page.number}: cluster_drawings unavailable ({cause})")
+ try:
+ for info in page.get_image_info():
+ bbox = rect_tuple(info.get("bbox"))
+ if bbox is not None:
+ regions.append(normalize_rect(bbox))
+ except Exception as cause:
+ log(f"page {page.number}: get_image_info unavailable ({cause})")
+ return [rect for rect in regions if area(rect) >= 350]
+
+
+def nearby_caption_for_table(
+ page: pymupdf.Page,
+ bbox: tuple[float, float, float, float],
+) -> tuple[str, tuple[float, float, float, float] | None, str]:
+ best_distance = math.inf
+ best_label = ""
+ best_caption = ""
+ best_bbox: tuple[float, float, float, float] | None = None
+ for block_rect, text in page_blocks(page):
+ parsed = parse_caption(text)
+ if not parsed or parsed[0] != "table":
+ continue
+
+ # Academic styles vary: some place table captions above, others below.
+ caption_above_gap = bbox[1] - block_rect.y1
+ caption_below_gap = block_rect.y0 - bbox[3]
+ valid_distances = [
+ gap
+ for gap in (caption_above_gap, caption_below_gap)
+ if -8 <= gap <= 260
+ ]
+ if not valid_distances:
+ continue
+ if horizontal_overlap_ratio(bbox, tuple(block_rect)) <= 0.12:
+ continue
+ distance = min(valid_distances)
+ if distance < best_distance:
+ best_distance = distance
+ best_label = parsed[1]
+ best_caption = text
+ best_bbox = normalize_rect(tuple(block_rect))
+ return best_label, best_bbox, best_caption
+
+
+def find_table_candidates(
+ doc: pymupdf.Document,
+ include_uncaptioned: bool,
+) -> list[Candidate]:
+ candidates: list[Candidate] = []
+ fallback_counter = 0
+ for page_index, page in enumerate(doc):
+ tables: list[Any] = []
+ try:
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ finder = page.find_tables()
+ tables.extend(finder.tables)
+ except Exception as exc:
+ warn(f"第 {page_index + 1} 页表格检测失败:{exc}")
+
+ for table in tables:
+ bbox = normalize_rect(table.bbox)
+ if area(bbox) < 900:
+ continue
+ if any(
+ old.page_index == page_index and iou(old.region_bbox, bbox) > 0.55
+ for old in candidates
+ ):
+ continue
+ label, caption_bbox, caption = nearby_caption_for_table(page, bbox)
+ if not label and not include_uncaptioned:
+ continue
+ fallback_counter += 1
+ candidates.append(
+ Candidate(
+ kind="table",
+ label=label or f"fallback_{fallback_counter:03d}",
+ page_index=page_index,
+ region_bbox=bbox,
+ caption_bbox=caption_bbox,
+ caption=caption,
+ source="pymupdf_find_tables",
+ confidence=0.82 if label else 0.66,
+ )
+ )
+ return candidates
+
+
+def infer_figure_region(
+ page: pymupdf.Page,
+ caption_rect: pymupdf.Rect,
+ blocks: list[tuple[pymupdf.Rect, str]],
+ graphics: list[tuple[float, float, float, float]],
+) -> tuple[float, float, float, float] | None:
+ left, right = column_bounds(page, caption_rect)
+ page_height = page.rect.height
+
+ compatible_graphics = []
+ for graphic in graphics:
+ gx0, gy0, gx1, gy1 = graphic
+ if gy1 > caption_rect.y0 + 8:
+ continue
+ gap = caption_rect.y0 - gy1
+ if gap > page_height * 0.56:
+ continue
+ if gx1 <= left or gx0 >= right:
+ continue
+ compatible_graphics.append(graphic)
+
+ if compatible_graphics:
+ compatible_graphics.sort(key=lambda rect: (caption_rect.y0 - rect[3], -area(rect)))
+ seed = compatible_graphics[0]
+ selected = [seed]
+ current_top = seed[1]
+ current_bottom = seed[3]
+ for graphic in compatible_graphics[1:]:
+ vertical_gap = current_top - graphic[3]
+ if vertical_gap <= page_height * 0.055:
+ selected.append(graphic)
+ current_top = min(current_top, graphic[1])
+ current_bottom = max(current_bottom, graphic[3])
+
+ merged = union_rect(*selected)
+ if merged is None:
+ raise RuntimeError("union_rect returned None for a non-empty selection")
+ x0 = max(left, merged[0])
+ x1 = min(right, merged[2])
+ y0 = max(page.rect.y0, merged[1])
+ # Do not extend the crop toward the caption merely to fill whitespace.
+ # Actual labels are added below only when they are spatially close to
+ # the detected graphical region.
+ y1 = min(caption_rect.y0 - 1, merged[3])
+
+ # Include short labels / legends only when they are genuinely adjacent
+ # to the visual. This prevents vertical arXiv stamps and page headers
+ # from enlarging a full-width figure crop.
+ base_graphic = normalize_rect(merged)
+ max_horizontal_gap = max(10.0, page.rect.width * 0.025)
+ max_vertical_gap = max(3.0, page.rect.height * 0.004)
+ for block_rect, text in blocks:
+ if block_rect.y1 < y0 - max_vertical_gap or block_rect.y0 > y1 + max_vertical_gap:
+ continue
+ if block_rect.x1 <= left or block_rect.x0 >= right:
+ continue
+ if len(text) > 120 or parse_caption(text):
+ continue
+
+ h_gap = axis_gap(block_rect.x0, block_rect.x1, base_graphic[0], base_graphic[2])
+ v_gap = axis_gap(block_rect.y0, block_rect.y1, base_graphic[1], base_graphic[3])
+ if h_gap > max_horizontal_gap or v_gap > max_vertical_gap:
+ continue
+ if looks_like_page_margin_stamp(page, block_rect, text) and h_gap > 2.0:
+ continue
+
+ x0 = min(x0, max(left, block_rect.x0))
+ x1 = max(x1, min(right, block_rect.x1))
+ y0 = min(y0, block_rect.y0)
+ y1 = max(y1, min(caption_rect.y0 - 1, block_rect.y1))
+ region = normalize_rect((x0, y0, x1, y1))
+ return region if area(region) >= 1000 else None
+
+ # Fallback: use the band between the nearest preceding body paragraph and caption.
+ upper = page.rect.y0
+ for block_rect, text in blocks:
+ if block_rect.y1 > caption_rect.y0:
+ break
+ if block_rect.x1 <= left or block_rect.x0 >= right:
+ continue
+ if len(text) >= 120 or parse_caption(text):
+ upper = max(upper, block_rect.y1)
+ region = normalize_rect((left, upper + 2, right, caption_rect.y0 - 2))
+ return region if area(region) >= 1400 else None
+
+
+def looks_like_body_prose(
+ page: pymupdf.Page,
+ rect: pymupdf.Rect,
+ text: str,
+) -> bool:
+ alnum = sum(char.isalnum() for char in text)
+ digits = sum(char.isdigit() for char in text)
+ digit_ratio = digits / max(alnum, 1)
+ width_ratio = rect.width / max(page.rect.width, 1)
+ near_body_margin = rect.x0 <= page.rect.x0 + page.rect.width * 0.18
+ return (
+ len(text) >= 90
+ and width_ratio >= 0.60
+ and near_body_margin
+ and digit_ratio < 0.16
+ )
+
+
+def infer_table_region_from_caption(
+ page: pymupdf.Page,
+ caption_rect: pymupdf.Rect,
+ blocks: list[tuple[pymupdf.Rect, str]],
+) -> tuple[float, float, float, float] | None:
+ left, right = column_bounds(page, caption_rect)
+
+ def collect_below() -> tuple[list[pymupdf.Rect], float]:
+ lower = page.rect.y1
+ for block_rect, text in blocks:
+ if block_rect.y0 <= caption_rect.y1:
+ continue
+ if block_rect.x1 <= left or block_rect.x0 >= right:
+ continue
+ if parse_caption(text) or looks_like_body_prose(page, block_rect, text):
+ lower = min(lower, block_rect.y0)
+ break
+ content: list[pymupdf.Rect] = []
+ for block_rect, text in blocks:
+ if block_rect.y0 < caption_rect.y1 - 1 or block_rect.y1 > lower + 1:
+ continue
+ if block_rect.x1 <= left or block_rect.x0 >= right:
+ continue
+ if parse_caption(text) or looks_like_body_prose(page, block_rect, text):
+ continue
+ content.append(block_rect)
+ return content, lower
+
+ def collect_above() -> tuple[list[pymupdf.Rect], float]:
+ upper = page.rect.y0
+ for block_rect, text in blocks:
+ if block_rect.y1 >= caption_rect.y0:
+ break
+ if block_rect.x1 <= left or block_rect.x0 >= right:
+ continue
+ if parse_caption(text) or looks_like_body_prose(page, block_rect, text):
+ upper = max(upper, block_rect.y1)
+ content: list[pymupdf.Rect] = []
+ for block_rect, text in blocks:
+ if block_rect.y0 < upper - 1 or block_rect.y1 > caption_rect.y0 + 1:
+ continue
+ if block_rect.x1 <= left or block_rect.x0 >= right:
+ continue
+ if parse_caption(text) or looks_like_body_prose(page, block_rect, text):
+ continue
+ content.append(block_rect)
+ return content, upper
+
+ below, lower = collect_below()
+ above, upper = collect_above()
+
+ candidates: list[tuple[float, tuple[float, float, float, float]]] = []
+ if below:
+ gap = max(0.0, min(rect.y0 for rect in below) - caption_rect.y1)
+ region = (
+ max(left, min(rect.x0 for rect in below) - 5),
+ max(caption_rect.y1 + 1, min(rect.y0 for rect in below) - 4),
+ min(right, max(rect.x1 for rect in below) + 5),
+ min(lower - 1, max(rect.y1 for rect in below) + 5),
+ )
+ candidates.append((gap, normalize_rect(region)))
+ if above:
+ gap = max(0.0, caption_rect.y0 - max(rect.y1 for rect in above))
+ region = (
+ max(left, min(rect.x0 for rect in above) - 5),
+ max(upper + 1, min(rect.y0 for rect in above) - 4),
+ min(right, max(rect.x1 for rect in above) + 5),
+ min(caption_rect.y0 - 1, max(rect.y1 for rect in above) + 5),
+ )
+ candidates.append((gap, normalize_rect(region)))
+
+ valid = [(gap, region) for gap, region in candidates if area(region) >= 1000]
+ if not valid:
+ return None
+ return min(valid, key=lambda item: item[0])[1]
+
+
+def caption_heuristic_candidates(
+ doc: pymupdf.Document,
+ existing: list[Candidate],
+) -> list[Candidate]:
+ out: list[Candidate] = []
+ for page_index, page in enumerate(doc):
+ blocks = page_blocks(page)
+ graphics = graphical_regions(page)
+ for caption_rect, text in blocks:
+ parsed = parse_caption(text)
+ if not parsed:
+ continue
+ kind, label = parsed
+ caption_bbox = normalize_rect(tuple(caption_rect))
+
+ wanted_label = safe_label(label).lower()
+ same_label = []
+ for candidate in existing + out:
+ if candidate.page_index != page_index or candidate.kind != kind:
+ continue
+ if safe_label(candidate.label).lower() == wanted_label:
+ same_label.append(candidate)
+ if same_label:
+ for candidate in same_label:
+ if candidate.caption_bbox is None:
+ candidate.caption_bbox = caption_bbox
+ if not candidate.caption:
+ candidate.caption = text
+ candidate.label = label
+ candidate.confidence = max(candidate.confidence, 0.82)
+ if kind == "figure":
+ continue
+ combined_existing = union_rect(*(candidate.region_bbox for candidate in same_label))
+ if combined_existing is None:
+ raise RuntimeError("union_rect returned None for a non-empty label group")
+ above_gap = combined_existing[1] - caption_rect.y1
+ below_gap = caption_rect.y0 - combined_existing[3]
+ nearest_gap = min(
+ gap for gap in (above_gap, below_gap) if gap >= -8
+ ) if any(gap >= -8 for gap in (above_gap, below_gap)) else math.inf
+ # A large caption-to-detection gap usually means find_tables()
+ # captured only a fragment. Generate a full caption-guided region.
+ if nearest_gap <= 85:
+ continue
+
+ if kind == "figure":
+ region = infer_figure_region(page, caption_rect, blocks, graphics)
+ source = "caption_figure_heuristic"
+ confidence = 0.62
+ else:
+ region = infer_table_region_from_caption(page, caption_rect, blocks)
+ source = "caption_table_heuristic"
+ confidence = 0.55
+
+ if region is None:
+ continue
+ out.append(
+ Candidate(
+ kind=kind,
+ label=label,
+ page_index=page_index,
+ region_bbox=region,
+ caption_bbox=caption_bbox,
+ caption=text,
+ source=source,
+ confidence=confidence,
+ )
+ )
+ return out
+
+
+def load_pdffigures_json(path: Path | None) -> list[Candidate]:
+ """Load optional PDFFigures2 JSON, without requiring Java in this script."""
+ if path is None:
+ return []
+ if not path.is_file():
+ raise FileNotFoundError(f"PDFFigures2 JSON 不存在:{path}")
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ if isinstance(raw, dict) and isinstance(raw.get("figures"), list):
+ raw = raw["figures"]
+ if not isinstance(raw, list):
+ raise ValueError("PDFFigures2 JSON 格式不正确:顶层应为列表或含 figures 的对象。")
+
+ candidates: list[Candidate] = []
+ for item in raw:
+ if not isinstance(item, dict):
+ continue
+ region = rect_tuple(item.get("regionBoundary"))
+ if region is None:
+ continue
+ caption_bbox = rect_tuple(item.get("captionBoundary"))
+ kind_raw = str(item.get("figType", "Figure"))
+ kind = "table" if "table" in kind_raw.lower() else "figure"
+ candidates.append(
+ Candidate(
+ kind=kind,
+ label=str(item.get("name", len(candidates) + 1)),
+ page_index=int(item.get("page", 0)),
+ region_bbox=normalize_rect(region),
+ caption_bbox=normalize_rect(caption_bbox) if caption_bbox else None,
+ caption=str(item.get("caption", "")).strip(),
+ source="pdffigures2_json",
+ confidence=0.96,
+ )
+ )
+ return candidates
+
+
+def merge_same_label_tables(candidates: Iterable[Candidate]) -> list[Candidate]:
+ groups: dict[tuple[int, str, str], list[Candidate]] = {}
+ passthrough: list[Candidate] = []
+ for candidate in candidates:
+ label_key = safe_label(candidate.label).lower()
+ if candidate.kind == "table" and not label_key.startswith("fallback_"):
+ groups.setdefault((candidate.page_index, candidate.kind, label_key), []).append(candidate)
+ else:
+ passthrough.append(candidate)
+
+ merged: list[Candidate] = []
+ for group in groups.values():
+ if len(group) == 1:
+ merged.append(group[0])
+ continue
+ region = union_rect(*(item.region_bbox for item in group))
+ if region is None:
+ raise RuntimeError("union_rect returned None for a non-empty table group")
+ caption_item = next((item for item in group if item.caption_bbox), group[0])
+ merged.append(
+ Candidate(
+ kind="table",
+ label=caption_item.label,
+ page_index=caption_item.page_index,
+ region_bbox=region,
+ caption_bbox=caption_item.caption_bbox,
+ caption=caption_item.caption,
+ source="merged_pymupdf_tables",
+ confidence=max(item.confidence for item in group),
+ )
+ )
+ return passthrough + merged
+
+
+def deduplicate(candidates: Iterable[Candidate]) -> list[Candidate]:
+ priority = {
+ "pdffigures2_json": 5,
+ "caption_table_heuristic": 4,
+ "merged_pymupdf_tables": 3,
+ "pymupdf_find_tables": 3,
+ "caption_figure_heuristic": 2,
+ }
+ chosen: list[Candidate] = []
+ ordered = sorted(
+ candidates,
+ key=lambda candidate: (
+ -priority.get(candidate.source, 0),
+ candidate.page_index,
+ candidate.region_bbox[1],
+ candidate.region_bbox[0],
+ ),
+ )
+ for candidate in ordered:
+ is_duplicate = False
+ for old in chosen:
+ if old.page_index != candidate.page_index or old.kind != candidate.kind:
+ continue
+ same_label = (
+ safe_label(old.label).lower() == safe_label(candidate.label).lower()
+ )
+ overlap = iou(old.region_bbox, candidate.region_bbox)
+ containment = intersection_area(old.region_bbox, candidate.region_bbox) / max(
+ 1.0, min(area(old.region_bbox), area(candidate.region_bbox))
+ )
+ strong_overlap = overlap > 0.42
+ mostly_contained = containment > 0.78
+ same_label_touching = same_label and overlap > 0.04
+ if strong_overlap or mostly_contained or same_label_touching:
+ is_duplicate = True
+ break
+ if not is_duplicate:
+ chosen.append(candidate)
+ return sorted(
+ chosen,
+ key=lambda candidate: (
+ candidate.page_index,
+ candidate.region_bbox[1],
+ candidate.region_bbox[0],
+ ),
+ )
+
+
+def clipped_rect(
+ page: pymupdf.Page,
+ bbox: Sequence[float],
+ padding: float,
+ avoid_bbox: Sequence[float] | None = None,
+) -> pymupdf.Rect:
+ content = pymupdf.Rect(*normalize_rect(bbox))
+ rect = pymupdf.Rect(content)
+ rect.x0 -= padding
+ rect.y0 -= padding
+ rect.x1 += padding
+ rect.y1 += padding
+
+ # For the content-only export, padding must not leak into its caption.
+ if avoid_bbox is not None:
+ avoid = pymupdf.Rect(*normalize_rect(avoid_bbox))
+ horizontal_overlap = max(0.0, min(rect.x1, avoid.x1) - max(rect.x0, avoid.x0))
+ vertical_overlap = max(0.0, min(rect.y1, avoid.y1) - max(rect.y0, avoid.y0))
+ if horizontal_overlap > 0:
+ if avoid.y0 >= content.y1 - 1.0:
+ rect.y1 = min(rect.y1, avoid.y0 - 0.5)
+ elif avoid.y1 <= content.y0 + 1.0:
+ rect.y0 = max(rect.y0, avoid.y1 + 0.5)
+ if vertical_overlap > 0:
+ if avoid.x0 >= content.x1 - 1.0:
+ rect.x1 = min(rect.x1, avoid.x0 - 0.5)
+ elif avoid.x1 <= content.x0 + 1.0:
+ rect.x0 = max(rect.x0, avoid.x1 + 0.5)
+
+ return rect & page.rect
+
+
+@dataclass(frozen=True)
+class RenderSettings:
+ """Raster settings shared by every region render."""
+ dpi: int
+ padding: float
+
+
+@dataclass(frozen=True)
+class ExtractOptions:
+ """Everything extract_visuals needs beyond the paper itself."""
+ render: RenderSettings
+ keep_pages: bool
+ debug_dpi: int
+ pdffigures_json: Path | None
+ include_uncaptioned_tables: bool
+
+
+def render_region(
+ page: pymupdf.Page,
+ bbox: Sequence[float],
+ output: Path,
+ settings: RenderSettings,
+ avoid_bbox: Sequence[float] | None = None,
+) -> tuple[int, int]:
+ clip = clipped_rect(page, bbox, settings.padding, avoid_bbox=avoid_bbox)
+ if clip.is_empty or clip.width <= 2 or clip.height <= 2:
+ raise ValueError(f"无效裁剪区域:{list(bbox)}")
+ pixmap = page.get_pixmap(
+ dpi=settings.dpi,
+ clip=clip,
+ colorspace=pymupdf.csRGB,
+ alpha=False,
+ annots=False,
+ )
+ output.parent.mkdir(parents=True, exist_ok=True)
+ pixmap.save(str(output))
+ return pixmap.width, pixmap.height
+
+
+def load_font(size: int) -> ImageFont.ImageFont:
+ candidates = []
+ if os.name == "nt":
+ candidates.extend(
+ [
+ Path(os.environ.get("WINDIR", "C:/Windows")) / "Fonts" / "arial.ttf",
+ Path(os.environ.get("WINDIR", "C:/Windows")) / "Fonts" / "msyh.ttc",
+ ]
+ )
+ elif sys.platform == "darwin":
+ candidates.extend(
+ [
+ Path("/System/Library/Fonts/Supplemental/Arial.ttf"),
+ Path("/System/Library/Fonts/PingFang.ttc"),
+ ]
+ )
+ else:
+ candidates.extend(
+ [
+ Path("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"),
+ Path("/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf"),
+ ]
+ )
+ for path in candidates:
+ if path.is_file():
+ try:
+ return ImageFont.truetype(str(path), size=size)
+ except OSError as cause:
+ # Present but unusable (wrong format, unreadable): try the next
+ # candidate rather than falling straight back to the tiny default.
+ log(f"font unusable, skipping {path}: {cause}")
+ return ImageFont.load_default()
+
+
+def make_debug_pages(
+ doc: pymupdf.Document,
+ candidates: list[Candidate],
+ output_dir: Path,
+ dpi: int,
+) -> None:
+ by_page: dict[int, list[Candidate]] = {}
+ for candidate in candidates:
+ by_page.setdefault(candidate.page_index, []).append(candidate)
+ font = load_font(max(12, int(dpi / 8)))
+
+ for page_index, page_candidates in by_page.items():
+ if not 0 <= page_index < doc.page_count:
+ continue
+ page = doc[page_index]
+ pixmap = page.get_pixmap(
+ dpi=dpi,
+ colorspace=pymupdf.csRGB,
+ alpha=False,
+ annots=False,
+ )
+ image = Image.frombytes("RGB", (pixmap.width, pixmap.height), pixmap.samples)
+ draw = ImageDraw.Draw(image)
+ scale = dpi / 72.0
+ for candidate in page_candidates:
+ x0, y0, x1, y1 = candidate.region_bbox
+ box = tuple(int(value * scale) for value in (x0, y0, x1, y1))
+ draw.rectangle(box, outline="red", width=max(2, int(scale * 1.8)))
+ label = f"{candidate.kind} {candidate.label} [{candidate.source}]"
+ text_x, text_y = box[0] + 4, max(0, box[1] + 4)
+ text_bbox = draw.textbbox((text_x, text_y), label, font=font)
+ draw.rectangle(text_bbox, fill="white")
+ draw.text((text_x, text_y), label, fill="black", font=font)
+ image.save(output_dir / f"page_{page_index + 1:03d}_detections.png")
+
+
+def make_contact_sheet(paths: list[Path], output: Path) -> None:
+ thumbnails: list[Image.Image] = []
+ font = load_font(18)
+ for path in paths:
+ try:
+ with Image.open(path) as source:
+ image = source.convert("RGB")
+ image.thumbnail((520, 360))
+ canvas = Image.new("RGB", (540, 420), "white")
+ canvas.paste(image, ((540 - image.width) // 2, 10))
+ draw = ImageDraw.Draw(canvas)
+ name = path.name if len(path.name) <= 72 else path.name[:69] + "..."
+ draw.text((12, 385), name, fill="black", font=font)
+ thumbnails.append(canvas)
+ except Exception as exc:
+ warn(f"无法加入 contact sheet:{path.name}:{exc}")
+
+ if not thumbnails:
+ return
+ columns = 3 if len(thumbnails) >= 3 else len(thumbnails)
+ rows = math.ceil(len(thumbnails) / columns)
+ sheet = Image.new("RGB", (columns * 540, rows * 420), "white")
+ for index, thumbnail in enumerate(thumbnails):
+ x = (index % columns) * 540
+ y = (index // columns) * 420
+ sheet.paste(thumbnail, (x, y))
+ sheet.save(output)
+
+
+def render_all_pages(doc: pymupdf.Document, output_dir: Path, dpi: int) -> None:
+ for page_index, page in enumerate(doc):
+ pixmap = page.get_pixmap(
+ dpi=dpi,
+ colorspace=pymupdf.csRGB,
+ alpha=False,
+ annots=False,
+ )
+ pixmap.save(str(output_dir / f"page_{page_index + 1:03d}.png"))
+
+
+def extract_visuals(
+ pdf_path: Path,
+ output: Path,
+ resource: InputResource,
+ options: ExtractOptions,
+) -> dict[str, Any]:
+ dpi = options.render.dpi
+ doc = pymupdf.open(pdf_path)
+ if doc.page_count == 0:
+ doc.close()
+ raise ValueError("PDF 没有页面。")
+
+ try:
+ candidates: list[Candidate] = []
+ candidates.extend(load_pdffigures_json(options.pdffigures_json))
+ candidates.extend(find_table_candidates(doc, options.include_uncaptioned_tables))
+ candidates.extend(caption_heuristic_candidates(doc, candidates))
+ candidates = merge_same_label_tables(candidates)
+ candidates = deduplicate(candidates)
+
+ # Final detector-independent cleanup. This is intentionally applied
+ # after deduplication so every candidate path receives the same crop
+ # sanitation, including externally supplied PDFFigures2 boxes.
+ for candidate in candidates:
+ candidate.region_bbox = sanitize_margin_artifacts(
+ doc[candidate.page_index], candidate.region_bbox
+ )
+
+ counters = {"figure": 0, "table": 0}
+ extracted: list[ExtractedVisual] = []
+ contact_paths: list[Path] = []
+ failures: list[dict[str, Any]] = []
+
+ for candidate in candidates:
+ if not 0 <= candidate.page_index < doc.page_count:
+ failures.append(
+ {
+ "candidate": asdict(candidate),
+ "error": "page_index out of range",
+ }
+ )
+ continue
+ page = doc[candidate.page_index]
+ ordinal = counters.get(candidate.kind, 0) + 1
+ counters[candidate.kind] = ordinal
+ label = safe_label(candidate.label)
+ stem = f"{candidate.kind}_{ordinal:03d}_{label}"
+ base_dir = output / ("tables" if candidate.kind == "table" else "figures")
+ caption_dir = output / (
+ "tables_with_caption"
+ if candidate.kind == "table"
+ else "figures_with_caption"
+ )
+ image_path = base_dir / f"{stem}.png"
+ caption_path = caption_dir / f"{stem}_with_caption.png"
+
+ try:
+ width, height = render_region(
+ page,
+ candidate.region_bbox,
+ image_path,
+ options.render,
+ avoid_bbox=candidate.caption_bbox,
+ )
+ # Remove residual blank gutter after the PDF-coordinate crop.
+ # This is what turns the post-stamp whitespace into a tight
+ # figure image without touching internal white areas.
+ width, height = trim_white_border(image_path)
+ combined = union_rect(candidate.region_bbox, candidate.caption_bbox)
+ if combined is not None:
+ try:
+ render_region(page, combined, caption_path, options.render)
+ except Exception:
+ shutil.copy2(image_path, caption_path)
+ else:
+ shutil.copy2(image_path, caption_path)
+ except Exception as exc:
+ failures.append(
+ {
+ "candidate": asdict(candidate),
+ "error": str(exc),
+ }
+ )
+ continue
+
+ contact_paths.append(image_path)
+ extracted.append(
+ ExtractedVisual(
+ id=stem,
+ type=candidate.kind,
+ label=candidate.label,
+ page_index=candidate.page_index,
+ page_number=candidate.page_index + 1,
+ bbox=list(candidate.region_bbox),
+ caption_bbox=(
+ list(candidate.caption_bbox) if candidate.caption_bbox else None
+ ),
+ caption=candidate.caption,
+ image_path=image_path.relative_to(output).as_posix(),
+ image_with_caption_path=caption_path.relative_to(output).as_posix(),
+ extraction_method=candidate.source,
+ confidence=candidate.confidence,
+ pixel_width=width,
+ pixel_height=height,
+ )
+ )
+
+ if options.keep_pages:
+ render_all_pages(doc, output / "pages", dpi)
+
+ make_debug_pages(doc, candidates, output / "debug", options.debug_dpi)
+ make_contact_sheet(contact_paths, output / "contact_sheet.png")
+
+ metadata = doc.metadata or {}
+ manifest: dict[str, Any] = {
+ "schema_version": "1.0",
+ "generator": {
+ "name": "extract_arxiv_visuals.py",
+ "version": SCRIPT_VERSION,
+ "python": sys.version.split()[0],
+ "platform": sys.platform,
+ "pymupdf": getattr(pymupdf, "__version__", "unknown"),
+ },
+ "paper": {
+ "paper_id": resource.paper_id,
+ "source_kind": resource.source_kind,
+ "source_input": resource.original_input,
+ "resolved_pdf_url": resource.pdf_url,
+ "pdf_path": pdf_path.relative_to(output).as_posix(),
+ "pdf_sha256": sha256_file(pdf_path),
+ "page_count": doc.page_count,
+ "title": metadata.get("title", ""),
+ "author": metadata.get("author", ""),
+ "dpi": dpi,
+ },
+ "summary": {
+ "figure_count": sum(1 for item in extracted if item.type == "figure"),
+ "table_count": sum(1 for item in extracted if item.type == "table"),
+ "visual_count": len(extracted),
+ "failure_count": len(failures),
+ },
+ "visuals": [asdict(item) for item in extracted],
+ "failures": failures,
+ "quality_note": (
+ "PyMuPDF 表格检测与 Caption 启发式属于自动检测。"
+ "请查看 debug/ 和 contact_sheet.png 进行视觉复核。"
+ ),
+ }
+ (output / "manifest.json").write_text(
+ json.dumps(manifest, ensure_ascii=False, indent=2),
+ encoding="utf-8",
+ )
+ return manifest
+ finally:
+ doc.close()
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "从 arXiv/PDF 链接或本地 PDF 中检测 Figure 和 Table,"
+ "并按高分辨率保存为 PNG。"
+ ),
+ formatter_class=argparse.RawTextHelpFormatter,
+ epilog=(
+ "示例:\n"
+ ' python extract_arxiv_visuals.py "https://arxiv.org/abs/2606.20515"\n'
+ ' python extract_arxiv_visuals.py "https://arxiv.org/pdf/2606.20515" '
+ "--output ./2606.20515-assets --dpi 400\n"
+ ' python extract_arxiv_visuals.py "D:\\\\papers\\\\paper.pdf" --keep-pages\n'
+ ),
+ )
+ parser.add_argument("input", help="arXiv ID、arXiv URL、PDF URL 或本地 PDF 路径")
+ parser.add_argument(
+ "-o",
+ "--output",
+ type=Path,
+ help="输出目录;默认:./paper-assets-<paper-id>",
+ )
+ parser.add_argument("--dpi", type=int, default=DEFAULT_DPI, help="PNG 分辨率,默认 300")
+ parser.add_argument(
+ "--padding",
+ type=float,
+ default=4.0,
+ help="裁剪区域四周留白,单位为 PDF point,默认 4",
+ )
+ parser.add_argument("--keep-pages", action="store_true", help="同时保存每一页完整 PNG")
+ parser.add_argument("--force", action="store_true", help="覆盖已有输出目录")
+ parser.add_argument(
+ "--debug-dpi",
+ type=int,
+ default=DEFAULT_DEBUG_DPI,
+ help="debug 标注页分辨率,默认 120",
+ )
+ parser.add_argument(
+ "--include-uncaptioned-tables",
+ action="store_true",
+ help=(
+ "保留没有 Table Caption 对应的 PyMuPDF 表格候选。默认关闭,"
+ "因为流程图和仪表盘容易被误判为表格。"
+ ),
+ )
+ parser.add_argument(
+ "--pdffigures-json",
+ type=Path,
+ help=(
+ "可选:读取现有 PDFFigures2 JSON,以提高复杂论文的检测准确率;"
+ "本脚本本身不要求 Java。"
+ ),
+ )
+ parser.add_argument(
+ "--no-auto-install",
+ action="store_true",
+ help="禁止自动 pip 安装 PyMuPDF/Pillow",
+ )
+ parser.add_argument("--version", action="version", version=SCRIPT_VERSION)
+ return parser
+
+
+def main() -> int:
+ parser = build_parser()
+ args = parser.parse_args()
+ if args.dpi <= 0:
+ parser.error("--dpi 必须是正整数")
+ if args.debug_dpi <= 0:
+ parser.error("--debug-dpi 必须是正整数")
+ if args.padding < 0:
+ parser.error("--padding 不能为负数")
+
+ try:
+ log(f"版本 {SCRIPT_VERSION};脚本路径:{Path(__file__).resolve()}")
+ resource = resolve_input(args.input)
+ output = (args.output or Path(f"paper-assets-{resource.paper_id}")).expanduser().resolve()
+ prepare_output(output, args.force, args.keep_pages)
+
+ pdf_path = output / "source" / "paper.pdf"
+ if resource.local_pdf is not None:
+ log(f"复制本地 PDF:{resource.local_pdf}")
+ copy_local_pdf(resource.local_pdf, pdf_path)
+ elif resource.pdf_url is not None:
+ download_pdf(resource.pdf_url, pdf_path)
+ else:
+ raise RuntimeError("没有可用的 PDF 来源。")
+
+ with pdf_path.open("rb") as handle:
+ if handle.read(5) != b"%PDF-":
+ raise ValueError("输入文件不是有效 PDF。")
+
+ log("开始检测并渲染 Figure / Table")
+ manifest = extract_visuals(
+ pdf_path=pdf_path,
+ output=output,
+ resource=resource,
+ options=ExtractOptions(
+ render=RenderSettings(dpi=args.dpi, padding=args.padding),
+ keep_pages=args.keep_pages,
+ debug_dpi=args.debug_dpi,
+ pdffigures_json=args.pdffigures_json,
+ include_uncaptioned_tables=args.include_uncaptioned_tables,
+ ),
+ )
+ summary = manifest["summary"]
+ emit(f"\n完成。输出目录:{output}")
+ emit(
+ "结果:"
+ f"Figure {summary['figure_count']},"
+ f"Table {summary['table_count']},"
+ f"总计 {summary['visual_count']},"
+ f"失败 {summary['failure_count']}"
+ )
+ emit(f"Manifest:{output / 'manifest.json'}")
+ contact_sheet = output / "contact_sheet.png"
+ if contact_sheet.exists():
+ emit(f"总览图:{contact_sheet}")
+ return 0
+ except KeyboardInterrupt:
+ eprint("\n用户中断。")
+ return 130
+ except Exception as exc:
+ eprint(f"\n错误:{exc}")
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/figure-panel.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/figure-panel.js
new file mode 100644
index 0000000000..44842932bc
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/figure-panel.js
@@ -0,0 +1,104 @@
+// Figure panel engine — reads PNG dimensions and computes pure geometry for
+// laying out extracted paper figures into a content-page region. Mirrors the
+// system-diagram.js split: this file holds the engine, components.js
+// holds the thin addFigurePanel wrapper.
+//
+// Everything here is SYNCHRONOUS on purpose: slides.js calls components in
+// sequence, so sharp (async) is not an option for reading image sizes.
+const fs = require("fs");
+
+// A figure this wide (or wider) takes a full row on its own; anything squarer
+// pairs up with a neighbour. Calibrated against real papers: must sit between
+// 1.48 (Alita GAIA table) and 2.96 (Alita architecture figure).
+const WIDE_AR = 2.5;
+const LABEL_H = 0.22; // inches reserved under each row for its Chinese label
+const GAP = 0.12; // inches between rows and between paired figures
+
+// Mirrored from components.js (FONT, THEME.darkGray). Duplicated rather
+// than imported because that module requires this one — same reason
+// system-diagram.js carries its own DEFAULT_THEME palette.
+const LABEL_FONT = "Microsoft YaHei";
+const LABEL_COLOR = "595757";
+
+// Read a PNG's pixel dimensions from its IHDR header, synchronously.
+// PNG layout: 8-byte signature, 4-byte chunk length, 4-byte "IHDR",
+// then width and height as big-endian uint32 at offsets 16 and 20.
+function pngSize(filePath) {
+ const fd = fs.openSync(filePath, "r");
+ const buf = Buffer.alloc(24);
+ try {
+ fs.readSync(fd, buf, 0, 24, 0);
+ } finally {
+ fs.closeSync(fd);
+ }
+ if (buf.readUInt32BE(0) !== 0x89504e47) throw new Error(`not a PNG: ${filePath}`);
+ if (buf.toString("ascii", 12, 16) !== "IHDR") throw new Error(`not a PNG: missing IHDR: ${filePath}`);
+ return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
+}
+
+// Lay figures out in rows inside a w×h region. Returns rects relative to the
+// region's top-left. Labels and gaps keep their absolute size; only the images
+// scale, so labels stay readable however tight the packing gets.
+function layoutFigures(figs, w, h) {
+ const rows = [];
+ for (let i = 0; i < figs.length; i++) {
+ if (figs[i].ar >= WIDE_AR) rows.push([i]);
+ else if (i + 1 < figs.length && figs[i + 1].ar < WIDE_AR) { rows.push([i, i + 1]); i++; }
+ else rows.push([i]);
+ }
+
+ const natural = rows.map((r) => {
+ const cw = r.length === 2 ? (w - GAP) / 2 : w;
+ return Math.max(...r.map((i) => cw / figs[i].ar));
+ });
+
+ const avail = h - rows.length * LABEL_H - GAP * (rows.length - 1);
+ const naturalSum = natural.reduce((a, b) => a + b, 0);
+ const scale = Math.min(1, avail / naturalSum);
+
+ let y = 0;
+ const rects = [];
+ rows.forEach((r, ri) => {
+ const cw = (r.length === 2 ? (w - GAP) / 2 : w) * scale;
+ const rowH = natural[ri] * scale;
+ const rowW = r.length === 2 ? cw * 2 + GAP : cw;
+ let x = (w - rowW) / 2;
+ r.forEach((i) => {
+ const ih = cw / figs[i].ar;
+ rects.push({ i, x, y: y + (rowH - ih) / 2, w: cw, h: ih, labelY: y + rowH });
+ x += cw + GAP;
+ });
+ y += rowH + LABEL_H + (ri < rows.length - 1 ? GAP : 0);
+ });
+
+ return { rects, rows: rows.length, scale, totalH: y };
+}
+
+// Draw the figures into `bounds`. Images are pasted verbatim — no border, no
+// fill, no pixel-level edit (the Python extractor already trimmed white
+// margins). Labels are centered Chinese captions under each figure.
+// No `pres` parameter: unlike renderSystemDiagram (which needs pres.ShapeType),
+// pasting images and captions only ever touches the slide.
+function renderFigurePanel({ slide, figures, bounds }) {
+ const figs = figures.map((f) => {
+ const s = pngSize(f.path);
+ return { ar: s.w / s.h };
+ });
+ const out = layoutFigures(figs, bounds.w, bounds.h);
+ const oy = bounds.y + (bounds.h - out.totalH) / 2; // 内容不足时垂直居中
+
+ out.rects.forEach((c) => {
+ const f = figures[c.i];
+ slide.addImage({ path: f.path, x: bounds.x + c.x, y: oy + c.y, w: c.w, h: c.h });
+ if (f.label) {
+ slide.addText(String(f.label), {
+ x: bounds.x + c.x, y: oy + c.labelY, w: c.w, h: LABEL_H,
+ fontFace: LABEL_FONT, fontSize: 10, color: LABEL_COLOR,
+ align: "center", valign: "middle", margin: 0, fit: "shrink",
+ });
+ }
+ });
+ return out;
+}
+
+module.exports = { pngSize, layoutFigures, renderFigurePanel, WIDE_AR, LABEL_H, GAP };
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/prepare_evidence.py b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/prepare_evidence.py
new file mode 100644
index 0000000000..b84c00093c
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/prepare_evidence.py
@@ -0,0 +1,360 @@
+#!/usr/bin/env python3
+"""Prepare evidence assets declared in evidence-plan.json.
+
+Deterministic routes are handled locally. The paper route delegates to the
+existing extract_arxiv_visuals_v2_2.py and selects from its manifest. Web rows
+accept a confirmed direct URL; AI rows intentionally remain Needs-Manual until
+the Agent generates and reviews the requested illustration.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import logging
+import re
+import shutil
+import subprocess
+import sys
+import urllib.request
+from pathlib import Path
+
+# Diagnostics go to stderr through logging; the completion line is program
+# output and goes to stdout via emit().
+LOGGER = logging.getLogger("prepare_evidence")
+
+
+# Program output (report bodies, --json payloads) goes to stdout, diagnostics
+# to stderr. Both travel through logging; this logger owns stdout, keeps a bare
+# "%(message)s" format so the text is unchanged, and does not propagate so the
+# stderr root handler never sees it.
+STDOUT_LOGGER = logging.getLogger("prepare_evidence.stdout")
+STDOUT_LOGGER.propagate = False
+STDOUT_LOGGER.setLevel(logging.INFO)
+_stdout_handler = logging.StreamHandler(sys.stdout)
+_stdout_handler.setFormatter(logging.Formatter("%(message)s"))
+STDOUT_LOGGER.addHandler(_stdout_handler)
+
+
+def emit(line: str) -> None:
+ STDOUT_LOGGER.info(line)
+
+
+FILE_COPY_ROUTES = {
+ "user", "source-extracted", "product-screenshot", "code-screenshot",
+ "official-logo", "formula", "manual",
+}
+
+# Routes that land a file on disk, so their "path" must stay under the asset root.
+PATH_BEARING_ROUTES = FILE_COPY_ROUTES | {"paper-figure", "web", "ai-illustration"}
+
+# A planned item is (re)prepared only from one of these states.
+PREPARABLE_STATUSES = {"planned", "acquiring", "needs-manual"}
+
+
+def nonempty(value) -> bool:
+ return isinstance(value, str) and bool(value.strip())
+
+
+def resolve(root: Path, value: str | None) -> Path | None:
+ return (root / value).resolve() if nonempty(value) else None
+
+
+def save_plan(path: Path, plan: dict) -> None:
+ path.write_text(json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+def copy_asset(source: Path, destination: Path, force: bool) -> None:
+ if not source.exists():
+ raise FileNotFoundError(source)
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ if destination.exists() and not force:
+ if hashlib.sha256(source.read_bytes()).digest() == hashlib.sha256(destination.read_bytes()).digest():
+ return
+ raise FileExistsError(f"destination exists with different content: {destination}")
+ shutil.copy2(source, destination)
+
+
+def download_asset(url: str, destination: Path, force: bool) -> None:
+ if destination.exists() and not force:
+ return
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ request = urllib.request.Request(url, headers={"User-Agent": "jiuwenswarm-evidence/1.0"})
+ temp = destination.with_suffix(destination.suffix + ".part")
+ with urllib.request.urlopen(request, timeout=120) as response, temp.open("wb") as output:
+ shutil.copyfileobj(response, output)
+ temp.replace(destination)
+
+
+def normalize_label(value: str | None) -> str:
+ normalized = re.sub(r"^(?:fig(?:ure)?|table)\s*\.?\s*", "", str(value or ""), flags=re.I)
+ return normalized.strip().strip(":.、 ").lower()
+
+
+def select_paper_visual(item: dict, manifest: dict) -> tuple[dict | None, list[dict]]:
+ selector = item.get("paper_selector") or {}
+ label = normalize_label(selector.get("label"))
+ keywords = [str(value).lower() for value in selector.get("caption_keywords", [])]
+ # The bundled extractor assigns 0.62 to many valid caption-derived figures.
+ # Confidence narrows candidates; approval remains the hard visual gate.
+ minimum = float(selector.get("min_confidence", 0.55))
+ expected_type = "table" if item.get("kind") == "paper-table" else "figure"
+ ranked = []
+ for visual in manifest.get("visuals", []):
+ if visual.get("type") != expected_type or float(visual.get("confidence", 0)) < minimum:
+ continue
+ caption = str(visual.get("caption", "")).lower()
+ score = float(visual.get("confidence", 0))
+ if label:
+ if normalize_label(visual.get("label")) != label:
+ continue
+ score += 2
+ hits = sum(1 for keyword in keywords if keyword in caption)
+ if keywords and hits == 0:
+ continue
+ score += hits * 0.5
+ ranked.append((score, visual))
+ ranked.sort(key=lambda pair: pair[0], reverse=True)
+ candidates = [visual for _, visual in ranked]
+ if not candidates:
+ return None, []
+ if label or keywords or len(candidates) == 1:
+ if len(ranked) == 1 or ranked[0][0] > ranked[1][0] + 0.15:
+ return ranked[0][1], candidates
+ return None, candidates
+
+
+def prepare_paper(item: dict, root: Path, analysis_root: Path, force: bool) -> None:
+ paper_input = item.get("source_path") or item.get("source_url") or item.get("source")
+ if not nonempty(paper_input):
+ raise ValueError("paper route requires source_path, source_url, or source")
+ local_input = resolve(root, paper_input) if item.get("source_path") else None
+ actual_input = str(local_input if local_input else paper_input)
+ output = analysis_root / "papers" / item["id"]
+ extractor = Path(__file__).with_name("extract_arxiv_visuals_v2_2.py")
+ command = [sys.executable, str(extractor), actual_input, "--output", str(output), "--dpi", "300"]
+ if force or output.exists():
+ command.append("--force")
+ subprocess.run(command, check=True)
+ manifest_path = output / "manifest.json"
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ selected, candidates = select_paper_visual(item, manifest)
+ item["result"] = {
+ "manifest": manifest_path.relative_to(root).as_posix(),
+ "contact_sheet": (output / "contact_sheet.png").relative_to(root).as_posix(),
+ "candidate_ids": [candidate.get("id") for candidate in candidates],
+ }
+ if selected is None:
+ item["status"] = "needs-manual"
+ item["review"] = {
+ "status": "pending",
+ "notes": "Automatic selection was ambiguous; inspect the paper contact "
+ "sheet and set a label/caption selector.",
+ }
+ return
+ include_caption = bool((item.get("paper_selector") or {}).get("include_caption", False))
+ key = "image_with_caption_path" if include_caption else "image_path"
+ source_image = output / selected[key]
+ destination = resolve(root, item.get("path"))
+ if destination is None:
+ raise ValueError("selected paper evidence requires path")
+ copy_asset(source_image, destination, force)
+ item["status"] = "acquiring"
+ item["review"] = {
+ "status": "pending",
+ "notes": f"Selected {selected.get('type')} {selected.get('label')} from "
+ f"page {selected.get('page_number')}; visual review required.",
+ }
+ item["result"].update({
+ "selected_id": selected.get("id"),
+ "caption": selected.get("caption"),
+ "page_number": selected.get("page_number"),
+ "confidence": selected.get("confidence"),
+ })
+
+
+def prepare_item(item: dict, root: Path, analysis_root: Path, force: bool) -> None:
+ route = item.get("acquire_via")
+ if route == "paper-figure":
+ prepare_paper(item, root, analysis_root, force)
+ return
+ if route in FILE_COPY_ROUTES:
+ source = resolve(root, item.get("source_path"))
+ destination = resolve(root, item.get("path"))
+ if source is None or destination is None:
+ raise ValueError(f"{route} requires source_path and path")
+ copy_asset(source, destination, force)
+ item["status"] = "acquiring"
+ item["review"] = {"status": "pending", "notes": "File prepared; visual review required."}
+ return
+ if route == "web":
+ destination = resolve(root, item.get("path"))
+ if destination is None or not nonempty(item.get("source_url")):
+ raise ValueError("web requires a confirmed source_url and path")
+ download_asset(item["source_url"], destination, force)
+ item["status"] = "acquiring"
+ item["review"] = {
+ "status": "pending",
+ "notes": "Downloaded from confirmed URL; verify identity, quality, and rights.",
+ }
+ return
+ if route == "native-chart":
+ source = resolve(root, item.get("source_path"))
+ if source is None or not source.exists():
+ raise ValueError("native-chart requires an existing source_path")
+ item["status"] = "ready"
+ item["review"] = {
+ "status": "not-required",
+ "notes": "Data source is ready; chart rendering is handled in slides.js.",
+ }
+ return
+ if route == "native-drawing":
+ item["status"] = "ready"
+ item["review"] = {"status": "not-required", "notes": "Relationship is encoded as editable native drawing."}
+ return
+ if route == "ai-illustration":
+ prompt_dir = analysis_root / "ai-prompts"
+ prompt_dir.mkdir(parents=True, exist_ok=True)
+ prompt_path = prompt_dir / f"{item['id']}.md"
+ prompt_path.write_text(item.get("query") or item.get("reference") or item.get("purpose"), encoding="utf-8")
+ item["status"] = "needs-manual"
+ item["review"] = {
+ "status": "pending",
+ "notes": f"Generate with the host image tool using "
+ f"{prompt_path.relative_to(root)}; AI cannot serve as factual evidence.",
+ }
+ return
+ raise ValueError(f"unsupported acquire_via: {route}")
+
+
+def approve_item(item: dict, root: Path) -> None:
+ if item.get("acquire_via") in {"native-chart", "native-drawing"}:
+ item["status"] = "ready"
+ item["review"] = {"status": "not-required", "notes": item.get("review", {}).get("notes")}
+ return
+ destination = resolve(root, item.get("path"))
+ if destination is None or not destination.exists():
+ raise FileNotFoundError(f"cannot approve missing asset: {item.get('path')}")
+ item["status"] = "ready"
+ item["review"] = {"status": "approved", "notes": "Approved after visual review."}
+
+
+def use_item(item: dict, root: Path) -> None:
+ if item.get("acquire_via") in {"native-chart", "native-drawing"}:
+ item["status"] = "used"
+ item["review"] = {"status": "not-required", "notes": item.get("review", {}).get("notes")}
+ return
+ destination = resolve(root, item.get("path"))
+ if destination is None or not destination.exists():
+ raise FileNotFoundError(f"cannot mark missing asset as used: {item.get('path')}")
+ if item.get("review", {}).get("status") != "approved":
+ raise ValueError("asset must be visually approved before it can be marked used")
+ item["status"] = "used"
+
+
+def make_contact_sheet(plan: dict, root: Path, analysis_root: Path) -> None:
+ try:
+ from PIL import Image, ImageDraw
+ except ImportError:
+ return
+ entries = []
+ for item in plan.get("items", []):
+ path = resolve(root, item.get("path"))
+ if path and path.exists():
+ try:
+ entries.append((item["id"], path, Image.open(path).convert("RGB")))
+ except (OSError, ValueError) as cause:
+ # A single unreadable asset must not sink the whole sheet; name it
+ # on stderr so the missing tile is traceable.
+ LOGGER.warning("contact sheet skipped %s: %s", item.get("id"), cause)
+ if not entries:
+ return
+ cell_w, cell_h, label_h, cols = 360, 220, 34, 3
+ rows = (len(entries) + cols - 1) // cols
+ sheet = Image.new("RGB", (cols * cell_w, rows * (cell_h + label_h)), "white")
+ draw = ImageDraw.Draw(sheet)
+ for index, (label, _, image) in enumerate(entries):
+ image.thumbnail((cell_w - 20, cell_h - 20))
+ x = (index % cols) * cell_w + (cell_w - image.width) // 2
+ y = (index // cols) * (cell_h + label_h) + (cell_h - image.height) // 2
+ sheet.paste(image, (x, y))
+ label_x = (index % cols) * cell_w + 10
+ label_y = (index // cols) * (cell_h + label_h) + cell_h + 5
+ draw.text((label_x, label_y), label, fill="black")
+ analysis_root.mkdir(parents=True, exist_ok=True)
+ sheet.save(analysis_root / "evidence-contact-sheet.jpg", quality=92)
+
+
+def main() -> int:
+ # Keep the historical "[WARN]" tag rather than logging's default "WARNING".
+ logging.addLevelName(logging.WARNING, "WARN")
+ logging.basicConfig(stream=sys.stderr, level=logging.INFO,
+ format="[%(levelname)s] %(message)s")
+ parser = argparse.ArgumentParser()
+ parser.add_argument("project")
+ parser.add_argument("--plan", default="evidence-plan.json")
+ parser.add_argument("--item", action="append", default=[])
+ parser.add_argument("--approve", action="append", default=[])
+ parser.add_argument("--used", action="append", default=[])
+ parser.add_argument("--reject", action="append", default=[])
+ parser.add_argument("--force", action="store_true")
+ args = parser.parse_args()
+ root = Path(args.project).resolve()
+ plan_path = resolve(root, args.plan)
+ if plan_path is None or not plan_path.exists():
+ LOGGER.error("evidence plan not found: %s", plan_path)
+ return 1
+ plan = json.loads(plan_path.read_text(encoding="utf-8"))
+ asset_root = resolve(root, plan.get("asset_root")) or root / "assets"
+ analysis_root = resolve(root, plan.get("analysis_root")) or root / "analysis"
+ for directory, name in ((asset_root, "asset_root"), (analysis_root, "analysis_root")):
+ try:
+ directory.relative_to(root)
+ except ValueError:
+ LOGGER.error("%s must stay inside project: %s", name, directory)
+ return 1
+ selected = set(args.item)
+ approvals = set(args.approve)
+ used = set(args.used)
+ rejections = set(args.reject)
+ errors = []
+ # --approve / --used / --reject act on named items only; a bare run prepares.
+ review_pass = bool(approvals or used or rejections)
+ for item in plan.get("items", []):
+ item_id = item.get("id")
+ in_scope = not selected or item_id in selected
+ try:
+ if item.get("acquire_via") in PATH_BEARING_ROUTES and nonempty(item.get("path")):
+ destination = resolve(root, item.get("path"))
+ if destination is not None:
+ destination.relative_to(asset_root)
+ if item_id in used:
+ use_item(item, root)
+ elif item_id in approvals:
+ approve_item(item, root)
+ elif item_id in rejections:
+ item["status"] = "needs-manual"
+ item["review"] = {"status": "rejected", "notes": "Rejected during visual review."}
+ elif not review_pass and in_scope:
+ status = item.get("status")
+ requested_retry = bool(selected and item_id in selected)
+ preparable = status in PREPARABLE_STATUSES
+ wanted = status == "planned" or requested_retry or args.force
+ if preparable and wanted:
+ prepare_item(item, root, analysis_root, args.force)
+ except Exception as cause:
+ item["status"] = "needs-manual"
+ item["review"] = {"status": "pending", "notes": str(cause)}
+ errors.append(f"{item.get('id')}: {cause}")
+ save_plan(plan_path, plan)
+ make_contact_sheet(plan, root, analysis_root)
+ for message in errors:
+ LOGGER.warning("%s", message)
+ emit(f"evidence preparation complete: {len(plan.get('items', []))} item(s), "
+ f"{len(errors)} warning(s)")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/qa_density.py b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/qa_density.py
new file mode 100644
index 0000000000..7e7fc4d95a
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/qa_density.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+"""Per-page text-volume gate.
+
+Counts each slide's visible text in "visual chars" (CJK/fullwidth = 1,
+ASCII/latin/digit = 0.5, whitespace ignored) and judges standard content pages
+against floors calibrated on a real internal deck (content pages there
+run 400-700 visual chars, median ~480):
+
+ < 300 EMPTY — hard error: the page reads as half-blank
+ 300-400 LOW — warning: justify against the layout, or flesh out
+ >= 400 OK
+
+ python3 scripts/qa_density.py output/final.pptx --lock execution-lock.json
+
+With --lock, page roles come from execution-lock.json and only
+"standard-content" pages are judged (cover/TOC/closing are exempt). Without
+it, pages under 100 visual chars are assumed structural and only warned —
+always pass the lock in the deck pipeline.
+"""
+import json
+import logging
+import re
+import sys
+import zipfile
+from argparse import ArgumentParser
+from pathlib import Path
+
+FLOOR_HARD = 300
+FLOOR_WARN = 400
+TARGET = "400-700"
+
+
+# Program output (report bodies, --json payloads) goes to stdout, diagnostics
+# to stderr. Both travel through logging; this logger owns stdout, keeps a bare
+# "%(message)s" format so the text is unchanged, and does not propagate so the
+# stderr root handler never sees it.
+STDOUT_LOGGER = logging.getLogger("qa_density.stdout")
+STDOUT_LOGGER.propagate = False
+STDOUT_LOGGER.setLevel(logging.INFO)
+_stdout_handler = logging.StreamHandler(sys.stdout)
+_stdout_handler.setFormatter(logging.Formatter("%(message)s"))
+STDOUT_LOGGER.addHandler(_stdout_handler)
+
+
+def emit(line):
+ """报告正文是工具输出,走 stdout logger,不与 stderr 诊断混在一起。"""
+ STDOUT_LOGGER.info(line)
+
+
+def vis_len(text):
+ return sum(1.0 if ord(c) > 0x2E80 else 0.5 for c in text if not c.isspace())
+
+
+def slide_chars(pptx):
+ with zipfile.ZipFile(pptx) as z:
+ names = sorted(
+ (n for n in z.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
+ key=lambda n: int(re.search(r"\d+", n.rsplit("/", 1)[-1]).group()),
+ )
+ out = []
+ for name in names:
+ xml = z.read(name).decode("utf-8", errors="ignore")
+ out.append(round(vis_len("".join(re.findall(r"<a:t>([^<]*)</a:t>", xml)))))
+ return out
+
+
+def main():
+ ap = ArgumentParser(description=__doc__)
+ ap.add_argument("pptx")
+ ap.add_argument("--lock", help="execution-lock.json for per-page roles")
+ ap.add_argument("--json", action="store_true")
+ args = ap.parse_args()
+
+ chars = slide_chars(args.pptx)
+ roles = [None] * len(chars)
+ if args.lock:
+ pages = json.loads(Path(args.lock).read_text(encoding="utf-8")).get("pages", [])
+ if len(pages) == len(chars):
+ roles = [p.get("role") for p in pages]
+ else:
+ emit(f"qa_density: WARNING lock has {len(pages)} pages but deck has "
+ f"{len(chars)} slides; falling back to role-less judgement")
+ args.lock = None
+
+ rows, errors, warnings = [], 0, 0
+ for i, (n, role) in enumerate(zip(chars, roles), 1):
+ if args.lock:
+ judged = role == "standard-content"
+ else:
+ judged = not (i == 1 or i == len(chars) or n < 100)
+ if not judged:
+ verdict = "exempt" if args.lock or i in (1, len(chars)) else "structural?"
+ elif n < FLOOR_HARD:
+ verdict = "EMPTY"
+ errors += 1
+ elif n < FLOOR_WARN:
+ verdict = "LOW"
+ warnings += 1
+ else:
+ verdict = "OK"
+ rows.append({"page": i, "role": role or "-", "vis_chars": n, "verdict": verdict})
+
+ if args.json:
+ emit(json.dumps({"pages": rows, "errors": errors, "warnings": warnings,
+ "target": TARGET}, ensure_ascii=False, indent=2))
+ else:
+ for r in rows:
+ emit(f" p{r['page']:>2} {r['vis_chars']:>5} {r['verdict']:<11} {r['role']}")
+ emit(f"qa_density: {errors} EMPTY (<{FLOOR_HARD}), {warnings} LOW "
+ f"(<{FLOOR_WARN}); content-page target {TARGET} visual chars")
+ sys.exit(1 if errors else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/qa_geometry.py b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/qa_geometry.py
new file mode 100644
index 0000000000..5dd066c2f3
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/qa_geometry.py
@@ -0,0 +1,486 @@
+#!/usr/bin/env python3
+"""几何自检:直接解析 .pptx,抓重叠、遮挡、越界和轴线不齐。
+
+不依赖生成代码,对任何 pptx 都能跑。设计目的是补上人眼 QA 的盲区——
+contact sheet 缩略图看不见 0.1 英寸级的重叠和错位。
+
+用法:
+ python3 qa_geometry.py deck.pptx
+ python3 qa_geometry.py deck.pptx --json
+ python3 qa_geometry.py deck.pptx --slide 6
+
+坐标一律换算回 10 × 5.625 创作坐标系报告,因为那是 slides.js 里写的数值。
+"""
+
+import argparse
+import json
+import logging
+import re
+import sys
+import zipfile
+from dataclasses import dataclass, field
+
+EMU_PER_INCH = 914400
+AUTHOR_W, AUTHOR_H = 10.0, 5.625
+
+# 总结条上沿。内容必须在此之上结束(base/template-contract.md)。
+SUMMARY_TOP = 4.65
+
+NS = {
+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",
+}
+
+
+# Program output (report bodies, --json payloads) goes to stdout, diagnostics
+# to stderr. Both travel through logging; this logger owns stdout, keeps a bare
+# "%(message)s" format so the text is unchanged, and does not propagate so the
+# stderr root handler never sees it.
+STDOUT_LOGGER = logging.getLogger("qa_geometry.stdout")
+STDOUT_LOGGER.propagate = False
+STDOUT_LOGGER.setLevel(logging.INFO)
+_stdout_handler = logging.StreamHandler(sys.stdout)
+_stdout_handler.setFormatter(logging.Formatter("%(message)s"))
+STDOUT_LOGGER.addHandler(_stdout_handler)
+
+
+def emit(line: str) -> None:
+ """报告正文是工具输出,走 stdout logger,不与 stderr 诊断混在一起。"""
+ STDOUT_LOGGER.info(line)
+
+
+@dataclass(frozen=True)
+class Offset:
+ """group 造成的坐标偏移(已换算为英寸)。"""
+ dx: float = 0.0
+ dy: float = 0.0
+
+
+@dataclass
+class Element:
+ z: int # 文档顺序 = z-order,越大越靠上
+ kind: str # sp | pic | graphicFrame | grpSp
+ name: str
+ x: float
+ y: float
+ w: float
+ h: float
+ filled: bool = False # 有不透明填充
+ text: str = ""
+ font_pts: list = field(default_factory=list)
+
+ @property
+ def x2(self):
+ return self.x + self.w
+
+ @property
+ def y2(self):
+ return self.y + self.h
+
+ @property
+ def area(self):
+ return max(0.0, self.w) * max(0.0, self.h)
+
+ @property
+ def has_text(self):
+ return bool(self.text.strip())
+
+ def label(self):
+ t = self.text.strip().replace("\n", " ")
+ if len(t) > 22:
+ t = t[:22] + "…"
+ return f'"{t}"' if t else f"<{self.kind} {self.name}>"
+
+
+def intersect(a: Element, b: Element):
+ """返回 (相交面积, 相交矩形)。"""
+ x1, y1 = max(a.x, b.x), max(a.y, b.y)
+ x2, y2 = min(a.x2, b.x2), min(a.y2, b.y2)
+ if x2 <= x1 or y2 <= y1:
+ return 0.0, None
+ return (x2 - x1) * (y2 - y1), (x1, y1, x2 - x1, y2 - y1)
+
+
+def contains(outer: Element, inner: Element, tol=0.02):
+ return (outer.x - tol <= inner.x and outer.y - tol <= inner.y
+ and outer.x2 + tol >= inner.x2 and outer.y2 + tol >= inner.y2)
+
+
+# ---------------------------------------------------------------- XML 解析
+
+def _lname(tag):
+ return tag.split("}")[-1]
+
+
+def _xfrm(node):
+ """从 spPr/xfrm 或 grpSpPr/xfrm 读 off/ext,返回 EMU。"""
+ for child in node:
+ if _lname(child.tag) in ("spPr", "grpSpPr", "xfrm"):
+ xfrm = child if _lname(child.tag) == "xfrm" else child.find("a:xfrm", NS)
+ if xfrm is None:
+ continue
+ off = xfrm.find("a:off", NS)
+ ext = xfrm.find("a:ext", NS)
+ if off is None or ext is None:
+ continue
+ return (int(off.get("x", 0)), int(off.get("y", 0)),
+ int(ext.get("cx", 0)), int(ext.get("cy", 0)))
+ # graphicFrame 的 xfrm 是直接子元素
+ xfrm = node.find("p:xfrm", NS)
+ if xfrm is not None:
+ off, ext = xfrm.find("a:off", NS), xfrm.find("a:ext", NS)
+ if off is not None and ext is not None:
+ return (int(off.get("x", 0)), int(off.get("y", 0)),
+ int(ext.get("cx", 0)), int(ext.get("cy", 0)))
+ return None
+
+
+def _is_filled(node):
+ """判断有没有不透明填充。noFill / 无 fill 元素都算透明。"""
+ sp_pr = node.find("p:spPr", NS)
+ if sp_pr is None:
+ return False
+ for tag in ("solidFill", "gradFill", "blipFill", "pattFill"):
+ el = sp_pr.find(f"a:{tag}", NS)
+ if el is not None:
+ # 检查 alpha,全透明不算
+ alpha = el.find(".//a:alpha", NS)
+ if alpha is not None and int(alpha.get("val", 100000)) < 20000:
+ return False
+ return True
+ return False
+
+
+def _text_and_fonts(node):
+ txt, fonts = [], []
+ for r in node.iter():
+ ln = _lname(r.tag)
+ if ln == "t" and r.text:
+ txt.append(r.text)
+ elif ln in ("rPr", "defRPr", "endParaRPr"):
+ sz = r.get("sz")
+ if sz:
+ fonts.append(int(sz) / 100.0)
+ return "".join(txt), fonts
+
+
+def _walk(container, scale, elements, z_start=0, offset=Offset()):
+ """递归收集元素。offset 是 group 造成的偏移(已换算为英寸)。"""
+ z = z_start
+ for node in container:
+ ln = _lname(node.tag)
+ if ln not in ("sp", "pic", "graphicFrame", "grpSp"):
+ continue
+ geom = _xfrm(node)
+ if geom is None:
+ continue
+ x, y, cx, cy = [v / EMU_PER_INCH / scale for v in geom]
+ x, y = x + offset.dx, y + offset.dy
+
+ nv = node.find(f"p:nv{'Grp' if ln == 'grpSp' else ''}SpPr/p:cNvPr", NS)
+ if nv is None:
+ for c in node.iter():
+ if _lname(c.tag) == "cNvPr":
+ nv = c
+ break
+ name = nv.get("name", "?") if nv is not None else "?"
+
+ if ln == "grpSp":
+ # group 内部坐标需按 chOff/chExt 映射;这里做常见情况的近似处理
+ z = _walk(node, scale, elements, z, Offset(dx=x, dy=y))
+ continue
+
+ text, fonts = _text_and_fonts(node)
+ elements.append(Element(
+ z=z, kind=ln, name=name, x=x, y=y, w=cx, h=cy,
+ filled=_is_filled(node) if ln == "sp" else True,
+ text=text, font_pts=fonts,
+ ))
+ z += 1
+ return z
+
+
+def parse_slide(xml_bytes, scale):
+ import xml.etree.ElementTree as ET
+ root = ET.fromstring(xml_bytes)
+ sp_tree = root.find(".//p:cSld/p:spTree", NS)
+ elements = []
+ if sp_tree is not None:
+ _walk(sp_tree, scale, elements)
+ return elements
+
+
+def _rel_target(zf, part, want):
+ """从某个 part 的 .rels 里找指定类型的目标 part 路径。"""
+ base, name = part.rsplit("/", 1)
+ rels = f"{base}/_rels/{name}.rels"
+ if rels not in zf.namelist():
+ return None
+ xml = zf.read(rels).decode("utf-8", "ignore")
+ m = re.search(rf'Target="([^"]*{want}[^"]*)"', xml)
+ if not m:
+ return None
+ tgt = m.group(1)
+ if tgt.startswith("../"):
+ return "ppt/" + tgt[3:]
+ return f"{base}/{tgt}"
+
+
+def inherited_elements(zf, slide_part, scale):
+ """收集从 slideLayout / slideMaster 继承下来的、真正会渲染的元素。
+
+ 最典型的错误是「页面自绘页脚 + 母版继承页脚」叠在一起。
+ 只看 slide XML 永远发现不了,必须把继承层一起算进来。
+ 空占位符不渲染,按有无文字/图片过滤。
+ """
+ out = []
+ layout = _rel_target(zf, slide_part, "slideLayout")
+ parts = []
+ if layout:
+ parts.append(layout)
+ master = _rel_target(zf, layout, "slideMaster")
+ if master:
+ parts.append(master)
+ for p in parts:
+ if p not in zf.namelist():
+ continue
+ for e in parse_slide(zf.read(p), scale):
+ if not e.has_text and e.kind != "pic":
+ continue # 空占位符不渲染
+ e.z = -1000 # 继承层永远画在最底下
+ e.name = f"[继承]{e.name}"
+ out.append(e)
+ return out
+
+
+def check_duplicate_chrome(slide_els, inherited, tol=0.30):
+ """页面自绘元素与继承的固定框架元素重合 —— 底部框架画了两遍。"""
+ out = []
+ for inh in inherited:
+ for e in slide_els:
+ # 位置接近且都是文字,或都是图片 —— 判为重复
+ same_spot = (abs(e.x - inh.x) < tol and abs(e.y - inh.y) < tol)
+ if not same_spot:
+ continue
+ if e.kind == "pic" and inh.kind == "pic":
+ out.append({
+ "type": "duplicate-chrome",
+ "severity": "error",
+ "detail": f"页面自绘图片与继承的 {inh.name} 位置重合,"
+ f"Logo/页脚可能画了两遍",
+ })
+ elif e.has_text and inh.has_text:
+ out.append({
+ "type": "duplicate-chrome",
+ "severity": "error",
+ "detail": f"页面 {e.label()} 与继承的 {inh.label()} 位置重合,"
+ f"密级/页码/页脚可能画了两遍",
+ })
+ return out
+
+
+# ---------------------------------------------------------------- 检查项
+
+def ink_box(e: Element):
+ """估算文字真正占用的矩形,而不是整个文本框。
+
+ 文本框通常开得比文字大,直接用框判重叠会把"卡片左标签 + 右正文"
+ 这种正常排版误判成碰撞。按字符宽度粗估实际墨迹范围。
+ """
+ if not e.has_text:
+ return e
+ pt = max(e.font_pts) if e.font_pts else 12.0
+ ch = pt / 72.0 # 一个全角字的近似宽度(英寸)
+ lines = e.text.split("\n")
+ widest = 0.0
+ for ln in lines:
+ w = sum(ch if ord(c) > 0x2E80 else ch * 0.55 for c in ln)
+ widest = max(widest, w)
+ # 超出框宽会自动折行
+ text_w = min(widest, e.w) if e.w > 0 else widest
+ wrapped = sum(max(1, int(sum(ch if ord(c) > 0x2E80 else ch * 0.55
+ for c in ln) / e.w) + 1) if e.w > 0 else 1
+ for ln in lines)
+ text_h = min(e.h, wrapped * pt / 72.0 * 1.35)
+
+ # 水平方向按居中估计(居中和左对齐都常见,居中是较松的假设)
+ cx = e.x + e.w / 2
+ x = max(e.x, cx - text_w / 2)
+ # 垂直方向同样按居中
+ cy = e.y + e.h / 2
+ y = max(e.y, cy - text_h / 2)
+ return Element(z=e.z, kind=e.kind, name=e.name, x=x, y=y,
+ w=min(text_w, e.w), h=min(text_h, e.h),
+ filled=e.filled, text=e.text, font_pts=e.font_pts)
+
+
+def check_text_collision(els, min_area=0.012, min_frac=0.12):
+ """两个元素的实际文字墨迹重叠 —— 字压字,一定是错。"""
+ out = []
+ texts = [e for e in els if e.has_text]
+ inks = {id(e): ink_box(e) for e in texts}
+ for i, a in enumerate(texts):
+ for b in texts[i + 1:]:
+ # 一方完全包住另一方,通常是卡片带标题的正常嵌套
+ if contains(a, b) or contains(b, a):
+ continue
+ ia, ib = inks[id(a)], inks[id(b)]
+ area, rect = intersect(ia, ib)
+ if area < min_area:
+ continue
+ if area / min(ia.area, ib.area) < min_frac:
+ continue
+ out.append({
+ "type": "text-collision",
+ "severity": "error",
+ "detail": f"{a.label()} 与 {b.label()} 文字重叠",
+ "overlap_in2": round(area, 4),
+ "rect": [round(v, 3) for v in rect],
+ })
+ return out
+
+
+def check_occlusion(els, min_area=0.02, min_frac=0.10):
+ """后画的不透明形状盖住先画的文字,且没有完全包住 —— 遮挡截断。"""
+ out = []
+ for a in els:
+ if not a.has_text:
+ continue
+ for b in els:
+ if b.z <= a.z or not b.filled or b.has_text:
+ continue
+ if contains(b, a):
+ continue # 完全覆盖当背景处理,另有检查
+ area, rect = intersect(a, b)
+ if area < min_area or area / a.area < min_frac:
+ continue
+ out.append({
+ "type": "occlusion",
+ "severity": "error",
+ "detail": f"{b.label()} 压住 {a.label()}(后者更早绘制)",
+ "overlap_in2": round(area, 4),
+ "rect": [round(v, 3) for v in rect],
+ })
+ return out
+
+
+def check_bounds(els, tol=0.02):
+ out = []
+ for e in els:
+ starts_off_canvas = e.x < -tol or e.y < -tol
+ ends_off_canvas = e.x2 > AUTHOR_W + tol or e.y2 > AUTHOR_H + tol
+ if starts_off_canvas or ends_off_canvas:
+ out.append({
+ "type": "out-of-bounds",
+ "severity": "error",
+ "detail": f"{e.label()} 越出画布:x={e.x:.2f}..{e.x2:.2f} y={e.y:.2f}..{e.y2:.2f}",
+ })
+ elif e.has_text and e.y2 > SUMMARY_TOP + tol and e.y < SUMMARY_TOP:
+ out.append({
+ "type": "summary-intrusion",
+ "severity": "warning",
+ "detail": f"{e.label()} 侵入总结条区域(底端 {e.y2:.2f} > {SUMMARY_TOP})",
+ })
+ return out
+
+
+def check_axis(els, near=0.16, exact=0.012, min_w=3.0):
+ """主区块的左右边界近似但不相等 —— 各区各写各的魔数,而非共用常量。
+
+ 只看宽度 >= min_w 的大区块(矩阵、路径带、通栏框这类撑起版面的),
+ 卡片和小标签的边界本来就不该强求对齐。每条轴线只报一次最小偏差。
+ """
+ out = []
+ wide = [e for e in els if e.w >= min_w and e.y < SUMMARY_TOP]
+ if len(wide) < 2:
+ return out
+ for side, get in (("左", lambda e: e.x), ("右", lambda e: e.x2)):
+ vals = sorted({round(get(e), 3) for e in wide})
+ # 把彼此接近的边界聚成一簇,只对簇内跨度报一次
+ cluster = [vals[0]]
+ for v in vals[1:] + [float("inf")]:
+ if v - cluster[-1] <= near:
+ cluster.append(v)
+ continue
+ if len(cluster) > 1:
+ span = cluster[-1] - cluster[0]
+ if span > exact:
+ out.append({
+ "type": "axis-drift",
+ "severity": "warning",
+ "detail": f"{side}边界有 {len(cluster)} 个不同取值 "
+ f"({cluster[0]:.3f}..{cluster[-1]:.3f}),"
+ f"相差 {span:.3f}\",应共用同一条轴线常量",
+ })
+ cluster = [v]
+ return out
+
+
+# ---------------------------------------------------------------- 主流程
+
+def analyze(path, only_slide=None):
+ zf = zipfile.ZipFile(path)
+
+ pres = zf.read("ppt/presentation.xml").decode("utf-8", "ignore")
+ m = re.search(r'sldSz[^/]*cx="(\d+)"', pres)
+ canvas_w = int(m.group(1)) / EMU_PER_INCH if m else 13.3333
+ scale = canvas_w / AUTHOR_W # 成品画布 / 创作画布
+
+ names = sorted(
+ (n for n in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
+ key=lambda n: int(re.search(r"(\d+)", n.rsplit("/", 1)[1]).group(1)),
+ )
+
+ report = {
+ "pptx": path,
+ "canvas_in": round(canvas_w, 3),
+ "scale_to_authoring": round(scale, 4),
+ "slides": len(names),
+ "findings": [],
+ }
+
+ for idx, n in enumerate(names, 1):
+ if only_slide and idx != only_slide:
+ continue
+ els = parse_slide(zf.read(n), scale)
+ inh = inherited_elements(zf, n, scale)
+ found = (check_text_collision(els) + check_occlusion(els)
+ + check_bounds(els) + check_axis(els)
+ + check_duplicate_chrome(els, inh))
+ for f in found:
+ f["slide"] = idx
+ report["findings"].extend(found)
+
+ report["errors"] = sum(1 for f in report["findings"] if f["severity"] == "error")
+ report["warnings"] = sum(1 for f in report["findings"] if f["severity"] == "warning")
+ return report
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("pptx")
+ ap.add_argument("--json", action="store_true")
+ ap.add_argument("--slide", type=int)
+ args = ap.parse_args()
+
+ rep = analyze(args.pptx, args.slide)
+
+ if args.json:
+ emit(json.dumps(rep, ensure_ascii=False, indent=2))
+ return 1 if rep["errors"] else 0
+
+ emit(f"qa-geometry: {rep['errors']} error(s), {rep['warnings']} warning(s), "
+ f"slides={rep['slides']}, 坐标已换算回 10×5.625")
+ by_slide = {}
+ for f in rep["findings"]:
+ by_slide.setdefault(f["slide"], []).append(f)
+ for slide_no, slide_findings in sorted(by_slide.items()):
+ emit(f"\n— slide {slide_no}")
+ for f in slide_findings:
+ mark = "✗" if f["severity"] == "error" else "!"
+ emit(f" {mark} [{f['type']}] {f['detail']}")
+ return 1 if rep["errors"] else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/sync-runtime-skill.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/sync-runtime-skill.js
new file mode 100644
index 0000000000..e93b61d8d0
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/sync-runtime-skill.js
@@ -0,0 +1,179 @@
+#!/usr/bin/env node
+// Sync the repo copy of the ppt-creation skill to the runtime copy the agent
+// actually loads, register any new files in agent-data.json manifests, and verify
+// the two copies match by hash. No third-party deps.
+//
+// node scripts/sync-runtime-skill.js
+//
+// Exits 0 and prints "ALL IN SYNC" when the key files are byte-identical on both
+// sides; exits 1 and lists the mismatches otherwise.
+
+const fs = require("fs");
+const path = require("path");
+const crypto = require("crypto");
+
+const SRC = path.resolve(__dirname, ".."); // .../skills/ppt-creation (repo copy)
+const DST = path.resolve(
+ process.env.HOME, ".jiuwenswarm/agent/workspace/skills/ppt-creation" // runtime copy
+);
+const AGENT_DATA = [
+ path.resolve(SRC, "../../agent-data.json"), // repo manifest
+ path.resolve(process.env.HOME, ".jiuwenswarm/agent/workspace/agent-data.json"), // runtime manifest
+];
+
+const EXCLUDE_DIRS = new Set(["node_modules", "output", ".git"]);
+const EXCLUDE_EXT = new Set([".pptx", ".pdf", ".png.tmp"]);
+const EXCLUDE_NAME = new Set([".DS_Store"]);
+
+// Repo-only files stay in the repo copy and must never reach the runtime
+// workspace or its manifests — the agent treats everything there as reference
+// material. Unlike EXCLUDE_*, these are still walked on the runtime side so a
+// previously synced copy gets removed as stale.
+function isRepoOnly(name) {
+ return /^demo[_-]/.test(name);
+}
+
+function shouldSkip(name) {
+ if (EXCLUDE_DIRS.has(name) || EXCLUDE_NAME.has(name)) return true;
+ if (EXCLUDE_EXT.has(path.extname(name))) return true;
+ return false;
+}
+
+function walk(dir, base = "") {
+ const out = [];
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (shouldSkip(entry.name)) continue;
+ const rel = path.join(base, entry.name);
+ const abs = path.join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...walk(abs, rel));
+ else if (entry.isFile()) out.push(rel);
+ }
+ return out;
+}
+
+function sha256(file) {
+ return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
+}
+
+// 1) Mirror repo -> runtime (create/overwrite current files, remove stale files).
+const files = walk(SRC).filter((rel) => !isRepoOnly(path.basename(rel)));
+const sourceFiles = new Set(files);
+let copied = 0;
+for (const rel of files) {
+ const from = path.join(SRC, rel);
+ const to = path.join(DST, rel);
+ fs.mkdirSync(path.dirname(to), { recursive: true });
+ const changed = !fs.existsSync(to) || sha256(from) !== sha256(to);
+ if (changed) { fs.copyFileSync(from, to); copied += 1; }
+}
+// Stale removal is confined to path roots the repo actually mirrors. Anything
+// else in the runtime copy (e.g. a task workspace an agent created next to the
+// skill files) is not ours to manage — deleting it destroys live task state.
+// 2026-07-22: the unguarded version wiped a just-finished deck workspace.
+const ownedRoots = new Set(files.map((rel) => rel.split(path.sep)[0]));
+let removedRuntime = 0;
+if (fs.existsSync(DST)) {
+ for (const rel of walk(DST)) {
+ if (sourceFiles.has(rel)) continue;
+ if (!ownedRoots.has(rel.split(path.sep)[0])) continue;
+ fs.rmSync(path.join(DST, rel), { force: true });
+ removedRuntime += 1;
+ }
+
+ // File mirroring can leave empty directories behind (for example when an
+ // obsolete asset family is removed). Prune those without touching excluded
+ // runtime directories such as node_modules.
+ const pruneEmptyDirs = (dir) => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (!entry.isDirectory() || shouldSkip(entry.name)) continue;
+ const child = path.join(dir, entry.name);
+ pruneEmptyDirs(child);
+ if (fs.readdirSync(child).length === 0) fs.rmdirSync(child);
+ }
+ };
+ for (const entry of fs.readdirSync(DST, { withFileTypes: true })) {
+ if (!entry.isDirectory() || shouldSkip(entry.name) || !ownedRoots.has(entry.name)) continue;
+ const child = path.join(DST, entry.name);
+ pruneEmptyDirs(child);
+ if (fs.readdirSync(child).length === 0) fs.rmdirSync(child);
+ }
+}
+console.log(`Mirrored ${files.length} file(s): ${copied} changed, ${removedRuntime} stale runtime file(s) removed.`);
+
+// 2) Reconcile files in the skill root and owned first-level directories with
+// the agent-data.json manifests (idempotent). Including the root makes a
+// git-restored compatibility file discoverable again on the next sync.
+const MANIFEST_DIRS = ["", "agents", "base", "components", "references", "scripts", "workflows"];
+
+function reconcileManifest(manifestPath) {
+ if (!fs.existsSync(manifestPath)) { console.warn(` (skip, absent) ${manifestPath}`); return; }
+ const data = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
+ let added = 0, removed = 0;
+ const skillKey = "workspace/skills/ppt-creation";
+ const prefix = `${skillKey}/`;
+
+ // Remove directory keys and file entries whose source paths no longer exist.
+ for (const key of Object.keys(data)) {
+ if ((key !== skillKey && !key.startsWith(prefix)) || !Array.isArray(data[key])) continue;
+ const dirRel = key === skillKey ? "" : key.slice(prefix.length);
+ const dirPath = path.join(SRC, dirRel);
+ if (!fs.existsSync(dirPath) || !fs.statSync(dirPath).isDirectory()) {
+ removed += data[key].length;
+ delete data[key];
+ continue;
+ }
+ const kept = data[key].filter((entry) => {
+ const exists = entry && entry.name && !isRepoOnly(entry.name) &&
+ fs.existsSync(path.join(dirPath, entry.name));
+ if (!exists) removed += 1;
+ return exists;
+ });
+ data[key] = kept;
+ }
+
+ for (const dirRel of MANIFEST_DIRS) {
+ const dirPath = path.join(SRC, dirRel);
+ if (!fs.existsSync(dirPath)) continue;
+ const key = dirRel
+ ? `workspace/skills/ppt-creation/${dirRel}`
+ : "workspace/skills/ppt-creation";
+ if (!Array.isArray(data[key])) data[key] = [];
+ const present = new Set(data[key].map((e) => e.name));
+ for (const name of fs.readdirSync(dirPath)) {
+ if (shouldSkip(name) || isRepoOnly(name) || fs.statSync(path.join(dirPath, name)).isDirectory()) continue;
+ if (!present.has(name)) {
+ data[key].push({
+ name,
+ path: dirRel
+ ? `agent/workspace/skills/ppt-creation/${dirRel}/${name}`
+ : `agent/workspace/skills/ppt-creation/${name}`,
+ isMarkdown: name.endsWith(".md"),
+ });
+ added += 1;
+ }
+ }
+ }
+ if (added || removed) fs.writeFileSync(manifestPath, JSON.stringify(data, null, 2));
+ console.log(
+ ` ${path.basename(path.dirname(manifestPath))}/agent-data.json: +${added}, -${removed} file entr${removed === 1 ? "y" : "ies"}`
+ );
+}
+console.log("Manifest reconciliation:");
+for (const m of AGENT_DATA) reconcileManifest(m);
+
+// 3) Hash-compare the key working files.
+const KEY = files.filter((r) =>
+ MANIFEST_DIRS.some((dir) => dir && r.startsWith(`${dir}/`)) ||
+ (!r.includes("/") && r.endsWith(".md"))
+);
+const diffs = [];
+for (const rel of KEY) {
+ const to = path.join(DST, rel);
+ if (!fs.existsSync(to) || sha256(path.join(SRC, rel)) !== sha256(to)) diffs.push(rel);
+}
+console.log(`Hash check: ${KEY.length - diffs.length}/${KEY.length} key files identical.`);
+if (diffs.length) {
+ console.error("DIFF:", diffs.join(", "));
+ process.exit(1);
+}
+console.log("ALL IN SYNC");
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/system-diagram.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/system-diagram.js
new file mode 100644
index 0000000000..eaffabf212
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/system-diagram.js
@@ -0,0 +1,874 @@
+// System-diagram renderer for the deck pptxgenjs skill.
+// Declarative Diagram IR (bands / groups / items / edges) -> deterministic layout
+// -> native pptxgenjs shapes (p:sp / p:cxnSp; never an image). CommonJS module.
+//
+// Adapted from the generic_system_diagram bundle: kept normalizeSpec's structural
+// validation + the layout/draw engine; removed the OpenAI planner, CLI, offline
+// demos, and the suitability (assessment / render_decision) gate. Palette and font
+// bounds are injected per render via `theme`, so the engine is not hard-wired to
+// any one palette — components.js passes the deck theme. Consumers call
+// renderSystemDiagram({ pres, slide, spec, bounds, theme }).
+
+const FONT = "Microsoft YaHei";
+
+// Neutral fallback palette, in the internal (bundle) key shape. The soft
+// green/yellow/orange tints fill bands and groups; emphasis uses the deck
+// accent, genuine warnings use a distinct red, text/lines use grays.
+const DEFAULT_COLORS = {
+ accent: "4472C4", warning: "C00000",
+ green: "E2F2D5", green2: "D9EAD3", yellow: "FFF2CC", orange: "FCE4D6",
+ blue: "DDEBF7", comparisonB: "EDE7F6",
+ white: "FFFFFF", text: "000000",
+ gray: "B5B5B5", lightGray: "B5B5B5", darkGray: "595757",
+};
+
+// Public theme shape callers pass; mapped onto the internal COLORS at render entry.
+const DEFAULT_THEME = {
+ accent: "4472C4", warning: "C00000", white: "FFFFFF", text: "000000",
+ gray: "B5B5B5", lightGray: "B5B5B5", darkGray: "595757",
+ tints: { green: "E2F2D5", green2: "D9EAD3", yellow: "FFF2CC", orange: "FCE4D6", blue: "DDEBF7", gray: "EDE7F6" },
+ fontMin: 6, fontMax: 13,
+ pageW: 10, pageH: 5.625, // LAYOUT_16x9 — used only to clamp loop-edge labels on-slide
+};
+
+// Module-level render state, (re)assigned at the start of every renderSystemDiagram call.
+let SHAPE_TYPE = null; // set from pres.ShapeType
+let COLORS = DEFAULT_COLORS;
+let FONT_MIN = 6;
+let FONT_MAX = 13;
+let PAGE_W = 10;
+let PAGE_H = 5.625;
+
+function clampFont(size) {
+ return Math.max(FONT_MIN, Math.min(FONT_MAX, size));
+}
+
+// Legibility floors for node/item boxes, shared between the measure phase
+// (measureBandMinHeight) and the render phase (computeBandLayout) so the two
+// can never disagree about how small a box is allowed to get. See the
+// [DIAGRAM-OVER-CAPACITY] comment on computeBandRects for why this needs to
+// be a real floor rather than a bare Math.min.
+const ITEM_H_FLOOR = 0.24;
+const NODE_H_FLOOR = 0.26;
+const SIMPLE_BAR_MIN_H = 0.42;
+
+function themeToColors(theme) {
+ if (!theme) return DEFAULT_COLORS;
+ const t = theme.tints || DEFAULT_THEME.tints;
+ return {
+ accent: theme.accent, warning: theme.warning || theme.accent,
+ green: t.green, green2: t.green2 || t.green, yellow: t.yellow, orange: t.orange,
+ blue: t.blue, comparisonB: t.gray,
+ white: theme.white, text: theme.text,
+ gray: theme.gray, lightGray: theme.lightGray || theme.gray, darkGray: theme.darkGray,
+ };
+}
+
+function assertString(value, name, allowEmpty = false) {
+ if (typeof value !== "string" || (!allowEmpty && value.trim() === "")) {
+ throw new Error(`${name} must be ${allowEmpty ? "a string" : "a non-empty string"}.`);
+ }
+}
+
+// CJK/fullwidth glyphs render roughly twice as wide as Latin letters. `max` was
+// tuned by eye against Chinese labels (1 char = 1 unit); counting Latin/digit/
+// punctuation runs as 0.5 unit keeps that Chinese calibration unchanged while
+// giving English labels ~2x the character budget. Without this, a plain
+// `length > max` cut English labels far too early — "Residual Extraction
+// Agent" (26 chars) was truncating to "Residual Extraction Age…" under a
+// max of 24, well short of running out of box width.
+function isWideChar(ch) {
+ const code = ch.codePointAt(0);
+ return (
+ (code >= 0x1100 && code <= 0x115f) || // Hangul Jamo
+ (code >= 0x2e80 && code <= 0xa4cf) || // CJK radicals..Yi (covers CJK Unified, Kana, Hangul-adjacent blocks)
+ (code >= 0xac00 && code <= 0xd7a3) || // Hangul syllables
+ (code >= 0xf900 && code <= 0xfaff) || // CJK compatibility ideographs
+ (code >= 0xff00 && code <= 0xff60) || // Fullwidth forms
+ (code >= 0xffe0 && code <= 0xffe6)
+ );
+}
+
+function truncateLabel(text, max = 28) {
+ const normalized = String(text ?? "").replace(/\s+/g, " ").trim();
+ const chars = Array.from(normalized);
+ let visualLen = 0;
+ for (const ch of chars) visualLen += isWideChar(ch) ? 1 : 0.5;
+ if (visualLen <= max) return normalized;
+
+ let acc = 0;
+ let cut = chars.length;
+ for (let i = 0; i < chars.length; i++) {
+ acc += isWideChar(chars[i]) ? 1 : 0.5;
+ if (acc > max - 0.5) { cut = i; break; }
+ }
+ return `${chars.slice(0, Math.max(1, cut)).join("")}…`;
+}
+
+function collectIds(spec) {
+ const ids = new Set();
+ const add = (id, pathName) => {
+ if (ids.has(id)) throw new Error(`Duplicate id '${id}' at ${pathName}.`);
+ ids.add(id);
+ };
+ for (const band of spec.bands) {
+ add(band.id, `band:${band.id}`);
+ for (const node of band.nodes) add(node.id, `node:${node.id}`);
+ for (const group of band.groups) {
+ add(group.id, `group:${group.id}`);
+ for (const item of group.items) add(item.id, `item:${item.id}`);
+ }
+ }
+ return ids;
+}
+
+
+// 语义损失弱信号:一个 label 疑似把多个平级条目合并/省略了。引擎不会自己删条目,
+// 也不会缩字换空间(4+ 项 itemGridShape 自动多列、不压扁)——所以 label 里出现「等/…」
+// 省略、或「型号A/型号B」斜杠合并,几乎都是 authoring 时手工减条目造成的语义损失。
+// 返回原因串或 null。
+function mergeSuspect(label) {
+ const s = String(label).trim();
+ // 纯省略号("……"/"…")是"还有更多同类"的续行暗示,不算语义损失;只有"具体名字 + 等/…"
+ // (如"Llama-3-70B等")才是把某个条目名省略掉了。
+ const stripped = s.replace(/(等|…|\.{2,}|、)+$/, "").trim();
+ if (stripped.length > 0 && stripped.length < s.length) return "以「等/…」省略了条目";
+ const parts = s.split("/");
+ if (parts.length >= 2 && /[A-Za-z0-9]/.test(parts[0]) && /[A-Za-z0-9]/.test(parts[parts.length - 1])) {
+ return "用「/」把多个条目合并进一个 label";
+ }
+ return null;
+}
+
+function normalizeSpec(rawSpec) {
+ const spec = structuredClone(rawSpec);
+ // orientation "left_to_right" 已移除。它是本 skill 里唯一不测量内容就渲染的路径:
+ // computeBandRects 给每个 band 无条件分配整个区域高度,节点高度又被封顶在
+ // 0.50*scale 并垂直居中——单行节点最多填 0.41" 于约 3.2" 的 content 高度,87% 的
+ // 空白是结构性保证的,且页面级 UNDERFILL 检测器按图形覆盖判定,看不见空心 band。
+ // top_to_bottom 会测量并在装不下时报 OVER-CAPACITY,于是严格的路径把作者推向宽松
+ // 的这条。fail loud 而非静默转向:见 commit c7bc7b70(cols() 静默忽略参数)。
+ if (spec.orientation === "left_to_right") {
+ throw new Error(
+ `[CALL-ERROR in YOUR slides.js — NOT a library bug] addSystemDiagram: ` +
+ `orientation "left_to_right" 已移除——它不测量内容,band 无条件撑满区域高度,` +
+ `稀疏内容必然产生大片空白且无任何警告。系统图一律纵向排(缺省即 top_to_bottom,` +
+ `删掉这个字段即可);真正线性的 3-5 步横向流程请改用 addPipelineDiagram。`
+ );
+ }
+ // The suitability (assessment / render_decision) gate was intentionally removed:
+ // every diagram-worthy page should render. Structural validation below stays —
+ // it prevents a corrupt IR from producing a broken PPTX (duplicate ids, dangling
+ // edges, empty groups, out-of-range counts).
+ assertString(spec.title, "title", true);
+ assertString(spec.subtitle, "subtitle", true);
+ assertString(spec.core_message, "core_message", true);
+
+ if (!Array.isArray(spec.bands)) throw new Error("bands must be an array.");
+ if (!Array.isArray(spec.edges)) throw new Error("edges must be an array.");
+
+ if (spec.bands.length < 2 || spec.bands.length > 8) {
+ throw new Error("Renderable specs must contain 2–8 bands.");
+ }
+
+ let leafCount = 0;
+ const mergeSuspects = [];
+ for (const [bandIndex, band] of spec.bands.entries()) {
+ assertString(band.id, `bands[${bandIndex}].id`);
+ assertString(band.label, `bands[${bandIndex}].label`);
+ band.label = truncateLabel(band.label, 32);
+ if (!Array.isArray(band.nodes) || !Array.isArray(band.groups)) {
+ throw new Error(`Band '${band.id}' must have nodes and groups arrays.`);
+ }
+ if (band.layout === "full_width" && (band.nodes.length > 0 || band.groups.length > 0)) {
+ band.layout = band.groups.length > 0 ? "grid" : "row";
+ }
+ for (const node of band.nodes) {
+ assertString(node.id, `${band.id}.node.id`);
+ assertString(node.label, `${node.id}.label`);
+ node.label = truncateLabel(node.label, 24);
+ { const r = mergeSuspect(node.label); if (r) mergeSuspects.push(`「${node.label}」(${r})`); }
+ leafCount += 1;
+ }
+ for (const group of band.groups) {
+ assertString(group.id, `${band.id}.group.id`);
+ assertString(group.title, `${group.id}.title`);
+ group.title = truncateLabel(group.title, 20);
+ if (!Array.isArray(group.items) || group.items.length === 0) {
+ throw new Error(`Group '${group.id}' must contain at least one item.`);
+ }
+ for (const item of group.items) {
+ assertString(item.id, `${group.id}.item.id`);
+ assertString(item.label, `${item.id}.label`);
+ item.label = truncateLabel(item.label, 24);
+ { const r = mergeSuspect(item.label); if (r) mergeSuspects.push(`「${item.label}」(${r})`); }
+ leafCount += 1;
+ }
+ }
+ }
+ if (leafCount > 36) throw new Error(`The diagram has ${leafCount} leaf nodes; limit is 36 for one slide.`);
+ if (mergeSuspects.length > 0) {
+ console.warn(
+ `[SEMANTIC-LOSS NOTICE — addSystemDiagram succeeded] ${mergeSuspects.length} 个 label 疑似合并/省略了平级条目:` +
+ `${mergeSuspects.join(";")}。平级 N 项应写成一个 group 的 N 个完整 items——4+ 项引擎会自动多列排布` +
+ `(不压扁、不需你合并)。在 YOUR slides.js 里把它们拆成独立 items、恢复完整名称,不要用「等」「A/B」减条目(语义损失)。` +
+ `放不下时靠扩大区域/换骨架/拆页,不靠合并。不要改 system-diagram.js。`
+ );
+ }
+
+ const ids = collectIds(spec);
+ for (const edge of spec.edges) {
+ if (!ids.has(edge.from)) throw new Error(`Edge source '${edge.from}' does not exist.`);
+ if (!ids.has(edge.to)) throw new Error(`Edge target '${edge.to}' does not exist.`);
+ edge.label = truncateLabel(edge.label, 18);
+ }
+
+ if (spec.edges.length === 0 && ["process", "closed_loop", "layered"].includes(spec.diagram_type)) {
+ for (let i = 0; i < spec.bands.length - 1; i += 1) {
+ spec.edges.push({
+ from: spec.bands[i].id,
+ to: spec.bands[i + 1].id,
+ relation: "flow",
+ direction: "forward",
+ label: "",
+ line_style: "solid",
+ emphasis: "normal",
+ routing: "direct",
+ multiplicity: "single",
+ });
+ }
+ }
+
+ return spec;
+}
+
+function styleForVisualRole(role, isContainer = false) {
+ switch (role) {
+ case "primary":
+ return { fill: COLORS.green, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ case "secondary":
+ return { fill: COLORS.green2, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ case "factor_group":
+ return { fill: COLORS.yellow, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ case "warning":
+ return { fill: COLORS.white, transparency: isContainer ? 100 : 0, line: COLORS.warning, dash: "dash", text: COLORS.text };
+ case "action":
+ return { fill: COLORS.orange, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ case "result":
+ return { fill: COLORS.blue, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ case "comparison_a":
+ return { fill: COLORS.green, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ case "comparison_b":
+ return { fill: COLORS.comparisonB, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ case "neutral":
+ default:
+ return { fill: COLORS.white, line: COLORS.gray, dash: "solid", text: COLORS.text };
+ }
+}
+
+function addText(slide, text, rect, options = {}) {
+ slide.addText(text, {
+ x: rect.x,
+ y: rect.y,
+ w: rect.w,
+ h: rect.h,
+ fontFace: FONT,
+ bold: options.bold ?? false,
+ color: options.color ?? COLORS.text,
+ align: options.align ?? "center",
+ valign: options.valign ?? "mid",
+ margin: options.margin ?? 0.03,
+ fit: "shrink",
+ breakLine: false,
+ ...options,
+ // Clamp last so no caller/spread pushes the nominal size below readability.
+ fontSize: clampFont(options.fontSize ?? 12),
+ });
+}
+
+function addRect(slide, rect, options = {}) {
+ slide.addShape(SHAPE_TYPE.rect, {
+ x: rect.x,
+ y: rect.y,
+ w: rect.w,
+ h: rect.h,
+ fill: options.fill ?? { color: COLORS.white },
+ line: options.line ?? { color: COLORS.gray, width: 0.8 },
+ shadow: options.shadow,
+ });
+}
+
+function addLine(slide, x1, y1, x2, y2, options = {}) {
+ slide.addShape(SHAPE_TYPE.line, {
+ x: x1,
+ y: y1,
+ w: x2 - x1,
+ h: y2 - y1,
+ line: {
+ color: options.color ?? COLORS.lightGray,
+ width: options.width ?? 1,
+ dashType: options.dashType ?? "solid",
+ beginArrowType: options.beginArrowType ?? "none",
+ endArrowType: options.endArrowType ?? "none",
+ },
+ });
+}
+
+function gridShape(count, preferredCols = 4) {
+ if (count <= 0) return { cols: 1, rows: 1 };
+ const cols = Math.min(preferredCols, count);
+ return { cols, rows: Math.ceil(count / cols) };
+}
+
+// A group's items used to always stack in a single column, no matter how many
+// there were — a group with 6 items (e.g. 6 model names under one "proposer"
+// factor_group) needed 6x a single item's height, when 2 columns of 3 would
+// need half that. Groups themselves already reflow via gridShape when a band
+// has several of them; this gives items-within-one-group the same treatment.
+// 1-3 items: single column (splitting 2-3 short items rarely saves useful
+// height and just adds a second alignment axis). 4+: 2 columns.
+function itemGridShape(count) {
+ return gridShape(count, count >= 4 ? 2 : 1);
+}
+
+function estimateBandHeight(band) {
+ if (band.groups.length > 0) {
+ const { rows } = gridShape(band.groups.length, band.groups.length <= 4 ? 4 : 3);
+ const maxItems = Math.max(...band.groups.map((g) => g.items.length));
+ const oneGroupH = 0.44 + maxItems * 0.44 + Math.max(0, maxItems - 1) * 0.08 + 0.20;
+ return 0.46 + rows * oneGroupH + Math.max(0, rows - 1) * 0.16 + 0.18;
+ }
+ if (band.nodes.length > 0) {
+ const cols = band.layout === "column" ? 1 : Math.min(5, band.nodes.length);
+ const rows = Math.ceil(band.nodes.length / cols);
+ return 0.42 + rows * 0.50 + Math.max(0, rows - 1) * 0.10 + 0.15;
+ }
+ return 0.48;
+}
+
+// Bottom-up measurement of the height a band truly cannot go below without
+// crushing its own content past the ITEM_H_FLOOR/NODE_H_FLOOR/title floors
+// that computeBandLayout enforces at render time. Mirrors computeBandLayout's
+// arithmetic exactly (same title/pad/gap constants, same itemGridShape choice
+// for item columns) so measure and render can never disagree — see
+// computeBandRects for why that agreement matters.
+function measureBandMinHeight(band, scale) {
+ if (band.groups.length === 0 && band.nodes.length === 0) {
+ return SIMPLE_BAR_MIN_H;
+ }
+
+ const titleH = Math.max(0.27, 0.38 * scale);
+ const titleGap = 0.08 * scale;
+ const bottomPad = 0.12 * scale;
+ let contentMinH = 0;
+
+ if (band.groups.length > 0) {
+ const preferredCols = band.groups.length <= 4 ? 4 : 3;
+ const { rows } = gridShape(band.groups.length, preferredCols);
+ const gy = 0.14 * scale;
+ const groupTitleH = Math.max(0.25, 0.34 * scale);
+ const itemGap = Math.max(0.05, 0.08 * scale);
+ // All group cells in a band share one uniform row height (computeBandLayout
+ // divides content.h evenly across rows), so the binding constraint is the
+ // single neediest group, not a per-row max.
+ let maxGroupMinH = 0;
+ for (const group of band.groups) {
+ const { rows: itemRows } = itemGridShape(group.items.length);
+ const itemsMinH = itemRows * ITEM_H_FLOOR + Math.max(0, itemRows - 1) * itemGap;
+ maxGroupMinH = Math.max(maxGroupMinH, groupTitleH + 0.05 * scale + 0.11 * scale + itemsMinH);
+ }
+ contentMinH = rows * maxGroupMinH + Math.max(0, rows - 1) * gy;
+ }
+
+ if (band.nodes.length > 0) {
+ let cols;
+ if (band.layout === "column") cols = 1;
+ else if (band.layout === "row") cols = band.nodes.length;
+ else cols = Math.min(5, band.nodes.length);
+ cols = Math.max(1, cols);
+ const rows = Math.ceil(band.nodes.length / cols);
+ const ny = 0.10 * scale;
+ contentMinH = Math.max(contentMinH, rows * NODE_H_FLOOR + Math.max(0, rows - 1) * ny);
+ }
+
+ return titleH + titleGap + bottomPad + contentMinH;
+}
+
+function computeBandRects(spec, bounds) {
+ const gap = 0.24;
+ const natural = spec.bands.map(estimateBandHeight);
+ const totalNaturalBands = natural.reduce((a, b) => a + b, 0);
+ const gapCount = natural.length - 1;
+ const totalNatural = totalNaturalBands + gap * gapCount;
+ // fillScale stretches (or shrinks) the bands to fill the region vertically — a
+ // sparse diagram (few full-width bands) should occupy the whole region, not pack
+ // at the top. The font/padding scale stays bounded so labels don't balloon.
+ const fillScale = bounds.h / totalNatural;
+ const scale = Math.max(0.6, Math.min(1.2, fillScale));
+ // Gaps carry inter-band edge labels (a ~0.28"-tall pill). A dense diagram
+ // (many bands, or a band with a big group grid) can push fillScale well
+ // below 1, shrinking scaledGap until the label pill no longer fits and
+ // collides with the neighboring band's border. Keep a legibility floor on
+ // the gap and let band heights (not gaps) absorb the rest of the squeeze.
+ const gapFloor = Math.min(gap, 0.34);
+ const scaledGap = Math.max(gap * fillScale, gapFloor);
+
+ // measure -> allocate -> render. The old code went straight from `natural`
+ // (a rough weight, not a hard requirement) to each band's rect height via
+ // bandFillScale, with no floor — so a dense diagram (many bands, or a band
+ // with a big group grid) could compress a band's rect below what its own
+ // content floors (ITEM_H_FLOOR/NODE_H_FLOOR/titleH, all enforced in
+ // computeBandLayout/measureBandMinHeight) need. The rect would shrink but
+ // the content inside it wouldn't, so content spilled into the next band —
+ // bands visually overlapping. Measure the true per-band minimum first; if
+ // it fits, distribute only the leftover slack by content weight (same
+ // `natural` weighting as before). If it doesn't fit, refuse to render a
+ // diagram that can only be legible or overlap-free but not both — throw
+ // with an actionable breakdown instead of silently producing either.
+ const bandMinHs = spec.bands.map((band) => measureBandMinHeight(band, scale));
+ const totalMinH = bandMinHs.reduce((a, b) => a + b, 0) + gapFloor * gapCount;
+ if (totalMinH > bounds.h + 0.01) {
+ const breakdown = spec.bands
+ .map((band, i) => ({ id: band.id, label: band.label, minH: bandMinHs[i] }))
+ .sort((a, b) => b.minH - a.minH)
+ .slice(0, 3)
+ .map((b) => ` - ${b.id} (${b.label}): ${b.minH.toFixed(2)}"`)
+ .join("\n");
+ throw new Error(
+ `[DIAGRAM-OVER-CAPACITY] 引擎已自动做完前两级降级——①平级 items 二维网格重排(4+ 项自动多列、` +
+ `不压扁)②按内容量分配各 band 高度(不平均分)——但内容仍需至少 ${totalMinH.toFixed(2)}" 高,` +
+ `本区只有 ${bounds.h.toFixed(2)}"(超 ${(totalMinH - bounds.h).toFixed(2)}")。最占高的 band:\n${breakdown}\n` +
+ `请在 YOUR slides.js 里按顺序调整——**绝不缩字,更不要合并/删除条目或用"等"省略(那是语义损失,禁止)**:\n` +
+ ` ③ 扩大本视觉区的 h(若右侧文字栏更短,还可加宽 w:越宽每行放的列越多、行数越少越矮);\n` +
+ ` ④ 换一个更省高度的整页骨架(上下双图拆开分列、或复杂结构改单图整页 w:9);\n` +
+ ` ⑤ 以上都不够,才拆成两页、每页承载部分 band。\n` +
+ `不要改 system-diagram.js 绕过本检查——它保证文字不会被压到不可读、band 不会重叠。`
+ );
+ }
+
+ const bandBudget = bounds.h - scaledGap * gapCount;
+ const totalMinBands = bandMinHs.reduce((a, b) => a + b, 0);
+ const slack = Math.max(0, bandBudget - totalMinBands);
+ let y = bounds.y;
+ return spec.bands.map((band, i) => {
+ const h = bandMinHs[i] + slack * (natural[i] / totalNaturalBands);
+ const result = { band, rect: { x: bounds.x, y, w: bounds.w, h }, scale };
+ y += h + scaledGap;
+ return result;
+ });
+}
+
+function computeBandLayout(entry) {
+ const { band, rect, scale } = entry;
+ const titleH = Math.max(0.27, 0.38 * scale);
+ const pad = Math.max(0.10, 0.16 * scale);
+ const childLayouts = [];
+ const anchors = new Map([[band.id, rect]]);
+
+ if (band.groups.length === 0 && band.nodes.length === 0) {
+ return { ...entry, titleRect: rect, childLayouts, anchors, simpleBar: true };
+ }
+
+ const titleRect = { x: rect.x + pad, y: rect.y + 0.02, w: rect.w - 2 * pad, h: titleH };
+ const content = {
+ x: rect.x + pad,
+ y: rect.y + titleH + 0.08 * scale,
+ w: rect.w - 2 * pad,
+ h: rect.h - titleH - 0.12 * scale,
+ };
+
+ if (band.groups.length > 0) {
+ const preferredCols = band.groups.length <= 4 ? 4 : 3;
+ const { cols, rows } = gridShape(band.groups.length, preferredCols);
+ const gx = 0.15 * scale;
+ const gy = 0.14 * scale;
+ const groupW = (content.w - gx * (cols - 1)) / cols;
+ const groupH = (content.h - gy * (rows - 1)) / rows;
+
+ band.groups.forEach((group, index) => {
+ const row = Math.floor(index / cols);
+ const col = index % cols;
+ const groupRect = {
+ x: content.x + col * (groupW + gx),
+ y: content.y + row * (groupH + gy),
+ w: groupW,
+ h: groupH,
+ };
+ anchors.set(group.id, groupRect);
+
+ const groupTitleH = Math.max(0.25, 0.34 * scale);
+ const itemPad = Math.max(0.07, 0.12 * scale);
+ const itemGap = Math.max(0.05, 0.08 * scale);
+ const itemsAvailable = groupRect.h - groupTitleH - 0.11 * scale;
+ // Items used to always stack in a single column (itemGridShape reflows
+ // 4+ items into 2 columns — see its comment), which is what made a
+ // 6-item group need 6x a single item's height instead of 3x.
+ const itemShape = itemGridShape(group.items.length);
+ // Legibility floor (ITEM_H_FLOOR), same idiom as titleH/groupTitleH above:
+ // itemH used to be a bare Math.min (capped above, unbounded below), so a
+ // dense diagram could shrink it toward zero; addText hardcodes
+ // fit:"shrink", so a near-zero box crushed the item's fontSize far below
+ // its nominal value at render time. computeBandRects now measures this
+ // same floor before allocating band heights, so in practice the band
+ // arrives with enough room — this Math.max is the last-line guarantee
+ // that itemH itself never goes below what fontSize needs, independent of
+ // upstream allocation.
+ const itemH = Math.max(ITEM_H_FLOOR, Math.min(0.47 * scale, (itemsAvailable - itemGap * (itemShape.rows - 1)) / itemShape.rows));
+ const itemGx = 0.08 * scale;
+ const itemW = (groupRect.w - 2 * itemPad - itemGx * (itemShape.cols - 1)) / itemShape.cols;
+ // Center the item grid in the slot instead of pinning it to the top —
+ // sibling groups in the same row share groupRect.h (the row's tallest
+ // group sets it), so a sparser group would otherwise strand its grid at
+ // the top with dead space below.
+ const stackH = itemShape.rows * itemH + itemGap * (itemShape.rows - 1);
+ const itemsTop = groupRect.y + groupTitleH + 0.05 * scale + Math.max(0, (itemsAvailable - stackH) / 2);
+
+ const itemLayouts = group.items.map((item, itemIndex) => {
+ const row = Math.floor(itemIndex / itemShape.cols);
+ const col = itemIndex % itemShape.cols;
+ const itemRect = {
+ x: groupRect.x + itemPad + col * (itemW + itemGx),
+ y: itemsTop + row * (itemH + itemGap),
+ w: itemW,
+ h: itemH,
+ };
+ anchors.set(item.id, itemRect);
+ return { item, rect: itemRect };
+ });
+
+ childLayouts.push({ type: "group", group, rect: groupRect, itemLayouts, scale });
+ });
+ }
+
+ if (band.nodes.length > 0) {
+ let cols;
+ if (band.layout === "column") cols = 1;
+ else if (band.layout === "row") cols = band.nodes.length;
+ else cols = Math.min(5, band.nodes.length);
+ cols = Math.max(1, cols);
+ const rows = Math.ceil(band.nodes.length / cols);
+ const nx = 0.14 * scale;
+ const ny = 0.10 * scale;
+ const nodeW = (content.w - nx * (cols - 1)) / cols;
+ // Same legibility floor (NODE_H_FLOOR) as itemH above, and the same
+ // last-line-guarantee framing — computeBandRects measures this floor
+ // before allocating band heights, so it's expected to already have room.
+ const nodeH = Math.max(NODE_H_FLOOR, Math.min(0.50 * scale, (content.h - ny * (rows - 1)) / rows));
+ // Center the node grid vertically — a sparse band (few nodes, tall region)
+ // would otherwise strand its grid at the top with dead space below.
+ const gridH = rows * nodeH + ny * (rows - 1);
+ const gridTop = content.y + Math.max(0, (content.h - gridH) / 2);
+
+ band.nodes.forEach((node, index) => {
+ const row = Math.floor(index / cols);
+ const col = index % cols;
+ const nodeRect = {
+ x: content.x + col * (nodeW + nx),
+ y: gridTop + row * (nodeH + ny),
+ w: nodeW,
+ h: nodeH,
+ };
+ anchors.set(node.id, nodeRect);
+ childLayouts.push({ type: "node", node, rect: nodeRect, scale });
+ });
+ }
+
+ return { ...entry, titleRect, childLayouts, anchors, simpleBar: false };
+}
+
+function rectCenter(rect) {
+ return { x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 };
+}
+
+function edgeEndpoints(source, target) {
+ const sc = rectCenter(source);
+ const tc = rectCenter(target);
+ if (tc.y >= sc.y) return { x1: sc.x, y1: source.y + source.h, x2: tc.x, y2: target.y };
+ return { x1: sc.x, y1: source.y, x2: tc.x, y2: target.y + target.h };
+}
+
+function drawEdgeLabel(slide, label, x, y, emphasis, scale = 1) {
+ if (!label) return;
+ const w = Math.max(0.85, Math.min(2.2, label.length * 0.13 + 0.34));
+ const h = 0.28;
+ addRect(slide, { x: x - w / 2, y: y - h / 2, w, h }, {
+ fill: { color: COLORS.white },
+ line: { color: COLORS.white, transparency: 100 },
+ });
+ addText(slide, label, { x: x - w / 2, y: y - h / 2, w, h }, {
+ fontSize: 10.5 * scale,
+ color: emphasis === "warning" ? COLORS.warning : COLORS.text,
+ bold: emphasis === "warning",
+ });
+}
+
+// Loop-back edges (left_loop/right_loop) run their label along a rail that
+// hugs the page margin — typically ~0.5" wide, nowhere near enough for a
+// horizontal pill (a 10+ char label needs ~1.5-2.2"). A horizontal label
+// there either gets clipped by the page edge or (once clamped on-slide)
+// lands underneath the diagram's own band rects, which are drawn after
+// edges and paint over it. Setting the label vertical along the rail is the
+// standard fix for tight-margin loop-back labels.
+function drawLoopEdgeLabel(slide, label, railX, railY1, railY2, emphasis, scale = 1) {
+ if (!label) return;
+ const margin = 0.04;
+ const railLen = Math.abs(railY2 - railY1);
+ const h = Math.max(0.6, Math.min(railLen * 0.85, label.length * 0.13 + 0.34));
+ const w = 0.30;
+ const cy = (railY1 + railY2) / 2;
+ const rx = Math.max(margin, Math.min(railX - w / 2, PAGE_W - w - margin));
+ const ry = Math.max(margin, Math.min(cy - h / 2, PAGE_H - h - margin));
+ addRect(slide, { x: rx, y: ry, w, h }, {
+ fill: { color: COLORS.white },
+ line: { color: COLORS.white, transparency: 100 },
+ });
+ addText(slide, label, { x: rx, y: ry, w, h }, {
+ fontSize: 9 * scale,
+ color: emphasis === "warning" ? COLORS.warning : COLORS.text,
+ bold: emphasis === "warning",
+ textDirection: "vert270",
+ });
+}
+
+function drawEdge(slide, edge, anchors, spec, bounds) {
+ const source = anchors.get(edge.from);
+ const target = anchors.get(edge.to);
+ if (!source || !target) return;
+
+ // "normal" edges now use darkGray, not lightGray — lightGray reads as nearly
+ // invisible at 1pt against a white slide, which made every un-emphasized
+ // connector (the majority of edges) disappear on render.
+ const color = edge.emphasis === "warning" ? COLORS.warning : COLORS.darkGray;
+ const width = edge.emphasis === "strong" || edge.emphasis === "warning" ? 1.35 : 1.1;
+ const dashType = edge.line_style === "dashed" ? "dash" : "solid";
+ const beginArrowType = edge.direction === "bidirectional" ? "triangle" : "none";
+ const endArrowType = edge.direction === "none" ? "none" : "triangle";
+
+ if (edge.routing === "right_loop" || edge.routing === "left_loop") {
+ const right = edge.routing === "right_loop";
+ const margin = 0.15;
+ // Clamp the loop's outer rail to stay on-slide — an unclamped loopX can
+ // push past x=0 (or past the page's right edge) when bounds.x is small,
+ // physically cutting off the edge label's text against the slide boundary.
+ const loopX = right
+ ? Math.min(bounds.x + bounds.w + 0.28, PAGE_W - margin)
+ : Math.max(bounds.x - 0.28, margin);
+ const sx = right ? source.x + source.w : source.x;
+ const tx = right ? target.x + target.w : target.x;
+ const sy = source.y + source.h / 2;
+ const ty = target.y + target.h / 2;
+ addLine(slide, sx, sy, loopX, sy, { color, width, dashType });
+ addLine(slide, loopX, sy, loopX, ty, { color, width, dashType });
+ addLine(slide, loopX, ty, tx, ty, { color, width, dashType, endArrowType });
+ drawLoopEdgeLabel(slide, edge.label, loopX, sy, ty, edge.emphasis, 0.9);
+ return;
+ }
+
+ const endpoints = edgeEndpoints(source, target);
+
+ if (edge.direction === "bidirectional" && edge.multiplicity === "repeated") {
+ const count = 8;
+ // 纵向是唯一排布方式,不再判 orientation:以前写 `spec.orientation === "top_to_bottom"`,
+ // 而缺省时该字段是 undefined,多箭头分支实际上从来没走进来过。
+ if (Math.abs(source.w - target.w) < 0.6) {
+ for (let i = 0; i < count; i += 1) {
+ const x = source.x + 0.72 + i * ((source.w - 1.44) / (count - 1));
+ const down = i % 2 === 1;
+ const yTop = source.y + source.h + 0.02;
+ const yBottom = target.y - 0.02;
+ if (down) addLine(slide, x, yTop, x, yBottom, { color, width, dashType, endArrowType: "triangle" });
+ else addLine(slide, x, yBottom, x, yTop, { color, width, dashType, endArrowType: "triangle" });
+ }
+ } else {
+ addLine(slide, endpoints.x1, endpoints.y1, endpoints.x2, endpoints.y2, {
+ color, width, dashType, beginArrowType, endArrowType,
+ });
+ }
+ drawEdgeLabel(slide, edge.label, (endpoints.x1 + endpoints.x2) / 2, (endpoints.y1 + endpoints.y2) / 2, edge.emphasis);
+ return;
+ }
+
+ if (edge.routing === "orthogonal") {
+ const midY = (endpoints.y1 + endpoints.y2) / 2;
+ addLine(slide, endpoints.x1, endpoints.y1, endpoints.x1, midY, { color, width, dashType, beginArrowType });
+ addLine(slide, endpoints.x1, midY, endpoints.x2, midY, { color, width, dashType });
+ addLine(slide, endpoints.x2, midY, endpoints.x2, endpoints.y2, { color, width, dashType, endArrowType });
+ drawEdgeLabel(slide, edge.label, (endpoints.x1 + endpoints.x2) / 2, midY, edge.emphasis);
+ return;
+ }
+
+ addLine(slide, endpoints.x1, endpoints.y1, endpoints.x2, endpoints.y2, {
+ color, width, dashType, beginArrowType, endArrowType,
+ });
+ drawEdgeLabel(slide, edge.label, (endpoints.x1 + endpoints.x2) / 2, (endpoints.y1 + endpoints.y2) / 2, edge.emphasis);
+}
+
+function drawBand(slide, layout) {
+ const { band, rect, titleRect, childLayouts, simpleBar, scale } = layout;
+ const style = styleForVisualRole(band.visual_role, !simpleBar);
+
+ if (simpleBar) {
+ addRect(slide, rect, {
+ fill: { color: style.fill, transparency: style.transparency ?? 0 },
+ line: { color: style.line, width: band.visual_role === "warning" ? 1.5 : 0.8, dashType: style.dash },
+ });
+ addText(slide, band.label, rect, {
+ fontSize: 13.5 * Math.max(0.78, scale),
+ bold: band.visual_role === "warning",
+ });
+ return;
+ }
+
+ addRect(slide, rect, {
+ fill: { color: style.fill, transparency: style.transparency ?? (band.visual_role === "warning" ? 100 : 72) },
+ line: { color: style.line, width: band.visual_role === "warning" ? 1.5 : 0.8, dashType: style.dash },
+ });
+
+ // Band titles render straight onto the band's own fill — no separate
+ // opaque white backing plate. That backing used to draw as a hard-edged
+ // white rectangle sitting on top of the band's pale tint (bands default to
+ // 72% transparency, i.e. a faint wash), which reads as a visible sticker
+ // rather than a title bar. Bold text is legible directly on the tint (and
+ // on "warning" bands, which have no fill at all — text sits on the white
+ // canvas either way), so the backing was pure liability, no benefit.
+ const titleBacking = { x: rect.x, y: titleRect.y, w: rect.w, h: titleRect.h };
+ addText(slide, band.label, titleBacking, {
+ fontSize: 12.6 * Math.max(0.78, scale),
+ bold: true,
+ });
+
+ for (const child of childLayouts) {
+ if (child.type === "group") {
+ const groupStyle = styleForVisualRole(child.group.visual_role, true);
+ addRect(slide, child.rect, {
+ fill: { color: groupStyle.fill, transparency: groupStyle.transparency ?? 0 },
+ line: { color: groupStyle.line, width: 0.75, dashType: groupStyle.dash },
+ });
+ addText(slide, child.group.title, {
+ x: child.rect.x + 0.04,
+ y: child.rect.y + 0.02,
+ w: child.rect.w - 0.08,
+ h: Math.max(0.24, 0.32 * child.scale),
+ }, {
+ fontSize: 10.9 * Math.max(0.78, child.scale),
+ bold: false,
+ });
+
+ for (const itemLayout of child.itemLayouts) {
+ const itemStyle = styleForVisualRole(itemLayout.item.visual_role, false);
+ addRect(slide, itemLayout.rect, {
+ fill: { color: itemStyle.fill, transparency: itemStyle.transparency ?? 0 },
+ line: { color: itemStyle.line, width: 0.75, dashType: itemStyle.dash },
+ });
+ addText(slide, itemLayout.item.label, itemLayout.rect, {
+ fontSize: (itemLayout.item.label.length > 10 ? 9.2 : 10.2) * Math.max(0.78, child.scale),
+ margin: 0.02,
+ });
+ }
+ } else if (child.type === "node") {
+ const nodeStyle = styleForVisualRole(child.node.visual_role, false);
+ addRect(slide, child.rect, {
+ fill: { color: nodeStyle.fill, transparency: nodeStyle.transparency ?? 0 },
+ line: { color: nodeStyle.line, width: 0.8, dashType: nodeStyle.dash },
+ });
+ addText(slide, child.node.label, child.rect, {
+ fontSize: (child.node.label.length > 10 ? 9.5 : 10.8) * Math.max(0.78, child.scale),
+ });
+ }
+ }
+}
+
+function computeLayouts(spec, bounds) {
+ const bandEntries = computeBandRects(spec, bounds);
+ const layouts = bandEntries.map(computeBandLayout);
+ const anchors = new Map();
+ for (const layout of layouts) {
+ for (const [id, rect] of layout.anchors.entries()) anchors.set(id, rect);
+ }
+ return { layouts, anchors };
+}
+
+function rectsOverlap(a, b) {
+ const pad = 0.02;
+ return a.x < b.x + b.w - pad && a.x + a.w > b.x + pad &&
+ a.y < b.y + b.h - pad && a.y + a.h > b.y + pad;
+}
+
+// Draw a system diagram into a region of an existing slide, using native shapes.
+// No title / core_message chrome — the host content slide owns those. Returns a
+// layout descriptor { bounds, nodes, groups, edgeLabels, warnings } so QA and the
+// diagram-verifier can inspect geometry without re-parsing the PPTX.
+function renderSystemDiagram({ pres, slide, spec, bounds, theme = DEFAULT_THEME } = {}) {
+ if (!pres || !slide) throw new Error("renderSystemDiagram requires { pres, slide }.");
+ SHAPE_TYPE = pres.ShapeType;
+ COLORS = themeToColors(theme);
+ FONT_MIN = theme.fontMin ?? DEFAULT_THEME.fontMin;
+ FONT_MAX = theme.fontMax ?? DEFAULT_THEME.fontMax;
+ PAGE_W = theme.pageW ?? DEFAULT_THEME.pageW;
+ PAGE_H = theme.pageH ?? DEFAULT_THEME.pageH;
+
+ const normalized = normalizeSpec(spec);
+ const region = bounds || { x: 0.5, y: 1.05, w: 9.0, h: 3.6 };
+ const { layouts, anchors } = computeLayouts(normalized, region);
+
+ // Edges first so node boxes sit above connector lines; labels live in the
+ // inter-band gaps, not over nodes. Bands (containers + leaves) drawn last.
+ for (const edge of normalized.edges) drawEdge(slide, edge, anchors, normalized, region);
+ for (const layout of layouts) drawBand(slide, layout);
+
+ const nodes = [];
+ const groups = [];
+ for (const band of normalized.bands) {
+ for (const node of band.nodes) {
+ if (anchors.has(node.id)) nodes.push({ id: node.id, rect: anchors.get(node.id) });
+ }
+ for (const group of band.groups) {
+ if (anchors.has(group.id)) groups.push({ id: group.id, rect: anchors.get(group.id) });
+ for (const item of group.items) {
+ if (anchors.has(item.id)) nodes.push({ id: item.id, rect: anchors.get(item.id) });
+ }
+ }
+ }
+ const warnings = [];
+ for (let i = 0; i < nodes.length; i += 1) {
+ for (let j = i + 1; j < nodes.length; j += 1) {
+ if (rectsOverlap(nodes[i].rect, nodes[j].rect)) {
+ warnings.push(`nodes '${nodes[i].id}' & '${nodes[j].id}' overlap`);
+ }
+ }
+ }
+ return { bounds: region, nodes, groups, edgeLabels: [], warnings };
+}
+
+// ---- Diagram IR 构造器 ----------------------------------------------------
+// 裸 IR 要求每个 band/group/item 自带唯一 id,并重复 nodes:[] / groups:[] 样板。
+// 这是纯记账负担,且密度越高税越重——实测两份同题 deck:自建构造器的那份平均每图
+// 8.3 个条目、2 张带嵌套 groups;手搓裸 IR 的那份 6.7 个、零嵌套,稀疏到出废图。
+// 构造器把记账收进库里,让「写密集内容」变便宜。刻意不发射 `role`:渲染器不读它、
+// 文档不提它、normalizeSpec 不校验它。
+function item(id, label, visual_role = "neutral") {
+ return { id, label, visual_role };
+}
+
+// labels 收字符串数组(item id 自动派生为 `${id}_1`、`${id}_2`…)。数组元素也可
+// 直接传 item() 对象——只为给单项定制 visual_role,避免「需要一个 warning 单项就得
+// 放弃构造器、手写整个 group」的悬崖。
+function group(id, title, labels, visual_role = "factor_group") {
+ return {
+ id,
+ title,
+ visual_role,
+ items: labels.map((l, i) => (typeof l === "string" ? item(`${id}_${i + 1}`, l) : l)),
+ };
+}
+
+function bandNode(id, label, nodes, visual_role = "neutral", layout = "row") {
+ return { id, label, visual_role, layout, nodes, groups: [] };
+}
+
+function groupBand(id, label, groups, visual_role = "factor_group") {
+ return { id, label, visual_role, layout: "grid", nodes: [], groups };
+}
+
+module.exports = { renderSystemDiagram, normalizeSpec, DEFAULT_THEME, item, group, bandNode, groupBand };
+
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/validate-evidence-plan.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/validate-evidence-plan.js
new file mode 100644
index 0000000000..f72521a166
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/validate-evidence-plan.js
@@ -0,0 +1,133 @@
+#!/usr/bin/env node
+
+const fs = require("fs");
+const path = require("path");
+
+const FILE_ROUTES = new Set([
+ "user", "source-extracted", "paper-figure", "product-screenshot",
+ "code-screenshot", "official-logo", "web", "ai-illustration", "formula", "manual",
+]);
+const ROUTES = new Set([...FILE_ROUTES, "native-chart", "native-drawing"]);
+const KINDS = new Set([
+ "user-material", "paper-figure", "paper-table", "product-screenshot",
+ "code-screenshot", "official-logo", "data-chart", "web-image",
+ "ai-illustration", "formula", "native-diagram", "other",
+]);
+const STATUSES = new Set(["planned", "acquiring", "ready", "used", "needs-manual", "skipped"]);
+const REVIEW_STATUSES = new Set(["pending", "approved", "rejected", "not-required"]);
+const PLACEMENT_ROLES = new Set(["hero", "evidence", "support", "background", "inline"]);
+
+function nonEmpty(value) { return typeof value === "string" && value.trim().length > 0; }
+function isWithin(parent, child) {
+ const relative = path.relative(parent, child);
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
+}
+
+function validateEvidencePlan(planPath, { phase = "design", pageIds = null } = {}) {
+ const resolved = path.resolve(planPath);
+ const projectRoot = path.dirname(resolved);
+ const errors = [];
+ const warnings = [];
+ let plan;
+ try {
+ plan = JSON.parse(fs.readFileSync(resolved, "utf8"));
+ } catch (cause) {
+ return { plan: null, itemsById: new Map(), errors: [`Cannot parse evidence plan: ${cause.message}`], warnings };
+ }
+ if (plan.version !== 1) errors.push(`evidence plan version must be 1; got ${JSON.stringify(plan.version)}`);
+ if (!nonEmpty(plan.asset_root)) errors.push("asset_root must be a non-empty string");
+ if (!nonEmpty(plan.analysis_root)) errors.push("analysis_root must be a non-empty string");
+ if (!Array.isArray(plan.items)) errors.push("items must be an array");
+ const assetRoot = path.resolve(projectRoot, nonEmpty(plan.asset_root) ? plan.asset_root : "assets");
+ const analysisRoot = path.resolve(projectRoot, nonEmpty(plan.analysis_root) ? plan.analysis_root : "analysis");
+ if (path.isAbsolute(plan.asset_root || "") || !isWithin(projectRoot, assetRoot)) {
+ errors.push("asset_root must be a project-relative directory");
+ }
+ if (path.isAbsolute(plan.analysis_root || "") || !isWithin(projectRoot, analysisRoot)) {
+ errors.push("analysis_root must be a project-relative directory");
+ }
+ const items = Array.isArray(plan.items) ? plan.items : [];
+ const itemsById = new Map();
+
+ for (const item of items) {
+ const id = item && item.id;
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(id || "")) errors.push(`Invalid evidence id: ${JSON.stringify(id)}`);
+ if (itemsById.has(id)) errors.push(`Duplicate evidence id: ${id}`);
+ itemsById.set(id, item);
+ if (!/^P\d{2,3}$/.test(item.page || "")) errors.push(`${id}.page is invalid`);
+ if (pageIds && !pageIds.has(item.page)) errors.push(`${id}.page refers to unknown page ${item.page}`);
+ for (const field of ["claim", "purpose", "reference", "fallback"]) {
+ if (!nonEmpty(item[field])) errors.push(`${id}.${field} must be a non-empty string`);
+ }
+ if (!KINDS.has(item.kind)) errors.push(`${id}.kind is unsupported: ${JSON.stringify(item.kind)}`);
+ if (!ROUTES.has(item.acquire_via)) errors.push(`${id}.acquire_via is unsupported: ${JSON.stringify(item.acquire_via)}`);
+ if (typeof item.required !== "boolean") errors.push(`${id}.required must be boolean`);
+ if (!PLACEMENT_ROLES.has(item.placement_role)) errors.push(`${id}.placement_role is unsupported`);
+ if (!STATUSES.has(item.status)) errors.push(`${id}.status is unsupported: ${JSON.stringify(item.status)}`);
+ const reviewStatus = item.review && item.review.status;
+ if (!REVIEW_STATUSES.has(reviewStatus)) errors.push(`${id}.review.status is missing or unsupported`);
+
+ const native = ["native-chart", "native-drawing"].includes(item.acquire_via);
+ if (FILE_ROUTES.has(item.acquire_via)) {
+ if (!nonEmpty(item.path)) errors.push(`${id}.${item.acquire_via} requires a destination path`);
+ else if (!isWithin(assetRoot, path.resolve(projectRoot, item.path))) {
+ errors.push(`${id}.path must stay inside asset_root (${plan.asset_root})`);
+ }
+ }
+ if (native && reviewStatus !== "not-required") {
+ errors.push(`${id}.review.status must be not-required for ${item.acquire_via}`);
+ }
+ if (FILE_ROUTES.has(item.acquire_via) && ["ready", "used"].includes(item.status)) {
+ if (!nonEmpty(item.path)) errors.push(`${id} is ${item.status} but has no path`);
+ else if (!fs.existsSync(path.resolve(projectRoot, item.path))) errors.push(`${id} path does not exist: ${item.path}`);
+ if (reviewStatus !== "approved") errors.push(`${id} is ${item.status} but review.status is not approved`);
+ }
+ if (item.acquire_via === "native-chart" && ["ready", "used"].includes(item.status)) {
+ if (!nonEmpty(item.source_path)) errors.push(`${id} native-chart requires source_path`);
+ else if (!fs.existsSync(path.resolve(projectRoot, item.source_path))) errors.push(`${id} source_path does not exist: ${item.source_path}`);
+ }
+ if (["paper-figure", "web"].includes(item.acquire_via) && item.status === "used") {
+ if (!nonEmpty(item.source)) errors.push(`${id} used ${item.acquire_via} evidence requires source citation`);
+ if (!nonEmpty(item.license)) warnings.push(`${id} used ${item.acquire_via} evidence has no rights/license note`);
+ }
+ if (item.acquire_via === "ai-illustration" && item.placement_role === "evidence") {
+ errors.push(`${id} uses AI illustration as evidence; AI visuals may only be hero/support/background/inline`);
+ }
+ if (phase !== "design" && item.required && !["ready", "used"].includes(item.status)) {
+ errors.push(`${id} is required but not ready for ${phase}: ${item.status}`);
+ }
+ if (phase === "deliver" && item.required && item.status !== "used") {
+ errors.push(`${id} is required and must be used before delivery; got ${item.status}`);
+ }
+ }
+ return { plan, itemsById, errors, warnings };
+}
+
+function main() {
+ const args = process.argv.slice(2);
+ const phaseIndex = args.indexOf("--phase");
+ const phase = phaseIndex >= 0 ? args[phaseIndex + 1] : "design";
+ const planArg = args.find((arg, index) => arg !== "--phase" && index !== phaseIndex + 1);
+ if (!planArg || !["design", "generate", "deliver"].includes(phase)) {
+ console.error("Usage: node validate-evidence-plan.js <evidence-plan.json> [--phase design|generate|deliver]");
+ process.exit(2);
+ }
+ // Same workspace rule as validate-execution-lock.js: task files must not
+ // live inside the shared skill directory.
+ const skillRoot = path.resolve(__dirname, "..");
+ if (path.resolve(planArg).startsWith(skillRoot + path.sep)) {
+ console.error(
+ `[ERROR] task workspace is inside the skill directory (${skillRoot}). ` +
+ "Move the whole workspace outside skills/ppt-creation (e.g. <workspace>/projects/<task>/) and rerun."
+ );
+ process.exit(1);
+ }
+ const result = validateEvidencePlan(planArg, { phase });
+ for (const message of result.warnings) console.warn(`[WARN] ${message}`);
+ for (const message of result.errors) console.error(`[ERROR] ${message}`);
+ console.log(`evidence-plan: ${result.errors.length} error(s), ${result.warnings.length} warning(s), phase=${phase}`);
+ process.exit(result.errors.length ? 1 : 0);
+}
+
+if (require.main === module) main();
+module.exports = { validateEvidencePlan };
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/validate-execution-lock.js b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/validate-execution-lock.js
new file mode 100644
index 0000000000..43fff2450e
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/scripts/validate-execution-lock.js
@@ -0,0 +1,252 @@
+#!/usr/bin/env node
+
+// Dependency-free semantic validator for a deck execution-lock.json.
+// JSON Schema documents the shape; this script also checks brand constants,
+// page-level strategy, and asset readiness.
+
+const fs = require("fs");
+const path = require("path");
+const { validateEvidencePlan } = require("./validate-evidence-plan.js");
+
+const args = process.argv.slice(2);
+const phaseIndex = args.indexOf("--phase");
+const phase = phaseIndex >= 0 ? args[phaseIndex + 1] : "design";
+const lockArg = args.find((arg, index) => arg !== "--phase" && index !== phaseIndex + 1);
+
+if (!lockArg || !["design", "generate", "deliver"].includes(phase)) {
+ console.error("Usage: node validate-execution-lock.js <execution-lock.json> [--phase design|generate|deliver]");
+ process.exit(2);
+}
+
+const lockPath = path.resolve(lockArg);
+const projectRoot = path.dirname(lockPath);
+const skillRoot = path.resolve(__dirname, "..");
+
+// Task workspaces are forbidden inside the skill directory: the skill tree is
+// shared reference material for every run, and sync tooling only guarantees
+// its own mirrored content there.
+if (lockPath.startsWith(skillRoot + path.sep)) {
+ console.error(
+ `[ERROR] task workspace is inside the skill directory (${skillRoot}). ` +
+ "Move the whole workspace outside skills/ppt-creation (e.g. <workspace>/projects/<task>/) and rerun."
+ );
+ process.exit(1);
+}
+const errors = [];
+const warnings = [];
+
+function error(message) { errors.push(message); }
+function warn(message) { warnings.push(message); }
+function at(value, keys) {
+ return keys.reduce((current, key) => current && current[key], value);
+}
+function expect(actual, expected, label) {
+ if (actual !== expected) error(`${label} must be ${JSON.stringify(expected)}; got ${JSON.stringify(actual)}`);
+}
+function nonEmpty(value) { return typeof value === "string" && value.trim().length > 0; }
+
+let lock;
+try {
+ lock = JSON.parse(fs.readFileSync(lockPath, "utf8"));
+} catch (cause) {
+ console.error(`[ERROR] Cannot parse ${lockPath}: ${cause.message}`);
+ process.exit(1);
+}
+
+if (![1, 2].includes(lock.version)) error(`version must be 1 or 2; got ${JSON.stringify(lock.version)}`);
+expect(at(lock, ["template", "content_shell"]), "blank-content", "template.content_shell");
+if (!["template-master", "10x5.625-compatible"].includes(at(lock, ["template", "canvas_mode"]))) {
+ error("template.canvas_mode must be template-master or 10x5.625-compatible");
+}
+const templateSource = at(lock, ["template", "source"]);
+const templatePath = [
+ path.resolve(projectRoot, templateSource || ""),
+ path.resolve(skillRoot, templateSource || ""),
+].find((candidate) => templateSource && fs.existsSync(candidate));
+if (!templatePath) error(`template.source does not exist in the project or skill: ${JSON.stringify(templateSource)}`);
+if (at(lock, ["template", "canvas_mode"]) === "template-master") {
+ expect(at(lock, ["template", "authoring_canvas"]), "10x5.625-scaled", "template.authoring_canvas");
+ expect(at(lock, ["template", "merge_mode"]), "template-layout", "template.merge_mode");
+ expect(at(lock, ["template", "content_layout"]), "slideLayout7.xml", "template.content_layout");
+ expect(at(lock, ["template", "footer_mode"]), "master", "template.footer_mode");
+}
+
+// Kept in sync with base/execution-lock-reference.json and THEME in
+// scripts/components.js. Rethemeing the deck means changing all three.
+const brandConstants = [
+ [["brand", "colors", "primary"], "4472C4"],
+ [["brand", "colors", "secondary"], "8FAADC"],
+ [["brand", "colors", "text"], "1D1D1A"],
+ [["brand", "colors", "secondary_text"], "666666"],
+ [["brand", "colors", "background"], "FFFFFF"],
+ [["brand", "typography", "cjk"], "Microsoft YaHei"],
+ [["brand", "typography", "latin"], "Arial"],
+ [["brand", "footer", "required_on"], "standard-content"],
+ [["brand", "summary_banner", "required_on"], "standard-content"],
+ [["brand", "summary_banner", "fill"], "4472C4"],
+ [["brand", "summary_banner", "text_color"], "FFFFFF"],
+ [["brand", "summary_banner", "position"], "above-footer"],
+];
+for (const [keys, expected] of brandConstants) expect(at(lock, keys), expected, keys.join("."));
+
+const narrativeModes = new Set([
+ "executive-report", "technical-explainer", "research-review", "showcase", "briefing",
+]);
+if (!narrativeModes.has(at(lock, ["deck", "narrative_mode"]))) {
+ error("deck.narrative_mode is missing or unsupported");
+}
+const typography = at(lock, ["deck", "typography_policy"]) || {};
+if (!(typography.title_min_pt >= 20)) error("deck.typography_policy.title_min_pt must be at least 20");
+if (!(typography.body_min_pt >= 9)) error("deck.typography_policy.body_min_pt must be at least 9");
+if (!(typography.absolute_min_pt >= 7)) error("deck.typography_policy.absolute_min_pt must be at least 7");
+
+const referenceIndexPath = path.join(skillRoot, "references", "index.yaml");
+const knownReferenceIds = new Set();
+if (fs.existsSync(referenceIndexPath)) {
+ const indexText = fs.readFileSync(referenceIndexPath, "utf8");
+ for (const match of indexText.matchAll(/^\s*-\s+id:\s*([^\s#]+)/gm)) knownReferenceIds.add(match[1]);
+}
+
+// The bundled icon libraries were removed from this skill. Old locks may still
+// carry a deck.icons block; only library "none" (or no block at all) is valid.
+const iconConfig = at(lock, ["deck", "icons"]);
+if (iconConfig != null && iconConfig.library !== "none") {
+ error(
+ `deck.icons.library ${JSON.stringify(iconConfig.library)} is unsupported: ` +
+ "the bundled icon libraries were removed; omit deck.icons or set library to \"none\""
+ );
+}
+if (iconConfig != null && (iconConfig.inventory || []).length) {
+ error("deck.icons.inventory must be empty: the bundled icon libraries were removed");
+}
+
+const roles = new Set(["fixed-cover", "toc", "standard-content", "section", "fixed-closing"]);
+const rhythms = new Set(["anchor", "navigation", "dense"]);
+const strategies = new Set([
+ "template", "user-material", "paper", "web", "native-drawing", "component", "svg", "hybrid", "none",
+]);
+const componentPolicies = new Set(["optional", "preferred", "avoid"]);
+const pages = Array.isArray(lock.pages) ? lock.pages : [];
+if (!pages.length) error("pages must contain at least one page contract");
+const pageIds = new Set();
+
+for (const page of pages) {
+ const id = page && page.id;
+ if (!/^P\d{2,3}$/.test(id || "")) error(`Invalid page id: ${JSON.stringify(id)}`);
+ if (pageIds.has(id)) error(`Duplicate page id: ${id}`);
+ pageIds.add(id);
+ if (!roles.has(page.role)) error(`${id || "page"}.role is missing or unsupported`);
+ if (!rhythms.has(page.rhythm)) error(`${id || "page"}.rhythm is missing or unsupported`);
+ if (!nonEmpty(page.core_message)) error(`${id || "page"}.core_message must be a non-empty string`);
+ if (!componentPolicies.has(page.component_policy)) error(`${id || "page"}.component_policy is missing or unsupported`);
+ if (!Array.isArray(page.reference_ids)) error(`${id || "page"}.reference_ids must be an array`);
+ if (!nonEmpty(page.composition)) error(`${id || "page"}.composition must describe the intended visual hierarchy`);
+ const evidenceKind = at(page, ["evidence_visual", "kind"]);
+ const evidenceAssetIds = at(page, ["evidence_visual", "asset_ids"]);
+ const evidenceKinds = new Set([
+ "template", "user-material", "paper", "product-screenshot", "code-screenshot",
+ "official-diagram", "data-chart", "native-diagram", "none",
+ ]);
+ if (!evidenceKinds.has(evidenceKind)) error(`${id || "page"}.evidence_visual.kind is missing or unsupported`);
+ if (!Array.isArray(evidenceAssetIds)) error(`${id || "page"}.evidence_visual.asset_ids must be an array`);
+ for (const referenceId of page.reference_ids || []) {
+ if (!knownReferenceIds.has(referenceId)) error(`${id}.reference_ids contains unknown reference: ${referenceId}`);
+ }
+ const primary = at(page, ["visual_strategy", "primary"]);
+ const fallback = at(page, ["visual_strategy", "fallback"]);
+ if (!strategies.has(primary)) error(`${id || "page"}.visual_strategy.primary is missing or unsupported`);
+ if (!strategies.has(fallback) || fallback === "hybrid") error(`${id || "page"}.visual_strategy.fallback is missing or unsupported`);
+
+ if (page.role === "standard-content" && !nonEmpty(page.summary)) {
+ error(`${id}.summary is required for standard-content pages`);
+ }
+ if (page.role !== "standard-content" && page.summary != null && String(page.summary).trim()) {
+ warn(`${id}.summary is ignored because ${page.role} does not use the standard content chrome`);
+ }
+ if (["fixed-cover", "fixed-closing"].includes(page.role) && primary !== "template") {
+ error(`${id}.visual_strategy.primary must be template for ${page.role}`);
+ }
+ if (page.role === "standard-content" && primary === "template") {
+ error(`${id}.visual_strategy.primary cannot be template for a standard content page`);
+ }
+ if (page.role === "standard-content" && ["dense", "anchor"].includes(page.rhythm)) {
+ if (!(page.reference_ids || []).length && !nonEmpty(page.reference_waiver)) {
+ error(`${id} is a ${page.rhythm} content page and requires reference_ids or a specific reference_waiver`);
+ }
+ if (evidenceKind === "none") {
+ error(`${id} is a ${page.rhythm} content page and requires an evidence_visual strategy`);
+ }
+ }
+}
+
+let evidenceItemsById = null;
+if (lock.version === 2) {
+ if (!nonEmpty(lock.evidence_plan)) {
+ error("version 2 requires evidence_plan");
+ } else {
+ const evidencePath = path.resolve(projectRoot, lock.evidence_plan);
+ if (!fs.existsSync(evidencePath)) {
+ error(`evidence_plan does not exist: ${lock.evidence_plan}`);
+ } else {
+ const result = validateEvidencePlan(evidencePath, { phase, pageIds });
+ evidenceItemsById = result.itemsById;
+ for (const message of result.warnings) warn(`evidence-plan: ${message}`);
+ for (const message of result.errors) error(`evidence-plan: ${message}`);
+ }
+ }
+} else {
+ warn("execution-lock version 1 uses the legacy inline assets list; migrate to version 2 + evidence-plan.json");
+}
+
+if (lock.version === 1 && !Array.isArray(lock.assets)) error("assets must be an array");
+const assets = Array.isArray(lock.assets) ? lock.assets : [];
+const assetIds = new Set();
+for (const asset of assets) {
+ if (!nonEmpty(asset.id)) { error("Every asset requires a non-empty id"); continue; }
+ if (assetIds.has(asset.id)) error(`Duplicate asset id: ${asset.id}`);
+ assetIds.add(asset.id);
+ if (!pageIds.has(asset.page)) error(`Asset ${asset.id} refers to unknown page ${asset.page}`);
+ if (!["user", "paper", "web", "ai", "icon", "diagram", "screenshot", "code", "logo", "other"].includes(asset.kind)) {
+ error(`Asset ${asset.id} has unsupported kind ${JSON.stringify(asset.kind)}`);
+ }
+ if (!["planned", "acquiring", "ready", "used", "needs-manual", "skipped"].includes(asset.status)) {
+ error(`Asset ${asset.id} has unsupported status ${JSON.stringify(asset.status)}`);
+ }
+ if (!nonEmpty(asset.fallback)) error(`Asset ${asset.id} requires a fallback`);
+ if (["ready", "used"].includes(asset.status)) {
+ if (!nonEmpty(asset.path)) error(`Asset ${asset.id} is ${asset.status} but has no path`);
+ else if (!fs.existsSync(path.resolve(projectRoot, asset.path))) {
+ error(`Asset ${asset.id} path does not exist: ${asset.path}`);
+ }
+ }
+ if (["web", "paper"].includes(asset.kind) && asset.status === "used") {
+ if (!nonEmpty(asset.source)) error(`Used ${asset.kind} asset ${asset.id} requires source`);
+ if (!nonEmpty(asset.license)) warn(`Used ${asset.kind} asset ${asset.id} has no license/rights note`);
+ }
+ if (phase !== "design" && asset.required && ["planned", "acquiring", "needs-manual"].includes(asset.status)) {
+ error(`Required asset ${asset.id} is not ready for ${phase}: ${asset.status}`);
+ }
+ if (phase === "deliver" && asset.required && asset.status !== "used") {
+ error(`Required asset ${asset.id} must be used before delivery; got ${asset.status}`);
+ }
+}
+
+for (const page of pages) {
+ const referenced = at(page, ["evidence_visual", "asset_ids"]) || [];
+ for (const assetId of referenced) {
+ const known = evidenceItemsById ? evidenceItemsById.has(assetId) : assetIds.has(assetId);
+ if (!known) error(`${page.id}.evidence_visual refers to unknown evidence item ${assetId}`);
+ if (evidenceItemsById && evidenceItemsById.has(assetId) && evidenceItemsById.get(assetId).page !== page.id) {
+ error(`${page.id}.evidence_visual refers to ${assetId}, which belongs to ${evidenceItemsById.get(assetId).page}`);
+ }
+ }
+ const kind = at(page, ["evidence_visual", "kind"]);
+ if (["paper", "product-screenshot", "code-screenshot", "official-diagram", "data-chart", "user-material"].includes(kind) && !referenced.length) {
+ error(`${page.id}.evidence_visual.kind=${kind} requires at least one evidence asset_id`);
+ }
+}
+
+for (const message of warnings) console.warn(`[WARN] ${message}`);
+for (const message of errors) console.error(`[ERROR] ${message}`);
+console.log(`execution-lock: ${errors.length} error(s), ${warnings.length} warning(s), phase=${phase}`);
+process.exit(errors.length ? 1 : 0);
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/workflows/acquire-visuals.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/workflows/acquire-visuals.md
new file mode 100644
index 0000000000..7a3a82e0b5
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/workflows/acquire-visuals.md
@@ -0,0 +1,130 @@
+# 视觉来源路由
+
+视觉选择的目标是提高证据价值和表达效率,不是保证每页都有图片。
+
+## 可执行契约
+
+所有非临时视觉先写入项目 `evidence-plan.json`,再运行 `prepare_evidence.py`。`design-spec.md` 解释为什么需要,evidence plan 记录怎样获取和当前事实状态,execution lock 只保存逐页允许使用的 `asset_ids`。
+
+典型论文项:
+
+```json
+{
+ "id": "reasoningbank-architecture",
+ "page": "P08",
+ "claim": "ReasoningBank 通过共享记忆支持多 Agent 迁移",
+ "purpose": "用论文原始架构图证明记忆检索和协作关系",
+ "kind": "paper-figure",
+ "acquire_via": "paper-figure",
+ "required": true,
+ "placement_role": "evidence",
+ "status": "planned",
+ "path": "assets/papers/reasoningbank-architecture.png",
+ "source_path": null,
+ "source_url": "https://arxiv.org/pdf/xxxx.xxxxx",
+ "source": "Paper title, authors, Figure 2",
+ "license": "Paper figure quoted for analysis; retain citation",
+ "reference": "Figure 2 architecture, not a recreated approximation",
+ "query": null,
+ "crop_policy": "no-crop",
+ "paper_selector": {
+ "label": "Figure 2",
+ "caption_keywords": ["ReasoningBank", "memory"],
+ "include_caption": false,
+ "min_confidence": 0.55
+ },
+ "review": { "status": "pending", "notes": null },
+ "result": null,
+ "fallback": "Use the full PDF page with citation or draw a clearly labeled interpretation."
+}
+```
+
+准备脚本复用 `extract_arxiv_visuals_v2_2.py`,不会重新实现裁图。自动选择不唯一时保留 manifest 和 contact sheet,状态转为 `needs-manual`。
+
+```bash
+python3 ../scripts/prepare_evidence.py .
+# 查看 analysis/evidence-contact-sheet.jpg 或论文专属 contact sheet 后:
+python3 ../scripts/prepare_evidence.py . --approve reasoningbank-architecture
+# 素材真正加入幻灯片后:
+python3 ../scripts/prepare_evidence.py . --used reasoningbank-architecture
+```
+
+文件视觉只有经过 `review.approved` 才能标为 `ready/used`。原生图表和原生绘制不需要图像审核,但仍需在交付前标为 `used`。
+
+## 六种路径
+
+### user-material
+
+适用:用户材料已有照片、图表、截图、品牌视觉或产品界面。
+
+- 优先保持原文件和语义;
+- 检查分辨率、比例、裁切和使用范围;
+- 不因为已有组件更方便就替换真实材料。
+
+### paper
+
+适用:页面解释一篇具体论文的机制、架构或实验结果,原图能直接作为证据。
+
+- 可使用 `../scripts/extract_arxiv_visuals_v2_2.py` 提取;
+- 默认由 `prepare_evidence.py` 的 `paper-figure` 路由调用该脚本并解析 manifest;
+- 根据图注、尺寸和页面核心信息选择,不按置信度机械排序;
+- 先确认可读性,再决定使用 1–3 张或改为自绘;
+- 原图保持比例和内部视觉,外围使用本 deck 模板语言;
+- 在 `evidence-plan.json` 中记录论文来源;**不在幻灯片上画来源行**,除非用户明确要求。
+
+### web
+
+适用:真实人物、地点、产品、机构、新闻事件或企业场景。
+
+- 搜索具体实体或场景,不用泛化关键词接受错误图片;
+- 验证主体、时间、来源和许可;
+- 需要署名时在页面内提供简洁署名;
+- 无法验证则使用占位、用户 URL 或其他表达路径。
+
+### native-drawing
+
+适用:流程、机制、架构、因果、关系、分类、抽象框架,需要可编辑和语义清晰。
+
+- 可直接使用 PptxGenJS、原生图表/表格或自定义 SVG;
+- 图形结构从内容关系推导,不从组件外形反推内容;
+- 只有理解关系需要的节点和连线才画出来。
+
+### component
+
+适用:现有组件与页面信息结构高度吻合,且使用组件不会迫使内容删改或变形。
+
+- 先完成设计判断,再打开组件文档;
+- 可以组合、改造或只使用组件的一部分;
+- 组件不匹配时切换到 native-drawing,不修改内容迎合 API。
+
+### none
+
+适用:核心信息通过文字、数字或引语表达最清晰。
+
+- 允许没有图形组件;
+- 通过字号、位置、分隔和对齐建立层级;
+- 文字仍需填满内容区,不得靠空白撑版面;
+- 不添加装饰图标或无证据视觉充数。
+
+## 决策问题
+
+逐页回答:
+
+1. 页面是在证明事实、解释关系、展示实体还是强调结论?
+2. 真实原始视觉是否比重绘更有证据价值?
+3. 可编辑性是否重要?
+4. 外部素材是否可验证、可授权、可读?
+5. 某组件是否真正匹配内容关系?
+6. 不使用视觉是否反而更强?
+
+## 回退示例
+
+| 首选 | 失败原因 | 回退 |
+|---|---|---|
+| paper | 图太复杂或提取残缺 | 根据论文自绘并注明整理来源 |
+| web | 实体或许可无法验证 | 用户素材、占位或文字表达 |
+| component | API 迫使结构失真 | native-drawing |
+| native-drawing | 内容缺少可靠关系 | 文字、表格或补充调研 |
+| user-material | 清晰度不足 | 请求原图、重新绘制或标注限制 |
+
+所有失败和替代都记录到 `design-spec.md` 或素材清单,不静默编造。
diff --git a/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/workflows/create-deck.md b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/workflows/create-deck.md
new file mode 100644
index 0000000000..c482452c86
--- /dev/null
+++ b/jiuwenswarm/resources/agent/workspace/skills/ppt-creation/workflows/create-deck.md
@@ -0,0 +1,152 @@
+# 新建 Deck
+
+## 1. 建立任务工作区
+
+**工作区必须建在 skill 目录之外。** `skills/ppt-creation/` 内的任何位置都不允许创建任务文件——skill 目录是所有任务共享的参考材料,任务残留会污染后续生成,且同步工具只维护该目录内的 skill 自身内容。在 workspace 根目录下新建,如 `<workspace>/projects/<task-name>/`。design 阶段的两个校验脚本会直接拒绝位于 skill 目录内的工作区。
+
+建议结构:
+
+```text
+<project>/
+├── sources/ # 用户材料和调研材料
+├── analysis/ # 提取文本、数据和素材清单
+├── assets/ # 本 deck 使用的图片、论文图、图标
+├── design-spec.md
+├── evidence-plan.json
+├── evidence-plan.schema.json
+├── execution-lock.json
+├── execution-lock.schema.json
+├── slides.js
+├── output/
+└── qa/
+```
+
+任务下载物、生成图和输出 PPTX 一律留在工作区内,不进入 skill 目录的任何子目录。
+
+## 2. 内容分析
+
+- 提取用户材料的正文、数据、图表、图片和结构。
+- 区分来源事实、用户观点、Agent 推断和待验证内容。
+- 明确受众、场景、页数/时长、语言、保密级别和核心行动。
+- 用户已有结构时保留其顺序和标题,除非用户允许重组。
+
+## 3. Strategist 规划
+
+先建立整套叙事,再规划单页。避免把章节菜单机械转换成页面。
+
+每页至少明确:
+
+- 页面角色;
+- 标题;
+- 核心信息;
+- 固定红色总结条使用的一句话结论;
+- 真实内容块;
+- 页面节奏;
+- 视觉策略与回退;
+- 来源和候选参考。
+
+页面数量由内容和用户约束决定,目录页和分节页的取舍自由(这里说的「无硬性配额」指它们,不指结尾页)。但**模板封面和模板结尾页是标准收尾,默认都要有**:deck 首页是 `fixed-cover`、末页是 `fixed-closing`(模板 Thank You 页),两者都在设计阶段就写进页面计划,只有用户明确不要结尾页时才省略。每张内容页都应有明确叙事作用。
+
+## 4. 写设计产物
+
+### design-spec.md
+
+复制 `../base/design-spec-reference.md` 的完整结构——I 到 VII 全部章节、每页全部字段——逐字段填入实际内容。**不许自拟大纲、不许省略字段**;确实不适用的字段显式写 `none` 并给一句原因。缺章节或缺字段视为本阶段未完成。
+
+写完先对照 reference 自检一遍,不合格先回改,再进入后续 JSON 校验:
+
+1. I–VII 章节齐全,每页字段齐全;
+2. 每个标准内容页的 Composition 达到元素级(分区比例 + 每区元素清单 + 关键实文,见 reference 中该字段的合格样例);只有一句「左 X% 图右 Y% 文」的页面必须回改——这类页面在执行阶段最容易偏离声明的骨架。
+
+### evidence-plan.json
+
+复制 `../base/evidence-plan.json` 和 `../base/evidence-plan.schema.json`。每个证据项必须说明:页面、要支撑的 claim、purpose、kind、acquire_via、placement、目标路径、来源/权利、状态、审核结果和 fallback。
+
+论文项使用 `acquire_via: paper-figure`,并提供论文来源与 `paper_selector.label` / `caption_keywords`。产品、代码和官方 Logo 优先使用用户或官方本地文件;网络项必须先确认直接 URL 和权利信息;AI 只用于非事实性视觉。
+
+### execution-lock.json
+
+复制 `../base/execution-lock-reference.json` 为 `execution-lock.json`,同时复制 schema,并保持 `evidence_plan: "evidence-plan.json"`。页面通过 `evidence_visual.asset_ids` 引用 evidence plan,不再在 lock 内重复维护素材表。
+
+记录:
+
+- 模板来源与画布模式;
+- 不可改变的主题色、字体、页脚和总结条;
+- narrative mode 与 image treatment;
+- `research-editorial` 参考族、字号 floor 和最大连续 dense 页数;
+- 每页 role、core message、rhythm、visual strategy、component policy 和 reference IDs;
+- 每页 composition、evidence visual,以及必要时的 reference waiver;
+- 素材状态、来源、权利说明与 fallback。
+
+不锁单页坐标、区域比例或强制组件名。写完立即执行:
+
+```bash
+node ../scripts/validate-execution-lock.js execution-lock.json --phase design
+node ../scripts/validate-evidence-plan.js evidence-plan.json --phase design
+```
+
+## 5. 参考选择
+
+通读 `../references/index.yaml` 的全部 `name`,建立可选骨架的认识,再为每页选定一个骨架并记录其 `name`。随后打开该项 `image` 确认细节,参考 `skeleton` 与 `rules` 规划分区和比例。内容不吻合时先看 `variants`,仍不吻合就换骨架,或在 `composition` 里写出自己的分区——骨架是选型参考,不是强制模板。
+
+逐页选完后整体看一遍节奏:相邻内容页避免连用「同一骨架 + 同一右栏文本样式」(连续几页都是左视觉区 + 右侧编号列表就是典型信号),用 `variants`、错开文本样式或换骨架打破重复;论文图/实验证据页优先评估 `architecture-evidence`(外框内左文右图)。
+
+## 6. 素材准备
+
+按 `acquire-visuals.md` 获取用户素材、论文图、网络图或其他视觉。先执行:
+
+```bash
+python3 ../scripts/prepare_evidence.py .
+```
+
+论文路线会调用现有 Figure/Table 提取器并生成 `analysis/papers/<id>/contact_sheet.png`;通用素材总览为 `analysis/evidence-contact-sheet.jpg`。主 Agent 必须查看总览,再批准合格项:
+
+```bash
+python3 ../scripts/prepare_evidence.py . --approve <evidence-id>
+node ../scripts/validate-evidence-plan.js evidence-plan.json --phase generate
+```
+
+## 7. 生成
+
+1. 用 10×5.625 兼容坐标生成内容,模板目标锁定为 `official-master` / `slideLayout6.xml`;
+2. 生成封面;
+3. 选择一张代表性复杂内容页生成并渲染;
+4. 修复系统性问题;
+5. 同一主 Agent 顺序生成剩余页面;
+6. 每页动手前先打开该页 `Layout ref` 的参考图,对照 `skeleton` 与 `rules` 落实分区;
+7. 每页根据设计计划选择原生绘制、组件或图片;
+8. 每张标准内容页最后调用一次 `Brand.addContentChrome(pres, slide, { summary, pageNum, footerMode: "master" })`;
+9. 保持跨页字体角色、色彩和页脚一致。
+
+**封面和结尾页不在 `content.pptx` 里生成**——它们是官方模板页,由下一步 `finalize_deck.py` 的默认顺序 `t1,s*,t5` 自动挂上(t1 官方封面、t5 官方结尾页)。`content.pptx` 只含标准内容页。但 `execution-lock.json.pages` 仍必须登记 `fixed-cover` 和 `fixed-closing` 两个条目(visual_strategy 用 `template`),否则合并出的最终页数与 lock 计划不一致,交付校验会报页数不符。
+
+生成内容文件后,用一条命令合并进官方模板并打包:
+
+```bash
+python3 ../scripts/finalize_deck.py output/content.pptx output/final.pptx \
+ --cover-title "Mixture-of-Agents 多智能体模式洞察" \
+ --cover-meta "研发部|吴云凯|2026-07-22"
+```
+
+它封装了 unpack → merge_slides → fill_cover → clean → pack 全流程,默认顺序 `t1,s*,t5`(官方封面 + 全部内容页 + 官方结束页),等比放大内容并继承官方页脚、Logo 和版式,结束时自检并打印页数/母版/版式摘要。**正常流程不手工解包模板或内容、不阅读拆包 XML**;合并失败需要定位时才加 `--keep-workdir` 保留中间目录。需要目录页时用 `--order "t1,t2,s*,t5"` 这类写法调整。不得把 `--source-layout-mode source` 当作新建 deck 默认值。
+
+**`--cover-title` 不是可选项。** 模板封面的主标题占位符(`ctrTitle`)出厂就是空的,PowerPoint 对空占位符不显示任何提示文字,合并流程本身也不写它——漏传就会交付一张没有标题的封面,且肉眼看上去"完整"。设计阶段定下的封面主标题必须在这一步传进去,取值与 `design-spec` 的封面文案一致,样式按 `base/template-contract.md`(主题色、单行)。`finalize_deck.py` 结束时有 cover-title 硬门禁,为空直接判失败。`--cover-meta` 按 部门|作者|日期 顺序追加到模板已有标签后面,留空的段保持标签原样。合并后若还要改这些文字,走 `editing.md` 的解包-编辑-打包流程。
+
+不使用预制图标库(内置图标资源已从本 skill 移除)。需要识别锚点时用 `initial` 首字母徽标或自绘 SVG,且不得取代架构关系、证据或页面叙事。
+
+不得让不同执行者各自自由设计一批页面后直接拼接。研究或素材检索可以独立,最终页面构图由同一执行上下文统一完成。
+
+## 8. 代表页精修(hero pages)
+
+全 deck 构建通过、QA 硬错误清零后,对 design-spec 中标记 `Hero: yes` 的 1-2 页做一轮升格精修——这两页是整套 deck 被评价的门面,值得单页级投入。
+
+**精修要达成的就是版式库成品参考图的完成度。** 动手前必须打开 `references/complex-slide.png`(矩阵分组·漏斗汇聚·路径带,精修的标杆样例)和该 hero 页骨架对应的参考图实际看一遍——整页一张结构大图、淡彩只在分组头、白卡挂阴影、箭头表达汇聚与流转、无空白象限。每张参考图的分区骨架与绘制规则在 `references/index.yaml` 对应条目里,精修时逐条对照落实:
+
+1. 打开该页当前渲染图与上述参考图并排对比,列出差距(结构表达力、分组配色、流转关系、卡片质感);
+2. 精修不受"只用组件"限制:优先用 `addTintMatrix` / `addConvergeFunnel` / `addChevronStages` 等结构组件重构主区域;组件表达不了的关系,直接用原生 shapes 逐元素绘制(淡彩分组头、汇聚漏斗、chevron 带、带阴影白卡是参考 deck 的核心词汇);
+3. 精修后重新渲染该页并与参考图再对比一次,仍有明显差距再迭代一轮(精修每页至多两轮,不无限循环);
+4. 精修只动 hero 页,不回头重排其他页面;改动同步回 `design-spec.md` 的该页 Composition。
+
+## 9. QA 与交付
+
+按 `../base/quality-gates.md` 执行。页面真正使用素材后运行 `python3 ../scripts/prepare_evidence.py . --used <evidence-id>`。交付前运行 evidence plan、execution lock、`audit_pptx.py` 和缩略图总览检查,输出 PPTX、QA 说明、素材来源和回退清单。