AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
feat(visual-review): add per-page rubric-based visual self-review workflow (#121)
Napstablook9f620e783780
diff --git a/.gitignore b/.gitignoreindex bab91b96..ab68ea09 100644--- a/.gitignore+++ b/.gitignore@@ -89,6 +89,18 @@ tramptest_output/temp_files/+# Playwright (both MCP-side and visual-review script outputs)+# MCP server auto-creates .playwright-mcp/ at CWD for snapshot/console logs+.playwright-mcp/+# Visual-review renderer writes per-project preview PNGs and the render lock+projects/*/.preview/+projects/*/.review/+# Stray top-level screenshots created when MCP filename was a bare relative path+# (the agreed convention is to always pass an absolute /tmp/... path)+/probe-*.png+/screenshot-*.png+/page-*.png+# Large media files (if any)*.psd*.aidiff --git a/skills/ppt-master/references/visual-review.md b/skills/ppt-master/references/visual-review.mdnew file mode 100644index 00000000..8891ca98--- /dev/null+++ b/skills/ppt-master/references/visual-review.md@@ -0,0 +1,227 @@+# Visual Review Rubric++> Per-page visual self-check rubric for slide SVGs. Read by the subagents spawned during the `visual-review` workflow. Companion to the [`visual-review` workflow](../workflows/visual-review.md) and the [`visual_review.py`](../scripts/visual_review.py) renderer.++## §0 Prerequisites++This rubric **does not repeat** what `svg_quality_checker.py` already covers. Required upstream order:++```+Executor finishes page → svg_quality_checker.py passes → visual_review.py renders PNG → this rubric runs+```++If the static checker has not been run or has failed, the subagent must abort with status `prereq_failed` and not start the rubric. Topics already enforced by the static checker (do **not** re-check here):++- font-size ramp drift (`RAMP_MIN_RATIO=0.5` / `MAX=5.0`)+- id uniqueness, XML well-formed+- spec_lock drift (colors / fonts / canvas)+- animation_config compliance++## §0.1 Subagent inputs++Every per-page review subagent must receive:++1. **SVG path** — the assigned page under `<project>/svg_output/<page>.svg`+2. **PNG path** — pre-rendered 1280×720 screenshot at `<project>/.preview/<page>.png`+3. **`page_role`** — one of `cover` / `chapter` / `tldr` / `content` / `data` / `closing` / `breathing`. Parsed from `design_spec.md §IX` by the orchestrator. Subagents do **not** guess.+4. **Path to this rubric file**+5. **`<project>/design_spec.md`** (read-only) — §IX outline is the source of truth for "what should this page deliver"+6. **`<project>/spec_lock.md`** (read-only) — brand-locked values+7. **`<project>/.review/`** (writable) — where backups and findings JSON go++## §1 Hard rules (fix every hit)++| # | Category | Trigger | Permitted fix |+|---|----------|---------|---------------|+| H1 | Out-of-bounds | element bbox falls outside `0,0,1280,720` | shrink or reposition into canvas |+| H2 | Text overflow | text bbox extends past its visual container | reduce font-size or line-break |+| H3 | Text overlap | two `<text>` elements' bboxes intersect (tspans within one text excluded) | reposition or resize |+| H4 | Readability | contrast < 4.5 (small text) / < 3.0 (font-size ≥ 24px); OR text directly atop a complex image with no scrim | **(v2)** position-only escape: add a `<rect>` scrim under the text, or raise the offending text's font-size to ≥ 24px so the 3.0 threshold applies. Full color change is brand-locked → goto §1.1 escalation. |+| H6 | Element collision | rect/circle/path bboxes overlap with z-order violating semantics | open spacing |+| H7 | Anchored element displaced | page number / header / footer covered, missing, or out of canvas | restore to anchor position |+| H8 | Image rendering broken | `<image>` empty / broken-image / severe distortion | fix `href`, adjust `preserveAspectRatio`, add `no-crop` if face/data is cropped |+| H9 | Missing key element | element required by `design_spec §IX` outline is absent from rendered slide | recreate from spec |++*H5 (font-ramp drift) is covered by `svg_quality_checker.py` and intentionally omitted.*++Detection order (run sequentially, do not parallelize within a single subagent):++```+H1 → H2 → H7 (structure)+H3 → H6 (collisions)+H4 (readability)+H8 → H9 (content)+```++### §1.1 Brand-token contrast escalation *(new in v2)*++If H4 fires and the underlying color is a **brand token** (defined in `spec_lock.md`) — i.e., the violation will repeat on every page using that token — do **not** mark the page `needs_human`. Instead:++1. Apply the position-only escape if one is genuinely viable on this page (scrim or size escalation).+2. Append the finding to `<project>/.review/brand_review.json` (append-only log; one entry per distinct token+context pair).+3. In the page JSON, record the finding under `untouched_concerns` with `reason: "brand_token_aggregated"` so the page does **not** block on it.++The aggregated brand review is the responsibility of the orchestrator at the end of the run, not the per-page subagent.++## §2 Soft rules (act only when clearly bad)++Subagents must apply the **明显** ("clearly bad") threshold — when in doubt, leave it. Better to under-fix than to oscillate.++| # | Category | Trigger | Fix direction |+|---|----------|---------|---------------|+| S1 | Vertical rhythm tight | Within the **same logical text block**, consecutive baselines have gap < 1.05× larger font-size | open to 1.15–1.3× |+| S2 | Vertical rhythm hollow | Within one logical block, > 150 px non-decorative whitespace; `breathing` pages exempt | tighten |+| S3 | Visual centroid off | hero/title block centroid offset from canvas center exceeds threshold by `page_role`: `cover` > 35%, `chapter` > 25%, `tldr`/`closing`/`breathing` > 25%, `content`/`data` > 20% | shift toward intended anchor |+| S4 | Alignment drift | same-column elements differ in `x` by > 4 px (or same-row baselines by > 4 px) **and** are semantically meant to be on the same grid line | snap to grid |+| S5 | Grid non-uniform | N-card row: neighbor `x`-spacing differs by > 5% of the average | re-distribute |+| S6 | CJK letter-spacing | CJK characters with `letter-spacing / font-size > 5%` | reduce to ≤ 2% |+| S7 | Accent overload | > 2 accent colors across ≥ 3 distinct elements | collapse to 1 primary + 1 secondary |+| S8 | Emphasis mismatch | most visually prominent element ≠ the element `design_spec §IX` declares as the page's primary | rescale to match intent |+| S9 | Image-text relationship | caption > 60 px from its image; text on busy image without scrim; image clearly purposeless | tighten / add scrim / remove |+| S10 | Breathing violation | only when `page_role = breathing`: ≥3 rounded card grid | replace with naked text / single hero |++## §3 Don't-touch++Hard boundary, equal weight to §1.++- **Brand decisions** — color tokens, font families, geometry style (decided by `spec_lock.md` / brand directory)+- **Layout restructure** — do not change column counts, replace chart types, add/remove sections+- **Content** — do not add or remove copy; only adjust position, font-size (within ramp), spacing, letter-spacing, alignment, scrim+- **Other files** — never edit `design_spec.md` / `spec_lock.md` / `animations.json` / `image_prompts.json` / `images/` / other pages' SVGs+- **Atomicity** — one edit per fix, no bulk multi-element replacements++If a "violation" requires reinterpreting `design_spec.md` to fix → mark `needs_human` with a one-line `suggested_fix_summary`.++## §4 Iteration protocol++### §4.0 Iteration 0 — PNG sanity check *(v2 — relaxed)*++Run before applying any rule:++- PNG file exists and is non-zero bytes+- PNG dimensions = 1280 × 720+- PNG is **not** all-background (a histogram check: count of background-color pixels < 99% of total) — guards against blank/white-out renders only, **does not** filter sparse dark layouts++Any check fails → status = `render_failed`, abort without scanning rules. The earlier "non-bg pixel ratio ≥ 5%" rule is **deprecated** — it false-fires on legitimate minimalist dark decks (verified empirically in v1 plumbing test).++### §4.1 Iteration loop++```+iteration 1: scan all Hard + Soft → fix → re-render → re-screenshot+iteration 2: re-verify changed elements + scan for new Hard hits → fix → re-render+iteration 3: report only, no further fix+```++Per-iteration fix caps:++- **Hard rules**: no per-round cap — every Hard hit must be addressed in the iteration it was found in+- **Soft rules**: ≤ 2 fixes per iteration; remaining Soft hits go to `untouched_concerns`++### §4.2 Termination conditions++- **Rollback trigger**: any iteration's fix introduces a **new Hard hit** that did not exist before → immediately `cp` the backup back over the SVG, status = `needs_human`, finding records "rolled back fix X — created Hard Y"+- **Soft thrash trigger**: iteration 2's fix introduces a **new Soft hit** that did not exist before → stop, status = `needs_human` with note "fixes are competing"+- **Clean exit**: iteration 1 ends with zero Hard hits and ≤ 1 Soft hit remaining → status = `ok` if no fixes were applied, `fixed` if any were applied++### §4.3 Backup discipline++Before the **first** `Edit` on a page in any iteration `N`, the subagent must:++```bash+cp <project>/svg_output/<page>.svg <project>/.review/backup/<page>.iter<N>.svg+```++The backup path is recorded in every finding's `backup_path` field. Backups are the rollback anchor for §4.2.++## §5 Output schema++Each subagent writes exactly one file to `<project>/.review/<page>.json`:++```json+{+ "page": "02_three_steps.svg",+ "page_role": "content",+ "status": "ok" | "fixed" | "needs_human" | "render_failed" | "prereq_failed",+ "iterations_run": 1,+ "screenshot_paths": [+ ".preview/02_three_steps.png",+ ".preview/02_three_steps.iter1.png"+ ],+ "findings": [+ {+ "iter": 1,+ "rule": "S6",+ "severity": "soft",+ "evidence": "letter-spacing=10 on font-size=84, ratio=11.9% > 5%",+ "fix_applied": {+ "element": "#hero-statement text[font-size='84']",+ "before": "letter-spacing=\"10\"",+ "after": "letter-spacing=\"2\""+ },+ "verified_in_iter": 2,+ "backup_path": ".review/backup/02_three_steps.iter1.svg"+ }+ ],+ "untouched_concerns": [+ {+ "rule": "S1",+ "evidence": "...",+ "reason": "soft-cap reached" | "brand_token_aggregated" | "ambiguous_design_intent"+ }+ ],+ "needs_human_items": [+ {+ "rule": "H9",+ "suggested_fix_summary": "Hero subtitle declared in spec §IX.4 missing; add a <text> at (80,496) per design language"+ }+ ],+ "design_intent_check": {+ "spec_says": "TL;DR — emphasize 意图 as the core abstraction",+ "render_delivers": true,+ "note": "..."+ }+}+```++`needs_human_items` must include a `suggested_fix_summary` for every entry — never bare problem descriptions.++## §6 Dispatch & messaging contract *(new in v2)*++This rubric is consumed by subagents spawned via the `visual-review` workflow. Mandatory dispatch invariants:++### §6.1 Orchestrator → subagent++- Spawn all per-page subagents in **one assistant message** (parallel `Agent` calls). Sequential dispatch breaks pipelining.+- Each subagent prompt is **self-contained** — no prior conversation context. Inline the absolute paths for §0.1 inputs 1–7 explicitly. Do not assume the subagent knows the project root.+- `subagent_type: general-purpose`. Tool restrictions: Read, Edit, Bash (for `cp` backups), Write (for JSON output). MCP playwright is **not** required by subagents — orchestrator pre-renders PNGs.+- `name` / `team_name` parameters may be unavailable from nested teammate context. Dispatch must remain functional with anonymous subagents — do not require named addressing.++### §6.2 Subagent → orchestrator++- Subagent's **final action before going idle** must be `SendMessage(to=<lead>)` with the page's JSON path and a ≤150-word text summary of findings + actions. Going idle without messaging is a protocol violation.++### §6.3 Orchestrator → main agent++- Orchestrator's **final action before going idle** must be `SendMessage(to=<lead>)` containing:+ - the aggregate Markdown table (page × status × hard_hits × soft_hits × fixes_applied × needs_human_reason)+ - one ≤150-word "plumbing verdict" paragraph+ - path to `brand_review.json` if any §1.1 aggregations occurred++### §6.4 Concurrency++- Pre-rendering is serialized by `visual_review.py`'s file lock at `<project>/.preview/.render.lock`. Subagents must **not** call the renderer concurrently. Re-renders during iteration loop go through the same lock.++## §7 Renderer expectations *(script contract)*++`visual_review.py <project> [pages...]` must guarantee:++- Output PNG matches what the user would see in the live-preview browser (inlined `<use data-icon>`, resolved `<image href>`)+- Output dimensions = 1280 × 720+- File-lock serialization at `<project>/.preview/.render.lock`+- Clean exit codes:+ - `0` — all requested pages rendered+ - `2` — live-preview server not running for this project (subagent should not retry; surfaces to the orchestrator)+ - `3` — rendering backend (playwright + chromium) missing or unable to launch (config error, surface to user)+ - `4` — page-level render failure (specific failures listed in stderr; partial output is acceptable)++The renderer never edits SVGs and never reads any rule from this rubric — it is a pure render-and-validate tool.diff --git a/skills/ppt-master/scripts/visual_review.py b/skills/ppt-master/scripts/visual_review.pynew file mode 100644index 00000000..a929674f--- /dev/null+++ b/skills/ppt-master/scripts/visual_review.py@@ -0,0 +1,305 @@+#!/usr/bin/env python3+"""+PPT Master - Visual Review Renderer++Renders project SVGs to 1280x720 PNGs that match the live-preview browser view+(inlined <use data-icon>, resolved <image href>, full font fallback including CJK).+The pure renderer for the visual-review workflow — does not edit SVGs, does not+interpret the rubric.++Backend: Playwright (Chromium). The cairosvg backend was evaluated and rejected+because cairo's text API has no font-fallback chain — CJK characters render as+tofu boxes for any deck whose font-family list relies on system fallback.++Usage:+ python3 scripts/visual_review.py <project_path>+ python3 scripts/visual_review.py <project_path> --pages 02 03+ python3 scripts/visual_review.py <project_path> --server-url http://localhost:5050++Exit codes (per references/visual-review.md §7):+ 0 — all requested pages rendered+ 2 — live-preview server not reachable for this project+ 3 — rendering backend (playwright + chromium) missing or unable to launch+ 4 — one or more page-level render failures (details in stderr)++Output: JSON summary printed to stdout, PNGs written to <project>/.preview/.+"""++from __future__ import annotations++import argparse+import io+import json+import os+import sys+import time+import urllib.error+import urllib.request+from contextlib import contextmanager+from pathlib import Path+++# Histogram threshold: PNG counts as "all background" if a single quantized+# color bucket holds >= ALL_BG_THRESHOLD of pixels. Guards against blank+# renders without false-firing on legitimate sparse dark layouts.+ALL_BG_THRESHOLD = 0.99+++def _safe_print(msg: str) -> None:+ print(msg, file=sys.stderr, flush=True)+++@contextmanager+def file_lock(lock_path: Path, timeout: float = 30.0):+ """POSIX advisory lock via fcntl. Falls back to lockless on Windows."""+ try:+ import fcntl+ except ImportError:+ yield+ return++ lock_path.parent.mkdir(parents=True, exist_ok=True)+ fp = open(lock_path, 'w')+ deadline = time.monotonic() + timeout+ while True:+ try:+ fcntl.flock(fp.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ break+ except BlockingIOError:+ if time.monotonic() >= deadline:+ fp.close()+ raise TimeoutError(f"render lock contended for {timeout}s at {lock_path}")+ time.sleep(0.1)+ try:+ fp.write(str(os.getpid()))+ fp.flush()+ yield+ finally:+ fcntl.flock(fp.fileno(), fcntl.LOCK_UN)+ fp.close()+ try:+ lock_path.unlink()+ except FileNotFoundError:+ pass+++def is_all_background(png_bytes: bytes) -> bool:+ """Histogram check: quantize each channel to 4 bits, count dominant bucket.+ Returns True only when the PNG is essentially monochrome (blank render)."""+ try:+ from PIL import Image+ except ImportError:+ # PIL not installed — skip this check, the rubric subagent will+ # re-validate visually.+ return False++ img = Image.open(io.BytesIO(png_bytes)).convert('RGB')+ pixels = list(img.getdata())+ total = len(pixels)+ if total == 0:+ return True+ counts: dict[tuple[int, int, int], int] = {}+ for r, g, b in pixels:+ key = (r >> 4, g >> 4, b >> 4)+ counts[key] = counts.get(key, 0) + 1+ dominant = max(counts.values())+ return dominant / total >= ALL_BG_THRESHOLD+++def fetch_slide_text(server_url: str, page_name: str, timeout: float = 5.0) -> int:+ """Probe that the server can return the slide. Returns content length.+ Used only for failure detection — the actual fetch happens inside the+ browser via fetch() so the response is parsed by JS, not Python."""+ url = f"{server_url.rstrip('/')}/api/slide/{page_name}"+ req = urllib.request.Request(url, headers={'Accept': 'application/json'})+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ payload = json.loads(resp.read().decode('utf-8'))+ if 'content' not in payload:+ raise RuntimeError(f'unexpected response shape from {url}: {payload!r}')+ return len(payload['content'])+++def render_pages(server_url: str, pages: list[str], preview_dir: Path) -> list[dict]:+ """Render all requested pages in a single browser session.++ Each render: page.goto(server_url) anchors the base URL so the SVG's+ relative <image href="../images/..."> resolves against the server.+ Then fetch the slide via the server's /api/slide endpoint (which inlines+ <use data-icon> references) and inject it as the document body.+ """+ from playwright.sync_api import sync_playwright++ preview_dir.mkdir(parents=True, exist_ok=True)+ records: list[dict] = []++ inject_js = """+async (pageName) => {+ const res = await fetch('/api/slide/' + pageName + '?_=' + Date.now());+ if (!res.ok) throw new Error('fetch /api/slide/' + pageName + ' returned ' + res.status);+ const data = await res.json();+ document.documentElement.innerHTML =+ '<head><style>html,body{margin:0;padding:0;background:#0E1116;overflow:hidden}'+ + ' svg{display:block;width:1280px;height:720px}</style></head>'+ + '<body>' + data.content + '</body>';+ return { len: data.content.length };+}+"""++ with sync_playwright() as p:+ browser = p.chromium.launch()+ try:+ context = browser.new_context(viewport={'width': 1280, 'height': 720})+ for page_name in pages:+ rec: dict = {'page': page_name, 'ok': False}+ try:+ fetch_slide_text(server_url, page_name)+ except urllib.error.URLError as e:+ rec['error'] = f'server_unreachable: {e!r}'+ records.append(rec)+ continue+ except Exception as e: # noqa: BLE001+ rec['error'] = f'{type(e).__name__}: {e}'+ records.append(rec)+ continue++ stem = page_name[:-4] if page_name.endswith('.svg') else page_name+ out_path = preview_dir / f'{stem}.png'++ try:+ pg = context.new_page()+ pg.goto(server_url, wait_until='domcontentloaded')+ pg.evaluate(inject_js, page_name)+ # Wait one frame so font/text shaping settles before capture.+ pg.wait_for_timeout(100)+ png_bytes = pg.screenshot(type='png', full_page=False)+ pg.close()++ out_path.write_bytes(png_bytes)+ rec['ok'] = True+ rec['path'] = str(out_path)+ rec['bytes'] = len(png_bytes)+ rec['all_background'] = is_all_background(png_bytes)+ except Exception as e: # noqa: BLE001 — best-effort per-page+ rec['error'] = f'{type(e).__name__}: {e}'+ records.append(rec)+ finally:+ browser.close()++ return records+++def discover_pages(project_path: Path, requested: list[str] | None) -> list[str]:+ svg_dir = project_path / 'svg_output'+ if not svg_dir.is_dir():+ raise FileNotFoundError(f'no svg_output/ in {project_path}')+ all_svgs = sorted(p.name for p in svg_dir.glob('*.svg'))+ if not requested:+ return all_svgs+ selected: list[str] = []+ for token in requested:+ match = next((n for n in all_svgs if n.startswith(token) or n == token), None)+ if match is None:+ raise ValueError(f'no SVG matches token {token!r} in {svg_dir}')+ selected.append(match)+ return selected+++def check_server(server_url: str) -> None:+ """Probe server liveness via /api/slides. Raises RuntimeError if down."""+ url = f"{server_url.rstrip('/')}/api/slides"+ try:+ with urllib.request.urlopen(url, timeout=3.0) as resp:+ if resp.status != 200:+ raise RuntimeError(f'{url} returned HTTP {resp.status}')+ except urllib.error.URLError as e:+ raise RuntimeError(f'live-preview server not reachable at {server_url}: {e}')+++def main() -> int:+ parser = argparse.ArgumentParser(+ description='Render project SVGs to PNGs for visual review.',+ )+ parser.add_argument('project_path', help='Path to project directory (contains svg_output/)')+ parser.add_argument(+ '--pages', nargs='+', default=None,+ help='Page tokens to render (default: all SVGs in svg_output/). '+ "Accepts '02', '02_three_steps', or '02_three_steps.svg'.",+ )+ parser.add_argument(+ '--server-url', default='http://localhost:5050',+ help='Live-preview server URL (default: http://localhost:5050)',+ )+ parser.add_argument(+ '--lock-timeout', type=float, default=30.0,+ help='Seconds to wait for render lock (default: 30)',+ )+ args = parser.parse_args()++ project_path = Path(args.project_path).resolve()+ if not project_path.is_dir():+ _safe_print(f'project path not found: {project_path}')+ return 2++ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except ImportError:+ _safe_print(+ 'playwright not installed. Install with:\n'+ ' pip install playwright\n'+ ' python3 -m playwright install chromium\n'+ '(see skills/ppt-master/requirements.txt)'+ )+ return 3++ try:+ check_server(args.server_url)+ except RuntimeError as e:+ _safe_print(str(e))+ _safe_print(+ 'start it with:\n'+ f' python3 skills/ppt-master/scripts/svg_editor/server.py {project_path}'+ )+ return 2++ try:+ pages = discover_pages(project_path, args.pages)+ except (FileNotFoundError, ValueError) as e:+ _safe_print(str(e))+ return 2++ preview_dir = project_path / '.preview'+ lock_path = preview_dir / '.render.lock'++ with file_lock(lock_path, timeout=args.lock_timeout):+ try:+ records = render_pages(args.server_url, pages, preview_dir)+ except Exception as e: # noqa: BLE001 — browser launch failure+ _safe_print(f'browser session failed: {type(e).__name__}: {e}')+ _safe_print(+ 'try: python3 -m playwright install chromium'+ )+ return 3++ for rec in records:+ if not rec['ok']:+ _safe_print(f"[FAIL] {rec['page']}: {rec.get('error')}")+ elif rec.get('all_background'):+ _safe_print(f"[WARN] {rec['page']}: PNG rendered but is all-background")++ summary = {+ 'project': str(project_path),+ 'server_url': args.server_url,+ 'rendered': sum(1 for r in records if r['ok']),+ 'failed': sum(1 for r in records if not r['ok']),+ 'all_background': sum(1 for r in records if r.get('all_background')),+ 'pages': records,+ }+ print(json.dumps(summary, indent=2, ensure_ascii=False))++ if summary['failed']:+ return 4+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/skills/ppt-master/workflows/visual-review.md b/skills/ppt-master/workflows/visual-review.mdnew file mode 100644index 00000000..037dc9a6--- /dev/null+++ b/skills/ppt-master/workflows/visual-review.md@@ -0,0 +1,177 @@+---+description: Per-page rubric-based visual self-review via parallel subagents. Run after Executor, before post-processing.+---++# Visual Review Workflow++> Standalone post-generation step. Goal: reduce human iteration by letting AI subagents visually self-check each rendered slide against a fixed rubric and apply atomic position/spacing fixes.+>+> Reads `<project>/svg_output/<page>.svg` and a pre-rendered PNG of each slide, then either applies a fix or flags `needs_human`. **Never touches** brand decisions, layout structure, or other files.+>+> This workflow is **independent** — invokable in a fresh chat session with only `<project_path>` as input. No upstream conversation context required.++## When to Run++- Executor (SKILL.md Step 6) has finished all pages+- `svg_quality_checker.py` has passed+- Post-processing (`finalize_svg.py`, `svg_to_pptx.py`) has **not** yet run+- User wants to reduce manual review iterations before export++Optional but recommended for any deck where layout precision matters. For decks containing data charts, run [`verify-charts`](./verify-charts.md) first — visual-review focuses on visual rhythm / collision / alignment, not chart coordinate math.++## When NOT to Run++- The project has no `svg_output/<page>.svg` files yet — finish Executor first+- `svg_quality_checker.py` has not been run or has failed — fix static violations first+- User has already applied annotations via `live-preview` workflow and is in a fixed-edit loop — describe changes directly, do not re-trigger rubric+- The deck is < 3 pages and the user is reviewing manually anyway — manual review is faster++---++## Prerequisites++```bash+# 1. playwright + chromium installed (the PNG renderer)+pip install playwright+python3 -m playwright install chromium++# 2. live-preview server running for this project (provides inlined SVG fetch)+python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --no-browser+# (single instance per project — if it's already running, skip)+```++The renderer (`visual_review.py`) does **not** auto-start the live-preview server. It expects the server to be reachable at `http://localhost:5050` (override with `--server-url`).++> **Why playwright, not cairosvg**: cairo's text API has no font-fallback chain, so CJK characters render as tofu boxes for any deck whose font-family list relies on system fallback (Microsoft YaHei / PingFang SC / etc.). Playwright drives a real chromium and produces output identical to what the live-preview browser shows — the only fidelity-preserving option for bilingual decks.++---++## Step 1 — Pre-render all PNGs++```bash+python3 skills/ppt-master/scripts/visual_review.py <project_path>+```++This writes one PNG per page to `<project_path>/.preview/<page>.png` at 1280×720, with `<use data-icon>` inlined and `<image href>` resolved exactly as the live-preview browser sees them. Renders are serialized via a project-local file lock — safe to invoke concurrently.++Exit codes:++- `0` — all pages rendered+- `2` — live-preview server unreachable (start it per Prerequisites)+- `3` — playwright python / chromium not installed (or browser failed to launch)+- `4` — one or more page-level render failures (see stderr; partial output is on disk)++If any page comes back with `"all_background": true` in the JSON summary, that page rendered to a blank surface — investigate before continuing (broken `<use>` reference, missing image asset, etc.).++---++## Step 2 — Spawn the review team++Create a team and dispatch one orchestrator agent. The orchestrator spawns one per-page review subagent **in parallel** (single message, N parallel `Agent` calls), aggregates their JSON outputs, and reports back.++```text+TeamCreate(team_name="visual-review-<project>", agent_type="orchestrator")+Agent(+ team_name="visual-review-<project>",+ subagent_type="general-purpose",+ name="orchestrator",+ prompt=<orchestrator-prompt>, # see template below+)+```++### Orchestrator prompt template++The orchestrator prompt must be self-contained. Required fields (all absolute paths):++- `<project_path>` — project root+- Page list with role for each page (parse `<project>/design_spec.md` §IX outline; if §IX is absent, default every page to `content` and flag this in the final report)+- Path to the rubric: `skills/ppt-master/references/visual-review.md`+- Instruction: **dispatch all per-page subagents in a single message**+- Instruction: after aggregation, `SendMessage(to="team-lead")` with results before going idle — orchestrator must **not** end its turn without sending the aggregate++### Per-page subagent prompt template++Composed by the orchestrator, one per page, also self-contained:++- SVG path, PNG path, `page_role`+- Path to rubric+- Path to `design_spec.md` and `spec_lock.md` (read-only)+- Output JSON path: `<project>/.review/<page>.json`+- Backup directory: `<project>/.review/backup/`+- Iteration budget: 1 by default (2 for high-stakes decks — opt in explicitly)+- Explicit forbid list: do not edit any other page, `design_spec.md`, `spec_lock.md`, `animations.json`, `image_prompts.json`, or `images/`+- Mandatory final action: `SendMessage(to=<orchestrator-name>)` with the JSON path + a ≤150-word summary before going idle++See [`references/visual-review.md`](../references/visual-review.md) §6 for the full dispatch contract.++---++## Step 3 — Aggregate findings++The orchestrator emits the aggregate Markdown table back to you (the main agent):++```+| page | role | status | hard_hits | soft_hits | fixes_applied | needs_human_reason |+|------|------|--------|-----------|-----------|---------------|---------------------|+```++Statuses:++- `ok` — page passed clean, no fixes applied+- `fixed` — at least one fix applied, all Hard rules now pass+- `needs_human` — fix attempted but rolled back (rule §4.2), or rule violation requires brand/structure decision outside the rubric's scope+- `render_failed` — Iteration 0 PNG sanity failed (rare; usually means renderer / server issue)+- `prereq_failed` — static checker hadn't been run++Plus a brand-token aggregate at `<project>/.review/brand_review.json` if any §1.1 escalations occurred — review this once at the end of the run, not per page.++---++## Step 4 — Decide next move++For each row in the table:++- `ok` / `fixed` — no action; the SVG has been updated in-place (originals are at `<project>/.review/backup/<page>.iter<N>.svg`)+- `needs_human` — read the page's JSON `needs_human_items[].suggested_fix_summary`, decide with the user whether to apply or defer+- `render_failed` — re-run `visual_review.py` for that page only (`--pages <token>`); if it persists, hand off to manual review+- `prereq_failed` — go back and run `svg_quality_checker.py`++If `brand_review.json` is non-empty, that's a single decision applied across the deck (e.g., bump footer text color from `#6E7681` to `#8B949E` — one change, every page benefits). Do this once, then optionally re-run visual-review for the affected pages only.++After the table is clean, continue to post-processing per [`SKILL.md`](../SKILL.md) Step 7:++```bash+python3 skills/ppt-master/scripts/total_md_split.py <project_path>+python3 skills/ppt-master/scripts/finalize_svg.py <project_path>+python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path>+```++---++## Notes & invariants++- **Single source of truth for rules**: [`references/visual-review.md`](../references/visual-review.md). This workflow file is just the orchestration — never restate or paraphrase rules here.+- **Concurrency**: `visual_review.py` serializes renders via `<project>/.preview/.render.lock`. Subagents must never call the renderer directly without the lock.+- **Iteration budget**: default 1 iteration. Bumping to 2 doubles render cost and roughly triples token cost. Only worth it for high-stakes / final-cut decks.+- **Don't-touch (rubric §3)** is hard-enforced by subagents. If you want the subagent to e.g. change a brand color, that is **out of scope** — make the change manually first, then re-render & re-review.+- **Backups**: every modified SVG has a `.review/backup/<page>.iter<N>.svg` rollback anchor. Restore by `cp`.+- **The rubric is not the designer**: it catches collisions, drift, and rhythm errors — it does not improve a fundamentally weak layout. If 80%+ of pages come back `needs_human`, the design spec or the executor's choice of layout patterns is the root cause, not this workflow.+- **Playwright output discipline**: when an agent uses the playwright MCP tool `browser_take_screenshot` directly (outside the `visual_review.py` script), the `filename` parameter is resolved against the CWD (typically the repo root) — passing a bare relative path will create stray directories inside the repository. Always pass an absolute path:+ - One-off probe / ad-hoc inspection → `/tmp/probe-<topic>-<n>.png`+ - Project artifact (replaces what the script would have produced) → `<project_path>/.preview/<page>.png` (absolute)+ - Never write to `<repo>/<anything>.png` or `<repo>/<some_dir>/...` — those are caught by `.gitignore` patterns but the cleanup burden is real++ The `visual_review.py` script handles output paths correctly on its own; this rule only applies to direct playwright MCP usage during interactive exploration or recovery.++---++## Appendix: Iteration loop (v2 behavior)++This v1 workflow uses single-iteration review (one scan, fix, done). The full iteration loop per [`references/visual-review.md`](../references/visual-review.md) §4.1 supports:++1. Iteration 1: scan + fix+2. Re-render via `visual_review.py --pages <token>`+3. Iteration 2: re-verify changed elements + scan for new Hard hits+4. Rollback on any new Hard hit introduced by a fix++To enable, pass `--iteration-budget 2` in the orchestrator prompt (currently advisory; the script itself does not enforce — subagent prompt must mention it explicitly). Reserve for final-cut runs.