Skip to content

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

feat(visualizations): add family-aware reference contracts

hugohe3e214c6d2fbdf
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 1f32e13d..89946e1e 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -55,7 +55,7 @@ python3 scripts/update_repo.py
| SVG pipeline | `preset_shape_svg.py`, `shape_boolean_svg.py`, `svg_authoring_view.py`, `compact_svg_coordinates.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py`, `narration_sync.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native shape authoring](../references/native-shape-authoring.md) |
| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
-| Spec maintenance | `update_spec.py`, `chart_recall.py` | [docs/update_spec.md](./docs/update_spec.md); [docs/chart-recall.md](./docs/chart-recall.md) |
+| Spec maintenance | `update_spec.py`, `visualization_recall.py`; legacy `chart_recall.py` | [docs/update_spec.md](./docs/update_spec.md); [docs/visualization-recall.md](./docs/visualization-recall.md) |
| Image tools | `image_gen.py`, `latex_render.py`, `analyze_images.py`, `gemini_watermark_remover.py` | [docs/image.md](./docs/image.md) |
| Maintenance smokes | Inline temporary-project commands | [advanced image and motion](./docs/advanced-image-motion-smoke.md); [mask and gradient](./docs/mask-gradient-smoke.md); [multilingual text](./docs/multilingual-text-smoke.md) |
| Repo maintenance | `update_repo.py` | README install/update section |
@@ -91,17 +91,17 @@ python3 scripts/project_manager.py page-context-report <project_path>
routing checks, or context measurement; normal generation retains the complete
Design Spec and lock once per valid execution context. Each invocation includes
the global lock projection as a continuity anchor set, not a color/font allowlist; large Design Specs,
-prototype, and `templates/charts/` references are emitted only as scoped
+prototype, and selected family visualization references are emitted only as scoped
path/SHA fingerprints and are read once per execution context. `--bundle` is a
deprecated compatibility no-op. `--record-usage` writes one derived snapshot
under `analysis/page-context/`; exact `o200k_base` token counts are optional and
degrade to `tokens: null` when `tiktoken` is absent. Telemetry may be partial.
-Chart candidate recall:
+Visualization candidate recall:
```bash
-python3 scripts/chart_recall.py recall --page P03 --tag "time series" --tag "three metrics" --tag "direction over time"
-python3 scripts/chart_recall.py validate line_chart
+python3 scripts/visualization_recall.py recall --page P03 --tag "time series" --tag "three metrics" --tag "direction over time"
+python3 scripts/visualization_recall.py validate chart/line_chart
```
Template source import:
diff --git a/skills/ppt-master/scripts/chart_recall.py b/skills/ppt-master/scripts/chart_recall.py
index b050ccce..b0474c81 100644
--- a/skills/ppt-master/scripts/chart_recall.py
+++ b/skills/ppt-master/scripts/chart_recall.py
@@ -1,346 +1,25 @@
#!/usr/bin/env python3
"""
-PPT Master - Chart Candidate Recall
+PPT Master - Legacy Chart Recall Compatibility
-Recalls a deterministic chart-template shortlist from page-shape semantic tags,
-or validates selected chart keys against the live chart catalog.
+Preserve the historical broad chart-recall CLI while delegating to the unified
+visualization recall implementation.
Usage:
python3 scripts/chart_recall.py recall --page P03 --tag "time series" --tag "three metrics" --tag "trend"
python3 scripts/chart_recall.py validate line_chart column_chart
Examples:
- python3 scripts/chart_recall.py recall --page P07 --tag "named quadrants" \
- --tag "bullet lists" --tag "SWOT" --limit 6
- python3 scripts/chart_recall.py validate quadrant_text_bullets
+ python3 scripts/chart_recall.py validate fishbone_diagram
Dependencies:
- None (only uses standard library)
-
-See scripts/docs/chart-recall.md for the Strategist workflow and output contract.
+ None (only uses the standard library)
"""
from __future__ import annotations
-import argparse
-import json
-import re
-import sys
-import unicodedata
-from pathlib import Path
-from typing import Optional
-
-from console_encoding import configure_utf8_stdio
-
-configure_utf8_stdio()
-
-_SCRIPTS_DIR = Path(__file__).resolve().parent
-_INDEX_PATH = _SCRIPTS_DIR.parent / "templates" / "charts" / "charts_index.json"
-_TOKEN_RE = re.compile(r"[a-z0-9]+")
-_PAGE_RE = re.compile(r"^P\d{2,}$")
-_KEY_RE = re.compile(r"^[a-z0-9]+(?:_[a-z0-9]+)*$")
-_SKIP_RE = re.compile(r"\bskip\s+(?:if|for)\b", re.IGNORECASE)
-_STOP_WORDS = {
- "a",
- "an",
- "and",
- "as",
- "at",
- "by",
- "for",
- "from",
- "if",
- "in",
- "into",
- "of",
- "on",
- "or",
- "per",
- "the",
- "to",
- "use",
- "with",
-}
-
-
-def _normalize(text: str) -> str:
- normalized = unicodedata.normalize("NFKC", text).casefold().replace("_", " ")
- return " ".join(_TOKEN_RE.findall(normalized))
-
-
-def _stem(token: str) -> str:
- if len(token) > 5 and token.endswith("ies"):
- return token[:-3] + "y"
- if len(token) > 5 and token.endswith("ing"):
- return token[:-3]
- if len(token) > 4 and token.endswith("ed"):
- return token[:-2]
- if len(token) > 4 and token.endswith("es"):
- return token[:-2]
- if len(token) > 3 and token.endswith("s"):
- return token[:-1]
- return token
-
-
-def _tokens(text: str) -> set[str]:
- return {
- _stem(token)
- for token in _TOKEN_RE.findall(_normalize(text))
- if token not in _STOP_WORDS
- }
-
-
-def load_catalog() -> dict[str, str]:
- """Load and validate the live chart catalog."""
- try:
- payload = json.loads(_INDEX_PATH.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
- raise RuntimeError(f"Cannot read chart catalog {_INDEX_PATH}: {exc}") from exc
-
- if not isinstance(payload, dict):
- raise RuntimeError(f"Chart catalog {_INDEX_PATH} root must be an object")
- raw_charts = payload.get("charts")
- if not isinstance(raw_charts, dict) or not raw_charts:
- raise RuntimeError(f"Chart catalog {_INDEX_PATH} has no non-empty 'charts' object")
-
- charts: dict[str, str] = {}
- for key, item in raw_charts.items():
- if (
- not isinstance(key, str)
- or _KEY_RE.fullmatch(key) is None
- or not isinstance(item, dict)
- ):
- raise RuntimeError(f"Chart catalog entry {key!r} is malformed")
- summary = item.get("summary")
- if not isinstance(summary, str) or not summary.strip():
- raise RuntimeError(f"Chart catalog entry {key!r} has no non-empty summary")
- charts[key] = summary.strip()
- return charts
-
-
-def _score_candidate(key: str, summary: str, tags: list[str]) -> tuple[int, list[str]]:
- skip_match = _SKIP_RE.search(summary)
- if skip_match is None:
- pick_clause, skip_clause = summary, ""
- else:
- pick_clause = summary[:skip_match.start()]
- skip_clause = summary[skip_match.start():]
- key_text = _normalize(key)
- pick_text = _normalize(pick_clause)
- skip_text = _normalize(skip_clause)
- key_tokens = _tokens(key)
- pick_tokens = _tokens(pick_clause)
- skip_tokens = _tokens(skip_clause)
- score = 0
- matched_tags: list[str] = []
-
- for tag in tags:
- tag_text = _normalize(tag)
- tag_tokens = _tokens(tag)
- positive_score = 0
- negative_score = 0
- if tag_text and tag_text in key_text:
- positive_score += 20
- elif tag_text and tag_text in pick_text:
- positive_score += 14
- if tag_text and tag_text in skip_text:
- negative_score += 12
-
- for token in tag_tokens:
- if token in key_tokens:
- positive_score += 9
- elif token in pick_tokens:
- positive_score += 5
- if token in skip_tokens:
- negative_score += 6
-
- if positive_score:
- matched_tags.append(tag)
- score += positive_score - negative_score
-
- return score, matched_tags
-
-
-def recall_candidates(
- page: str,
- tags: list[str],
- limit: int,
- *,
- force_semantic_fallback: bool = False,
-) -> dict[str, object]:
- """Recall a deterministic shortlist for one page."""
- charts = load_catalog()
- scored: list[tuple[int, str, str, list[str]]] = []
- for key, summary in charts.items():
- score, matched_tags = _score_candidate(key, summary, tags)
- if score > 0 and matched_tags:
- scored.append((score, key, summary, matched_tags))
- scored.sort(key=lambda item: (-item[0], item[1]))
-
- candidates = []
- for score, key, summary, matched_tags in scored[:limit]:
- candidates.append(
- {
- "key": key,
- "path": f"templates/charts/{key}.svg",
- "summary": summary,
- "score": score,
- "matched_tags": matched_tags,
- }
- )
-
- top_score = candidates[0]["score"] if candidates else 0
- if top_score >= 35:
- confidence = "high"
- elif top_score >= 15:
- confidence = "medium"
- elif top_score > 0:
- confidence = "low"
- else:
- confidence = "none"
-
- fallback_required_before_no_match = (
- confidence in {"low", "none"} and not force_semantic_fallback
- )
- if fallback_required_before_no_match:
- no_match_instruction = (
- f"Lexical confidence is {confidence}. Select a bounded candidate when one "
- "fits; otherwise rerun the same recall with --semantic-fallback before "
- "keeping no-template-match. Keep the final negative result out of Design "
- "Spec Section VII and describe the chosen fallback in the page's Section "
- "IX block."
- )
- else:
- no_match_instruction = (
- "Use when none of the reviewed candidates fits the page structure. Keep "
- "this result out of Design Spec Section VII and describe the chosen fallback "
- "in the page's Section IX block."
- )
-
- result: dict[str, object] = {
- "page": page,
- "semantic_tags": tags,
- "confidence": confidence,
- "candidates": candidates,
- "no_template_match": {
- "allowed": not fallback_required_before_no_match,
- "key": "no-template-match",
- "instruction": no_match_instruction,
- },
- }
- if force_semantic_fallback:
- result["semantic_fallback"] = {
- "reason": "requested-after-bounded-review",
- "instruction": (
- "Semantically compare the page tags with every returned selection rule. "
- "Choose one exact catalog key or keep no-template-match; lexical overlap "
- "is not required in this review."
- ),
- "path_pattern": "templates/charts/{key}.svg",
- "catalog": charts,
- }
- return result
-
-
-def _dedupe(values: list[str]) -> list[str]:
- result: list[str] = []
- seen: set[str] = set()
- for value in values:
- stripped = value.strip()
- normalized = _normalize(stripped)
- if not stripped or not normalized or normalized in seen:
- continue
- seen.add(normalized)
- result.append(stripped)
- return result
-
-
-def _run_recall(args: argparse.Namespace) -> int:
- page = args.page.upper()
- if not _PAGE_RE.fullmatch(page):
- print("Error: --page must match P<NN>, for example P03.", file=sys.stderr)
- return 2
-
- tags = _dedupe(args.tag)
- if not 3 <= len(tags) <= 8:
- print("Error: recall requires 3-8 distinct non-empty --tag values.", file=sys.stderr)
- return 2
-
- result = recall_candidates(
- page,
- tags,
- args.limit,
- force_semantic_fallback=args.semantic_fallback,
- )
- print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
- return 0
-
-
-def _run_validate(args: argparse.Namespace) -> int:
- charts = load_catalog()
- selected = _dedupe(args.keys)
- invalid = sorted(key for key in selected if key not in charts)
- result = {
- "invalid": invalid,
- "valid": sorted(key for key in selected if key in charts),
- }
- print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
- if invalid:
- print(
- "Error: replace each invalid key with a key returned by the recall command, "
- "or keep no-template-match out of Section VII and page_charts while "
- "recording the custom fallback in the page's Section IX block.",
- file=sys.stderr,
- )
- return 1
- return 0
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(
- description="Recall chart-template candidates or validate selected keys.",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- )
- subparsers = parser.add_subparsers(dest="command", required=True)
-
- recall = subparsers.add_parser("recall", help="Recall candidates for one planned page.")
- recall.add_argument("--page", required=True, help="Planned page key, for example P03.")
- recall.add_argument(
- "--tag",
- action="append",
- required=True,
- help="English semantic content-shape tag; repeat 3-8 times.",
- )
- recall.add_argument(
- "--limit",
- type=int,
- choices=range(3, 9),
- default=6,
- metavar="3..8",
- help="Candidate count (default: 6).",
- )
- recall.add_argument(
- "--semantic-fallback",
- action="store_true",
- help="Include the full catalog when bounded recall may have missed a semantic match.",
- )
- recall.set_defaults(handler=_run_recall)
-
- validate = subparsers.add_parser("validate", help="Validate selected catalog keys.")
- validate.add_argument("keys", nargs="+", help="One or more selected chart keys.")
- validate.set_defaults(handler=_run_validate)
- return parser
-
-
-def main(argv: Optional[list[str]] = None) -> int:
- parser = build_parser()
- args = parser.parse_args(argv)
- try:
- return args.handler(args)
- except RuntimeError as exc:
- print(f"Error: {exc}", file=sys.stderr)
- return 1
+from visualization_recall import main
if __name__ == "__main__":
- raise SystemExit(main())
+ raise SystemExit(main(legacy_output=True))
diff --git a/skills/ppt-master/scripts/docs/chart-recall.md b/skills/ppt-master/scripts/docs/chart-recall.md
index 9d78b8a8..285964a3 100644
--- a/skills/ppt-master/scripts/docs/chart-recall.md
+++ b/skills/ppt-master/scripts/docs/chart-recall.md
@@ -1,51 +1,19 @@
-# Chart Candidate Recall
+# Legacy Chart Recall Compatibility
-`chart_recall.py` gives Default Strategist or the Quick Generate main agent a bounded deterministic shortlist. It exposes the full live catalog only when the caller explicitly requests semantic review. It reads `templates/charts/charts_index.json` on every invocation, so the catalog remains the only template registry.
-
-## Recall candidates
-
-Describe one page's information shape with 3-8 concise English semantic tags. Translate source-language or industry terms into structural meaning before invoking the script.
+`chart_recall.py` preserves the historical broad visualization-recall CLI for
+existing projects and external callers. It delegates to
+`visualization_recall.py`, reads the same live family registries, and emits the
+legacy bare-key JSON shape.
```bash
python3 skills/ppt-master/scripts/chart_recall.py recall \
--page P03 \
- --tag "time series" \
- --tag "three metrics" \
- --tag "direction over time" \
- --limit 6
+ --tag "process flow" \
+ --tag "five stages" \
+ --tag "left to right"
+python3 skills/ppt-master/scripts/chart_recall.py validate process_flow
```
-`--limit` accepts 3-8 and defaults to 6. The JSON is already bounded and must be read unfiltered: `tail`, `head`, `grep`, or another truncator can discard higher-ranked candidates. `confidence` reports lexical strength only; it never decides whether a candidate fits. At `low` / `none`, a fitting bounded candidate needs no expansion, but `no_template_match.allowed` remains false until one explicit semantic fallback review.
-
-Semantically review the bounded candidates. At `high` / `medium`, retain `no-template-match` when none fits. At `low` / `none`, select a fitting bounded candidate directly; otherwise rerun the same command once with `--semantic-fallback`, compare the returned rules semantically, and only then retain `no-template-match`. The full-catalog review is therefore a narrow low-confidence no-match gate, not a routine recall step. Do not open or maintain a second keyword/category index. `no-template-match` is an internal recall result, not a Design Spec §VII row.
-
-| Field | Contract |
-|---|---|
-| `page` | Input `P<NN>` page key |
-| `semantic_tags` | Deduplicated input tags |
-| `confidence` | Lexical recall strength; never a selection decision |
-| `candidates` | Ranked keys, SVG paths, verbatim catalog summaries, scores, and matched tags |
-| `semantic_fallback` | Full live catalog, present only with `--semantic-fallback`; requires semantic comparison |
-| `no_template_match` | Explicit fallback; `allowed` stays false for `low` / `none` until `--semantic-fallback` is used |
-
-The scorer treats the key and the summary's Pick clause as positive evidence and the Skip clause as negative evidence. A term found only in Skip cannot make a candidate eligible, and Skip matches explicitly reduce a candidate's score. Unicode input is NFKC-normalized before matching. The active profile owner still applies semantic judgment: inspect the returned candidates, reject candidates whose Skip clause matches, and prefer the most specific valid structure. An empty or low-confidence shortlist requires one `--semantic-fallback` review only when the owner is about to keep `no-template-match`.
-
-## Validate selected keys
-
-Validate every selected template key before Default writes `design_spec.md §VII` / `spec_lock.md page_charts` or Quick opens that key for immediate use:
-
-```bash
-python3 skills/ppt-master/scripts/chart_recall.py validate line_chart quadrant_text_bullets
-```
-
-The command is read-only. It exits `0` when every key exists and `1` when any key is absent. A Default `no-template-match` page appears in neither §VII nor `page_charts`; record its chosen fallback in the page's §IX `Visualization` / `Layout`. Quick keeps the fallback only in active context and writes no mapping artifact.
-
-## Selection boundary
-
-- Preserve the two-lens review: numeric/data pages and structural-information pages.
-- Default keeps §VII as a positive selection list: record `Page | Template | Usage` for each selected key, and omit the whole section when no candidate is selected.
-- Default makes `Usage` one concise page-local purpose, not geometry or execution instructions; derive `templates/charts/<key>.svg` from the key and keep detailed adaptation in §IX.
-- Quick retains the selected key and immediate page purpose only in active context; do not create §VII, `page_charts`, or a substitute mapping file.
-- Never serialize `no-template-match`, an empty table, or a no-reference explanation into §VII.
-- Do not serialize returned summaries, paths, or runners-up into new §VII tables. Legacy wider tables remain readable.
-- Open the selected `<key>.svg` only as a reference for its mapped page; it does not lock type or geometry. Do not load unrelated catalog SVGs.
+Do not use this wrapper in new planning prompts. See
+[`visualization-recall.md`](./visualization-recall.md) for the canonical
+`family/key` workflow and `page_visualizations` contract.
diff --git a/skills/ppt-master/scripts/docs/visualization-recall.md b/skills/ppt-master/scripts/docs/visualization-recall.md
new file mode 100644
index 00000000..ef2894c8
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/visualization-recall.md
@@ -0,0 +1,85 @@
+# Visualization Candidate Recall
+
+`visualization_recall.py` gives Default Strategist or the Quick Generate main
+agent one bounded deterministic shortlist across the live chart, structure, and
+table family registries. It exposes the selected full catalog only when the
+caller explicitly requests semantic review. The tool reads these indexes on
+every invocation and maintains no second category or keyword index:
+
+- `templates/charts/charts_index.json`
+- `templates/structures/structures_index.json`
+- `templates/tables/tables_index.json`
+
+## Recall candidates
+
+Describe one page's information shape with 3-8 concise English semantic tags.
+Translate source-language or industry terms into structural meaning first.
+
+```bash
+python3 skills/ppt-master/scripts/visualization_recall.py recall \
+ --page P03 \
+ --tag "time series" \
+ --tag "three metrics" \
+ --tag "direction over time" \
+ --limit 6
+```
+
+Use `--family chart|structure|table` only when the page semantics already make
+that boundary certain; the default `all` preserves unified page-level recall.
+`--limit` accepts 3-8 and defaults to 6. Read the returned JSON unfiltered:
+`tail`, `head`, `grep`, or another truncator can discard higher-ranked
+candidates. `confidence` reports lexical strength only and never decides fit.
+
+At `high` / `medium`, retain `no-template-match` when none fits. At `low` /
+`none`, select a fitting bounded candidate directly; otherwise rerun the same
+command once with `--semantic-fallback`, compare the returned selection rules
+semantically, and only then retain `no-template-match`. The full-catalog review
+is a narrow low-confidence no-match gate, not a routine recall step.
+
+| Field | Contract |
+|---|---|
+| `page` | Input `P<NN>` page key |
+| `family_filter` | Requested family or `all` |
+| `semantic_tags` | Deduplicated input tags |
+| `confidence` | Lexical recall strength; never a selection decision |
+| `candidates` | Ranked family/key references, SVG paths, summaries, scores, and matched tags |
+| `semantic_fallback` | Selected live catalogs, present only with `--semantic-fallback` |
+| `no_template_match` | Explicit fallback; blocked at low/none until semantic fallback review |
+
+The scorer treats the key and summary Pick clause as positive evidence and the
+Skip clause as negative evidence. A term found only in Skip cannot make a
+candidate eligible. Unicode input is NFKC-normalized before matching. The
+active profile owner still applies semantic judgment and prefers the most
+specific valid information structure.
+
+## Validate selected references
+
+Validate every selected reference before Default writes Design Spec §VII and
+`spec_lock.md page_visualizations`, or before Quick opens it for immediate use:
+
+```bash
+python3 skills/ppt-master/scripts/visualization_recall.py validate \
+ chart/line_chart structure/quadrant_text_bullets table/basic_table
+```
+
+The command is read-only. It exits `0` when every canonical `family/key` exists
+with its SVG and `1` otherwise. A Default `no-template-match` page appears in
+neither §VII nor `page_visualizations`; record its custom fallback in §IX.
+
+## Selection boundary
+
+- Default records `Page | Family | Template | Usage` for each positive
+ selection and projects `family/key` into `page_visualizations`.
+- Usage is one concise page-local purpose; detailed adaptation remains in §IX.
+- Quick keeps the selected reference and purpose only in active context.
+- Never serialize `no-template-match`, empty tables, summaries, paths, or
+ runners-up into planning artifacts.
+- Open only the selected SVG for its mapped page. It is a flexible reference,
+ not a type, geometry, style, or native-replacement lock.
+
+## Legacy compatibility
+
+`chart_recall.py` remains a compatibility wrapper for existing callers. It
+uses the same scorer and all-family live registries, preserves bare-key
+validation and the historical JSON shape, and resolves each candidate to its
+current family path. New prompts and automation use `visualization_recall.py`.
diff --git a/skills/ppt-master/scripts/project_management/page_context.py b/skills/ppt-master/scripts/project_management/page_context.py
index 3bbf2732..8669304b 100644
--- a/skills/ppt-master/scripts/project_management/page_context.py
+++ b/skills/ppt-master/scripts/project_management/page_context.py
@@ -26,7 +26,6 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Iterable
-from .paths import CHARTS_DIR as _CHARTS_DIR
from .paths import SKILL_DIR as _SKILL_DIR
from .project_specs import (
default_spec_lock_forbidden,
@@ -39,6 +38,11 @@ from svg_to_pptx.pptx_package.template_structure import (
TemplateStructureError,
load_pptx_structure_lock,
)
+from visualization_catalog import (
+ VisualizationCatalogError,
+ VisualizationEntry,
+ resolve_visualization_reference,
+)
PAGE_CONTEXT_SCHEMA = "ppt-master.page-context.v2"
@@ -413,24 +417,43 @@ def _reference_payload(
return payload
-def _chart_reference(chart_key: str) -> tuple[dict[str, str], Path]:
- """Resolve one locked chart key to the shared Skill catalog."""
- if Path(chart_key).name != chart_key or not chart_key:
- raise PageContextError(f"invalid page_charts key: {chart_key!r}")
- chart_path = (_CHARTS_DIR / f"{chart_key}.svg").resolve()
- if not chart_path.is_file():
- raise PageContextError(
- f"page_charts key {chart_key!r} has no shared SVG reference"
+def _visualization_reference(
+ value: str,
+ *,
+ allow_legacy_bare: bool,
+) -> tuple[dict[str, str], Path, VisualizationEntry]:
+ """Resolve one current or legacy visualization reference."""
+ source_section = "page_charts" if allow_legacy_bare else "page_visualizations"
+ try:
+ entry = resolve_visualization_reference(
+ value,
+ allow_legacy_bare=allow_legacy_bare,
)
- return (
- _reference_payload(
- "chart-svg",
- chart_path,
- scope="skill",
- display_path=f"templates/charts/{chart_path.name}",
- ),
- chart_path,
+ except VisualizationCatalogError as exc:
+ raise PageContextError(
+ f"{source_section} value {value!r} cannot resolve a visualization: {exc}"
+ ) from exc
+ path = Path(entry.path).resolve()
+ try:
+ display_path = path.relative_to(_SKILL_DIR.resolve()).as_posix()
+ except ValueError as exc:
+ raise PageContextError(
+ f"{source_section} value {value!r} resolves outside the Skill: {path}"
+ ) from exc
+ payload = _reference_payload(
+ entry.kind,
+ path,
+ scope="skill",
+ display_path=display_path,
)
+ payload.update(
+ {
+ "reference": entry.reference,
+ "family": entry.family,
+ "key": entry.key,
+ }
+ )
+ return payload, path, entry
def build_page_context(project: str | Path, raw_page: str) -> PageContextResult:
@@ -475,7 +498,16 @@ def build_page_context(project: str | Path, raw_page: str) -> PageContextResult:
if rhythm is None:
rhythm = "dense"
warnings.append(f"page_rhythm has no {page}; using compatibility default dense")
- chart_key = _section_fields(lock_sections, "page_charts").get(page)
+ visualization_value = _section_fields(
+ lock_sections,
+ "page_visualizations",
+ ).get(page)
+ legacy_chart_key = _section_fields(lock_sections, "page_charts").get(page)
+ if visualization_value is not None and legacy_chart_key is not None:
+ raise PageContextError(
+ f"{page} is declared in both page_visualizations and legacy "
+ "page_charts; keep only page_visualizations"
+ )
try:
structure_lock = load_pptx_structure_lock(project_path)
except TemplateStructureError as exc:
@@ -545,10 +577,21 @@ def build_page_context(project: str | Path, raw_page: str) -> PageContextResult:
display_path=_relative_project_path(project_path, prototype_path),
)
)
- if chart_key is not None:
- chart_reference, chart_path = _chart_reference(chart_key)
- inputs.append(chart_path)
- reference_set.append(chart_reference)
+ visualization_entry: VisualizationEntry | None = None
+ selected_visualization = (
+ visualization_value
+ if visualization_value is not None
+ else legacy_chart_key
+ )
+ if selected_visualization is not None:
+ visualization_reference, visualization_path, visualization_entry = (
+ _visualization_reference(
+ selected_visualization,
+ allow_legacy_bare=visualization_value is None,
+ )
+ )
+ inputs.append(visualization_path)
+ reference_set.append(visualization_reference)
mode_fields = _section_fields(lock_sections, "mode")
visual_style_fields = _section_fields(lock_sections, "visual_style")
# Each on-demand projection includes bounded lock anchors; large reference
@@ -579,8 +622,10 @@ def build_page_context(project: str | Path, raw_page: str) -> PageContextResult:
"rhythm": rhythm,
"image_selection": image_selection,
}
- if chart_key is not None:
- current_page["chart"] = chart_key
+ if visualization_entry is not None:
+ current_page["visualization"] = visualization_entry.reference
+ if legacy_chart_key is not None:
+ current_page["chart"] = legacy_chart_key
if selected_images:
current_page["images"] = selected_images
if template is not None:
diff --git a/skills/ppt-master/scripts/project_management/project_specs.py b/skills/ppt-master/scripts/project_management/project_specs.py
index 3260e0ee..041c018e 100644
--- a/skills/ppt-master/scripts/project_management/project_specs.py
+++ b/skills/ppt-master/scripts/project_management/project_specs.py
@@ -49,6 +49,21 @@ except ImportError:
validate_communication_trace,
)
+try:
+ from visualization_catalog import (
+ VisualizationCatalogError,
+ resolve_visualization_reference,
+ )
+except ImportError:
+ import sys
+
+ if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+ from visualization_catalog import ( # type: ignore
+ VisualizationCatalogError,
+ resolve_visualization_reference,
+ )
+
TOOLS_DIR = SCRIPTS_DIR
@@ -1017,6 +1032,8 @@ def _validate_spec_lock_relations(
layouts = fields("pptx_layouts")
page_pptx_layouts = fields("page_pptx_layouts")
page_layouts = fields("page_layouts")
+ page_visualizations = fields("page_visualizations")
+ legacy_page_charts = fields("page_charts")
structure = fields("pptx_structure")
for layout_key, raw_value in layouts.items():
@@ -1059,14 +1076,52 @@ def _validate_spec_lock_relations(
f"pages {', '.join(extra)}"
)
- chart_pages = set(fields("page_charts"))
- unknown_chart_pages = sorted(chart_pages - set(rhythm))
- if unknown_chart_pages:
+ overlapping_visualization_pages = sorted(
+ set(page_visualizations) & set(legacy_page_charts)
+ )
+ if overlapping_visualization_pages:
errors.append(
- f"{markdown_name} schema: page_charts has unknown pages "
- f"{', '.join(unknown_chart_pages)}"
+ f"{markdown_name} schema: pages "
+ f"{', '.join(overlapping_visualization_pages)} are declared in both "
+ "page_visualizations and legacy page_charts; keep only "
+ "page_visualizations"
)
+ for section_id, mapping, allow_legacy_bare in (
+ ("page_visualizations", page_visualizations, False),
+ ("page_charts", legacy_page_charts, True),
+ ):
+ unknown_pages = sorted(set(mapping) - set(rhythm))
+ if unknown_pages:
+ errors.append(
+ f"{markdown_name} schema: {section_id} has unknown pages "
+ f"{', '.join(unknown_pages)}"
+ )
+ for page_key, raw_reference in mapping.items():
+ reference = _normalize_schema_value(raw_reference)
+ try:
+ entry = resolve_visualization_reference(
+ reference,
+ allow_legacy_bare=allow_legacy_bare,
+ )
+ except VisualizationCatalogError as exc:
+ errors.append(
+ f"{markdown_name} schema: {section_id}.{page_key} "
+ f"cannot resolve visualization {reference!r}: {exc}"
+ )
+ continue
+ if entry.kind != "visualization-svg":
+ errors.append(
+ f"{markdown_name} schema: {section_id}.{page_key} resolves "
+ f"to unsupported kind {entry.kind!r}"
+ )
+ asset_path = Path(entry.path)
+ if asset_path.suffix.casefold() != ".svg" or not asset_path.is_file():
+ errors.append(
+ f"{markdown_name} schema: {section_id}.{page_key} does not "
+ f"resolve to an SVG asset at {asset_path}"
+ )
+
info = get_project_info_common(str(markdown_path.parent))
format_key = str(info.get("format", "unknown"))
canvas = CANVAS_FORMATS.get(format_key)
diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.json
index dbb4555e..aec0c923 100644
--- a/skills/ppt-master/scripts/prompt_audit_manifest.json
+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json
@@ -318,7 +318,7 @@
"stage.generate.verify-charts"
],
"files": [
- "skills/ppt-master/scripts/docs/chart-recall.md"
+ "skills/ppt-master/scripts/docs/visualization-recall.md"
],
"max_tokens": 105000
},
@@ -1339,6 +1339,10 @@
"glob": "skills/ppt-master/scripts/docs/update_spec.md",
"reason": "Maintainer command reference for an optional helper script."
},
+ {
+ "glob": "skills/ppt-master/scripts/docs/chart-recall.md",
+ "reason": "Legacy compatibility note; current generation loads visualization-recall.md."
+ },
{
"glob": "skills/ppt-master/scripts/pptx_shapes/data/NOTICE.md",
"reason": "License notice; never loaded as prompt context."
diff --git a/skills/ppt-master/scripts/visualization_catalog.py b/skills/ppt-master/scripts/visualization_catalog.py
new file mode 100644
index 00000000..038fc6b9
--- /dev/null
+++ b/skills/ppt-master/scripts/visualization_catalog.py
@@ -0,0 +1,280 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Visualization Catalog Resolver
+
+Resolve chart, structure, and table references from their live family indexes.
+
+Usage:
+ Import load_visualization_entries() or resolve_visualization_reference().
+
+Examples:
+ from visualization_catalog import resolve_visualization_reference
+
+Dependencies:
+ None (only uses the standard library)
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Iterable
+
+
+_SCRIPTS_DIR = Path(__file__).resolve().parent
+_TEMPLATES_DIR = _SCRIPTS_DIR.parent / "templates"
+_KEY_RE = re.compile(r"^[a-z0-9]+(?:_[a-z0-9]+)*$")
+_FAMILY_SPECS = {
+ "chart": ("charts", "charts_index.json", "charts"),
+ "structure": ("structures", "structures_index.json", "structures"),
+ "table": ("tables", "tables_index.json", "tables"),
+}
+
+
+class VisualizationCatalogError(RuntimeError):
+ """Reject an unreadable, malformed, missing, or ambiguous reference."""
+
+
+@dataclass(frozen=True)
+class VisualizationEntry:
+ """One canonical family catalog entry and its SVG asset."""
+
+ family: str
+ key: str
+ summary: str
+ path: Path
+
+ @property
+ def kind(self) -> str:
+ """Return the page-context reference kind."""
+ return "visualization-svg"
+
+ @property
+ def reference(self) -> str:
+ """Return the canonical ``family/key`` reference."""
+ return f"{self.family}/{self.key}"
+
+ @property
+ def display_path(self) -> str:
+ """Return the Skill-relative SVG path."""
+ return self.path.relative_to(_SCRIPTS_DIR.parent).as_posix()
+
+
+@dataclass(frozen=True)
+class VisualizationCatalog:
+ """Canonical entries plus family-local compatibility aliases."""
+
+ entries: dict[str, VisualizationEntry]
+ aliases: dict[str, str]
+
+
+def visualization_families() -> tuple[str, ...]:
+ """Return the stable visualization family order."""
+ return tuple(_FAMILY_SPECS)
+
+
+def _normalize_families(families: Iterable[str] | None) -> tuple[str, ...]:
+ requested = visualization_families() if families is None else tuple(families)
+ normalized: list[str] = []
+ for raw_family in requested:
+ family = str(raw_family).strip().casefold()
+ if family not in _FAMILY_SPECS:
+ allowed = ", ".join(visualization_families())
+ raise VisualizationCatalogError(
+ f"unknown visualization family {raw_family!r}; expected one of {allowed}"
+ )
+ if family not in normalized:
+ normalized.append(family)
+ if not normalized:
+ raise VisualizationCatalogError("at least one visualization family is required")
+ return tuple(normalized)
+
+
+def _load_family(family: str) -> tuple[dict[str, VisualizationEntry], dict[str, str]]:
+ directory_name, index_name, object_key = _FAMILY_SPECS[family]
+ family_dir = _TEMPLATES_DIR / directory_name
+ index_path = family_dir / index_name
+ try:
+ payload = json.loads(index_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise VisualizationCatalogError(
+ f"cannot read {family} catalog {index_path}: {exc}"
+ ) from exc
+ if not isinstance(payload, dict):
+ raise VisualizationCatalogError(f"{family} catalog root must be an object")
+ raw_entries = payload.get(object_key)
+ if not isinstance(raw_entries, dict):
+ raise VisualizationCatalogError(
+ f"{family} catalog {index_path} has no '{object_key}' object"
+ )
+
+ entries: dict[str, VisualizationEntry] = {}
+ for raw_key, raw_item in raw_entries.items():
+ if (
+ not isinstance(raw_key, str)
+ or _KEY_RE.fullmatch(raw_key) is None
+ or not isinstance(raw_item, dict)
+ ):
+ raise VisualizationCatalogError(
+ f"{family} catalog entry {raw_key!r} is malformed"
+ )
+ summary = raw_item.get("summary")
+ if not isinstance(summary, str) or not summary.strip():
+ raise VisualizationCatalogError(
+ f"{family} catalog entry {raw_key!r} has no non-empty summary"
+ )
+ entry = VisualizationEntry(
+ family=family,
+ key=raw_key,
+ summary=summary.strip(),
+ path=(family_dir / f"{raw_key}.svg").resolve(),
+ )
+ entries[entry.reference] = entry
+
+ raw_aliases = payload.get("aliases", {})
+ if not isinstance(raw_aliases, dict):
+ raise VisualizationCatalogError(f"{family} catalog aliases must be an object")
+ aliases: dict[str, str] = {}
+ for raw_alias, raw_target in raw_aliases.items():
+ if (
+ not isinstance(raw_alias, str)
+ or _KEY_RE.fullmatch(raw_alias) is None
+ or not isinstance(raw_target, str)
+ or _KEY_RE.fullmatch(raw_target) is None
+ ):
+ raise VisualizationCatalogError(
+ f"{family} catalog alias {raw_alias!r} is malformed"
+ )
+ target_reference = f"{family}/{raw_target}"
+ if raw_alias in raw_entries:
+ raise VisualizationCatalogError(
+ f"{family} alias {raw_alias!r} collides with a canonical key"
+ )
+ if target_reference not in entries:
+ raise VisualizationCatalogError(
+ f"{family} alias {raw_alias!r} targets missing key {raw_target!r}"
+ )
+ aliases[f"{family}/{raw_alias}"] = target_reference
+ return entries, aliases
+
+
+def load_visualization_catalog(
+ families: Iterable[str] | None = None,
+ *,
+ allow_missing_families: bool = False,
+) -> VisualizationCatalog:
+ """Load selected live family registries."""
+ selected = _normalize_families(families)
+ entries: dict[str, VisualizationEntry] = {}
+ aliases: dict[str, str] = {}
+ for family in selected:
+ directory_name, index_name, _object_key = _FAMILY_SPECS[family]
+ index_path = _TEMPLATES_DIR / directory_name / index_name
+ if not index_path.is_file() and allow_missing_families:
+ continue
+ family_entries, family_aliases = _load_family(family)
+ entries.update(family_entries)
+ aliases.update(family_aliases)
+ if not entries:
+ shown = ", ".join(selected)
+ raise VisualizationCatalogError(
+ f"no visualization entries are available for family selection {shown}"
+ )
+ return VisualizationCatalog(entries=entries, aliases=aliases)
+
+
+def load_visualization_entries(
+ families: Iterable[str] | None = None,
+ *,
+ allow_missing_families: bool = False,
+) -> dict[str, VisualizationEntry]:
+ """Return canonical entries keyed by ``family/key``."""
+ return load_visualization_catalog(
+ families,
+ allow_missing_families=allow_missing_families,
+ ).entries
+
+
+def _require_svg(entry: VisualizationEntry) -> VisualizationEntry:
+ if entry.path.suffix.casefold() != ".svg" or not entry.path.is_file():
+ raise VisualizationCatalogError(
+ f"{entry.reference!r} has no SVG asset at {entry.path}"
+ )
+ return entry
+
+
+def resolve_visualization_reference(
+ value: str,
+ *,
+ allow_legacy_bare: bool = False,
+) -> VisualizationEntry:
+ """Resolve one canonical ``family/key`` or supported legacy bare key."""
+ normalized = str(value).strip().casefold()
+ if not normalized:
+ raise VisualizationCatalogError("visualization reference must not be empty")
+
+ catalog = load_visualization_catalog(allow_missing_families=True)
+ if "/" in normalized:
+ family, separator, key = normalized.partition("/")
+ if (
+ not separator
+ or family not in _FAMILY_SPECS
+ or _KEY_RE.fullmatch(key) is None
+ or "/" in key
+ ):
+ raise VisualizationCatalogError(
+ f"invalid canonical visualization reference {value!r}"
+ )
+ reference = f"{family}/{key}"
+ entry = catalog.entries.get(reference)
+ if entry is None:
+ if reference in catalog.aliases:
+ raise VisualizationCatalogError(
+ f"{value!r} is a legacy alias; use {catalog.aliases[reference]!r}"
+ )
+ raise VisualizationCatalogError(
+ f"canonical visualization reference {value!r} is not registered"
+ )
+ return _require_svg(entry)
+
+ if not allow_legacy_bare:
+ raise VisualizationCatalogError(
+ f"{value!r} must use canonical family/key grammar"
+ )
+ if _KEY_RE.fullmatch(normalized) is None:
+ raise VisualizationCatalogError(f"invalid legacy visualization key {value!r}")
+
+ matches = [
+ entry
+ for entry in catalog.entries.values()
+ if entry.key == normalized
+ ]
+ for alias_reference, target_reference in catalog.aliases.items():
+ _, alias = alias_reference.split("/", 1)
+ if alias == normalized:
+ matches.append(catalog.entries[target_reference])
+ unique_matches = {entry.reference: entry for entry in matches}
+ if not unique_matches:
+ raise VisualizationCatalogError(
+ f"legacy visualization key {value!r} is not registered"
+ )
+ if len(unique_matches) > 1:
+ candidates = ", ".join(sorted(unique_matches))
+ raise VisualizationCatalogError(
+ f"legacy visualization key {value!r} is ambiguous across {candidates}"
+ )
+ return _require_svg(next(iter(unique_matches.values())))
+
+
+if __name__ == "__main__":
+ from console_encoding import configure_utf8_stdio
+
+ configure_utf8_stdio()
+ print(
+ "Use visualization_catalog via visualization_recall.py or project_manager.py.",
+ file=sys.stderr,
+ )
+ raise SystemExit(2)
diff --git a/skills/ppt-master/scripts/visualization_recall.py b/skills/ppt-master/scripts/visualization_recall.py
new file mode 100644
index 00000000..3b31d2e1
--- /dev/null
+++ b/skills/ppt-master/scripts/visualization_recall.py
@@ -0,0 +1,431 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Visualization Candidate Recall
+
+Recall a deterministic chart, structure, or table shortlist from semantic tags,
+or validate selected references against the live family catalogs.
+
+Usage:
+ python3 scripts/visualization_recall.py recall --page P03 --tag "time series" --tag "three metrics" --tag "trend"
+ python3 scripts/visualization_recall.py validate chart/line_chart structure/hub_spoke
+
+Examples:
+ python3 scripts/visualization_recall.py recall --page P07 --family structure \
+ --tag "named quadrants" --tag "bullet lists" --tag "SWOT" --limit 6
+ python3 scripts/visualization_recall.py validate table/basic_table
+
+Dependencies:
+ None (only uses the standard library)
+
+See scripts/docs/visualization-recall.md for the planning workflow and output contract.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+import unicodedata
+from typing import Optional
+
+from console_encoding import configure_utf8_stdio
+from visualization_catalog import (
+ VisualizationCatalogError,
+ VisualizationEntry,
+ load_visualization_entries,
+ resolve_visualization_reference,
+ visualization_families,
+)
+
+configure_utf8_stdio()
+
+_TOKEN_RE = re.compile(r"[a-z0-9]+")
+_PAGE_RE = re.compile(r"^P\d{2,}$")
+_SKIP_RE = re.compile(r"\bskip\s+(?:if|for)\b", re.IGNORECASE)
+_STOP_WORDS = {
+ "a",
+ "an",
+ "and",
+ "as",
+ "at",
+ "by",
+ "for",
+ "from",
+ "if",
+ "in",
+ "into",
+ "of",
+ "on",
+ "or",
+ "per",
+ "the",
+ "to",
+ "use",
+ "with",
+}
+
+
+def _normalize(text: str) -> str:
+ normalized = unicodedata.normalize("NFKC", text).casefold().replace("_", " ")
+ return " ".join(_TOKEN_RE.findall(normalized))
+
+
+def _stem(token: str) -> str:
+ if len(token) > 5 and token.endswith("ies"):
+ return token[:-3] + "y"
+ if len(token) > 5 and token.endswith("ing"):
+ return token[:-3]
+ if len(token) > 4 and token.endswith("ed"):
+ return token[:-2]
+ if len(token) > 4 and token.endswith("es"):
+ return token[:-2]
+ if len(token) > 3 and token.endswith("s"):
+ return token[:-1]
+ return token
+
+
+def _tokens(text: str) -> set[str]:
+ return {
+ _stem(token)
+ for token in _TOKEN_RE.findall(_normalize(text))
+ if token not in _STOP_WORDS
+ }
+
+
+def _selected_families(family: str) -> tuple[str, ...]:
+ return visualization_families() if family == "all" else (family,)
+
+
+def load_catalog(family: str = "all") -> dict[str, VisualizationEntry]:
+ """Load the selected live family catalogs."""
+ return load_visualization_entries(
+ _selected_families(family),
+ allow_missing_families=family == "all",
+ )
+
+
+def _score_candidate(
+ key: str,
+ summary: str,
+ tags: list[str],
+) -> tuple[int, list[str]]:
+ skip_match = _SKIP_RE.search(summary)
+ if skip_match is None:
+ pick_clause, skip_clause = summary, ""
+ else:
+ pick_clause = summary[:skip_match.start()]
+ skip_clause = summary[skip_match.start():]
+ key_text = _normalize(key)
+ pick_text = _normalize(pick_clause)
+ skip_text = _normalize(skip_clause)
+ key_tokens = _tokens(key)
+ pick_tokens = _tokens(pick_clause)
+ skip_tokens = _tokens(skip_clause)
+ score = 0
+ matched_tags: list[str] = []
+
+ for tag in tags:
+ tag_text = _normalize(tag)
+ tag_tokens = _tokens(tag)
+ positive_score = 0
+ negative_score = 0
+ if tag_text and tag_text in key_text:
+ positive_score += 20
+ elif tag_text and tag_text in pick_text:
+ positive_score += 14
+ if tag_text and tag_text in skip_text:
+ negative_score += 12
+
+ for token in tag_tokens:
+ if token in key_tokens:
+ positive_score += 9
+ elif token in pick_tokens:
+ positive_score += 5
+ if token in skip_tokens:
+ negative_score += 6
+
+ if positive_score:
+ matched_tags.append(tag)
+ score += positive_score - negative_score
+
+ return score, matched_tags
+
+
+def _candidate_payload(
+ entry: VisualizationEntry,
+ score: int,
+ matched_tags: list[str],
+ *,
+ legacy_output: bool,
+) -> dict[str, object]:
+ payload: dict[str, object] = {
+ "key": entry.key,
+ "path": entry.display_path,
+ "summary": entry.summary,
+ "score": score,
+ "matched_tags": matched_tags,
+ }
+ if not legacy_output:
+ payload.update(
+ {
+ "family": entry.family,
+ "reference": entry.reference,
+ }
+ )
+ return payload
+
+
+def recall_candidates(
+ page: str,
+ tags: list[str],
+ limit: int,
+ *,
+ family: str = "all",
+ force_semantic_fallback: bool = False,
+ legacy_output: bool = False,
+) -> dict[str, object]:
+ """Recall a deterministic shortlist for one page."""
+ entries = load_catalog(family)
+ scored: list[tuple[int, VisualizationEntry, list[str]]] = []
+ for entry in entries.values():
+ score, matched_tags = _score_candidate(entry.key, entry.summary, tags)
+ if score > 0 and matched_tags:
+ scored.append((score, entry, matched_tags))
+ scored.sort(key=lambda item: (-item[0], item[1].family, item[1].key))
+
+ candidates = [
+ _candidate_payload(
+ entry,
+ score,
+ matched_tags,
+ legacy_output=legacy_output,
+ )
+ for score, entry, matched_tags in scored[:limit]
+ ]
+
+ top_score = candidates[0]["score"] if candidates else 0
+ if top_score >= 35:
+ confidence = "high"
+ elif top_score >= 15:
+ confidence = "medium"
+ elif top_score > 0:
+ confidence = "low"
+ else:
+ confidence = "none"
+
+ fallback_required_before_no_match = (
+ confidence in {"low", "none"} and not force_semantic_fallback
+ )
+ if fallback_required_before_no_match:
+ no_match_instruction = (
+ f"Lexical confidence is {confidence}. Select a bounded candidate when one "
+ "fits; otherwise rerun the same recall with --semantic-fallback before "
+ "keeping no-template-match. Keep the final negative result out of Design "
+ "Spec Section VII and describe the chosen fallback in the page's Section "
+ "IX block."
+ )
+ else:
+ no_match_instruction = (
+ "Use when none of the reviewed candidates fits the page structure. Keep "
+ "this result out of Design Spec Section VII and describe the chosen fallback "
+ "in the page's Section IX block."
+ )
+
+ result: dict[str, object] = {
+ "page": page,
+ "semantic_tags": tags,
+ "confidence": confidence,
+ "candidates": candidates,
+ "no_template_match": {
+ "allowed": not fallback_required_before_no_match,
+ "key": "no-template-match",
+ "instruction": no_match_instruction,
+ },
+ }
+ if not legacy_output:
+ result["family_filter"] = family
+ if force_semantic_fallback:
+ if legacy_output:
+ catalog: object = {
+ entry.key: entry.summary
+ for entry in sorted(entries.values(), key=lambda item: item.key)
+ }
+ else:
+ catalog = {
+ entry.reference: {
+ "family": entry.family,
+ "key": entry.key,
+ "path": entry.display_path,
+ "summary": entry.summary,
+ }
+ for entry in sorted(
+ entries.values(),
+ key=lambda item: (item.family, item.key),
+ )
+ }
+ result["semantic_fallback"] = {
+ "reason": "requested-after-bounded-review",
+ "instruction": (
+ "Semantically compare the page tags with every returned selection rule. "
+ "Choose one exact catalog reference or keep no-template-match; lexical "
+ "overlap is not required in this review."
+ ),
+ "reference_pattern": "family/key",
+ "catalog": catalog,
+ }
+ return result
+
+
+def _dedupe(values: list[str]) -> list[str]:
+ result: list[str] = []
+ seen: set[str] = set()
+ for value in values:
+ stripped = value.strip()
+ normalized = _normalize(stripped)
+ if not stripped or not normalized or normalized in seen:
+ continue
+ seen.add(normalized)
+ result.append(stripped)
+ return result
+
+
+def _run_recall(args: argparse.Namespace) -> int:
+ page = args.page.upper()
+ if not _PAGE_RE.fullmatch(page):
+ print("Error: --page must match P<NN>, for example P03.", file=sys.stderr)
+ return 2
+
+ tags = _dedupe(args.tag)
+ if not 3 <= len(tags) <= 8:
+ print("Error: recall requires 3-8 distinct non-empty --tag values.", file=sys.stderr)
+ return 2
+
+ result = recall_candidates(
+ page,
+ tags,
+ args.limit,
+ family=args.family,
+ force_semantic_fallback=args.semantic_fallback,
+ legacy_output=args.legacy_output,
+ )
+ print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
+ return 0
+
+
+def _resolve_validation_value(raw: str, family: str) -> VisualizationEntry:
+ if "/" in raw:
+ return resolve_visualization_reference(raw)
+ if family != "all":
+ return resolve_visualization_reference(f"{family}/{raw}")
+ return resolve_visualization_reference(raw, allow_legacy_bare=True)
+
+
+def _run_validate(args: argparse.Namespace) -> int:
+ selected = _dedupe(args.keys)
+ invalid: list[str] = []
+ valid_entries: list[tuple[str, VisualizationEntry]] = []
+ for value in selected:
+ try:
+ valid_entries.append((value, _resolve_validation_value(value, args.family)))
+ except VisualizationCatalogError:
+ invalid.append(value)
+
+ if args.legacy_output:
+ valid: object = sorted(raw for raw, _entry in valid_entries)
+ else:
+ valid = [
+ {
+ "family": entry.family,
+ "key": entry.key,
+ "path": entry.display_path,
+ "reference": entry.reference,
+ }
+ for _raw, entry in sorted(
+ valid_entries,
+ key=lambda item: (item[1].family, item[1].key),
+ )
+ ]
+ result = {"invalid": sorted(invalid), "valid": valid}
+ print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
+ if invalid:
+ mapping_name = "page_charts" if args.legacy_output else "page_visualizations"
+ print(
+ "Error: replace each invalid reference with one returned by recall, or "
+ f"keep no-template-match out of Section VII and {mapping_name} while "
+ "recording the custom fallback in the page's Section IX block.",
+ file=sys.stderr,
+ )
+ return 1
+ return 0
+
+
+def _add_family_argument(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "--family",
+ choices=("all",) + visualization_families(),
+ default="all",
+ help="Limit candidates to one family (default: all).",
+ )
+
+
+def build_parser(*, legacy_output: bool = False) -> argparse.ArgumentParser:
+ description = (
+ "Recall legacy chart-catalog candidates or validate selected keys."
+ if legacy_output
+ else "Recall visualization candidates or validate selected references."
+ )
+ parser = argparse.ArgumentParser(
+ description=description,
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.set_defaults(legacy_output=legacy_output)
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ recall = subparsers.add_parser("recall", help="Recall candidates for one page.")
+ recall.add_argument("--page", required=True, help="Planned page key, for example P03.")
+ recall.add_argument(
+ "--tag",
+ action="append",
+ required=True,
+ help="English semantic content-shape tag; repeat 3-8 times.",
+ )
+ recall.add_argument(
+ "--limit",
+ type=int,
+ choices=range(3, 9),
+ default=6,
+ metavar="3..8",
+ help="Candidate count (default: 6).",
+ )
+ recall.add_argument(
+ "--semantic-fallback",
+ action="store_true",
+ help="Include the selected live catalogs after a low-confidence review.",
+ )
+ _add_family_argument(recall)
+ recall.set_defaults(handler=_run_recall)
+
+ validate = subparsers.add_parser("validate", help="Validate selected references.")
+ validate.add_argument("keys", nargs="+", help="One or more keys or family/key references.")
+ _add_family_argument(validate)
+ validate.set_defaults(handler=_run_validate)
+ return parser
+
+
+def main(
+ argv: Optional[list[str]] = None,
+ *,
+ legacy_output: bool = False,
+) -> int:
+ parser = build_parser(legacy_output=legacy_output)
+ args = parser.parse_args(argv)
+ try:
+ return args.handler(args)
+ except VisualizationCatalogError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/templates/schemas/spec_lock.schema.json b/skills/ppt-master/templates/schemas/spec_lock.schema.json
index bba03902..60699797 100644
--- a/skills/ppt-master/templates/schemas/spec_lock.schema.json
+++ b/skills/ppt-master/templates/schemas/spec_lock.schema.json
@@ -62,6 +62,7 @@
"pptx_layouts": {"type": "object"},
"page_pptx_layouts": {"type": "object"},
"page_layouts": {"type": "object"},
+ "page_visualizations": {"type": "object"},
"page_charts": {"type": "object"},
"forbidden": {"type": "string"}
},
@@ -223,17 +224,21 @@
"entry_key_pattern": "^P[0-9]{2,}$",
"value_pattern": "^[A-Za-z0-9._-]+$"
},
+ {
+ "id": "page_visualizations",
+ "pattern": "^page_visualizations$",
+ "required": false,
+ "min_entries": 1,
+ "entry_key_pattern": "^P[0-9]{2,}$",
+ "value_pattern": "^(?:chart|structure|table)/[a-z0-9]+(?:_[a-z0-9]+)*$"
+ },
{
"id": "page_charts",
"pattern": "^page_charts$",
"required": false,
"min_entries": 1,
"entry_key_pattern": "^P[0-9]{2,}$",
- "value_catalog": {
- "path": "../charts/charts_index.json",
- "pointer": ["charts"],
- "asset_path_pattern": "../charts/{value}.svg"
- }
+ "value_pattern": "^[a-z0-9]+(?:_[a-z0-9]+)*$"
},
{"id": "forbidden", "pattern": "^forbidden$", "required": true, "min_body_chars": 1}
],
diff --git a/skills/ppt-master/templates/spec_lock_reference.md b/skills/ppt-master/templates/spec_lock_reference.md
index 28a368e3..0e2cc8a7 100644
--- a/skills/ppt-master/templates/spec_lock_reference.md
+++ b/skills/ppt-master/templates/spec_lock_reference.md
@@ -29,7 +29,8 @@ After Generate Step 4 Gate 1, read the completed Design Spec and current page/re
| `pptx_structure` | `mode` | Values: `flat`, `structured` |
| `forbidden` | Literal list items | General standards stay in their owning reference |
-Optional data sections: `images`, `page_charts`.
+Optional data sections: `images`, `page_visualizations`. Existing locks may
+retain legacy `page_charts`; never write both sections for the same page.
The required universal block is:
@@ -70,7 +71,24 @@ Structured section value shapes:
- P01: 03_content
```
-Project each §VII `Page | Template | Usage` row's first two fields into `page_charts`; Usage stays in the Design Spec. This is a page-local reference, not a type/geometry lock. Keys must exist in `charts/charts_index.json`; no-match stays in §IX.
+Project each §VII `Page | Family | Template | Usage` row's Page, Family, and
+Template fields into `page_visualizations` as `<family>/<key>`; Usage stays in
+the Design Spec. The families are `chart`, `structure`, and `table`. This is a
+page-local reference, not a type/geometry lock. The family/key must resolve
+through its live family registry to one SVG; no-match stays in §IX.
+
+```markdown
+## page_visualizations
+- P03: chart/line_chart
+- P06: structure/hub_spoke
+- P09: table/basic_table
+```
+
+**Legacy compatibility**: existing `page_charts` rows keep their bare keys.
+Validation resolves each bare key only when it has one unambiguous match across
+the three live family registries and their declared aliases. New locks write
+`page_visualizations`. A page present in both sections is a conflict, even when
+both values resolve to the same SVG.
Typography projection excludes Character/upgrade References:
@@ -96,7 +114,12 @@ New locks always write `title_family` and `body_family`, even when their values
- Custom reference grammar: comma-separated exact catalog ids with no duplicates. Reference fields are valid only for `custom`; omit them for a genuinely novel direction.
- `stroke_width` grammar: `1.5`, `2`, or `3`; present only for `tabler-outline`.
- `page_rhythm` grammar: `P` + at least two digits (`P01`, `P100`) followed by `anchor|dense|breathing`.
-- `page_charts` grammar: `P` + at least two digits followed by a `charts_index` key; the key and `<key>.svg` must both exist.
+- `page_visualizations` grammar: `P` + at least two digits followed by
+ `chart|structure|table`, `/`, and one canonical visualization key; the
+ family/key must resolve to one SVG through the matching live index.
+- Legacy `page_charts` grammar: `P` + at least two digits followed by one bare
+ key; it must resolve uniquely across the three live family registries and
+ their declared aliases. Never add this section to a new lock.
- `pptx_masters` grammar: `<master_key>: <PowerPoint picker name>`.
- `pptx_layouts` grammar: `<layout_key>: <master_key> | <PowerPoint layout name> | <prototype source>`.
- `page_pptx_layouts` grammar: `P` + at least two digits followed by a declared Layout key.