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
refactor(project-management): move internals behind stable script shims
hugohe30f8d84dafe38
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.mdindex cb2ed446..b7abbcea 100644--- a/skills/ppt-master/scripts/README.md+++ b/skills/ppt-master/scripts/README.md@@ -5,6 +5,7 @@ This directory contains user-facing scripts for conversion, project setup, direc## Directory Layout- Top-level `scripts/`: runnable entry scripts+- `scripts/project_management/`: internals behind `project_manager.py`- `scripts/source_to_md.py`: unified source-document → Markdown dispatcher- `scripts/source_to_md/`: source-document → Markdown routing/batch helpers and backend converters (`_dispatcher.py`, `_batch.py`, `pdf_to_md.py`, `doc_to_md.py`, `excel_to_md.py`, `ppt_to_md.py`, `web_to_md.py`)- `scripts/image_backends/`: internal provider implementations used by `image_gen.py`@@ -45,7 +46,7 @@ python3 scripts/update_repo.py| Area | Primary scripts | Documentation ||------|-----------------|---------------|| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |-| Project management | `project_manager.py`, `page_context.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py`, `pptx_delivery_check.py` | [docs/project.md](./docs/project.md) |+| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py`, `pptx_delivery_check.py` | [docs/project.md](./docs/project.md) || 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) |diff --git a/skills/ppt-master/scripts/page_context.py b/skills/ppt-master/scripts/page_context.pyindex 3d0d7c81..55b2689f 100644--- a/skills/ppt-master/scripts/page_context.py+++ b/skills/ppt-master/scripts/page_context.py@@ -1,917 +1,50 @@#!/usr/bin/env python3"""-PPT Master - Page Context Projection+PPT Master - Page Context Compatibility Module-Build deterministic per-page execution views and optional token telemetry.+Re-export the project-management page-context API from its domain package.+New internal imports should use ``project_management.page_context``.Usage:- Imported by project_manager.py.+ Import the public projection helpers from this module.Examples:- build_page_context(Path("projects/demo"), "P07")+ from page_context import build_page_contextDependencies:- None for projection; tiktoken is optional for exact usage counts.+ Same as project_management.page_context."""-from __future__ import annotations--import hashlib-import json-import math-import re-import statistics-import xml.etree.ElementTree as ET-from dataclasses import dataclass-from pathlib import Path-from typing import Callable, Iterable--from project_specs import (- default_spec_lock_forbidden,- parse_markdown_artifact,- parse_spec_lock_artifact,- validate_project_artifacts,-)-from svg_to_pptx.pptx_package.template_structure import (- PptxStructureLock,- TemplateStructureError,- load_pptx_structure_lock,-)---PAGE_CONTEXT_SCHEMA = "ppt-master.page-context.v2"-PAGE_CONTEXT_USAGE_SCHEMA = "ppt-master.page-context-usage.v2"-PAGE_CONTEXT_REPORT_SCHEMA = "ppt-master.page-context-usage-report.v2"-TOKEN_ENCODING = "o200k_base"-PAGE_CONTEXT_TOKEN_TARGET = 2000-LOCK_PROJECTION_TOKEN_TARGET = 1000--_SKILL_DIR = Path(__file__).resolve().parent.parent-_CHARTS_DIR = _SKILL_DIR / "templates" / "charts"--_PAGE_RE = re.compile(r"^(?:P)?([0-9]+)$", re.IGNORECASE)-_SLIDE_HEADING_RE = re.compile(- r"^#{3,6}[ \t]+Slide[ \t]+0*([0-9]+)(?:[ \t]*(?:[-:–—]).*)?$",- re.IGNORECASE | re.MULTILINE,+from project_management.page_context import (+ LOCK_PROJECTION_TOKEN_TARGET,+ PAGE_CONTEXT_REPORT_SCHEMA,+ PAGE_CONTEXT_SCHEMA,+ PAGE_CONTEXT_TOKEN_TARGET,+ PAGE_CONTEXT_USAGE_SCHEMA,+ TOKEN_ENCODING,+ PageContextError,+ PageContextResult,+ PageRead,+ build_page_context,+ normalize_page_key,+ page_context_usage_report,+ record_page_context_usage,+ render_page_context,)-_BLOCK_BOUNDARY_RE = re.compile(r"^#{2,6}[ \t]+", re.MULTILINE)-_PART_HEADING_RE = re.compile(r"^###[ \t]+(?!#)(.+?)[ \t]*$", re.MULTILINE)-_PAGE_TOKEN_RE = re.compile(- r"(?<![A-Za-z0-9_])P0*([1-9][0-9]*)(?![A-Za-z0-9_])",- re.IGNORECASE,-)---class PageContextError(RuntimeError):- """Reject an incomplete or ambiguous page-context request."""---@dataclass(frozen=True)-class PageRead:- """One exact model-visible page payload."""-- kind: str- path: str- payload: str---@dataclass(frozen=True)-class PageContextResult:- """One projected page view plus the files that make it current."""-- project_path: Path- page: str- context: dict[str, object]- inputs: tuple[Path, ...]---def normalize_page_key(raw_page: str) -> tuple[str, int]:- """Normalize a positive page identifier to the schema's P<NN> form."""- match = _PAGE_RE.fullmatch(raw_page.strip())- if match is None or int(match.group(1)) <= 0:- raise PageContextError("page must be a positive P<NN> identifier")- number = int(match.group(1))- return f"P{number:02d}", number---def _section_index(- sections: Iterable[dict[str, object]],-) -> dict[str, dict[str, object]]:- return {- str(section["heading"]).strip().casefold(): section- for section in sections- }---def _section_fields(- sections: dict[str, dict[str, object]],- heading: str,-) -> dict[str, str]:- section = sections.get(heading.casefold())- if section is None:- return {}- fields = section.get("fields", {})- if not isinstance(fields, dict):- return {}- return {str(key): str(value) for key, value in fields.items()}---def _forbidden_items(- sections: dict[str, dict[str, object]],-) -> list[str]:- section = sections.get("forbidden")- if section is None:- return []- items: list[str] = []- default_items = default_spec_lock_forbidden()- for raw_line in str(section.get("body", "")).splitlines():- line = raw_line.strip()- if not line:- continue- item = re.sub(r"^-[ \t]+", "", line)- if item not in default_items:- items.append(item)- return items---def _outline_section(- sections: Iterable[dict[str, object]],-) -> dict[str, object] | None:- for section in sections:- heading = str(section.get("heading", "")).strip().casefold()- if heading == "content outline" or heading.endswith(". content outline"):- return section- return None---def _page_image_filenames(- design_sections: Iterable[dict[str, object]],- page_number: int,-) -> tuple[set[str], set[str]]:- """Read explicit P<NN> usage from the canonical image-resource table."""- section = next(- (- item- for item in design_sections- if (- (heading := str(item.get("heading", "")).strip().casefold())- == "image resource list"- or heading.startswith("viii. image resource list")- )- ),- None,- )- if section is None:- return set(), set()- table_rows = [- [- cell.strip().replace(r"\|", "|")- for cell in re.split(r"(?<!\\)\|", line.strip().strip("|"))- ]- for line in str(section.get("body", "")).splitlines()- if line.strip().startswith("|") and line.strip().endswith("|")- ]- if not table_rows:- return set(), set()- header = {- name.casefold(): index- for index, name in enumerate(table_rows[0])- }- filename_index = header.get("filename")- purpose_index = header.get("purpose")- if filename_index is None or purpose_index is None:- return set(), set()- assigned: set[str] = set()- selected: set[str] = set()- for row in table_rows[1:]:- if len(row) <= max(filename_index, purpose_index):- continue- purpose = row[purpose_index]- pages = {int(match.group(1)) for match in _PAGE_TOKEN_RE.finditer(purpose)}- if not pages:- continue- filename = row[filename_index].strip().strip("`")- if not filename:- continue- basename = Path(filename).name- assigned.add(basename)- if page_number in pages:- selected.add(basename)- return assigned, selected---def _locked_image_basename(value: str) -> str:- return Path(value.split("|", 1)[0].strip()).name---def _outline_image_assignments(- design_sections: Iterable[dict[str, object]],- locked_images: dict[str, str],-) -> set[str]:- outline = _outline_section(design_sections)- if outline is None:- return set()- body = str(outline.get("body", ""))- return {- _locked_image_basename(value)- for key, value in locked_images.items()- if any(- _contains_token(body, token)- for token in (- key,- value.split("|", 1)[0].strip(),- _locked_image_basename(value),- )- )- }---def _slide_block(- design_sections: Iterable[dict[str, object]],- page_number: int,-) -> tuple[str | None, str]:- outline = _outline_section(design_sections)- if outline is None:- raise PageContextError("design_spec.md has no Content Outline section")- body = str(outline.get("body", ""))- matches = [- match- for match in _SLIDE_HEADING_RE.finditer(body)- if int(match.group(1)) == page_number- ]- if not matches:- raise PageContextError(- f"design_spec.md Content Outline has no Slide {page_number:02d} block"- )- if len(matches) > 1:- raise PageContextError(- f"design_spec.md Content Outline repeats Slide {page_number:02d}"- )- match = matches[0]- next_boundary = _BLOCK_BOUNDARY_RE.search(body, match.end())- block_end = next_boundary.start() if next_boundary else len(body)- block = body[match.start():block_end].strip()- part_matches = list(_PART_HEADING_RE.finditer(body, 0, match.start()))- part = part_matches[-1].group(1).strip() if part_matches else None- return part, block---def _relative_project_path(project_path: Path, path: Path) -> str:- try:- return path.resolve().relative_to(project_path).as_posix()- except ValueError as exc:- raise PageContextError(f"path escapes project: {path}") from exc---def _prototype_image_refs(svg_path: Path) -> list[str]:- try:- root = ET.parse(svg_path).getroot()- except (OSError, ET.ParseError) as exc:- raise PageContextError(f"cannot read prototype SVG {svg_path}: {exc}") from exc- refs: set[str] = set()- for element in root.iter():- if element.tag.rsplit("}", 1)[-1] != "image":- continue- for name, value in element.attrib.items():- if name.rsplit("}", 1)[-1] != "href":- continue- normalized = value.strip()- if normalized and not normalized.startswith(("data:", "#")):- refs.add(normalized)- return sorted(refs)---def _contains_token(text: str, token: str) -> bool:- if not token:- return False- if re.fullmatch(r"[A-Za-z0-9_]+", token):- return re.search(- rf"(?<![A-Za-z0-9_]){re.escape(token)}(?![A-Za-z0-9_])",- text,- ) is not None- return token in text---def _page_images(- locked_images: dict[str, str],- brief: str,- prototype_refs: list[str],- assigned_filenames: set[str],- resolved_filenames: set[str],-) -> tuple[str, dict[str, str]]:- if not locked_images:- return "none", {}- ref_basenames = {Path(ref).name for ref in prototype_refs}- selected: dict[str, str] = {}- unresolved: dict[str, str] = {}- for key, value in locked_images.items():- basename = _locked_image_basename(value)- if (- _contains_token(brief, key)- or _contains_token(brief, value)- or _contains_token(brief, basename)- or basename in ref_basenames- or basename in assigned_filenames- ):- selected[key] = value- elif basename not in resolved_filenames:- unresolved[key] = value- if selected and unresolved:- return "explicit+unassigned", {**selected, **unresolved}- if selected:- return "explicit", selected- if unresolved:- return "unassigned", unresolved- return "confirmed-none", {}---def _page_template(- project_path: Path,- structure_lock: PptxStructureLock | None,- page_number: int,-) -> tuple[dict[str, object] | None, Path | None]:- if structure_lock is None or structure_lock.mode != "structured":- return None, None- prototype = next(- (item for item in structure_lock.prototypes if item.slide_num == page_number),- None,- )- assignment = next(- (item for item in structure_lock.layouts if item.slide_num == page_number),- None,- )- if prototype is None or assignment is None:- raise PageContextError(- f"structured lock has no complete mapping for P{page_number:02d}"- )- definition = next(- (- item- for item in structure_lock.layout_definitions- if item.layout_key == assignment.layout_key- ),- None,- )- if definition is None:- raise PageContextError(- f"structured lock has no definition for Layout {assignment.layout_key!r}"- )- master = next(- (- item- for item in structure_lock.masters- if item.master_key == definition.master_key- ),- None,- )- if master is None:- raise PageContextError(- f"structured lock has no definition for Master {definition.master_key!r}"- )- template = {- "reuse_scope": structure_lock.template_reuse_scope,- "adherence": structure_lock.template_adherence,- "prototype": prototype.template_basename,- "prototype_path": _relative_project_path(project_path, prototype.svg_path),- "layout": {- "key": definition.layout_key,- "name": definition.layout_name,- "source": (- f"P{definition.prototype_slide_num:02d}"- if definition.prototype_slide_num is not None- else _relative_project_path(- project_path,- definition.prototype_svg_path,- )- ),- },- "master": {- "key": master.master_key,- "name": master.master_name,- },- }- return template, prototype.svg_path---def _reference_payload(- kind: str,- path: Path,- *,- scope: str,- display_path: str,- same_context_edit_policy: str | None = None,-) -> dict[str, str]:- """Describe one large reference without injecting its contents per page."""- payload = {- "kind": kind,- "scope": scope,- "path": display_path,- "sha256": _file_sha256(path),- "load_policy": "once-per-execution-context",- }- if same_context_edit_policy is not None:- payload["same_context_edit_policy"] = same_context_edit_policy- 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"- )- return (- _reference_payload(- "chart-svg",- chart_path,- scope="skill",- display_path=f"templates/charts/{chart_path.name}",- ),- chart_path,- )---def build_page_context(project: str | Path, raw_page: str) -> PageContextResult:- """Build one current per-page projection without writing the project."""- project_path = Path(project).resolve()- if not project_path.is_dir():- raise PageContextError(f"project directory not found: {project_path}")- page, page_number = normalize_page_key(raw_page)- lock_path = project_path / "spec_lock.md"- design_path = project_path / "design_spec.md"- for required in (lock_path, design_path):- if not required.is_file():- raise PageContextError(f"required artifact not found: {required.name}")- preflight_errors, _preflight_warnings = validate_project_artifacts(- project_path,- include_design=False,- )- if preflight_errors:- preview = "; ".join(preflight_errors[:8])- suffix = (- ""- if len(preflight_errors) <= 8- else f"; +{len(preflight_errors) - 8} more"- )- raise PageContextError(- "spec_lock/template preflight failed before page generation: "- f"{preview}{suffix}"- )- try:- lock_sections_raw = parse_spec_lock_artifact(- lock_path,- report_duplicate_fields=True,- )- design_sections = parse_markdown_artifact(design_path)- except (OSError, ValueError) as exc:- raise PageContextError(str(exc)) from exc- lock_sections = _section_index(lock_sections_raw)- part, brief = _slide_block(design_sections, page_number)- warnings: list[str] = []- rhythm_fields = _section_fields(lock_sections, "page_rhythm")- rhythm = rhythm_fields.get(page)- 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)- try:- structure_lock = load_pptx_structure_lock(project_path)- except TemplateStructureError as exc:- raise PageContextError(str(exc)) from exc- template, prototype_path = _page_template(- project_path,- structure_lock,- page_number,- )- prototype_refs = (- _prototype_image_refs(prototype_path)- if prototype_path is not None- else []- )- table_assigned_filenames, assigned_filenames = _page_image_filenames(- design_sections,- page_number,- )- locked_images = _section_fields(lock_sections, "images")- resolved_filenames = (- {_locked_image_basename(value) for value in locked_images.values()}- if structure_lock is not None- and structure_lock.template_reuse_scope == "mirror"- else table_assigned_filenames- | _outline_image_assignments(design_sections, locked_images)- )- image_selection, selected_images = _page_images(- locked_images,- brief,- (- prototype_refs- if structure_lock is not None- and structure_lock.template_reuse_scope == "mirror"- else []- ),- assigned_filenames,- resolved_filenames,- )- inputs = [lock_path, design_path]- reference_set: list[dict[str, str]] = [- _reference_payload(- "design-spec",- design_path,- scope="project",- display_path="design_spec.md",- same_context_edit_policy="targeted-readback-and-rebind",- ),- ]- template_design_path = project_path / "templates" / "design_spec.md"- if template_design_path.is_file():- inputs.append(template_design_path)- reference_set.append(- _reference_payload(- "template-design-spec",- template_design_path,- scope="project",- display_path="templates/design_spec.md",- )- )- if prototype_path is not None:- inputs.append(prototype_path)- reference_set.append(- _reference_payload(- "prototype-svg",- prototype_path,- scope="project",- 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)- 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- # payloads stay outside it and are represented by reference_set.- global_context = {- "communication": _section_fields(lock_sections, "communication"),- "canvas": _section_fields(lock_sections, "canvas"),- "mode": mode_fields.get("mode"),- "mode_behavior": mode_fields.get("mode_behavior"),- "visual_style": visual_style_fields.get("visual_style"),- "visual_style_behavior": visual_style_fields.get(- "visual_style_behavior"- ),- "colors": _section_fields(lock_sections, "colors"),- "typography": _section_fields(lock_sections, "typography"),- "icons": _section_fields(lock_sections, "icons"),- "pptx_structure": _section_fields(lock_sections, "pptx_structure"),- "forbidden": _forbidden_items(lock_sections),- }- global_context = {- key: value- for key, value in global_context.items()- if value not in ({}, [], None, "")- }- current_page: dict[str, object] = {- "part": part,- "brief_markdown": brief,- "rhythm": rhythm,- "image_selection": image_selection,- }- if chart_key is not None:- current_page["chart"] = chart_key- if selected_images:- current_page["images"] = selected_images- if template is not None:- current_page["template"] = template- context: dict[str, object] = {- "schema": PAGE_CONTEXT_SCHEMA,- "page": page,- "lock_source": {- "path": "spec_lock.md",- "sha256": _file_sha256(lock_path),- "load_policy": "on-demand-anchor-projection",- },- "global": global_context,- "page_context": current_page,- "reference_set": reference_set,- }- if warnings:- context["warnings"] = warnings- unique_inputs = tuple(dict.fromkeys(path.resolve() for path in inputs))- return PageContextResult(- project_path=project_path,- page=page,- context=context,- inputs=unique_inputs,- )---def _compact_json(payload: object) -> str:- return json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"---def _pretty_json(payload: object) -> str:- return json.dumps(payload, ensure_ascii=False, indent=2) + "\n"---def render_page_context(- result: PageContextResult,- *,- bundle: bool = False,- pretty: bool = False,-) -> tuple[str, tuple[PageRead, ...]]:- """Render compact stdout; ``bundle`` remains a compatibility no-op."""- context_payload = (- _pretty_json(result.context) if pretty else _compact_json(result.context)- )- context_read = PageRead(- kind="page-context",- path="stdout:page-context",- payload=context_payload,- )- return context_payload, (context_read,)---def _sha256_bytes(payload: bytes) -> str:- return hashlib.sha256(payload).hexdigest()---def _file_sha256(path: Path) -> str:- digest = hashlib.sha256()- with path.open("rb") as stream:- for chunk in iter(lambda: stream.read(1024 * 1024), b""):- digest.update(chunk)- return digest.hexdigest()---def _input_location(project_path: Path, path: Path) -> tuple[str, str]:- """Return a stable project- or Skill-relative locator for telemetry."""- resolved = path.resolve()- for scope, root in (("project", project_path), ("skill", _SKILL_DIR)):- try:- return scope, resolved.relative_to(root.resolve()).as_posix()- except ValueError:- continue- raise PageContextError(f"input escapes project and Skill roots: {path}")---def _resolve_input_location(- project_path: Path,- scope: str,- relative_path: str,-) -> Path | None:- """Resolve one recorded input without accepting arbitrary filesystem roots."""- roots = {"project": project_path, "skill": _SKILL_DIR}- root = roots.get(scope)- if root is None:- return None- resolved = (root / relative_path).resolve()- try:- resolved.relative_to(root.resolve())- except ValueError:- return None- return resolved---def _token_counter() -> tuple[Callable[[str], int] | None, str]:- try:- import tiktoken- except ImportError:- return None, "unavailable"- try:- encoder = tiktoken.get_encoding(TOKEN_ENCODING)- except Exception:- return None, "unavailable"- return (- lambda text: len(encoder.encode(text, disallowed_special=())),- "exact",- )---def _payload_measurement(- read: PageRead,- count_tokens: Callable[[str], int] | None,-) -> dict[str, object]:- payload = read.payload.encode("utf-8")- measurement: dict[str, object] = {- "kind": read.kind,- "scope": "component" if read.kind == "lock-projection" else "page",- "path": read.path,- "sha256": _sha256_bytes(payload),- "utf8_bytes": len(payload),- "characters": len(read.payload),- "tokens": count_tokens(read.payload) if count_tokens else None,- }- return measurement---def record_page_context_usage(- result: PageContextResult,- output: str,- measured_reads: tuple[PageRead, ...],-) -> tuple[Path, str]:- """Write one deterministic, derived token snapshot for the current page."""- count_tokens, token_status = _token_counter()- lock_read = PageRead(- kind="lock-projection",- path="stdout:global",- payload=_compact_json(result.context["global"]),- )- documents = [- _payload_measurement(read, count_tokens)- for read in (*measured_reads, lock_read)- ]- output_bytes = output.encode("utf-8")- input_records: list[dict[str, object]] = []- for path in result.inputs:- scope, relative_path = _input_location(result.project_path, path)- input_records.append(- {- "scope": scope,- "path": relative_path,- "exists": True,- "sha256": _file_sha256(path),- }- )- by_kind = {- str(item["kind"]): item.get("tokens")- for item in documents- }- route = dict(result.context["global"].get("pptx_structure", {}))- template = result.context["page_context"].get("template")- if isinstance(template, dict):- if isinstance(value := template.get("reuse_scope"), str):- route["template_reuse_scope"] = value- usage = {- "schema": PAGE_CONTEXT_USAGE_SCHEMA,- "page": result.page,- "output_mode": "compact",- "route": route,- "encoding": TOKEN_ENCODING,- "token_status": token_status,- "image_selection": result.context["page_context"]["image_selection"],- "inputs": input_records,- "references": result.context.get("reference_set", []),- "documents": documents,- "controlled_output": {- "sha256": _sha256_bytes(output_bytes),- "utf8_bytes": len(output_bytes),- "characters": len(output),- "tokens": count_tokens(output) if count_tokens else None,- },- "totals": {- "page_context": by_kind.get("page-context"),- "lock_projection": by_kind.get("lock-projection"),- },- "targets": {- "page_context_max_tokens": PAGE_CONTEXT_TOKEN_TARGET,- "lock_projection_max_tokens": LOCK_PROJECTION_TOKEN_TARGET,- },- "untracked": [- "source-material reads",- "once-per-execution-context reference payloads",- "other session-level prompt references",- ],- }- usage_dir = result.project_path / "analysis" / "page-context"- usage_dir.mkdir(parents=True, exist_ok=True)- usage_path = usage_dir / f"{result.page}.usage.json"- temporary_path = usage_path.with_suffix(".usage.json.tmp")- temporary_path.write_text(_pretty_json(usage), encoding="utf-8")- temporary_path.replace(usage_path)- return usage_path, token_status---def _nearest_rank(values: list[int], percentile: float) -> int:- rank = max(1, math.ceil(percentile * len(values)))- return sorted(values)[rank - 1]---def _metric(values: list[int], *, target: int | None = None) -> dict[str, object]:- if not values:- return {- "count": 0,- "sum": 0,- "min": None,- "p50": None,- "p95": None,- "max": None,- **({"over_target_count": 0, "target": target} if target else {}),- }- metric: dict[str, object] = {- "count": len(values),- "sum": sum(values),- "min": min(values),- "p50": round(statistics.median(values)),- "p95": _nearest_rank(values, 0.95),- "max": max(values),- }- if target is not None:- metric.update({- "target": target,- "over_target_count": sum(value > target for value in values),- })- return metric---def page_context_usage_report(project: str | Path) -> dict[str, object]:- """Summarize fresh per-page telemetry without changing recorded history."""- project_path = Path(project).resolve()- usage_dir = project_path / "analysis" / "page-context"- records: list[dict[str, object]] = []- stale_pages: list[str] = []- unavailable_pages: list[str] = []- if usage_dir.is_dir():- for usage_path in sorted(usage_dir.glob("P*.usage.json")):- try:- record = json.loads(usage_path.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- stale_pages.append(usage_path.stem.split(".", 1)[0])- continue- page = str(record.get("page", usage_path.stem.split(".", 1)[0]))- if record.get("schema") != PAGE_CONTEXT_USAGE_SCHEMA:- stale_pages.append(page)- continue- if record.get("output_mode") != "compact":- stale_pages.append(page)- continue- stale = False- for item in record.get("inputs", []):- if not isinstance(item, dict):- stale = True- break- source_path = _resolve_input_location(- project_path,- str(item.get("scope", "project")),- str(item.get("path", "")),- )- if source_path is None:- stale = True- break- expected_exists = item.get("exists", True)- if expected_exists is False:- if source_path.exists():- stale = True- break- elif (- not source_path.is_file()- or _file_sha256(source_path) != item.get("sha256")- ):- stale = True- break- if stale:- stale_pages.append(page)- continue- if record.get("token_status") != "exact":- unavailable_pages.append(page)- records.append(record)-- def tokens_for(kind: str) -> list[int]:- values: list[int] = []- for record in records:- for document in record.get("documents", []):- if not isinstance(document, dict) or document.get("kind") != kind:- continue- value = document.get("tokens")- if isinstance(value, int):- values.append(value)- return values- controlled = [- value- for record in records- if isinstance(- value := record.get("controlled_output", {}).get("tokens"),- int,- )- ]- unique_references = sorted({- f"{reference.get('scope', 'project')}:{reference.get('path', '')}"- for record in records- for reference in record.get("references", [])- if isinstance(reference, dict) and reference.get("path")- })- return {- "schema": PAGE_CONTEXT_REPORT_SCHEMA,- "project": project_path.name,- "record_count": len(records),- "pages": sorted(str(record["page"]) for record in records),- "stale_pages": sorted(set(stale_pages)),- "token_unavailable_pages": sorted(set(unavailable_pages)),- "unique_reference_count": len(unique_references),- "unique_references": unique_references,- "metrics": {- "page_context": _metric(- tokens_for("page-context"),- target=PAGE_CONTEXT_TOKEN_TARGET,- ),- "lock_projection": _metric(- tokens_for("lock-projection"),- target=LOCK_PROJECTION_TOKEN_TARGET,- ),- "controlled_output": _metric(controlled),- },- }+__all__ = [+ "LOCK_PROJECTION_TOKEN_TARGET",+ "PAGE_CONTEXT_REPORT_SCHEMA",+ "PAGE_CONTEXT_SCHEMA",+ "PAGE_CONTEXT_TOKEN_TARGET",+ "PAGE_CONTEXT_USAGE_SCHEMA",+ "TOKEN_ENCODING",+ "PageContextError",+ "PageContextResult",+ "PageRead",+ "build_page_context",+ "normalize_page_key",+ "page_context_usage_report",+ "record_page_context_usage",+ "render_page_context",+]diff --git a/skills/ppt-master/scripts/project_management/__init__.py b/skills/ppt-master/scripts/project_management/__init__.pynew file mode 100644index 00000000..93a20f3b--- /dev/null+++ b/skills/ppt-master/scripts/project_management/__init__.py@@ -0,0 +1,16 @@+#!/usr/bin/env python3+"""+PPT Master - Project Management Internals++Internal project lifecycle, planning-artifact, and page-context implementation.+Use the stable ``scripts/project_manager.py`` entry point for CLI operations.++Usage:+ Imported by the top-level project-management compatibility modules.++Examples:+ from project_management.project_specs import validate_project_artifacts++Dependencies:+ Same as the selected project-management module.+"""diff --git a/skills/ppt-master/scripts/project_management/cli.py b/skills/ppt-master/scripts/project_management/cli.pynew file mode 100644index 00000000..b34b1b1e--- /dev/null+++ b/skills/ppt-master/scripts/project_management/cli.py@@ -0,0 +1,1298 @@+#!/usr/bin/env python3+"""PPT Master project-management CLI implementation.++Usage:+ python3 scripts/project_manager.py init <project_name> [--format ppt169] [--dir <path>] [--quick-generate]+ 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>+ python3 scripts/project_manager.py page-context <project_path> P07 [--record-usage]+ python3 scripts/project_manager.py page-context-report <project_path>++Examples:+ python3 scripts/project_manager.py init demo --format ppt169+ python3 scripts/project_manager.py validate projects/demo++Dependencies:+ Standard library plus local PPT Master project and source-conversion modules.+"""++from __future__ import annotations++import argparse+import filecmp+import json+import os+import re+import shutil+import subprocess+import sys+import tempfile+from datetime import datetime+from pathlib import Path+from urllib.parse import urlparse++from .page_context import (+ build_page_context,+ page_context_usage_report,+ record_page_context_usage,+ render_page_context,+)+from .paths import (+ PROJECTS_ROOT,+ REPO_ROOT,+ SCRIPTS_DIR,+ SOURCE_TO_MD_DIR,+)+from .project_specs import scaffold_project_artifact, validate_project_artifacts++try:+ from project_utils import (+ CANVAS_FORMATS,+ get_project_info as get_project_info_common,+ normalize_canvas_format,+ validate_project_structure,+ validate_svg_viewbox,+ )+except ImportError:+ tools_dir = SCRIPTS_DIR+ 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,+ normalize_canvas_format,+ validate_project_structure,+ validate_svg_viewbox,+ )++TOOLS_DIR = SCRIPTS_DIR+SOURCE_TO_MD_TOOLS_DIR = SOURCE_TO_MD_DIR+if str(SOURCE_TO_MD_TOOLS_DIR) not in sys.path:+ sys.path.insert(0, str(SOURCE_TO_MD_TOOLS_DIR))++from _dispatcher import ( # noqa: E402+ DOC_SUFFIXES,+ EXCEL_SUFFIXES,+ LEGACY_EXCEL_SUFFIXES,+ PDF_SUFFIXES,+ PRESENTATION_SUFFIXES,+ build_conversion_command,+)++SOURCE_DIRNAME = "sources"+TEXT_SOURCE_SUFFIXES = {".md", ".markdown", ".txt"}+TABLE_TEXT_SUFFIXES = {".csv", ".tsv"}+BITMAP_IMAGE_SUFFIXES = {+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif",+}+IMAGE_ASSET_SUFFIXES = BITMAP_IMAGE_SUFFIXES | {+ ".emf", ".wmf", ".svg",+}+++def _validate_image_manifest(+ payload: object,+ path: Path,+) -> list[dict]:+ """Require a safe, case-insensitively unique image manifest payload."""+ if not isinstance(payload, list):+ raise RuntimeError(+ f"Image manifest must be a JSON array: {path}"+ )++ seen_filenames: dict[str, str] = {}+ for index, item in enumerate(payload):+ if not isinstance(item, dict):+ raise RuntimeError(+ f"Existing image manifest item {index} must be an object: {path}"+ )+ filename = item.get("filename")+ if (+ not isinstance(filename, str)+ or not filename.strip()+ or filename in {".", ".."}+ or "/" in filename+ or "\\" in filename+ or ":" in filename+ or Path(filename).is_absolute()+ or Path(filename).name != filename+ ):+ raise RuntimeError(+ f"Image manifest item {index} has no safe bare filename: {path}"+ )+ normalized_filename = filename.casefold()+ if normalized_filename in seen_filenames:+ raise RuntimeError(+ f"Image manifest filename {filename!r} conflicts with "+ f"{seen_filenames[normalized_filename]!r} (case-insensitive): {path}"+ )+ seen_filenames[normalized_filename] = filename+ return payload+++def _read_existing_image_manifest(path: Path) -> list[dict]:+ """Load an existing project image manifest or fail closed on corruption."""+ if not path.exists():+ return []+ if not path.is_file():+ raise RuntimeError(f"Existing image manifest is not a regular file: {path}")+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise RuntimeError(+ f"Existing image manifest is unreadable: {path} ({exc}); "+ "repair or restore it before importing more assets"+ ) from exc+ return _validate_image_manifest(payload, path)+++def _write_json_atomic(path: Path, payload: object) -> None:+ """Write JSON through a same-directory temporary file and atomic rename."""+ fd, temp_name = tempfile.mkstemp(+ prefix=f"{path.stem}.",+ suffix=".tmp",+ dir=str(path.parent),+ )+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ json.dump(payload, handle, ensure_ascii=False, indent=2)+ handle.write("\n")+ os.replace(temp_name, path)+ except Exception:+ try:+ os.unlink(temp_name)+ except OSError:+ pass+ raise+++def is_url(value: str) -> bool:+ """Return whether a string looks like an HTTP(S) URL."""+ parsed = urlparse(value)+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc)+++def sanitize_name(value: str) -> str:+ """Sanitize a user-facing name into a filesystem-safe token."""+ safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in value.strip())+ safe = safe.strip("._")+ while "__" in safe:+ safe = safe.replace("__", "_")+ return safe[:120] or "source"+++def derive_url_basename(url: str) -> str:+ """Derive a stable base filename from a URL."""+ parsed = urlparse(url)+ parts = [sanitize_name(parsed.netloc)]+ if parsed.path and parsed.path != "/":+ path_part = sanitize_name(parsed.path.strip("/").replace("/", "_"))+ if path_part:+ parts.append(path_part)+ return "_".join(part for part in parts if part) or "web_source"+++def is_within_path(path: Path, parent: Path) -> bool:+ """Return whether `path` resolves inside `parent`."""+ try:+ path.resolve().relative_to(parent.resolve())+ return True+ except ValueError:+ return False+++def _has_usable_import(summary: dict[str, list[str]]) -> bool:+ """Return whether import-sources produced at least one usable source artifact."""+ return any(+ summary.get(key)+ for key in ("archived", "markdown", "assets", "images", "analysis")+ )+++class ProjectManager:+ """Create, inspect, validate, and populate project folders."""++ CANVAS_FORMATS = CANVAS_FORMATS++ 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,+ canvas_format: str = "ppt169",+ base_dir: str | None = None,+ *,+ quick_generate: bool = False,+ ) -> str:+ base_path = Path(base_dir) if base_dir else self.base_dir++ if (+ not project_name+ or project_name in {".", ".."}+ or Path(project_name).is_absolute()+ or "/" in project_name+ or "\\" in project_name+ ):+ raise ValueError(+ "Project name must be a single, non-absolute path component"+ )++ normalized_format = normalize_canvas_format(canvas_format)+ if normalized_format not in self.CANVAS_FORMATS:+ available = ", ".join(sorted(self.CANVAS_FORMATS.keys()))+ raise ValueError(+ f"Unsupported canvas format: {canvas_format} "+ f"(available: {available}; common alias: xhs -> xiaohongshu)"+ )++ date_str = datetime.now().strftime("%Y%m%d")+ # A name already carrying a `_<format>_<YYYYMMDD>` suffix (e.g. a full+ # project dir name pasted back into init) is used as-is — re-appending+ # would produce `name_ppt169_20260101_ppt169_20260102`.+ if re.search(rf"_{re.escape(normalized_format)}_\d{{8}}$", project_name):+ project_dir_name = project_name+ else:+ project_dir_name = f"{project_name}_{normalized_format}_{date_str}"+ project_path = base_path / project_dir_name++ if not is_within_path(project_path, base_path):+ raise ValueError(+ f"Project directory must stay within the base directory: {base_path}"+ )+ if project_path.exists():+ raise FileExistsError(f"Project directory already exists: {project_path}")++ project_dirs = (+ ("svg_output",)+ if quick_generate+ else (+ "svg_output",+ "svg_final",+ "images",+ "icons",+ "notes",+ "templates",+ "live_preview",+ SOURCE_DIRNAME,+ "analysis",+ "validation",+ "exports",+ )+ )+ for rel_path in project_dirs:+ (project_path / rel_path).mkdir(parents=True, exist_ok=True)++ canvas_info = self.CANVAS_FORMATS[normalized_format]+ if not quick_generate:+ readme_path = project_path / "README.md"+ readme_path.write_text(+ (+ f"# {project_name}\n\n"+ f"- Canvas format: {normalized_format}\n"+ f"- Created: {date_str}\n\n"+ "## Directories\n\n"+ "- `svg_output/`: raw SVG output\n"+ "- `svg_final/`: self-contained SVG visual preview; may be inserted manually as an SVG image, but PowerPoint Convert to Shape is unsupported\n"+ "- `images/`: runtime image pool; converter assets keep their original short filenames when possible\n"+ "- `icons/`: project icon set — selected library icons copied in (via icon_sync.py) plus any custom icons you add; embedded from here at export\n"+ "- `notes/`: speaker notes\n"+ "- `templates/`: project templates\n"+ "- `live_preview/`: browser preview runtime files and history (lock.json, server.log, edits.jsonl, annotations.jsonl)\n"+ "- `sources/`: source materials and normalized markdown\n"+ "- `analysis/`: machine-extracted intermediate analysis (PPTX intake, image_analysis.csv) — the pipeline's canonical must-read source/asset facts\n"+ "- `validation/`: SVG quality reports and PPTX postflight audit reports\n"+ "- `exports/`: final native DrawingML pptx deliverables only (timestamped); `_native_charts_tables.pptx` name with `--native-charts-and-tables`, `_narrated.pptx` name when narration audio is embedded\n"+ "- `backup/<timestamp>/`: svg_output/ archive (always written in default-flow mode; safe to delete old timestamps)\n"+ ),+ encoding="utf-8",+ )++ print(f"Project created: {project_path}")+ print(f"Canvas: {canvas_info['name']} ({canvas_info['dimensions']})")+ return str(project_path)++ def _source_dir(self, project_path: Path) -> Path:+ sources_dir = project_path / SOURCE_DIRNAME+ sources_dir.mkdir(parents=True, exist_ok=True)+ return sources_dir++ def _analysis_dir(self, project_path: Path) -> Path:+ analysis_dir = project_path / "analysis"+ analysis_dir.mkdir(parents=True, exist_ok=True)+ return analysis_dir++ def _ensure_unique_path(self, path: Path) -> Path:+ if not path.exists():+ return path++ suffix = path.suffix+ stem = path.stem+ counter = 2+ while True:+ candidate = path.with_name(f"{stem}_{counter}{suffix}")+ if not candidate.exists():+ return candidate+ counter += 1++ def _copy_or_move_file(self, source: Path, destination: Path, move: bool) -> Path:+ try:+ if source.resolve() == destination.resolve():+ return destination+ except FileNotFoundError:+ pass++ destination = self._ensure_unique_path(destination)+ if move:+ shutil.move(str(source), str(destination))+ else:+ shutil.copy2(source, destination)+ return destination++ def _copy_or_move_tree(self, source: Path, destination: Path, move: bool) -> Path:+ try:+ if source.resolve() == destination.resolve():+ return destination+ except FileNotFoundError:+ pass++ destination = self._ensure_unique_path(destination)+ if move:+ shutil.move(str(source), str(destination))+ else:+ shutil.copytree(source, destination)+ return destination++ def _run_tool(self, args: list[str]) -> None:+ child_env = os.environ.copy()+ child_env["PYTHONUTF8"] = "1"+ child_env["PYTHONIOENCODING"] = "utf-8:replace"+ try:+ result = subprocess.run(+ args,+ cwd=REPO_ROOT,+ check=True,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ env=child_env,+ )+ except FileNotFoundError as exc:+ raise RuntimeError(f"Missing executable: {args[0]}") from exc+ except subprocess.CalledProcessError as exc:+ details = (exc.stderr or exc.stdout or "").strip()+ raise RuntimeError(details or "tool execution failed") from exc++ if result.stdout.strip():+ print(result.stdout.strip())++ def _import_pdf(self, pdf_path: Path, markdown_path: Path) -> None:+ route = build_conversion_command(+ str(pdf_path),+ markdown_path,+ forced_type="pdf",+ )+ self._run_tool(route.command)++ def _import_doc(self, doc_path: Path, markdown_path: Path) -> None:+ route = build_conversion_command(+ str(doc_path),+ markdown_path,+ forced_type="doc",+ )+ self._run_tool(route.command)++ def _import_presentation(self, presentation_path: Path, markdown_path: Path) -> None:+ route = build_conversion_command(+ str(presentation_path),+ markdown_path,+ forced_type="pptx",+ )+ self._run_tool(route.command)++ def _import_pptx_intake(self, presentation_path: Path, project_dir: Path) -> Path:+ # Multi-deck intake: each PPTX writes its own `<stem>.identity.json` /+ # `<stem>.slide_library.json` and is merged into the single multi-deck+ # index `analysis/source_profile.json` (one entry per source deck).+ analysis_dir = self._analysis_dir(project_dir)+ self._run_tool(+ [+ sys.executable,+ str(TOOLS_DIR / "pptx_intake.py"),+ str(presentation_path),+ "-o",+ str(analysis_dir),+ ]+ )+ return analysis_dir++ def _import_excel(self, excel_path: Path, markdown_path: Path) -> None:+ route = build_conversion_command(+ str(excel_path),+ markdown_path,+ forced_type="excel",+ )+ self._run_tool(route.command)++ def _import_url(self, url: str, markdown_path: Path) -> None:+ route = build_conversion_command(+ url,+ markdown_path,+ forced_type="web",+ )+ self._run_tool(route.command)++ def _is_valid_imported_url_markdown(self, markdown_path: Path) -> bool:+ """Return whether web_to_md produced a usable Markdown source."""+ if not markdown_path.is_file():+ return False+ content = markdown_path.read_text(encoding="utf-8", errors="replace")+ if "[Failed URLs]:" in content:+ return False+ return bool(content.strip())++ def _archive_url_record(self, sources_dir: Path, url: str) -> Path:+ file_path = self._ensure_unique_path(sources_dir / f"{derive_url_basename(url)}.url.txt")+ file_path.write_text(+ f"URL: {url}\nImported: {datetime.now().isoformat(timespec='seconds')}\n",+ encoding="utf-8",+ )+ return file_path++ def _normalize_text_source(self, source_path: Path, sources_dir: Path) -> Path:+ target = self._ensure_unique_path(sources_dir / f"{source_path.stem}.md")+ content = source_path.read_text(encoding="utf-8", errors="replace")+ target.write_text(content, encoding="utf-8")+ return target++ def _canonicalize_markdown_content(self, content: str) -> str:+ canonical = content.replace("\r\n", "\n")+ canonical = re.sub(r"(?m)^(\s*Crawled:\s+).*$", r"\1__IGNORED__", canonical)+ canonical = re.sub(r"(?m)^(\s*Imported:\s+).*$", r"\1__IGNORED__", canonical)+ canonical = re.sub(r"([^\s\]()/]+_files)/", "__ASSET_DIR__/", canonical)+ return canonical.strip()++ def _find_equivalent_markdown(self, source_path: Path, sources_dir: Path) -> Path | None:+ source_content = source_path.read_text(encoding="utf-8", errors="replace")+ canonical_source = self._canonicalize_markdown_content(source_content)++ for existing in sorted(sources_dir.iterdir()):+ if existing.suffix.lower() not in {".md", ".markdown"}:+ continue+ try:+ if existing.resolve() == source_path.resolve():+ continue+ except FileNotFoundError:+ pass++ existing_content = existing.read_text(encoding="utf-8", errors="replace")+ if self._canonicalize_markdown_content(existing_content) == canonical_source:+ return existing++ return None++ def _companion_asset_dir(self, source_path: Path) -> Path | None:+ candidate = source_path.with_name(f"{source_path.stem}_files")+ if candidate.exists() and candidate.is_dir():+ return candidate+ return None++ def _rewrite_markdown_asset_refs(+ self,+ markdown_path: Path,+ original_asset_dirname: str,+ imported_asset_dirname: str,+ ) -> None:+ if original_asset_dirname == imported_asset_dirname:+ return++ content = markdown_path.read_text(encoding="utf-8", errors="replace")+ updated = content.replace(f"{original_asset_dirname}/", f"{imported_asset_dirname}/")+ if updated != content:+ markdown_path.write_text(updated, encoding="utf-8")++ def _merge_image_manifest(self, source_items: list[dict], destination_manifest: Path) -> None:+ """Merge per-source manifest items into the project-level manifest, keyed by filename."""+ _validate_image_manifest(source_items, destination_manifest)+ existing_data = _read_existing_image_manifest(destination_manifest)++ new_by_filename: dict[str, dict] = {}+ new_order: list[str] = []+ for item in source_items:+ filename = item.get("filename")+ if not isinstance(filename, str):+ continue+ normalized_filename = filename.casefold()+ if normalized_filename not in new_by_filename:+ new_order.append(normalized_filename)+ new_by_filename[normalized_filename] = item++ merged: list[dict] = []+ seen: set[str] = set()+ for item in existing_data:+ if not isinstance(item, dict):+ continue+ filename = item.get("filename")+ if not isinstance(filename, str):+ continue+ normalized_filename = filename.casefold()+ if normalized_filename in new_by_filename:+ merged.append(new_by_filename[normalized_filename])+ else:+ merged.append(item)+ seen.add(normalized_filename)++ for normalized_filename in new_order:+ if normalized_filename not in seen:+ merged.append(new_by_filename[normalized_filename])++ _validate_image_manifest(merged, destination_manifest)+ _write_json_atomic(destination_manifest, merged)++ @staticmethod+ def _namespace_from_asset_dir(asset_dir: Path) -> str:+ """Derive a per-source namespace from a `<stem>_files` companion directory name."""+ name = asset_dir.name+ suffix = "_files"+ return name[:-len(suffix)] if name.endswith(suffix) else name++ def _image_destination_name(+ self,+ images_dir: Path,+ source_file: Path,+ namespace: str,+ existing_manifest: dict[str, dict],+ occupied_names: set[str],+ ) -> str:+ """Return a short unique image filename for the runtime image pool."""+ candidate = images_dir / source_file.name+ if candidate.name.casefold() not in occupied_names:+ return source_file.name+ try:+ meta = existing_manifest.get(candidate.name, {})+ if (+ meta.get("source_namespace") == namespace+ and candidate.is_file()+ and filecmp.cmp(source_file, candidate, shallow=False)+ ):+ return candidate.name+ except OSError:+ pass++ stem = source_file.stem+ suffix = source_file.suffix+ counter = 2+ while True:+ candidate = images_dir / f"{stem}_{counter}{suffix}"+ if candidate.name.casefold() not in occupied_names:+ return candidate.name+ try:+ meta = existing_manifest.get(candidate.name, {})+ if (+ meta.get("source_namespace") == namespace+ and candidate.is_file()+ and filecmp.cmp(source_file, candidate, shallow=False)+ ):+ return candidate.name+ except OSError:+ pass+ counter += 1++ def _propagate_image_assets(self, asset_dir: Path, project_dir: Path) -> None:+ """Copy converter-generated image assets and manifest into project images/.++ Filenames are preserved when possible because source Markdown commonly+ uses short names that are meaningful in context. Only real collisions+ receive a compact numeric suffix.+ """+ manifest_path = asset_dir / "image_manifest.json"+ if not manifest_path.is_file():+ return++ try:+ source_payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ print(f"[WARN] Cannot read image manifest {manifest_path}: {exc}")+ return+ try:+ source_data = _validate_image_manifest(source_payload, manifest_path)+ except RuntimeError as exc:+ print(f"[WARN] {exc}")+ return++ images_dir = project_dir / "images"+ namespace = self._namespace_from_asset_dir(asset_dir)+ destination_manifest = images_dir / "image_manifest.json"+ existing_data = _read_existing_image_manifest(destination_manifest)+ images_dir.mkdir(parents=True, exist_ok=True)++ existing_manifest = {+ item["filename"]: item+ for item in existing_data+ }+ occupied_names = {+ path.name.casefold()+ for path in images_dir.iterdir()+ if path.is_file()+ }+ rename_map: dict[str, str] = {}++ copied_count = 0+ for source_file in sorted(asset_dir.iterdir()):+ if not source_file.is_file():+ continue+ if source_file.suffix.lower() not in IMAGE_ASSET_SUFFIXES:+ continue+ new_name = self._image_destination_name(+ images_dir,+ source_file,+ namespace,+ existing_manifest,+ occupied_names,+ )+ destination = images_dir / new_name+ if source_file.resolve() != destination.resolve():+ shutil.copy2(source_file, destination)+ occupied_names.add(new_name.casefold())+ rename_map[source_file.name] = new_name+ copied_count += 1++ rebased_items: list[dict] = []+ for item in source_data:+ if not isinstance(item, dict):+ continue+ original = item.get("filename")+ if not isinstance(original, str):+ continue+ new_item = dict(item)+ new_item["filename"] = rename_map.get(original, original)+ new_item["source_namespace"] = namespace+ rebased_items.append(new_item)++ self._merge_image_manifest(rebased_items, images_dir / "image_manifest.json")+ print(+ f"Propagated {copied_count} image asset(s) + manifest "+ f"from {asset_dir} → images/ (namespace: {namespace})"+ )++ def _propagate_companion_image_assets(self, markdown_path: Path, project_dir: Path) -> None:+ asset_dir = markdown_path.with_name(f"{markdown_path.stem}_files")+ if asset_dir.is_dir():+ self._propagate_image_assets(asset_dir, project_dir)++ def _import_markdown_with_assets(+ self,+ source_path: Path,+ sources_dir: Path,+ move: bool,+ ) -> tuple[Path, Path | None, str | None]:+ archived_markdown = self._copy_or_move_file(+ source_path,+ sources_dir / source_path.name,+ move=move,+ )++ profile_src = source_path.with_name(f"{source_path.stem}.conversion_profile.json")+ if profile_src.is_file():+ self._copy_or_move_file(+ profile_src,+ sources_dir / f"{archived_markdown.stem}.conversion_profile.json",+ move=move,+ )++ asset_dir = self._companion_asset_dir(source_path)+ if asset_dir is None:+ return archived_markdown, None, None++ imported_asset_dir = self._copy_or_move_tree(+ asset_dir,+ sources_dir / f"{archived_markdown.stem}_files",+ move=move,+ )+ self._rewrite_markdown_asset_refs(+ archived_markdown,+ original_asset_dirname=asset_dir.name,+ imported_asset_dirname=imported_asset_dir.name,+ )++ note = None+ if archived_markdown.stem != source_path.stem:+ note = (+ f"{source_path}: renamed imported markdown to {archived_markdown.name} "+ f"and rewrote asset references to {imported_asset_dir.name}/"+ )+ return archived_markdown, imported_asset_dir, note++ def import_sources(+ self,+ project_path: str,+ source_items: list[str],+ move: bool = False,+ copy: bool = False,+ ) -> dict[str, list[str]]:+ if move and copy:+ raise ValueError("--move and --copy are mutually exclusive")+ project_dir = Path(project_path)+ if not project_dir.exists() or not project_dir.is_dir():+ raise FileNotFoundError(f"Project directory not found: {project_dir}")+ if not source_items:+ raise ValueError("At least one source path or URL is required")++ sources_dir = self._source_dir(project_dir)+ summary: dict[str, list[str]] = {+ "archived": [],+ "url_records": [],+ "markdown": [],+ "assets": [],+ "images": [],+ "analysis": [],+ "notes": [],+ "skipped": [],+ }++ expanded_items: list[str] = []+ supplied_dirs: list[Path] = []+ for item in source_items:+ if is_url(item):+ expanded_items.append(item)+ continue+ item_path = Path(item)+ if item_path.is_dir():+ supplied_dirs.append(item_path)+ directory_files = sorted(+ path for path in item_path.iterdir() if path.is_file()+ )+ if directory_files:+ expanded_items.extend(str(path) for path in directory_files)+ summary["notes"].append(+ f"{item}: expanded directory into {len(directory_files)} file(s)"+ )+ else:+ summary["skipped"].append(f"{item}: directory contains no files")+ continue+ expanded_items.append(item)++ explicit_markdown_stems = {+ Path(item).stem+ for item in expanded_items+ if not is_url(item)+ and Path(item).exists()+ and Path(item).is_file()+ and Path(item).suffix.lower() in {".md", ".markdown"}+ }++ for item in expanded_items:+ if is_url(item):+ markdown_path = self._ensure_unique_path(+ sources_dir / f"{derive_url_basename(item)}.md"+ )+ try:+ self._import_url(item, markdown_path)+ except Exception as exc: # pragma: no cover - summary path+ archived = self._archive_url_record(sources_dir, item)+ summary["url_records"].append(str(archived))+ summary["skipped"].append(f"{item}: {exc}")+ continue++ if not self._is_valid_imported_url_markdown(markdown_path):+ markdown_path.unlink(missing_ok=True)+ archived = self._archive_url_record(sources_dir, item)+ summary["url_records"].append(str(archived))+ summary["skipped"].append(f"{item}: URL conversion produced no usable Markdown")+ continue++ summary["markdown"].append(str(markdown_path))+ self._propagate_companion_image_assets(markdown_path, project_dir)+ continue++ source_path = Path(item)+ if not source_path.exists():+ summary["skipped"].append(f"{item}: path not found")+ continue+ if source_path.is_dir():+ summary["skipped"].append(f"{item}: directories are not supported")+ continue++ inside_projects = is_within_path(source_path, PROJECTS_ROOT)+ if copy:+ effective_move = False+ elif inside_projects:+ effective_move = True+ else:+ effective_move = False+ if move and not inside_projects:+ print(+ f"note: {source_path} is outside {PROJECTS_ROOT}; copied "+ f"(not moved). Only sources under projects/ may be moved.",+ file=sys.stderr,+ )+ elif inside_projects and not move and not copy:+ print(+ f"note: {source_path} is under projects/; moved into the target "+ f"project. Pass --copy to preserve it.",+ file=sys.stderr,+ )+ suffix = source_path.suffix.lower()++ if suffix in {".md", ".markdown"}:+ duplicate_markdown = self._find_equivalent_markdown(source_path, sources_dir)+ if duplicate_markdown is not None:+ summary["markdown"].append(str(duplicate_markdown))+ self._propagate_companion_image_assets(duplicate_markdown, project_dir)+ summary["notes"].append(+ f"{item}: skipped duplicate markdown import because equivalent content already exists as {duplicate_markdown.name}"+ )+ continue++ archived_markdown, asset_dir, note = self._import_markdown_with_assets(+ source_path,+ sources_dir,+ move=effective_move,+ )+ summary["archived"].append(str(archived_markdown))+ summary["markdown"].append(str(archived_markdown))+ if asset_dir is not None:+ summary["assets"].append(str(asset_dir))+ self._propagate_image_assets(asset_dir, project_dir)+ if note:+ summary["notes"].append(note)+ continue++ archived_path = self._copy_or_move_file(+ source_path,+ sources_dir / source_path.name,+ move=effective_move,+ )+ summary["archived"].append(str(archived_path))++ if suffix in BITMAP_IMAGE_SUFFIXES:+ images_dir = project_dir / "images"+ images_dir.mkdir(parents=True, exist_ok=True)+ image_path = self._ensure_unique_path(images_dir / archived_path.name)+ shutil.copy2(archived_path, image_path)+ summary["images"].append(str(image_path))+ if image_path.name != archived_path.name:+ summary["notes"].append(+ f"{item}: copied runtime image as {image_path.name} "+ "to avoid a filename collision"+ )+ elif suffix in PDF_SUFFIXES:+ canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"+ if archived_path.stem in explicit_markdown_stems:+ summary["notes"].append(+ f"{item}: skipped PDF auto-conversion because a same-stem Markdown source was provided"+ )+ continue+ if canonical_markdown_path.exists():+ summary["markdown"].append(str(canonical_markdown_path))+ self._propagate_companion_image_assets(canonical_markdown_path, project_dir)+ summary["notes"].append(+ f"{item}: skipped PDF auto-conversion because {canonical_markdown_path.name} already exists"+ )+ continue+ markdown_path = canonical_markdown_path+ try:+ self._import_pdf(archived_path, markdown_path)+ summary["markdown"].append(str(markdown_path))+ self._propagate_companion_image_assets(markdown_path, project_dir)+ except Exception as exc: # pragma: no cover - summary path+ summary["skipped"].append(f"{item}: PDF conversion failed ({exc})")+ elif suffix in PRESENTATION_SUFFIXES:+ canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"+ try:+ intake_dir = self._import_pptx_intake(archived_path, project_dir)+ intake_str = str(intake_dir)+ if intake_str not in summary["analysis"]:+ summary["analysis"].append(intake_str)+ except Exception as exc: # pragma: no cover - summary path+ summary["notes"].append(f"{item}: PPTX intake analysis failed ({exc})")+ if archived_path.stem in explicit_markdown_stems:+ summary["notes"].append(+ f"{item}: skipped presentation auto-conversion because a same-stem Markdown source was provided"+ )+ continue+ if canonical_markdown_path.exists():+ summary["markdown"].append(str(canonical_markdown_path))+ self._propagate_companion_image_assets(canonical_markdown_path, project_dir)+ summary["notes"].append(+ f"{item}: skipped presentation auto-conversion because {canonical_markdown_path.name} already exists"+ )+ continue+ markdown_path = canonical_markdown_path+ try:+ self._import_presentation(archived_path, markdown_path)+ summary["markdown"].append(str(markdown_path))+ self._propagate_companion_image_assets(markdown_path, project_dir)+ except Exception as exc: # pragma: no cover - summary path+ summary["skipped"].append(f"{item}: presentation conversion failed ({exc})")+ elif suffix in EXCEL_SUFFIXES:+ canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"+ if archived_path.stem in explicit_markdown_stems:+ summary["notes"].append(+ f"{item}: skipped Excel auto-conversion because a same-stem Markdown source was provided"+ )+ continue+ if canonical_markdown_path.exists():+ summary["markdown"].append(str(canonical_markdown_path))+ self._propagate_companion_image_assets(canonical_markdown_path, project_dir)+ summary["notes"].append(+ f"{item}: skipped Excel auto-conversion because {canonical_markdown_path.name} already exists"+ )+ continue+ markdown_path = canonical_markdown_path+ try:+ self._import_excel(archived_path, markdown_path)+ summary["markdown"].append(str(markdown_path))+ self._propagate_companion_image_assets(markdown_path, project_dir)+ except Exception as exc: # pragma: no cover - summary path+ summary["skipped"].append(f"{item}: Excel conversion failed ({exc})")+ elif suffix in LEGACY_EXCEL_SUFFIXES:+ summary["notes"].append(+ f"{item}: archived only; legacy .xls is not converted automatically. "+ "Resave as .xlsx to generate Markdown."+ )+ elif suffix in TABLE_TEXT_SUFFIXES:+ summary["notes"].append(+ f"{item}: archived as a plain-text table source; no Markdown conversion needed"+ )+ elif suffix in DOC_SUFFIXES:+ canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"+ if archived_path.stem in explicit_markdown_stems:+ summary["notes"].append(+ f"{item}: skipped document auto-conversion because a same-stem Markdown source was provided"+ )+ continue+ if canonical_markdown_path.exists():+ summary["markdown"].append(str(canonical_markdown_path))+ self._propagate_companion_image_assets(canonical_markdown_path, project_dir)+ summary["notes"].append(+ f"{item}: skipped document auto-conversion because {canonical_markdown_path.name} already exists"+ )+ continue+ markdown_path = canonical_markdown_path+ try:+ self._import_doc(archived_path, markdown_path)+ summary["markdown"].append(str(markdown_path))+ self._propagate_companion_image_assets(markdown_path, project_dir)+ except Exception as exc: # pragma: no cover - summary path+ summary["skipped"].append(f"{item}: document conversion failed ({exc})")+ elif suffix == ".txt":+ markdown_path = self._normalize_text_source(archived_path, sources_dir)+ summary["markdown"].append(str(markdown_path))+ else:+ summary["notes"].append(f"{item}: archived only, no automatic conversion")++ # Cleanup: only a projects-local source directory may be removed after+ # its files move into the target project. Every other location is copied+ # and remains untouched, even when the caller passes --move.+ for directory in supplied_dirs:+ if copy or not is_within_path(directory, PROJECTS_ROOT):+ continue+ if directory.is_dir() and not any(directory.iterdir()):+ try:+ directory.rmdir()+ except OSError:+ continue+ summary["notes"].append(+ f"{directory}: removed empty source directory after import"+ )++ return summary++ def validate_project(self, project_path: str) -> tuple[bool, list[str], list[str]]:+ project_path_obj = Path(project_path)+ _, 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))+ if info.get("svg_files"):+ svg_files = [project_path_obj / "svg_output" / name for name in info["svg_files"]]+ expected_format = info.get("format")+ if expected_format == "unknown":+ expected_format = None+ warnings.extend(validate_svg_viewbox(svg_files, expected_format))++ return not errors, list(dict.fromkeys(errors)), warnings++ def get_project_info(self, project_path: str) -> dict[str, object]:+ shared = get_project_info_common(project_path)+ return {+ "name": shared.get("name", Path(project_path).name),+ "path": shared.get("path", str(project_path)),+ "exists": shared.get("exists", False),+ "svg_count": shared.get("svg_count", 0),+ "has_spec": shared.get("has_spec", False),+ "has_source": shared.get("has_source", False),+ "source_count": shared.get("source_count", 0),+ "canvas_format": shared.get("format_name", "Unknown"),+ "create_date": shared.get("date_formatted", "Unknown"),+ }+++def build_parser() -> argparse.ArgumentParser:+ """Build the command-line parser."""+ parser = argparse.ArgumentParser(+ description="PPT Master project management helpers.",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog="""Examples:+ python3 scripts/project_manager.py init demo --format ppt169+ python3 scripts/project_manager.py import-sources projects/demo file.md+ python3 scripts/project_manager.py scaffold-spec projects/demo_ppt169_20260718+ python3 scripts/project_manager.py scaffold-lock projects/demo_ppt169_20260718+ python3 scripts/project_manager.py validate projects/demo+ python3 scripts/project_manager.py info projects/demo+ python3 scripts/project_manager.py page-context projects/demo P07 --record-usage+ python3 scripts/project_manager.py page-context-report projects/demo+""",+ )+ subparsers = parser.add_subparsers(dest="command", required=True)++ init = subparsers.add_parser("init", help="Create a project directory")+ init.add_argument("project_name", help="Project name")+ init.add_argument("--format", default="ppt169", help="Canvas format (default: ppt169)")+ init.add_argument("--dir", default=None, help="Base directory for the project")+ init.add_argument(+ "--quick-generate",+ action="store_true",+ help="Create only the svg_output directory and omit README.md",+ )++ import_sources = subparsers.add_parser(+ "import-sources",+ help="Import source files or URLs into a project",+ )+ import_sources.add_argument("project_path", help="Project directory")+ import_sources.add_argument("sources", nargs="+", help="Source files, directories, or URLs")+ mode = import_sources.add_mutually_exclusive_group()+ mode.add_argument(+ "--move",+ action="store_true",+ help="Move local sources under projects/; sources elsewhere are copied",+ )+ 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")++ info = subparsers.add_parser("info", help="Print project metadata")+ info.add_argument("project_path", help="Project directory")++ page_context = subparsers.add_parser(+ "page-context",+ help="Print one deterministic per-page execution view",+ )+ page_context.add_argument("project_path", help="Project directory")+ page_context.add_argument("page", help="Positive page key such as P07")+ page_context.add_argument(+ "--bundle",+ action="store_true",+ help="Deprecated compatibility flag; output remains compact",+ )+ page_context.add_argument(+ "--pretty",+ action="store_true",+ help="Pretty-print the page-context JSON payload",+ )+ page_context.add_argument(+ "--record-usage",+ action="store_true",+ help="Write compact-output token telemetry under analysis/page-context/",+ )++ page_context_report = subparsers.add_parser(+ "page-context-report",+ help="Summarize fresh per-page context telemetry",+ )+ page_context_report.add_argument("project_path", help="Project directory")+ return parser+++def main(argv: list[str] | None = None) -> int:+ """Run the CLI entry point."""+ parser = build_parser()+ args = parser.parse_args(argv)+ manager = ProjectManager()++ try:+ if args.command == "init":+ project_path = manager.init_project(+ args.project_name,+ args.format,+ base_dir=args.dir,+ quick_generate=args.quick_generate,+ )+ print(f"[OK] Project initialized: {project_path}")+ print("Next:")+ if args.quick_generate:+ print("1. Generate SVG files into svg_output/")+ print("2. Run the Quick Generate final checker and exporter")+ else:+ print("1. Put source files into sources/ (or use import-sources)")+ print("2. Save your design spec to the project root")+ print("3. Generate SVG files into svg_output/")+ return 0++ if args.command == "import-sources":+ summary = manager.import_sources(+ args.project_path,+ args.sources,+ move=args.move,+ copy=args.copy,+ )+ has_usable_import = _has_usable_import(summary)+ if has_usable_import:+ print(f"[OK] Imported sources into: {args.project_path}")+ else:+ print(+ f"[ERROR] No usable sources imported into: {args.project_path}",+ file=sys.stderr,+ )+ if summary["archived"]:+ print("\nArchived originals:")+ for item in summary["archived"]:+ print(f" - {item}")+ if summary["url_records"]:+ print("\nArchived URL records:")+ for item in summary["url_records"]:+ print(f" - {item}")+ if summary["markdown"]:+ print("\nNormalized markdown:")+ for item in summary["markdown"]:+ print(f" - {item}")+ if summary["assets"]:+ print("\nImported asset directories:")+ for item in summary["assets"]:+ print(f" - {item}")+ if summary["images"]:+ print("\nRuntime image copies:")+ for item in summary["images"]:+ print(f" - {item}")+ if summary["analysis"]:+ print("\nAnalysis artifacts:")+ for item in summary["analysis"]:+ print(f" - {item}")+ if summary["notes"]:+ print("\nNotes:")+ for item in summary["notes"]:+ print(f" - {item}")+ if summary["skipped"]:+ print("\nSkipped:")+ for item in summary["skipped"]:+ print(f" - {item}")+ return 0 if has_usable_import else 1++ 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_path+ is_valid, errors, warnings = manager.validate_project(project_path)++ print(f"\nProject validation: {project_path}")+ print("=" * 60)++ if errors:+ print("\n[ERROR]")+ for error in errors:+ print(f" - {error}")++ if warnings:+ print("\n[WARN]")+ for warning in warnings:+ print(f" - {warning}")++ if is_valid and not warnings:+ print("\n[OK] Project structure is complete.")+ elif is_valid:+ print("\n[OK] Project structure is valid, with warnings.")+ else:+ print("\n[ERROR] Project structure is invalid.")+ return 1+ return 0++ if args.command == "info":+ project_path = args.project_path+ info = manager.get_project_info(project_path)++ print(f"\nProject info: {info['name']}")+ print("=" * 60)+ print(f"Path: {info['path']}")+ print(f"Exists: {'Yes' if info['exists'] else 'No'}")+ print(f"SVG files: {info['svg_count']}")+ print(f"Design spec: {'Yes' if info['has_spec'] else 'No'}")+ print(f"Source materials: {'Yes' if info['has_source'] else 'No'}")+ print(f"Source count: {info['source_count']}")+ print(f"Canvas format: {info['canvas_format']}")+ print(f"Created: {info['create_date']}")+ return 0++ if args.command == "page-context":+ result = build_page_context(args.project_path, args.page)+ output, measured_reads = render_page_context(+ result,+ bundle=args.bundle,+ pretty=args.pretty,+ )+ if args.record_usage:+ _usage_path, token_status = record_page_context_usage(+ result,+ output,+ measured_reads,+ )+ if token_status != "exact":+ print(+ "[WARN] tiktoken/o200k_base unavailable; recorded bytes "+ "and hashes without token counts",+ file=sys.stderr,+ )+ print(output, end="")+ return 0++ if args.command == "page-context-report":+ report = page_context_usage_report(args.project_path)+ print(json.dumps(report, ensure_ascii=False, indent=2))+ return 0++ parser.error(f"Unknown command: {args.command}")+ except Exception as exc:+ print(f"[ERROR] {exc}")+ return 1diff --git a/skills/ppt-master/scripts/project_management/page_context.py b/skills/ppt-master/scripts/project_management/page_context.pynew file mode 100644index 00000000..3bbf2732--- /dev/null+++ b/skills/ppt-master/scripts/project_management/page_context.py@@ -0,0 +1,916 @@+#!/usr/bin/env python3+"""+PPT Master - Page Context Projection++Build deterministic per-page execution views and optional token telemetry.++Usage:+ Imported by project_management.cli.++Examples:+ build_page_context(Path("projects/demo"), "P07")++Dependencies:+ None for projection; tiktoken is optional for exact usage counts.+"""++from __future__ import annotations++import hashlib+import json+import math+import re+import statistics+import xml.etree.ElementTree as ET+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,+ parse_markdown_artifact,+ parse_spec_lock_artifact,+ validate_project_artifacts,+)+from svg_to_pptx.pptx_package.template_structure import (+ PptxStructureLock,+ TemplateStructureError,+ load_pptx_structure_lock,+)+++PAGE_CONTEXT_SCHEMA = "ppt-master.page-context.v2"+PAGE_CONTEXT_USAGE_SCHEMA = "ppt-master.page-context-usage.v2"+PAGE_CONTEXT_REPORT_SCHEMA = "ppt-master.page-context-usage-report.v2"+TOKEN_ENCODING = "o200k_base"+PAGE_CONTEXT_TOKEN_TARGET = 2000+LOCK_PROJECTION_TOKEN_TARGET = 1000++_PAGE_RE = re.compile(r"^(?:P)?([0-9]+)$", re.IGNORECASE)+_SLIDE_HEADING_RE = re.compile(+ r"^#{3,6}[ \t]+Slide[ \t]+0*([0-9]+)(?:[ \t]*(?:[-:–—]).*)?$",+ re.IGNORECASE | re.MULTILINE,+)+_BLOCK_BOUNDARY_RE = re.compile(r"^#{2,6}[ \t]+", re.MULTILINE)+_PART_HEADING_RE = re.compile(r"^###[ \t]+(?!#)(.+?)[ \t]*$", re.MULTILINE)+_PAGE_TOKEN_RE = re.compile(+ r"(?<![A-Za-z0-9_])P0*([1-9][0-9]*)(?![A-Za-z0-9_])",+ re.IGNORECASE,+)+++class PageContextError(RuntimeError):+ """Reject an incomplete or ambiguous page-context request."""+++@dataclass(frozen=True)+class PageRead:+ """One exact model-visible page payload."""++ kind: str+ path: str+ payload: str+++@dataclass(frozen=True)+class PageContextResult:+ """One projected page view plus the files that make it current."""++ project_path: Path+ page: str+ context: dict[str, object]+ inputs: tuple[Path, ...]+++def normalize_page_key(raw_page: str) -> tuple[str, int]:+ """Normalize a positive page identifier to the schema's P<NN> form."""+ match = _PAGE_RE.fullmatch(raw_page.strip())+ if match is None or int(match.group(1)) <= 0:+ raise PageContextError("page must be a positive P<NN> identifier")+ number = int(match.group(1))+ return f"P{number:02d}", number+++def _section_index(+ sections: Iterable[dict[str, object]],+) -> dict[str, dict[str, object]]:+ return {+ str(section["heading"]).strip().casefold(): section+ for section in sections+ }+++def _section_fields(+ sections: dict[str, dict[str, object]],+ heading: str,+) -> dict[str, str]:+ section = sections.get(heading.casefold())+ if section is None:+ return {}+ fields = section.get("fields", {})+ if not isinstance(fields, dict):+ return {}+ return {str(key): str(value) for key, value in fields.items()}+++def _forbidden_items(+ sections: dict[str, dict[str, object]],+) -> list[str]:+ section = sections.get("forbidden")+ if section is None:+ return []+ items: list[str] = []+ default_items = default_spec_lock_forbidden()+ for raw_line in str(section.get("body", "")).splitlines():+ line = raw_line.strip()+ if not line:+ continue+ item = re.sub(r"^-[ \t]+", "", line)+ if item not in default_items:+ items.append(item)+ return items+++def _outline_section(+ sections: Iterable[dict[str, object]],+) -> dict[str, object] | None:+ for section in sections:+ heading = str(section.get("heading", "")).strip().casefold()+ if heading == "content outline" or heading.endswith(". content outline"):+ return section+ return None+++def _page_image_filenames(+ design_sections: Iterable[dict[str, object]],+ page_number: int,+) -> tuple[set[str], set[str]]:+ """Read explicit P<NN> usage from the canonical image-resource table."""+ section = next(+ (+ item+ for item in design_sections+ if (+ (heading := str(item.get("heading", "")).strip().casefold())+ == "image resource list"+ or heading.startswith("viii. image resource list")+ )+ ),+ None,+ )+ if section is None:+ return set(), set()+ table_rows = [+ [+ cell.strip().replace(r"\|", "|")+ for cell in re.split(r"(?<!\\)\|", line.strip().strip("|"))+ ]+ for line in str(section.get("body", "")).splitlines()+ if line.strip().startswith("|") and line.strip().endswith("|")+ ]+ if not table_rows:+ return set(), set()+ header = {+ name.casefold(): index+ for index, name in enumerate(table_rows[0])+ }+ filename_index = header.get("filename")+ purpose_index = header.get("purpose")+ if filename_index is None or purpose_index is None:+ return set(), set()+ assigned: set[str] = set()+ selected: set[str] = set()+ for row in table_rows[1:]:+ if len(row) <= max(filename_index, purpose_index):+ continue+ purpose = row[purpose_index]+ pages = {int(match.group(1)) for match in _PAGE_TOKEN_RE.finditer(purpose)}+ if not pages:+ continue+ filename = row[filename_index].strip().strip("`")+ if not filename:+ continue+ basename = Path(filename).name+ assigned.add(basename)+ if page_number in pages:+ selected.add(basename)+ return assigned, selected+++def _locked_image_basename(value: str) -> str:+ return Path(value.split("|", 1)[0].strip()).name+++def _outline_image_assignments(+ design_sections: Iterable[dict[str, object]],+ locked_images: dict[str, str],+) -> set[str]:+ outline = _outline_section(design_sections)+ if outline is None:+ return set()+ body = str(outline.get("body", ""))+ return {+ _locked_image_basename(value)+ for key, value in locked_images.items()+ if any(+ _contains_token(body, token)+ for token in (+ key,+ value.split("|", 1)[0].strip(),+ _locked_image_basename(value),+ )+ )+ }+++def _slide_block(+ design_sections: Iterable[dict[str, object]],+ page_number: int,+) -> tuple[str | None, str]:+ outline = _outline_section(design_sections)+ if outline is None:+ raise PageContextError("design_spec.md has no Content Outline section")+ body = str(outline.get("body", ""))+ matches = [+ match+ for match in _SLIDE_HEADING_RE.finditer(body)+ if int(match.group(1)) == page_number+ ]+ if not matches:+ raise PageContextError(+ f"design_spec.md Content Outline has no Slide {page_number:02d} block"+ )+ if len(matches) > 1:+ raise PageContextError(+ f"design_spec.md Content Outline repeats Slide {page_number:02d}"+ )+ match = matches[0]+ next_boundary = _BLOCK_BOUNDARY_RE.search(body, match.end())+ block_end = next_boundary.start() if next_boundary else len(body)+ block = body[match.start():block_end].strip()+ part_matches = list(_PART_HEADING_RE.finditer(body, 0, match.start()))+ part = part_matches[-1].group(1).strip() if part_matches else None+ return part, block+++def _relative_project_path(project_path: Path, path: Path) -> str:+ try:+ return path.resolve().relative_to(project_path).as_posix()+ except ValueError as exc:+ raise PageContextError(f"path escapes project: {path}") from exc+++def _prototype_image_refs(svg_path: Path) -> list[str]:+ try:+ root = ET.parse(svg_path).getroot()+ except (OSError, ET.ParseError) as exc:+ raise PageContextError(f"cannot read prototype SVG {svg_path}: {exc}") from exc+ refs: set[str] = set()+ for element in root.iter():+ if element.tag.rsplit("}", 1)[-1] != "image":+ continue+ for name, value in element.attrib.items():+ if name.rsplit("}", 1)[-1] != "href":+ continue+ normalized = value.strip()+ if normalized and not normalized.startswith(("data:", "#")):+ refs.add(normalized)+ return sorted(refs)+++def _contains_token(text: str, token: str) -> bool:+ if not token:+ return False+ if re.fullmatch(r"[A-Za-z0-9_]+", token):+ return re.search(+ rf"(?<![A-Za-z0-9_]){re.escape(token)}(?![A-Za-z0-9_])",+ text,+ ) is not None+ return token in text+++def _page_images(+ locked_images: dict[str, str],+ brief: str,+ prototype_refs: list[str],+ assigned_filenames: set[str],+ resolved_filenames: set[str],+) -> tuple[str, dict[str, str]]:+ if not locked_images:+ return "none", {}+ ref_basenames = {Path(ref).name for ref in prototype_refs}+ selected: dict[str, str] = {}+ unresolved: dict[str, str] = {}+ for key, value in locked_images.items():+ basename = _locked_image_basename(value)+ if (+ _contains_token(brief, key)+ or _contains_token(brief, value)+ or _contains_token(brief, basename)+ or basename in ref_basenames+ or basename in assigned_filenames+ ):+ selected[key] = value+ elif basename not in resolved_filenames:+ unresolved[key] = value+ if selected and unresolved:+ return "explicit+unassigned", {**selected, **unresolved}+ if selected:+ return "explicit", selected+ if unresolved:+ return "unassigned", unresolved+ return "confirmed-none", {}+++def _page_template(+ project_path: Path,+ structure_lock: PptxStructureLock | None,+ page_number: int,+) -> tuple[dict[str, object] | None, Path | None]:+ if structure_lock is None or structure_lock.mode != "structured":+ return None, None+ prototype = next(+ (item for item in structure_lock.prototypes if item.slide_num == page_number),+ None,+ )+ assignment = next(+ (item for item in structure_lock.layouts if item.slide_num == page_number),+ None,+ )+ if prototype is None or assignment is None:+ raise PageContextError(+ f"structured lock has no complete mapping for P{page_number:02d}"+ )+ definition = next(+ (+ item+ for item in structure_lock.layout_definitions+ if item.layout_key == assignment.layout_key+ ),+ None,+ )+ if definition is None:+ raise PageContextError(+ f"structured lock has no definition for Layout {assignment.layout_key!r}"+ )+ master = next(+ (+ item+ for item in structure_lock.masters+ if item.master_key == definition.master_key+ ),+ None,+ )+ if master is None:+ raise PageContextError(+ f"structured lock has no definition for Master {definition.master_key!r}"+ )+ template = {+ "reuse_scope": structure_lock.template_reuse_scope,+ "adherence": structure_lock.template_adherence,+ "prototype": prototype.template_basename,+ "prototype_path": _relative_project_path(project_path, prototype.svg_path),+ "layout": {+ "key": definition.layout_key,+ "name": definition.layout_name,+ "source": (+ f"P{definition.prototype_slide_num:02d}"+ if definition.prototype_slide_num is not None+ else _relative_project_path(+ project_path,+ definition.prototype_svg_path,+ )+ ),+ },+ "master": {+ "key": master.master_key,+ "name": master.master_name,+ },+ }+ return template, prototype.svg_path+++def _reference_payload(+ kind: str,+ path: Path,+ *,+ scope: str,+ display_path: str,+ same_context_edit_policy: str | None = None,+) -> dict[str, str]:+ """Describe one large reference without injecting its contents per page."""+ payload = {+ "kind": kind,+ "scope": scope,+ "path": display_path,+ "sha256": _file_sha256(path),+ "load_policy": "once-per-execution-context",+ }+ if same_context_edit_policy is not None:+ payload["same_context_edit_policy"] = same_context_edit_policy+ 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"+ )+ return (+ _reference_payload(+ "chart-svg",+ chart_path,+ scope="skill",+ display_path=f"templates/charts/{chart_path.name}",+ ),+ chart_path,+ )+++def build_page_context(project: str | Path, raw_page: str) -> PageContextResult:+ """Build one current per-page projection without writing the project."""+ project_path = Path(project).resolve()+ if not project_path.is_dir():+ raise PageContextError(f"project directory not found: {project_path}")+ page, page_number = normalize_page_key(raw_page)+ lock_path = project_path / "spec_lock.md"+ design_path = project_path / "design_spec.md"+ for required in (lock_path, design_path):+ if not required.is_file():+ raise PageContextError(f"required artifact not found: {required.name}")+ preflight_errors, _preflight_warnings = validate_project_artifacts(+ project_path,+ include_design=False,+ )+ if preflight_errors:+ preview = "; ".join(preflight_errors[:8])+ suffix = (+ ""+ if len(preflight_errors) <= 8+ else f"; +{len(preflight_errors) - 8} more"+ )+ raise PageContextError(+ "spec_lock/template preflight failed before page generation: "+ f"{preview}{suffix}"+ )+ try:+ lock_sections_raw = parse_spec_lock_artifact(+ lock_path,+ report_duplicate_fields=True,+ )+ design_sections = parse_markdown_artifact(design_path)+ except (OSError, ValueError) as exc:+ raise PageContextError(str(exc)) from exc+ lock_sections = _section_index(lock_sections_raw)+ part, brief = _slide_block(design_sections, page_number)+ warnings: list[str] = []+ rhythm_fields = _section_fields(lock_sections, "page_rhythm")+ rhythm = rhythm_fields.get(page)+ 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)+ try:+ structure_lock = load_pptx_structure_lock(project_path)+ except TemplateStructureError as exc:+ raise PageContextError(str(exc)) from exc+ template, prototype_path = _page_template(+ project_path,+ structure_lock,+ page_number,+ )+ prototype_refs = (+ _prototype_image_refs(prototype_path)+ if prototype_path is not None+ else []+ )+ table_assigned_filenames, assigned_filenames = _page_image_filenames(+ design_sections,+ page_number,+ )+ locked_images = _section_fields(lock_sections, "images")+ resolved_filenames = (+ {_locked_image_basename(value) for value in locked_images.values()}+ if structure_lock is not None+ and structure_lock.template_reuse_scope == "mirror"+ else table_assigned_filenames+ | _outline_image_assignments(design_sections, locked_images)+ )+ image_selection, selected_images = _page_images(+ locked_images,+ brief,+ (+ prototype_refs+ if structure_lock is not None+ and structure_lock.template_reuse_scope == "mirror"+ else []+ ),+ assigned_filenames,+ resolved_filenames,+ )+ inputs = [lock_path, design_path]+ reference_set: list[dict[str, str]] = [+ _reference_payload(+ "design-spec",+ design_path,+ scope="project",+ display_path="design_spec.md",+ same_context_edit_policy="targeted-readback-and-rebind",+ ),+ ]+ template_design_path = project_path / "templates" / "design_spec.md"+ if template_design_path.is_file():+ inputs.append(template_design_path)+ reference_set.append(+ _reference_payload(+ "template-design-spec",+ template_design_path,+ scope="project",+ display_path="templates/design_spec.md",+ )+ )+ if prototype_path is not None:+ inputs.append(prototype_path)+ reference_set.append(+ _reference_payload(+ "prototype-svg",+ prototype_path,+ scope="project",+ 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)+ 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+ # payloads stay outside it and are represented by reference_set.+ global_context = {+ "communication": _section_fields(lock_sections, "communication"),+ "canvas": _section_fields(lock_sections, "canvas"),+ "mode": mode_fields.get("mode"),+ "mode_behavior": mode_fields.get("mode_behavior"),+ "visual_style": visual_style_fields.get("visual_style"),+ "visual_style_behavior": visual_style_fields.get(+ "visual_style_behavior"+ ),+ "colors": _section_fields(lock_sections, "colors"),+ "typography": _section_fields(lock_sections, "typography"),+ "icons": _section_fields(lock_sections, "icons"),+ "pptx_structure": _section_fields(lock_sections, "pptx_structure"),+ "forbidden": _forbidden_items(lock_sections),+ }+ global_context = {+ key: value+ for key, value in global_context.items()+ if value not in ({}, [], None, "")+ }+ current_page: dict[str, object] = {+ "part": part,+ "brief_markdown": brief,+ "rhythm": rhythm,+ "image_selection": image_selection,+ }+ if chart_key is not None:+ current_page["chart"] = chart_key+ if selected_images:+ current_page["images"] = selected_images+ if template is not None:+ current_page["template"] = template+ context: dict[str, object] = {+ "schema": PAGE_CONTEXT_SCHEMA,+ "page": page,+ "lock_source": {+ "path": "spec_lock.md",+ "sha256": _file_sha256(lock_path),+ "load_policy": "on-demand-anchor-projection",+ },+ "global": global_context,+ "page_context": current_page,+ "reference_set": reference_set,+ }+ if warnings:+ context["warnings"] = warnings+ unique_inputs = tuple(dict.fromkeys(path.resolve() for path in inputs))+ return PageContextResult(+ project_path=project_path,+ page=page,+ context=context,+ inputs=unique_inputs,+ )+++def _compact_json(payload: object) -> str:+ return json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"+++def _pretty_json(payload: object) -> str:+ return json.dumps(payload, ensure_ascii=False, indent=2) + "\n"+++def render_page_context(+ result: PageContextResult,+ *,+ bundle: bool = False,+ pretty: bool = False,+) -> tuple[str, tuple[PageRead, ...]]:+ """Render compact stdout; ``bundle`` remains a compatibility no-op."""+ context_payload = (+ _pretty_json(result.context) if pretty else _compact_json(result.context)+ )+ context_read = PageRead(+ kind="page-context",+ path="stdout:page-context",+ payload=context_payload,+ )+ return context_payload, (context_read,)+++def _sha256_bytes(payload: bytes) -> str:+ return hashlib.sha256(payload).hexdigest()+++def _file_sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _input_location(project_path: Path, path: Path) -> tuple[str, str]:+ """Return a stable project- or Skill-relative locator for telemetry."""+ resolved = path.resolve()+ for scope, root in (("project", project_path), ("skill", _SKILL_DIR)):+ try:+ return scope, resolved.relative_to(root.resolve()).as_posix()+ except ValueError:+ continue+ raise PageContextError(f"input escapes project and Skill roots: {path}")+++def _resolve_input_location(+ project_path: Path,+ scope: str,+ relative_path: str,+) -> Path | None:+ """Resolve one recorded input without accepting arbitrary filesystem roots."""+ roots = {"project": project_path, "skill": _SKILL_DIR}+ root = roots.get(scope)+ if root is None:+ return None+ resolved = (root / relative_path).resolve()+ try:+ resolved.relative_to(root.resolve())+ except ValueError:+ return None+ return resolved+++def _token_counter() -> tuple[Callable[[str], int] | None, str]:+ try:+ import tiktoken+ except ImportError:+ return None, "unavailable"+ try:+ encoder = tiktoken.get_encoding(TOKEN_ENCODING)+ except Exception:+ return None, "unavailable"+ return (+ lambda text: len(encoder.encode(text, disallowed_special=())),+ "exact",+ )+++def _payload_measurement(+ read: PageRead,+ count_tokens: Callable[[str], int] | None,+) -> dict[str, object]:+ payload = read.payload.encode("utf-8")+ measurement: dict[str, object] = {+ "kind": read.kind,+ "scope": "component" if read.kind == "lock-projection" else "page",+ "path": read.path,+ "sha256": _sha256_bytes(payload),+ "utf8_bytes": len(payload),+ "characters": len(read.payload),+ "tokens": count_tokens(read.payload) if count_tokens else None,+ }+ return measurement+++def record_page_context_usage(+ result: PageContextResult,+ output: str,+ measured_reads: tuple[PageRead, ...],+) -> tuple[Path, str]:+ """Write one deterministic, derived token snapshot for the current page."""+ count_tokens, token_status = _token_counter()+ lock_read = PageRead(+ kind="lock-projection",+ path="stdout:global",+ payload=_compact_json(result.context["global"]),+ )+ documents = [+ _payload_measurement(read, count_tokens)+ for read in (*measured_reads, lock_read)+ ]+ output_bytes = output.encode("utf-8")+ input_records: list[dict[str, object]] = []+ for path in result.inputs:+ scope, relative_path = _input_location(result.project_path, path)+ input_records.append(+ {+ "scope": scope,+ "path": relative_path,+ "exists": True,+ "sha256": _file_sha256(path),+ }+ )+ by_kind = {+ str(item["kind"]): item.get("tokens")+ for item in documents+ }+ route = dict(result.context["global"].get("pptx_structure", {}))+ template = result.context["page_context"].get("template")+ if isinstance(template, dict):+ if isinstance(value := template.get("reuse_scope"), str):+ route["template_reuse_scope"] = value+ usage = {+ "schema": PAGE_CONTEXT_USAGE_SCHEMA,+ "page": result.page,+ "output_mode": "compact",+ "route": route,+ "encoding": TOKEN_ENCODING,+ "token_status": token_status,+ "image_selection": result.context["page_context"]["image_selection"],+ "inputs": input_records,+ "references": result.context.get("reference_set", []),+ "documents": documents,+ "controlled_output": {+ "sha256": _sha256_bytes(output_bytes),+ "utf8_bytes": len(output_bytes),+ "characters": len(output),+ "tokens": count_tokens(output) if count_tokens else None,+ },+ "totals": {+ "page_context": by_kind.get("page-context"),+ "lock_projection": by_kind.get("lock-projection"),+ },+ "targets": {+ "page_context_max_tokens": PAGE_CONTEXT_TOKEN_TARGET,+ "lock_projection_max_tokens": LOCK_PROJECTION_TOKEN_TARGET,+ },+ "untracked": [+ "source-material reads",+ "once-per-execution-context reference payloads",+ "other session-level prompt references",+ ],+ }+ usage_dir = result.project_path / "analysis" / "page-context"+ usage_dir.mkdir(parents=True, exist_ok=True)+ usage_path = usage_dir / f"{result.page}.usage.json"+ temporary_path = usage_path.with_suffix(".usage.json.tmp")+ temporary_path.write_text(_pretty_json(usage), encoding="utf-8")+ temporary_path.replace(usage_path)+ return usage_path, token_status+++def _nearest_rank(values: list[int], percentile: float) -> int:+ rank = max(1, math.ceil(percentile * len(values)))+ return sorted(values)[rank - 1]+++def _metric(values: list[int], *, target: int | None = None) -> dict[str, object]:+ if not values:+ return {+ "count": 0,+ "sum": 0,+ "min": None,+ "p50": None,+ "p95": None,+ "max": None,+ **({"over_target_count": 0, "target": target} if target else {}),+ }+ metric: dict[str, object] = {+ "count": len(values),+ "sum": sum(values),+ "min": min(values),+ "p50": round(statistics.median(values)),+ "p95": _nearest_rank(values, 0.95),+ "max": max(values),+ }+ if target is not None:+ metric.update({+ "target": target,+ "over_target_count": sum(value > target for value in values),+ })+ return metric+++def page_context_usage_report(project: str | Path) -> dict[str, object]:+ """Summarize fresh per-page telemetry without changing recorded history."""+ project_path = Path(project).resolve()+ usage_dir = project_path / "analysis" / "page-context"+ records: list[dict[str, object]] = []+ stale_pages: list[str] = []+ unavailable_pages: list[str] = []+ if usage_dir.is_dir():+ for usage_path in sorted(usage_dir.glob("P*.usage.json")):+ try:+ record = json.loads(usage_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ stale_pages.append(usage_path.stem.split(".", 1)[0])+ continue+ page = str(record.get("page", usage_path.stem.split(".", 1)[0]))+ if record.get("schema") != PAGE_CONTEXT_USAGE_SCHEMA:+ stale_pages.append(page)+ continue+ if record.get("output_mode") != "compact":+ stale_pages.append(page)+ continue+ stale = False+ for item in record.get("inputs", []):+ if not isinstance(item, dict):+ stale = True+ break+ source_path = _resolve_input_location(+ project_path,+ str(item.get("scope", "project")),+ str(item.get("path", "")),+ )+ if source_path is None:+ stale = True+ break+ expected_exists = item.get("exists", True)+ if expected_exists is False:+ if source_path.exists():+ stale = True+ break+ elif (+ not source_path.is_file()+ or _file_sha256(source_path) != item.get("sha256")+ ):+ stale = True+ break+ if stale:+ stale_pages.append(page)+ continue+ if record.get("token_status") != "exact":+ unavailable_pages.append(page)+ records.append(record)++ def tokens_for(kind: str) -> list[int]:+ values: list[int] = []+ for record in records:+ for document in record.get("documents", []):+ if not isinstance(document, dict) or document.get("kind") != kind:+ continue+ value = document.get("tokens")+ if isinstance(value, int):+ values.append(value)+ return values++ controlled = [+ value+ for record in records+ if isinstance(+ value := record.get("controlled_output", {}).get("tokens"),+ int,+ )+ ]+ unique_references = sorted({+ f"{reference.get('scope', 'project')}:{reference.get('path', '')}"+ for record in records+ for reference in record.get("references", [])+ if isinstance(reference, dict) and reference.get("path")+ })+ return {+ "schema": PAGE_CONTEXT_REPORT_SCHEMA,+ "project": project_path.name,+ "record_count": len(records),+ "pages": sorted(str(record["page"]) for record in records),+ "stale_pages": sorted(set(stale_pages)),+ "token_unavailable_pages": sorted(set(unavailable_pages)),+ "unique_reference_count": len(unique_references),+ "unique_references": unique_references,+ "metrics": {+ "page_context": _metric(+ tokens_for("page-context"),+ target=PAGE_CONTEXT_TOKEN_TARGET,+ ),+ "lock_projection": _metric(+ tokens_for("lock-projection"),+ target=LOCK_PROJECTION_TOKEN_TARGET,+ ),+ "controlled_output": _metric(controlled),+ },+ }diff --git a/skills/ppt-master/scripts/project_management/paths.py b/skills/ppt-master/scripts/project_management/paths.pynew file mode 100644index 00000000..fbb3b9ca--- /dev/null+++ b/skills/ppt-master/scripts/project_management/paths.py@@ -0,0 +1,27 @@+#!/usr/bin/env python3+"""+PPT Master - Project Management Paths++Own the repository and Skill resource roots used by project-management modules.++Usage:+ Import the required path constants from project_management.paths.++Examples:+ from project_management.paths import PROJECTS_ROOT, SCHEMA_DIR++Dependencies:+ None (only uses the standard library)+"""++from pathlib import Path++PACKAGE_DIR = Path(__file__).resolve().parent+SCRIPTS_DIR = PACKAGE_DIR.parent+SKILL_DIR = SCRIPTS_DIR.parent+REPO_ROOT = SKILL_DIR.parent.parent+PROJECTS_ROOT = REPO_ROOT / "projects"+SOURCE_TO_MD_DIR = SCRIPTS_DIR / "source_to_md"+CHARTS_DIR = SKILL_DIR / "templates" / "charts"+SCHEMA_DIR = SKILL_DIR / "templates" / "schemas"+SCAFFOLD_DIR = SKILL_DIR / "templates" / "scaffolds"diff --git a/skills/ppt-master/scripts/project_management/project_specs.py b/skills/ppt-master/scripts/project_management/project_specs.pynew file mode 100644index 00000000..3260e0ee--- /dev/null+++ b/skills/ppt-master/scripts/project_management/project_specs.py@@ -0,0 +1,1370 @@+#!/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_management.project_specs import validate_markdown_schema++Dependencies:+ None (only uses the standard library and local project modules)+"""++from __future__ import annotations++import json+import math+import re+from pathlib import Path+from typing import Mapping++from .paths import (+ SCAFFOLD_DIR,+ SCHEMA_DIR,+ SCRIPTS_DIR,+ SKILL_DIR,+)++try:+ from project_utils import (+ CANVAS_FORMATS,+ get_project_info as get_project_info_common,+ validate_communication_trace,+ )+except ImportError:+ import sys++ tools_dir = SCRIPTS_DIR+ 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 = SCRIPTS_DIR++_CUSTOM_REFERENCE_CATALOGS = (+ ("mode", "mode", "mode_references", SKILL_DIR / "references" / "modes"),+ (+ "visual_style",+ "visual_style",+ "visual_style_references",+ SKILL_DIR / "references" / "visual-styles",+ ),+ (+ "colors",+ "image_rendering",+ "image_rendering_references",+ SKILL_DIR / "references" / "image-renderings",+ ),+)++_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,+)+_IMAGE_PATH_SUFFIXES = frozenset(+ {+ ".bmp",+ ".emf",+ ".gif",+ ".jpeg",+ ".jpg",+ ".png",+ ".svg",+ ".tif",+ ".tiff",+ ".webp",+ ".wmf",+ }+)+_IMAGE_ACQUISITION_SOURCES = frozenset(+ {"ai", "web", "user", "formula", "placeholder", "slice"}+)+_IMAGE_CROP_POLICIES = frozenset({"adaptive", "no-crop"})+_LEGACY_IMAGE_METADATA_KEYS = frozenset(+ {+ "image_rendering",+ "image_rendering_behavior",+ "image_rendering_references",+ }+)+_LEGACY_SPEC_LOCK_FORBIDDEN = frozenset({"Mixing icon libraries"})+_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 parse_markdown_artifact(+ markdown_path: Path,+ *,+ report_duplicate_fields: bool = False,+) -> list[dict[str, object]]:+ """Parse one Markdown planning artifact without changing it.++ This is the public read-only entry point for consumers that need the same+ heading/data-line grammar as schema validation. Keeping the parser here+ prevents runtime projections from drifting into their own lock grammar.+ """+ text = markdown_path.read_text(encoding="utf-8")+ sections, errors = _parse_markdown_sections(+ text,+ report_duplicate_fields=report_duplicate_fields,+ )+ if errors:+ raise ValueError("; ".join(errors))+ return sections+++def _looks_like_image_path(raw: str) -> bool:+ """Return whether one lock token looks like a project image path."""+ token = raw.strip().strip("`'\"").replace("\\", "/")+ return bool(token) and Path(token).suffix.casefold() in _IMAGE_PATH_SUFFIXES+++def parse_spec_lock_image_value(key: str, value: str) -> dict[str, str]:+ """Parse one image-lock row while preserving supported legacy rows.++ Current rows use ``<path> | source=... | pattern=... | crop=...``. Legacy+ rows remain readable, but any row that starts using named metadata must+ provide the complete current contract.+ """+ normalized_key = str(key).strip()+ normalized_value = str(value).strip()+ parts = [part.strip() for part in normalized_value.split("|")]+ path_part = parts[0] if parts else ""++ if _looks_like_image_path(normalized_key) and not _looks_like_image_path(path_part):+ parts.insert(0, normalized_key)+ path_part = normalized_key+ elif (+ len(parts) >= 2+ and parts[0].casefold() in _IMAGE_ACQUISITION_SOURCES+ and _looks_like_image_path(parts[1])+ ):+ path_part = parts[1]++ metadata_parts = [part for part in parts[1:] if "=" in part]+ if not metadata_parts:+ legacy_crop = (+ "no-crop"+ if any(+ re.search(r"(?<![a-z])no-crop(?![a-z])", part, re.IGNORECASE)+ for part in parts[1:]+ )+ else ""+ )+ return {+ "path": path_part,+ "source": "",+ "pattern": "",+ "crop": legacy_crop,+ "legacy": "true",+ }++ metadata: dict[str, str] = {}+ unsupported_parts: list[str] = []+ for part in parts[1:]:+ field, separator, raw = part.partition("=")+ if not separator:+ unsupported_parts.append(part)+ continue+ field = field.strip().casefold()+ if field in metadata:+ raise ValueError(f"repeats metadata field {field!r}")+ metadata[field] = raw.strip()++ expected_fields = {"source", "pattern", "crop"}+ unknown_fields = sorted(set(metadata) - expected_fields)+ missing_fields = sorted(expected_fields - set(metadata))+ if unsupported_parts:+ shown = ", ".join(repr(part) for part in unsupported_parts)+ raise ValueError(f"has unsupported metadata token(s) {shown}")+ if unknown_fields:+ raise ValueError(+ f"has unknown metadata field(s) {', '.join(unknown_fields)}"+ )+ if missing_fields:+ raise ValueError(+ f"misses metadata field(s) {', '.join(missing_fields)}"+ )+ if not _looks_like_image_path(path_part):+ raise ValueError(f"has invalid image path {path_part!r}")++ normalized_path = path_part.replace("\\", "/")+ path = Path(normalized_path)+ if (+ path.is_absolute()+ or len(path.parts) != 2+ or path.parts[0] != "images"+ or path.name in {"", ".", ".."}+ or ":" in path.name+ or normalized_path != f"images/{path.name}"+ ):+ raise ValueError(+ f"must use canonical project path images/<filename>, got {path_part!r}"+ )++ source = metadata["source"].casefold()+ if source not in _IMAGE_ACQUISITION_SOURCES:+ allowed = ", ".join(sorted(_IMAGE_ACQUISITION_SOURCES))+ raise ValueError(f"source must be one of {allowed}, got {metadata['source']!r}")+ if not metadata["pattern"]:+ raise ValueError("pattern must be non-empty")+ crop = metadata["crop"].casefold()+ if crop not in _IMAGE_CROP_POLICIES:+ allowed = ", ".join(sorted(_IMAGE_CROP_POLICIES))+ raise ValueError(f"crop must be one of {allowed}, got {metadata['crop']!r}")++ return {+ "path": normalized_path,+ "source": source,+ "pattern": metadata["pattern"],+ "crop": crop,+ "legacy": "false",+ }+++def parse_spec_lock_artifact(+ lock_path: Path,+ *,+ report_duplicate_fields: bool = False,+ compatibility_warnings: list[str] | None = None,+) -> list[dict[str, object]]:+ """Parse one execution lock and normalize supported legacy image rows.++ New locks use ``- <key>: <path> | source=... | pattern=... | crop=...``.+ Some versioned projects instead placed the image path before the colon.+ Preserve those projects by projecting the key path back into the value so+ every consumer sees the same path-first image value.+ """+ sections = parse_markdown_artifact(+ lock_path,+ report_duplicate_fields=report_duplicate_fields,+ )+ normalized_sections: list[dict[str, object]] = []+ compatibility_keys: list[str] = []++ for section in sections:+ if str(section.get("heading", "")).strip().casefold() != "images":+ normalized_sections.append(section)+ continue+ raw_fields = section.get("fields")+ if not isinstance(raw_fields, dict):+ normalized_sections.append(section)+ continue++ fields: dict[str, str] = {}+ for raw_key, raw_value in raw_fields.items():+ key = str(raw_key)+ value = str(raw_value).strip()+ value_path = value.split("|", 1)[0].strip()+ if _looks_like_image_path(key) and not _looks_like_image_path(value_path):+ value = f"{key} | {value}" if value else key+ compatibility_keys.append(key)+ fields[key] = value++ normalized_section = dict(section)+ normalized_section["fields"] = fields+ normalized_sections.append(normalized_section)++ if compatibility_warnings is not None and compatibility_keys:+ sample = ", ".join(compatibility_keys[:3])+ suffix = "" if len(compatibility_keys) <= 3 else ", ..."+ compatibility_warnings.append(+ f"{lock_path.name} images: normalized {len(compatibility_keys)} legacy "+ "path-as-key row(s); new locks should use '- <key>: <path> | "+ "source=... | pattern=... | crop=...' "+ f"(found: {sample}{suffix})"+ )+ return normalized_sections+++def parse_spec_lock(+ lock_path: Path,+ *,+ report_duplicate_fields: bool = False,+ compatibility_warnings: list[str] | None = None,+) -> dict[str, dict[str, str]]:+ """Return one execution lock as ``{section: {key: value}}`."""+ sections = parse_spec_lock_artifact(+ lock_path,+ report_duplicate_fields=report_duplicate_fields,+ compatibility_warnings=compatibility_warnings,+ )+ parsed: dict[str, dict[str, str]] = {}+ for section in sections:+ raw_fields = section.get("fields")+ if not isinstance(raw_fields, dict):+ continue+ parsed[str(section.get("heading", "")).strip()] = {+ str(key): str(value) for key, value in raw_fields.items()+ }+ return parsed+++def default_spec_lock_forbidden() -> frozenset[str]:+ """Return the versioned scaffold's universal forbidden-item defaults."""+ sections = parse_markdown_artifact(SCAFFOLD_DIR / "spec_lock.md")+ section = next(+ (+ item+ for item in sections+ if str(item.get("heading", "")).strip().casefold() == "forbidden"+ ),+ None,+ )+ if section is None:+ raise ValueError("spec-lock scaffold has no forbidden section")+ current = frozenset(+ re.sub(r"^-[ \t]+", "", line.strip())+ for line in str(section.get("body", "")).splitlines()+ if line.strip()+ )+ return current | _LEGACY_SPEC_LOCK_FORBIDDEN+++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}'"+ )++ field_value_rules = definition.get("field_value_rules", [])+ if isinstance(field_value_rules, list):+ for rule in field_value_rules:+ if not isinstance(rule, dict):+ continue+ key_pattern = rule.get("key_pattern")+ value_pattern = rule.get("value_pattern")+ if not isinstance(key_pattern, str) or not isinstance(+ value_pattern, str+ ):+ continue+ requirement = str(rule.get("requirement", "match its value grammar"))+ for field_name, raw_value in fields.items():+ if re.fullmatch(key_pattern, str(field_name)) is None:+ continue+ value = str(raw_value).strip()+ if bool(rule.get("normalize", True)):+ value = _normalize_schema_value(value)+ value_matches = re.fullmatch(value_pattern, value) is not None+ if value_matches and rule.get("numeric") == "positive_finite":+ try:+ number = float(value)+ except ValueError:+ value_matches = False+ else:+ value_matches = math.isfinite(number) and number > 0+ if not value_matches:+ errors.append(+ f"{markdown_name} schema: section '{section_id}' field "+ f"'{field_name}' must {requirement}; found '{value}'"+ )++ 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):+ asset_value = reference_value+ suffix_match = re.search(r"\{value\}(\.[A-Za-z0-9]+)$", asset_pattern)+ if (+ suffix_match is not None+ and asset_value.casefold().endswith(+ suffix_match.group(1).casefold()+ )+ ):+ asset_value = asset_value[: -len(suffix_match.group(1))]+ try:+ relative_asset = asset_pattern.format(value=asset_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()}++ for section_id, selector_field, references_field, catalog_dir in (+ _CUSTOM_REFERENCE_CATALOGS+ ):+ section_fields = fields(section_id)+ is_custom = (+ _normalize_schema_value(section_fields.get(selector_field, "")) == "custom"+ )+ raw_references = _normalize_schema_value(+ section_fields.get(references_field, "")+ )+ if not is_custom:+ if raw_references:+ errors.append(+ f"{markdown_name} schema: field '{references_field}' is valid "+ f"only when '{selector_field}' is custom"+ )+ continue+ if not raw_references:+ continue+ references = [item.strip() for item in raw_references.split(",")]+ duplicates = sorted(+ reference+ for reference in set(references)+ if references.count(reference) > 1+ )+ if duplicates:+ errors.append(+ f"{markdown_name} schema: field '{references_field}' repeats "+ f"catalog id(s) {', '.join(duplicates)}"+ )+ for reference in references:+ catalog_file = catalog_dir / f"{reference}.md"+ if reference == "custom" or not catalog_file.is_file():+ errors.append(+ f"{markdown_name} schema: field '{references_field}' references "+ f"unknown catalog id '{reference}'"+ )++ for key, value in fields("images").items():+ if key.strip().casefold() in _LEGACY_IMAGE_METADATA_KEYS:+ continue+ try:+ parse_spec_lock_image_value(key, value)+ except ValueError as exc:+ errors.append(+ f"{markdown_name} schema: images row {key!r} {exc}"+ )++ 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()+ if basename.casefold().endswith(".svg"):+ basename = basename[:-4]+ 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,+ *,+ include_design: bool = True,+) -> tuple[list[str], list[str]]:+ """Validate the lock and, when requested, the human-facing design brief."""+ 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 include_design and 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+ versioned_lock_valid = 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+ artifact_errors = validate_markdown_schema(artifact_path, schema_path)+ errors.extend(artifact_errors)+ if artifact_kind == "lock" and not artifact_errors:+ try:+ parse_spec_lock_artifact(+ artifact_path,+ compatibility_warnings=warnings,+ )+ except (OSError, UnicodeError, ValueError) as exc:+ errors.append(f"spec_lock.md compatibility parse failed: {exc}")+ continue+ versioned_lock_valid = True+ if versioned_lock_valid:+ try:+ from svg_to_pptx.pptx_package.template_structure import (+ TemplateStructureError,+ load_pptx_structure_lock,+ template_prototype_lock_errors,+ )++ structure_lock = load_pptx_structure_lock(project_path)+ if structure_lock is not None:+ errors.extend(template_prototype_lock_errors(structure_lock))+ except (ImportError, TemplateStructureError) as exc:+ errors.append(f"spec_lock.md structure preflight failed: {exc}")+ 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_manager.py b/skills/ppt-master/scripts/project_manager.pyindex 3e8b3dab..957a698a 100644--- a/skills/ppt-master/scripts/project_manager.py+++ b/skills/ppt-master/scripts/project_manager.py@@ -1,1295 +1,77 @@#!/usr/bin/env python3-"""PPT Master project management helpers.+"""+PPT Master - Project Management Tool++Stable CLI entry point for project creation, source import, validation, and+page-context diagnostics. Implementation lives in ``project_management/``.Usage:- python3 scripts/project_manager.py init <project_name> [--format ppt169] [--dir <path>] [--quick-generate]- 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 init <project_name> [--format ppt169]+ python3 scripts/project_manager.py import-sources <project_path> <sources...>python3 scripts/project_manager.py validate <project_path>- python3 scripts/project_manager.py info <project_path>- python3 scripts/project_manager.py page-context <project_path> P07 [--record-usage]- python3 scripts/project_manager.py page-context-report <project_path>++Examples:+ python3 scripts/project_manager.py init demo --format ppt169+ python3 scripts/project_manager.py validate projects/demo++Dependencies:+ Same as project_management.cli."""from __future__ import annotations-import argparse-import filecmp-import json-import os-import re-import shutil-import subprocessimport sys-import tempfile-from datetime import datetimefrom pathlib import Path-from urllib.parse import urlparse-from console_encoding import configure_utf8_stdio-from page_context import (- build_page_context,- page_context_usage_report,- record_page_context_usage,- render_page_context,-)-from project_specs import scaffold_project_artifact, validate_project_artifacts--try:- from project_utils import (- CANVAS_FORMATS,- get_project_info as get_project_info_common,- normalize_canvas_format,- validate_project_structure,- validate_svg_viewbox,- )-except ImportError:- 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,- normalize_canvas_format,- validate_project_structure,- validate_svg_viewbox,- )--TOOLS_DIR = Path(__file__).resolve().parent-SKILL_DIR = TOOLS_DIR.parent-REPO_ROOT = SKILL_DIR.parent.parent-PROJECTS_ROOT = REPO_ROOT / "projects"-SOURCE_TO_MD_TOOLS_DIR = TOOLS_DIR / "source_to_md"-if str(SOURCE_TO_MD_TOOLS_DIR) not in sys.path:- sys.path.insert(0, str(SOURCE_TO_MD_TOOLS_DIR))--from _dispatcher import ( # noqa: E402- DOC_SUFFIXES,- EXCEL_SUFFIXES,- LEGACY_EXCEL_SUFFIXES,- PDF_SUFFIXES,- PRESENTATION_SUFFIXES,- build_conversion_command,-)--SOURCE_DIRNAME = "sources"-TEXT_SOURCE_SUFFIXES = {".md", ".markdown", ".txt"}-TABLE_TEXT_SUFFIXES = {".csv", ".tsv"}-BITMAP_IMAGE_SUFFIXES = {- ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif",-}-IMAGE_ASSET_SUFFIXES = BITMAP_IMAGE_SUFFIXES | {- ".emf", ".wmf", ".svg",-}+_SCRIPTS_DIR = Path(__file__).resolve().parent+if str(_SCRIPTS_DIR) not in sys.path:+ sys.path.insert(0, str(_SCRIPTS_DIR))+from console_encoding import configure_utf8_stdio # noqa: E402configure_utf8_stdio()+from project_management.cli import ( # noqa: E402+ BITMAP_IMAGE_SUFFIXES,+ IMAGE_ASSET_SUFFIXES,+ SOURCE_DIRNAME,+ SOURCE_TO_MD_TOOLS_DIR,+ TABLE_TEXT_SUFFIXES,+ TEXT_SOURCE_SUFFIXES,+ TOOLS_DIR,+ ProjectManager,+ build_parser,+ derive_url_basename,+ is_url,+ is_within_path,+ main,+ sanitize_name,+)+from project_management.paths import ( # noqa: E402+ PROJECTS_ROOT,+ REPO_ROOT,+ SKILL_DIR,+)-def _validate_image_manifest(- payload: object,- path: Path,-) -> list[dict]:- """Require a safe, case-insensitively unique image manifest payload."""- if not isinstance(payload, list):- raise RuntimeError(- f"Image manifest must be a JSON array: {path}"- )-- seen_filenames: dict[str, str] = {}- for index, item in enumerate(payload):- if not isinstance(item, dict):- raise RuntimeError(- f"Existing image manifest item {index} must be an object: {path}"- )- filename = item.get("filename")- if (- not isinstance(filename, str)- or not filename.strip()- or filename in {".", ".."}- or "/" in filename- or "\\" in filename- or ":" in filename- or Path(filename).is_absolute()- or Path(filename).name != filename- ):- raise RuntimeError(- f"Image manifest item {index} has no safe bare filename: {path}"- )- normalized_filename = filename.casefold()- if normalized_filename in seen_filenames:- raise RuntimeError(- f"Image manifest filename {filename!r} conflicts with "- f"{seen_filenames[normalized_filename]!r} (case-insensitive): {path}"- )- seen_filenames[normalized_filename] = filename- return payload---def _read_existing_image_manifest(path: Path) -> list[dict]:- """Load an existing project image manifest or fail closed on corruption."""- if not path.exists():- return []- if not path.is_file():- raise RuntimeError(f"Existing image manifest is not a regular file: {path}")- try:- payload = json.loads(path.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError) as exc:- raise RuntimeError(- f"Existing image manifest is unreadable: {path} ({exc}); "- "repair or restore it before importing more assets"- ) from exc- return _validate_image_manifest(payload, path)---def _write_json_atomic(path: Path, payload: object) -> None:- """Write JSON through a same-directory temporary file and atomic rename."""- fd, temp_name = tempfile.mkstemp(- prefix=f"{path.stem}.",- suffix=".tmp",- dir=str(path.parent),- )- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- json.dump(payload, handle, ensure_ascii=False, indent=2)- handle.write("\n")- os.replace(temp_name, path)- except Exception:- try:- os.unlink(temp_name)- except OSError:- pass- raise---def is_url(value: str) -> bool:- """Return whether a string looks like an HTTP(S) URL."""- parsed = urlparse(value)- return parsed.scheme in {"http", "https"} and bool(parsed.netloc)---def sanitize_name(value: str) -> str:- """Sanitize a user-facing name into a filesystem-safe token."""- safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in value.strip())- safe = safe.strip("._")- while "__" in safe:- safe = safe.replace("__", "_")- return safe[:120] or "source"---def derive_url_basename(url: str) -> str:- """Derive a stable base filename from a URL."""- parsed = urlparse(url)- parts = [sanitize_name(parsed.netloc)]- if parsed.path and parsed.path != "/":- path_part = sanitize_name(parsed.path.strip("/").replace("/", "_"))- if path_part:- parts.append(path_part)- return "_".join(part for part in parts if part) or "web_source"---def is_within_path(path: Path, parent: Path) -> bool:- """Return whether `path` resolves inside `parent`."""- try:- path.resolve().relative_to(parent.resolve())- return True- except ValueError:- return False---def _has_usable_import(summary: dict[str, list[str]]) -> bool:- """Return whether import-sources produced at least one usable source artifact."""- return any(- summary.get(key)- for key in ("archived", "markdown", "assets", "images", "analysis")- )---class ProjectManager:- """Create, inspect, validate, and populate project folders."""-- CANVAS_FORMATS = CANVAS_FORMATS-- 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,- canvas_format: str = "ppt169",- base_dir: str | None = None,- *,- quick_generate: bool = False,- ) -> str:- base_path = Path(base_dir) if base_dir else self.base_dir-- if (- not project_name- or project_name in {".", ".."}- or Path(project_name).is_absolute()- or "/" in project_name- or "\\" in project_name- ):- raise ValueError(- "Project name must be a single, non-absolute path component"- )-- normalized_format = normalize_canvas_format(canvas_format)- if normalized_format not in self.CANVAS_FORMATS:- available = ", ".join(sorted(self.CANVAS_FORMATS.keys()))- raise ValueError(- f"Unsupported canvas format: {canvas_format} "- f"(available: {available}; common alias: xhs -> xiaohongshu)"- )-- date_str = datetime.now().strftime("%Y%m%d")- # A name already carrying a `_<format>_<YYYYMMDD>` suffix (e.g. a full- # project dir name pasted back into init) is used as-is — re-appending- # would produce `name_ppt169_20260101_ppt169_20260102`.- if re.search(rf"_{re.escape(normalized_format)}_\d{{8}}$", project_name):- project_dir_name = project_name- else:- project_dir_name = f"{project_name}_{normalized_format}_{date_str}"- project_path = base_path / project_dir_name-- if not is_within_path(project_path, base_path):- raise ValueError(- f"Project directory must stay within the base directory: {base_path}"- )- if project_path.exists():- raise FileExistsError(f"Project directory already exists: {project_path}")-- project_dirs = (- ("svg_output",)- if quick_generate- else (- "svg_output",- "svg_final",- "images",- "icons",- "notes",- "templates",- "live_preview",- SOURCE_DIRNAME,- "analysis",- "validation",- "exports",- )- )- for rel_path in project_dirs:- (project_path / rel_path).mkdir(parents=True, exist_ok=True)-- canvas_info = self.CANVAS_FORMATS[normalized_format]- if not quick_generate:- readme_path = project_path / "README.md"- readme_path.write_text(- (- f"# {project_name}\n\n"- f"- Canvas format: {normalized_format}\n"- f"- Created: {date_str}\n\n"- "## Directories\n\n"- "- `svg_output/`: raw SVG output\n"- "- `svg_final/`: self-contained SVG visual preview; may be inserted manually as an SVG image, but PowerPoint Convert to Shape is unsupported\n"- "- `images/`: runtime image pool; converter assets keep their original short filenames when possible\n"- "- `icons/`: project icon set — selected library icons copied in (via icon_sync.py) plus any custom icons you add; embedded from here at export\n"- "- `notes/`: speaker notes\n"- "- `templates/`: project templates\n"- "- `live_preview/`: browser preview runtime files and history (lock.json, server.log, edits.jsonl, annotations.jsonl)\n"- "- `sources/`: source materials and normalized markdown\n"- "- `analysis/`: machine-extracted intermediate analysis (PPTX intake, image_analysis.csv) — the pipeline's canonical must-read source/asset facts\n"- "- `validation/`: SVG quality reports and PPTX postflight audit reports\n"- "- `exports/`: final native DrawingML pptx deliverables only (timestamped); `_native_charts_tables.pptx` name with `--native-charts-and-tables`, `_narrated.pptx` name when narration audio is embedded\n"- "- `backup/<timestamp>/`: svg_output/ archive (always written in default-flow mode; safe to delete old timestamps)\n"- ),- encoding="utf-8",- )-- print(f"Project created: {project_path}")- print(f"Canvas: {canvas_info['name']} ({canvas_info['dimensions']})")- return str(project_path)-- def _source_dir(self, project_path: Path) -> Path:- sources_dir = project_path / SOURCE_DIRNAME- sources_dir.mkdir(parents=True, exist_ok=True)- return sources_dir-- def _analysis_dir(self, project_path: Path) -> Path:- analysis_dir = project_path / "analysis"- analysis_dir.mkdir(parents=True, exist_ok=True)- return analysis_dir-- def _ensure_unique_path(self, path: Path) -> Path:- if not path.exists():- return path-- suffix = path.suffix- stem = path.stem- counter = 2- while True:- candidate = path.with_name(f"{stem}_{counter}{suffix}")- if not candidate.exists():- return candidate- counter += 1-- def _copy_or_move_file(self, source: Path, destination: Path, move: bool) -> Path:- try:- if source.resolve() == destination.resolve():- return destination- except FileNotFoundError:- pass-- destination = self._ensure_unique_path(destination)- if move:- shutil.move(str(source), str(destination))- else:- shutil.copy2(source, destination)- return destination-- def _copy_or_move_tree(self, source: Path, destination: Path, move: bool) -> Path:- try:- if source.resolve() == destination.resolve():- return destination- except FileNotFoundError:- pass-- destination = self._ensure_unique_path(destination)- if move:- shutil.move(str(source), str(destination))- else:- shutil.copytree(source, destination)- return destination-- def _run_tool(self, args: list[str]) -> None:- child_env = os.environ.copy()- child_env["PYTHONUTF8"] = "1"- child_env["PYTHONIOENCODING"] = "utf-8:replace"- try:- result = subprocess.run(- args,- cwd=REPO_ROOT,- check=True,- capture_output=True,- text=True,- encoding="utf-8",- errors="replace",- env=child_env,- )- except FileNotFoundError as exc:- raise RuntimeError(f"Missing executable: {args[0]}") from exc- except subprocess.CalledProcessError as exc:- details = (exc.stderr or exc.stdout or "").strip()- raise RuntimeError(details or "tool execution failed") from exc-- if result.stdout.strip():- print(result.stdout.strip())-- def _import_pdf(self, pdf_path: Path, markdown_path: Path) -> None:- route = build_conversion_command(- str(pdf_path),- markdown_path,- forced_type="pdf",- )- self._run_tool(route.command)-- def _import_doc(self, doc_path: Path, markdown_path: Path) -> None:- route = build_conversion_command(- str(doc_path),- markdown_path,- forced_type="doc",- )- self._run_tool(route.command)-- def _import_presentation(self, presentation_path: Path, markdown_path: Path) -> None:- route = build_conversion_command(- str(presentation_path),- markdown_path,- forced_type="pptx",- )- self._run_tool(route.command)-- def _import_pptx_intake(self, presentation_path: Path, project_dir: Path) -> Path:- # Multi-deck intake: each PPTX writes its own `<stem>.identity.json` /- # `<stem>.slide_library.json` and is merged into the single multi-deck- # index `analysis/source_profile.json` (one entry per source deck).- analysis_dir = self._analysis_dir(project_dir)- self._run_tool(- [- sys.executable,- str(TOOLS_DIR / "pptx_intake.py"),- str(presentation_path),- "-o",- str(analysis_dir),- ]- )- return analysis_dir-- def _import_excel(self, excel_path: Path, markdown_path: Path) -> None:- route = build_conversion_command(- str(excel_path),- markdown_path,- forced_type="excel",- )- self._run_tool(route.command)-- def _import_url(self, url: str, markdown_path: Path) -> None:- route = build_conversion_command(- url,- markdown_path,- forced_type="web",- )- self._run_tool(route.command)-- def _is_valid_imported_url_markdown(self, markdown_path: Path) -> bool:- """Return whether web_to_md produced a usable Markdown source."""- if not markdown_path.is_file():- return False- content = markdown_path.read_text(encoding="utf-8", errors="replace")- if "[Failed URLs]:" in content:- return False- return bool(content.strip())-- def _archive_url_record(self, sources_dir: Path, url: str) -> Path:- file_path = self._ensure_unique_path(sources_dir / f"{derive_url_basename(url)}.url.txt")- file_path.write_text(- f"URL: {url}\nImported: {datetime.now().isoformat(timespec='seconds')}\n",- encoding="utf-8",- )- return file_path-- def _normalize_text_source(self, source_path: Path, sources_dir: Path) -> Path:- target = self._ensure_unique_path(sources_dir / f"{source_path.stem}.md")- content = source_path.read_text(encoding="utf-8", errors="replace")- target.write_text(content, encoding="utf-8")- return target-- def _canonicalize_markdown_content(self, content: str) -> str:- canonical = content.replace("\r\n", "\n")- canonical = re.sub(r"(?m)^(\s*Crawled:\s+).*$", r"\1__IGNORED__", canonical)- canonical = re.sub(r"(?m)^(\s*Imported:\s+).*$", r"\1__IGNORED__", canonical)- canonical = re.sub(r"([^\s\]()/]+_files)/", "__ASSET_DIR__/", canonical)- return canonical.strip()-- def _find_equivalent_markdown(self, source_path: Path, sources_dir: Path) -> Path | None:- source_content = source_path.read_text(encoding="utf-8", errors="replace")- canonical_source = self._canonicalize_markdown_content(source_content)-- for existing in sorted(sources_dir.iterdir()):- if existing.suffix.lower() not in {".md", ".markdown"}:- continue- try:- if existing.resolve() == source_path.resolve():- continue- except FileNotFoundError:- pass-- existing_content = existing.read_text(encoding="utf-8", errors="replace")- if self._canonicalize_markdown_content(existing_content) == canonical_source:- return existing-- return None-- def _companion_asset_dir(self, source_path: Path) -> Path | None:- candidate = source_path.with_name(f"{source_path.stem}_files")- if candidate.exists() and candidate.is_dir():- return candidate- return None-- def _rewrite_markdown_asset_refs(- self,- markdown_path: Path,- original_asset_dirname: str,- imported_asset_dirname: str,- ) -> None:- if original_asset_dirname == imported_asset_dirname:- return-- content = markdown_path.read_text(encoding="utf-8", errors="replace")- updated = content.replace(f"{original_asset_dirname}/", f"{imported_asset_dirname}/")- if updated != content:- markdown_path.write_text(updated, encoding="utf-8")-- def _merge_image_manifest(self, source_items: list[dict], destination_manifest: Path) -> None:- """Merge per-source manifest items into the project-level manifest, keyed by filename."""- _validate_image_manifest(source_items, destination_manifest)- existing_data = _read_existing_image_manifest(destination_manifest)-- new_by_filename: dict[str, dict] = {}- new_order: list[str] = []- for item in source_items:- filename = item.get("filename")- if not isinstance(filename, str):- continue- normalized_filename = filename.casefold()- if normalized_filename not in new_by_filename:- new_order.append(normalized_filename)- new_by_filename[normalized_filename] = item-- merged: list[dict] = []- seen: set[str] = set()- for item in existing_data:- if not isinstance(item, dict):- continue- filename = item.get("filename")- if not isinstance(filename, str):- continue- normalized_filename = filename.casefold()- if normalized_filename in new_by_filename:- merged.append(new_by_filename[normalized_filename])- else:- merged.append(item)- seen.add(normalized_filename)-- for normalized_filename in new_order:- if normalized_filename not in seen:- merged.append(new_by_filename[normalized_filename])-- _validate_image_manifest(merged, destination_manifest)- _write_json_atomic(destination_manifest, merged)-- @staticmethod- def _namespace_from_asset_dir(asset_dir: Path) -> str:- """Derive a per-source namespace from a `<stem>_files` companion directory name."""- name = asset_dir.name- suffix = "_files"- return name[:-len(suffix)] if name.endswith(suffix) else name-- def _image_destination_name(- self,- images_dir: Path,- source_file: Path,- namespace: str,- existing_manifest: dict[str, dict],- occupied_names: set[str],- ) -> str:- """Return a short unique image filename for the runtime image pool."""- candidate = images_dir / source_file.name- if candidate.name.casefold() not in occupied_names:- return source_file.name- try:- meta = existing_manifest.get(candidate.name, {})- if (- meta.get("source_namespace") == namespace- and candidate.is_file()- and filecmp.cmp(source_file, candidate, shallow=False)- ):- return candidate.name- except OSError:- pass-- stem = source_file.stem- suffix = source_file.suffix- counter = 2- while True:- candidate = images_dir / f"{stem}_{counter}{suffix}"- if candidate.name.casefold() not in occupied_names:- return candidate.name- try:- meta = existing_manifest.get(candidate.name, {})- if (- meta.get("source_namespace") == namespace- and candidate.is_file()- and filecmp.cmp(source_file, candidate, shallow=False)- ):- return candidate.name- except OSError:- pass- counter += 1-- def _propagate_image_assets(self, asset_dir: Path, project_dir: Path) -> None:- """Copy converter-generated image assets and manifest into project images/.-- Filenames are preserved when possible because source Markdown commonly- uses short names that are meaningful in context. Only real collisions- receive a compact numeric suffix.- """- manifest_path = asset_dir / "image_manifest.json"- if not manifest_path.is_file():- return-- try:- source_payload = json.loads(manifest_path.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError) as exc:- print(f"[WARN] Cannot read image manifest {manifest_path}: {exc}")- return- try:- source_data = _validate_image_manifest(source_payload, manifest_path)- except RuntimeError as exc:- print(f"[WARN] {exc}")- return-- images_dir = project_dir / "images"- namespace = self._namespace_from_asset_dir(asset_dir)- destination_manifest = images_dir / "image_manifest.json"- existing_data = _read_existing_image_manifest(destination_manifest)- images_dir.mkdir(parents=True, exist_ok=True)-- existing_manifest = {- item["filename"]: item- for item in existing_data- }- occupied_names = {- path.name.casefold()- for path in images_dir.iterdir()- if path.is_file()- }- rename_map: dict[str, str] = {}-- copied_count = 0- for source_file in sorted(asset_dir.iterdir()):- if not source_file.is_file():- continue- if source_file.suffix.lower() not in IMAGE_ASSET_SUFFIXES:- continue- new_name = self._image_destination_name(- images_dir,- source_file,- namespace,- existing_manifest,- occupied_names,- )- destination = images_dir / new_name- if source_file.resolve() != destination.resolve():- shutil.copy2(source_file, destination)- occupied_names.add(new_name.casefold())- rename_map[source_file.name] = new_name- copied_count += 1-- rebased_items: list[dict] = []- for item in source_data:- if not isinstance(item, dict):- continue- original = item.get("filename")- if not isinstance(original, str):- continue- new_item = dict(item)- new_item["filename"] = rename_map.get(original, original)- new_item["source_namespace"] = namespace- rebased_items.append(new_item)-- self._merge_image_manifest(rebased_items, images_dir / "image_manifest.json")- print(- f"Propagated {copied_count} image asset(s) + manifest "- f"from {asset_dir} → images/ (namespace: {namespace})"- )-- def _propagate_companion_image_assets(self, markdown_path: Path, project_dir: Path) -> None:- asset_dir = markdown_path.with_name(f"{markdown_path.stem}_files")- if asset_dir.is_dir():- self._propagate_image_assets(asset_dir, project_dir)-- def _import_markdown_with_assets(- self,- source_path: Path,- sources_dir: Path,- move: bool,- ) -> tuple[Path, Path | None, str | None]:- archived_markdown = self._copy_or_move_file(- source_path,- sources_dir / source_path.name,- move=move,- )-- profile_src = source_path.with_name(f"{source_path.stem}.conversion_profile.json")- if profile_src.is_file():- self._copy_or_move_file(- profile_src,- sources_dir / f"{archived_markdown.stem}.conversion_profile.json",- move=move,- )-- asset_dir = self._companion_asset_dir(source_path)- if asset_dir is None:- return archived_markdown, None, None-- imported_asset_dir = self._copy_or_move_tree(- asset_dir,- sources_dir / f"{archived_markdown.stem}_files",- move=move,- )- self._rewrite_markdown_asset_refs(- archived_markdown,- original_asset_dirname=asset_dir.name,- imported_asset_dirname=imported_asset_dir.name,- )-- note = None- if archived_markdown.stem != source_path.stem:- note = (- f"{source_path}: renamed imported markdown to {archived_markdown.name} "- f"and rewrote asset references to {imported_asset_dir.name}/"- )- return archived_markdown, imported_asset_dir, note-- def import_sources(- self,- project_path: str,- source_items: list[str],- move: bool = False,- copy: bool = False,- ) -> dict[str, list[str]]:- if move and copy:- raise ValueError("--move and --copy are mutually exclusive")- project_dir = Path(project_path)- if not project_dir.exists() or not project_dir.is_dir():- raise FileNotFoundError(f"Project directory not found: {project_dir}")- if not source_items:- raise ValueError("At least one source path or URL is required")-- sources_dir = self._source_dir(project_dir)- summary: dict[str, list[str]] = {- "archived": [],- "url_records": [],- "markdown": [],- "assets": [],- "images": [],- "analysis": [],- "notes": [],- "skipped": [],- }-- expanded_items: list[str] = []- supplied_dirs: list[Path] = []- for item in source_items:- if is_url(item):- expanded_items.append(item)- continue- item_path = Path(item)- if item_path.is_dir():- supplied_dirs.append(item_path)- directory_files = sorted(- path for path in item_path.iterdir() if path.is_file()- )- if directory_files:- expanded_items.extend(str(path) for path in directory_files)- summary["notes"].append(- f"{item}: expanded directory into {len(directory_files)} file(s)"- )- else:- summary["skipped"].append(f"{item}: directory contains no files")- continue- expanded_items.append(item)-- explicit_markdown_stems = {- Path(item).stem- for item in expanded_items- if not is_url(item)- and Path(item).exists()- and Path(item).is_file()- and Path(item).suffix.lower() in {".md", ".markdown"}- }-- for item in expanded_items:- if is_url(item):- markdown_path = self._ensure_unique_path(- sources_dir / f"{derive_url_basename(item)}.md"- )- try:- self._import_url(item, markdown_path)- except Exception as exc: # pragma: no cover - summary path- archived = self._archive_url_record(sources_dir, item)- summary["url_records"].append(str(archived))- summary["skipped"].append(f"{item}: {exc}")- continue-- if not self._is_valid_imported_url_markdown(markdown_path):- markdown_path.unlink(missing_ok=True)- archived = self._archive_url_record(sources_dir, item)- summary["url_records"].append(str(archived))- summary["skipped"].append(f"{item}: URL conversion produced no usable Markdown")- continue-- summary["markdown"].append(str(markdown_path))- self._propagate_companion_image_assets(markdown_path, project_dir)- continue-- source_path = Path(item)- if not source_path.exists():- summary["skipped"].append(f"{item}: path not found")- continue- if source_path.is_dir():- summary["skipped"].append(f"{item}: directories are not supported")- continue-- inside_projects = is_within_path(source_path, PROJECTS_ROOT)- if copy:- effective_move = False- elif inside_projects:- effective_move = True- else:- effective_move = False- if move and not inside_projects:- print(- f"note: {source_path} is outside {PROJECTS_ROOT}; copied "- f"(not moved). Only sources under projects/ may be moved.",- file=sys.stderr,- )- elif inside_projects and not move and not copy:- print(- f"note: {source_path} is under projects/; moved into the target "- f"project. Pass --copy to preserve it.",- file=sys.stderr,- )- suffix = source_path.suffix.lower()-- if suffix in {".md", ".markdown"}:- duplicate_markdown = self._find_equivalent_markdown(source_path, sources_dir)- if duplicate_markdown is not None:- summary["markdown"].append(str(duplicate_markdown))- self._propagate_companion_image_assets(duplicate_markdown, project_dir)- summary["notes"].append(- f"{item}: skipped duplicate markdown import because equivalent content already exists as {duplicate_markdown.name}"- )- continue-- archived_markdown, asset_dir, note = self._import_markdown_with_assets(- source_path,- sources_dir,- move=effective_move,- )- summary["archived"].append(str(archived_markdown))- summary["markdown"].append(str(archived_markdown))- if asset_dir is not None:- summary["assets"].append(str(asset_dir))- self._propagate_image_assets(asset_dir, project_dir)- if note:- summary["notes"].append(note)- continue-- archived_path = self._copy_or_move_file(- source_path,- sources_dir / source_path.name,- move=effective_move,- )- summary["archived"].append(str(archived_path))-- if suffix in BITMAP_IMAGE_SUFFIXES:- images_dir = project_dir / "images"- images_dir.mkdir(parents=True, exist_ok=True)- image_path = self._ensure_unique_path(images_dir / archived_path.name)- shutil.copy2(archived_path, image_path)- summary["images"].append(str(image_path))- if image_path.name != archived_path.name:- summary["notes"].append(- f"{item}: copied runtime image as {image_path.name} "- "to avoid a filename collision"- )- elif suffix in PDF_SUFFIXES:- canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"- if archived_path.stem in explicit_markdown_stems:- summary["notes"].append(- f"{item}: skipped PDF auto-conversion because a same-stem Markdown source was provided"- )- continue- if canonical_markdown_path.exists():- summary["markdown"].append(str(canonical_markdown_path))- self._propagate_companion_image_assets(canonical_markdown_path, project_dir)- summary["notes"].append(- f"{item}: skipped PDF auto-conversion because {canonical_markdown_path.name} already exists"- )- continue- markdown_path = canonical_markdown_path- try:- self._import_pdf(archived_path, markdown_path)- summary["markdown"].append(str(markdown_path))- self._propagate_companion_image_assets(markdown_path, project_dir)- except Exception as exc: # pragma: no cover - summary path- summary["skipped"].append(f"{item}: PDF conversion failed ({exc})")- elif suffix in PRESENTATION_SUFFIXES:- canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"- try:- intake_dir = self._import_pptx_intake(archived_path, project_dir)- intake_str = str(intake_dir)- if intake_str not in summary["analysis"]:- summary["analysis"].append(intake_str)- except Exception as exc: # pragma: no cover - summary path- summary["notes"].append(f"{item}: PPTX intake analysis failed ({exc})")- if archived_path.stem in explicit_markdown_stems:- summary["notes"].append(- f"{item}: skipped presentation auto-conversion because a same-stem Markdown source was provided"- )- continue- if canonical_markdown_path.exists():- summary["markdown"].append(str(canonical_markdown_path))- self._propagate_companion_image_assets(canonical_markdown_path, project_dir)- summary["notes"].append(- f"{item}: skipped presentation auto-conversion because {canonical_markdown_path.name} already exists"- )- continue- markdown_path = canonical_markdown_path- try:- self._import_presentation(archived_path, markdown_path)- summary["markdown"].append(str(markdown_path))- self._propagate_companion_image_assets(markdown_path, project_dir)- except Exception as exc: # pragma: no cover - summary path- summary["skipped"].append(f"{item}: presentation conversion failed ({exc})")- elif suffix in EXCEL_SUFFIXES:- canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"- if archived_path.stem in explicit_markdown_stems:- summary["notes"].append(- f"{item}: skipped Excel auto-conversion because a same-stem Markdown source was provided"- )- continue- if canonical_markdown_path.exists():- summary["markdown"].append(str(canonical_markdown_path))- self._propagate_companion_image_assets(canonical_markdown_path, project_dir)- summary["notes"].append(- f"{item}: skipped Excel auto-conversion because {canonical_markdown_path.name} already exists"- )- continue- markdown_path = canonical_markdown_path- try:- self._import_excel(archived_path, markdown_path)- summary["markdown"].append(str(markdown_path))- self._propagate_companion_image_assets(markdown_path, project_dir)- except Exception as exc: # pragma: no cover - summary path- summary["skipped"].append(f"{item}: Excel conversion failed ({exc})")- elif suffix in LEGACY_EXCEL_SUFFIXES:- summary["notes"].append(- f"{item}: archived only; legacy .xls is not converted automatically. "- "Resave as .xlsx to generate Markdown."- )- elif suffix in TABLE_TEXT_SUFFIXES:- summary["notes"].append(- f"{item}: archived as a plain-text table source; no Markdown conversion needed"- )- elif suffix in DOC_SUFFIXES:- canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"- if archived_path.stem in explicit_markdown_stems:- summary["notes"].append(- f"{item}: skipped document auto-conversion because a same-stem Markdown source was provided"- )- continue- if canonical_markdown_path.exists():- summary["markdown"].append(str(canonical_markdown_path))- self._propagate_companion_image_assets(canonical_markdown_path, project_dir)- summary["notes"].append(- f"{item}: skipped document auto-conversion because {canonical_markdown_path.name} already exists"- )- continue- markdown_path = canonical_markdown_path- try:- self._import_doc(archived_path, markdown_path)- summary["markdown"].append(str(markdown_path))- self._propagate_companion_image_assets(markdown_path, project_dir)- except Exception as exc: # pragma: no cover - summary path- summary["skipped"].append(f"{item}: document conversion failed ({exc})")- elif suffix == ".txt":- markdown_path = self._normalize_text_source(archived_path, sources_dir)- summary["markdown"].append(str(markdown_path))- else:- summary["notes"].append(f"{item}: archived only, no automatic conversion")-- # Cleanup: only a projects-local source directory may be removed after- # its files move into the target project. Every other location is copied- # and remains untouched, even when the caller passes --move.- for directory in supplied_dirs:- if copy or not is_within_path(directory, PROJECTS_ROOT):- continue- if directory.is_dir() and not any(directory.iterdir()):- try:- directory.rmdir()- except OSError:- continue- summary["notes"].append(- f"{directory}: removed empty source directory after import"- )-- return summary-- def validate_project(self, project_path: str) -> tuple[bool, list[str], list[str]]:- project_path_obj = Path(project_path)- _, 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))- if info.get("svg_files"):- svg_files = [project_path_obj / "svg_output" / name for name in info["svg_files"]]- expected_format = info.get("format")- if expected_format == "unknown":- expected_format = None- warnings.extend(validate_svg_viewbox(svg_files, expected_format))-- return not errors, list(dict.fromkeys(errors)), warnings-- def get_project_info(self, project_path: str) -> dict[str, object]:- shared = get_project_info_common(project_path)- return {- "name": shared.get("name", Path(project_path).name),- "path": shared.get("path", str(project_path)),- "exists": shared.get("exists", False),- "svg_count": shared.get("svg_count", 0),- "has_spec": shared.get("has_spec", False),- "has_source": shared.get("has_source", False),- "source_count": shared.get("source_count", 0),- "canvas_format": shared.get("format_name", "Unknown"),- "create_date": shared.get("date_formatted", "Unknown"),- }---def build_parser() -> argparse.ArgumentParser:- """Build the command-line parser."""- parser = argparse.ArgumentParser(- description="PPT Master project management helpers.",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""Examples:- python3 scripts/project_manager.py init demo --format ppt169- python3 scripts/project_manager.py import-sources projects/demo file.md- python3 scripts/project_manager.py scaffold-spec projects/demo_ppt169_20260718- python3 scripts/project_manager.py scaffold-lock projects/demo_ppt169_20260718- python3 scripts/project_manager.py validate projects/demo- python3 scripts/project_manager.py info projects/demo- python3 scripts/project_manager.py page-context projects/demo P07 --record-usage- python3 scripts/project_manager.py page-context-report projects/demo-""",- )- subparsers = parser.add_subparsers(dest="command", required=True)-- init = subparsers.add_parser("init", help="Create a project directory")- init.add_argument("project_name", help="Project name")- init.add_argument("--format", default="ppt169", help="Canvas format (default: ppt169)")- init.add_argument("--dir", default=None, help="Base directory for the project")- init.add_argument(- "--quick-generate",- action="store_true",- help="Create only the svg_output directory and omit README.md",- )-- import_sources = subparsers.add_parser(- "import-sources",- help="Import source files or URLs into a project",- )- import_sources.add_argument("project_path", help="Project directory")- import_sources.add_argument("sources", nargs="+", help="Source files, directories, or URLs")- mode = import_sources.add_mutually_exclusive_group()- mode.add_argument(- "--move",- action="store_true",- help="Move local sources under projects/; sources elsewhere are copied",- )- 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")-- info = subparsers.add_parser("info", help="Print project metadata")- info.add_argument("project_path", help="Project directory")-- page_context = subparsers.add_parser(- "page-context",- help="Print one deterministic per-page execution view",- )- page_context.add_argument("project_path", help="Project directory")- page_context.add_argument("page", help="Positive page key such as P07")- page_context.add_argument(- "--bundle",- action="store_true",- help="Deprecated compatibility flag; output remains compact",- )- page_context.add_argument(- "--pretty",- action="store_true",- help="Pretty-print the page-context JSON payload",- )- page_context.add_argument(- "--record-usage",- action="store_true",- help="Write compact-output token telemetry under analysis/page-context/",- )-- page_context_report = subparsers.add_parser(- "page-context-report",- help="Summarize fresh per-page context telemetry",- )- page_context_report.add_argument("project_path", help="Project directory")- return parser---def main(argv: list[str] | None = None) -> int:- """Run the CLI entry point."""- parser = build_parser()- args = parser.parse_args(argv)- manager = ProjectManager()-- try:- if args.command == "init":- project_path = manager.init_project(- args.project_name,- args.format,- base_dir=args.dir,- quick_generate=args.quick_generate,- )- print(f"[OK] Project initialized: {project_path}")- print("Next:")- if args.quick_generate:- print("1. Generate SVG files into svg_output/")- print("2. Run the Quick Generate final checker and exporter")- else:- print("1. Put source files into sources/ (or use import-sources)")- print("2. Save your design spec to the project root")- print("3. Generate SVG files into svg_output/")- return 0-- if args.command == "import-sources":- summary = manager.import_sources(- args.project_path,- args.sources,- move=args.move,- copy=args.copy,- )- has_usable_import = _has_usable_import(summary)- if has_usable_import:- print(f"[OK] Imported sources into: {args.project_path}")- else:- print(- f"[ERROR] No usable sources imported into: {args.project_path}",- file=sys.stderr,- )- if summary["archived"]:- print("\nArchived originals:")- for item in summary["archived"]:- print(f" - {item}")- if summary["url_records"]:- print("\nArchived URL records:")- for item in summary["url_records"]:- print(f" - {item}")- if summary["markdown"]:- print("\nNormalized markdown:")- for item in summary["markdown"]:- print(f" - {item}")- if summary["assets"]:- print("\nImported asset directories:")- for item in summary["assets"]:- print(f" - {item}")- if summary["images"]:- print("\nRuntime image copies:")- for item in summary["images"]:- print(f" - {item}")- if summary["analysis"]:- print("\nAnalysis artifacts:")- for item in summary["analysis"]:- print(f" - {item}")- if summary["notes"]:- print("\nNotes:")- for item in summary["notes"]:- print(f" - {item}")- if summary["skipped"]:- print("\nSkipped:")- for item in summary["skipped"]:- print(f" - {item}")- return 0 if has_usable_import else 1-- 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_path- is_valid, errors, warnings = manager.validate_project(project_path)-- print(f"\nProject validation: {project_path}")- print("=" * 60)-- if errors:- print("\n[ERROR]")- for error in errors:- print(f" - {error}")-- if warnings:- print("\n[WARN]")- for warning in warnings:- print(f" - {warning}")-- if is_valid and not warnings:- print("\n[OK] Project structure is complete.")- elif is_valid:- print("\n[OK] Project structure is valid, with warnings.")- else:- print("\n[ERROR] Project structure is invalid.")- return 1- return 0-- if args.command == "info":- project_path = args.project_path- info = manager.get_project_info(project_path)-- print(f"\nProject info: {info['name']}")- print("=" * 60)- print(f"Path: {info['path']}")- print(f"Exists: {'Yes' if info['exists'] else 'No'}")- print(f"SVG files: {info['svg_count']}")- print(f"Design spec: {'Yes' if info['has_spec'] else 'No'}")- print(f"Source materials: {'Yes' if info['has_source'] else 'No'}")- print(f"Source count: {info['source_count']}")- print(f"Canvas format: {info['canvas_format']}")- print(f"Created: {info['create_date']}")- return 0-- if args.command == "page-context":- result = build_page_context(args.project_path, args.page)- output, measured_reads = render_page_context(- result,- bundle=args.bundle,- pretty=args.pretty,- )- if args.record_usage:- _usage_path, token_status = record_page_context_usage(- result,- output,- measured_reads,- )- if token_status != "exact":- print(- "[WARN] tiktoken/o200k_base unavailable; recorded bytes "- "and hashes without token counts",- file=sys.stderr,- )- print(output, end="")- return 0-- if args.command == "page-context-report":- report = page_context_usage_report(args.project_path)- print(json.dumps(report, ensure_ascii=False, indent=2))- return 0-- parser.error(f"Unknown command: {args.command}")- except Exception as exc:- print(f"[ERROR] {exc}")- return 1+__all__ = [+ "BITMAP_IMAGE_SUFFIXES",+ "IMAGE_ASSET_SUFFIXES",+ "PROJECTS_ROOT",+ "REPO_ROOT",+ "SKILL_DIR",+ "SOURCE_DIRNAME",+ "SOURCE_TO_MD_TOOLS_DIR",+ "TABLE_TEXT_SUFFIXES",+ "TEXT_SOURCE_SUFFIXES",+ "TOOLS_DIR",+ "ProjectManager",+ "build_parser",+ "derive_url_basename",+ "is_url",+ "is_within_path",+ "main",+ "sanitize_name",+]if __name__ == "__main__":diff --git a/skills/ppt-master/scripts/project_specs.py b/skills/ppt-master/scripts/project_specs.pyindex 9f6f1d60..9cd0533c 100644--- a/skills/ppt-master/scripts/project_specs.py+++ b/skills/ppt-master/scripts/project_specs.py@@ -1,1366 +1,46 @@#!/usr/bin/env python3"""-PPT Master - Project Specification Helpers+PPT Master - Project Specification Compatibility Module-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.+Re-export the project planning-artifact API from its domain package. New+internal imports should use ``project_management.project_specs``.Usage:- Import validate_project_artifacts() or scaffold_project_artifact().+ Import validation or scaffold helpers from this module.Examples:from project_specs import validate_markdown_schemaDependencies:- None (only uses the standard library and local project modules)+ Same as project_management.project_specs."""-from __future__ import annotations--import json-import math-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"--_CUSTOM_REFERENCE_CATALOGS = (- ("mode", "mode", "mode_references", SKILL_DIR / "references" / "modes"),- (- "visual_style",- "visual_style",- "visual_style_references",- SKILL_DIR / "references" / "visual-styles",- ),- (- "colors",- "image_rendering",- "image_rendering_references",- SKILL_DIR / "references" / "image-renderings",- ),-)--_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,+from project_management.project_specs import (+ SCAFFOLD_DIR,+ SCHEMA_DIR,+ SKILL_DIR,+ TOOLS_DIR,+ default_spec_lock_forbidden,+ parse_markdown_artifact,+ parse_spec_lock,+ parse_spec_lock_artifact,+ parse_spec_lock_image_value,+ scaffold_project_artifact,+ validate_markdown_schema,+ validate_project_artifacts,)-_IMAGE_PATH_SUFFIXES = frozenset(- {- ".bmp",- ".emf",- ".gif",- ".jpeg",- ".jpg",- ".png",- ".svg",- ".tif",- ".tiff",- ".webp",- ".wmf",- }-)-_IMAGE_ACQUISITION_SOURCES = frozenset(- {"ai", "web", "user", "formula", "placeholder", "slice"}-)-_IMAGE_CROP_POLICIES = frozenset({"adaptive", "no-crop"})-_LEGACY_IMAGE_METADATA_KEYS = frozenset(- {- "image_rendering",- "image_rendering_behavior",- "image_rendering_references",- }-)-_LEGACY_SPEC_LOCK_FORBIDDEN = frozenset({"Mixing icon libraries"})-_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 parse_markdown_artifact(- markdown_path: Path,- *,- report_duplicate_fields: bool = False,-) -> list[dict[str, object]]:- """Parse one Markdown planning artifact without changing it.-- This is the public read-only entry point for consumers that need the same- heading/data-line grammar as schema validation. Keeping the parser here- prevents runtime projections from drifting into their own lock grammar.- """- text = markdown_path.read_text(encoding="utf-8")- sections, errors = _parse_markdown_sections(- text,- report_duplicate_fields=report_duplicate_fields,- )- if errors:- raise ValueError("; ".join(errors))- return sections---def _looks_like_image_path(raw: str) -> bool:- """Return whether one lock token looks like a project image path."""- token = raw.strip().strip("`'\"").replace("\\", "/")- return bool(token) and Path(token).suffix.casefold() in _IMAGE_PATH_SUFFIXES---def parse_spec_lock_image_value(key: str, value: str) -> dict[str, str]:- """Parse one image-lock row while preserving supported legacy rows.-- Current rows use ``<path> | source=... | pattern=... | crop=...``. Legacy- rows remain readable, but any row that starts using named metadata must- provide the complete current contract.- """- normalized_key = str(key).strip()- normalized_value = str(value).strip()- parts = [part.strip() for part in normalized_value.split("|")]- path_part = parts[0] if parts else ""-- if _looks_like_image_path(normalized_key) and not _looks_like_image_path(path_part):- parts.insert(0, normalized_key)- path_part = normalized_key- elif (- len(parts) >= 2- and parts[0].casefold() in _IMAGE_ACQUISITION_SOURCES- and _looks_like_image_path(parts[1])- ):- path_part = parts[1]-- metadata_parts = [part for part in parts[1:] if "=" in part]- if not metadata_parts:- legacy_crop = (- "no-crop"- if any(- re.search(r"(?<![a-z])no-crop(?![a-z])", part, re.IGNORECASE)- for part in parts[1:]- )- else ""- )- return {- "path": path_part,- "source": "",- "pattern": "",- "crop": legacy_crop,- "legacy": "true",- }-- metadata: dict[str, str] = {}- unsupported_parts: list[str] = []- for part in parts[1:]:- field, separator, raw = part.partition("=")- if not separator:- unsupported_parts.append(part)- continue- field = field.strip().casefold()- if field in metadata:- raise ValueError(f"repeats metadata field {field!r}")- metadata[field] = raw.strip()-- expected_fields = {"source", "pattern", "crop"}- unknown_fields = sorted(set(metadata) - expected_fields)- missing_fields = sorted(expected_fields - set(metadata))- if unsupported_parts:- shown = ", ".join(repr(part) for part in unsupported_parts)- raise ValueError(f"has unsupported metadata token(s) {shown}")- if unknown_fields:- raise ValueError(- f"has unknown metadata field(s) {', '.join(unknown_fields)}"- )- if missing_fields:- raise ValueError(- f"misses metadata field(s) {', '.join(missing_fields)}"- )- if not _looks_like_image_path(path_part):- raise ValueError(f"has invalid image path {path_part!r}")-- normalized_path = path_part.replace("\\", "/")- path = Path(normalized_path)- if (- path.is_absolute()- or len(path.parts) != 2- or path.parts[0] != "images"- or path.name in {"", ".", ".."}- or ":" in path.name- or normalized_path != f"images/{path.name}"- ):- raise ValueError(- f"must use canonical project path images/<filename>, got {path_part!r}"- )-- source = metadata["source"].casefold()- if source not in _IMAGE_ACQUISITION_SOURCES:- allowed = ", ".join(sorted(_IMAGE_ACQUISITION_SOURCES))- raise ValueError(f"source must be one of {allowed}, got {metadata['source']!r}")- if not metadata["pattern"]:- raise ValueError("pattern must be non-empty")- crop = metadata["crop"].casefold()- if crop not in _IMAGE_CROP_POLICIES:- allowed = ", ".join(sorted(_IMAGE_CROP_POLICIES))- raise ValueError(f"crop must be one of {allowed}, got {metadata['crop']!r}")-- return {- "path": normalized_path,- "source": source,- "pattern": metadata["pattern"],- "crop": crop,- "legacy": "false",- }---def parse_spec_lock_artifact(- lock_path: Path,- *,- report_duplicate_fields: bool = False,- compatibility_warnings: list[str] | None = None,-) -> list[dict[str, object]]:- """Parse one execution lock and normalize supported legacy image rows.-- New locks use ``- <key>: <path> | source=... | pattern=... | crop=...``.- Some versioned projects instead placed the image path before the colon.- Preserve those projects by projecting the key path back into the value so- every consumer sees the same path-first image value.- """- sections = parse_markdown_artifact(- lock_path,- report_duplicate_fields=report_duplicate_fields,- )- normalized_sections: list[dict[str, object]] = []- compatibility_keys: list[str] = []-- for section in sections:- if str(section.get("heading", "")).strip().casefold() != "images":- normalized_sections.append(section)- continue- raw_fields = section.get("fields")- if not isinstance(raw_fields, dict):- normalized_sections.append(section)- continue-- fields: dict[str, str] = {}- for raw_key, raw_value in raw_fields.items():- key = str(raw_key)- value = str(raw_value).strip()- value_path = value.split("|", 1)[0].strip()- if _looks_like_image_path(key) and not _looks_like_image_path(value_path):- value = f"{key} | {value}" if value else key- compatibility_keys.append(key)- fields[key] = value-- normalized_section = dict(section)- normalized_section["fields"] = fields- normalized_sections.append(normalized_section)-- if compatibility_warnings is not None and compatibility_keys:- sample = ", ".join(compatibility_keys[:3])- suffix = "" if len(compatibility_keys) <= 3 else ", ..."- compatibility_warnings.append(- f"{lock_path.name} images: normalized {len(compatibility_keys)} legacy "- "path-as-key row(s); new locks should use '- <key>: <path> | "- "source=... | pattern=... | crop=...' "- f"(found: {sample}{suffix})"- )- return normalized_sections---def parse_spec_lock(- lock_path: Path,- *,- report_duplicate_fields: bool = False,- compatibility_warnings: list[str] | None = None,-) -> dict[str, dict[str, str]]:- """Return one execution lock as ``{section: {key: value}}`."""- sections = parse_spec_lock_artifact(- lock_path,- report_duplicate_fields=report_duplicate_fields,- compatibility_warnings=compatibility_warnings,- )- parsed: dict[str, dict[str, str]] = {}- for section in sections:- raw_fields = section.get("fields")- if not isinstance(raw_fields, dict):- continue- parsed[str(section.get("heading", "")).strip()] = {- str(key): str(value) for key, value in raw_fields.items()- }- return parsed---def default_spec_lock_forbidden() -> frozenset[str]:- """Return the versioned scaffold's universal forbidden-item defaults."""- sections = parse_markdown_artifact(SCAFFOLD_DIR / "spec_lock.md")- section = next(- (- item- for item in sections- if str(item.get("heading", "")).strip().casefold() == "forbidden"- ),- None,- )- if section is None:- raise ValueError("spec-lock scaffold has no forbidden section")- current = frozenset(- re.sub(r"^-[ \t]+", "", line.strip())- for line in str(section.get("body", "")).splitlines()- if line.strip()- )- return current | _LEGACY_SPEC_LOCK_FORBIDDEN---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}'"- )-- field_value_rules = definition.get("field_value_rules", [])- if isinstance(field_value_rules, list):- for rule in field_value_rules:- if not isinstance(rule, dict):- continue- key_pattern = rule.get("key_pattern")- value_pattern = rule.get("value_pattern")- if not isinstance(key_pattern, str) or not isinstance(- value_pattern, str- ):- continue- requirement = str(rule.get("requirement", "match its value grammar"))- for field_name, raw_value in fields.items():- if re.fullmatch(key_pattern, str(field_name)) is None:- continue- value = str(raw_value).strip()- if bool(rule.get("normalize", True)):- value = _normalize_schema_value(value)- value_matches = re.fullmatch(value_pattern, value) is not None- if value_matches and rule.get("numeric") == "positive_finite":- try:- number = float(value)- except ValueError:- value_matches = False- else:- value_matches = math.isfinite(number) and number > 0- if not value_matches:- errors.append(- f"{markdown_name} schema: section '{section_id}' field "- f"'{field_name}' must {requirement}; found '{value}'"- )-- 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):- asset_value = reference_value- suffix_match = re.search(r"\{value\}(\.[A-Za-z0-9]+)$", asset_pattern)- if (- suffix_match is not None- and asset_value.casefold().endswith(- suffix_match.group(1).casefold()- )- ):- asset_value = asset_value[: -len(suffix_match.group(1))]- try:- relative_asset = asset_pattern.format(value=asset_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()}-- for section_id, selector_field, references_field, catalog_dir in (- _CUSTOM_REFERENCE_CATALOGS- ):- section_fields = fields(section_id)- is_custom = (- _normalize_schema_value(section_fields.get(selector_field, "")) == "custom"- )- raw_references = _normalize_schema_value(- section_fields.get(references_field, "")- )- if not is_custom:- if raw_references:- errors.append(- f"{markdown_name} schema: field '{references_field}' is valid "- f"only when '{selector_field}' is custom"- )- continue- if not raw_references:- continue- references = [item.strip() for item in raw_references.split(",")]- duplicates = sorted(- reference- for reference in set(references)- if references.count(reference) > 1- )- if duplicates:- errors.append(- f"{markdown_name} schema: field '{references_field}' repeats "- f"catalog id(s) {', '.join(duplicates)}"- )- for reference in references:- catalog_file = catalog_dir / f"{reference}.md"- if reference == "custom" or not catalog_file.is_file():- errors.append(- f"{markdown_name} schema: field '{references_field}' references "- f"unknown catalog id '{reference}'"- )-- for key, value in fields("images").items():- if key.strip().casefold() in _LEGACY_IMAGE_METADATA_KEYS:- continue- try:- parse_spec_lock_image_value(key, value)- except ValueError as exc:- errors.append(- f"{markdown_name} schema: images row {key!r} {exc}"- )-- 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()- if basename.casefold().endswith(".svg"):- basename = basename[:-4]- 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,- *,- include_design: bool = True,-) -> tuple[list[str], list[str]]:- """Validate the lock and, when requested, the human-facing design brief."""- 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 include_design and 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- versioned_lock_valid = 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- artifact_errors = validate_markdown_schema(artifact_path, schema_path)- errors.extend(artifact_errors)- if artifact_kind == "lock" and not artifact_errors:- try:- parse_spec_lock_artifact(- artifact_path,- compatibility_warnings=warnings,- )- except (OSError, UnicodeError, ValueError) as exc:- errors.append(f"spec_lock.md compatibility parse failed: {exc}")- continue- versioned_lock_valid = True- if versioned_lock_valid:- try:- from svg_to_pptx.pptx_package.template_structure import (- TemplateStructureError,- load_pptx_structure_lock,- template_prototype_lock_errors,- )-- structure_lock = load_pptx_structure_lock(project_path)- if structure_lock is not None:- errors.extend(template_prototype_lock_errors(structure_lock))- except (ImportError, TemplateStructureError) as exc:- errors.append(f"spec_lock.md structure preflight failed: {exc}")- 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)+__all__ = [+ "SCAFFOLD_DIR",+ "SCHEMA_DIR",+ "SKILL_DIR",+ "TOOLS_DIR",+ "default_spec_lock_forbidden",+ "parse_markdown_artifact",+ "parse_spec_lock",+ "parse_spec_lock_artifact",+ "parse_spec_lock_image_value",+ "scaffold_project_artifact",+ "validate_markdown_schema",+ "validate_project_artifacts",+]diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 81903628..c6f101f2 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -54,7 +54,7 @@ from svg_to_pptx.canvas_contract import ()try:- from project_specs import (+ from project_management.project_specs import (parse_spec_lock as _parse_spec_lock,parse_spec_lock_image_value as _parse_spec_lock_image_value,)diff --git a/skills/ppt-master/scripts/update_spec.py b/skills/ppt-master/scripts/update_spec.pyindex 440a6893..ac73c903 100755--- a/skills/ppt-master/scripts/update_spec.py+++ b/skills/ppt-master/scripts/update_spec.py@@ -33,7 +33,7 @@ import tempfilefrom pathlib import Pathfrom console_encoding import configure_utf8_stdio-from project_specs import parse_spec_lock as parse_lock+from project_management.project_specs import parse_spec_lock as parse_lockconfigure_utf8_stdio()