Raven-1/plugins-dist/ppt-engine/fetch_templates.py
Tchen 5b4cce3f43 feat(ppt-engine): deliver where the user named, one route onto a page, and the ten templates
## Summary

This branch folds four merge requests and one unpushed commit into one, so that `main`
takes one review, one approval and one merge instead of four, and so the eight-file
overlap between them is resolved once. It carries, in this order:

- **!602** `feat/ppt_deliver_to_named_path` -- `ppt_build` takes `deliver_to`; every
  publish writes the deck under `out/` and copies the same measured bytes to the path
  the user named, recording it with `role: "delivery"`. The PDF preview rides along only
  where its own `.pdf` name is free: a file already at that stem is the user's and is
  left alone, and the reply says the preview stayed under `out/`.
- **!628** `feat/ppt_copy_route_and_page_isolation` -- `adapt` is removed, so cloning a
  template page and writing into it with `replace_text` is the only route; a page whose
  block raises loses only itself and the pages after it still build; a draft counts
  against the tier's build cap and one is released at it.
- **!632** `feat/ship_templates_and_soffice_dep` -- the ten bundled deck templates are
  tracked in git with per-file sha256 pins, so a fresh clone can build a deck; the
  LibreOffice dependency is declared and resolved through one resolver.
- **!642** `fix/ppt_copy_route_and_clone_typography` -- a copy-route lookup that finds
  nothing names the near miss before the inventory; a text frame with no paragraph at
  all can be written into; a cloned page's title size is said; `row_type_drift` compares
  the same structural slot across a run's units.
- **D57's other-page clause, rewired.** D57 gave five refusals a "did you mean" hint,
  and one of them also answered "the string you named is on page N of this template".
  That clause needs the file a page was cloned out of, and the only refusal holding it
  was `adapt`'s, which !628 removed. It is restored by reading `PPT_TEMPLATE_SOURCE`,
  which the runner already sets in the author's own process and which this module
  already reads for `bundled()`; the two helpers behind the clause are unchanged.
- **D60** `read the ground under each word, not across the whole box` -- the `unreadable`
  contrast gate also measures the render's own word boxes, as extra regions through the
  same guards, so a two-line block crossed by a narrow bright ridge can no longer elect
  the dark ground and read as legible.

Decisions the union forced, none of which drops a behaviour:

- The publish record is built !602's way, with its delivery `role`, and written the way
  D49 requires -- read back off the file, atomic, and refused rather than silent when
  the record cannot be written.
- `clear_region`, `shapes_in`, `page_box` and the refusal of a bare four-number region
  survive `adapt`'s removal; so do `_heading_rows` and its helpers, which the row
  reading loads even though the call they were written for is gone.
- The author-facing guidance names !628's single route and keeps D59's rule that a
  region must declare which reading it is.
**The decision log carries a numbering collision, on purpose.** It is a set union with
no wording changed, and the numbers are left exactly as each branch wrote them, so a
reviewer meets this rather than discovers it:

- !602 and !628 each wrote a **D37** and a **D38**, about different decisions.
- !628's **D45** is not `main`'s D45; they are unrelated entries under one number.
- !628's **D42** is `main`'s **D45** word for word, so the merged log carries one
  decision under two numbers.

Renumbering touches every cross-reference in the log, and doing that inside a
seventy-commit fold immediately before a merge is how a silent break gets in. The
numbering is being fixed on a separate branch, which carries a script and a test that
fails when a citation points at nothing.

## Type

- [x] Feature
- [x] Fix
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Run on an interpreter carrying `python-pptx`, with `PYTHONPATH` at this worktree and its
`plugins-dist/ppt-engine`, confirmed from a neutral working directory that `raven` and
`raven_ppt` resolve out of the worktree and not the host repo.

- `make test-python` (the whole suite, as CI runs it) -- 20826 passed, 49 skipped, and
  26 failures this machine produces on any branch: it has no `/usr/share/zoneinfo`, so
  every cron timezone case raises `ValueError: unknown timezone 'Asia/Shanghai'`. Checked
  out plain `origin/main` in a clean worktree and ran the same two files: the same 6
  failed and 20 errors, the ids identical character for character. Nothing on this branch
  touches cron or timezones. The stale `test_trunks_executor_would_have_dropped_that_output`
  that failed on the previous revision is retired on the new base and its replacement,
  `test_trunks_executor_preserves_output_on_timeout`, was run on its own and passes.
  The 6 failures and 20 errors are all cron timezone tests failing identically on plain
  `main` in a clean worktree, on a host with no `/usr/share/zoneinfo`.
- `make check-commits` -- exit 0.
- `make check-source-language` -- exit 0.
- `make check-large-files` -- exit 0.
- `make lint-imports` -- exit 0, 9 contracts kept, 0 broken.
- `ruff check` and `ruff format --check` over the 80 changed Python files -- exit 0.
- `pytest tests/test_ppt_engine_templates.py tests/test_utils_office.py
  tests/test_cli_doctor_commands.py` -- 97 passed; the ten templates are tracked and
  satisfy their pins, and the soffice resolver finds the local binary.
- The delivery contract, the record read-back, the page isolation and the near miss were
  each run as a measurement rather than asserted; the `unreadable` gate was run through
  the real LibreOffice render chain on a delivered 12-page deck and reports BLOCKING on
  page 12 under one word at 1.6:1.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

User-visible changes: `ppt_build` gains `deliver_to` and delivers outside `out/`;
`adapt` is gone from the author-facing template module, so a program calling it fails to
import -- `title=` and `subtitle=` have no replacement and the heading is named by the
words the template put there; a draft now counts against the tier's build cap; three
gates that nothing measured against being wrong no longer refuse; and the ten templates
are now bytes in the repository rather than a private registry fetch.

Two pieces here are about not destroying something the user has. The delivery
refuses to write its `.pdf` where a file the user already owns sits at the same
stem, rather than replacing it; and the large-file roster moved out of the manifest
inside the tree being checked and into the gate's own source, so a change can no
longer grant itself the exception the gate exists to withhold.

Rollback is per piece: each of the five sources is a contiguous run of commits on this
branch, in the order listed above, so any one of them can be reverted as a range without
touching the others.

- [x] Backward compatibility considered
- [x] Security impact considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A
2026-09-11 05:52:36 +00:00

177 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""Verify the tracked deck templates, or land a fresh cut of them.
Not an install step. The .pptx payload is tracked in git under the destination
``templates.manifest.json`` names, and rides the ppt-engine wheel from there, so a
fresh clone already has all ten: the registry this script pulls from is private, and
requiring it was why an outside install got an empty template catalogue. What remains
is the maintainer half of the loop.
``--verify`` (the everyday mode) hashes what is on disk against the pins -- the same
check the release gate runs against the built wheel. Landing a re-cut is the other
half: ``--from <dir>`` copies from a local directory, and a bare run pulls the pinned
version out of the project's GitLab generic package registry, carrying ``PRIVATE-TOKEN``
from ``$GITLAB_TOKEN`` (any token that can read the repository) or ``JOB-TOKEN`` from
``$CI_JOB_TOKEN`` inside CI. Either way the new bytes must then be committed, with the
pins rewritten to match. Whatever fails its pin is removed, never kept: a wheel built
over the destination must not package a byte the manifest did not sign.
A manifest whose endpoint is still a ``stub://`` placeholder is refused with the owner
card rather than guessed at.
Exit codes: 0 verified; 1 payload missing or failing its pin; 2 endpoint
still un-named (the owner card was printed).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import sys
import urllib.request
from pathlib import Path
HERE = Path(__file__).resolve().parent
DEFAULT_MANIFEST = HERE / "templates.manifest.json"
EXIT_OK = 0
EXIT_VERIFY = 1
EXIT_UNNAMED = 2
_FETCHABLE_SCHEMES = ("https://", "http://", "file://")
def log(message: str) -> None:
print(message, file=sys.stderr, flush=True)
def load_manifest(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
def destination(manifest: dict, manifest_path: Path) -> Path:
"""The payload directory, resolved against the manifest's own location."""
return (manifest_path.parent / manifest["destination"]).resolve()
def sha256_file(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 check_one(target: Path, entry: dict) -> str | None:
"""One complaint, or None when ``target`` matches its pin exactly."""
if not target.is_file():
return f"missing: {entry['name']}"
size = target.stat().st_size
if size != entry["bytes"]:
return f"size mismatch: {entry['name']} holds {size} bytes, pinned {entry['bytes']}"
digest = sha256_file(target)
if digest != entry["sha256"]:
return f"sha256 mismatch: {entry['name']} is {digest}, pinned {entry['sha256']}"
return None
def verify(dest: Path, manifest: dict) -> list[str]:
"""Every complaint against the destination, empty when every pin holds."""
return [complaint for entry in manifest["files"] if (complaint := check_one(dest / entry["name"], entry))]
def refuse_unnamed(endpoint: dict) -> int:
"""The owner card: who names the host, and what works meanwhile."""
log("error: the template hosting endpoint is not yet named; refusing to invent one.")
log(f" url: {endpoint.get('url')}")
log(f" status: {endpoint.get('status')}")
log(f" owner: {endpoint.get('owner')}")
log(f" ruling: {endpoint.get('ruling')}")
log(f" today: {sys.executable} {Path(__file__).name} --from <dir holding the pinned .pptx>")
return EXIT_UNNAMED
def auth_headers(environ: dict[str, str] | None = None) -> dict[str, str]:
"""The header a private registry wants, from whichever token the environment holds.
A personal or project token first (``GITLAB_TOKEN``, the one that clones the repo),
the CI job token when only that is present, nothing for a public host.
"""
env = os.environ if environ is None else environ
if token := env.get("GITLAB_TOKEN") or env.get("PPT_TEMPLATES_TOKEN"):
return {"PRIVATE-TOKEN": token}
if job := env.get("CI_JOB_TOKEN"):
return {"JOB-TOKEN": job}
return {}
def pull(source: str, dest: Path, manifest: dict) -> list[str]:
"""Copy every pinned file from ``source`` (a directory or a URL base)
into ``dest``, verifying each against its pin as it lands.
A file failing its pin is removed rather than left behind: a wheel built
over this directory must never package a byte the manifest did not sign.
"""
complaints: list[str] = []
dest.mkdir(parents=True, exist_ok=True)
source_dir = Path(source) if not source.startswith(_FETCHABLE_SCHEMES) else None
for entry in manifest["files"]:
name = entry["name"]
target = dest / name
if source_dir is not None:
candidate = source_dir / name
if not candidate.is_file():
complaints.append(f"missing at source: {name}")
continue
shutil.copyfile(candidate, target)
else:
request = urllib.request.Request(f"{source.rstrip('/')}/{name}", headers=auth_headers()) # noqa: S310 -- scheme gated in main()
with urllib.request.urlopen(request) as response: # noqa: S310
target.write_bytes(response.read())
if complaint := check_one(target, entry):
target.unlink(missing_ok=True)
complaints.append(complaint + " (removed)")
else:
log(f"[templates] verified {name} ({entry['bytes']} bytes)")
return complaints
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Fetch or verify the pinned deck templates.")
parser.add_argument("--manifest", default=str(DEFAULT_MANIFEST))
parser.add_argument("--dest", default=None, help="override the manifest's destination directory")
parser.add_argument(
"--from", dest="source_dir", default=None, help="pull from a local directory instead of the endpoint"
)
parser.add_argument("--verify", action="store_true", help="verify what is already in place; pull nothing")
args = parser.parse_args(argv)
manifest_path = Path(args.manifest).resolve()
manifest = load_manifest(manifest_path)
dest = Path(args.dest).resolve() if args.dest else destination(manifest, manifest_path)
if args.verify:
complaints = verify(dest, manifest)
elif args.source_dir:
complaints = pull(args.source_dir, dest, manifest)
else:
endpoint = manifest.get("endpoint") or {}
url = str(endpoint.get("url") or "")
if endpoint.get("status") != "NAMED" or not url.startswith(_FETCHABLE_SCHEMES):
return refuse_unnamed(endpoint)
complaints = pull(url, dest, manifest)
for complaint in complaints:
log(f"[templates] {complaint}")
if complaints:
return EXIT_VERIFY
log(f"[templates] all {len(manifest['files'])} pins hold under {dest}")
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())