diff --git a/.ash.yaml b/.ash.yaml index c82ed189b..cbebf79ba 100644 --- a/.ash.yaml +++ b/.ash.yaml @@ -55,6 +55,34 @@ global_settings: 12-hex-digit task ids (the shape compose_dispatch.py gives them), not credentials. expiration: "2027-11-08" + # --- Animation catalog provenance: commit SHAs and a corpus digest --- + # The catalog records which commit of each external reference was read and a digest of + # the fixture corpus the facts were checked against, so the attribution is verifiable + # and a changed upstream fails the test. Public identifiers, deliberately published. + + - rule_id: "SECRET-HEX-HIGH-ENTROPY-STRING" + path: "scripts/animation_catalog/generate.py" + reason: > + PROVENANCE_REFERENCES pins the git commit of each external reference read while + deriving the animation catalog (office-kit/pptx, ChristopherVR/ooxml) and the + sha256 of the fixture corpus the facts were checked against. Public commit ids and + a digest of public files, not credentials. + expiration: "2027-11-13" + + - rule_id: "SECRET-HEX-HIGH-ENTROPY-STRING" + path: "sdpm/references/catalogs/powerpoint-animation-catalog.json" + reason: > + The generated catalog's provenance block, carrying the same commit ids and corpus + digest as generate.py so a reader can check the attribution without the generator. + expiration: "2027-11-13" + + - rule_id: "SECRET-HEX-HIGH-ENTROPY-STRING" + path: "tests/test_animation_catalog.py" + reason: > + test_catalog_provenance_names_every_external_reference_without_vendoring asserts + those commit ids, which is the point: a silently changed provenance block fails. + expiration: "2027-11-13" + # --- CFn Custom Resource: urlopen to pre-signed ResponseURL --- # Standard pattern for CloudFormation custom resources. # The URL is the CFn-provided ResponseURL, not user-controlled. diff --git a/.gitattributes b/.gitattributes index 30e0b7bea..6f62f7708 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,10 @@ sdpm/vendor/** -text # Slide JSON of the documentation diagrams and the key visual: collapsed in GitHub diffs. docs/assets/src/**/*.json linguist-generated +# The animation capability catalog is produced by scripts/animation_catalog/generate.py +# and the GUI capture evidence is written by the capture drivers: collapsed in GitHub diffs +# so a review of this area reads the code rather than ~240k lines of data. +sdpm/references/catalogs/*.json linguist-generated +tests/fixtures/animations/** linguist-generated +# The seven READMEs in that tree are written by hand and explain the captures. +tests/fixtures/animations/**/README.md -linguist-generated diff --git a/CHANGELOG.md b/CHANGELOG.md index e9d9dc427..44d6c10d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,54 @@ Under an Upgrading section, the bullets after **Local installs (`sdpm update`).* ## [Unreleased] +### Added + +- **Object animations and slide transitions, opt-in per deck.** A slide JSON file can now + carry `transition` (how that slide enters, including Morph by object / word / character) + and `animations` (a main sequence plus one interactive sequence per trigger shape), and + `deck.json` carries the two independent switches `animations.enabled` and + `transitions.enabled`. Both default to off, an absent switch is off, and a deck written + before this release builds byte-identically; `generate` / the CLI / both MCP servers also + take independent `animation_mode` / `transition_mode` overrides (`inherit` / `on` / `off`) + that never rewrite `deck.json`. Importing a PPTX derives each switch from what the file + actually contained, recovers transitions, sequences, triggers, timing and `morphId` as + editable JSON, and preserves anything it cannot decode semantically as raw XML in the + import bundle with a hashed dependency manifest, so a GUI-edited deck round-trips instead + of losing its motion. The authoring contract is a new optional guide, + `read_guides(["animations"])`: composers load it only when a switch is on or a slide + already carries those fields, so ordinary still decks pay no context for it. Authoring + coverage is deliberately partial and the guide says exactly where — 12 entrance and 12 + exit effects, media play, all 53 transition effects and all three Morph variants are + generated today, while effect directions, emphasis and motion-path galleries, + after-animation effects, sounds and four timing options are preserved on import but + refused at generation by their catalog key rather than approximated. + `read_guides(["effect:flyIn"])` answers what a gallery + animation actually does — measured from + PowerPoint rather than guessed: a bare `effect:` returns the routing table (which effects + move, resize, recolour, rotate, fade, wipe or follow a path), an effect name returns every + behaviour it writes with keyframes and durations, and a transition name returns the + `parameters` sets it accepts. A name the routing table shows qualified is asked for that + way (`effect:entrance.bounce`, which is a different effect from `motionPath.bounce`). It rides on `read_guides` rather than being a tool of its + own because a tool's description is sent on every turn of every conversation, including the + decks that carry no animation; the MCP tool count is unchanged. +- **A storyboard: one still frame per click.** `storyboard()` (CLI: `storyboard `) + derives the state after each click from the animation catalog and renders it, so a build + can be inspected. The ordinary preview draws every element where it is authored, which is + exactly why it cannot show build order: an element revealed too early, never revealed, or + hidden at the end of its own build all look correct in it. Each frame carries notes for + what a still cannot show — an emphasis that returns to where it started, a path that + leaves and comes back. `generate` also reports `animated_slides`, and a text build that + cannot survive the file format is now warned about at build time rather than silently + flattened. +- **A craft guide for motion**, `read_guides(["animation-craft"])`: how much to move and + when, as recommendations rather than rules, split by who controls the pace — `presenter` + (one idea per click, motion as feedback) and `cinematic` (one click per scene, motion as + content) — with a recipe table, the translation from the usual easing vocabulary to what + PowerPoint records (it has no bézier: `acceleration` / `deceleration` are duration + fractions, and there is no overshoot or spring), and the accessibility limits, which are + the one hard requirement in it (WCAG 2.3.3 and the Office animation setting are external + facts, not taste). + ## [0.19.0] - 2026-11-18 The Web UI is laid out anew. It has a left rail and a home screen that is the chat, with diff --git a/scripts/animation_catalog/README.md b/scripts/animation_catalog/README.md new file mode 100644 index 000000000..ec75a1dd0 --- /dev/null +++ b/scripts/animation_catalog/README.md @@ -0,0 +1,403 @@ +# PowerPoint animation catalog tools + +Development-only tools in this directory create native PowerPoint evidence used by sdpm's checked-in animation and transition catalog. Runtime generation never invokes PowerPoint, AppleScript, or GUI automation. + +## Morph spike + +Run from the repository root: + +```bash +uv run python scripts/animation_catalog/morph_probe.py --verify-package +``` + +The probe applies Microsoft's documented forced-Morph naming convention: matching adjacent objects are named with the same `!!`-prefixed Selection Pane name. It builds destination slides for `byObject`, `byWord`, and `byChar` using the Office 2015/09 `p159:morph` transition inside `mc:AlternateContent`, with a standard fade fallback. + +The automated probe verifies package structure only. This dashboard's sandbox cannot control PowerPoint through Apple Events (`-10004` privilege violation), so visible interpolation versus cross-fade is verified once in the final PowerPoint acceptance flow. + +Source: [Morph transition: Tips and tricks](https://support.microsoft.com/en-us/office/morph-tips-and-tricks-bc7f48ff-f152-4ee8-9081-d3121788024f) + +## Capability catalog + +Two checked-in artefacts, with different owners: + +| File | Owner | Role | +| --- | --- | --- | +| `scripts/animation_catalog/powerpoint-gui-surface-16.113.1.json` | hand-maintained | the versioned **expected universe**: every GUI control/value with its discovery evidence, persistence flag, verification method and expected disposition, plus the assignment of all 435 scripting candidates to a GUI surface | +| `sdpm/references/catalogs/powerpoint-animation-catalog.json` | generated | the **derived catalog**: full semantic JSON, OOXML mapping metadata, capability level, evidence and provenance per entry | + +`generate.py` writes the second file and the generated candidate arrays inside `powerpoint.applescript`. The manifest is never written by a script, which is what lets `--check` catch drift in either direction (REQ-7.4). + +```bash +# verify the checked-in pair and the oracle (no network, no PowerPoint) +uv run python scripts/animation_catalog/generate.py --check + +# the same, but fail if the local scripting definition or the oracle is missing +uv run python scripts/animation_catalog/generate.py --check --require-sdef + +# deterministically regenerate the catalog and the oracle's candidate arrays +# (needs PowerPoint installed; reads its scripting definition, never runs it) +uv run python scripts/animation_catalog/generate.py --write +``` + +`--check` compares four independent inputs and reports every disagreement: + +- the local `PowerPoint.sdef` candidate set against the manifest and the catalog — missing and extra candidates, and four-char code drift; +- manifest expectations against catalog dispositions — status and `guiKey` drift, GUI items accounted on one side only; +- required metadata — fixed `generatedAt`, manifest linkage, a reason on every non-accepted entry, `semanticJson` plus `ooxml` on every accepted entry, a pinned fixture behind every `nativeTemplate` claim, and a documented gap behind every `semanticPreservationOnly` claim; +- the AppleScript oracle — all 435 candidate names and codes against the sdef, no empty candidate array or unfinished-work marker, and the object-model constructs the scripting definition actually declares (see [the oracle section](#powerpoint-oracle-and-gui-only-values)); +- byte-level drift against a deterministic regeneration of both the catalog and the oracle's generated region. + +Without PowerPoint installed, `--check` skips only the sdef comparison and still runs every structural and drift check, so CI stays green on machines that have no Office. + +### Candidate universe + +435 candidates, read from the locally installed scripting definition: + +| Enumeration | Count | GUI surface | +| --- | --- | --- | +| `MsoAnimEffect` | 150 | Animations gallery, More … Effects dialogs | +| `MsoAnimDirection` | 45 | Effect Options ▸ Direction | +| `MsoAnimTriggerType` | 5 | Animations ▸ Start | +| `MsoAnimateByLevel` | 12 | Effect Options ▸ Text / Chart Animation ▸ Group | +| `MsoAnimTextUnitEffect` | 3 | Effect Options ▸ Effect ▸ Animate text | +| `MsoAnimAfterEffect` | 4 | Effect Options ▸ Effect ▸ After animation | +| `MsoAnimType` | 9 | Animation Pane behaviour primitives | +| `EPPEntryEffect` | 207 | Transitions gallery and Effect Options | + +Animation-relevant enumerations outside that set are listed in the manifest's `supplementaryEnums` with an explicit disposition, so nothing disappears quietly. + +### Capability levels + +Every accepted entry declares how far its evidence actually reaches. Task 4's writer must branch on this rather than assume a usable template exists. + +| Level | Meaning | Writer action | +| --- | --- | --- | +| `nativeTemplate` | exact OOXML captured from retail PowerPoint for this value; `evidence.fixture` names the artefact | emit the captured form | +| `presetMapping` | the element, attribute or identifier is fixed by a normative ECMA-376 enumeration, or corroborated by two independent sources; no visual capture | emit the mapping; schedule read-back | +| `semanticPreservationOnly` | the JSON round-trips, but the OOXML identifier or geometry is **not** established; `ooxml.gap` says exactly what is missing and `ooxml.requiresCapture` is set | do not guess an identifier — emit a documented fallback or defer to Task 8 | + +Two gaps are worth knowing before reading the catalog: + +- **`MsoAnimEffect` ordinals above 31 have no established `presetID`.** The ordinal equals the OOXML entrance/exit `presetID` only up to 31. Above that the numbering diverges (`msoAnimEffectLightSpeed` is 32 but saves 34; `msoAnimEffectFold` is 53 but saves 58). Where a gallery tile has the same name, the catalog records it under `ooxml.nameMatchedGalleryItem` with `nameMatchConfidence: nameMatchOnly` — a lead to verify, not a mapping to trust. +- **Preset motion paths carry literal path data.** `p:animMotion/@path` is the payload and the `presetID` is informational, so every motion-path entry stays `semanticPreservationOnly` until the geometry is captured. + +### Maintaining the manifest + +Edit `powerpoint-gui-surface-16.113.1.json` by hand when the GUI surface changes, then regenerate and check: + +1. Bump `manifestVersion` (the catalog's `baseline.guiManifest` pins it, so a stale catalog fails `--check`). +2. Add or change `items` entries. Every item needs `control`, `value`, `surface`, `sourceEvidence`, `persisted`, `verificationMethod` and `status`. +3. Add or change `candidates` entries. Every candidate needs `enum`, `enumerator`, `code`, `guiKey` and `status`. +4. Teach `generate.py` the matching evidence — a new GUI item with no generator evidence fails `--check` rather than being silently accepted. +5. Run `--write`, then `--check --require-sdef`, then `uv run pytest tests/test_animation_catalog.py -q`. + +A PowerPoint upgrade that changes an enumeration shows up as a missing or extra candidate, which is the point: the manifest, not the generator, defines what complete means. + +### Evidence sources + +The catalog records provenance for every external input in `provenance.references`. No external code or fixture bytes are copied into this repository; the OOXML facts were re-derived and the generator is original work. + +| Source | Pin | License | Used for | +| --- | --- | --- | --- | +| [`office-kit/pptx`](https://github.com/office-kit/pptx) | `18b7e75c` | MIT | 95 animation gallery, 3 text-build and 49 transition native fixtures saved by PowerPoint for Mac 16.113.3, plus their capture provenance | +| [`ChristopherVR/ooxml`](https://github.com/ChristopherVR/ooxml) | `e269a0bb` | Apache-2.0 | COM-derived entrance/exit and emphasis `presetID` tables, and its documented ordinal/`presetID` divergence above 31 | +| `PowerPoint.sdef` | local 16.113.1 | not redistributed | the candidate universe: enumerator names and four-char codes | +| ECMA-376 Part 1 PresentationML | — | — | normative transition elements, `ST_TLTimeNodeType`, `ST_IterateType`, chart and diagram build types | + +The captured fixtures come from 16.113.**3** while the baseline is 16.113.**1**. That difference is recorded in `provenance.references[].capturedApplicationVersion` and is one of the things Task 8's read-back has to confirm. + +## PowerPoint oracle and GUI-only values + +`powerpoint.applescript` is the development-only scripting oracle. It drives the AppleScript dictionary only — no VBA anywhere. Nothing in sdpm's runtime, CLI, MCP servers, tests or CI runs it; a maintainer ran it once, on 2026-10-31, from a terminal holding the Automation grant. This dashboard still cannot: addressing PowerPoint from it is refused with a `-10004` privilege violation. + +### What the 2026-10-31 run established, and what it did not + +The run's three artefacts are checked in under `tests/fixtures/animations/oracle-16.113.1/` and are a **generator input**: `--write` folds them into the catalog, so a promoted value is derived from evidence in the repository rather than hand-edited into the JSON, and `--check` fails when the catalog and the capture disagree. + +| | Result | +| --- | --- | +| **Transitions** | All 207 `EPPEntryEffect` candidates probed. 160 produced a `p:transition`; 157 of them are accepted mappings and are promoted, with `verification: "scriptingOracleCapture"` and `capture` naming the package, the read-back, the slide and the measured attributes. No transition entry is capture-required any more. | +| **Animations** | Nothing. All 150 `MsoAnimEffect` candidates were refused with the same error, and no slide in the package carries a `p:timing` tree. | +| **The other six enumerations** | Never reached: the run aborted in `msoAnimDirectionConstants`. Their entries carry no `capture` block, and `provenance.scriptingOracle.unprobedEnumerations` names them. | + +### `add effect` is not implemented in 16.113.1, so the dictionary cannot author animations + +Every `MsoAnimEffect` probe failed with: + +``` +main sequence of timeline of slide N of presentation "Presentation1" +doesn't understand the "add effect" message. +``` + +`add effect` **is** declared in `PowerPoint.sdef` — the oracle's whole animation half was written against it — but PowerPoint for Mac 16.113.1 does not implement it on `main sequence`. The dictionary over-promises, and correcting the oracle's terminology cannot fix it: `probeAnimations`, `probeDirections`, `probeTriggers`, `probeBuildLevels`, `probeTextUnits`, `probeBehaviors` and `probeAfterEffects` all depend on first adding an effect. + +**Do not rewrite the AppleScript animation probes.** Every animation-side capture — the remaining capture-required entries and the unresolved behavior payloads — has to go through the GUI procedure in [`computer-use.md`](computer-use.md). The transition half of the oracle is worth keeping, and is the better route where it works, because it applies a candidate **by enumerator code** and so yields the enumerator → OOXML mapping the catalog is keyed on; the GUI applies by label and cannot. + +### Where a captured duration is and is not evidence + +All 160 captured transitions carry `spd="slow"` and `p14:dur="2000"`. The probe set each slide's `entry effect` and nothing else, so that is the duration the script-created probe slide already held, not the effect's own default — a per-effect default could not be identical across 160 effects, and the Box tile is 1600 ms in both its native capture and the Transitions ribbon. The capture is therefore recorded per entry as `capture.transitionAttributes`, `provenance.scriptingOracle` explains it, and `ooxml.defaultDurationMs` keeps its native-capture value. + +### It only launches PowerPoint when a maintainer says so + +The run handler needs two arguments and refuses to send a single Apple event without the second one: + +```bash +osascript scripts/animation_catalog/powerpoint.applescript \ + /absolute/path/to/output-dir --run-powerpoint +``` + +Without `--run-powerpoint` it errors out before the first `tell application` block. `tests/test_animation_catalog.py` asserts that the consent argument appears nowhere except the oracle, the generator that checks it, this README and the test itself, so `--check` and `pytest` cannot start PowerPoint even by accident. + +### Checking its syntax does not launch PowerPoint + +Compiling resolves the terminology out of the application bundle's `PowerPoint.sdef`; it does not start the application: + +```bash +osacompile -o /tmp/powerpoint-oracle.scpt scripts/animation_catalog/powerpoint.applescript +``` + +The test suite runs exactly that on macOS when PowerPoint is installed, and round-trips the result through `osadecompile` to prove the 435 constants are real enumerators rather than identifiers the compiler happened to tolerate. + +### The candidate arrays are generated, not hand-pasted + +Everything between `-- >>> BEGIN GENERATED sdef CANDIDATE ARRAYS >>>` and its end marker is written by `generate.py --write` from the locally installed scripting definition: three parallel arrays per enumeration — the constants, their sdef names, and their sdef codes — for all 435 candidates, including the 150 `MsoAnimEffect` and 207 `EPPEntryEffect` values. `--check --require-sdef` compares every name and every code in that region against the sdef, rejects an empty array or an unfinished-work marker, and requires the object-model constructs below. + +A constant is named **by code**, not by term: `my enumConstant("pEeF00F60F55")` is the enumeration's four-character type code followed by the enumerator's own eight hex digits, and the oracle's `enumConstant` handler turns it into the Apple Event constant through AppleScript's raw constant syntax. A bare enumerator term is ambiguous two ways, and both are measured in `tests/test_animation_catalog.py`: + +- `top`, `font bold`, `font italic` (`MsoAnimDirection`) and `dim` (`MsoAnimAfterEffect`) are also PowerPoint **property** names, so the compiler builds a property reference and evaluating one raises `-1728`. That is what aborted the 2026-10-31 run, after 357 candidates had been applied. +- `horizontal` and `vertical` (`MsoAnimDirection`) compile to constants of a **different enumeration** — `TxOr`, text orientation. Nothing fails: the probe would apply a text orientation and the record would name the direction that was asked for. + +Naming every candidate by code removes both classes by construction rather than by keeping a list of the terms known to collide. A raw `«data pEeF00F60F55»` literal would compile, but its AppleScript class is `data` rather than `constant`, so it compares unequal to the value PowerPoint reports back and every record's `applied` field would be `null`; the constant `enumConstant` builds compares equal to the term it names, which the test suite checks for all 435 candidates offline. + +### The object model it uses + +| Candidate | How the oracle applies it | How the value comes back | +| --- | --- | --- | +| `EPPEntryEffect` | `set entry effect of slide show transition of theSlide to …` | `entry effect of slide show transition of theSlide` | +| `MsoAnimEffect` | `add effect (main sequence of timeline of theSlide) for theShape fx … trigger on page click` | `animation effect type of theEffect` | +| `MsoAnimDirection` | `set direction of effect parameters of theEffect to …` | `direction of effect parameters of theEffect` | +| `MsoAnimateByLevel` | `add effect … level … trigger on page click` | `build by level of effect information of theEffect` | +| `MsoAnimTextUnitEffect` | `convert to text unit effect … Effect … unit …` | `text unit effect information of effect information of …` | +| `MsoAnimType` | `add behavior theEffect type …` | `animation behavior type of theBehavior` | +| `MsoAnimTriggerType` | `add effect … trigger …` | **not readable**: neither `effect` nor `timing` exposes a trigger property | +| `MsoAnimAfterEffect` | **not settable**: `after effect information` is read-only | — | + +A slide's transition is a property of its own `slide show transition` object and animations hang off `timeline` → `main sequence`, not off the slide. The first draft of this file had neither, plus empty candidate lists and a constant mapper that raised on every name; `--check` now fails on all of those. Everything in the `MsoAnim*` rows of that table is declared by the dictionary and refused by the application — see `add effect` above. + +### One failed probe no longer discards the run + +`captureCatalog` dispatches the eight probes through `runProbe`, which contains each one: a failure becomes a `{"record": "probe", "rejected": true, …}` line and the run continues to the next probe, `saveSnapshot` writes the package after every probe, and `savePackage` is reached whatever happened. A capture run is expensive and partially valuable by nature — the 2026-10-31 run applied 357 candidates and then lost all of them to one bad term in the fourth probe, because the failure propagated out before the save; only a hand save of the still-open deck recovered the evidence that is now checked in. + +### The values the dictionary cannot report + +The oracle saves its probe deck (`save probe in (POSIX file packagePath) as save as Open XML presentation`) and the Python side reads the rest out of the package — no PowerPoint, no network: + +```bash +uv run python scripts/animation_catalog/generate.py --parse-oracle /absolute/path/to/output-dir +``` + +That reads `powerpoint-oracle.pptx` part by part and joins it with `powerpoint-readback.jsonl` on the probe slide index, reporting: + +- `p:transition`, its attributes, and which `mc:Choice`/`mc:Fallback` branch it came from, with the `Requires` prefix; +- `p:cTn/@presetClass`, `@presetID`, `@presetSubtype`, `@nodeType` and `@afterEffect`, with the behaviour elements under each preset node; +- `p:cond/@evt` start conditions, `p:iterate/@type`, `p:bldP`/`p:bldDgm` builds and `p:animMotion/@path` geometry; +- a `unresolvedCandidates` list, so a candidate whose evidence is still missing is named rather than quietly dropped. + +Nothing in that output is promoted to a capability level automatically. A maintainer decides, and the catalog entry then names the artefact the claim came from. + +`computer-use.md` covers the remaining values no offline source and no dictionary call can settle, with reproducible steps, required evidence and a logging format keyed to the catalog entries they would promote. + +## GUI capture driver + +Every remaining animation value has to be applied through the ribbon, and the macOS Accessibility API is reachable from Python here, so the four calls per value that `computer-use.md` measures are a loop inside one process rather than four agent turns. Two development-only modules do that, and like the oracle, nothing in sdpm's runtime, CLI, MCP servers, tests or CI invokes either. + +| File | Role | +| --- | --- | +| `gui_capture_plan.py` | derives the target list from the catalog's own gaps, and builds the capture deck that list implies | +| `gui_capture.py` | drives PowerPoint: select a target's own shape by its Selection Pane row, press by title, save, attribute the new effect to that shape | + +### It selects a shape through its Selection Pane row, because clicking the canvas did not work + +A canvas shape has no accessibility element, so shape selection used to be a +synthetic global mouse event at a point derived from the package geometry, the +live editor-pane frame and the live zoom. It never became reliable: watching a +run, the pointer landed in the right place and the shape stayed unselected, +while the same click by hand always worked. Pacing the event — a click state, a +settle before the button-down, a hold, and a 0.35 s settle after the up — helped +without fixing it. The last run of that version captured **2 of 12** attempted +targets; the other ten were rejected as `effectNotAdded` with "no new effect +appeared", which is what a click that did not change the selection looks like, +because the gallery press then replaced the *previously* selected shape's +effect. + +Canvas shapes have no element, but **their Selection Pane rows do**. The driver +opens `Home ▸ Arrange ▸ Selection Pane...` once per run and selects each target +by **setting `AXSelected` on that shape's row** — there is no `AXPress` on a row +— then reads the row back to confirm. No coordinates, no pointer, no zoom, no +editor-pane frame and no settling. + +A row is addressed by **index**, which is the shape's position in **reverse +z-order**, read offline from the package and matched against the row that reports +that `AXIndex`. The row order was verified against the live pane twice at 152 +rows with 0 mismatches. + +Two keys were tried and discarded, and both failures are measured. A **name** +cannot be the key: a row's `title` is `None` and its name is the `value` of a +descendant `AXStaticText` that only exists once the row has been scrolled into +view, so one run's batches read 80 names, then 54, and rejected 11 targets as "no +Selection Pane row is named ..." for rows that were selectable throughout. An +**offset into `AXRows`** cannot be the key either: the pane published 43, 54, 61, +63, 74, 88 and 91 rows on consecutive reads of the same 152-shape slide, because +it rebuilds while the application works, and that rejected 7 more targets. Every +row publishes its own `AXIndex` in both states, so that is what a row is found +by, and a read that does not contain the row is retried until it does. + +The name is still checked whenever the pane publishes one, as a check on the +order rather than a lookup: if the row at an index is named something other than +the shape expected there, the target is refused. That is what stands between a +renumbered pane and a value applied to the wrong shape under the right key, which +no later gate can undo. + +So `read_canvas_geometry`, `canvas_point`, `read_shape_center_pt`, `parse_zoom` +and the `--pane-frame` / `--pane-role` / `--zoom` options are gone, along with +the backend's `click`. `computer-use.md` records the measured pane mechanics +under "Why the driver selects shapes in the Selection Pane", and keeps the +canvas formula for manual work only. + +### It does not select slides, because that is what failed + +A live run of the first version — one slide per target, selected in the +navigator — returned **76 records, 0 captured, 76 rejected**, with no record +getting as far as pressing a control. The navigator's cells expose no +accessibility actions and `kAXSelected` never reads back true, so the first six +targets timed out; and the navigator publishes only the cells currently +**scrolled into view**, six of seventy-six, so the rest were not addressable at +all. + +Slide selection is therefore gone, together with the thumbnail lookup and the +`Has Animation` check that depended on it. `computer-use.md` records both +failures under "Why the driver does not select slides", and +`tests/test_animation_gui_capture.py` fails if either function's name comes back. + +### The plan is derived, so it cannot drift + +A hand-written target list stays the same length when a capture closes an entry, which is exactly when it stops being true. So the plan is read out of `powerpoint-animation-catalog.json`: the entries whose `ooxml.requiresCapture` is true, restricted to the key namespaces the GUI can address, with the GUI path each entry's own metadata implies. + +```bash +uv run python scripts/animation_catalog/gui_capture_plan.py --summary +``` + +Four lists come out, because "not in the plan" has four different meanings and none of them is "dropped": + +| List | Count today | What it is | +| --- | --- | --- | +| `targets` | 0 | GUI-addressable and resolvable by title in one press. **Empty, because every gallery gap is closed** — 76 captured on 2026-11-01 (71 gallery tiles plus 5 motion-path presets), and 16 more reached through their own default effect option, whose measured behaviours are the tile's — and the plan is the catalog's own open gaps. A tile added to the gallery tables, or a gap reopened, appears here again | +| `deferredTargets` | 47 | GUI-addressable namespace whose metadata implies no pressable path: the 45 `Effect Options` directions (their labels depend on which effect is applied) and 2 Media tiles (need a media object on the slide). The custom motion path used to be the 51st; it is not a target at all now, because the Custom group is a selection surface for the four Draw tools and the catalog records it `nonPersisted`. The 3 After animation values were deferred as "a dialog behind a prerequisite effect" — this build has no effect dialog, and they were measured in the Animation Pane on 2026-11-02 | +| `setAsideScriptingEnumerators` | 181 | the `MsoAnim*` candidates. The GUI applies by **label**; a scripting enumerator is a different identity, so closing one here would state a name correspondence rather than measure a value. 184, not 185: `MsoAnimTriggerType.no trigger` left the accepted set, because an absent start condition is not a value a capture can reach. 181, not 184: the three `MsoAnimAfterEffect` values are written now — the Animation Pane measurement on 2026-11-02 established the OOXML their `animation.afterAnimation.*` twins carry, so the enumerator is no longer a name correspondence awaiting a value | +| `gapsWithoutCaptureFlag` | 2 | GUI-addressable entries carrying an `ooxml.gap` and `powerPointReadBackRequired` but no `requiresCapture` flag. Listed so the selection rule's edge is visible rather than looking like coverage. Down from 8: `animation.start.none` left when an absent start condition stopped being treated as an unmeasured value; Smooth Start and Smooth End left when the measurement showed them to be `timing.acceleration` / `.deceleration` under the Animation Pane's names; `animation.timing.rewind` left when the same pass measured it as `p:cTn/@fill` moving `hold` → `remove`; `animation.timing.bounceEnd` left when the writer learned to emit the `mc:AlternateContent` wrapper its two `p14` attributes need. The 2 that remain are the effect sounds, which need an audio part and a package relationship rather than a measurement | + +The driver supports a prerequisite press, so a deferral is a statement about the derivation, not a limit of the driver: a plan that names the prerequisite effect for a direction can be run. + +### The capture deck is generated by committed code: as few slides as the constraints allow + +Today's 99 targets become **two slides** carrying one named shape each, laid out +as an **8x7** grid with the key's last segment as visible text under its own +shape, built through `sdpm.api.generate` with **both motion switches off** — in +`deck.json` and again as a caller override — so sdpm contributes no motion and +every `p:timing` tree in the saved package came from PowerPoint. + +The grid was 8x10 with two-line labels, which left each shape 77x22 pt. A click's +accuracy was bounded by the **short** side, and 22 pt was too small: a live run put +71 presses onto five shapes, because a click that lands on empty canvas leaves the +previous shape selected and the next press overwrites **its** effect. Squarer cells +and a one-line label take the short side to 43.5 pt. The key itself is not lost — +it is in the plan, and each shape carries its ordinal. + +Shape size and separation are **no longer load-bearing**, because nothing is +clicked: a shape is selected through its Selection Pane row. The deck is kept as +it is rather than regenerated, and the grid's separation checks stay, so a future +reader is not left wondering whether a tighter grid would change a capture. + +```bash +uv run python scripts/animation_catalog/gui_capture_plan.py --emit-plan \ + --out /abs/out/plan.json \ + --build-deck /abs/out/deck \ + --generate /abs/out/capture-deck.pptx +``` + +The grid is derived from the target count and then checked rather than eyeballed: +no two shapes overlap, a shape's centre sits at least 10 pt inside its own edges, +and it clears every other shape by at least 10 pt, so a click aimed at a centre +cannot land on a neighbour. A count that does not fit one slide under those +constraints is split across as few slides as it can be and the plan's `deck` +block says so. One slide holds 128 at the 40 pt minimum short side, and fewer once +the widest label has to fit on one line — `complementaryColor2` needs 114 px — so +99 takes two slides at 200x105 px per shape. Both floors are layout constraints +rather than checks run afterwards: the short side because 22 pt shapes once took +71 presses and landed them on five shapes, and the label width because a label +that wraps steals the height that keeps a shape clickable. + +`--generate` also reads every target shape's real name back out of the package, +matching each target to the shape at the position the grid asked for, and writes +the `target key -> shape name` mapping into the plan. sdpm names a shape from its +geometry rather than from the element id the deck JSON asked for: the first shape +is asked for as `target001` and the package calls it `Rounded Rectangle 1` while +giving it `p:cNvPr/@id="2"`, so the name and the `spid` are two different numbers +and the driver reads both. + +### Running it + +Open the generated deck in PowerPoint. It does **not** have to stay frontmost — a run +drives an occluded window and takes no focus, so keep working while it goes: + +```bash +uv run --with pyobjc-framework-ApplicationServices --with pyobjc-framework-Cocoa \ + --with lxml \ + python scripts/animation_catalog/gui_capture.py \ + --plan /abs/out/plan.json --out /abs/out --document /abs/out/capture-deck.pptx \ + --drive-powerpoint +``` + +Three dependencies, and that is the whole list. **Quartz is not among them** — the only +binding that needed it was the mouse event, which went with the coordinate click. +`lxml` is: the package readers import it lazily inside the function, which keeps `--help` +working with nothing installed, and a run outside this repository's environment then +fails with `ModuleNotFoundError: No module named 'lxml'` at the first attribution unless +the invocation asks for it. + +A line per batch goes to **stderr** while it runs — batch index, targets attempted, +captured so far, elapsed — so a 76-target run is distinguishable from a hang, while +stdout stays pure JSON for the summary. + +**It does not move the pointer**, and it **does not need PowerPoint to be frontmost**. Every action is an `AXPress` or a single `AXSelected` write addressed to a named element, so no mouse event is posted, the pointer is never taken over, and an occluded window is still reached — the operator keeps the keyboard and the screen while a run proceeds. The driver still **refuses to start** unless PowerPoint's document window is the expected capture deck: an `AXPress` goes to whatever window the title resolution found, and the wrong document would mean pressing ribbon controls and `Save` on the operator's own deck. + +Without `--drive-powerpoint` it sends nothing. `--help` and `--emit-record-schema` work with no accessibility bindings installed at all: pyobjc is imported inside the live backend, so importing the module never requires it and `tests/test_animation_gui_capture.py` runs against a fake. + +### What it guarantees, and why each guarantee exists + +- **One shape per target, and every press attributed to its own shape.** A gallery press *replaces* the effect of the **selected shape** rather than adding one, so a target owns a shape rather than a slide. After the press and the save, the slide must have gained at least one effect and **every** new effect's `p:spTgt/@spid` must be the selected shape's `p:cNvPr/@id`. (Not "exactly one": a compound value writes several `p:cTn` nodes, and the stricter form rejected a correctly applied target.) An effect on another shape is a `rejected` record naming **both** spids; a press that added nothing is a recorded failure. This gate is unchanged by the move to the Selection Pane, deliberately — it is what proved the click unreliable, and it is the only thing that makes a capture evidence. +- **Re-read and re-resolve by title before every press.** A press scrolls the gallery and renumbers it; a press aimed by a stale index applies the wrong effect while the record names the right one. Scopes are held as titles, never as elements, and a title matching two controls is a refusal rather than a choice. +- **A failure is recorded and the run continues.** A control that is absent, ambiguous, disabled, a verification that times out, or an effect that cannot be attributed becomes a `rejected` record with its error kind. The 2026-10-31 scripting run lost 357 applied candidates to one bad term because the failure propagated out before the save. +- **Every wait is bounded.** There is one `while True` in the module, inside the bounded poll, and a timeout is a recorded failure rather than a hang. Nothing blocks on the GUI. +- **One Save per batch of targets**, because the save is the measurement: the attribution reads the file Save writes, so there is no switch to skip it and a save that does not land rejects every target pressed into it rather than being a footnote on a passing one. The default batch is 10 and `--batch-size` changes it; `1` is a save per target. Each target is still attributed by **its own** `spid` against the saved package, and the batch adds a gate of its own — **no spid outside the batch may have gained an effect**, which fails the batch naming the stray — while a target whose own spid gained nothing is rejected on its own with the rest of the batch still credited. Each record carries its `batchIndex`, and `effectCount` is then the batch's before/after for the slide while `newEffectCount` is the target's own. + + What batching gives up, stated rather than implied: **crash granularity** (a crash costs the presses since the last save, which a resumed run re-presses because an uncaptured target has no record), and **telling two targets inside one batch apart when they swap effects** — if each gained one effect and nothing outside the batch did, the package cannot say whose value is whose. `--batch-size 1` gives both back. What bounds the second is that the mechanism which used to cause it, a selection that did not take, is caught by `select_shape`'s `AXSelected` read-back *before* any press, and a press landing outside the batch is caught by the stray-spid gate. +- **Cost is a correctness property, and it is measured rather than assumed.** A run of the previous version captured **7 targets in 28 minutes** — about four minutes each, every one correct and attributed. The mechanism worked; it was far too slow to reach 76. Timed live against the real window, best of three: one `find_all_by_title` over the whole window **6.4 s**, `selection_outline` **17.8 s**, walking only the pane's outline (762 nodes) 4.1 s, reading 152 row names 4.3 s. The window is **907 nodes, 762 of them the Selection Pane's rows**, and every accessibility attribute read is an interprocess round trip. + + The dominant cost was full-tree walking, not saving. Every lookup started at the window, so resolving a ribbon control traversed all 762 pane rows and resolving a row traversed the ribbon; and `document_window` identified the ribbon-carrying window by walking **each** of PowerPoint's four or five same-titled windows, from a function nearly every helper calls. Four changes, in descending order of what they were worth: lookups are **scoped to a container** (`Save` in the window's `AXToolbar`, tabs and galleries in the ribbon `AXTabGroup`, rows in the `AXOutline`), found by a search of the window's top levels that **stops at every container boundary** instead of descending through one; `document_window` probes each candidate's direct children; the window and its containers are resolved once per stretch of work and dropped at **every** press, every `AXSelected` write and every poll; and one Save judges a batch. A scope that cannot be identified **raises** — it never widens back to the window, because a lookup that quietly walked everything is exactly what this removed and nobody would look for it again. + + Measured against the test fake, whose pane carries 156 rows and which publishes the same four same-titled sibling windows: **2,218 attribute reads per target, down from 19,826 — 8.9x.** `tests/test_animation_gui_capture.py` counts the reads and budgets them at 3,000 per target, so a lookup that goes back to walking the window fails a test rather than costing an operator an afternoon. + +- **Resumable.** An output directory that already has records skips the targets already captured and retries the ones that failed, restarting at the first uncaptured target whatever the batch boundaries were; `--force` reruns everything. The read-back is rewritten rather than appended to, so there is exactly one record per key. **`--force` wants a freshly generated deck**, because a re-press on a shape that already carries an effect *replaces* it rather than adding one, and the attribution gate requires a new effect — a forced rerun against an already-captured deck is rejected per target rather than credited on the previous run's evidence. + +### Its output feeds `--parse-oracle` + +The driver writes `powerpoint-readback.jsonl` in the shape the generator already consumes — an `{"record": "application"}` first line naming the PowerPoint version and the driver, then one record per target with the catalog key, the slide index, the GUI path applied, the shape name and `spid` it aimed at, the Selection Pane row it selected and that it selected by row rather than by click, the ribbon read-back (`Start:`, `Duration:`) taken while that shape was still the selected one, the `spid` the new effect was attributed to with that effect's own `p:cTn` attributes, how many `p:cTn` nodes appeared on that `spid`, the batch index whose Save judged it with that batch's before/after effect counts, whether it was rejected and any error — and copies the saved deck to `powerpoint-oracle.pptx` beside it, so the two join offline: + +```bash +uv run python scripts/animation_catalog/generate.py --parse-oracle /abs/out +``` + +A GUI record carries `enum: "guiCapture"` with the catalog key as its enumerator, which is what the join is keyed on, and `code: null` — a GUI control has no four-character scripting code and inventing one would assert the very correspondence the capture does not measure. + +That join is **by slide index**, and every target now shares one slide, so the merged view puts the whole slide's OOXML beside every candidate. The per-target evidence is therefore read out of the record rather than out of the join: match a record's `attributedSpid` against the `p:spTgt/@spid` of the effects in the merged `ooxml.timing`, or read its `effectCTn` directly. As with the oracle, nothing in that output is promoted automatically: a maintainer decides, and the catalog entry then names the artefact the claim came from. diff --git a/scripts/animation_catalog/accept.py b/scripts/animation_catalog/accept.py new file mode 100644 index 000000000..46950823c --- /dev/null +++ b/scripts/animation_catalog/accept.py @@ -0,0 +1,1904 @@ +#!/usr/bin/env python3 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 +"""Catalog-derived acceptance harness for PowerPoint animations and transitions. + +This is the REQ-9 release gate. It has two halves and they are deliberately +unequal in size: + +* **The deterministic half runs by default and offline.** It derives the + coverage matrix from the checked-in catalog, writes every accepted catalog + fragment with the real writer, re-imports it with the real reader, checks the + package-validity invariants REQ-6.2 names, and runs the acceptance fixtures in + ``tests/fixtures/animations/manifest.json``. +* **The PowerPoint half runs only with ``--powerpoint``.** It reads an actually + saved package back through Apple Events and detects the repair prompt. This + sandbox cannot drive PowerPoint (Task 1 recorded ``-10004``), so that path is + implemented, strictly non-blocking, and fails fast with remediation text. + It is never approximated and never reported as a pass it did not earn. + +Why the matrix is derived rather than chosen +-------------------------------------------- +REQ-9.2 forbids discretionary "representative" fixtures. Every cell in +``tests/fixtures/animations/coverage-matrix.json`` therefore comes from a rule +applied to the catalog: an axis value exists because the catalog contains it, +and the cell's representative entry is the first one in the catalog's own +preference order (gallery capture, then GUI item, then key). Nobody picks the +interesting ones. ``--write-matrix`` regenerates the file byte-identically from +an unchanged catalog, with no wall-clock timestamp, and ``--all`` fails if the +checked-in matrix has drifted from a fresh derivation. + +Why it exits non-zero today +--------------------------- +The catalog still records mappings whose OOXML form PowerPoint has not been +asked for: 262 capture-required refusals and 71 gallery tiles whose behavior +payload was never captured. The writer refuses them by design rather than +guessing. A harness that printed "OK" while those exist would make the gate +worthless, so every gap is counted, keyed and reported, and the process exits +non-zero while any remains. Zero gaps plus a passing ``--powerpoint`` run is +what closes Task 8. + +Usage +----- +Run from the repository root:: + + uv run python scripts/animation_catalog/accept.py --all + uv run python scripts/animation_catalog/accept.py --all --json + uv run python scripts/animation_catalog/accept.py --write-matrix + +The PowerPoint half, on a machine where PowerPoint is drivable and a human is +watching the screen:: + + uv run python scripts/animation_catalog/accept.py --all --powerpoint + +``--powerpoint`` is itself the consent: nothing in sdpm's runtime, tests or CI +passes it, and no scheduled job may. See ``tests/fixtures/animations/README.md`` +for the operator procedure and what the human has to confirm by eye. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import shutil +import subprocess +import sys +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Iterable, Mapping, Sequence + +from lxml import etree + +REPO_ROOT = Path(__file__).resolve().parents[2] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from sdpm.engine.timing import ( # noqa: E402 (path bootstrap must precede the import) + CATALOG_TARGET_ID, + CapabilityEntry, + CapabilityGapError, + CapabilityIndex, + MotionWriteError, + ShapeIdentityRegistry, + TimingWriter, + catalog_coverage, + coverage_summary, + load_capability_index, + validate_catalog, +) +from sdpm.engine.timing.reader import ( # noqa: E402 + read_slide_motion, + reverse_index, + select_representation, + supported_requires, +) +from sdpm.engine.timing.transition import build_transition # noqa: E402 + +DEFAULT_CATALOG = REPO_ROOT / "sdpm/references/catalogs/powerpoint-animation-catalog.json" +FIXTURE_DIR = REPO_ROOT / "tests/fixtures/animations" +DEFAULT_MATRIX = FIXTURE_DIR / "coverage-matrix.json" +DEFAULT_MANIFEST = FIXTURE_DIR / "manifest.json" +DEFAULT_TEMPLATE = REPO_ROOT / "sdpm/templates/blank-dark.pptx" + +MATRIX_SCHEMA_VERSION = 1 +REPORT_SCHEMA_VERSION = 1 + +P_NS = "http://schemas.openxmlformats.org/presentationml/2006/main" +A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main" +MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006" +R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" +P14_NS = "http://schemas.microsoft.com/office/powerpoint/2010/main" +P15_NS = "http://schemas.microsoft.com/office/powerpoint/2012/main" +P159_NS = "http://schemas.microsoft.com/office/powerpoint/2015/09/main" +#: The prefixes a fixture assertion may use in its XPath. +NS = { + "p": P_NS, + "a": A_NS, + "mc": MC_NS, + "r": R_NS, + "p14": P14_NS, + "p15": P15_NS, + "p159": P159_NS, +} + +#: ``CT_Slide`` child order (ECMA-376 Part 1). ``mc:AlternateContent`` stands in +#: for whichever element it wraps, so it is resolved before the comparison. +SLIDE_CHILD_ORDER = ("cSld", "clrMapOvr", "transition", "timing", "extLst") +#: ``CT_SlideTiming`` child order. +TIMING_CHILD_ORDER = ("tnLst", "bldLst", "extLst") +#: Elements whose ``@spid`` the reader recognises as a shape reference. +SPID_OWNERS = ("spTgt", "bldP", "bldGraphic", "bldDgm", "bldOleChart") + +#: Timing values the writer treats as "nothing to persist". The reader omits +#: them, so normalized equality has to drop them on the expected side too +#: rather than call a neutral default a round-trip loss. +NEUTRAL_TIMING = { + "repeatCount": 1, + "repeatDurationMs": None, + "autoReverse": False, + "acceleration": 0, + "deceleration": 0, + "rewind": False, + "smoothStart": False, + "smoothEnd": False, + "bounceEnd": 0, + "restart": "always", +} + +#: A detached catalog slide: one shape, so every fragment has an ``spid`` to +#: resolve, and a ``p:cSld/p:spTree`` so the reader's identity scan works. +CATALOG_SLIDE_XML = ( + '' + '' + "" % (P_NS, A_NS) +) + +#: Hard ceiling on any Apple Event. A GUI process that does not answer inside +#: this window is treated as unavailable; the harness never waits on a window. +OSASCRIPT_TIMEOUT_SECONDS = 20.0 +POWERPOINT_BUNDLE_ID = "com.microsoft.Powerpoint" +POWERPOINT_APP = Path("/Applications/Microsoft PowerPoint.app") + +APPLE_EVENT_REMEDIATION = ( + "Run this on a logged-in macOS desktop session where Microsoft PowerPoint " + "16.113.1 is installed and the terminal application holds the Automation " + "and Accessibility permissions for it " + "(System Settings -> Privacy & Security -> Automation / Accessibility). " + "A headless, SSH or sandboxed session cannot deliver Apple Events and " + "reports -10004." +) + + +# --------------------------------------------------------------------------- +# Result plumbing +# --------------------------------------------------------------------------- +@dataclass +class Check: + """One named acceptance check and what it proved.""" + + id: str + requirement: str + status: str # "passed" | "failed" | "blockedOnPowerPoint" + detail: str = "" + findings: tuple[str, ...] = () + data: dict[str, Any] = field(default_factory=dict) + + @property + def passed(self) -> bool: + return self.status == "passed" + + def as_json(self) -> dict[str, Any]: + payload: dict[str, Any] = { + "id": self.id, + "requirement": self.requirement, + "status": self.status, + "detail": self.detail, + } + if self.findings: + payload["findings"] = list(self.findings) + if self.data: + payload["data"] = self.data + return payload + + +def _passed(check_id: str, requirement: str, detail: str, **data: Any) -> Check: + return Check(check_id, requirement, "passed", detail, data=data) + + +def _failed(check_id: str, requirement: str, detail: str, findings: Sequence[str], **data: Any) -> Check: + return Check(check_id, requirement, "failed", detail, tuple(findings), data=data) + + +# --------------------------------------------------------------------------- +# Catalog access +# --------------------------------------------------------------------------- +def load_catalog_document(path: Path) -> dict[str, Any]: + """Load and structurally validate the checked-in catalog.""" + return validate_catalog(json.loads(path.read_text(encoding="utf-8"))) + + +def digest(payload: bytes) -> str: + """Return the stable content digest used in every provenance block.""" + return "sha256:" + hashlib.sha256(payload).hexdigest() + + +def repo_path(path: Path) -> str: + """Render a path relative to the repository when it lives inside it.""" + resolved = Path(path).resolve() + try: + return resolved.relative_to(REPO_ROOT).as_posix() + except ValueError: + return resolved.as_posix() + + +def accepted_entries(catalog: Mapping[str, Any]) -> list[tuple[str, Mapping[str, Any]]]: + """Return ``(group, entry)`` for every accepted catalog fragment.""" + rows: list[tuple[str, Mapping[str, Any]]] = [] + for group in ("guiItems", "candidates"): + for entry in catalog.get(group) or (): + if entry.get("status") == "accepted": + rows.append((group, entry)) + return rows + + +def gui_key_of(group: str, entry: Mapping[str, Any]) -> str: + """Return the GUI-surface key an entry belongs to. + + A GUI item *is* its own key; a scripting candidate names the GUI item it was + assigned to. Both sides therefore collapse onto the same family, which is + what lets one axis value own entries from both arrays. + """ + return str(entry["key"] if group == "guiItems" else entry.get("guiKey") or entry["key"]) + + +#: GUI-key segments that name a control group rather than a single value, so the +#: family is three segments deep instead of two. +_DEEP_FAMILIES = frozenset({"gallery", "moreEffects", "effectOptions", "textOptions", "behavior"}) + + +def family_of(group: str, entry: Mapping[str, Any]) -> str: + """Return the catalog-derived family path of one entry.""" + parts = gui_key_of(group, entry).split(".") + if len(parts) >= 3 and parts[1] in _DEEP_FAMILIES: + return ".".join(parts[:3]) + return ".".join(parts[:2]) + + +def preference(group: str, entry: Mapping[str, Any]) -> tuple[int, int, str]: + """Deterministic representative order, mirroring the reader's own rule. + + ``sdpm.engine.timing.reader._preference`` prefers a captured gallery tile + over an enum candidate that merely corroborates the same mapping. Using the + same order here means the matrix names the catalog key that actually owns a + form in both directions, instead of a second key describing it. + """ + ooxml = entry.get("ooxml") or {} + return ( + 0 if "galleryTile" in ooxml else 1, + 0 if group == "guiItems" else 1, + str(entry["key"]), + ) + + +def catalog_establishes_form(entry: Mapping[str, Any]) -> bool: + """True when the catalog establishes an OOXML element form for an entry. + + This is deliberately a property of the *catalog alone* — + ``status == accepted`` with no ``ooxml.gap`` and no ``ooxml.requiresCapture`` + — so the checked-in matrix never encodes writer state and cannot drift when + the writer changes. :class:`CapabilityEntry` owns the rule, so there is one + definition of it rather than a copy. + + Whether the writer can *also* fill in a preset's behavior payload is a + second, finer gate that lives in the writer + (:func:`sdpm.engine.timing.writer.preset_payload_gaps`). The harness + discovers it by running the writer, which is where that truth belongs; the + matrix only records what the catalog itself claims. + """ + probe = CapabilityEntry( + key=str(entry["key"]), + status=str(entry.get("status")), + level=str(entry.get("capabilityLevel") or ""), + ooxml=entry.get("ooxml") or {}, + semantic=entry.get("semanticJson") or {}, + group="guiItems", + ) + return probe.writable + + +# --------------------------------------------------------------------------- +# Coverage matrix derivation +# --------------------------------------------------------------------------- +@dataclass(frozen=True) +class Cell: + """One coverage-matrix cell: an axis value and the entries that own it.""" + + id: str + axis: str + value: str + members: tuple[tuple[str, Mapping[str, Any]], ...] + covered_by: tuple[str, ...] = () + note: str = "" + + def representative(self) -> tuple[str, Mapping[str, Any]] | None: + ordered = sorted(self.members, key=lambda row: preference(*row)) + return ordered[0] if ordered else None + + def established_representative(self) -> tuple[str, Mapping[str, Any]] | None: + """Return the first member whose OOXML form the catalog establishes.""" + ordered = sorted( + (row for row in self.members if catalog_establishes_form(row[1])), + key=lambda row: preference(*row), + ) + return ordered[0] if ordered else None + + def as_json(self) -> dict[str, Any]: + rep = self.representative() + established = self.established_representative() + payload: dict[str, Any] = { + "id": self.id, + "axis": self.axis, + "value": self.value, + "catalogKey": None if rep is None else str(rep[1]["key"]), + "catalogGroup": None if rep is None else rep[0], + "status": "notInCatalog" if rep is None else str(rep[1].get("status")), + "capabilityLevel": None if rep is None else (rep[1].get("capabilityLevel") or None), + "verification": None if rep is None else (rep[1].get("verification") or None), + "members": len(self.members), + "formEstablishedMembers": sum(1 for row in self.members if catalog_establishes_form(row[1])), + "formEstablishedCatalogKey": None if established is None else str(established[1]["key"]), + } + if self.covered_by: + payload["coveredBy"] = list(self.covered_by) + if self.note: + payload["note"] = self.note + return payload + + +def _numeric_paths(catalog: Mapping[str, Any]) -> dict[str, dict[float, list[tuple[str, Mapping[str, Any]]]]]: + """Collect every numeric semantic-JSON path and the values the catalog pins. + + Boundary classes have to come from the catalog too, so the observed value + set *is* the domain: its minimum, its most frequent value and its maximum + are the minimum/normal/maximum classes REQ-9.2 asks for. Where the catalog + pins only one value the three classes collapse onto one fixture, and the + matrix says so rather than implying a range nobody established. + """ + paths: dict[str, dict[float, list[tuple[str, Mapping[str, Any]]]]] = {} + + def walk(node: Any, prefix: str, row: tuple[str, Mapping[str, Any]]) -> None: + if isinstance(node, Mapping): + for key, value in node.items(): + walk(value, f"{prefix}.{key}", row) + elif isinstance(node, list): + for value in node: + walk(value, f"{prefix}[]", row) + elif isinstance(node, (int, float)) and not isinstance(node, bool): + paths.setdefault(prefix.lstrip("."), {}).setdefault(float(node), []).append(row) + + for group, entry in accepted_entries(catalog): + walk(entry.get("semanticJson") or {}, "", (group, entry)) + return paths + + +def _group(rows: Iterable[tuple[str, Mapping[str, Any]]], key: Callable[[str, Mapping[str, Any]], str | None]): + buckets: dict[str, list[tuple[str, Mapping[str, Any]]]] = {} + for group, entry in rows: + value = key(group, entry) + if value is not None: + buckets.setdefault(value, []).append((group, entry)) + return buckets + + +def _first_effect(entry: Mapping[str, Any]) -> Mapping[str, Any] | None: + animations = (entry.get("semanticJson") or {}).get("animations") + if not isinstance(animations, Mapping): + return None + sequence = animations.get("mainSequence") + if isinstance(sequence, list) and sequence and isinstance(sequence[0], Mapping): + return sequence[0] + return None + + +#: Build elements, by the target family they address. +_BUILD_ELEMENT_FAMILIES = { + "p:bldGraphic": "chart", + "p:bldOleChart": "chart", + "p:bldDgm": "smartArt", + "p:bldP": "buildLevel", +} + + +def _target_family(group: str, entry: Mapping[str, Any]) -> str | None: + """Classify an entry by the kind of thing it animates. + + The classification follows what the entry *is about* — its semantic payload + and the build element its OOXML mapping names — not an incidental side + effect. Nearly every gallery tile records ``ooxml.buildList`` because + PowerPoint writes ``p:bldP/@animBg`` beside it, but a tile still animates a + shape; treating that as a paragraph-build target would empty the shape cell + and overfill the build cell. + """ + effect = _first_effect(entry) + if effect is None: + return None + element = str((entry.get("ooxml") or {}).get("element") or "") + target = effect.get("target") or {} + if "chart" in effect or _BUILD_ELEMENT_FAMILIES.get(element) == "chart": + return "chart" + if "smartArt" in effect or _BUILD_ELEMENT_FAMILIES.get(element) == "smartArt": + return "smartArt" + if isinstance(target, Mapping) and "paragraphRange" in target: + return "paragraphRange" + if "text" in effect or _BUILD_ELEMENT_FAMILIES.get(element) == "buildLevel": + return "buildLevel" + preset = effect.get("preset") or {} + if isinstance(preset, Mapping) and preset.get("category") == "media": + return "media" + return "shape" + + +def build_matrix(catalog: Mapping[str, Any], index: CapabilityIndex, *, catalog_digest: str) -> dict[str, Any]: + """Derive the whole coverage matrix from the checked-in catalog.""" + rows = accepted_entries(catalog) + supported = [str(row["requires"]) for row in catalog["alternateContent"].get("supported") or () if row.get("requires")] + + def namespace_value(group: str, entry: Mapping[str, Any]) -> str: + ooxml = entry.get("ooxml") or {} + if not ooxml.get("alternateContent"): + return "direct" + requires = ooxml.get("requires") + return f"choice:{requires}" if requires in supported else "choice:standard" + + def fallback_value(group: str, entry: Mapping[str, Any]) -> str | None: + ooxml = entry.get("ooxml") or {} + if not ooxml.get("alternateContent") or not ooxml.get("fallbackElement"): + return None + requires = ooxml.get("requires") + return f"fallback:{requires}" if requires in supported else "fallback:standard" + + def transition_effect(group: str, entry: Mapping[str, Any]) -> str | None: + transition = (entry.get("semanticJson") or {}).get("transition") + return str(transition["effect"]) if isinstance(transition, Mapping) else None + + def transition_parameters(group: str, entry: Mapping[str, Any]) -> str | None: + transition = (entry.get("semanticJson") or {}).get("transition") + if not isinstance(transition, Mapping): + return None + keys = sorted(transition.get("parameters") or {}) + return "+".join(keys) if keys else "none" + + def animation_category(group: str, entry: Mapping[str, Any]) -> str | None: + effect = _first_effect(entry) + if effect is None: + return None + preset = effect.get("preset") + if isinstance(preset, Mapping): + return str(preset.get("category")) + return "custom" if "behaviors" in effect else None + + def animation_variant(group: str, entry: Mapping[str, Any]) -> str | None: + effect = _first_effect(entry) + if effect is None: + return None + preset = effect.get("preset") + if not isinstance(preset, Mapping): + return None + options = preset.get("options") + if isinstance(options, Mapping) and options: + return ",".join(f"{setting}={value}" for setting, value in sorted(options.items())) + return "none" + + cells: list[Cell] = [] + + def add(axis: str, buckets: Mapping[str, list[tuple[str, Mapping[str, Any]]]]) -> None: + for value in sorted(buckets): + cells.append(Cell(f"{axis}:{value}", axis, value, tuple(buckets[value]))) + + add("mapping", _group(rows, lambda g, e: str((e.get("ooxml") or {}).get("strategy") or "") or None)) + add("namespace", _group(rows, namespace_value)) + add("namespace", _group(rows, fallback_value)) + add("animationCategory", _group(rows, animation_category)) + add("animationFamily", _group(rows, lambda g, e: family_of(g, e) if gui_key_of(g, e).startswith("animation.") else None)) + add("transitionEffect", _group(rows, transition_effect)) + add("transitionParameters", _group(rows, transition_parameters)) + add("animationVariant", _group(rows, animation_variant)) + add("targetFamily", _group(rows, _target_family)) + + # The placeholder target family is a builder distinction, not a catalog + # one: every catalog fragment animates the same synthetic shape. The axis + # value still has to exist, so it is declared here with no catalog key and + # an explicit owning fixture instead of being quietly dropped. + cells.append( + Cell( + "targetFamily:placeholder", + "targetFamily", + "placeholder", + (), + covered_by=("fixture:placeholder-target",), + note=( + "the catalog's fragments all animate one synthetic shape, so no catalog entry " + "distinguishes a layout placeholder; the acceptance fixture does" + ), + ) + ) + + for path, values in sorted(_numeric_paths(catalog).items()): + ordered = sorted(values) + modal = max(ordered, key=lambda value: (len(values[value]), -value)) + classes = {"minimum": ordered[0], "normal": modal, "maximum": ordered[-1]} + for boundary, value in classes.items(): + rendered = int(value) if float(value).is_integer() else value + cells.append( + Cell( + f"boundary:{path}:{boundary}", + "boundary", + f"{path}:{boundary}", + tuple(values[value]), + note=( + f"catalog-pinned value {rendered}; the catalog establishes " + f"{len(ordered)} distinct value(s) for this path" + ), + ) + ) + + axes: dict[str, int] = {} + for cell in cells: + axes[cell.axis] = axes.get(cell.axis, 0) + 1 + + return { + "schemaVersion": MATRIX_SCHEMA_VERSION, + "derivation": { + "rule": ( + "every cell is produced by a rule applied to the checked-in catalog; no entry is " + "selected by hand (REQ-9.2). An axis value exists because the catalog contains it, " + "and each cell's representative is the first member in the catalog's own preference " + "order (captured gallery tile, then GUI item, then key)." + ), + "representativeOrder": ["galleryTileCaptured", "guiItemBeforeCandidate", "keyAscending"], + "formEstablished": ( + "catalog-derived: accepted status with no ooxml.gap and no ooxml.requiresCapture. It " + "records what the catalog itself claims and never encodes writer state, so this file " + "cannot drift when the writer changes. Whether a preset's behavior payload is also " + "captured is a finer gate the harness discovers by running the writer." + ), + "boundaryClasses": ( + "minimum and maximum are the smallest and largest value the catalog pins for a " + "numeric semantic-JSON path; normal is the most frequently pinned value, ties " + "resolved to the smaller. A path with one pinned value collapses all three classes " + "onto one fixture and says so in the cell note." + ), + "reproducible": ( + "derived only from the catalog bytes named below, with no wall-clock timestamp, so " + "two runs over an unchanged catalog are byte-identical." + ), + }, + "source": { + "catalog": repo_path(DEFAULT_CATALOG), + "catalogDigest": catalog_digest, + "catalogGeneratedAt": catalog["baseline"]["generatedAt"], + "guiManifest": catalog["baseline"]["guiManifest"], + "baseline": { + "application": catalog["baseline"]["application"], + "version": catalog["baseline"]["version"], + "platform": catalog["baseline"]["platform"], + }, + "supportedChoiceRequires": supported, + "acceptedEntries": len(rows), + }, + "axes": {name: axes[name] for name in sorted(axes)}, + "cellCount": len(cells), + "cells": [cell.as_json() for cell in sorted(cells, key=lambda cell: (cell.axis, cell.value))], + } + + +def dump_matrix(matrix: Mapping[str, Any]) -> str: + """Serialize the matrix deterministically.""" + return json.dumps(matrix, indent=2, ensure_ascii=False, sort_keys=False) + "\n" + + +def matrix_cells(matrix: Mapping[str, Any], index: CapabilityIndex, catalog: Mapping[str, Any]) -> list[Cell]: + """Rebuild :class:`Cell` objects for a matrix document, for walking.""" + by_key = {str(entry["key"]): (group, entry) for group, entry in accepted_entries(catalog)} + cells: list[Cell] = [] + for raw in matrix.get("cells") or (): + members: list[tuple[str, Mapping[str, Any]]] = [] + for name in (raw.get("catalogKey"), raw.get("formEstablishedCatalogKey")): + if name and name in by_key and by_key[name] not in members: + members.append(by_key[name]) + cells.append( + Cell( + str(raw["id"]), + str(raw["axis"]), + str(raw["value"]), + tuple(members), + covered_by=tuple(raw.get("coveredBy") or ()), + note=str(raw.get("note") or ""), + ) + ) + return cells + + +# --------------------------------------------------------------------------- +# Normalization +# --------------------------------------------------------------------------- +def normalize(value: Any) -> Any: + """Drop nulls and sort keys so two semantic trees compare structurally.""" + if isinstance(value, Mapping): + return {key: normalize(item) for key, item in sorted(value.items()) if item is not None} + if isinstance(value, list): + return [normalize(item) for item in value] + return value + + +def normalize_effect(effect: Mapping[str, Any]) -> dict[str, Any]: + """Normalize one animation effect for equality. + + Timing values the writer persists nothing for are removed from both sides: + the reader cannot invent ``autoReverse: false`` from XML that never carried + it, and calling that a round-trip loss would be noise. Everything else is + compared as written. + """ + pruned = dict(effect) + timing = { + key: item + for key, item in (effect.get("timing") or {}).items() + if not (key in NEUTRAL_TIMING and item == NEUTRAL_TIMING[key]) + } + pruned["timing"] = timing + return normalize(pruned) + + +def interactive_diff(expected: Mapping[str, Any], motion: Any) -> list[str]: + """Return where one written interactive sequence and the re-import disagree. + + An interactive sequence is a trigger plus its effects, so both halves are + compared: a reader that recovered the effects but lost the shape the click + is bound to has not round-tripped the sequence. + """ + read = (getattr(motion, "animations", None) or {}).get("interactiveSequences") or [] + if not read: + return ["interactiveSequences: wrote 1, read none"] + actual = read[0] + findings: list[str] = [] + want_trigger = expected.get("trigger") or {} + got_trigger = actual.get("trigger") or {} + for name in sorted(set(want_trigger) | set(got_trigger)): + if want_trigger.get(name) != got_trigger.get(name): + findings.append( + f"trigger.{name}: wrote {want_trigger.get(name)!r}, read {got_trigger.get(name)!r}" + ) + want_effects = expected.get("effects") or [] + got_effects = actual.get("effects") or [] + if len(want_effects) != len(got_effects): + findings.append(f"effects: wrote {len(want_effects)}, read {len(got_effects)}") + elif want_effects: + findings.extend(effect_diff(want_effects[0], got_effects[0])) + return findings + + +def effect_diff(expected: Mapping[str, Any], actual: Mapping[str, Any]) -> list[str]: + """Return the JSON paths where two normalized effects disagree.""" + left, right = normalize_effect(expected), normalize_effect(actual) + findings: list[str] = [] + for key in sorted(set(left) | set(right)): + if left.get(key) == right.get(key): + continue + if key == "timing": + for inner in sorted(set(left.get("timing", {})) | set(right.get("timing", {}))): + if left.get("timing", {}).get(inner) != right.get("timing", {}).get(inner): + findings.append( + f"timing.{inner}: wrote {left.get('timing', {}).get(inner)!r}, " + f"read {right.get('timing', {}).get(inner)!r}" + ) + else: + findings.append(f"{key}: wrote {left.get(key)!r}, read {right.get(key)!r}") + return findings + + +# --------------------------------------------------------------------------- +# Package-validity invariants (REQ-6.2) +# --------------------------------------------------------------------------- +def _local(node: etree._Element) -> str: + return etree.QName(node).localname + + +def active_branch(node: etree._Element) -> etree._Element: + """Return the branch a conforming consumer actually applies. + + Uniqueness and ordering hold *within one active timing branch*: an + ``mc:Fallback`` legitimately repeats the IDs of the Choice it replaces, + because only one of them is ever live. + """ + if _local(node) != "AlternateContent": + return node + for child in node: + if isinstance(child.tag, str) and _local(child) == "Choice": + return child + return node + + +def timing_findings(fragment: etree._Element, *, known_spids: Sequence[int], what: str) -> list[str]: + """Check unique cTn IDs, schema child order, spid validity and rIds.""" + findings: list[str] = [] + branch = active_branch(fragment) + + ids = branch.xpath(".//p:cTn/@id", namespaces=NS) + duplicates = sorted({value for value in ids if ids.count(value) > 1}) + if duplicates: + findings.append(f"{what}: duplicate p:cTn/@id in the active branch: {duplicates}") + if not ids: + findings.append(f"{what}: the timing tree carries no p:cTn") + non_numeric = [value for value in ids if not str(value).isdigit()] + if non_numeric: + findings.append(f"{what}: non-numeric p:cTn/@id {non_numeric}") + + for timing in branch.iter(f"{{{P_NS}}}timing"): + order = [_local(child) for child in timing if isinstance(child.tag, str)] + ranks = [TIMING_CHILD_ORDER.index(name) for name in order if name in TIMING_CHILD_ORDER] + unknown = [name for name in order if name not in TIMING_CHILD_ORDER] + if unknown: + findings.append(f"{what}: p:timing carries unexpected children {unknown}") + if ranks != sorted(ranks): + findings.append(f"{what}: p:timing children are out of schema order: {order}") + if not timing.xpath("./p:tnLst/p:par/p:cTn[@nodeType='tmRoot']", namespaces=NS): + findings.append(f"{what}: p:timing has no p:cTn[@nodeType='tmRoot']") + + allowed = set(known_spids) + for owner in SPID_OWNERS: + for value in branch.xpath(f".//p:{owner}/@spid", namespaces=NS): + if not str(value).isdigit(): + findings.append(f"{what}: p:{owner}/@spid {value!r} is not a shape id") + elif int(value) not in allowed: + findings.append(f"{what}: p:{owner}/@spid {value} resolves to no shape in the slide") + + for node in branch.iter(): + if not isinstance(node.tag, str): + continue + for name, value in node.attrib.items(): + if name.startswith(f"{{{R_NS}}}") and not str(value).startswith("rId"): + findings.append(f"{what}: {_local(node)} carries a malformed relationship id {value!r}") + return findings + + +def transition_findings(node: etree._Element, entry: Mapping[str, Any], *, what: str) -> list[str]: + """Check the direct and AlternateContent transition forms.""" + findings: list[str] = [] + ooxml = entry.get("ooxml") or {} + wrapped = _local(node) == "AlternateContent" + if bool(ooxml.get("alternateContent")) and not wrapped and ooxml.get("requires"): + findings.append(f"{what}: catalog requires {ooxml['requires']!r} but the writer emitted a direct p:transition") + if not wrapped: + if _local(node) != "transition": + findings.append(f"{what}: expected p:transition, got {_local(node)}") + return findings + + choices = node.findall(f"{{{MC_NS}}}Choice") + fallbacks = node.findall(f"{{{MC_NS}}}Fallback") + if not choices: + findings.append(f"{what}: mc:AlternateContent has no mc:Choice") + for choice in choices: + if not (choice.get("Requires") or "").split(): + findings.append(f"{what}: mc:Choice without @Requires") + if not choice.xpath("./p:transition", namespaces=NS): + findings.append(f"{what}: mc:Choice carries no p:transition") + expected_fallback = ooxml.get("fallbackElement") + if expected_fallback: + if len(fallbacks) != 1: + findings.append(f"{what}: expected exactly one mc:Fallback, found {len(fallbacks)}") + else: + payload = [ + f"p:{_local(child)}" + for transition in fallbacks[0].xpath("./p:transition", namespaces=NS) + for child in transition + if isinstance(child.tag, str) + ] + if not fallbacks[0].xpath("./p:transition", namespaces=NS): + findings.append(f"{what}: mc:Fallback carries no p:transition") + elif payload and expected_fallback not in payload: + findings.append( + f"{what}: mc:Fallback payload {payload} does not carry the catalog's " + f"fallbackElement {expected_fallback!r}" + ) + return findings + + +def slide_order_findings(slide: etree._Element, *, what: str) -> list[str]: + """Check CT_Slide child order, resolving AlternateContent to its payload.""" + ranks: list[int] = [] + order: list[str] = [] + for child in slide: + if not isinstance(child.tag, str): + continue + name = _local(child) + if name == "AlternateContent": + payload = { + _local(inner) + for branch in child + for inner in branch + if isinstance(inner.tag, str) + } + name = next((item for item in SLIDE_CHILD_ORDER if item in payload), name) + order.append(name) + if name in SLIDE_CHILD_ORDER: + ranks.append(SLIDE_CHILD_ORDER.index(name)) + if ranks != sorted(ranks): + return [f"{what}: slide children are out of CT_Slide order: {order}"] + return [] + + +# --------------------------------------------------------------------------- +# Catalog slide helpers +# --------------------------------------------------------------------------- +def catalog_slide() -> tuple[etree._Element, ShapeIdentityRegistry, list[int]]: + """Return a detached catalog slide, its registry and its shape ids.""" + slide = etree.fromstring(CATALOG_SLIDE_XML) + shape = slide.find(f"{{{P_NS}}}cSld/{{{P_NS}}}spTree/{{{P_NS}}}sp") + registry = ShapeIdentityRegistry("catalog") + registry.register(CATALOG_TARGET_ID, [shape], source_path="catalog") + spids = [int(value) for value in slide.xpath(".//p:cNvPr/@id", namespaces=NS)] + return slide, registry, spids + + +@dataclass +class EntryOutcome: + """What one accepted catalog entry did through writer and reader.""" + + key: str + group: str + kind: str + outcome: str # "generated" | "refused" | "error" + reversible: bool = False + equal: bool = False + gap: str = "" + elements: tuple[str, ...] = () + findings: tuple[str, ...] = () + diff: tuple[str, ...] = () + + +def walk_entry( + group: str, + entry: Mapping[str, Any], + *, + index: CapabilityIndex, + reversible_transitions: Mapping[str, Any], + reversible_presets: Mapping[str, Any], +) -> EntryOutcome: + """Write one catalog entry, re-import it, and record exactly what happened.""" + key = str(entry["key"]) + semantic = entry.get("semanticJson") or {} + transition = semantic.get("transition") + kind = "transition" if isinstance(transition, Mapping) else "animation" + slide, registry, spids = catalog_slide() + try: + if kind == "transition": + node, _report = build_transition(transition, index=index, slide_slug="catalog") + else: + node = TimingWriter(registry, index=index, slide_slug="catalog").build(semantic.get("animations")) + except CapabilityGapError as error: + return EntryOutcome(key, group, kind, "refused", gap=str(error), elements=tuple(error.elements)) + except MotionWriteError as error: + return EntryOutcome(key, group, kind, "error", findings=(str(error),)) + + slide.append(node) + findings: list[str] = list(slide_order_findings(slide, what=key)) + if kind == "transition": + findings += transition_findings(node, entry, what=key) + else: + findings += timing_findings(node, known_spids=spids, what=key) + + outcome = EntryOutcome(key, group, kind, "generated", findings=tuple(findings)) + try: + motion = read_slide_motion(slide, slide_slug="catalog", index=index) + except Exception as error: # noqa: BLE001 - any reader failure is a finding, not a crash + outcome.findings = outcome.findings + (f"{key}: the reader raised {type(error).__name__}: {error}",) + return outcome + + # Reversibility is **measured**, not looked up. It used to be membership in + # the reader's reverse index, and that index maps each OOXML form to exactly + # one preferred key — so every other key describing the same form was + # counted one-way even when its own example round-tripped perfectly. 143 of + # the 210 did. The property that matters is `JSON -> PPTX -> the same JSON`, + # and which catalog key the reader resolved on the way is not part of it. + if kind == "transition": + expected, actual = normalize(transition), normalize(motion.transition or {}) + outcome.equal = expected == actual + outcome.reversible = outcome.equal or key in reversible_transitions + if outcome.reversible and not outcome.equal: + outcome.diff = (f"transition: wrote {expected!r}, read {actual!r}",) + return outcome + + written_animations = semantic.get("animations") or {} + written_sequence = written_animations.get("mainSequence") or [] + written_interactive = written_animations.get("interactiveSequences") or [] + if not written_sequence and written_interactive: + # An interactive sequence animates something, and comparing only + # `mainSequence` said otherwise. Four entries — the shape-click + # trigger, its target, the interactive sequence itself and the + # scripting enumerator for it — were counted one-way because their + # examples put the effect here and nothing ever looked. + outcome.diff = tuple(interactive_diff(written_interactive[0], motion)) + outcome.equal = not outcome.diff + outcome.reversible = outcome.equal or key in reversible_presets + return outcome + if not written_sequence: + # An entry whose example animates nothing — a pane-ordering record. + # There is no effect to compare, so reversibility stays whatever the + # index says. + outcome.reversible = key in reversible_presets + return outcome + expected_effect = written_sequence[0] + read_sequence = (motion.animations or {}).get("mainSequence") or [] + if not read_sequence: + # Nothing came back, so there is nothing to compare. Claimed reversible + # only if the index says this key is the form's inverse target, which + # makes the empty read a reportable failure rather than a silent pass. + outcome.reversible = key in reversible_presets + if outcome.reversible: + outcome.diff = (f"{key}: the reader returned no mainSequence effect",) + return outcome + diff = effect_diff(expected_effect, read_sequence[0]) + outcome.equal = not diff + outcome.reversible = outcome.equal or key in reversible_presets + outcome.diff = tuple(diff) + return outcome + + +# --------------------------------------------------------------------------- +# Acceptance fixtures +# --------------------------------------------------------------------------- +def load_fixture_manifest(path: Path) -> dict[str, Any]: + """Load the acceptance fixture index.""" + manifest = json.loads(path.read_text(encoding="utf-8")) + if manifest.get("schemaVersion") != 1: + raise ValueError(f"{path}: schemaVersion must be 1") + if not isinstance(manifest.get("packages"), list) or not manifest["packages"]: + raise ValueError(f"{path}: packages must be a non-empty array") + seen: set[str] = set() + for package in manifest["packages"]: + for required in ("id", "purpose", "requirement", "deck", "slides", "covers", "proves", "powerPointReadBack"): + if required not in package: + raise ValueError(f"{path}: package {package.get('id')!r} is missing {required!r}") + if package["id"] in seen: + raise ValueError(f"{path}: duplicate package id {package['id']!r}") + seen.add(package["id"]) + return manifest + + +def build_fixture_package(package: Mapping[str, Any], out_dir: Path, *, template: Path) -> Path: + """Build one acceptance fixture into a real .pptx on disk.""" + from sdpm.engine.builder import PPTXBuilder + + media_dir = out_dir / f"{package['id']}-media" + media_dir.mkdir(parents=True, exist_ok=True) + for name in package.get("media") or (): + # A tiny but structurally plausible MP4 header: python-pptx only needs + # bytes plus a content type to create the media part and its timing. + (media_dir / name).write_bytes(b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 128) + + deck = package["deck"] + builder = PPTXBuilder( + template, + fonts={"fullwidth": "Meiryo", "halfwidth": "Arial"}, + default_text_color="#FFFFFF", + base_dir=media_dir, + animations_enabled=bool(deck.get("animations", {}).get("enabled", False)), + transitions_enabled=bool(deck.get("transitions", {}).get("enabled", False)), + ) + for slide_def in package["slides"]: + builder.add_slide(slide_def) + target = out_dir / f"{package['id']}.pptx" + builder.prs.save(str(target)) + return target + + +def fixture_slides(path: Path) -> list[etree._Element]: + """Return the slide XML of a built package, in slide order.""" + from pptx import Presentation + + presentation = Presentation(str(path)) + return [etree.fromstring(etree.tostring(slide._element)) for slide in presentation.slides] + + +def _timing_nodes(slide: etree._Element) -> list[etree._Element]: + return [ + child + for child in slide + if isinstance(child.tag, str) + and ( + _local(child) == "timing" + or ( + _local(child) == "AlternateContent" + and child.xpath(".//p:timing", namespaces=NS) + ) + ) + ] + + +def check_fixture( + package: Mapping[str, Any], + path: Path, + *, + index: CapabilityIndex, +) -> Check: + """Run one acceptance fixture's offline assertions.""" + findings: list[str] = [] + slides = fixture_slides(path) + expected = package.get("slideCount") + if expected is not None and len(slides) != expected: + findings.append(f"expected {expected} slides, built {len(slides)}") + + supported = supported_requires(index) + observations: dict[str, Any] = {"slides": len(slides), "package": path.name} + + for position, slide in enumerate(slides, start=1): + label = f"{package['id']} slide {position}" + findings += slide_order_findings(slide, what=label) + timings = _timing_nodes(slide) + if len(timings) > 1: + findings.append(f"{label}: {len(timings)} timing representations (python-pptx issue 954)") + spids = [int(value) for value in slide.xpath(".//p:cNvPr/@id", namespaces=NS)] + for timing in timings: + findings += timing_findings(timing, known_spids=spids, what=label) + try: + select_representation(slide, "timing", supported=supported) + select_representation(slide, "transition", supported=supported) + except Exception as error: # noqa: BLE001 + findings.append(f"{label}: representation selection failed: {error}") + + for name, assertion in (package.get("assert") or {}).items(): + findings += run_fixture_assertion(name, assertion, slides, observations, label=package["id"]) + + if findings: + return _failed( + f"fixture:{package['id']}", + package["requirement"], + package["purpose"], + findings, + **observations, + ) + return _passed(f"fixture:{package['id']}", package["requirement"], package["purpose"], **observations) + + +def run_fixture_assertion( + name: str, + assertion: Mapping[str, Any], + slides: Sequence[etree._Element], + observations: dict[str, Any], + *, + label: str, +) -> list[str]: + """Evaluate one declarative assertion from the fixture manifest. + + Assertions are data in ``manifest.json`` rather than code here, so adding a + fixture does not mean editing the harness. Each one is an XPath plus the + count the fixture claims; an unknown assertion kind is a failure, never a + silent skip. + """ + index = assertion.get("slide") + targets = slides if index is None else ([slides[index - 1]] if 0 < index <= len(slides) else []) + if index is not None and not targets: + return [f"{label}/{name}: slide {index} does not exist"] + + found = 0 + for slide in targets: + try: + found += len(slide.xpath(assertion["xpath"], namespaces=NS)) + except etree.XPathError as error: + return [f"{label}/{name}: invalid xpath: {error}"] + observations.setdefault("assertions", {})[name] = found + + if "count" in assertion: + if found != assertion["count"]: + return [f"{label}/{name}: expected {assertion['count']} node(s), found {found} ({assertion['xpath']})"] + return [] + if "minimum" in assertion: + if found < assertion["minimum"]: + return [f"{label}/{name}: expected at least {assertion['minimum']} node(s), found {found}"] + return [] + return [f"{label}/{name}: assertion declares neither 'count' nor 'minimum'"] + + +def check_identical_timing(packages: Mapping[str, Path], pair: Mapping[str, Any]) -> Check: + """Prove that switching one feature off leaves the other's XML untouched.""" + left, right = pair["packages"] + missing = [name for name in (left, right) if name not in packages] + if missing: + return _failed( + f"invariant:{pair['id']}", + pair["requirement"], + pair["purpose"], + [f"fixture package(s) not built: {missing}"], + ) + + def canonical(path: Path) -> list[bytes]: + # A detached subtree inherits its namespace declarations from an + # ancestor lxml no longer has, and c14n2 refuses an undeclared prefix. + # Round-tripping through tostring materializes the declarations. + return [ + etree.tostring(etree.fromstring(etree.tostring(node)), method="c14n2") + for slide in fixture_slides(path) + for node in _timing_nodes(slide) + ] + + before, after = canonical(packages[left]), canonical(packages[right]) + if before != after: + return _failed( + f"invariant:{pair['id']}", + pair["requirement"], + pair["purpose"], + [ + f"{left} produced {len(before)} timing representation(s) and {right} produced " + f"{len(after)}; the canonical XML differs, so turning the feature off changed timing" + ], + ) + return _passed( + f"invariant:{pair['id']}", + pair["requirement"], + pair["purpose"], + timingRepresentations=len(before), + ) + + +# --------------------------------------------------------------------------- +# PowerPoint oracle path +# --------------------------------------------------------------------------- +def osascript(script: str) -> tuple[int, str, str]: + """Run one AppleScript with a hard timeout and no GUI wait. + + ``open -W`` and any other indefinite wait on a GUI process are forbidden + (notes.md, 2026-10-30 23:49): a blocked tool call is not a verification + result. Everything here is bounded, and a timeout is reported as a timeout. + """ + binary = shutil.which("osascript") + if binary is None: + return (127, "", "osascript is not on PATH") + try: + completed = subprocess.run( # noqa: S603 - fixed binary, no shell, bounded + [binary, "-e", script], + capture_output=True, + text=True, + timeout=OSASCRIPT_TIMEOUT_SECONDS, + check=False, + ) + except subprocess.TimeoutExpired: + return ( + 124, + "", + f"no reply within {OSASCRIPT_TIMEOUT_SECONDS:g}s; a modal dialog (for example the " + "file-repair prompt) is the usual cause", + ) + except OSError as error: + return (126, "", f"cannot launch osascript: {error}") + return (completed.returncode, completed.stdout.strip(), completed.stderr.strip()) + + +def is_privilege_violation(detail: str) -> bool: + """True when a failure is the sandbox refusing the Apple Event itself.""" + return "-10004" in detail or "privilege violation" in detail.lower() + + +def powerpoint_availability() -> dict[str, Any]: + """Decide, without blocking, whether Apple Events can drive PowerPoint. + + The probe is deliberately a *document-model* event. ``get version`` is + answered out of the application registry and succeeds even where every + useful event is refused — this host answers ``get version`` with 16.113.1 + and then fails ``count of documents`` with -10004. Probing the shallow + property would report "available" and turn every read-back into a spurious + failure, which is exactly the false result this harness must not produce. + ``count of documents`` is read-only, opens no window and needs the same + privilege the read-back needs. + """ + if sys.platform != "darwin": + return { + "available": False, + "reason": f"platform {sys.platform!r} has no Apple Events", + "remediation": APPLE_EVENT_REMEDIATION, + } + if not POWERPOINT_APP.exists(): + return { + "available": False, + "reason": f"{POWERPOINT_APP} is not installed", + "remediation": APPLE_EVENT_REMEDIATION, + } + version_code, version_out, _ = osascript(f'tell application id "{POWERPOINT_BUNDLE_ID}" to get version') + version = version_out if version_code == 0 else "" + code, _out, err = osascript(f'tell application id "{POWERPOINT_BUNDLE_ID}" to count of documents') + if code == 0: + return {"available": True, "reason": "", "version": version, "probe": "count of documents"} + detail = err or f"osascript exited {code}" + if is_privilege_violation(detail): + detail = ( + "PowerPoint answers static properties" + + (f" (version {version})" if version else "") + + " but refuses every document-model Apple Event with -10004 (privilege violation), so " + "this session cannot open or read back a package" + ) + return { + "available": False, + "reason": detail, + "remediation": APPLE_EVENT_REMEDIATION, + "version": version, + "probe": "count of documents", + } + + +def powerpoint_read_back(packages: Mapping[str, Path], manifest: Mapping[str, Any]) -> tuple[dict[str, Any], list[Check]]: + """Run the PowerPoint half: open a saved package, read it back, close it. + + Nothing here is simulated. When Apple Events are unavailable the function + returns the reason and every read-back check is reported as + ``blockedOnPowerPoint`` — an explicit, counted gap, not a pass. + """ + availability = powerpoint_availability() + report: dict[str, Any] = {"attempted": True, **availability, "readBack": []} + checks: list[Check] = [] + expected = [ + package + for package in manifest["packages"] + if package.get("powerPointReadBack", {}).get("required") + ] + + if not availability["available"]: + for package in expected: + checks.append( + Check( + f"powerpoint:{package['id']}", + package["requirement"], + "blockedOnPowerPoint", + package["powerPointReadBack"]["expect"], + (availability["reason"],), + {"package": package["id"], "remediation": availability.get("remediation", "")}, + ) + ) + return report, checks + + for package in expected: + path = packages.get(package["id"]) + if path is None: + checks.append( + _failed( + f"powerpoint:{package['id']}", + package["requirement"], + package["powerPointReadBack"]["expect"], + ["the fixture package was not built"], + ) + ) + continue + code, out, err = osascript(_read_back_script(path)) + entry = {"package": package["id"], "exit": code, "stdout": out, "stderr": err} + report["readBack"].append(entry) + if code == 124: + # A dialog is the only thing that holds an Apple Event open this + # long, and the repair prompt is the dialog REQ-9.3 forbids. + checks.append( + _failed( + f"powerpoint:{package['id']}", + package["requirement"], + package["powerPointReadBack"]["expect"], + [f"repair prompt suspected: {err}"], + repairPromptSuspected=True, + ) + ) + continue + if code != 0: + detail = err or f"osascript exited {code}" + if is_privilege_violation(detail): + # The sandbox refused the event. That is an environment block, + # not evidence about the package, and must never be recorded as + # a package failure. + checks.append( + Check( + f"powerpoint:{package['id']}", + package["requirement"], + "blockedOnPowerPoint", + package["powerPointReadBack"]["expect"], + (detail,), + {"package": package["id"], "remediation": APPLE_EVENT_REMEDIATION}, + ) + ) + else: + checks.append( + _failed( + f"powerpoint:{package['id']}", + package["requirement"], + package["powerPointReadBack"]["expect"], + [detail], + ) + ) + continue + observed = [piece.strip() for piece in out.split("\x1f") if piece.strip()] + wanted = list(package["powerPointReadBack"].get("transitions") or ()) + if wanted and observed != wanted: + checks.append( + _failed( + f"powerpoint:{package['id']}", + package["requirement"], + package["powerPointReadBack"]["expect"], + [f"read back {observed}, expected {wanted}"], + ) + ) + continue + checks.append( + Check( + f"powerpoint:{package['id']}", + package["requirement"], + "passed" if not package["powerPointReadBack"].get("humanConfirms") else "blockedOnPowerPoint", + package["powerPointReadBack"]["expect"], + () + if not package["powerPointReadBack"].get("humanConfirms") + else ( + "the remaining claim is visual and only a human watching playback can confirm it: " + + "; ".join(package["powerPointReadBack"]["humanConfirms"]), + ), + {"package": package["id"], "transitions": observed}, + ) + ) + return report, checks + + +def _read_back_script(path: Path) -> str: + """Return the AppleScript that opens, reads back and closes one package. + + It never activates PowerPoint, never saves, and closes without saving, so a + read-back cannot mutate the fixture. The unit separator joins the per-slide + values because AppleScript list text is locale-dependent. + """ + quoted = str(path).replace("\\", "\\\\").replace('"', '\\"') + return ( + f'tell application id "{POWERPOINT_BUNDLE_ID}"\n' + f' set theDoc to open "{quoted}"\n' + " set readings to {}\n" + " repeat with theSlide in (slides of theDoc)\n" + " set end of readings to (entry effect of slide show transition of theSlide) as text\n" + " end repeat\n" + ' set AppleScript\'s text item delimiters to (ASCII character 31)\n' + " set result to readings as text\n" + " close theDoc saving no\n" + " return result\n" + "end tell" + ) + + +# --------------------------------------------------------------------------- +# The run +# --------------------------------------------------------------------------- +def run_acceptance( + *, + catalog_path: Path, + matrix_path: Path, + manifest_path: Path, + template: Path, + use_powerpoint: bool, + out_dir: Path | None, +) -> dict[str, Any]: + """Run the deterministic half, optionally the PowerPoint half, and report.""" + catalog_bytes = catalog_path.read_bytes() + catalog = load_catalog_document(catalog_path) + catalog_digest = digest(catalog_bytes) + index = load_capability_index(catalog_path) + checks: list[Check] = [] + + # --- the matrix is derived, and the checked-in copy must match --------- + derived = build_matrix(catalog, index, catalog_digest=catalog_digest) + derived_text = dump_matrix(derived) + if matrix_path.exists(): + checked_in = matrix_path.read_text(encoding="utf-8") + if checked_in == derived_text: + checks.append( + _passed( + "matrix:derivation", + "REQ-9.2", + "the checked-in coverage matrix is byte-identical to a fresh derivation from the catalog", + cells=derived["cellCount"], + ) + ) + else: + checks.append( + _failed( + "matrix:derivation", + "REQ-9.2", + "the checked-in coverage matrix has drifted from the catalog", + ["run: uv run python scripts/animation_catalog/accept.py --write-matrix"], + ) + ) + matrix = json.loads(checked_in) + else: + checks.append( + _failed( + "matrix:derivation", + "REQ-9.2", + "the coverage matrix is missing", + [f"{matrix_path} does not exist; run --write-matrix"], + ) + ) + matrix = derived + + # --- every accepted catalog entry, through writer and reader ----------- + reverse = reverse_index(index) + reversible_transitions = {entry.key: entry for entry in reverse.transitions.values()} + reversible_presets = {entry.key: entry for entry in reverse.presets.values()} + outcomes: dict[str, EntryOutcome] = {} + for group, entry in accepted_entries(catalog): + outcomes[str(entry["key"])] = walk_entry( + group, + entry, + index=index, + reversible_transitions=reversible_transitions, + reversible_presets=reversible_presets, + ) + + structural = [finding for outcome in outcomes.values() for finding in outcome.findings] + if structural: + checks.append( + _failed( + "package:validity", + "REQ-6.2", + "every generated fragment must carry unique cTn ids, schema child order and resolvable spids/rIds", + structural[:40], + totalFindings=len(structural), + ) + ) + else: + checks.append( + _passed( + "package:validity", + "REQ-6.2", + "every generated fragment carries unique cTn ids, schema child order and resolvable spids/rIds", + fragments=sum(1 for outcome in outcomes.values() if outcome.outcome == "generated"), + ) + ) + + reversible = [outcome for outcome in outcomes.values() if outcome.reversible] + unequal = [outcome for outcome in reversible if not outcome.equal] + if unequal: + checks.append( + _failed( + "roundTrip:normalizedEquality", + "REQ-5.1", + "JSON -> PPTX -> JSON must preserve normalized semantic values for every invertible " + "entry; a loss here is a disagreement between the catalog's semanticJson and the " + "OOXML its own ooxml block records, not a reader defect", + [f"{outcome.key}: {'; '.join(outcome.diff)}" for outcome in unequal], + invertibleEntries=len(reversible), + ) + ) + else: + checks.append( + _passed( + "roundTrip:normalizedEquality", + "REQ-5.1", + "every invertible catalog entry survives JSON -> PPTX -> JSON unchanged", + invertibleEntries=len(reversible), + transitions=sum(1 for outcome in reversible if outcome.kind == "transition"), + presets=sum(1 for outcome in reversible if outcome.kind == "animation"), + ) + ) + + writer_errors = [outcome for outcome in outcomes.values() if outcome.outcome == "error"] + if writer_errors: + checks.append( + _failed( + "writer:noUnexpectedFailure", + "REQ-6.4", + "a catalog entry must either generate or raise a deterministic capability refusal", + [f"{outcome.key}: {'; '.join(outcome.findings)}" for outcome in writer_errors], + ) + ) + else: + checks.append( + _passed( + "writer:noUnexpectedFailure", + "REQ-6.4", + "every accepted entry either generated or refused deterministically", + entries=len(outcomes), + ) + ) + + # --- walk every coverage-matrix cell ---------------------------------- + cells = matrix_cells(matrix, index, catalog) + cell_report: list[dict[str, Any]] = [] + for cell in cells: + established = cell.established_representative() + if established is not None: + key = str(established[1]["key"]) + outcome = outcomes.get(key) + if outcome is None: + state, detail = "failed", "the representative entry is not in the accepted catalog" + elif outcome.findings: + state, detail = "failed", "; ".join(outcome.findings[:3]) + elif outcome.outcome == "refused": + # The catalog establishes the element form, but the writer still + # refuses: the remaining gap is the behavior payload. + state, detail = "blockedOnCapture", outcome.gap + elif outcome.outcome != "generated": + state, detail = "failed", f"the entry neither generated nor refused: {outcome.outcome}" + elif outcome.reversible and not outcome.equal: + state, detail = "failed", "; ".join(outcome.diff[:3]) + elif outcome.reversible: + state, detail = "verified", "generated and read back to equal semantic JSON" + else: + state, detail = "oneWay", "generated, but the catalog records no inverse mapping yet" + cell_report.append({"cell": cell.id, "state": state, "catalogKey": key, "detail": detail}) + continue + if cell.covered_by: + owners = [check for check in checks if check.id in cell.covered_by] + cell_report.append( + { + "cell": cell.id, + "state": "fixture", + "catalogKey": None, + "detail": "covered by " + ", ".join(cell.covered_by), + "fixtures": list(cell.covered_by), + "fixtureStatus": [check.status for check in owners] or ["pending"], + } + ) + continue + rep = cell.representative() + outcome = outcomes.get(str(rep[1]["key"])) if rep else None + cell_report.append( + { + "cell": cell.id, + "state": "blockedOnCapture", + "catalogKey": None if rep is None else str(rep[1]["key"]), + "detail": (outcome.gap if outcome and outcome.gap else "no catalog member establishes an OOXML form"), + } + ) + + # --- acceptance fixtures --------------------------------------------- + manifest = load_fixture_manifest(manifest_path) + scratch = out_dir or Path(tempfile.mkdtemp(prefix="sdpm-accept-")) + scratch.mkdir(parents=True, exist_ok=True) + packages: dict[str, Path] = {} + fixture_checks: list[Check] = [] + for package in manifest["packages"]: + try: + packages[package["id"]] = build_fixture_package(package, scratch, template=template) + except Exception as error: # noqa: BLE001 + fixture_checks.append( + _failed( + f"fixture:{package['id']}", + package["requirement"], + package["purpose"], + [f"building the package raised {type(error).__name__}: {error}"], + ) + ) + continue + fixture_checks.append(check_fixture(package, packages[package["id"]], index=index)) + for pair in manifest.get("invariants") or (): + fixture_checks.append(check_identical_timing(packages, pair)) + checks += fixture_checks + + # Cells owned by a fixture are resolved once the fixture checks exist. + by_id = {check.id: check for check in checks} + for row in cell_report: + if row["state"] != "fixture": + continue + statuses = [by_id[name].status for name in row.get("fixtures", ()) if name in by_id] + row["fixtureStatus"] = statuses or ["missing"] + if statuses and all(status == "passed" for status in statuses): + row["state"] = "verified" + elif "failed" in statuses or not statuses: + row["state"] = "failed" + else: + row["state"] = "blockedOnPowerPoint" + + # --- the gaps --------------------------------------------------------- + records = catalog_coverage(index, catalog=catalog) + writer_summary = coverage_summary(records) + # Split off the entries no capture can ever close. They are tracked so the + # sdef enumeration is accounted for, but counting them as "awaiting a + # PowerPoint read-back" asserts something their own recorded gap denies — + # and it means the capture-required total can never reach zero, so it stops + # being a measure of progress. + no_sdpm_input = sorted( + record.key for record in records if record.outcome == "refused" and record.no_sdpm_input + ) + platform_unavailable = sorted( + record.key + for record in records + if record.platform_unavailable and not record.no_sdpm_input + ) + capture_required = sorted( + record.key + for record in records + if record.outcome == "refused" + and not record.elements + and not record.no_sdpm_input + and not record.platform_unavailable + ) + payload_gaps = sorted( + ( + {"key": record.key, "group": record.group, "elements": list(record.elements)} + for record in records + if record.outcome == "refused" and record.elements + ), + key=lambda row: row["key"], + ) + gallery_payload_gaps = [row for row in payload_gaps if row["group"] == "guiItems"] + # An effect this build cannot apply is excluded from both gap counts, not + # just the capture one. Its form is unmeasured here, so the reader has + # nothing to invert it to, and no work available on this platform changes + # that — leaving it in `oneWayOnly` would be the same unreachable-total + # defect one column over. + unreachable = { + record.key for record in records if record.platform_unavailable or record.no_sdpm_input + } + one_way = sorted( + outcome.key + for outcome in outcomes.values() + if outcome.outcome == "generated" + and not outcome.reversible + and outcome.key not in unreachable + ) + partial = [ + {"key": outcome.key, "paths": list(outcome.diff)} + for outcome in sorted(outcomes.values(), key=lambda item: item.key) + if outcome.reversible and not outcome.equal + ] + degenerate = [ + row["id"] + for row in matrix.get("cells") or () + if row["axis"] == "boundary" and "1 distinct value(s)" in str(row.get("note", "")) + ] + + gaps = { + "captureRequired": { + "count": len(capture_required), + "meaning": "accepted catalog mappings whose OOXML element form PowerPoint has not been asked for", + "closes": "PowerPoint read-back (--powerpoint) recording the element and attributes for each key", + "keys": capture_required, + }, + "platformUnavailable": { + "count": len(platform_unavailable), + "meaning": ( + "effects that are real but which this PowerPoint build cannot apply, so no " + "capture taken here can record their OOXML form. On Windows the full effect list " + "is reached through Add Animation; PowerPoint for Mac has no such control, so its " + "galleries and the Path Animation popup are the complete set. Read from the " + "platform inventory and the gallery tiles, and corroborated by Microsoft's own " + "motion-path article and a Microsoft Q&A answer; each entry carries both links" + ), + "closes": "a capture on a platform whose PowerPoint offers the effect", + "keys": platform_unavailable, + }, + "noSdpmInput": { + "count": len(no_sdpm_input), + "meaning": ( + "enumerators tracked for sdef coverage that no sdpm JSON can ask for, so no " + "capture closes them. The 45 MsoAnimDirection names are these: a direction is " + "measured per effect and written as preset.options.direction, and the enumerator " + "name does not identify a presetSubtype — 33 of the 45 are not offered by any " + "gallery tile, and the same label means different subtypes on different effects" + ), + "closes": "nothing; these are recorded as out of the input vocabulary, not as a gap", + "keys": no_sdpm_input, + }, + "behaviorPayloads": { + "count": len(gallery_payload_gaps), + "meaning": ( + "gallery tiles whose behavior children were captured but whose payload values " + "(coordinates, colour, scale, angle, animated attribute) were not" + ), + "closes": "PowerPoint read-back capturing each behavior node's payload", + "entries": gallery_payload_gaps, + "mirroredCandidates": len(payload_gaps) - len(gallery_payload_gaps), + "allEntries": payload_gaps, + }, + "oneWayOnly": { + "count": len(one_way), + "meaning": ( + "entries the writer emits but the catalog records no inverse mapping for, so " + "PPTX -> JSON keeps them raw instead of semantic" + ), + "closes": "the same read-back: a captured presetSubtype/attribute domain makes the form invertible", + "keys": one_way, + }, + "partialRoundTrip": { + "count": len(partial), + "meaning": "invertible entries that lost a semantic field between write and read", + "entries": partial, + }, + } + + powerpoint: dict[str, Any] = { + "attempted": False, + "available": False, + "reason": "not requested; pass --powerpoint on a machine where PowerPoint is drivable", + "readBack": [], + } + if use_powerpoint: + powerpoint, powerpoint_checks = powerpoint_read_back(packages, manifest) + checks += powerpoint_checks + + blockers: list[str] = [] + for check in checks: + if check.status == "failed": + blockers.append(f"check {check.id} failed") + elif check.status == "blockedOnPowerPoint": + blockers.append(f"check {check.id} is blocked on PowerPoint") + # ``noSdpmInput`` is deliberately not a blocker: it counts entries nothing + # can close, so gating on it would make the gate unpassable by design. + for name in ("captureRequired", "behaviorPayloads", "oneWayOnly", "partialRoundTrip"): + if gaps[name]["count"]: + blockers.append(f"{gaps[name]['count']} {name} gap(s) remain") + if not use_powerpoint: + blockers.append("the PowerPoint oracle half has not run (REQ-9.3 is unproven without --powerpoint)") + + cell_states: dict[str, int] = {} + for row in cell_report: + cell_states[row["state"]] = cell_states.get(row["state"], 0) + 1 + + return { + "schemaVersion": REPORT_SCHEMA_VERSION, + "harness": repo_path(Path(__file__)), + "mode": {"all": True, "powerPoint": use_powerpoint, "offline": not use_powerpoint}, + "catalog": { + "path": repo_path(catalog_path), + "digest": catalog_digest, + "generatedAt": catalog["baseline"]["generatedAt"], + "guiManifest": catalog["baseline"]["guiManifest"], + "acceptedEntries": len(outcomes), + }, + "matrix": { + "path": repo_path(matrix_path), + "digest": digest(derived_text.encode("utf-8")), + "cellCount": len(cells), + "axes": matrix.get("axes", {}), + "states": cell_states, + "cells": cell_report, + }, + "writer": writer_summary, + "roundTrip": { + "invertibleEntries": len(reversible), + "equal": sum(1 for outcome in reversible if outcome.equal), + "transitions": sum(1 for outcome in reversible if outcome.kind == "transition"), + "presets": sum(1 for outcome in reversible if outcome.kind == "animation"), + }, + "checks": [check.as_json() for check in checks], + "gaps": gaps, + "informational": { + "boundaryClassesWithOnePinnedValue": degenerate, + "meaning": ( + "the catalog pins a single value for these numeric paths, so the minimum, normal and " + "maximum classes share one fixture. Not a release blocker; a note for the read-back." + ), + }, + "powerPoint": powerpoint, + "fixturePackages": {name: path.name for name, path in sorted(packages.items())}, + "gate": {"pass": not blockers, "blockers": blockers}, + "exitCode": 0 if not blockers else 1, + } + + +# --------------------------------------------------------------------------- +# Text rendering +# --------------------------------------------------------------------------- +def render(report: Mapping[str, Any]) -> str: + """Render the report for a human, keys included so the list is actionable.""" + lines: list[str] = [] + catalog = report["catalog"] + lines.append("PowerPoint animation/transition acceptance") + lines.append(f" catalog {catalog['path']} ({catalog['acceptedEntries']} accepted entries)") + lines.append(f" catalog digest {catalog['digest']}") + lines.append(f" matrix {report['matrix']['path']} ({report['matrix']['cellCount']} cells)") + lines.append(f" mode {'offline' if report['mode']['offline'] else 'offline + PowerPoint oracle'}") + + lines.append("") + lines.append("Coverage matrix cells by state") + for state, count in sorted(report["matrix"]["states"].items()): + lines.append(f" {state:18} {count}") + + lines.append("") + lines.append("Writer coverage") + writer = report["writer"] + lines.append(f" generated {writer['generated']['total']} refused {writer['refused']['total']} " + f"total {writer['total']}") + round_trip = report["roundTrip"] + lines.append( + f" invertible {round_trip['invertibleEntries']} " + f"(transitions {round_trip['transitions']}, presets {round_trip['presets']}), " + f"equal {round_trip['equal']}" + ) + + lines.append("") + lines.append("Checks") + for check in report["checks"]: + mark = {"passed": "PASS", "failed": "FAIL", "blockedOnPowerPoint": "BLOCKED"}[check["status"]] + lines.append(f" [{mark:7}] {check['id']} ({check['requirement']})") + lines.append(f" {check['detail']}") + for finding in check.get("findings", []): + lines.append(f" - {finding}") + + lines.append("") + lines.append("Gaps (each key is the stable catalog key that closes it)") + gaps = report["gaps"] + lines.append(f" captureRequired {gaps['captureRequired']['count']}") + for key in gaps["captureRequired"]["keys"]: + lines.append(f" {key}") + lines.append( + f" behaviorPayloads {gaps['behaviorPayloads']['count']} gallery tiles " + f"(+{gaps['behaviorPayloads']['mirroredCandidates']} mirrored enum candidates)" + ) + for row in gaps["behaviorPayloads"]["entries"]: + lines.append(f" {row['key']} unresolved: {', '.join(row['elements'])}") + lines.append(f" oneWayOnly {gaps['oneWayOnly']['count']}") + for key in gaps["oneWayOnly"]["keys"]: + lines.append(f" {key}") + lines.append(f" partialRoundTrip {gaps['partialRoundTrip']['count']}") + for row in gaps["partialRoundTrip"]["entries"]: + lines.append(f" {row['key']} {'; '.join(row['paths'])}") + + powerpoint = report["powerPoint"] + lines.append("") + lines.append("PowerPoint oracle") + lines.append(f" attempted {powerpoint['attempted']} available {powerpoint['available']}") + if powerpoint.get("reason"): + lines.append(f" reason {powerpoint['reason']}") + if powerpoint.get("remediation"): + lines.append(f" fix {powerpoint['remediation']}") + + lines.append("") + lines.append(f"GATE: {'PASS' if report['gate']['pass'] else 'FAIL'}") + for blocker in report["gate"]["blockers"]: + lines.append(f" - {blocker}") + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--all", action="store_true", help="run the full catalog-derived acceptance sweep") + parser.add_argument( + "--powerpoint", + action="store_true", + help="also run the PowerPoint read-back half; this flag is the operator's explicit consent", + ) + parser.add_argument("--write-matrix", action="store_true", help="regenerate the coverage matrix from the catalog") + parser.add_argument("--json", action="store_true", help="emit the structured report on stdout and nothing else") + parser.add_argument("--catalog", type=Path, default=DEFAULT_CATALOG) + parser.add_argument("--matrix", type=Path, default=DEFAULT_MATRIX) + parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) + parser.add_argument("--template", type=Path, default=DEFAULT_TEMPLATE) + parser.add_argument("--out", type=Path, default=None, help="keep the built fixture packages in this directory") + args = parser.parse_args(argv) + + if args.write_matrix: + catalog_bytes = args.catalog.read_bytes() + catalog = load_catalog_document(args.catalog) + index = load_capability_index(args.catalog) + matrix = build_matrix(catalog, index, catalog_digest=digest(catalog_bytes)) + text = dump_matrix(matrix) + args.matrix.parent.mkdir(parents=True, exist_ok=True) + args.matrix.write_text(text, encoding="utf-8") + payload = { + "wrote": repo_path(args.matrix), + "cellCount": matrix["cellCount"], + "axes": matrix["axes"], + "digest": digest(text.encode("utf-8")), + } + print(json.dumps(payload, indent=2)) + return 0 + + if not args.all and not args.powerpoint: + parser.error("pass --all (optionally with --powerpoint), or --write-matrix") + + report = run_acceptance( + catalog_path=args.catalog, + matrix_path=args.matrix, + manifest_path=args.manifest, + template=args.template, + use_powerpoint=args.powerpoint, + out_dir=args.out, + ) + print(json.dumps(report, indent=2, ensure_ascii=False) if args.json else render(report)) + return int(report["exitCode"]) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/animation_catalog/computer-use.md b/scripts/animation_catalog/computer-use.md new file mode 100644 index 000000000..ed5eef0d7 --- /dev/null +++ b/scripts/animation_catalog/computer-use.md @@ -0,0 +1,1060 @@ +# Computer Use reproduction steps for GUI-only catalog values + +These steps close the gaps the offline evidence cannot close. They are +development-only (REQ-7.3): sdpm's runtime, CLI, MCP servers, tests and CI never +invoke Computer Use, AppleScript, VBA or PowerPoint. + +Almost every entry in +`sdpm/references/catalogs/powerpoint-animation-catalog.json` whose +`capabilityLevel` is `semanticPreservationOnly` still carries its `ooxml.gap` +and `verification: "powerPointReadBackRequired"`. Running the steps below is how +a maintainer promotes those entries. + +**One capture has been executed** (2026-10-31), as a proof of the loop rather +than as coverage: Box ▸ Effect Options ▸ From Right. See "Driving mechanics" +below for the method and "What the pilot capture established" for its result. + +## This is the only route to an animation value + +> `add effect` is declared in `PowerPoint.sdef` but **PowerPoint for Mac +> 16.113.1 does not implement it** on `main sequence`. In the 2026-10-31 +> scripting-oracle run, all 150 `MsoAnimEffect` candidates were refused with +> one identical error: +> +> ``` +> main sequence of timeline of slide N of presentation "Presentation1" +> doesn't understand the "add effect" message. +> ``` +> +> No slide in that run's package carries a `p:timing` tree. The evidence is +> checked in at `tests/fixtures/animations/oracle-16.113.1/`, and each refused +> candidate's catalog entry records the error in its `capture` block. + +Two consequences, both load-bearing for the steps below: + +1. **Do not rewrite the AppleScript animation probes.** `probeAnimations`, + `probeDirections`, `probeTriggers`, `probeBuildLevels`, `probeTextUnits`, + `probeBehaviors` and `probeAfterEffects` all begin by adding an effect, so + no terminology fix can make them work in this build. Steps 3 to 10 of this + file are the *only* way to capture an animation value: every remaining + capture-required animation entry and every unresolved behavior payload has + to come through the Accessibility API, by hand, through this procedure. +2. **The transition steps are already closed**, and not from here. The + scripting oracle applies a candidate by enumerator code, which is what the + catalog is keyed on, so it settled the transition half outright — see + Steps 1 and 2. Transitions are scriptable in this build; animations are not. + That splits the remaining work by mechanism rather than by effort. + +## Baseline + +| Item | Value | +| --- | --- | +| Application | Microsoft PowerPoint for Mac | +| Version | 16.113.1 | +| Scripting definition | `/Applications/Microsoft PowerPoint.app/Contents/Resources/PowerPoint.sdef` | +| GUI manifest | `scripts/animation_catalog/powerpoint-gui-surface-16.113.1.json` | + +Record the exact version string from **PowerPoint ▸ About Microsoft PowerPoint** +before and after a session. A different build invalidates the capture: bump +`manifestVersion` and regenerate rather than mixing builds. + +## Session setup + +1. Quit PowerPoint. Confirm no recovery deck is pending. +2. Launch PowerPoint and create a deck from **Blank Presentation**. +3. Delete the title slide's placeholders so the slide is empty. +4. Set the window to a fixed size and record it in the session log. Screenshot + coordinates are only reproducible at a fixed window size. +5. Turn off **PowerPoint ▸ Settings ▸ General ▸ Show Start screen**. + +## Evidence that every step must produce + +For each value, capture all four of these or the value stays unverified: + +1. a screenshot of the control with the value selected, named + `--.png`; +2. the `.pptx` saved immediately after applying the value, named + `--.pptx`; +3. the extracted XML fragment — `ppt/slides/slideN.xml`'s `p:transition`, + `p:timing` and `p:bldLst` — named `--.xml`; +4. the value PowerPoint shows **after** closing and reopening the saved file. + +Extract (3) without PowerPoint: + +```bash +unzip -p "--.pptx" ppt/slides/slide1.xml \ + | python3 -c 'import re,sys; x=sys.stdin.read(); print("\n".join(re.findall(r"|", x, re.S)))' +``` + +Store the four files under `tests/fixtures/animations/gui-only//` and add +a row to that directory's `README.md` naming the application version, the date, +and the control path. Then update the catalog entry's `capabilityLevel`, +`evidence` and `verification`, and run +`uv run python scripts/animation_catalog/generate.py --check --require-sdef`. + +## Driving mechanics (measured 2026-10-31, PowerPoint 16.113.1, 1512x900 window) + +AppleScript is not the route. `osascript` reaches PowerPoint's **static** +properties (`get version`) but every document-model access and every +`System Events` call fails with `-10004`. The working route is the macOS +**Accessibility API** through KiroCrew's computer-use tools, which is a +different mechanism and is not blocked. + +**Use `computer_perform_action` with `AXPress`, not clicks.** This is the whole +method; everything below about coordinates is a fallback for controls that have +no addressable element. + +- **`computer_get_state` is reliable**, and the ribbon is fully enumerated: + every gallery tile, the Duration incrementor, the Sound popup, the advance + checkboxes, and each thumbnail's `Has Transition` / `Has Animation` state. + Enumerated is not the same as drivable: the thumbnails have titles and no + actions, which is the subject of "Why the driver does not select slides". +- **`computer_perform_action` with `element_index` works**, including on + main-window elements and on elements scrolled **outside** the visible band. + Pressing a tile at window `x=1448` inside a 320-pixel-wide gallery applies + it and scrolls it into view. So there is no coordinate arithmetic, no + paging, no tooltip problem, and **no pointer takeover** — the operator's + machine stays usable. +- **One explicit `computer_get_state` per `perform_action`, and nothing in + between.** The indices come from that call alone. The tree a *click* returns + does not register, which the tool says plainly once you hit it: + `no state for 'com.microsoft.Powerpoint'. Call computer_get_state first.` + Until that error appears the symptom is the misleading + `element N is no longer present`, so a run of presses reads like PowerPoint + invalidating its elements when it is really a missing read. Send the two + calls in separate turns: issued together they race and the action loses. +- **A popup's own window is only visible to an explicit read.** After a click + opens `Effect Options` or `Path Animation`, the click's refreshed tree still + shows the document window; the next `computer_get_state` reports + `Window: "Path Animation"` with the whole grid. Do not conclude a popup + failed to open from a click's own output. +- **`computer_click` with `element_index` always fails** against the main + window (`element … is no longer present`), because PowerPoint rebuilds its + accessibility elements between queries. This is a limitation of that tool, + not of the accessibility route. +- **`click_method: "app_post"` is delivered but ignored** by the ribbon: it is + custom-drawn and does not process per-process synthetic mouse events. + `click_method: "global"` does drive it, but it moves the real pointer, and + after such a click the pointer rests on the control and macOS raises a + tooltip there, so the **next** `global` click at the same point refuses with + `the topmost window there is 'Window Server'`. There is now **nothing in the + driver that needs it**: the one target with no addressable element, a shape + on the slide canvas, is reached through its Selection Pane row instead. See + "Why the driver selects shapes in the Selection Pane". + +A gallery **lazily materializes its tiles**: a first read of Entrance Effects +returned 22, and after one tile was pressed the same read returned different +tiles (Rise Up, Spinner, Basic Zoom, Stretch, Boomerang) that had not been +there. Re-read the tree after each press rather than caching an index list, +and never assume the first read enumerated the whole gallery. + +### Two constraints that set the cost of a batch + +Both were measured, and together they rule out the obvious shortcuts. + +**A gallery press replaces the effect of the selected shape; it does not add +one.** There is no Add Animation button on this build. Pressing Lines, then +Appear, then a third tile on one shape leaves **one** effect — the last. A batch +therefore needs **one shape per value**, not one shape with a stack of them. It +does *not* need one slide per value: what the press is scoped to is the +selection, so one slide carrying many well-separated shapes works, and each +effect in the saved `p:timing` says which shape it belongs to through +`p:spTgt/@spid`. That is how the driver attributes a capture — see +"Why the driver does not select slides" below for why it is also the only shape +that works. + +**Indices shift as soon as a press scrolls the gallery.** `perform_action` +keeps the state across consecutive actions, so several presses can share one +read — but only while the tile list holds still. After one press the Entrance +gallery scrolled, grew a Previous button, and materialized Swivel, Zoom, +Center Revolve, Float In and Grow Turn, so the index that had been +Checkerboard was Shape. A press aimed by a stale index applies the wrong +effect and the record names the right one, which is worse than failing. +**Re-read before every press.** + +So the real cost per value is three calls — select the shape's row, read, press. +(It was four while a slide had to be selected too; that step is gone, and the +next section says why.) Size a batch by the number of shapes in it. + +Set `max_tree_nodes: 1` before a run of presses when you do not need the tree: +a press returns a refreshed tree at the budget of the last read, and the full +ribbon tree is large. + +If you do fall back to coordinates, the Transition Styles gallery is positioned +arithmetically, verified against the tree: + +``` +tile x = 100 + 92 * i - 920 * page visible band: x in [100, 1012] +page = floor(92 * i / 920) Next/Previous move exactly one page +tile centre = (x + 47, 107) window-relative; add window origin y +``` + +`i` is the index in gallery order, which is fixed: +None, Morph, Fade, Push, Wipe, Split, Reveal, Cut, Random Bars, Shape, +Uncover, Cover, Flash, Fall Over, Drape, Curtains, Wind, Prestige, Fracture, +Crush, Peel Off, Page Curl, Airplane, Origami, Dissolve, Checkerboard, Blinds, +Clock, Ripple, Honeycomb, Glitter, Vortex, Shred, Switch, Flip, Gallery, Cube, +Doors, Box, Comb, Zoom, Random, Pan, Ferris Wheel, Conveyor, Rotate, Window, +Orbit, Fly Through. + +Order a batch by gallery page so the sweep is monotonic: 49 tiles are 5 pages, +so a whole pass costs four `Next` clicks rather than one per tile. + +Other measured coordinates, window-relative (add the window origin): + +| Control | Frame | Centre | +| --- | --- | --- | +| Transitions ribbon tab | x=247,y=39 94x26 | 294, 52 | +| Previous gallery page | x=82,y=78 18x58 | 91, 107 | +| Next gallery page | x=1020,y=78 18x58 | 1029, 107 | +| Effect Options | x=1040,y=74 50x66 | 1065, 107 | +| Duration (read-back) | x=1204,y=78 78x24 | — | +| Sound (read-back) | x=1180,y=109 102x26 | — | +| Save (Quick Access) | x=221,y=5 30x30 | 236, 20 | + +The slide-navigator thumbnail geometry that used to sit in this table has been +removed rather than corrected. It was never usable — see the next section. + +## Why the driver does not select slides + +Measured 2026-10-31 by a live run of the driver's first version, which selected +a slide per target. Against a 76-target plan on a 76-slide deck it returned +**76 records, 0 captured, 76 rejected**, with `steps` empty on every record: +nothing reached a control. Two distinct causes, both inside slide selection. + +**The navigator's cells expose no actions.** `select_slide` pressed the cell, +then set `kAXSelected`, then waited, bounded, for `AXSelected` to read back +true. A manual read of the live tree showed +`cell "Slide 1 of 17 Slides"` with **no `[AXPress]`** and no other action, and +the attribute never became true, so slides 1 to 6 each ended in a 6-second +timeout. The only thing that selected a slide by hand was a synthetic +**global click on the cell's own frame** — a pointer takeover per target, and +the pointer is exactly what the next section stops needing. + +**Only the cells scrolled into view exist.** The navigator publishes **6** of +76 cells; the rest are not in the tree at all. Slides 7 to 76 were therefore +rejected as `slide N is outside the 6 thumbnail cells read`. Position-indexing +cannot reach a cell the application has not materialized, and reaching them +would need scrollbar arithmetic plus title matching plus a status-bar +cross-check — three more assumptions with no offline check. + +The fix was to stop needing slide selection. `gui_capture_plan.py` now builds +**one slide carrying one named shape per target**, and `gui_capture.py` selects +a target through that shape's Selection Pane row. Attribution got +stronger rather than weaker: +each effect in the saved `p:timing` carries `p:spTgt/@spid`, and the slide's +`p:cNvPr/@id` and `@name` map that back to the shape and so to the target, which +survives reordering and catches a mis-aimed click. "Slide N is target N" did +neither. + +Two consequences worth keeping in mind for manual work in this file's other +steps: + +- the `Has Animation` thumbnail marker is **not** per-target evidence on a + one-slide deck. It says the slide has an animation, which it does after the + first capture. Read `p:spTgt/@spid` instead. +- a deck of 76 slides is still fine to *read* by hand; it is driving the + navigator that does not work. + +## Why the driver selects shapes in the Selection Pane + +Measured 2026-11-01. A canvas shape has **no accessibility element**, so for a +while the driver selected one with a synthetic global mouse event at a point +derived from the package geometry, the live editor-pane frame and the live zoom. +That never became reliable. Watching a run, the pointer landed in the right +place and the shape stayed unselected; the same click by hand always worked. +Pacing the event helped and did not fix it — `kCGMouseEventClickState`, a settle +before the button-down, a hold, and a 0.35 s settle after the up took the last +run of that version to **2 of 12** attempted targets, with the other ten +recorded as `effectNotAdded` / "no new effect appeared": the signature of a +click that did not change the selection, so the gallery press replaced the +*previously* selected shape's effect. + +Canvas shapes have no element. **Their Selection Pane rows do**, and that +removes coordinates, the pointer, the zoom, the pane frame and the timing all at +once. Measured live: + +| Fact | Value | +| --- | --- | +| `Home ▸ Arrange` | an `AXMenuButton`; pressing it opens a window titled `Arrange` | +| the `Arrange` window | holds an `AXMenuButton` titled `Selection Pane...` | +| pressing that | opens the pane **inside the document window that carries the ribbon** (PowerPoint publishes several same-titled windows) | +| the pane | an `AXOutline` whose children are one `AXRow` per shape — 153 rows for a deck of 76 shapes plus 76 labels plus one | +| row order | **reverse z-order**: row 0 `TextBox 152`, row 1 `Rounded Rectangle 151`, row 2 `TextBox 150` | +| a row's `title` | `None`. The shape name is the **`value` of a descendant `AXStaticText`** | +| a row's actions | `AXShowDefaultUI`, `AXShowAlternateUI` and a Rename. **No `AXPress`** | +| selecting a row | **set `AXSelected`**, the standard outline-row mechanism, then read it back | +| `AXRows` vs `AXChildren` | idle: `AXRows` 152, `AXChildren` 153, `AXVisibleRows` 24 | +| `AXRows` **during a run** | **43, 54, 61, 63, 74, 88, 91** rows on consecutive reads of the same 152-shape slide. It is not all of them | +| a row's **name**, during a run | published only for rows that have been scrolled into view. One run read **80** names, then **54** | +| **`AXIndex` on a row** | every row publishes one: 0, 1, 76 and 151 at those offsets. **This is what identifies a row** | +| `AXRowCount` on the outline | not published (`None`) | +| row order against the package | reverse z-order, **152 of 152 agreeing, 0 mismatches, verified twice** | +| the enclosing `AXScrollArea` | its `AXVerticalScrollBar`'s `AXValue` **is settable** — an unused fallback, should the retry below ever stop being enough | + +So a shape is selected **by row index** — its position in reverse z-order, read +offline from the package, matched against the row that reports that `AXIndex`. +No coordinates, no keyboard focus, no timing dependency. + +Two things that look like they would work and do not. **A name is not a key**: +selecting by name rejected 11 targets as "no Selection Pane row is named ..." +for rows that were there and selectable the whole time, because an unscrolled row +carries no `AXStaticText` to read a name from. And **an offset into `AXRows` is +not a key either**: that rejected 7 more, because the pane rebuilds while the +application works and a read catches it part-built. A row's own `AXIndex` is +readable in both states, so a partial read is usable whenever it contains the row +wanted, and a read that does not is simply retried. + +The name is kept as a **check**: if the row at an index publishes a name, it must +be the name expected there. That is what would catch a pane in some other order, +or an `AXIndex` that turned out to be relative to a partial read rather than +absolute, before a press lands on another shape. + +Two cautions carried over from elsewhere in this file: pressing +`Selection Pane...` while the pane is open **closes** it, the same trap as +pressing an already-active ribbon tab, so read the pane's presence rather than +remembering it; and rows are re-created between reads like every other element +here, so re-resolve the row from a fresh read every time, index and all. + +The coordinate table and the canvas formula below are kept for **manual** work +through the Computer Use tools. `gui_capture.py` uses neither: it posts no mouse +events at all, and the options that corrected the mapping (`--pane-frame`, +`--pane-role`, `--zoom`) are gone with it. + +Effect Options opens as its own window titled `Effect Options`, whose items +are `menubutton`s. Activate one with `computer_perform_action` + `AXPress`; a +plain `global` click only focuses it and leaves the menu open. + +### The loop is a script now, not an agent round trip + +Everything above is still how PowerPoint behaves; what changed is who sends the +calls. **The macOS Accessibility API is reachable from Python in this +environment**, which the KiroCrew tool wrapper is not required for: +`AXIsProcessTrusted()` returns true and `AXUIElementCreateApplication(pid)` +returns PowerPoint's window, under + +```bash +uv run --with pyobjc-framework-ApplicationServices --with pyobjc-framework-Cocoa \ + --with lxml \ + python … +``` + +(`lxml` because the package readers import it lazily, so a run outside the +repository's own environment fails at the first attribution without it. **Quartz +is not needed** — the only binding that wanted it was the mouse event.) + +So the calls per value — select the shape's row, read, press, save — are a loop +inside one process rather than that many agent turns, and the two rules that make +the tool contract awkward (one explicit read per action, a popup being invisible +to the read that opened it) stop being rules to remember: the driver re-reads +before every press by construction. It also posts **no mouse events**, so a run +no longer takes the pointer over. + +### What a read costs, and where the window's nodes are + +Every accessibility attribute read is an **interprocess round trip**, and the +document window is **907 nodes, 762 of them the Selection Pane's rows**. Timed +live on 2026-11-01, best of three: + +| operation | cost | +|---|---| +| `find_all_by_title(window, "Save")` — one full window walk | **6.4 s** | +| `selection_outline(backend)` | **17.8 s** | +| walking only the pane's outline (762 nodes) | 4.1 s | +| reading 152 rows' names | 4.3 s | + +Two consequences for anyone driving this by hand or by script: + +- **PowerPoint publishes four or five `AXWindow`s carrying the same document + title**, and only one of them holds the ribbon. Searching each by title to + find out costs a full walk per candidate. +- **The window's controls live in three containers**, and each is the smallest + thing certain to hold what it holds: `Save` under the window's `AXToolbar`; + the tab strip and the active tab's command galleries under one `AXTabGroup`; + the shape rows under the pane's `AXOutline`. The tab group is a **top-level + child** of the window, which is what makes identifying the right window a + two-level look rather than a walk. + +So a lookup aimed at the whole window pays for the pane's rows even when it wants +a ribbon tile, and vice versa. `gui_capture.py` scopes every lookup to one of the +three containers for exactly that reason, and a run of it that did not captured +**7 targets in 28 minutes**. + +`scripts/animation_catalog/gui_capture.py` is that driver and +`gui_capture_plan.py` derives its target list from the catalog's own +`ooxml.requiresCapture` entries. See +[the README](README.md#gui-capture-driver) for how to run them. Use this file +for what the application does; use the driver for doing it. + +### Mechanics this file did not record, found while coding against it + +Each of these was needed to write the driver and was not here: + +- **The Animations galleries are three separate named controls**, not one + gallery with sections: `Entrance Effects`, `Emphasis Effects`, + `Exit Effects`, plus the `Path Animation` menu button. A path is therefore + `Animations > Entrance Effects > Fly In`, and the `Animations` tab has to be + pressed before any of them resolves. +- **The canvas click point has a formula**, and only its worked example was + recorded. The driver no longer uses it — see "Why the driver selects shapes in + the Selection Pane" — but it is the mapping to use for manual work. With the + editor pane's frame in screen coordinates and the live zoom `z`, a slide of + `W x H` points showing a shape centred at `(sx, sy)` points: + + ``` + shown = (W * z, H * z) + origin = (pane.x + (pane.w - shown.w)/2, pane.y + (pane.h - shown.h)/2) + point = (origin.x + sx * z, origin.y + sy * z) + ``` + + The 2026-10-31 measurement is the check: a 960x540 pt slide at 92% in a + 1258x540 pane at screen (254, 177) puts a shape centred at (140, 190) pt on + screen (570.2, 373.4). This assumes the slide is **centred** in the pane, + which holds when the canvas is not scrolled. +- **sdpm names a shape from its geometry, not from the element id.** The capture + deck asks for elements called `target001`… and the package carries + `Rounded Rectangle 1`, `Rounded Rectangle 3`, and so on — and that first shape's + **`p:cNvPr/@id` is `2`, not `1`**, so the name and the `spid` are two different + numbers and both have to be read. `gui_capture_plan.py --generate` matches each + target to the shape at the position the grid asked for and writes the name it + finds into the plan, rather than either side assuming one. +- **A direction entry does not imply a GUI path.** The `Effect Options` + direction labels depend on which effect is applied — Fly In offers + `From Bottom`, Wheel offers `1 Spoke` — so Step 8's measurement is + *effect x label -> presetSubtype*, and the 45 `MsoAnimDirection` entries + cannot have a path derived from the entry alone. The driver can drive them + once a plan names the prerequisite effect; the derivation refuses to invent + one. +- **A gallery tile's title is a name correspondence, not a measurement.** The + catalog key's last segment de-camel-cases to the label for all but three + tiles (`Grow/Shrink`, `Grow & Turn`, `Shrink & Turn`). The driver matches the + live title exactly and records a failure naming what it looked for, so a + wrong label costs one record instead of producing a mislabelled capture. + +### Assumptions only a live run can confirm + +The driver is written against these and fails loudly on each rather than +guessing. Correct this section after the first run. + +| Assumption | If it is wrong | +| --- | --- | +| The Selection Pane stays open, and keeps publishing rows, across a ribbon tab change and a `Save` | the next target's row lookup fails as `controlNotFound` and the run continues; it does not press on the previous shape | +| Writing `AXSelected` on a row selects the shape, and the row then reads back selected | the read-back times out per target **before** any press, so a selection that does not take costs a record rather than another shape's effect | +| A row's `AXIndex` is its absolute position in the outline, not its offset in a partial read | the row at a derived index publishes another shape's name and that target is `controlNotFound` naming both — provided the row publishes a name at all | +| A row the pane has not published yet appears within the timeout | that target is `controlNotFound` saying how many rows the last read published and which indices, so the operator can tell a missing row from a part-built pane | +| The pane's row order is the reverse of the slide part's shape order | same as the first row of this table: a name mismatch at the derived index | +| A row's name, **when the pane publishes one**, is exactly the package's `p:cNvPr/@name` | the order check above misfires and reports a mismatch that is only a naming difference | +| PowerPoint writes one `p:cTn` with a `presetClass` per applied effect, with the target shape's `spid` beneath it | attribution reads nothing and every target is rejected as `effectNotAdded`, loudly and on the first target | +| `Save` writes the new effect into the file before the next read | the attribution reads a stale package and rejects, rather than crediting the wrong effect | +| The `Path Animation` window lists presets directly, without a `Basic` grouping level | an extra level in the path is tolerated and recorded as `groupAbsent` | +| `Save` in the Quick Access toolbar overwrites in place with no Save As sheet | the driver waits, bounded, for the file to change and records a save failure per target | + +### What the GUI route cannot establish + +The AppleScript oracle applied a candidate **by its enumerator code**, so its +read-back was an unambiguous `EPPEntryEffect.` → OOXML mapping. +The GUI applies by **label**, so a capture establishes +`gallery tile + Effect Options label` → OOXML. Linking that to a scripting +enumerator such as `entry effect box down` is a name correspondence, not a +measurement. Record a GUI capture under a `transition.gallery..