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(planning): add versioned spec scaffolds and chart recall
hugohe3a2e6a8336310
diff --git a/skills/ppt-master/scripts/chart_recall.py b/skills/ppt-master/scripts/chart_recall.pynew file mode 100644index 00000000..719ee7c4--- /dev/null+++ b/skills/ppt-master/scripts/chart_recall.py@@ -0,0 +1,299 @@+#!/usr/bin/env python3+"""+PPT Master - Chart Candidate Recall++Recalls a deterministic chart-template shortlist from page-shape semantic tags,+or validates selected chart keys against the live chart catalog.++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++Dependencies:+ None (only uses standard library)++See scripts/docs/chart-recall.md for the Strategist workflow and output contract.+"""++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) -> 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"++ return {+ "page": page,+ "semantic_tags": tags,+ "confidence": confidence,+ "candidates": candidates,+ "no_template_match": {+ "allowed": True,+ "key": "no-template-match",+ "instruction": "Use when every candidate conflicts with the page content shape or a Skip clause.",+ },+ }+++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)+ 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 record no-template-match without a page_charts entry.",+ 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.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+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/project_manager.py b/skills/ppt-master/scripts/project_manager.pyindex 672f06f7..ac3c3db0 100644--- a/skills/ppt-master/scripts/project_manager.py+++ b/skills/ppt-master/scripts/project_manager.py@@ -4,6 +4,8 @@Usage:python3 scripts/project_manager.py init <project_name> [--format ppt169] [--dir <path>]python3 scripts/project_manager.py import-sources <project_path> <source1> [<source2> ...] [--move | --copy]+ python3 scripts/project_manager.py scaffold-spec <project_path>+ python3 scripts/project_manager.py scaffold-lock <project_path>python3 scripts/project_manager.py validate <project_path>python3 scripts/project_manager.py info <project_path>"""@@ -23,6 +25,7 @@ from pathlib import Pathfrom urllib.parse import urlparsefrom console_encoding import configure_utf8_stdio+from project_specs import scaffold_project_artifact, validate_project_artifactstry:from project_utils import (@@ -115,6 +118,10 @@ class ProjectManager:def __init__(self, base_dir: str | Path | None = None) -> None:self.base_dir = Path(base_dir) if base_dir is not None else Path.cwd() / "projects"+ def scaffold_artifact(self, project_path: str, artifact: str) -> str:+ """Delegate deterministic Markdown scaffold rendering."""+ return scaffold_project_artifact(Path(project_path), artifact)+def init_project(self,project_name: str,@@ -844,7 +851,19 @@ class ProjectManager:def validate_project(self, project_path: str) -> tuple[bool, list[str], list[str]]:project_path_obj = Path(project_path)- is_valid, errors, warnings = validate_project_structure(str(project_path_obj))+ _, errors, warnings = validate_project_structure(+ str(project_path_obj),+ validate_communication=False,+ )++ if project_path_obj.exists() and project_path_obj.is_dir():+ project_info = get_project_info_common(str(project_path_obj))+ artifact_errors, artifact_warnings = validate_project_artifacts(+ project_path_obj,+ project_info,+ )+ errors.extend(artifact_errors)+ warnings.extend(artifact_warnings)if project_path_obj.exists() and project_path_obj.is_dir():info = get_project_info_common(str(project_path_obj))@@ -855,7 +874,7 @@ class ProjectManager:expected_format = Nonewarnings.extend(validate_svg_viewbox(svg_files, expected_format))- return is_valid, errors, warnings+ return not errors, list(dict.fromkeys(errors)), warningsdef get_project_info(self, project_path: str) -> dict[str, object]:shared = get_project_info_common(project_path)@@ -880,6 +899,8 @@ def build_parser() -> argparse.ArgumentParser:epilog="""Examples:python3 scripts/project_manager.py init demo --format ppt169python3 scripts/project_manager.py import-sources projects/demo file.md --move+ python3 scripts/project_manager.py scaffold-spec projects/demo_ppt169_20260718+ python3 scripts/project_manager.py scaffold-lock projects/demo_ppt169_20260718python3 scripts/project_manager.py validate projects/demopython3 scripts/project_manager.py info projects/demo""",@@ -901,6 +922,18 @@ def build_parser() -> argparse.ArgumentParser:mode.add_argument("--move", action="store_true", help="Move local source files")mode.add_argument("--copy", action="store_true", help="Copy local source files")+ scaffold_spec = subparsers.add_parser(+ "scaffold-spec",+ help="Create design_spec.md from the versioned scaffold",+ )+ scaffold_spec.add_argument("project_path", help="Project directory")++ scaffold_lock = subparsers.add_parser(+ "scaffold-lock",+ help="Create spec_lock.md from the versioned scaffold",+ )+ scaffold_lock.add_argument("project_path", help="Project directory")+validate = subparsers.add_parser("validate", help="Validate a project directory")validate.add_argument("project_path", help="Project directory")@@ -963,6 +996,16 @@ def main(argv: list[str] | None = None) -> int:print(f" - {item}")return 0+ if args.command == "scaffold-spec":+ artifact_path = manager.scaffold_artifact(args.project_path, "design_spec")+ print(f"[OK] Design spec scaffold created: {artifact_path}")+ return 0++ if args.command == "scaffold-lock":+ artifact_path = manager.scaffold_artifact(args.project_path, "spec_lock")+ print(f"[OK] Execution lock scaffold created: {artifact_path}")+ return 0+if args.command == "validate":project_path = args.project_pathis_valid, errors, warnings = manager.validate_project(project_path)diff --git a/skills/ppt-master/scripts/project_specs.py b/skills/ppt-master/scripts/project_specs.pynew file mode 100644index 00000000..8d19bb86--- /dev/null+++ b/skills/ppt-master/scripts/project_specs.py@@ -0,0 +1,976 @@+#!/usr/bin/env python3+"""+PPT Master - Project Specification Helpers++Scaffold and validate the Markdown planning artifacts used by project_manager.py.+The module keeps schema parsing and deterministic scaffold rendering independent+from the broader project-management command surface.++Usage:+ Import validate_project_artifacts() or scaffold_project_artifact().++Examples:+ from project_specs import validate_markdown_schema++Dependencies:+ None (only uses the standard library and local project_utils.py)+"""++from __future__ import annotations++import json+import re+from pathlib import Path+from typing import Mapping++try:+ from project_utils import (+ CANVAS_FORMATS,+ get_project_info as get_project_info_common,+ validate_communication_trace,+ )+except ImportError:+ import sys++ tools_dir = Path(__file__).resolve().parent+ if str(tools_dir) not in sys.path:+ sys.path.insert(0, str(tools_dir))+ from project_utils import ( # type: ignore+ CANVAS_FORMATS,+ get_project_info as get_project_info_common,+ validate_communication_trace,+ )+++TOOLS_DIR = Path(__file__).resolve().parent+SKILL_DIR = TOOLS_DIR.parent+SCHEMA_DIR = SKILL_DIR / "templates" / "schemas"+SCAFFOLD_DIR = SKILL_DIR / "templates" / "scaffolds"++_MARKDOWN_H2_RE = re.compile(r"^##[ \t]+(.+?)[ \t]*$", re.MULTILINE)+_MARKDOWN_SUBHEADING_RE = re.compile(r"^#{3,6}[ \t]+(.+?)[ \t]*$", re.MULTILINE)+_MARKDOWN_DATA_LINE_RE = re.compile(+ r"^[ \t]*-[ \t]+(?:\*\*)?([^:\n*]+?)(?:\*\*)?[ \t]*:[ \t]*(.*)$",+ re.MULTILINE,+)+_SCAFFOLD_TOKEN_RE = re.compile(r"\{\{[A-Z_]+\}\}")+_SCHEMA_MARKER_RE = re.compile(+ r"^<!--[ \t]+ppt-master-schema:[ \t]*([a-z0-9-]+/v[1-9][0-9]*)[ \t]+-->$",+ re.IGNORECASE,+)+++def _normalize_schema_value(value: str) -> str:+ """Normalize a Markdown scalar before enum, pattern, and catalog checks."""+ normalized = value.strip()+ if (+ len(normalized) >= 2+ and normalized[0] == normalized[-1]+ and normalized[0] in "'\"`"+ ):+ return normalized[1:-1].strip()+ return normalized+++def _extract_schema_marker(text: str) -> tuple[str | None, str | None]:+ """Read the optional version marker from the first non-empty line."""+ first_line = next((line.strip() for line in text.splitlines() if line.strip()), "")+ if not first_line.startswith("<!--") or "ppt-master-schema:" not in first_line:+ return None, None+ match = _SCHEMA_MARKER_RE.fullmatch(first_line)+ if match is None:+ return None, "has a malformed ppt-master-schema marker"+ return match.group(1).casefold(), None+++def _parse_markdown_sections(+ text: str,+ *,+ report_duplicate_fields: bool,+) -> tuple[list[dict[str, object]], list[str]]:+ """Parse H2 sections, data lines, and nested headings from Markdown."""+ headings = list(_MARKDOWN_H2_RE.finditer(text))+ sections: list[dict[str, object]] = []+ errors: list[str] = []++ for index, heading_match in enumerate(headings):+ body_start = heading_match.end()+ body_end = headings[index + 1].start() if index + 1 < len(headings) else len(text)+ body = text[body_start:body_end]+ fields: dict[str, str] = {}+ field_names: dict[str, str] = {}++ for field_match in _MARKDOWN_DATA_LINE_RE.finditer(body):+ field_name = field_match.group(1).strip()+ field_key = field_name+ if field_key in fields and report_duplicate_fields:+ errors.append(+ f"section '{heading_match.group(1).strip()}' repeats data key "+ f"'{field_name}'"+ )+ continue+ fields[field_key] = field_match.group(2).strip()+ field_names[field_key] = field_name++ sections.append(+ {+ "heading": heading_match.group(1).strip(),+ "offset": heading_match.start(),+ "body": body,+ "fields": fields,+ "field_names": field_names,+ "subheadings": [+ match.group(1).strip()+ for match in _MARKDOWN_SUBHEADING_RE.finditer(body)+ ],+ }+ )++ return sections, errors+++def _load_markdown_schema(schema_path: Path) -> dict[str, object]:+ """Load and sanity-check one versioned Markdown schema."""+ with schema_path.open("r", encoding="utf-8") as stream:+ schema = json.load(stream)+ contract = schema.get("x-markdown")+ if not isinstance(contract, dict):+ raise ValueError(f"Schema is missing x-markdown: {schema_path}")+ if contract.get("version") != 1:+ raise ValueError(f"Unsupported Markdown schema version: {schema_path}")+ return schema+++def _catalog_values(+ schema_path: Path,+ value_catalog: Mapping[str, object],+) -> tuple[Path, dict[str, object]]:+ """Resolve a schema-declared JSON catalog and object pointer."""+ relative_path = value_catalog.get("path")+ pointer = value_catalog.get("pointer", [])+ if not isinstance(relative_path, str) or not isinstance(pointer, list):+ raise ValueError("value_catalog requires string path and list pointer")++ catalog_path = (schema_path.parent / relative_path).resolve()+ with catalog_path.open("r", encoding="utf-8") as stream:+ node: object = json.load(stream)+ for pointer_part in pointer:+ if not isinstance(node, dict):+ raise ValueError(f"pointer enters a non-object at '{pointer_part}'")+ node = node[str(pointer_part)]+ if not isinstance(node, dict):+ raise ValueError("catalog pointer does not resolve to an object")+ return catalog_path, node+++def _validate_catalog_values(+ *,+ markdown_name: str,+ section_id: str,+ fields: Mapping[str, object],+ schema_path: Path,+ value_catalog: Mapping[str, object],+) -> list[str]:+ """Validate catalog membership and any schema-declared asset path."""+ errors: list[str] = []+ relative_path = value_catalog.get("path")+ try:+ catalog_path, catalog = _catalog_values(schema_path, value_catalog)+ except (OSError, KeyError, UnicodeError, json.JSONDecodeError, ValueError) as exc:+ return [+ f"{markdown_name} schema: cannot read value catalog "+ f"'{relative_path}': {exc}"+ ]++ asset_pattern = value_catalog.get("asset_path_pattern")+ for field_value in fields.values():+ value = _normalize_schema_value(str(field_value))+ if value not in catalog:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' value '{value}' "+ f"is absent from {catalog_path.name}"+ )+ continue+ if not isinstance(asset_pattern, str):+ continue+ try:+ relative_asset_path = asset_pattern.format(key=value, value=value)+ except (KeyError, ValueError) as exc:+ errors.append(+ f"{markdown_name} schema: invalid asset_path_pattern "+ f"'{asset_pattern}': {exc}"+ )+ break+ asset_path = (schema_path.parent / relative_asset_path).resolve()+ if asset_path.suffix.casefold() != ".svg" or not asset_path.is_file():+ errors.append(+ f"{markdown_name} schema: section '{section_id}' value '{value}' "+ f"does not resolve to an SVG asset at {asset_path}"+ )+ return errors+++def _validate_section(+ *,+ markdown_name: str,+ section_id: str,+ section: Mapping[str, object],+ definition: Mapping[str, object],+ schema_path: Path,+) -> list[str]:+ """Apply one section definition to one matched Markdown section."""+ errors: list[str] = []+ fields = section["fields"]+ assert isinstance(fields, dict)++ required_fields = definition.get("required_fields", [])+ allow_empty = {+ str(field_name)+ for field_name in definition.get("allow_empty_fields", [])+ }+ if isinstance(required_fields, list):+ for field_name in required_fields:+ field_key = str(field_name)+ if field_key not in fields:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' is missing field "+ f"'{field_name}'"+ )+ elif (+ field_key not in allow_empty+ and not _normalize_schema_value(str(fields[field_key]))+ ):+ errors.append(+ f"{markdown_name} schema: section '{section_id}' field "+ f"'{field_name}' must not be empty"+ )++ allowed_fields = definition.get("allowed_fields")+ if isinstance(allowed_fields, list):+ allowed = {str(field_name) for field_name in allowed_fields}+ for field_name in fields:+ if field_name not in allowed:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' has unknown "+ f"field '{field_name}'"+ )++ field_enums = definition.get("field_enums", {})+ if isinstance(field_enums, dict):+ for field_name, allowed in field_enums.items():+ field_key = str(field_name)+ if field_key not in fields or not isinstance(allowed, list):+ continue+ value = _normalize_schema_value(str(fields[field_key]))+ if value not in [str(item) for item in allowed]:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' field "+ f"'{field_name}' has illegal value '{value}'"+ )++ field_patterns = definition.get("field_patterns", {})+ if isinstance(field_patterns, dict):+ for field_name, pattern in field_patterns.items():+ field_key = str(field_name)+ if field_key not in fields:+ continue+ value = _normalize_schema_value(str(fields[field_key]))+ if re.fullmatch(str(pattern), value) is None:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' field "+ f"'{field_name}' does not match '{pattern}'"+ )++ minimum = definition.get("min_entries")+ if isinstance(minimum, int) and len(fields) < minimum:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' needs at least "+ f"{minimum} data line(s)"+ )++ min_body_chars = definition.get("min_body_chars")+ if isinstance(min_body_chars, int) and len(str(section["body"]).strip()) < min_body_chars:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' must contain content"+ )++ entry_key_pattern = definition.get("entry_key_pattern")+ if isinstance(entry_key_pattern, str):+ field_names = section["field_names"]+ assert isinstance(field_names, dict)+ for field_name in field_names.values():+ if re.fullmatch(entry_key_pattern, str(field_name)) is None:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' has malformed "+ f"entry key '{field_name}'"+ )++ value_enum = definition.get("value_enum")+ if isinstance(value_enum, list):+ allowed_values = [str(item) for item in value_enum]+ for field_value in fields.values():+ value = _normalize_schema_value(str(field_value))+ if value not in allowed_values:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' has illegal "+ f"value '{value}'"+ )++ value_pattern = definition.get("value_pattern")+ if isinstance(value_pattern, str):+ for field_value in fields.values():+ value = _normalize_schema_value(str(field_value))+ if re.fullmatch(value_pattern, value) is None:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' has malformed "+ f"value '{value}'"+ )++ value_catalog = definition.get("value_catalog")+ if isinstance(value_catalog, dict):+ errors.extend(+ _validate_catalog_values(+ markdown_name=markdown_name,+ section_id=section_id,+ fields=fields,+ schema_path=schema_path,+ value_catalog=value_catalog,+ )+ )+ return errors+++def _condition_applies(+ when: Mapping[str, object],+ matched: Mapping[str, dict[str, object] | None],+) -> bool:+ """Return whether a schema condition applies to the matched document."""+ section = matched.get(str(when.get("section", "")))+ if section is None:+ return False+ applies = True+ field_name = when.get("field")+ if field_name is not None:+ fields = section["fields"]+ assert isinstance(fields, dict)+ field_value = fields.get(str(field_name))+ applies = field_value is not None+ if applies and "equals" in when:+ applies = _normalize_schema_value(str(field_value)) == str(when["equals"])+ body_regex = when.get("body_regex")+ if applies and isinstance(body_regex, str):+ applies = re.search(body_regex, str(section["body"])) is not None+ return applies+++def _validate_condition(+ *,+ markdown_name: str,+ condition_id: str,+ then: Mapping[str, object],+ matched: Mapping[str, dict[str, object] | None],+) -> list[str]:+ """Apply one active cross-section condition."""+ errors: list[str] = []++ required_sections = then.get("required_sections", [])+ if isinstance(required_sections, list):+ for section_id in required_sections:+ if matched.get(str(section_id)) is None:+ errors.append(+ f"{markdown_name} schema: condition '{condition_id}' requires "+ f"section '{section_id}'"+ )++ forbidden_sections = then.get("forbidden_sections", [])+ if isinstance(forbidden_sections, list):+ for section_id in forbidden_sections:+ if matched.get(str(section_id)) is not None:+ errors.append(+ f"{markdown_name} schema: condition '{condition_id}' forbids "+ f"section '{section_id}'"+ )++ field_groups = then.get("required_fields", [])+ if isinstance(field_groups, list):+ for group in field_groups:+ if not isinstance(group, dict):+ continue+ target_id = str(group.get("section", ""))+ target = matched.get(target_id)+ if target is None:+ continue+ target_fields = target["fields"]+ assert isinstance(target_fields, dict)+ for field_name in group.get("fields", []):+ field_key = str(field_name)+ if field_key not in target_fields:+ errors.append(+ f"{markdown_name} schema: condition '{condition_id}' requires "+ f"field '{field_name}' in section '{target_id}'"+ )+ elif not _normalize_schema_value(str(target_fields[field_key])):+ errors.append(+ f"{markdown_name} schema: condition '{condition_id}' requires "+ f"non-empty field '{field_name}' in section '{target_id}'"+ )++ field_values = then.get("field_values", [])+ if isinstance(field_values, list):+ for value_rule in field_values:+ if not isinstance(value_rule, dict):+ continue+ target_id = str(value_rule.get("section", ""))+ target = matched.get(target_id)+ if target is None:+ continue+ target_fields = target["fields"]+ assert isinstance(target_fields, dict)+ target_field = str(value_rule.get("field", ""))+ value = target_fields.get(target_field)+ allowed = value_rule.get("enum", [])+ if value is None or not isinstance(allowed, list):+ continue+ normalized = _normalize_schema_value(str(value))+ if normalized not in [str(item) for item in allowed]:+ errors.append(+ f"{markdown_name} schema: condition '{condition_id}' requires "+ f"'{target_id}.{target_field}' to be one of {allowed}"+ )++ subheading_rules = then.get("required_subheadings", [])+ if isinstance(subheading_rules, list):+ for rule in subheading_rules:+ if not isinstance(rule, dict):+ continue+ target_id = str(rule.get("section", ""))+ target = matched.get(target_id)+ if target is None:+ continue+ heading = str(rule.get("heading", ""))+ subheadings = target["subheadings"]+ assert isinstance(subheadings, list)+ if not any(+ str(item).startswith(heading)+ for item in subheadings+ ):+ errors.append(+ f"{markdown_name} schema: condition '{condition_id}' requires "+ f"subheading '{heading}' in section '{target_id}'"+ )+ return errors+++def _validate_slides(+ *,+ markdown_name: str,+ slide_contract: Mapping[str, object],+ matched: Mapping[str, dict[str, object] | None],+) -> list[str]:+ """Validate repeated slide blocks inside the configured outline section."""+ outline = matched.get(str(slide_contract.get("section", "")))+ heading_pattern = str(slide_contract.get("heading_pattern", ""))+ if outline is None or not heading_pattern:+ return []++ body = str(outline["body"])+ heading_matches = [+ match+ for match in _MARKDOWN_SUBHEADING_RE.finditer(body)+ if re.match(heading_pattern, match.group(1))+ ]+ if not heading_matches:+ return [f"{markdown_name} schema: content outline has no Slide blocks"]++ errors: list[str] = []+ required_fields = slide_contract.get("required_fields", [])+ if not isinstance(required_fields, list):+ return errors+ for index, slide_match in enumerate(heading_matches):+ block_end = (+ heading_matches[index + 1].start()+ if index + 1 < len(heading_matches)+ else len(body)+ )+ block = body[slide_match.end():block_end]+ for field_name in required_fields:+ pattern = (+ rf"^[ \t]*-[ \t]+(?:\*\*)?{re.escape(str(field_name))}"+ rf"(?:\*\*)?[ \t]*:"+ )+ if re.search(pattern, block, flags=re.MULTILINE) is None:+ errors.append(+ f"{markdown_name} schema: '{slide_match.group(1)}' is missing "+ f"field '{field_name}'"+ )+ return errors+++def _validate_references(+ *,+ markdown_path: Path,+ markdown_name: str,+ rules: object,+ matched: Mapping[str, dict[str, object] | None],+) -> list[str]:+ """Validate schema-declared cross-section keys and project assets."""+ if not isinstance(rules, list):+ return []+ errors: list[str] = []+ project_root = markdown_path.parent.resolve()++ for rule in rules:+ if not isinstance(rule, dict):+ continue+ rule_id = str(rule.get("id", "reference"))+ source_id = str(rule.get("from_section", ""))+ source = matched.get(source_id)+ if source is None:+ continue+ source_fields = source["fields"]+ assert isinstance(source_fields, dict)++ target_id = rule.get("target_section")+ target_fields: Mapping[str, object] | None = None+ if isinstance(target_id, str):+ target = matched.get(target_id)+ if target is None:+ continue+ raw_target_fields = target["fields"]+ assert isinstance(raw_target_fields, dict)+ target_fields = raw_target_fields++ component = rule.get("value_component")+ asset_pattern = rule.get("asset_path_pattern")+ for source_key, raw_value in source_fields.items():+ value = _normalize_schema_value(str(raw_value))+ reference_value = value+ if isinstance(component, dict):+ separator = str(component.get("separator", "|"))+ index = component.get("index", 0)+ parts = [part.strip() for part in value.split(separator)]+ if not isinstance(index, int) or index >= len(parts):+ errors.append(+ f"{markdown_name} schema: reference '{rule_id}' cannot "+ f"parse value '{value}' from section '{source_id}'"+ )+ continue+ reference_value = _normalize_schema_value(parts[index])++ if target_fields is not None:+ if reference_value not in target_fields:+ errors.append(+ f"{markdown_name} schema: reference '{rule_id}' value "+ f"'{reference_value}' from '{source_id}.{source_key}' is not "+ f"declared in section '{target_id}'"+ )++ if isinstance(asset_pattern, str):+ try:+ relative_asset = asset_pattern.format(value=reference_value)+ except (KeyError, ValueError) as exc:+ errors.append(+ f"{markdown_name} schema: reference '{rule_id}' has invalid "+ f"asset_path_pattern '{asset_pattern}': {exc}"+ )+ continue+ asset_path = (project_root / relative_asset).resolve()+ try:+ asset_path.relative_to(project_root)+ except ValueError:+ errors.append(+ f"{markdown_name} schema: reference '{rule_id}' escapes the "+ f"project root for value '{reference_value}'"+ )+ continue+ if asset_path.suffix.casefold() != ".svg" or not asset_path.is_file():+ errors.append(+ f"{markdown_name} schema: reference '{rule_id}' value "+ f"'{reference_value}' does not resolve to {asset_path}"+ )+ return errors+++def _validate_strict_data_surface(+ markdown_name: str,+ text: str,+ sections: list[dict[str, object]],+ matched: Mapping[str, dict[str, object] | None],+) -> list[str]:+ """Reject unknown lock sections and prose outside the data-line grammar."""+ errors: list[str] = []+ section_ids = {+ int(section["offset"]): section_id+ for section_id, section in matched.items()+ if section is not None+ }+ first_offset = min((int(section["offset"]) for section in sections), default=len(text))+ for line in text[:first_offset].splitlines():+ stripped = line.strip()+ if not stripped or stripped.startswith("<!--") or stripped.startswith("# "):+ continue+ errors.append(f"{markdown_name} schema: unsupported preamble line '{stripped}'")++ for section in sections:+ heading = str(section["heading"])+ section_id = section_ids.get(int(section["offset"]))+ if section_id is None:+ errors.append(f"{markdown_name} schema: unknown section '{heading}'")+ continue+ for line in str(section["body"]).splitlines():+ stripped = line.strip()+ if not stripped:+ continue+ if section_id == "forbidden" and stripped.startswith("- "):+ continue+ if _MARKDOWN_DATA_LINE_RE.fullmatch(line) is not None:+ continue+ errors.append(+ f"{markdown_name} schema: section '{section_id}' has unsupported "+ f"line '{stripped}'"+ )+ return errors+++def _validate_spec_lock_relations(+ markdown_path: Path,+ matched: Mapping[str, dict[str, object] | None],+) -> list[str]:+ """Validate cross-section references that JSON field rules cannot express."""+ markdown_name = markdown_path.name+ errors: list[str] = []++ def fields(section_id: str) -> dict[str, str]:+ section = matched.get(section_id)+ if section is None:+ return {}+ raw_fields = section["fields"]+ assert isinstance(raw_fields, dict)+ return {str(key): str(value) for key, value in raw_fields.items()}++ rhythm = fields("page_rhythm")+ layouts = fields("pptx_layouts")+ page_pptx_layouts = fields("page_pptx_layouts")+ page_layouts = fields("page_layouts")+ structure = fields("pptx_structure")++ for layout_key, raw_value in layouts.items():+ parts = [part.strip() for part in raw_value.split("|")]+ if len(parts) != 3:+ continue+ _, _, source = parts+ if source.startswith("template:"):+ basename = source.removeprefix("template:").strip()+ template_path = markdown_path.parent / "templates" / f"{basename}.svg"+ if not template_path.is_file():+ errors.append(+ f"{markdown_name} schema: layout '{layout_key}' references "+ f"missing template SVG '{basename}.svg'"+ )+ elif source not in rhythm:+ errors.append(+ f"{markdown_name} schema: layout '{layout_key}' has unknown "+ f"prototype source '{source}'"+ )++ if structure.get("mode") == "structured":+ expected_pages = set(rhythm)+ for section_id, mapping in (+ ("page_pptx_layouts", page_pptx_layouts),+ ("page_layouts", page_layouts),+ ):+ missing = sorted(expected_pages - set(mapping))+ extra = sorted(set(mapping) - expected_pages)+ if missing:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' misses pages "+ f"{', '.join(missing)}"+ )+ if extra:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' has unknown "+ f"pages {', '.join(extra)}"+ )++ chart_pages = set(fields("page_charts"))+ unknown_chart_pages = sorted(chart_pages - set(rhythm))+ if unknown_chart_pages:+ errors.append(+ f"{markdown_name} schema: page_charts has unknown pages "+ f"{', '.join(unknown_chart_pages)}"+ )++ info = get_project_info_common(str(markdown_path.parent))+ format_key = str(info.get("format", "unknown"))+ canvas = CANVAS_FORMATS.get(format_key)+ canvas_fields = fields("canvas")+ if canvas is not None:+ expected_format = str(canvas["name"])+ expected_viewbox = str(canvas["viewbox"])+ if (+ "format" in canvas_fields+ and _normalize_schema_value(canvas_fields["format"]) != expected_format+ ):+ errors.append(+ f"{markdown_name} schema: canvas.format must be '{expected_format}'"+ )+ if (+ "viewBox" in canvas_fields+ and _normalize_schema_value(canvas_fields["viewBox"]) != expected_viewbox+ ):+ errors.append(+ f"{markdown_name} schema: canvas.viewBox must be '{expected_viewbox}'"+ )+ return errors+++def validate_markdown_schema(markdown_path: Path, schema_path: Path) -> list[str]:+ """Validate one existing Markdown artifact against a versioned schema."""+ try:+ text = markdown_path.read_text(encoding="utf-8-sig")+ schema = _load_markdown_schema(schema_path)+ except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:+ return [f"Schema validation could not read {markdown_path.name}: {exc}"]++ contract = schema["x-markdown"]+ assert isinstance(contract, dict)+ marker, marker_error = _extract_schema_marker(text)+ if marker_error is not None:+ return [f"{markdown_path.name} schema: {marker_error}"]+ expected_marker = contract.get("marker")+ if isinstance(expected_marker, str):+ if marker is None:+ return [+ f"{markdown_path.name} schema: missing ppt-master-schema marker "+ f"'{expected_marker}'"+ ]+ if marker != expected_marker.casefold():+ return [+ f"{markdown_path.name} schema: marker '{marker}' does not match "+ f"'{expected_marker}'"+ ]+ sections, parse_errors = _parse_markdown_sections(+ text,+ report_duplicate_fields=contract.get("parser") == "heading-data-lines-v1",+ )+ definitions = contract.get("sections", [])+ if not isinstance(definitions, list):+ return [f"Schema validation could not read {schema_path.name}: sections must be a list"]++ markdown_name = markdown_path.name+ errors = [f"{markdown_name} schema: {message}" for message in parse_errors]+ unresolved_patterns = contract.get("unresolved_patterns", [])+ if isinstance(unresolved_patterns, list):+ for pattern in unresolved_patterns:+ if not isinstance(pattern, str):+ continue+ matches = list(re.finditer(pattern, text))+ if matches:+ errors.append(+ f"{markdown_name} schema: contains {len(matches)} unresolved "+ f"placeholder(s) matching '{pattern}'"+ )++ matched: dict[str, dict[str, object] | None] = {}+ for definition in definitions:+ if not isinstance(definition, dict):+ continue+ section_id = str(definition.get("id", ""))+ pattern = str(definition.get("pattern", ""))+ if not section_id or not pattern:+ continue+ candidates = [+ section+ for section in sections+ if re.fullmatch(pattern, str(section["heading"]))+ ]+ if len(candidates) > 1:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' appears more than once"+ )+ section = candidates[0] if candidates else None+ matched[section_id] = section+ if definition.get("required") is True and section is None:+ errors.append(f"{markdown_name} schema: missing section '{section_id}'")+ continue+ if section is not None:+ errors.extend(+ _validate_section(+ markdown_name=markdown_name,+ section_id=section_id,+ section=section,+ definition=definition,+ schema_path=schema_path,+ )+ )++ section_order = contract.get("section_order", [])+ if isinstance(section_order, list):+ ordered_sections = [+ (str(section_id), matched.get(str(section_id)))+ for section_id in section_order+ if matched.get(str(section_id)) is not None+ ]+ offsets = [int(section["offset"]) for _, section in ordered_sections if section]+ if offsets != sorted(offsets):+ expected = " -> ".join(str(section_id) for section_id in section_order)+ errors.append(+ f"{markdown_name} schema: sections are out of order; expected {expected}"+ )++ conditions = contract.get("conditions", [])+ if isinstance(conditions, list):+ for condition in conditions:+ if not isinstance(condition, dict):+ continue+ when = condition.get("when", {})+ then = condition.get("then", {})+ if not isinstance(when, dict) or not isinstance(then, dict):+ continue+ if _condition_applies(when, matched):+ errors.extend(+ _validate_condition(+ markdown_name=markdown_name,+ condition_id=str(condition.get("id", "conditional rule")),+ then=then,+ matched=matched,+ )+ )++ errors.extend(+ _validate_references(+ markdown_path=markdown_path,+ markdown_name=markdown_name,+ rules=contract.get("references"),+ matched=matched,+ )+ )++ slide_contract = contract.get("slides")+ if isinstance(slide_contract, dict):+ errors.extend(+ _validate_slides(+ markdown_name=markdown_name,+ slide_contract=slide_contract,+ matched=matched,+ )+ )+ if contract.get("strict_lines") is True:+ errors.extend(+ _validate_strict_data_surface(markdown_name, text, sections, matched)+ )+ if schema.get("$id") == "ppt-master://schemas/spec-lock/v1":+ errors.extend(_validate_spec_lock_relations(markdown_path, matched))+ return errors+++def validate_project_artifacts(+ project_path: Path,+ project_info: Mapping[str, object] | None = None,+) -> tuple[list[str], list[str]]:+ """Validate versioned artifacts and preserve markerless legacy projects."""+ info = project_info or get_project_info_common(str(project_path))+ errors: list[str] = []+ warnings: list[str] = []+ artifacts: list[tuple[Path, Path, str]] = []+ spec_name = info.get("spec_file")+ if isinstance(spec_name, str):+ artifacts.append(+ (+ project_path / spec_name,+ SCHEMA_DIR / "design_spec.schema.json",+ "design",+ )+ )+ lock_path = project_path / "spec_lock.md"+ if lock_path.is_file():+ artifacts.append((lock_path, SCHEMA_DIR / "spec_lock.schema.json", "lock"))+ elif isinstance(spec_name, str):+ errors.append(+ "Communication trace: missing spec_lock.md with a "+ "## communication section."+ )++ legacy_design = False+ legacy_lock = False+ for artifact_path, schema_path, artifact_kind in artifacts:+ try:+ text = artifact_path.read_text(encoding="utf-8-sig")+ except (OSError, UnicodeError) as exc:+ errors.append(f"Schema validation could not read {artifact_path.name}: {exc}")+ continue+ marker, marker_error = _extract_schema_marker(text)+ if marker_error is not None:+ errors.append(f"{artifact_path.name} schema: {marker_error}")+ continue+ if marker is None:+ warnings.append(+ f"{artifact_path.name}: legacy artifact has no ppt-master-schema "+ "marker; skipped versioned schema validation"+ )+ legacy_design = legacy_design or artifact_kind == "design"+ legacy_lock = legacy_lock or artifact_kind == "lock"+ continue+ errors.extend(validate_markdown_schema(artifact_path, schema_path))+ if legacy_design or legacy_lock:+ errors.extend(+ validate_communication_trace(+ project_path,+ check_lock=legacy_lock,+ check_design=legacy_design,+ )+ )+ return errors, warnings+++def scaffold_project_artifact(project_path: Path, artifact: str) -> str:+ """Render one versioned Markdown scaffold without overwriting user work."""+ assets = {+ "design_spec": (SCAFFOLD_DIR / "design_spec.md", "design_spec.md"),+ "spec_lock": (SCAFFOLD_DIR / "spec_lock.md", "spec_lock.md"),+ }+ if artifact not in assets:+ raise ValueError(f"Unsupported scaffold artifact: {artifact}")+ if not project_path.exists() or not project_path.is_dir():+ raise FileNotFoundError(f"Project directory does not exist: {project_path}")++ info = get_project_info_common(str(project_path))+ format_key = str(info.get("format", "unknown"))+ if format_key not in CANVAS_FORMATS:+ raise ValueError(+ "Cannot derive the canvas format from the project directory name. "+ "Use a standard <name>_<format>_<YYYYMMDD> project path."+ )+ canvas = CANVAS_FORMATS[format_key]+ created_date = str(info.get("date_formatted", "Unknown date"))+ if created_date == "Unknown date":+ created_date = "[fill]"+ context = {+ "PROJECT_NAME": str(info.get("name", project_path.name)),+ "CANVAS_NAME": str(canvas["name"]),+ "CANVAS_DIMENSIONS": str(canvas["dimensions"]),+ "VIEWBOX": str(canvas["viewbox"]),+ "CREATED_DATE": created_date,+ }++ scaffold_path, target_name = assets[artifact]+ target_path = project_path / target_name+ existing_spec = info.get("spec_file") if artifact == "design_spec" else None+ if isinstance(existing_spec, str):+ existing_path = project_path / existing_spec+ raise FileExistsError(+ f"Refusing to shadow existing design spec: {existing_path}"+ )+ if target_path.exists() or target_path.is_symlink():+ raise FileExistsError(f"Refusing to overwrite existing artifact: {target_path}")+ rendered = scaffold_path.read_text(encoding="utf-8")+ for key, value in context.items():+ rendered = rendered.replace(f"{{{{{key}}}}}", value)+ unresolved = sorted(set(_SCAFFOLD_TOKEN_RE.findall(rendered)))+ if unresolved:+ raise ValueError(+ f"Unresolved scaffold token(s) in {scaffold_path}: {', '.join(unresolved)}"+ )+ with target_path.open("x", encoding="utf-8") as stream:+ stream.write(rendered)+ return str(target_path)diff --git a/skills/ppt-master/scripts/project_utils.py b/skills/ppt-master/scripts/project_utils.pyindex 9ba0336b..8b1133c7 100644--- a/skills/ppt-master/scripts/project_utils.py+++ b/skills/ppt-master/scripts/project_utils.py@@ -236,69 +236,80 @@ def get_project_info(project_path: str) -> Dict:return info-def validate_communication_trace(project_path: str | Path) -> List[str]:- """Validate the structural communication trace across both spec files."""+def validate_communication_trace(+ project_path: str | Path,+ *,+ check_lock: bool = True,+ check_design: bool = True,+) -> List[str]:+ """Validate either or both legacy communication-trace surfaces."""root = Path(project_path)design_spec = next((root / name for name in _DESIGN_SPEC_NAMES if (root / name).is_file()),None,)- if design_spec is None:+ if design_spec is None or not (check_lock or check_design):return []errors: List[str] = []lock_path = root / 'spec_lock.md'- if not lock_path.is_file():- return [- 'Communication trace: missing spec_lock.md with a '- '## communication section.',- ]+ if check_lock:+ if not lock_path.is_file():+ return [+ 'Communication trace: missing spec_lock.md with a '+ '## communication section.',+ ]+ try:+ lock_text = lock_path.read_text(encoding='utf-8-sig')+ except OSError as exc:+ return [f'Communication trace: unable to read specification files: {exc}']+ communication_match = re.search(+ r'^##[ \t]+communication[ \t]*$',+ lock_text,+ flags=re.IGNORECASE | re.MULTILINE,+ )+ if communication_match is None:+ errors.append(+ 'Communication trace: spec_lock.md must contain a '+ '## communication section.',+ )+ else:+ next_section = re.search(+ r'^##[ \t]+',+ lock_text[communication_match.end():],+ flags=re.MULTILINE,+ )+ section_end = (+ communication_match.end() + next_section.start()+ if next_section+ else len(lock_text)+ )+ communication_block = lock_text[+ communication_match.end():section_end+ ]+ missing_keys = [+ key+ for key in _COMMUNICATION_TRACE_KEYS+ if re.search(+ rf'^-[ \t]+{re.escape(key)}[ \t]*:',+ communication_block,+ flags=re.MULTILINE,+ ) is None+ ]+ if missing_keys:+ errors.append(+ 'Communication trace: spec_lock.md ## communication is '+ f'missing key line(s): {", ".join(missing_keys)}.',+ )++ if not check_design:+ return errorstry:- lock_text = lock_path.read_text(encoding='utf-8-sig')design_text = design_spec.read_text(encoding='utf-8-sig')except OSError as exc:return [f'Communication trace: unable to read specification files: {exc}']- communication_match = re.search(- r'^##[ \t]+communication[ \t]*$',- lock_text,- flags=re.IGNORECASE | re.MULTILINE,- )- if communication_match is None:- errors.append(- 'Communication trace: spec_lock.md must contain a '- '## communication section.',- )- else:- next_section = re.search(- r'^##[ \t]+',- lock_text[communication_match.end():],- flags=re.MULTILINE,- )- section_end = (- communication_match.end() + next_section.start()- if next_section- else len(lock_text)- )- communication_block = lock_text[- communication_match.end():section_end- ]- missing_keys = [- key- for key in _COMMUNICATION_TRACE_KEYS- if re.search(- rf'^-[ \t]+{re.escape(key)}[ \t]*:',- communication_block,- flags=re.MULTILINE,- ) is None- ]- if missing_keys:- errors.append(- 'Communication trace: spec_lock.md ## communication is '- f'missing key line(s): {", ".join(missing_keys)}.',- )-outline_match = re.search(r'^##[ \t]+IX\.[ \t]+Content Outline\b.*$',design_text,@@ -355,13 +366,19 @@ def validate_communication_trace(project_path: str | Path) -> List[str]:return errors-def validate_project_structure(project_path: str, verbose: bool = False) -> Tuple[bool, List[str], List[str]]:+def validate_project_structure(+ project_path: str,+ verbose: bool = False,+ *,+ validate_communication: bool = True,+) -> Tuple[bool, List[str], List[str]]:"""Validate project structure completeness.Args:project_path: Project directory pathverbose: Whether to show detailed fix suggestions+ validate_communication: Whether to run the markerless legacy trace checkReturns:(is_valid, error_list, warning_list)@@ -405,7 +422,7 @@ def validate_project_structure(project_path: str, verbose: bool = False) -> Tuplif use_helper and verbose:msg += "\n" + ErrorHelper.format_error_message('missing_spec')warnings.append(msg)- else:+ elif validate_communication:errors.extend(validate_communication_trace(project_path))# Check svg_output directorydiff --git a/skills/ppt-master/templates/charts/charts_index.json b/skills/ppt-master/templates/charts/charts_index.jsonindex 46c99e96..dde2f940 100644--- a/skills/ppt-master/templates/charts/charts_index.json+++ b/skills/ppt-master/templates/charts/charts_index.json@@ -5,7 +5,7 @@"formats": ["ppt169"],"filePattern": "{key}.svg","libraryPositioning": "Visualization template library covering charts, infographics, diagrams, and strategic frameworks. The `charts/` path is retained for backward compatibility. Templates are named by visual structure, not by business-model name — model-specific frameworks (SWOT, BCG, PEST, OKR, Porter's Five Forces, Value Chain, etc.) are matched via keywords in `summary`.",- "summaryGrammar": "Each chart's `summary` is a selection rule, not a description. Format: 'Pick for <content shape + scale>. Skip if <reason → alternative>'. Strategist matches every page's content shape against all 76 summaries; no category/keyword index — full-read is intentional.",+ "summaryGrammar": "Each chart's `summary` is a selection rule, not a description. Format: 'Pick for <content shape + scale>. Skip if <reason → alternative>'. Strategist supplies 3–8 semantic content-shape tags per candidate page; chart_recall.py returns a bounded shortlist without loading the full catalog into the runtime prompt.","updated": "2026-07-03"},"charts": {@@ -46,7 +46,7 @@"summary": "Pick for project schedule with 6-12 tasks, durations, and dependencies. Skip for simple milestones without duration (use timeline) or vertical roadmap (use roadmap_vertical)."},"gauge_chart": {- "summary": "Pick for one hero metric's goal achievement rate. Skip for multiple metrics (use bullet_chart for target+actual or progress_bar_chart for completion %)."+ "summary": "Pick for one hero metric or single KPI's goal achievement rate. Skip for multiple metrics (use bullet_chart for target+actual or progress_bar_chart for completion %)."},"grouped_bar_chart": {"summary": "Pick for 2-4 series side-by-side across the same categories (e.g. YoY/QoQ). Skip if showing composition within each category (use stacked_bar_chart)."diff --git a/skills/ppt-master/templates/scaffolds/design_spec.md b/skills/ppt-master/templates/scaffolds/design_spec.mdnew file mode 100644index 00000000..e5178ff4--- /dev/null+++ b/skills/ppt-master/templates/scaffolds/design_spec.md@@ -0,0 +1,123 @@+<!-- ppt-master-schema: design-spec/v1 -->+# {{PROJECT_NAME}} - Design Spec++## I. Project Information++| Item | Value |+| --- | --- |+| Project Name | {{PROJECT_NAME}} |+| Canvas Format | {{CANVAS_NAME}} ({{CANVAS_DIMENSIONS}}) |+| Page Count | [fill] |+| Target Audience | [fill] |+| Communication Intent | [fill] |+| Desired Audience Outcome | [fill] |+| Core Message / Ask / Action | [fill] |+| Delivery Context | [fill] |+| Artifact Afterlife | [fill] |+| Reading Mode | [fill] |+| Content Strategy | [fill] |+| Design Style | [fill] |+| Created Date | {{CREATED_DATE}} |++## II. Canvas Specification++| Property | Value |+| --- | --- |+| Format | {{CANVAS_NAME}} |+| Dimensions | {{CANVAS_DIMENSIONS}} |+| viewBox | `{{VIEWBOX}}` |+| Margins | [fill] |+| Content Area | [fill] |++## III. Visual Theme++### Theme Style++- **Mode**: [fill]+- **Visual style**: [fill]+- **Theme**: [fill]+- **Tone**: [fill]++### Color Scheme++| Role | HEX | Purpose |+| --- | --- | --- |+| Background | [fill] | [fill] |+| Primary | [fill] | [fill] |+| Accent | [fill] | [fill] |+| Body text | [fill] | [fill] |++## IV. Typography System++### Font Plan++| Role | Chinese | English | Fallback tail |+| --- | --- | --- | --- |+| Title | [fill] | [fill] | [fill] |+| Body | [fill] | [fill] | [fill] |+| Emphasis | [fill] | [fill] | [fill] |+| Code | [fill] | [fill] | [fill] |++- Title: [fill]+- Body: [fill]+- Emphasis: [fill or same as Body]+- Code: [fill]++### Font Size Hierarchy++| Purpose | Size |+| --- | --- |+| Body | [fill] |+| Page title | [fill] |+| Subtitle | [fill] |+| Annotation | [fill] |+| Footnote | [fill] |++## V. Layout Principles++### Page Structure++- **Header area**: [fill]+- **Content area**: [fill]+- **Footer area**: [fill]++### Spacing Specification++| Element | Current Project |+| --- | --- |+| Safe margin | [fill] |+| Content block gap | [fill] |+| Icon-text gap | [fill] |++## VI. Icon Usage Specification++| Purpose | Icon Path | Page |+| --- | --- | --- |+| [fill] | [fill] | [fill] |++## VII. Visualization Reference List++| Page | Template | Path | Summary-quote | Usage |+| --- | --- | --- | --- | --- |++## VIII. Image Resource List++| Filename | Dimensions | Ratio | Purpose | Type | Layout pattern | Acquire Via | Status | Reference | text_policy | page_role |+| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |++## IX. Content Outline++### Part 1: [fill]++#### Slide 01 - [fill]++- **Audience move**: [fill]+- **Layout**: [fill]+- **Title**: [fill]+- **Core message**: [fill]+- **Content**: [fill]++## X. Speaker Notes Requirements++- **Filename**: match each SVG filename under `notes/`+- **Content**: [fill]diff --git a/skills/ppt-master/templates/scaffolds/spec_lock.md b/skills/ppt-master/templates/scaffolds/spec_lock.mdnew file mode 100644index 00000000..82b523bd--- /dev/null+++ b/skills/ppt-master/templates/scaffolds/spec_lock.md@@ -0,0 +1,47 @@+<!-- ppt-master-schema: spec-lock/v1 -->+# Execution Lock++## canvas+- viewBox: {{VIEWBOX}}+- format: {{CANVAS_NAME}}++## communication+- audience:+- communication_intent:+- audience_outcome:+- core_message:+- delivery_context:+- artifact_afterlife:+- consumption_mode: [fill]++## mode+- mode: [fill]++## visual_style+- visual_style: [fill]++## colors+- bg: [fill]+- primary: [fill]+- accent: [fill]+- text: [fill]++## typography+- font_family: [fill]+- body: [fill]+- title: [fill]++## icons+- library: [fill]+- inventory: [fill]++## page_rhythm+- P01: [fill]++## pptx_structure+- mode: flat++## forbidden+- Mixing icon libraries+- `mask`, `<style>`, `class`, external CSS, `<foreignObject>`, `textPath`, `@font-face`, `<animate*>`, `<set>`, `<script>` / event attributes, `<iframe>`+- HTML named entities in text; write typography as raw Unicode and escape XML reserved charactersdiff --git a/skills/ppt-master/templates/schemas/design_spec.schema.json b/skills/ppt-master/templates/schemas/design_spec.schema.jsonnew file mode 100644index 00000000..f4d6168c--- /dev/null+++ b/skills/ppt-master/templates/schemas/design_spec.schema.json@@ -0,0 +1,93 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "ppt-master://schemas/design-spec/v1",+ "title": "PPT Master design_spec.md",+ "description": "Schema for the Markdown section model emitted by the design-spec parser.",+ "type": "object",+ "required": [+ "project_information",+ "canvas_specification",+ "visual_theme",+ "typography_system",+ "layout_principles",+ "icon_usage",+ "visualization_reference",+ "image_resource_list",+ "content_outline",+ "speaker_notes"+ ],+ "properties": {+ "project_information": {"type": "string", "minLength": 1},+ "canvas_specification": {"type": "string", "minLength": 1},+ "visual_theme": {"type": "string", "minLength": 1},+ "typography_system": {"type": "string", "minLength": 1},+ "layout_principles": {"type": "string", "minLength": 1},+ "icon_usage": {"type": "string", "minLength": 1},+ "visualization_reference": {"type": "string"},+ "image_resource_list": {"type": "string"},+ "content_outline": {"type": "string", "minLength": 1},+ "speaker_notes": {"type": "string", "minLength": 1}+ },+ "x-markdown": {+ "version": 1,+ "marker": "design-spec/v1",+ "parser": "heading-sections-v1",+ "unresolved_patterns": ["(?i)\\[fill(?:[^\\]]*)\\]"],+ "section_order": [+ "project_information",+ "canvas_specification",+ "visual_theme",+ "typography_system",+ "layout_principles",+ "icon_usage",+ "visualization_reference",+ "image_resource_list",+ "content_outline",+ "speaker_notes"+ ],+ "sections": [+ {"id": "project_information", "pattern": "^I\\. Project Information$", "required": true, "min_body_chars": 1},+ {"id": "canvas_specification", "pattern": "^II\\. Canvas Specification$", "required": true, "min_body_chars": 1},+ {"id": "visual_theme", "pattern": "^III\\. Visual Theme$", "required": true, "min_body_chars": 1},+ {"id": "typography_system", "pattern": "^IV\\. Typography System$", "required": true, "min_body_chars": 1},+ {"id": "layout_principles", "pattern": "^V\\. Layout Principles$", "required": true, "min_body_chars": 1},+ {"id": "icon_usage", "pattern": "^VI\\. Icon Usage Specification$", "required": true, "min_body_chars": 1},+ {+ "id": "visualization_reference",+ "pattern": "^VII\\. Visualization Reference List(?: \\(if needed\\))?$",+ "required": true+ },+ {+ "id": "image_resource_list",+ "pattern": "^VIII\\. Image Resource List(?: \\(if needed\\))?$",+ "required": true+ },+ {"id": "content_outline", "pattern": "^IX\\. Content Outline$", "required": true, "min_body_chars": 1},+ {+ "id": "speaker_notes",+ "pattern": "^X\\. Speaker Notes (?:Requirements|Plan|Strategy)$",+ "required": true,+ "min_body_chars": 1+ }+ ],+ "conditions": [+ {+ "id": "ai-image-strategy",+ "when": {+ "section": "image_resource_list",+ "body_regex": "(?im)^\\|[^\\n]*\\|\\s*ai\\s*\\|"+ },+ "then": {+ "required_subheadings": [+ {"section": "visual_theme", "heading": "AI Image Strategy"}+ ]+ }+ }+ ],+ "slides": {+ "section": "content_outline",+ "heading_pattern": "^Slide[ \\t]+(?:[0-9]+|NN)\\b",+ "required_fields": ["Audience move"]+ }+ }+}diff --git a/skills/ppt-master/templates/schemas/spec_lock.schema.json b/skills/ppt-master/templates/schemas/spec_lock.schema.jsonnew file mode 100644index 00000000..ca0ec973--- /dev/null+++ b/skills/ppt-master/templates/schemas/spec_lock.schema.json@@ -0,0 +1,314 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "ppt-master://schemas/spec-lock/v1",+ "title": "PPT Master spec_lock.md",+ "description": "Schema for the Markdown section-and-data-line model emitted by the spec-lock parser.",+ "type": "object",+ "required": [+ "canvas",+ "communication",+ "mode",+ "visual_style",+ "colors",+ "typography",+ "icons",+ "page_rhythm",+ "pptx_structure",+ "forbidden"+ ],+ "properties": {+ "canvas": {"type": "object"},+ "communication": {"type": "object"},+ "mode": {"type": "object"},+ "visual_style": {"type": "object"},+ "colors": {+ "type": "object",+ "properties": {+ "image_rendering": {"type": "string"},+ "image_rendering_behavior": {"type": "string"}+ }+ },+ "typography": {+ "type": "object",+ "properties": {+ "font_family": {"type": "string", "minLength": 1},+ "body": {"type": "number"},+ "title": {"type": "number"}+ }+ },+ "icons": {+ "type": "object",+ "properties": {+ "library": {"type": "string"},+ "inventory": {"type": "string"},+ "stroke_width": {"enum": [1.5, 2, 3]}+ }+ },+ "images": {"type": "object"},+ "page_rhythm": {"type": "object"},+ "pptx_structure": {"type": "object"},+ "pptx_masters": {"type": "object"},+ "pptx_layouts": {"type": "object"},+ "page_pptx_layouts": {"type": "object"},+ "page_layouts": {"type": "object"},+ "page_charts": {"type": "object"},+ "forbidden": {"type": "string"}+ },+ "x-markdown": {+ "version": 1,+ "marker": "spec-lock/v1",+ "parser": "heading-data-lines-v1",+ "strict_lines": true,+ "unresolved_patterns": ["(?i)\\[fill(?:[^\\]]*)\\]"],+ "sections": [+ {+ "id": "canvas",+ "pattern": "^canvas$",+ "required": true,+ "required_fields": ["viewBox", "format"],+ "allowed_fields": ["viewBox", "format"]+ },+ {+ "id": "communication",+ "pattern": "^communication$",+ "required": true,+ "required_fields": [+ "audience",+ "communication_intent",+ "audience_outcome",+ "core_message",+ "delivery_context",+ "artifact_afterlife"+ ],+ "allow_empty_fields": [+ "audience",+ "communication_intent",+ "audience_outcome",+ "core_message",+ "delivery_context",+ "artifact_afterlife"+ ],+ "allowed_fields": [+ "audience",+ "communication_intent",+ "audience_outcome",+ "core_message",+ "delivery_context",+ "artifact_afterlife",+ "consumption_mode"+ ],+ "field_enums": {+ "consumption_mode": ["text", "balanced", "presentation"]+ }+ },+ {+ "id": "mode",+ "pattern": "^mode$",+ "required": true,+ "required_fields": ["mode"],+ "allowed_fields": ["mode", "mode_behavior"],+ "field_enums": {+ "mode": ["pyramid", "narrative", "instructional", "showcase", "briefing", "custom"]+ }+ },+ {+ "id": "visual_style",+ "pattern": "^visual_style$",+ "required": true,+ "required_fields": ["visual_style"],+ "allowed_fields": ["visual_style", "visual_style_behavior"]+ },+ {"id": "colors", "pattern": "^colors$", "required": true, "min_entries": 1},+ {+ "id": "typography",+ "pattern": "^typography$",+ "required": true,+ "required_fields": ["font_family", "body", "title"],+ "field_patterns": {+ "body": "^[0-9]+(?:\\.[0-9]+)?$",+ "title": "^[0-9]+(?:\\.[0-9]+)?$"+ }+ },+ {+ "id": "icons",+ "pattern": "^icons$",+ "required": true,+ "required_fields": ["library", "inventory"],+ "allowed_fields": ["library", "inventory", "stroke_width"],+ "field_enums": {+ "stroke_width": ["1.5", "2", "3"]+ }+ },+ {"id": "images", "pattern": "^images$", "required": false},+ {+ "id": "page_rhythm",+ "pattern": "^page_rhythm$",+ "required": true,+ "min_entries": 1,+ "entry_key_pattern": "^P[0-9]{2,}$",+ "value_enum": ["anchor", "dense", "breathing"]+ },+ {+ "id": "pptx_structure",+ "pattern": "^pptx_structure$",+ "required": true,+ "required_fields": ["mode"],+ "allowed_fields": ["mode", "template_reuse_scope", "template_adherence"],+ "field_enums": {+ "mode": ["flat", "structured"],+ "template_reuse_scope": ["style", "layout", "mirror"],+ "template_adherence": ["adaptive", "strict"]+ }+ },+ {+ "id": "pptx_masters",+ "pattern": "^pptx_masters$",+ "required": false,+ "min_entries": 1,+ "entry_key_pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",+ "value_pattern": "^\\S(?:.*\\S)?$"+ },+ {+ "id": "pptx_layouts",+ "pattern": "^pptx_layouts$",+ "required": false,+ "min_entries": 1,+ "entry_key_pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$",+ "value_pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\\s*\\|\\s*[^|]+\\s*\\|\\s*(?:template:[A-Za-z0-9._-]+|P[0-9]{2,})$"+ },+ {+ "id": "page_pptx_layouts",+ "pattern": "^page_pptx_layouts$",+ "required": false,+ "min_entries": 1,+ "entry_key_pattern": "^P[0-9]{2,}$",+ "value_pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"+ },+ {+ "id": "page_layouts",+ "pattern": "^page_layouts$",+ "required": false,+ "min_entries": 1,+ "entry_key_pattern": "^P[0-9]{2,}$",+ "value_pattern": "^[A-Za-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"+ }+ },+ {"id": "forbidden", "pattern": "^forbidden$", "required": true, "min_body_chars": 1}+ ],+ "conditions": [+ {+ "id": "custom-mode",+ "when": {"section": "mode", "field": "mode", "equals": "custom"},+ "then": {"required_fields": [{"section": "mode", "fields": ["mode_behavior"]}]}+ },+ {+ "id": "custom-visual-style",+ "when": {"section": "visual_style", "field": "visual_style", "equals": "custom"},+ "then": {+ "required_fields": [{"section": "visual_style", "fields": ["visual_style_behavior"]}]+ }+ },+ {+ "id": "custom-image-rendering",+ "when": {"section": "colors", "field": "image_rendering", "equals": "custom"},+ "then": {+ "required_fields": [{"section": "colors", "fields": ["image_rendering_behavior"]}]+ }+ },+ {+ "id": "stroke-icon-weight",+ "when": {"section": "icons", "field": "library", "equals": "tabler-outline"},+ "then": {"required_fields": [{"section": "icons", "fields": ["stroke_width"]}]}+ },+ {+ "id": "structured-pptx",+ "when": {"section": "pptx_structure", "field": "mode", "equals": "structured"},+ "then": {+ "required_sections": ["pptx_masters", "pptx_layouts", "page_pptx_layouts", "page_layouts"],+ "required_fields": [+ {"section": "pptx_structure", "fields": ["template_reuse_scope", "template_adherence"]}+ ],+ "field_values": [+ {+ "section": "pptx_structure",+ "field": "template_reuse_scope",+ "enum": ["layout", "mirror"]+ }+ ]+ }+ },+ {+ "id": "style-is-flat",+ "when": {"section": "pptx_structure", "field": "template_reuse_scope", "equals": "style"},+ "then": {+ "field_values": [{"section": "pptx_structure", "field": "mode", "enum": ["flat"]}]+ }+ },+ {+ "id": "layout-is-structured",+ "when": {"section": "pptx_structure", "field": "template_reuse_scope", "equals": "layout"},+ "then": {+ "field_values": [{"section": "pptx_structure", "field": "mode", "enum": ["structured"]}]+ }+ },+ {+ "id": "mirror-is-strict",+ "when": {"section": "pptx_structure", "field": "template_reuse_scope", "equals": "mirror"},+ "then": {+ "required_fields": [+ {"section": "pptx_structure", "fields": ["template_adherence"]}+ ],+ "field_values": [+ {"section": "pptx_structure", "field": "mode", "enum": ["structured"]},+ {"section": "pptx_structure", "field": "template_adherence", "enum": ["strict"]}+ ]+ }+ },+ {+ "id": "flat-has-no-structured-mappings",+ "when": {"section": "pptx_structure", "field": "mode", "equals": "flat"},+ "then": {+ "forbidden_sections": [+ "pptx_masters",+ "pptx_layouts",+ "page_pptx_layouts",+ "page_layouts"+ ],+ "field_values": [+ {"section": "pptx_structure", "field": "template_reuse_scope", "enum": ["style"]},+ {"section": "pptx_structure", "field": "template_adherence", "enum": []}+ ]+ }+ }+ ],+ "references": [+ {+ "id": "layout-master",+ "from_section": "pptx_layouts",+ "value_component": {"separator": "|", "index": 0},+ "target_section": "pptx_masters"+ },+ {+ "id": "page-pptx-layout",+ "from_section": "page_pptx_layouts",+ "target_section": "pptx_layouts"+ },+ {+ "id": "page-input-prototype",+ "from_section": "page_layouts",+ "asset_path_pattern": "templates/{value}.svg"+ }+ ]+ }+}