Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat(hypit): move the authoring tools into the CLI, cut to the window, require every element

rponed886397260ef
diff --git a/.agents/skills/hypit/references/authoring.md b/.agents/skills/hypit/references/authoring.md
index 12d517c1..98ffd3a7 100644
--- a/.agents/skills/hypit/references/authoring.md
+++ b/.agents/skills/hypit/references/authoring.md
@@ -22,7 +22,7 @@ pnpm check
pnpm hypit check path/to/main.svml
pnpm hypit check path/to/recipes.svs
pnpm hypit check path/to/build.svrun
-node --import tsx .agents/skills/hypit/scripts/preview-check.mjs path/to/build.svrun
+hypit-reference-video-tools preview_check path/to/build.svrun
```
Check all of them, not only the Author Source: a Recipe the Author Source references and a Target the
@@ -31,9 +31,9 @@ Run Source demands are just as able to be wrong. Do not create a check wrapper.
**A check that passes is not a graph that traces.** `hypit check` proves a Source is legal — its
syntax, its references, its graph structure — and proves nothing about whether the tracks it declares
can actually be built, nor that an uncertain requirement was understood correctly. `preview.md`
-proves the Run traces, before any Provider is reached — which is why the last command above, the
-preview-check, is part of validating a Run and not a later step. Run it from the repository root:
-`tsx` is the repository's own dependency, so a working directory outside it fails to resolve it.
+proves the Run traces, before any Provider is reached — which is why the last command above,
+`preview_check`, is part of validating a Run and not a later step. Run it from the repository root:
+it resolves the installed packages against the working directory.
This file is about writing an element correctly, which is a narrower question than making the video
right. What a Track should contain, when a picture may be generated at all, how long a thing stays on
diff --git a/.agents/skills/hypit/references/environment.md b/.agents/skills/hypit/references/environment.md
index e528847c..650fd91b 100644
--- a/.agents/skills/hypit/references/environment.md
+++ b/.agents/skills/hypit/references/environment.md
@@ -26,13 +26,12 @@ install below still has to run there.
Every repository path written in these files — `.agents/skills/hypit/scripts/…`, `packages/…`,
`docs/…`, `examples/…` — is relative to the printed `repository` and to nothing else. That includes
-the other scripts: run the checkout's copies. `preview-check.mjs` reaches Studio's sources through
-its own position in the checkout, so that copy is the one that resolves them.
+the other scripts: run the checkout's copies.
Several commands resolve against the **working directory** rather than against the Source they are
given: `list_svml_packages` reads `node_modules/@hypit` from the cwd and refuses when it is empty, and
-`preview-check.mjs` resolves `tsx` the same way. Running them from the repository root is not a
-convention, it is the condition under which they work.
+`preview_check` and `reconstruction_check` read the installed packages from there too. Running them
+from the repository root is not a convention, it is the condition under which they work.
## Requirements
@@ -66,7 +65,8 @@ pnpm test
`npm link` links the `hypit` binary. The route also calls `hypit-reference-video-tools`
(`prepare_reference`, `observe_reference`, `compare_reconstruction`, `list_svml_packages`,
-`inspect_svml_vocabulary`) — a separate bin that the repository links on `pnpm install`, so it is
+`inspect_svml_vocabulary`, `render_element`, `render_previews`, `preview_check`,
+`reconstruction_check`) — a separate bin that the repository links on `pnpm install`, so it is
present once the workspace install above has run. If `hypit-reference-video-tools` is not on `PATH`
after installing, re-run `pnpm install` from the repository root; the bin resolves from
`packages/reference-video-tools/bin/`.
diff --git a/.agents/skills/hypit/references/local-author-package.md b/.agents/skills/hypit/references/local-author-package.md
index ac8b9896..4e01e022 100644
--- a/.agents/skills/hypit/references/local-author-package.md
+++ b/.agents/skills/hypit/references/local-author-package.md
@@ -179,7 +179,7 @@ nothing.
package the way its README does.
The picture `reconstruction-loop.md` compares is a different one and the package does not produce
- it. `scripts/render-element.mjs` reads the Source — the Canvas, the Recipe values, the Script text,
+ it. `render_element` reads the Source — the Canvas, the Recipe values, the Script text,
the bindings — and drives the package's own Producer to draw the component the way this video places
it. All the package has to be is a working Producer, which the Manifest already requires.
@@ -230,12 +230,12 @@ the preview check and repair until it passes — a graph failure is not a differ
work that is not finished, and it is not bounded by the loop's attempt ceiling:
```bash
-# from the repository root: tsx is the repository's dependency
-node --import tsx .agents/skills/hypit/scripts/preview-check.mjs path/to/build.svrun
+# from the repository root: it reads the installed packages from the working directory
+hypit-reference-video-tools preview_check path/to/build.svrun
```
It takes the Run Source, not the `.svml`. A pass here means the graph reaches a Film and a semantic
-spine; it exits zero while the Providers are still unrun, and says which capabilities it is waiting
+spine; it stays sound while the Providers are still unrun, and says which capabilities it is waiting
on. See `preview.md` for what that does and does not prove — notably, a
Producer that refuses the media kind it is handed is not caught here, because nothing is handed to
it until the Build runs.
diff --git a/.agents/skills/hypit/references/playbooks/craft/frame-coverage.md b/.agents/skills/hypit/references/playbooks/craft/frame-coverage.md
index a041dd61..5f4caf80 100644
--- a/.agents/skills/hypit/references/playbooks/craft/frame-coverage.md
+++ b/.agents/skills/hypit/references/playbooks/craft/frame-coverage.md
@@ -19,7 +19,7 @@ an interval inherits its edges whenever its length comes from something other th
around and between them;
- a generated take, which ends where its material ends rather than where the shot should — and then
draws nothing for the rest of its window, because `playback` defaults to `once-start`. This is the
- one edge on the list a machine can find before a Build: `reconstruction-check` reads each Recipe
+ one edge on the list a machine can find before a Build: `reconstruction_check` reads each Recipe
and refuses the default on timed generated material. `generated-dependencies.md` says what to set
instead;
- a blend, whose frames are edges of partial coverage — a one-frame fade is one frame on which the
diff --git a/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.md b/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.md
index b930ad0d..d15554a9 100644
--- a/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.md
+++ b/.agents/skills/hypit/references/playbooks/craft/generated-dependencies.md
@@ -148,7 +148,7 @@ three separate numbers that will not agree. Lengthening the material moves the m
removing it; `playback` decides what the window shows once the material is spent, which is the part
that stays true whichever way the three numbers fall.
-`reconstruction-check` reads this before a Build and refuses a Recipe that leaves `playback` at its
+`reconstruction_check` reads this before a Build and refuses a Recipe that leaves `playback` at its
default on generated material.
A bed makes a blend visible, so check the Items' entry and exit while you are here: `enter` and `exit`
diff --git a/.agents/skills/hypit/references/playbooks/craft/production-gates.md b/.agents/skills/hypit/references/playbooks/craft/production-gates.md
index e5c89cb9..6e035c56 100644
--- a/.agents/skills/hypit/references/playbooks/craft/production-gates.md
+++ b/.agents/skills/hypit/references/playbooks/craft/production-gates.md
@@ -87,7 +87,7 @@ visual QA.
to a `copy:Value` holding a performance direction is the defect this catches: the model receives no
words, invents its own, and the take sounds fluent and says nothing from the Script.
- It survives every structural check. `hypit check`, `preview-check` and `plan` all pass, because the
+ It survives every structural check. `hypit check`, `preview_check` and `plan` all pass, because the
graph is legal and complete — the prompt is a Text and the take consumes it. `whisperx:SemanticTake`
then fits the Segment's words onto whatever audio arrived rather than reporting that they differ, so
the Caption Track renders the Script over speech that shares none of it, and every downstream
@@ -117,8 +117,8 @@ visual QA.
and whether each Track contributes unique information.
- Treat `check` and `plan` as structural proofs only. They do not prove visual quality, real speech
alignment, Provider output quality, or factual correctness.
-- A reconstruction route may have compared these Tracks against a reference before this gate. That
- comparison runs on renders made from the Source's values with no SemanticTrack behind them, so it
+- A reconstruction route has compared these Tracks against a reference before this gate. That
+ comparison runs on renders made from the Source's values over a stand-in SemanticTake, so it
settles how a Track looks and leaves everything this gate is about — timing against real speech,
drift after a recompute, occlusion between Tracks that were rendered separately — still to be
measured here. Review them against the real SemanticTrack whatever was compared earlier.
@@ -131,7 +131,7 @@ visual QA.
captions, overlays, transitions, audio density, claims, and CTA as one program.
- **Measure the delivery's own speech against the Script.** An agent reads pictures and cannot hear,
so "listen and verify dialogue" above resolves to nothing on its own, and a take whose spoken words
- came from somewhere other than the Script passes `check`, `plan`, `preview-check` and both
+ came from somewhere other than the Script passes `check`, `plan`, `preview_check` and both
measurements below without a mark. Transcribe what was delivered and read it against the words the
Script holds:
diff --git a/.agents/skills/hypit/references/preview.md b/.agents/skills/hypit/references/preview.md
index 9cf86984..8dc64b0a 100644
--- a/.agents/skills/hypit/references/preview.md
+++ b/.agents/skills/hypit/references/preview.md
@@ -12,17 +12,17 @@ a new package with a bad schedule, a target that is not an output, a Film with n
composition. Find that now, not on the author's screen:
```bash
-# from the repository root: tsx is the repository's dependency
-node --import tsx .agents/skills/hypit/scripts/preview-check.mjs path/to/build.svrun
+# from the repository root: it reads the installed packages from the working directory
+hypit-reference-video-tools preview_check path/to/build.svrun
```
It takes the Run Source, not the Author SVML — Studio's unit of work is the Run, and it reads the
`.svml` back out of it.
-It exits non-zero when the graph itself is wrong, and it names what refused — a target that is not a
-Film or Render output of the current SVML, a Film with no traceable composition, a Film with no
-`SemanticTake` / Speech Track chain. This is not a guessing problem: the error says what is wrong, and
-you repair that. A graph that does not trace is not done, and **every failure it reports must be
+It reports `"sound": false` when the graph itself is wrong, and it names what refused — a target that
+is not a Film or Render output of the current SVML, a Film with no traceable composition, a Film with
+no `SemanticTake` / Speech Track chain. This is not a guessing problem: the error says what is wrong,
+and you repair that. A graph that does not trace is not done, and **every failure it reports must be
repaired until the check passes**, however many attempts that takes.
**One refusal is a pass, and it is the one you will see most.** A Source that declares its generation
@@ -30,13 +30,14 @@ rather than performing it leaves the closure waiting on Providers, and Studio re
closure before it will open. That is the expected state of a Source nobody has built yet, not a defect
in it. When every issue is `the Studio projection closure requires unresolved capabilities: …`, the
graph traced all the way to a Film and a semantic spine, and what remains is work a Provider has to
-do — the script prints the waiting capabilities and exits zero:
-
-```
-preview-check: the graph is sound, waiting on 6 capabilities.
- - @hypit/seedance@1#seedance-2-mini
- - @hypit/whisperx@1#whisperx-alignment
- ...
+do — the check stays sound and lists the waiting capabilities:
+
+```json
+{
+ "sound": true,
+ "summary": "the graph is sound, waiting on 6 capabilities.",
+ "awaiting": ["@hypit/seedance@1#seedance-2-mini", "@hypit/whisperx@1#whisperx-alignment"]
+}
```
Any other refusal means the graph is wrong and no amount of generation will fix it.
@@ -73,7 +74,7 @@ Each has its own command, and both are shared by every package.
own Canvas:
```bash
-node --import tsx .agents/skills/hypit/scripts/render-previews.mjs packages/<name>
+hypit-reference-video-tools render_previews packages/<name>
```
Which element draws which file comes from the Manifest's naming: a Surface tagged `Track` declares
@@ -86,7 +87,7 @@ component holding a picture rather than a placeholder.
**The comparison render** has one command too:
```bash
-node --import tsx .agents/skills/hypit/scripts/render-element.mjs projects/<name>/build.svrun \
+hypit-reference-video-tools render_element projects/<name>/build.svrun \
--element <id> --segment <id>|--selection <id> --out <path>.mp4
```
@@ -94,7 +95,7 @@ It reads the Canvas, the Recipes, the Script and the bindings out of the Source;
speech the Build has yet to synthesize using the Source's own `estimate:Speech`, so the window
lengths are the ones the Source already ordered its generations with; mocks every declared generation
with `make-placeholder` at the Canvas's size; and drives each package's Producer through the same
-Studio projection `preview-check` traces, with no Provider installed. The mocks and the stand-in takes
+Studio projection `preview_check` traces, with no Provider installed. The mocks and the stand-in takes
live in a derived Run under the project's `.hypit/`, never in the Source.
Name the window in words. `--segment` and `--selection` take a Script name rather than a timestamp,
diff --git a/.agents/skills/hypit/references/reconstruction/final-sources.md b/.agents/skills/hypit/references/reconstruction/final-sources.md
index 4cafab10..af91be15 100644
--- a/.agents/skills/hypit/references/reconstruction/final-sources.md
+++ b/.agents/skills/hypit/references/reconstruction/final-sources.md
@@ -52,8 +52,8 @@ loop's two-attempt ceiling: a graph that does not trace is not a difference to w
is not done.
One thing to expect here rather than to debug: a route that declares its generation instead of
-performing it leaves the closure waiting on Providers, so `preview-check` reporting only
-`unresolved capabilities` and exiting zero **is the pass**, and is the state every reconstruction is
+performing it leaves the closure waiting on Providers, so `preview_check` reporting only
+`unresolved capabilities` and staying sound **is the pass**, and is the state every reconstruction is
in when its sources are first written.
Fix package resolution and package implementation before repairing source use. Continue until all
@@ -61,6 +61,6 @@ three files are accepted. Do not create `check_svml_project` or another wrapper.
Accepted checks end the structural work, not the reconstruction. Every element you authored still has
to be rendered and compared against the reference under `reconstruction-loop.md`, and that work ends
-on `reconstruction-check` (`index.md` holds the command), which refuses to pass while any
-locally-drawn element has never been compared. It needs a prepared reference; when several are
-prepared it takes `--reference-id <id>`.
+on `reconstruction_check` (`index.md` holds the command), which refuses to pass while any drawing
+element has never been compared. It needs a prepared reference; when several are prepared it takes
+`--reference-id <id>`.
diff --git a/.agents/skills/hypit/references/reconstruction/index.md b/.agents/skills/hypit/references/reconstruction/index.md
index 0d43823f..3d1d754e 100644
--- a/.agents/skills/hypit/references/reconstruction/index.md
+++ b/.agents/skills/hypit/references/reconstruction/index.md
@@ -182,18 +182,18 @@ reading them half an hour before they matter, with a dozen other files in betwee
trigger worded around a package's catalogue preview fires too early, before any Source exists to
read values from.
-This route ends on a command rather than on a judgement that the work looks done. Every element a
-project-local package draws must have been compared against the reference at least once, and that is
-checkable:
+This route ends on a command rather than on a judgement that the work looks done. Every element the
+Source places that draws a Track must have been compared against the reference at least once, and
+that is checkable:
```text
-node --import tsx .agents/skills/hypit/scripts/reconstruction-check.mjs projects/<name>/build.svrun
+hypit-reference-video-tools reconstruction_check projects/<name>/build.svrun
```
-It names each element that has never been compared and the command that compares it, and exits
-non-zero until none are left. It asks for participation rather than convergence — `reconstruction-loop.md`
-is deliberately bounded and may stop with visible differences remaining — so an element compared once
-and stopped at its ceiling passes, and an element nobody looked at does not.
+It names each element that has never been compared and the command that compares it, and reports
+`"passed": false` until none are left. It asks for participation rather than convergence —
+`reconstruction-loop.md` is deliberately bounded and may stop with visible differences remaining — so
+an element compared once and stopped at its ceiling passes, and an element nobody looked at does not.
The same command settles one thing about the picture that a Build would otherwise be the first to
show: it reads each timed picture's appearance Recipe and refuses a `playback` left at its default,
@@ -201,18 +201,18 @@ which draws generated material once and then draws nothing for the rest of the w
`../playbooks/craft/generated-dependencies.md` says what to set and why the material's length cannot
be relied on.
-The script uses a prepared reference, and how it picks which one is worth knowing before it is run:
+It uses a prepared reference, and how it picks which one is worth knowing before it is run:
- exactly one reference is prepared → it uses that one;
-- several are prepared → it demands `--reference-id <id>`, and without it exits 2;
-- none → it exits 2 telling you to run `prepare_reference` first.
+- several are prepared → it demands `--reference-id <id>`, and refuses without it;
+- none → it refuses, telling you to run `prepare_reference` first.
A comparison run without `--element` is not credited to any element, and a misspelled `--element`
-credits nothing either — the script reports logged element names that do not exist in the Source. A
-project that places no `@hypit/local-*` element passes with nothing to require: the Tracks that
-installed vocabulary draws carry authored values this gate does not demand — timed against the real
-SemanticTrack none of them renders before a Build — and they are listed as deferred rather than
-required, to be checked at the delivery gates.
+credits nothing either — it reports logged element names that do not exist in the Source. Which
+package draws an element makes no difference to the requirement: a Track from installed vocabulary
+carries authored values exactly as a project-local one does — a caption Style's size, colour and
+placement — and `render_element` stands in for the speech, so it renders before a Build like any
+other. A project that places no drawing element passes with nothing to require.
Paths above are relative to this file's directory. Do not skip a file because the task looks like a
familiar video format.
diff --git a/.agents/skills/hypit/references/reconstruction/reconstruction-loop.md b/.agents/skills/hypit/references/reconstruction/reconstruction-loop.md
index c8254d4c..21593093 100644
--- a/.agents/skills/hypit/references/reconstruction/reconstruction-loop.md
+++ b/.agents/skills/hypit/references/reconstruction/reconstruction-loop.md
@@ -5,16 +5,16 @@ reference. A newly written package can resolve, activate, decode and pass every
something the reference never contained. Close that gap deliberately.
This loop is about how an element *looks* against the reference, and it is bounded. Whether an
-element is *wired at all* is a different gate with a different rule: `preview-check` (in
+element is *wired at all* is a different gate with a different rule: `preview_check` (in
`../preview.md`) must pass before this loop is even reached, and its failures are repaired
without any attempt ceiling. A graph that does not trace is not a difference to weigh; it is work
that is not done.
-Note what that gate covers: `preview-check` proves the graph is wired, not that every track draws.
+Note what that gate covers: `preview_check` proves the graph is wired, not that every track draws.
Nothing is handed to a Producer until the Build runs, so a Producer that refuses the media it
receives surfaces there rather than here.
-The difference between the two gates is what each reports. `preview-check` names the graph failure —
+The difference between the two gates is what each reports. `preview_check` names the graph failure —
the target that does not trace, the chain that is missing — so its repairs are not guessing. This
loop names the appearance difference: `compare_reconstruction` sends the rendered element and the
matching stretch of the reference to an observer and returns what differs in words, and a repair aims
@@ -54,7 +54,7 @@ draws which.
One command produces it, and it is not written per package:
```
-node --import tsx .agents/skills/hypit/scripts/render-element.mjs projects/<name>/build.svrun \
+hypit-reference-video-tools render_element projects/<name>/build.svrun \
--element <id> --segment <id>|--selection <id> --out <path>.mp4
```
@@ -82,7 +82,7 @@ it may be media slots the Source declares as generations. Render them as mocks r
them out: a missing base is not a neutral background, it is black, and text that is legible on black
can be illegible on the picture that will replace it.
-`render-element.mjs` does this itself. It finds every generation the Source declares — the takes, the
+`render_element` does this itself. It finds every generation the Source declares — the takes, the
stills, the slot contents — calls `make-placeholder` for each at the Canvas's own size, and declares
them in a derived Run under the project's `.hypit/`. Never `hypit image`, which pays for a generation
the video will not reuse, and never a placeholder drawn by a script written for the occasion.
@@ -99,7 +99,7 @@ declared-but-unbuilt generations, and to compare only what the element itself dr
costs one clause and saves the mock being reported as a difference every round.
A mock lives only in this render. It is never written into the Source, and no gate reads it: the
-`playback` check in `reconstruction-check` reads the Source's Recipes, so a mock cannot be mistaken
+`playback` check in `reconstruction_check` reads the Source's Recipes, so a mock cannot be mistaken
for coverage.
### Compare the whole shot, against every shot that shows the element
@@ -273,18 +273,19 @@ waits for in `../playbooks/craft/production-gates.md`:
- **every generated picture and take** — the images and the shots a Provider has still to make, at
Gate 1 and Gate 2;
-- **the authored values on installed vocabulary** — a caption Style's size, colour and placement, a
- Media Item's frame, a Typography Track's copy, at Gate 3 against the real SemanticTrack;
+- **the timing of every Track** — this route compares each one against a stand-in SemanticTake, so
+ how a Caption, Media or Typography Track sits against the speech that is finally delivered is
+ measured at Gate 3, against the real SemanticTrack;
- **whether the picture is continuous** — the frames nobody authored that `frame-coverage.md` is
about, at Gate 4, which measures them on the delivery. One inherited edge is settled before then:
- `reconstruction-check` reads each Recipe's `playback` and refuses a timed picture configured to
+ `reconstruction_check` reads each Recipe's `playback` and refuses a timed picture configured to
stop when its material runs out, which is the edge a generated take produces every time. The rest
of them — a window that starts late, a blend whose frames are half-covered, a schedule inside a
component that stops between activations — are measured on the delivery;
- **whether the delivery says the Script's words** — measured at Gate 4 by transcribing the finished
video, since a take generated from a prompt that lost its dialogue passes every gate before it.
-`reconstruction-check` is the mechanical half of this: it names the elements that were never compared
+`reconstruction_check` is the mechanical half of this: it names the elements that were never compared
and the timed pictures configured to empty their windows, and refuses to pass while either remains.
It cannot name what a Build has not produced yet, which is why
this list is stated rather than computed.
diff --git a/.agents/skills/hypit/references/reconstruction/workflow.md b/.agents/skills/hypit/references/reconstruction/workflow.md
index 008fc360..3a1870cb 100644
--- a/.agents/skills/hypit/references/reconstruction/workflow.md
+++ b/.agents/skills/hypit/references/reconstruction/workflow.md
@@ -38,16 +38,16 @@ list_svml_packages
→ read final-sources.md, then author complete main.svml, recipes.svs, build.svrun
and the hypit.runtime.json that binds every capability they demand
→ use existing checks and repair until legal
-→ run preview-check (final-sources.md) and repair until the graph traces —
+→ run preview_check (final-sources.md) and repair until the graph traces —
this has no attempt ceiling; a target Studio cannot trace is not done.
Waiting on unrun Providers is a pass, not a failure
→ read reconstruction-loop.md, then for each authored element: render it with
- render-element.mjs, which reads the sources and mocks the layers a Build has
+ render_element, which reads the sources and mocks the layers a Build has
not made, and compare it against every shot the reference shows it in before
repairing anything
→ repair against the differences that round returned, within the ceilings
-→ run reconstruction-check (index.md) and keep going until it passes; it names
- every locally-drawn element that has never been compared, and every timed
+→ run reconstruction_check (index.md) and keep going until it passes; it names
+ every drawing element that has never been compared, and every timed
picture whose Recipe leaves playback at its default. When more than one
reference is prepared it needs --reference-id <id>
```
@@ -185,7 +185,7 @@ that shot's duration, so both grids sample alike.
`--element` names the reconstructed element the render draws. It never reaches the observer — the
comparison stays as blind as it is without it — and is written to the reference's `comparisons.jsonl`
-so `reconstruction-check` can tell an element that was looked at from one that never was. A
+so `reconstruction_check` can tell an element that was looked at from one that never was. A
comparison run without it is not credited to any element.
The reference has one observer for its whole life, and this command goes through the same one that
diff --git a/.agents/skills/hypit/scripts/preview-check.mjs b/.agents/skills/hypit/scripts/preview-check.mjs
deleted file mode 100644
index 6f8c9ea4..00000000
--- a/.agents/skills/hypit/scripts/preview-check.mjs
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/env node
-/**
- * Preview-check a reconstruction before it is delivered.
- *
- * `pnpm hypit check` proves a Source is legal; it proves nothing about whether
- * the tracks it declares can actually be built. A track that fails here fails
- * the same way when the author opens Studio, so find out now.
- *
- * Usage: node --import tsx .agents/skills/hypit/scripts/preview-check.mjs <build.svrun> [<hypit.runtime.json>]
- * Exit: 0 when the graph is sound — either Studio opened and every Track
- * resolved, or the only thing missing is Providers that have not run.
- * 1 when the graph itself is wrong, naming what refused and why.
- *
- * The argument is the Run Source, not the Author SVML. Studio's unit of work is
- * the Run — it reads the Author SVML back out of it — so a check that took the
- * `.svml` would be checking something Studio never opens.
- *
- * Studio names what it cannot resolve and stops, so preflight throwing is itself
- * the report rather than something to inspect around. Two kinds of issue come
- * back, and they mean opposite things. An unresolved *capability* means the
- * graph traced all the way to a Film and a semantic spine, and what remains is
- * work a Provider has to do — the ordinary state of a Source that declares its
- * generation rather than performing it. Every other issue means the graph is
- * wrong and no amount of generation will fix it. Only the second kind fails.
- * `StudioPreflightError` carries `issues` as an array so the two can be told
- * apart rather than matched out of one joined message.
- *
- * Run it from the repository root. `tsx` is the repository's own dependency, so
- * a working directory outside the repository fails to resolve it before this
- * script runs at all — the error names `tsx`, not the source being checked.
- */
-import { dirname, resolve } from "node:path";
-
-// The script lives under `.agents/`; resolve Studio from the repo root.
-// Stay in URL space the whole way: a specifier built from a filesystem path is read as a URL, so
-// on Windows the drive letter becomes a scheme and the import fails before it resolves anything.
-const studio = (name) => new URL(`../../../../packages/studio/src/${name}`, import.meta.url).href;
-const { openStudioArchive } = await import(studio("archive.js"));
-const { loadStudioDomain } = await import(studio("domain.js"));
-const { loadStudioRun } = await import(studio("run.js"));
-const { readStudioSession } = await import(studio("session.js"));
-const { inspectStudioRun } = await import(studio("studio-preflight.js"));
-
-const runArgument = process.argv[2];
-if (runArgument === undefined) {
- console.error("usage: preview-check.mjs <build.svrun> [<hypit.runtime.json>]");
- process.exit(2);
-}
-const invokedFrom = process.env.INIT_CWD ?? process.cwd();
-const runPath = resolve(invokedFrom, runArgument);
-const runtimeArgument = process.argv[3];
-const runtimePath = runtimeArgument === undefined ? undefined : resolve(invokedFrom, runtimeArgument);
-const packageRoot = resolve(invokedFrom);
-const workspaceRoot = dirname(runPath);
-
-const domain = await loadStudioDomain({ run: runPath, workspaceRoot, packageRoot });
-const archive = await openStudioArchive(runtimePath, packageRoot);
-const AWAITING = "the Studio projection closure requires unresolved capabilities:";
-
-let session;
-let refusal;
-let awaiting;
-try {
- const run = await loadStudioRun({
- run: runPath,
- domain,
- ...(archive === undefined ? {} : { archive }),
- });
- // Preflight first, so an unopenable Run is reported as the refusal it is
- // rather than as whatever the build happens to fail on afterwards.
- inspectStudioRun(run.source, run);
- session = await readStudioSession({
- domain,
- run,
- ...(archive === undefined ? {} : { archive }),
- revision: 0,
- });
-} catch (error) {
- const issues = Array.isArray(error?.issues) ? error.issues : undefined;
- if (issues !== undefined && issues.every((issue) => issue.startsWith(AWAITING))) {
- awaiting = issues.flatMap((issue) => issue.slice(AWAITING.length).split(",").map((c) => c.trim()));
- } else {
- refusal = error instanceof Error ? error.message : String(error);
- }
-} finally {
- // Close before reporting: `process.exit` in a `try` skips the `finally`, and
- // a runtime archive left open outlives the check.
- await archive?.close();
-}
-
-if (refusal !== undefined) {
- console.log(JSON.stringify({ refused: refusal }, null, 2));
- process.exit(1);
-}
-
-if (awaiting !== undefined) {
- // The graph traced all the way to a Film and a semantic spine; what is left is
- // work a Provider has to do. That is a pass for this gate, and the delivery
- // measurements happen on the real Build either way.
- const noun = awaiting.length === 1 ? "capability" : "capabilities";
- console.log(`preview-check: the graph is sound, waiting on ${awaiting.length} ${noun}.`);
- for (const capability of awaiting) console.log(` - ${capability}`);
- process.exit(0);
-}
-
-const problems = [];
-for (const track of session.snapshot.tracks) {
- const { status, errors, output } = track.provenance;
- if (errors.length > 0) problems.push({ track: track.label, errors });
- else if (status === "unresolved") problems.push({ track: track.label, unresolved: output });
-}
-
-if (problems.length === 0) {
- console.log(`preview-check: every Track resolved (${session.snapshot.tracks.length}).`);
- process.exit(0);
-}
-for (const item of problems) console.log(JSON.stringify(item, null, 2));
-process.exit(1);
diff --git a/.agents/skills/hypit/scripts/reconstruction-check.mjs b/.agents/skills/hypit/scripts/reconstruction-check.mjs
deleted file mode 100644
index b5aeca81..00000000
--- a/.agents/skills/hypit/scripts/reconstruction-check.mjs
+++ /dev/null
@@ -1,291 +0,0 @@
-#!/usr/bin/env node
-/**
- * Report what the route can still settle after the Source is written and before a Build runs: which
- * reconstructed elements have never been compared against the reference, and which timed pictures are
- * configured to stop before their window ends.
- *
- * `preview-check` proves the graph is wired. It proves nothing about whether what the graph draws
- * resembles the reference video, and a Source can pass every structural check while a
- * project-local component draws something the reference never contained. Closing that gap is
- * `references/reconstruction/reconstruction-loop.md`, which is prose, and prose is what a route
- * skips silently. This is the same requirement as a command with an exit code.
- *
- * Usage: node --import tsx .agents/skills/hypit/scripts/reconstruction-check.mjs <build.svrun> [--reference-id <id>]
- * Exit: 0 when every locally-drawn element has at least one recorded comparison.
- * 1 when one or more have none, naming each and the command that compares it.
- * 2 on a usage or discovery error.
- *
- * What it checks is **participation, not convergence**. The loop is deliberately bounded and may
- * stop with visible differences remaining, so requiring convergence here would contradict it. An
- * element that was compared once and stopped at its ceiling passes; an element nobody ever looked
- * at does not.
- *
- * Only elements drawn by a `@hypit/local-*` package are required. Installed vocabulary is already
- * reviewed; a package written for this one video is the thing with no other reader.
- *
- * A comparison counts whether its answer came back in-band (`complete`, the gemini observer) or was
- * handed out to be answered by looking (`pending`, the agent observer); only `failed` is not a
- * comparison. The gate cannot judge whether the shot an element was compared against actually showed
- * it, so the shots are printed for a reader, and a lone comparison is called out rather than assumed
- * meaningful.
- *
- * A project that places no locally-drawn element passes with nothing to require — installed-vocabulary
- * Tracks are listed as deferred rather than demanded, since none renders before a Build without a
- * fixture SemanticTrack.
- */
-import { readFile, readdir } from "node:fs/promises";
-import { dirname, join, resolve } from "node:path";
-
-const packageLoader = new URL("../../../../packages/package-loader-node/src/index.ts", import.meta.url).href;
-const { loadNodePackageSelection } = await import(packageLoader);
-
-const runArgument = process.argv[2];
-if (runArgument === undefined || runArgument.startsWith("--")) {
- console.error("usage: reconstruction-check.mjs <build.svrun> [--reference-id <id>]");
- process.exit(2);
-}
-const flagIndex = process.argv.indexOf("--reference-id");
-const suppliedReference = flagIndex === -1 ? undefined : process.argv[flagIndex + 1];
-
-const invokedFrom = process.env.INIT_CWD ?? process.cwd();
-const runPath = resolve(invokedFrom, runArgument);
-const packageRoot = resolve(invokedFrom);
-
-function fail(message) {
- console.error(`reconstruction-check: ${message}`);
- process.exit(2);
-}
-
-const runSource = await readFile(runPath, "utf8").catch(() => fail(`cannot read ${runPath}`));
-const authorMatch = /<author\s+source="([^"]+)"/u.exec(runSource);
-if (authorMatch === null) fail(`${runArgument} declares no <author source="…"/>`);
-const svmlPath = resolve(dirname(runPath), authorMatch[1]);
-const svml = await readFile(svmlPath, "utf8").catch(() => fail(`cannot read ${svmlPath}`));
-
-// Every package this Source imports, and which of them were written for this project.
-const imports = [...svml.matchAll(/<import\s+as="([^"]+)"\s+from="(@hypit\/[^"@]+)@\d+"/gu)]
- .map(([, alias, specifier]) => ({ alias, specifier, local: specifier.startsWith("@hypit/local-") }));
-if (imports.length === 0) {
- console.log("reconstruction-check: the Source imports no package; nothing to compare.");
- process.exit(0);
-}
-
-// Which of their Surfaces draw a Track. A Style Surface publishes a Style and draws nothing, so
-// requiring a comparison of it would be asking for a picture that does not exist.
-const specifiers = [...new Set(imports.map((item) => item.specifier))];
-const loaded = await loadNodePackageSelection(specifiers, packageRoot).catch(() => []);
-const drawingTags = new Map();
-for (const pack of loaded) {
- for (const facet of pack.contribution.hostFacets ?? []) {
- const surface = facet.implementation;
- const draws = (surface.outputs ?? []).some((output) =>
- output.module?.name === "@hypit/composition" && (output.name === "VisualTrack" || output.name === "AudioTrack"));
- if (draws) drawingTags.set(`${pack.specifier}#${surface.tag}`, true);
- }
-}
-
-// Every use of one of those tags, by the id the Source gave it.
-const drawn = [];
-for (const { alias, specifier, local } of imports) {
- const pattern = new RegExp(`<${alias}:([A-Za-z][A-Za-z0-9]*)\\b[^>]*?\\bid="([^"]+)"`, "gu");
- for (const [, tag, id] of svml.matchAll(pattern)) {
- if (!drawingTags.has(`${specifier}#${tag}`)) continue;
- if (!drawn.some((item) => item.id === id)) drawn.push({ id, tag, alias, specifier, local });
- }
-}
-
-// A project-local package is required here: it was written for this one video and nothing else has
-// read it. A Track from installed vocabulary carries authored values too — a caption Style's size,
-// colour and placement are as unverified as a new package's — but it cannot be rendered before a
-// Build without a fixture SemanticTrack, so it is reported rather than demanded.
-const elements = drawn.filter((item) => item.local);
-const deferred = drawn.filter((item) => !item.local);
-
-// ---- Timed pictures that stop before their window ends ----
-//
-// A generated take is asked for a whole number of seconds, and the window it has to fill comes from
-// speech the same Build synthesizes. The two lengths are arrived at separately and do not meet: the
-// estimate rounds, and the voice that finally speaks is not the voice the estimate predicted. So the
-// material is routinely shorter than the window it was made for, by anything from a rounding
-// remainder to a couple of seconds.
-//
-// What happens then is decided by one Recipe key. `playback` defaults to `once-start`, which draws
-// the material once and then draws nothing at all — `sampling.ts` emits no segment for the remainder,
-// so those frames fall through to whatever is beneath. Under a full-frame base that is the Film
-// background, which is black. `hold-start` pins the last frame for the rest of the window instead,
-// `loop-start` repeats, and `stretch` retimes to fit; any of the three fills it.
-//
-// This is `frame-coverage.md`'s inherited edge — "a generated take, which ends where its material
-// ends rather than where the shot should" — in the one form the route can settle before a Build, from
-// the Source and its Recipe sheets alone.
-async function playbackReport() {
- // Every Recipe body the Source can name, by the alias its sheet was imported under.
- const sheets = new Map();
- for (const [, alias, source] of svml.matchAll(/<import\s+as="([^"]+)"\s+source="([^"]+\.svs)"/gu)) {
- const text = await readFile(resolve(dirname(svmlPath), source), "utf8").catch(() => undefined);
- if (text === undefined) continue;
- const recipes = new Map();
- for (const [, name, body] of text.matchAll(/([A-Za-z0-9_.-]+)\s*\{([^}]*)\}/gu)) recipes.set(name, body);
- sheets.set(alias, recipes);
- }
-
- // Which Normalize ids carry a picture. A take normalized with `video="none"` is a voice and has no
- // window to fill.
- const moving = new Set();
- for (const [, attributes] of svml.matchAll(/<pipeline:Normalize\b([^>]*?)\/?>/gsu)) {
- const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
- const video = /\bvideo="([^"]+)"/u.exec(attributes)?.[1];
- if (id !== undefined && video !== undefined && video !== "none") moving.add(id);
- }
-
- // Which aliases belong to a package that draws. Plenty of elements consume a normalized media
- // without placing it — `whisperx:SemanticTake` reads one to align speech against it and puts no
- // picture on the Canvas, so it has no window to fill and no occupancy to choose. Requiring the
- // alias to come from a package with a Track that outputs a VisualTrack keeps those out, and keeps
- // the Items and Sequences written inside such a Track in, without this needing to know their tags.
- const draws = new Set(imports
- .filter(({ specifier }) => [...drawingTags.keys()].some((key) => key.startsWith(`${specifier}#`)))
- .map(({ alias }) => alias));
-
- // Every element that places one of those pictures, and what its Recipe says to do with a window the
- // material does not fill.
- const running = [];
- for (const [, tag, attributes] of svml.matchAll(/<([a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9]*)\b([^>]*?)\/?>/gsu)) {
- if (!draws.has(tag.slice(0, tag.indexOf(":")))) continue;
- const media = /\bmedia=\{([A-Za-z0-9_-]+)\.media\}/u.exec(attributes)?.[1];
- if (media === undefined || !moving.has(media)) continue;
- const appearance = /\bappearance=\{([A-Za-z0-9_-]+)\.([A-Za-z0-9_.-]+)\}/u.exec(attributes);
- const body = appearance === null ? undefined : sheets.get(appearance[1])?.get(appearance[2]);
- const playback = body === undefined ? undefined : /\bplayback\s*:\s*([A-Za-z-]+)/u.exec(body)?.[1];
- if (playback !== undefined && playback !== "once-start" && playback !== "once-end") continue;
- running.push({
- id: /\bid="([^"]+)"/u.exec(attributes)?.[1] ?? tag,
- tag,
- recipe: appearance === null ? "no appearance Recipe" : `${appearance[1]}.${appearance[2]}`,
- playback: playback ?? "once-start, by default",
- });
- }
- return running;
-}
-
-const running = await playbackReport();
-
-if (elements.length === 0 && running.length === 0) {
- console.log("reconstruction-check: no locally-drawn element is placed in the Source; nothing to require.");
- if (deferred.length > 0) reportDeferred();
- process.exit(0);
-}
-
-// The Source does not name the reference it reconstructs, so a single prepared reference is used
-// when there is exactly one and named explicitly when there is more than one.
-const referenceRoot = join(packageRoot, ".hypit", "reference-video-tools");
-const prepared = (await readdir(referenceRoot, { withFileTypes: true }).catch(() => []))
- .filter((entry) => entry.isDirectory()).map((entry) => entry.name);
-let reference = suppliedReference;
-if (reference === undefined) {
- if (prepared.length === 1) reference = prepared[0];
- else if (prepared.length === 0) fail(`no prepared reference under ${referenceRoot}; run prepare_reference first`);
- else fail(`${prepared.length} prepared references; pass --reference-id (${prepared.join(", ")})`);
-}
-if (!prepared.includes(reference)) fail(`reference ${reference} is not prepared under ${referenceRoot}`);
-
-const logPath = join(referenceRoot, reference, "comparisons.jsonl");
-const log = (await readFile(logPath, "utf8").catch(() => ""))
- .split("\n").filter((line) => line.trim().length > 0)
- .map((line) => { try { return JSON.parse(line); } catch { return undefined; } })
- // A comparison counts when it was performed. On the gemini observer the answer comes back in-band
- // as `complete`; on the agent observer it is handed out as `pending` and answered by looking at the
- // images, which is participation too. Only `failed` means nothing was compared.
- .filter((entry) => entry !== undefined && (entry.status === "complete" || entry.status === "pending"));
-
-// Which shots each element was compared against, in order. The gate cannot judge whether a shot was
-// the right one to compare against — it does not know what the element draws — so it prints them and
-// lets a reader notice a component compared against a shot that never showed it.
-const rounds = new Map();
-for (const entry of log) {
- if (entry.element === undefined) continue;
- const seen = rounds.get(entry.element) ?? [];
- seen.push(entry.shot_id);
- rounds.set(entry.element, seen);
-}
-
-const never = elements.filter((element) => (rounds.get(element.id) ?? []).length === 0);
-const unlabelled = log.filter((entry) => entry.element === undefined).length;
-// A misspelled --element is otherwise silent: the comparison happens, the log grows, and the element
-// it was meant for stays at zero for ever.
-const known = new Set(drawn.map((item) => item.id));
-const unknown = [...new Set([...rounds.keys()].filter((id) => !known.has(id)))];
-
-for (const element of elements) {
- const shots = rounds.get(element.id) ?? [];
- const state = shots.length === 0
- ? "never compared"
- : `${shots.length} comparison${shots.length === 1 ? "" : "s"} against ${[...new Set(shots)].join(", ")}`;
- console.log(` ${element.alias}:${element.tag} id=${element.id}\n ${state}`);
- // The gate cannot judge whether the shot chosen actually showed the element, so a lone comparison
- // is called out for a reader to confirm rather than silently accepted.
- if (shots.length === 1) {
- console.log(" (single comparison — confirm this shot shows the element, not a look-alike)");
- }
-}
-
-function reportDeferred() {
- console.log("");
- console.log(` ${deferred.length} Track${deferred.length === 1 ? "" : "s"} from installed vocabulary carry authored values this gate does not require:`);
- for (const item of deferred) console.log(` ${item.alias}:${item.tag} id=${item.id}`);
- console.log(" Their Styles, placements and windows are as unauthored-until-checked as a new package's,");
- console.log(" and none of them renders before a Build without a fixture SemanticTrack. They are checked");
- console.log(" against the delivery under playbooks/craft/production-gates.md Gate 3 and Gate 4.");
-}
-
-if (unknown.length > 0) {
- console.log("");
- console.log(` ${unknown.length} logged element name${unknown.length === 1 ? " does" : "s do"} not exist in the Source: ${unknown.join(", ")}`);
- console.log(" A misspelled --element credits nothing; the element it was meant for is still at zero.");
-}
-if (unlabelled > 0) {
- console.log("");
- console.log(` ${unlabelled} comparison${unlabelled === 1 ? " was" : "s were"} recorded without --element and cannot be credited to one.`);
-}
-if (deferred.length > 0) reportDeferred();
-
-if (running.length > 0) {
- console.log("");
- console.log(` ${running.length} timed picture${running.length === 1 ? " draws" : "s draw"} nothing once the material ends:`);
- for (const item of running) console.log(` ${item.tag} id=${item.id} — ${item.recipe}, playback ${item.playback}`);
-}
-
-if (never.length === 0 && running.length === 0) {
- console.log("");
- console.log(`reconstruction-check: every locally-drawn element has been compared (${elements.length}), and every timed picture fills its window.`);
- process.exit(0);
-}
-
-console.log("");
-if (never.length > 0) {
- console.log(`reconstruction-check: ${never.length} of ${elements.length} elements have never been compared.`);
- console.log("");
- console.log("Read .claude/skills/hypit/references/reconstruction/reconstruction-loop.md, then for each:");
- console.log("render the element as the Source configures it, mock the layers a Build has not made,");
- console.log("and compare the whole shot blind — one comparison per shot the reference shows it in.");
- console.log("");
- for (const element of never) {
- console.log(` hypit-reference-video-tools compare_reconstruction --reference-id ${reference} \\`);
- console.log(` --shot-id <each shot that shows ${element.id}> \\`);
- console.log(` --video <rendered clip>.mp4 --element ${element.id}`);
- }
-}
-if (running.length > 0) {
- if (never.length > 0) console.log("");
- console.log(`reconstruction-check: ${running.length} window${running.length === 1 ? "" : "s"} will empty before ${running.length === 1 ? "it ends" : "they end"}.`);
- console.log("");
- console.log("A generated take is ordered in whole seconds and its window is measured from speech the");
- console.log("Build has yet to synthesize, so the material is shorter than the window it fills more");
- console.log("often than not. Under a full-frame picture the remainder is the Film background, which");
- console.log("reads as a black gap; under a cutaway it is the layer beneath blinking through.");
- console.log("");
- console.log("Give each Recipe above a playback: hold-start to pin the last frame for the rest of the");
- console.log("window, loop-start to repeat, or stretch to retime. Read playbooks/craft/frame-coverage.md");
- console.log("on inherited edges before choosing — lengthening the material instead leaves the same edge.");
-}
-process.exit(1);
diff --git a/.agents/skills/hypit/scripts/render-element.mjs b/.agents/skills/hypit/scripts/render-element.mjs
deleted file mode 100644
index 40e906f1..00000000
--- a/.agents/skills/hypit/scripts/render-element.mjs
+++ /dev/null
@@ -1,391 +0,0 @@
-#!/usr/bin/env node
-/**
- * Render one element of a Source the way that Source configures it, without a Build and without a
- * Provider.
- *
- * `reconstruction-loop.md` compares a reconstructed element against the reference. What it must
- * compare is the element as this video places it — the Recipe values the Source passes, the Script
- * text it feeds, the windows it binds — because a Source can fill those with values that collide
- * while a package's catalogue preview, drawn from sample values, stays perfect. Producing that
- * picture by hand means transcribing values into a per-package harness, one line at a time, which is
- * how a caption system gets compared as a single line that has nothing to collide with.
- *
- * So this reads the values instead. Everything it needs is already written down:
- *
- * Canvas and Frames, Recipe values, bindings the Source
- * which elements share a window, in what order the Script's words, through their Selections
- * how long each Segment runs the Source's own `estimate:Speech`
- * the layers a Build has not made `make-placeholder`, sized from the Canvas
- *
- * The one thing missing before a Build is real speech, and `stand-in-takes.mjs` supplies a Segment
- * skeleton from the estimator the Source already trusts — the same numbers it ordered its takes
- * with, not a second clock. Those takes enter through `<value>` and `<satisfy>`, the mechanism
- * `examples/all-components-preview` uses to open in Studio without spending anything, so nothing
- * here is a private back door into the graph.
- *
- * What this settles: which elements are on screen together, where each sits, at what size, weight and
- * colour. What it does not: real timing, which waits for `playbooks/craft/production-gates.md` Gate 3.
- *
- * Usage:
- * node --import tsx .agents/skills/hypit/scripts/render-element.mjs <build.svrun> \
- * --element <id> --out <path.png|path.mp4> [--segment <id>] [--base <mock.mp4>]
- *
- * Exit: 0 having written --out. 1 when the element cannot be projected, naming what is unresolved.
- * 2 on a usage or discovery error.
- */
-import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
-import { spawnSync } from "node:child_process";
-import { createHash } from "node:crypto";
-import { createRequire } from "node:module";
-import { cpus } from "node:os";
-import { dirname, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const studio = (name) => new URL(`../../../../packages/studio/src/${name}`, import.meta.url).href;
-const { openStudioArchive } = await import(studio("archive.js"));
-const { loadStudioDomain } = await import(studio("domain.js"));
-const { loadStudioRun } = await import(studio("run.js"));
-const { preview } = await import(studio("programme.js"));
-const { inspectStudioRun } = await import(studio("studio-preflight.js"));
-const { compileHyperframesDocument, materializeHyperframesHtml } = await import(new URL("../../../../packages/hyperframes/src/document.ts", import.meta.url).href);
-const { standInTakes } = await import(new URL("./stand-in-takes.mjs", import.meta.url).href);
-
-function fail(message, code = 2) {
- console.error(`render-element: ${message}`);
- process.exit(code);
-}
-
-function blobRef(bytes, mediaType) {
- return { kind: "blob", digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, size: bytes.byteLength, mediaType };
-}
-
-/** 48 kHz mono PCM silence, written by hand so the mock needs no encoder and lands on exact bytes. */
-function silentWav(sampleFrames) {
- const data = Math.max(2, sampleFrames * 2);
- const buffer = Buffer.alloc(44 + data);
- buffer.write("RIFF", 0);
- buffer.writeUInt32LE(36 + data, 4);
- buffer.write("WAVEfmt ", 8);
- buffer.writeUInt32LE(16, 16);
- buffer.writeUInt16LE(1, 20);
- buffer.writeUInt16LE(1, 22);
- buffer.writeUInt32LE(48_000, 24);
- buffer.writeUInt32LE(48_000 * 2, 28);
- buffer.writeUInt16LE(2, 32);
- buffer.writeUInt16LE(16, 34);
- buffer.write("data", 36);
- buffer.writeUInt32LE(data, 40);
- return buffer;
-}
-
-const argv = process.argv.slice(2);
-const runArgument = argv[0];
-if (runArgument === undefined || runArgument.startsWith("--")) {
- fail("usage: render-element.mjs <build.svrun> --element <id> --out <path> [--segment <id>] [--base <mock.mp4>]");
-}
-const flag = (name) => {
- const index = argv.indexOf(`--${name}`);
- return index === -1 ? undefined : argv[index + 1];
-};
-const element = flag("element") ?? fail("--element is required");
-const out = flag("out") ?? fail("--out is required");
-
-const invokedFrom = process.env.INIT_CWD ?? process.cwd();
-const runPath = resolve(invokedFrom, runArgument);
-// The repository, found from this file rather than from wherever it was called. Deriving it from the
-// working directory means the command works from the root and crashes anywhere else, on a missing
-// module rather than on anything a reader could act on.
-const packageRoot = fileURLToPath(new URL("../../../../", import.meta.url));
-const projectRoot = dirname(runPath);
-const outPath = resolve(invokedFrom, out);
-
-const runSource = await readFile(runPath, "utf8").catch(() => fail(`cannot read ${runPath}`));
-const authorMatch = /<author\s+source="([^"]+)"/u.exec(runSource);
-if (authorMatch === null) fail(`${runArgument} declares no <author source="…"/>`);
-const svmlPath = resolve(projectRoot, authorMatch[1]);
-const svml = await readFile(svmlPath, "utf8").catch(() => fail(`cannot read ${svmlPath}`));
-
-// The Program's frame rate and the Canvas the render composes at, both read rather than assumed. A
-// harness that hard-codes either produces a picture at a geometry the reference never had.
-const clock = /<[a-z-]*:?Clock\b[^>]*?\bframe-rate="(\d+)"/su.exec(svml)?.[1]
- ?? /<time:Clock\b[^>]*?\bfps="(\d+)"/su.exec(svml)?.[1];
-const frameRate = Number(clock ?? 30);
-const canvasMatch = /<space:Canvas\b[^>]*?\bwidth="(\d+)"[^>]*?\bheight="(\d+)"/su.exec(svml);
-if (canvasMatch === null) fail("the Source declares no <space:Canvas width= height=/>");
-const canvas = { width: Number(canvasMatch[1]), height: Number(canvasMatch[2]) };
-
-// Which SemanticTake output belongs to which Segment, so each stand-in lands on the right one.
-const takeOutputs = new Map();
-for (const [, attributes] of svml.matchAll(/<whisperx:SemanticTake\b([^>]*?)\/?>/gsu)) {
- const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
- const segment = /\bsegment=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
- if (id !== undefined && segment !== undefined) takeOutputs.set(segment, id);
-}
-if (takeOutputs.size === 0) fail("the Source declares no whisperx:SemanticTake to stand in for");
-
-// What the Run already brings. A project Run declares nothing and everything is mocked; a package's
-// preview Run ships its own sample pictures, and those are carried across untouched so the catalogue
-// picture shows the component holding something rather than a placeholder.
-const alreadySatisfied = new Set([...runSource.matchAll(/<satisfy\s+output="([^"]+)"/gu)].map(([, output]) => output));
-const carried = [...runSource.matchAll(/^[ \t]*<(?:file|value|satisfy)\b[^>]*\/>[ \t]*$/gmu)].map(([line]) => line.trim());
-
-// The window is resolved before the stand-ins are built, so the program is only as long as the
-// stretch being looked at. Rendering the whole program to crop six seconds out of it is the
-// difference between a few seconds and a few minutes.
-const segmentArgument = flag("segment");
-const selectionArgument = flag("selection");
-const { takes, selections, frameCount: programFrames } = await standInTakes(svmlPath, frameRate, {
- ...(segmentArgument === undefined ? {} : { segment: segmentArgument }),
- ...(selectionArgument === undefined ? {} : { selection: selectionArgument }),
-});
-const framesBySegment = new Map(takes.map((item) => [item.segmentId, item.take.segment.endFrameExclusive]));
-// A Selection's window in frames, summed over the stand-in tokens it covers. This is the same word
-// span the Source binds to, carried into frames by the same estimate that sized the Segment.
-const framesBySelection = new Map();
-for (const { segmentId, take } of takes) {
- for (const token of take.tokens) framesBySelection.set(token.tokenId, token.endFrameExclusive - token.startFrame);
- framesBySelection.set(`segment:${segmentId}`, take.segment.endFrameExclusive);
-}
-
-/**
- * Every media a Build would have produced, and how long its window is. A speech take carries no
- * picture and a base take fills a Segment; a cutaway fills whatever its `during=` binds. Each becomes
- * a placeholder of the Canvas's own size, so the composite has the geometry the Source declares.
- */
-function mockedMedia() {
- const windows = new Map();
- for (const [, attributes] of svml.matchAll(/<whisperx:SemanticTake\b([^>]*?)\/?>/gsu)) {
- const media = /\bmedia=\{([A-Za-z0-9_-]+)\.media\}/u.exec(attributes)?.[1];
- const segment = /\bsegment=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
- if (media !== undefined && segment !== undefined) windows.set(media, framesBySegment.get(segment) ?? frameRate);
- }
- for (const [, attributes] of svml.matchAll(/<[a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9]*\b([^>]*?)\/?>/gsu)) {
- const media = /\bmedia=\{([A-Za-z0-9_-]+)\.media\}/u.exec(attributes)?.[1];
- if (media === undefined || windows.has(media)) continue;
- const segment = /\bduring=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
- if (segment !== undefined) { windows.set(media, framesBySegment.get(segment) ?? frameRate); continue; }
- windows.set(media, frameRate * 2);
- }
- const carries = new Map();
- for (const [, attributes] of svml.matchAll(/<pipeline:Normalize\b([^>]*?)\/?>/gsu)) {
- const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
- const video = /\bvideo="([^"]+)"/u.exec(attributes)?.[1];
- if (id === undefined || !windows.has(id)) continue;
- // A Run that already satisfies this output brought its own material — a package's preview Source
- // supplies sample pictures this way — and a mock over the top would hide what it came to show.
- if (alreadySatisfied.has(`${id}.media`)) continue;
- carries.set(id, { frames: windows.get(id), picture: video !== "none" });
- }
- return carries;
-}
-
-// A derived Run lives beside the project so the original's relative sources still resolve, and under
-// `.hypit/` so it is never mistaken for something the author wrote. It is rewritten every run.
-const compareRoot = join(projectRoot, ".hypit", "compare");
-await rm(compareRoot, { recursive: true, force: true });
-await mkdir(compareRoot, { recursive: true });
-const declarations = [];
-const satisfactions = [];
-for (const { segmentId, take } of takes) {
- const output = takeOutputs.get(segmentId);
- if (output === undefined) continue;
- // The take's own audio has to be servable, not a digest stub: Studio resolves every Artifact a
- // projection references, and a preview that cannot serve one stops there.
- const sampleFrames = Math.round(take.segment.endFrameExclusive / frameRate * 48_000);
- const silence = silentWav(sampleFrames);
- await writeFile(join(compareRoot, `${segmentId}-take.wav`), silence);
- const spoken = { ...take, media: { ...take.media, audio: { artifact: blobRef(silence, "audio/wav"), sampleFrames } } };
- const fixture = join(compareRoot, `${segmentId}.json`);
- await writeFile(fixture, `${JSON.stringify({ kind: "inline", value: spoken }, null, 2)}\n`, "utf8");
- declarations.push(` <file id="stand-in-${segmentId}-audio" type="@hypit/artifact@1#BlobArtifact" from="./${segmentId}-take.wav" media-type="audio/wav"/>`);
- declarations.push(` <value id="stand-in-${segmentId}" type="@hypit/speech@1#SemanticTake" from="./${segmentId}.json"/>`);
- satisfactions.push(` <satisfy output="${output}.take" candidate="stand-in-${segmentId}"/>`);
-}
-// The layers a Build has not made, as placeholders of the Canvas's own size. `make-placeholder` is
-// the route's one tool for this: deterministic, Provider-free, and the same mock the comparison is
-// told to bypass. A mock never enters the project's own Source — it is declared in the derived Run
-// and nowhere else.
-const placeholderCli = new URL("../../../../packages/reference-video-tools/src/cli.ts", import.meta.url);
-for (const [id, { frames, picture }] of mockedMedia()) {
- // make-placeholder takes whole seconds, and a mock longer than its window costs nothing: the
- // SynchronizedMedia declares the frame count, the file only has to reach it.
- const seconds = Math.max(1, Math.ceil(frames / frameRate));
- const file = join(compareRoot, `${id}.mp4`);
- if (picture) {
- const made = spawnSync(process.execPath, [
- "--import", "tsx", fileURLToPath(placeholderCli), "make-placeholder",
- "--out", file, "--width", String(canvas.width), "--height", String(canvas.height),
- "--video", "--seconds", String(seconds), "--color", "mid",
- ], { encoding: "utf8", windowsHide: true, timeout: 120_000 });
- if (made.status !== 0) fail(`make-placeholder failed for ${id}: ${made.stderr?.trim()}`);
- }
- // Every SynchronizedMedia carries audio, and it is validated as WAV, so the silence is written as
- // one rather than pointed at the video. Both are declared: the picture is what gets drawn, the
- // silence is what makes the value legal.
- const wavPath = join(compareRoot, `${id}.wav`);
- const wav = silentWav(Math.round(frames / frameRate * 48_000));
- await writeFile(wavPath, wav);
- const audioBlob = blobRef(wav, "audio/wav");
- const media = {
- timeline: { frameRate: { numerator: frameRate, denominator: 1 }, frameCount: frames },
- audio: { artifact: audioBlob },
- };
- declarations.push(` <file id="mock-${id}-audio" type="@hypit/artifact@1#BlobArtifact" from="./${id}.wav" media-type="audio/wav"/>`);
- if (picture) {
- const bytes = await readFile(file);
- media.visual = { artifact: blobRef(bytes, "video/mp4"), width: canvas.width, height: canvas.height };
- declarations.push(` <file id="mock-${id}" type="@hypit/artifact@1#BlobArtifact" from="./${id}.mp4" media-type="video/mp4"/>`);
- }
- await writeFile(join(compareRoot, `${id}.media.json`), `${JSON.stringify({ kind: "inline", value: media }, null, 2)}\n`, "utf8");
- declarations.push(` <value id="media-${id}" type="@hypit/media@1#SynchronizedMedia" from="./${id}.media.json"/>`);
- satisfactions.push(` <satisfy output="${id}.media" candidate="media-${id}"/>`);
-}
-
-// Still images the Source declares as generations. Same treatment, same tool, at the Canvas's size:
-// a picture slot that is empty in the render is black, and black is not what will be there.
-const imageIds = [...new Set([...svml.matchAll(/\{([a-z0-9-]+)\.image\}/gu)].map(([, id]) => id))]
- .filter((id) => !alreadySatisfied.has(`${id}.image`));
-for (const id of imageIds) {
- const file = join(compareRoot, `${id}.png`);
- const made = spawnSync(process.execPath, [
- "--import", "tsx", fileURLToPath(placeholderCli), "make-placeholder",
- "--out", file, "--width", String(canvas.width), "--height", String(canvas.height), "--color", "mid",
- ], { encoding: "utf8", windowsHide: true, timeout: 120_000 });
- if (made.status !== 0) fail(`make-placeholder failed for ${id}: ${made.stderr?.trim()}`);
- declarations.push(` <file id="mock-${id}" type="@hypit/artifact@1#BlobArtifact" from="./${id}.png" media-type="image/png"/>`);
- satisfactions.push(` <satisfy output="${id}.image" candidate="mock-${id}"/>`);
-}
-
-const derivedRun = join(compareRoot, "compare.svrun");
-await writeFile(derivedRun, [
- `<?svml using="@hypit/run-markup@1"?>`,
- ``,
- `<svrun version="1">`,
- ` <author source="../../${authorMatch[1].replace(/^\.\//u, "")}"/>`,
- // Whatever the Run brought, repointed: the derived Run sits two directories deeper than the one
- // that declared these paths.
- ...carried.map((line) => ` ${line.replace(/from="\.\//gu, 'from="../../')}`),
- // Targeting the element's own output rather than the Film prunes the closure to what this one
- // Track needs. Asking for the whole delivery would pull in every generation the Source declares
- // and report each as unresolved, which is true and useless: none of them is what is being looked at.
- ` <target output="final.video"/>`,
- ``,
- ...declarations,
- ``,
- ...satisfactions,
- `</svrun>`,
- ``,
-].join("\n"), "utf8");
-
-const domain = await loadStudioDomain({ run: derivedRun, workspaceRoot: projectRoot, packageRoot });
-const archive = await openStudioArchive(undefined, packageRoot);
-let built;
-try {
- const run = await loadStudioRun({ run: derivedRun, domain, ...(archive === undefined ? {} : { archive }) });
- const inspection = inspectStudioRun(run.source, run);
- // Every Track, not only the one being looked at: the element is compared where it sits, over the
- // mocked base rather than on its own, because text that is legible on black may not be on a picture.
- built = await preview({
- source: run.source,
- run,
- domain,
- outputRefs: [inspection.filmComposition, ...inspection.projections.map((item) => item.ref)],
- compositionRef: inspection.filmComposition,
- projections: inspection.projections,
- ...(archive === undefined ? {} : { archive }),
- });
-} catch (error) {
- const issues = error?.issues;
- if (Array.isArray(issues)) {
- console.error("render-element: the Source does not project yet.");
- for (const issue of issues.slice(0, 12)) console.error(` ${issue}`);
- process.exit(1);
- }
- fail(error instanceof Error ? error.message : String(error), 1);
-}
-
-const placed = built.tracks.find((track) => String(track.outputRef ?? "").endsWith(`::output::${element}.track`)
- || String(track.outputRef ?? "").includes(`::output::${element}.`));
-if (placed === undefined) {
- console.error(`render-element: the Source places no element named ${element}. It places:`);
- for (const track of built.tracks) console.error(` ${String(track.outputRef ?? "").split("::output::")[1] ?? track.name}`);
- process.exit(1);
-}
-
-// The window to render, named in words. A shot of the reference is found by the words spoken over it
-// and those words are a Segment or a Selection here, so no reference timestamp is ever read across.
-let window = { startFrame: 0, endFrameExclusive: programFrames };
-if (selectionArgument !== undefined) {
- window = selections.get(selectionArgument)
- ?? fail(`the Script marks no Selection ${selectionArgument}`);
-} else if (segmentArgument !== undefined) {
- let cursor = 0;
- const take = takes.find((item) => { const hit = item.segmentId === segmentArgument; if (!hit) cursor += item.take.segment.endFrameExclusive; return hit; });
- if (take === undefined) fail(`the Script has no Segment ${segmentArgument}`);
- window = { startFrame: cursor, endFrameExclusive: cursor + take.take.segment.endFrameExclusive };
-}
-
-// Compile once, materialize with the artifact bytes written beside the document, and let the
-// HyperFrames runtime draw it. This is the path packages/hyperframes/test/browser-visual.test.ts
-// takes; nothing here is a private renderer.
-const document = compileHyperframesDocument(built.composition, built.space);
-const stage = join(compareRoot, "stage");
-await mkdir(stage, { recursive: true });
-const names = new Map();
-for (const [digest, file] of built.served) {
- const name = `${digest.replace(/[^a-z0-9]/giu, "")}`;
- await writeFile(join(stage, name), file.bytes);
- names.set(digest, name);
-}
-await writeFile(join(stage, "index.html"), materializeHyperframesHtml(document, (artifact) => {
- const name = names.get(artifact.digest);
- if (name === undefined) fail(`the projection references Artifact ${artifact.digest}, which was not served`, 1);
- return `./${name}`;
-}), "utf8");
-
-const clip = /\.(mp4|mov|webm)$/iu.test(outPath);
-const frames = join(compareRoot, "frames");
-await rm(frames, { recursive: true, force: true });
-await mkdir(frames, { recursive: true });
-const hyperframesCli = createRequire(join(packageRoot, "packages/provider-hyperframes-local/package.json"))
- .resolve("hyperframes/bin/hyperframes.mjs");
-const drawn = spawnSync(process.execPath, [
- hyperframesCli, "render", stage,
- "--format", "png-sequence", "--output", frames, "--fps", String(frameRate),
- "--workers", String(Math.max(1, cpus().length - 2)), "--no-best-effort", "--quiet",
-], { encoding: "utf8", windowsHide: true, timeout: 600_000 });
-if (drawn.status !== 0) fail(`the HyperFrames runtime refused: ${(drawn.stderr ?? "").trim().slice(-2000)}`, 1);
-
-const written = (await readdir(frames)).filter((name) => name.endsWith(".png")).sort();
-if (written.length === 0) fail("the HyperFrames runtime wrote no frames", 1);
-const first = Math.min(window.startFrame, written.length - 1);
-const last = Math.min(window.endFrameExclusive, written.length);
-// The runtime draws with an alpha channel and leaves unpainted area transparent. What a viewer is
-// under is the Film's own clear colour, so it is composited in here rather than left to whatever
-// opens the file: a reference clip is opaque, and an observer handed a transparent counterpart reads
-// the difference as design when it came from the encoding.
-const clear = built.canvas?.clearColor ?? "#000000";
-const background = `color=c=${clear.replace("#", "0x")}:s=${canvas.width}x${canvas.height}:r=${frameRate}`;
-const count = Math.max(1, clip ? last - first : 1);
-const encoded = spawnSync("ffmpeg", [
- "-hide_banner", "-loglevel", "error", "-y",
- "-f", "lavfi", "-i", background,
- "-framerate", String(frameRate), "-start_number", String(clip ? first : Math.min(first + Math.floor((last - first) / 2), written.length - 1)),
- "-i", join(frames, "frame_%06d.png"),
- "-filter_complex", "[0][1]overlay=shortest=1[v]", "-map", "[v]",
- "-frames:v", String(count),
- ...(clip ? ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20"] : []),
- outPath,
-], { encoding: "utf8", windowsHide: true, timeout: 600_000 });
-if (encoded.status !== 0) fail(`ffmpeg refused: ${(encoded.stderr ?? "").trim().slice(-2000)}`, 1);
-
-console.log(JSON.stringify({
- element,
- out: outPath,
- compared: clip ? "clip" : "still",
- canvas,
- frame_rate: frameRate,
- window,
- program_frames: programFrames,
- mocked: { media: mockedMedia().size, images: imageIds.length },
-}, null, 2));
diff --git a/.agents/skills/hypit/scripts/render-previews.mjs b/.agents/skills/hypit/scripts/render-previews.mjs
deleted file mode 100644
index 233a8ddb..00000000
--- a/.agents/skills/hypit/scripts/render-previews.mjs
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/env node
-/**
- * Draw a package's catalogue preview images from the package's own preview Source.
- *
- * A Manifest hands Studio and the README a picture per Surface, read off disk with `readFile`. Those
- * pictures were made once and committed, and nothing could make them again: a Recipe could change, a
- * Surface could gain a port, and the catalogue would go on showing what the package used to draw.
- *
- * So the sample lives in the package as a Source it can be drawn from. `preview/preview.svml`,
- * `preview/recipes.svs` and `preview/build.svrun` hold the package's own copy, its own Recipe values
- * and its own Canvas — nothing about any project — and `render-element.mjs` draws them through the
- * real authoring path. A Surface that stopped working cannot produce a preview that looks fine.
- *
- * Which element draws which file comes from the Manifest's own naming: a Surface tagged `Track`
- * declares `preview/Track.png`, so `Track.png` is drawn from whichever element in the preview Source
- * carries that tag. No third file has to agree with the other two.
- *
- * Usage: node --import tsx .agents/skills/hypit/scripts/render-previews.mjs <package-dir> [...]
- * Exit: 0 having written each picture, naming it. 1 when a preview Source refuses to draw.
- * 2 when a package has no preview Source, or its Manifest names a picture nothing draws.
- */
-import { readFile, readdir } from "node:fs/promises";
-import { spawnSync } from "node:child_process";
-import { basename, join, resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const renderElement = fileURLToPath(new URL("./render-element.mjs", import.meta.url));
-
-function fail(message, code = 2) {
- console.error(`render-previews: ${message}`);
- process.exit(code);
-}
-
-const directories = process.argv.slice(2).filter((value) => !value.startsWith("--"));
-if (directories.length === 0) fail("usage: render-previews.mjs <package-dir> [...]");
-
-const invokedFrom = process.env.INIT_CWD ?? process.cwd();
-let written = 0;
-for (const directory of directories) {
- const packageDir = resolve(invokedFrom, directory);
- const previewDir = join(packageDir, "preview");
- const run = join(previewDir, "build.svrun");
- const svml = await readFile(join(previewDir, "preview.svml"), "utf8").catch(() => undefined);
- if (svml === undefined) {
- fail(`${directory} has no preview/preview.svml. Write one: the package's own copy, its own Recipe values, its own Canvas.`);
- }
-
- // The alias the preview Source imports this package under. A preview Source places Tracks from
- // several packages — it needs a semantic spine and a Film like any other — and `Track` is a common
- // tag, so the tag alone would draw whichever one happened to be written first.
- const specifier = JSON.parse(await readFile(join(packageDir, "package.json"), "utf8").catch(() => "{}")).name;
- if (typeof specifier !== "string") fail(`${directory} has no package.json name`);
- const imported = [...svml.matchAll(/<import\s+as="([^"]+)"\s+from="(@[^"]+)@\d+"/gu)];
- const alias = imported.find(([, , from]) => from === specifier)?.[1];
- if (alias === undefined) {
- fail(`${directory}'s preview Source does not import ${specifier}, so nothing in it is this package's`);
- }
-
- // The pictures the Manifest promises, and the element tag each one is named for.
- const manifest = await readFile(join(packageDir, "src", "manifest.ts"), "utf8").catch(() => "");
- const promised = [...new Set([...manifest.matchAll(/previewImage\(\s*["']([^"']+)["']/gu)].map(([, file]) => file))];
- const existing = (await readdir(previewDir).catch(() => []))
- .filter((name) => /\.(png|jpe?g|svg)$/iu.test(name));
- const pictures = promised.length > 0 ? promised : existing;
- if (pictures.length === 0) fail(`${directory} promises no preview picture; nothing to draw`);
-
- for (const picture of pictures) {
- if (/\.svg$/iu.test(picture)) {
- console.log(` ${picture} is drawn by hand, not from a Source; left alone`);
- continue;
- }
- const tag = basename(picture).replace(/\.[^.]+$/u, "");
- const element = new RegExp(`<${alias}:${tag}\\b[^>]*?\\bid="([^"]+)"`, "su").exec(svml)?.[1];
- if (element === undefined) {
- fail(`${directory} promises ${picture} but its preview Source places no <${alias}:${tag}> to draw it from`);
- }
- const drawn = spawnSync(process.execPath, [
- "--import", "tsx", renderElement, run, "--element", element, "--out", join(previewDir, picture),
- ], { encoding: "utf8", windowsHide: true, timeout: 900_000 });
- if (drawn.status !== 0) {
- console.error((drawn.stderr ?? "").trim());
- fail(`${directory} could not draw ${picture}`, 1);
- }
- console.log(` ${directory}/preview/${picture} ← ${tag} id=${element}`);
- written += 1;
- }
-}
-console.log(`render-previews: drew ${written} picture${written === 1 ? "" : "s"}.`);
diff --git a/.agents/skills/hypit/scripts/stand-in-takes.mjs b/.agents/skills/hypit/scripts/stand-in-takes.mjs
deleted file mode 100644
index 92ecad68..00000000
--- a/.agents/skills/hypit/scripts/stand-in-takes.mjs
+++ /dev/null
@@ -1,190 +0,0 @@
-/**
- * Build a stand-in SemanticTake for every Segment a Source declares, from the Source alone.
- *
- * A Track timed against speech cannot be projected before the speech exists, and on this route it
- * does not exist: the Build has not run. What the Source does hold is the words themselves and the
- * estimator it already trusts to size its own generations — `estimate:Speech` with a policy Recipe.
- * Running that estimator here produces the same numbers the Source used to order its takes, so this
- * introduces no second clock; it reads the one already written down.
- *
- * What the result is good for: which elements are on screen together, where each sits, at what size
- * and colour. Those follow from word ranges and Recipe values and are exact. What it is not good for
- * is real timing — the delivered speech is not the estimate, and anything measured in seconds waits
- * for `production-gates.md` Gate 3.
- *
- * Tokens are laid across the Segment in proportion to the same syllable count the estimator uses, so
- * a long word occupies more of the window than a short one and the ordering is the Script's.
- */
-import { readFile } from "node:fs/promises";
-import { dirname, resolve } from "node:path";
-
-const from = (path) => new URL(`../../../../packages/${path}`, import.meta.url).href;
-const { parseScript } = await import(from("script/src/parser.ts"));
-const { estimateSpeechDuration, countSpeechEstimateUnits, resolveSpeechEstimateLanguage } =
- await import(from("estimate/src/program.ts"));
-const { speechEstimatePolicyFromRecipe } = await import(from("estimate/src/surface.ts"));
-
-/** The Script body, which `parseScript` takes on its own. */
-function scriptBody(svml) {
- const open = /<script\b[^>]*>/u.exec(svml);
- if (open === null) throw new Error("the Source declares no <script>");
- const start = open.index + open[0].length;
- const end = svml.indexOf("</script>", start);
- if (end < 0) throw new Error("the Source's <script> is not closed");
- return { text: svml.slice(start, end), offset: start };
-}
-
-/** Every Recipe body in every sheet the Source imports, keyed `alias.path`. */
-async function recipeSheets(svml, svmlPath) {
- const sheets = new Map();
- for (const [, alias, source] of svml.matchAll(/<import\s+as="([^"]+)"\s+source="([^"]+\.svs)"/gu)) {
- const text = await readFile(resolve(dirname(svmlPath), source), "utf8").catch(() => undefined);
- if (text === undefined) continue;
- for (const [, name, body] of text.matchAll(/([A-Za-z0-9_.-]+)\s*\{([^}]*)\}/gu)) {
- const properties = {};
- for (const [, key, raw] of body.matchAll(/([a-z][a-z0-9-]*)\s*:\s*([^;]+);/gu)) {
- const value = raw.trim();
- properties[key] = /^-?\d+(\.\d+)?$/u.test(value) ? Number(value) : value;
- }
- sheets.set(`${alias}.${name}`, { path: `${alias}.${name}`, properties });
- }
- }
- return sheets;
-}
-
-/**
- * The policy each Segment's duration was estimated with. A Source names it once per Segment through
- * `<estimate:Speech source={story.segment.NAME.speech} policy={recipes.X}/>`, and reading it back is
- * what keeps this on the Source's own basis rather than a second one.
- */
-function policiesBySegment(svml, sheets) {
- const policies = new Map();
- const named = new Set();
- for (const [, attributes] of svml.matchAll(/<estimate:Speech\b([^>]*?)\/?>/gsu)) {
- const segment = /\bsource=\{story\.segment\.([A-Za-z0-9_-]+)\.speech\}/u.exec(attributes)?.[1];
- const recipe = /\bpolicy=\{([A-Za-z0-9_.-]+)\}/u.exec(attributes)?.[1];
- if (segment === undefined || recipe === undefined) continue;
- const sheet = sheets.get(recipe);
- if (sheet === undefined) throw new Error(`policy Recipe ${recipe} is not in any imported sheet`);
- named.add(recipe);
- policies.set(segment, speechEstimatePolicyFromRecipe(sheet));
- }
- // A Segment whose take is shared with another Segment carries no estimate of its own, so it has no
- // policy named against it. One policy across the Source settles those; several leaves no basis to
- // pick from, and guessing would put a Segment on a pace the Source never chose for it.
- const shared = named.size === 1 ? policies.get([...policies.keys()][0]) : undefined;
- return { policies, shared, policyCount: named.size };
-}
-
-const SILENT_AUDIO = { kind: "blob", digest: `sha256:${"0".repeat(64)}`, size: 1, mediaType: "audio/wav" };
-
-/**
- * @param svmlPath the Author SVML this Source is written in
- * @param frameRate the Program's frame rate, as a whole number of frames per second
- * @returns one `{ segmentId, take }` per Segment, in Script order
- */
-export async function standInTakes(svmlPath, frameRate, focus = {}) {
- const svml = await readFile(svmlPath, "utf8");
- const body = scriptBody(svml);
- const parsed = parseScript(svmlPath, body.text, body.offset);
- const sheets = await recipeSheets(svml, svmlPath);
- const { policies, shared, policyCount } = policiesBySegment(svml, sheets);
-
- // Which Segment the render is actually looking at. Every other Segment still has to exist — a
- // Speech Track assembles one Take per Segment and an unsatisfied one refuses the whole projection —
- // but nothing needs it at its estimated length. Held to one frame per word it stays legal, keeps
- // its anchors, and stops the renderer drawing a minute of program to show six seconds of it.
- let focused;
- if (focus.segment !== undefined) focused = focus.segment;
- else if (focus.selection !== undefined) {
- const selection = parsed.selections.find((item) => item.id === focus.selection);
- const token = selection?.occurrences[0]?.open.boundary.tokenIndex;
- focused = token === undefined
- ? undefined
- : parsed.segments.find((segment) => token >= segment.tokenStart && token < segment.tokenEndExclusive)?.id;
- }
-
- const takes = [];
- // Global frame span of every word, in Script order, so a Selection can be turned into a frame
- // range without going near a clock. This is the correspondence the route uses everywhere else:
- // a stretch of the reference is found by its words, and its words are where the Script says.
- const frameOfToken = [];
- let frameCursor = 0;
- for (const segment of parsed.segments) {
- const policy = policies.get(segment.id) ?? shared;
- if (policy === undefined) {
- throw new Error(`Segment ${segment.id} names no estimate:Speech policy, and the Source uses ${policyCount} policies, so there is no single one to fall back to`);
- }
- const tokens = parsed.tokens.slice(segment.tokenStart, segment.tokenEndExclusive);
- const text = tokens.map((token) => token.text).join(" ");
- const seconds = estimateSpeechDuration({ value: text }, policy);
- const frameCount = focused !== undefined && segment.id !== focused
- ? Math.max(1, tokens.length)
- : Math.max(tokens.length, Math.round(seconds * frameRate));
-
- // Share the Segment's frames out by the estimator's own unit count, so the word order and the
- // relative widths both come from the same place the duration did.
- const language = resolveSpeechEstimateLanguage(text, policy.language);
- const weights = tokens.map((token) => Math.max(1, countSpeechEstimateUnits(token.text, language)));
- const total = weights.reduce((sum, weight) => sum + weight, 0);
- const anchors = [
- { identity: `segment:${segment.id}:start`, frame: 0 },
- { identity: `segment:${segment.id}:end`, frame: frameCount },
- ];
- const placed = [];
- let used = 0;
- for (const [index, token] of tokens.entries()) {
- const start = used;
- // The last token closes the Segment exactly, so rounding never leaves a frame unclaimed.
- used = index === tokens.length - 1
- ? frameCount
- : Math.min(frameCount - (tokens.length - 1 - index), start + Math.max(1, Math.round(frameCount * weights[index] / total)));
- const id = `segment:${segment.id}:token:${index + 1}`;
- placed.push({
- tokenId: id, segmentId: segment.id, text: token.text,
- startAnchorId: `${id}:start`, endAnchorId: `${id}:end`,
- startFrame: start, endFrameExclusive: used,
- });
- anchors.push({ identity: `${id}:start`, frame: start }, { identity: `${id}:end`, frame: used });
- }
-
- frameOfToken.push(...placed.map((token) => ({ frame: frameCursor + token.startFrame, end: frameCursor + token.endFrameExclusive })));
- takes.push({
- segmentId: segment.id,
- startFrame: frameCursor,
- take: {
- media: {
- timeline: { frameRate: { numerator: frameRate, denominator: 1 }, frameCount },
- audio: { artifact: SILENT_AUDIO, sampleFrames: Math.round(frameCount / frameRate * 48_000) },
- },
- segment: {
- segmentId: segment.id,
- startAnchorId: `segment:${segment.id}:start`,
- endAnchorId: `segment:${segment.id}:end`,
- startFrame: 0,
- endFrameExclusive: frameCount,
- },
- tokens: placed,
- anchors,
- },
- });
- frameCursor += frameCount;
- }
-
- // Every Selection the Script marks, as the frames its words occupy. Occurrences are unioned, since
- // one Selection id can be marked in several places and they nest freely.
- const selections = new Map();
- for (const selection of parsed.selections) {
- let start = Infinity;
- let end = 0;
- for (const occurrence of selection.occurrences) {
- const first = frameOfToken[occurrence.open.boundary.tokenIndex];
- const last = frameOfToken[occurrence.close.boundary.tokenIndex - 1];
- if (first === undefined || last === undefined) continue;
- start = Math.min(start, first.frame);
- end = Math.max(end, last.end);
- }
- if (start < end) selections.set(selection.id, { startFrame: start, endFrameExclusive: end });
- }
- return { takes, selections, frameCount: frameCursor };
-}
diff --git a/packages/media-track/preview/preview.svml b/packages/media-track/preview/preview.svml
index 1b886374..e66b258d 100644
--- a/packages/media-track/preview/preview.svml
+++ b/packages/media-track/preview/preview.svml
@@ -6,7 +6,7 @@
about a project reaches this file, and nothing in it reaches a project. It exists so a reader
can see the Surface's range in one picture, and so that picture can be made again.
- The generations it declares are never performed. `scripts/render-previews.mjs` mocks each one
+ The generations it declares are never performed. `render_previews` mocks each one
and draws the rest, so this stays free to run and free to re-run.
A placeholder shows the Frame treatment and nothing inside it. To show the component holding a
diff --git a/packages/reference-video-tools/package.json b/packages/reference-video-tools/package.json
index 53b8b4dc..87f7b12c 100644
--- a/packages/reference-video-tools/package.json
+++ b/packages/reference-video-tools/package.json
@@ -13,13 +13,20 @@
"dependencies": {
"@google/genai": "1.52.0",
"@hypit/driver-node": "workspace:*",
+ "@hypit/estimate": "workspace:*",
+ "@hypit/hyperframes": "workspace:*",
"@hypit/markup": "workspace:*",
+ "@hypit/media": "workspace:*",
"@hypit/model-kit": "workspace:*",
"@hypit/package-loader-node": "workspace:*",
+ "@hypit/program-space": "workspace:*",
"@hypit/protocol": "workspace:*",
"@hypit/provider-whisperx-local": "workspace:*",
+ "@hypit/script": "workspace:*",
"@hypit/speech": "workspace:*",
"@hypit/speech-evidence": "workspace:*",
+ "@hypit/studio": "workspace:*",
+ "@hypit/svs": "workspace:*",
"@hypit/whisperx": "workspace:*",
"tsx": "4.21.0"
},
diff --git a/packages/reference-video-tools/src/authoring.ts b/packages/reference-video-tools/src/authoring.ts
new file mode 100644
index 00000000..0f195e58
--- /dev/null
+++ b/packages/reference-video-tools/src/authoring.ts
@@ -0,0 +1,793 @@
+import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { readFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+
+import { writePlaceholder } from "./placeholder.js";
+import { sliceSource } from "./slice.js";
+import type { SliceResult } from "./slice.js";
+import { createHash } from "node:crypto";
+import { createRequire } from "node:module";
+import { cpus } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { compileHyperframesDocument, materializeHyperframesHtml } from "@hypit/hyperframes";
+import {
+ countSpeechEstimateUnits,
+ estimateSpeechDuration,
+ resolveSpeechEstimateLanguage,
+ speechEstimatePolicyFromRecipe,
+} from "@hypit/estimate";
+import type { SpeechEstimatePolicy } from "@hypit/estimate";
+import type { SynchronizedMedia } from "@hypit/media";
+import type { ProgramSpace } from "@hypit/program-space";
+import type { BlobRef, Digest } from "@hypit/protocol";
+import { parseScript } from "@hypit/script";
+import type { SemanticTake, SemanticTakeToken } from "@hypit/speech";
+import { openStudioArchive } from "@hypit/studio/src/archive.js";
+import { loadStudioDomain } from "@hypit/studio/src/domain.js";
+import type { Preview } from "@hypit/studio/src/programme.js";
+import { preview } from "@hypit/studio/src/programme.js";
+import { loadStudioRun } from "@hypit/studio/src/run.js";
+import { inspectStudioRun } from "@hypit/studio/src/studio-preflight.js";
+import type { SvsRecipe } from "@hypit/svs";
+
+import { assert } from "./media.js";
+
+/** A frame range of the stand-in program, half-open in the Script's own order. */
+export type AuthoringWindow = {
+ readonly startFrame: number;
+ readonly endFrameExclusive: number;
+};
+
+/**
+ * A stand-in Take. Its `media.audio` carries the sample count beside the Artifact, which is the
+ * shape the `<value>` fixture is written with.
+ */
+export type StandInTakeValue = Omit<SemanticTake, "media"> & {
+ readonly media: Omit<SynchronizedMedia, "audio"> & {
+ readonly audio: { readonly artifact: BlobRef; readonly sampleFrames: number };
+ };
+};
+
+export type StandInTake = {
+ readonly segmentId: string;
+ readonly startFrame: number;
+ readonly take: StandInTakeValue;
+};
+
+export type StandInTakes = {
+ readonly takes: readonly StandInTake[];
+ readonly selections: ReadonlyMap<string, AuthoringWindow>;
+ readonly frameCount: number;
+};
+
+/** Which Segment the render is looking at, named directly or through a Selection's words. */
+export type StandInFocus = {
+ readonly segment?: string;
+ readonly selection?: string;
+};
+
+/**
+ * The Hypit checkout this package is installed into.
+ *
+ * Studio's domain and the HyperFrames runtime are both found from it, and neither can be found from
+ * the working directory: a command run from a project directory would resolve no packages, and one
+ * that assumed the root would work there and crash anywhere else, on a missing module rather than on
+ * anything a reader could act on. Walking up from this module reaches the checkout from wherever the
+ * package was installed. `HYPIT_REPOSITORY` names one explicitly, the same override
+ * `locate-repository.mjs` reads.
+ */
+function isCheckout(directory: string): boolean {
+ try {
+ const manifest = JSON.parse(readFileSync(join(directory, "package.json"), "utf8")) as { readonly name?: string };
+ return manifest.name === "@hypit/repository";
+ } catch { return false; }
+}
+
+function nearestCheckout(start: string): string | undefined {
+ let directory = resolve(start);
+ while (true) {
+ if (isCheckout(directory)) return directory;
+ const parent = dirname(directory);
+ if (parent === directory) return undefined;
+ directory = parent;
+ }
+}
+
+function repositoryRoot(): string {
+ const override = process.env.HYPIT_REPOSITORY?.trim();
+ if (override !== undefined && override.length > 0) {
+ const directory = resolve(override);
+ assert(isCheckout(directory), `HYPIT_REPOSITORY is not a Hypit checkout: ${directory}`);
+ return directory;
+ }
+ const found = nearestCheckout(dirname(fileURLToPath(import.meta.url))) ?? nearestCheckout(process.cwd());
+ assert(found !== undefined, "no Hypit checkout above this package or the working directory; set HYPIT_REPOSITORY");
+ return found;
+}
+
+/** Where a relative path on the command line is measured from. */
+export function invokedFrom(): string {
+ return process.env.INIT_CWD ?? process.cwd();
+}
+
+/** The Script body, which `parseScript` takes on its own. */
+function scriptBody(svml: string): { readonly text: string; readonly offset: number } {
+ const open = /<script\b[^>]*>/u.exec(svml);
+ if (open === null) throw new Error("the Source declares no <script>");
+ const start = open.index + open[0].length;
+ const end = svml.indexOf("</script>", start);
+ if (end < 0) throw new Error("the Source's <script> is not closed");
+ return { text: svml.slice(start, end), offset: start };
+}
+
+/** Every Recipe body in every sheet the Source imports, keyed `alias.path`. */
+async function recipeSheets(svml: string, svmlPath: string): Promise<ReadonlyMap<string, SvsRecipe>> {
+ const sheets = new Map<string, SvsRecipe>();
+ for (const match of svml.matchAll(/<import\s+as="([^"]+)"\s+source="([^"]+\.svs)"/gu)) {
+ const alias = match[1] ?? "";
+ const source = match[2] ?? "";
+ const text = await readFile(resolve(dirname(svmlPath), source), "utf8").catch(() => undefined);
+ if (text === undefined) continue;
+ for (const recipe of text.matchAll(/([A-Za-z0-9_.-]+)\s*\{([^}]*)\}/gu)) {
+ const name = recipe[1] ?? "";
+ const body = recipe[2] ?? "";
+ const properties: Record<string, string | number> = {};
+ for (const property of body.matchAll(/([a-z][a-z0-9-]*)\s*:\s*([^;]+);/gu)) {
+ const key = property[1] ?? "";
+ const value = (property[2] ?? "").trim();
+ properties[key] = /^-?\d+(\.\d+)?$/u.test(value) ? Number(value) : value;
+ }
+ sheets.set(`${alias}.${name}`, { path: `${alias}.${name}`, properties });
+ }
+ }
+ return sheets;
+}
+
+/**
+ * The policy each Segment's duration was estimated with. A Source names it once per Segment through
+ * `<estimate:Speech source={story.segment.NAME.speech} policy={recipes.X}/>`, and reading it back is
+ * what keeps this on the Source's own basis rather than a second one.
+ */
+function policiesBySegment(svml: string, sheets: ReadonlyMap<string, SvsRecipe>): {
+ readonly policies: ReadonlyMap<string, SpeechEstimatePolicy>;
+ readonly shared: SpeechEstimatePolicy | undefined;
+ readonly policyCount: number;
+} {
+ const policies = new Map<string, SpeechEstimatePolicy>();
+ const named = new Set<string>();
+ for (const match of svml.matchAll(/<estimate:Speech\b([^>]*?)\/?>/gsu)) {
+ const attributes = match[1] ?? "";
+ const segment = /\bsource=\{story\.segment\.([A-Za-z0-9_-]+)\.speech\}/u.exec(attributes)?.[1];
+ const recipe = /\bpolicy=\{([A-Za-z0-9_.-]+)\}/u.exec(attributes)?.[1];
+ if (segment === undefined || recipe === undefined) continue;
+ const sheet = sheets.get(recipe);
+ if (sheet === undefined) throw new Error(`policy Recipe ${recipe} is not in any imported sheet`);
+ named.add(recipe);
+ policies.set(segment, speechEstimatePolicyFromRecipe(sheet));
+ }
+ // A Segment whose take is shared with another Segment carries no estimate of its own, so it has no
+ // policy named against it. One policy across the Source settles those; several leaves no basis to
+ // pick from, and guessing would put a Segment on a pace the Source never chose for it.
+ const shared = named.size === 1 ? policies.get([...policies.keys()][0]!) : undefined;
+ return { policies, shared, policyCount: named.size };
+}
+
+const SILENT_AUDIO: BlobRef = { kind: "blob", digest: `sha256:${"0".repeat(64)}` as Digest, size: 1, mediaType: "audio/wav" };
+
+/**
+ * Build a stand-in SemanticTake for every Segment a Source declares, from the Source alone.
+ *
+ * A Track timed against speech cannot be projected before the speech exists, and on this route it
+ * does not exist: the Build has not run. What the Source does hold is the words themselves and the
+ * estimator it already trusts to size its own generations — `estimate:Speech` with a policy Recipe.
+ * Running that estimator here produces the same numbers the Source used to order its takes, so this
+ * introduces no second clock; it reads the one already written down.
+ *
+ * What the result is good for: which elements are on screen together, where each sits, at what size
+ * and colour. Those follow from word ranges and Recipe values and are exact. What it is not good for
+ * is real timing — the delivered speech is not the estimate, and anything measured in seconds waits
+ * for `production-gates.md` Gate 3.
+ *
+ * Tokens are laid across the Segment in proportion to the same syllable count the estimator uses, so
+ * a long word occupies more of the window than a short one and the ordering is the Script's.
+ *
+ * @param svmlPath the Author SVML this Source is written in
+ * @param frameRate the Program's frame rate, as a whole number of frames per second
+ * @returns one `{ segmentId, take }` per Segment, in Script order
+ */
+/** The Segment a Selection is marked in, so a window named by Selection can still name the cut. */
+function segmentOfSelection(svml: string, selection: string | undefined): string | undefined {
+ if (selection === undefined) return undefined;
+ const open = /<script\b[^>]*>/u.exec(svml);
+ if (open === null) return undefined;
+ const start = open.index + open[0].length;
+ const end = svml.indexOf("</script>", start);
+ if (end < 0) return undefined;
+ const body = svml.slice(start, end);
+ const at = body.indexOf(`@${selection}`);
+ if (at < 0) return undefined;
+ let found: string | undefined;
+ for (const match of body.matchAll(/<([a-z][a-z0-9-]*)\b[^>]*>/gu)) {
+ if (match.index > at) break;
+ if (body.indexOf(`</${match[1]!}>`, match.index) > at) found = match[1]!;
+ }
+ return found;
+}
+
+export async function standInTakes(svmlPath: string, frameRate: number, focus: StandInFocus = {}): Promise<StandInTakes> {
+ const svml = await readFile(svmlPath, "utf8");
+ const body = scriptBody(svml);
+ const parsed = parseScript(svmlPath, body.text, body.offset);
+ const sheets = await recipeSheets(svml, svmlPath);
+ const { policies, shared, policyCount } = policiesBySegment(svml, sheets);
+
+ // Which Segment the render is actually looking at. Every other Segment still has to exist — a
+ // Speech Track assembles one Take per Segment and an unsatisfied one refuses the whole projection —
+ // but nothing needs it at its estimated length. Held to one frame per word it stays legal, keeps
+ // its anchors, and stops the renderer drawing a minute of program to show six seconds of it.
+ let focused: string | undefined;
+ if (focus.segment !== undefined) focused = focus.segment;
+ else if (focus.selection !== undefined) {
+ const selection = parsed.selections.find((item) => item.id === focus.selection);
+ const token = selection?.occurrences[0]?.open.boundary.tokenIndex;
+ focused = token === undefined
+ ? undefined
+ : parsed.segments.find((segment) => token >= segment.tokenStart && token < segment.tokenEndExclusive)?.id;
+ }
+
+ const takes: StandInTake[] = [];
+ // Global frame span of every word, in Script order, so a Selection can be turned into a frame
+ // range without going near a clock. This is the correspondence the route uses everywhere else:
+ // a stretch of the reference is found by its words, and its words are where the Script says.
+ const frameOfToken: { readonly frame: number; readonly end: number }[] = [];
+ let frameCursor = 0;
+ for (const segment of parsed.segments) {
+ const policy = policies.get(segment.id) ?? shared;
+ if (policy === undefined) {
+ throw new Error(`Segment ${segment.id} names no estimate:Speech policy, and the Source uses ${policyCount} policies, so there is no single one to fall back to`);
+ }
+ const tokens = parsed.tokens.slice(segment.tokenStart, segment.tokenEndExclusive);
+ const text = tokens.map((token) => token.text).join(" ");
+ const seconds = estimateSpeechDuration({ value: text }, policy);
+ const frameCount = focused !== undefined && segment.id !== focused
+ ? Math.max(1, tokens.length)
+ : Math.max(tokens.length, Math.round(seconds * frameRate));
+
+ // Share the Segment's frames out by the estimator's own unit count, so the word order and the
+ // relative widths both come from the same place the duration did.
+ const language = resolveSpeechEstimateLanguage(text, policy.language);
+ const weights = tokens.map((token) => Math.max(1, countSpeechEstimateUnits(token.text, language)));
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
+ const anchors: { readonly identity: string; readonly frame: number }[] = [
+ { identity: `segment:${segment.id}:start`, frame: 0 },
+ { identity: `segment:${segment.id}:end`, frame: frameCount },
+ ];
+ const placed: SemanticTakeToken[] = [];
+ let used = 0;
+ for (const [index, token] of tokens.entries()) {
+ const start = used;
+ // The last token closes the Segment exactly, so rounding never leaves a frame unclaimed.
+ used = index === tokens.length - 1
+ ? frameCount
+ : Math.min(frameCount - (tokens.length - 1 - index), start + Math.max(1, Math.round(frameCount * weights[index]! / total)));
+ const id = `segment:${segment.id}:token:${index + 1}`;
+ placed.push({
+ tokenId: id, segmentId: segment.id, text: token.text,
+ startAnchorId: `${id}:start`, endAnchorId: `${id}:end`,
+ startFrame: start, endFrameExclusive: used,
+ });
+ anchors.push({ identity: `${id}:start`, frame: start }, { identity: `${id}:end`, frame: used });
+ }
+
+ frameOfToken.push(...placed.map((token) => ({ frame: frameCursor + token.startFrame, end: frameCursor + token.endFrameExclusive })));
+ takes.push({
+ segmentId: segment.id,
+ startFrame: frameCursor,
+ take: {
+ media: {
+ timeline: { frameRate: { numerator: frameRate, denominator: 1 }, frameCount },
+ audio: { artifact: SILENT_AUDIO, sampleFrames: Math.round(frameCount / frameRate * 48_000) },
+ },
+ segment: {
+ segmentId: segment.id,
+ startAnchorId: `segment:${segment.id}:start`,
+ endAnchorId: `segment:${segment.id}:end`,
+ startFrame: 0,
+ endFrameExclusive: frameCount,
+ },
+ tokens: placed,
+ anchors,
+ },
+ });
+ frameCursor += frameCount;
+ }
+
+ // Every Selection the Script marks, as the frames its words occupy. Occurrences are unioned, since
+ // one Selection id can be marked in several places and they nest freely.
+ const selections = new Map<string, AuthoringWindow>();
+ for (const selection of parsed.selections) {
+ let start = Infinity;
+ let end = 0;
+ for (const occurrence of selection.occurrences) {
+ const first = frameOfToken[occurrence.open.boundary.tokenIndex];
+ const last = frameOfToken[occurrence.close.boundary.tokenIndex - 1];
+ if (first === undefined || last === undefined) continue;
+ start = Math.min(start, first.frame);
+ end = Math.max(end, last.end);
+ }
+ if (start < end) selections.set(selection.id, { startFrame: start, endFrameExclusive: end });
+ }
+ return { takes, selections, frameCount: frameCursor };
+}
+
+function blobRef(bytes: Uint8Array, mediaType: string): BlobRef {
+ return { kind: "blob", digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, size: bytes.byteLength, mediaType };
+}
+
+/** 48 kHz mono PCM silence, written by hand so the mock needs no encoder and lands on exact bytes. */
+function silentWav(sampleFrames: number): Buffer {
+ const data = Math.max(2, sampleFrames * 2);
+ const buffer = Buffer.alloc(44 + data);
+ buffer.write("RIFF", 0);
+ buffer.writeUInt32LE(36 + data, 4);
+ buffer.write("WAVEfmt ", 8);
+ buffer.writeUInt32LE(16, 16);
+ buffer.writeUInt16LE(1, 20);
+ buffer.writeUInt16LE(1, 22);
+ buffer.writeUInt32LE(48_000, 24);
+ buffer.writeUInt32LE(48_000 * 2, 28);
+ buffer.writeUInt16LE(2, 32);
+ buffer.writeUInt16LE(16, 34);
+ buffer.write("data", 36);
+ buffer.writeUInt32LE(data, 40);
+ return buffer;
+}
+
+export type RenderElementInput = {
+ readonly run: string;
+ readonly element: string;
+ readonly out: string;
+ readonly segment?: string;
+ readonly selection?: string;
+};
+
+/**
+ * Render one element of a Source the way that Source configures it, without a Build and without a
+ * Provider.
+ *
+ * `reconstruction-loop.md` compares a reconstructed element against the reference. What it must
+ * compare is the element as this video places it — the Recipe values the Source passes, the Script
+ * text it feeds, the windows it binds — because a Source can fill those with values that collide
+ * while a package's catalogue preview, drawn from sample values, stays perfect. Producing that
+ * picture by hand means transcribing values into a per-package harness, one line at a time, which is
+ * how a caption system gets compared as a single line that has nothing to collide with.
+ *
+ * So this reads the values instead. Everything it needs is already written down:
+ *
+ * Canvas and Frames, Recipe values, bindings the Source
+ * which elements share a window, in what order the Script's words, through their Selections
+ * how long each Segment runs the Source's own `estimate:Speech`
+ * the layers a Build has not made `make-placeholder`, sized from the Canvas
+ *
+ * The one thing missing before a Build is real speech, and `standInTakes` supplies a Segment
+ * skeleton from the estimator the Source already trusts — the same numbers it ordered its takes
+ * with, not a second clock. Those takes enter through `<value>` and `<satisfy>`, the mechanism
+ * `examples/all-components-preview` uses to open in Studio without spending anything, so nothing
+ * here is a private back door into the graph.
+ *
+ * What this settles: which elements are on screen together, where each sits, at what size, weight and
+ * colour. What it does not: real timing, which waits for `playbooks/craft/production-gates.md` Gate 3.
+ */
+export async function renderElement(input: RenderElementInput): Promise<Record<string, unknown>> {
+ const element = input.element;
+ const cwd = invokedFrom();
+ const runPath = resolve(cwd, input.run);
+ const packageRoot = repositoryRoot();
+ const projectRoot = dirname(runPath);
+ const outPath = resolve(cwd, input.out);
+
+ const runSource = await readFile(runPath, "utf8").catch(() => undefined);
+ assert(runSource !== undefined, `cannot read ${runPath}`);
+ const author = /<author\s+source="([^"]+)"/u.exec(runSource)?.[1];
+ assert(author !== undefined, `${input.run} declares no <author source="…"/>`);
+ const svmlPath = resolve(projectRoot, author);
+ let svml = await readFile(svmlPath, "utf8").catch(() => undefined);
+ assert(svml !== undefined, `cannot read ${svmlPath}`);
+
+ // The Program's frame rate and the Canvas the render composes at, both read rather than assumed. A
+ // harness that hard-codes either produces a picture at a geometry the reference never had.
+ const clock = /<[a-z-]*:?Clock\b[^>]*?\bframe-rate="(\d+)"/su.exec(svml)?.[1]
+ ?? /<time:Clock\b[^>]*?\bfps="(\d+)"/su.exec(svml)?.[1];
+ const frameRate = Number(clock ?? 30);
+ const canvasMatch = /<space:Canvas\b[^>]*?\bwidth="(\d+)"[^>]*?\bheight="(\d+)"/su.exec(svml);
+ assert(canvasMatch !== null, "the Source declares no <space:Canvas width= height=/>");
+ const canvas = { width: Number(canvasMatch[1]), height: Number(canvasMatch[2]) };
+
+ // Which SemanticTake output belongs to which Segment, so each stand-in lands on the right one.
+ const takeOutputs = new Map<string, string>();
+ for (const match of svml.matchAll(/<whisperx:SemanticTake\b([^>]*?)\/?>/gsu)) {
+ const attributes = match[1] ?? "";
+ const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
+ const segment = /\bsegment=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
+ if (id !== undefined && segment !== undefined) takeOutputs.set(segment, id);
+ }
+ assert(takeOutputs.size > 0, "the Source declares no whisperx:SemanticTake to stand in for");
+
+ // What the Run already brings. A project Run declares nothing and everything is mocked; a package's
+ // preview Run ships its own sample pictures, and those are carried across untouched so the catalogue
+ // picture shows the component holding something rather than a placeholder.
+ const alreadySatisfied = new Set([...runSource.matchAll(/<satisfy\s+output="([^"]+)"/gu)].map((match) => match[1] ?? ""));
+ const carried = [...runSource.matchAll(/^[ \t]*<(?:file|value|satisfy)\b[^>]*\/>[ \t]*$/gmu)].map((match) => (match[0] ?? "").trim());
+
+ // The window is resolved before the stand-ins are built, so the program is only as long as the
+ // stretch being looked at. Rendering the whole program to crop six seconds out of it is the
+ // difference between a few seconds and a few minutes.
+ const segmentArgument = input.segment;
+ const selectionArgument = input.selection;
+ const focus = {
+ ...(segmentArgument === undefined ? {} : { segment: segmentArgument }),
+ ...(selectionArgument === undefined ? {} : { selection: selectionArgument }),
+ };
+
+ // The derived Run is written here, and so is the cut, so the directory comes first.
+ const compareRoot = join(projectRoot, ".hypit", "compare");
+ await rm(compareRoot, { recursive: true, force: true });
+ await mkdir(compareRoot, { recursive: true });
+
+ // With a window named, the Source is cut down to it before anything else runs. Every Segment
+ // outside it would otherwise still be drawn — held to one frame per word, which is the shortest a
+ // Take can legally be, and still nearly half the frames. The cut is byte-for-byte from the
+ // original, so the fragment cannot say anything the Source does not; `slice.ts` explains what
+ // decides which elements come with it.
+ let sourcePath = svmlPath;
+ let sliced: SliceResult | undefined;
+ const focusedSegment = focus.segment ?? segmentOfSelection(svml, focus.selection);
+ if (focusedSegment !== undefined) {
+ sliced = sliceSource(svml, focusedSegment);
+ sourcePath = join(compareRoot, "sliced.svml");
+ // The fragment sits two directories below the Source it came from, so its own relative imports
+ // have to reach back the same distance the derived Run's carried files do.
+ const repointed = sliced.text.replace(/(\s(?:source|from)=")\.\//gu, "$1../../");
+ await writeFile(sourcePath, repointed, "utf8");
+ // Everything downstream reads the Source: which Takes to stand in for, which media to mock, which
+ // outputs to satisfy. Left on the original it would declare mocks for elements the cut removed,
+ // and a `<satisfy>` naming an output that no longer exists is refused.
+ svml = repointed;
+ }
+
+ const { takes, selections, frameCount: programFrames } = await standInTakes(sourcePath, frameRate, focus);
+ const framesBySegment = new Map(takes.map((item) => [item.segmentId, item.take.segment.endFrameExclusive]));
+ // A Selection's window in frames, summed over the stand-in tokens it covers. This is the same word
+ // span the Source binds to, carried into frames by the same estimate that sized the Segment.
+ const framesBySelection = new Map<string, number>();
+ for (const { segmentId, take } of takes) {
+ for (const token of take.tokens) framesBySelection.set(token.tokenId, token.endFrameExclusive - token.startFrame);
+ framesBySelection.set(`segment:${segmentId}`, take.segment.endFrameExclusive);
+ }
+
+ /**
+ * Every media a Build would have produced, and how long its window is. A speech take carries no
+ * picture and a base take fills a Segment; a cutaway fills whatever its `during=` binds. Each becomes
+ * a placeholder of the Canvas's own size, so the composite has the geometry the Source declares.
+ */
+ const mockedMedia = (): ReadonlyMap<string, { readonly frames: number; readonly picture: boolean }> => {
+ const windows = new Map<string, number>();
+ for (const match of svml.matchAll(/<whisperx:SemanticTake\b([^>]*?)\/?>/gsu)) {
+ const attributes = match[1] ?? "";
+ const media = /\bmedia=\{([A-Za-z0-9_-]+)\.media\}/u.exec(attributes)?.[1];
+ const segment = /\bsegment=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
+ if (media !== undefined && segment !== undefined) windows.set(media, framesBySegment.get(segment) ?? frameRate);
+ }
+ for (const match of svml.matchAll(/<[a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9]*\b([^>]*?)\/?>/gsu)) {
+ const attributes = match[1] ?? "";
+ const media = /\bmedia=\{([A-Za-z0-9_-]+)\.media\}/u.exec(attributes)?.[1];
+ if (media === undefined || windows.has(media)) continue;
+ const segment = /\bduring=\{story\.segment\.([A-Za-z0-9_-]+)\}/u.exec(attributes)?.[1];
+ if (segment !== undefined) { windows.set(media, framesBySegment.get(segment) ?? frameRate); continue; }
+ windows.set(media, frameRate * 2);
+ }
+ const carries = new Map<string, { readonly frames: number; readonly picture: boolean }>();
+ for (const match of svml.matchAll(/<pipeline:Normalize\b([^>]*?)\/?>/gsu)) {
+ const attributes = match[1] ?? "";
+ const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
+ const video = /\bvideo="([^"]+)"/u.exec(attributes)?.[1];
+ if (id === undefined || !windows.has(id)) continue;
+ // A Run that already satisfies this output brought its own material — a package's preview Source
+ // supplies sample pictures this way — and a mock over the top would hide what it came to show.
+ if (alreadySatisfied.has(`${id}.media`)) continue;
+ carries.set(id, { frames: windows.get(id)!, picture: video !== "none" });
+ }
+ return carries;
+ };
+
+ // A derived Run lives beside the project so the original's relative sources still resolve, and under
+ // `.hypit/` so it is never mistaken for something the author wrote. It is rewritten every run.
+ const declarations: string[] = [];
+ const satisfactions: string[] = [];
+ for (const { segmentId, take } of takes) {
+ const output = takeOutputs.get(segmentId);
+ if (output === undefined) continue;
+ // The take's own audio has to be servable, not a digest stub: Studio resolves every Artifact a
+ // projection references, and a preview that cannot serve one stops there.
+ const sampleFrames = Math.round(take.segment.endFrameExclusive / frameRate * 48_000);
+ const silence = silentWav(sampleFrames);
+ await writeFile(join(compareRoot, `${segmentId}-take.wav`), silence);
+ const spoken = { ...take, media: { ...take.media, audio: { artifact: blobRef(silence, "audio/wav"), sampleFrames } } };
+ const fixture = join(compareRoot, `${segmentId}.json`);
+ await writeFile(fixture, `${JSON.stringify({ kind: "inline", value: spoken }, null, 2)}\n`, "utf8");
+ declarations.push(` <file id="stand-in-${segmentId}-audio" type="@hypit/artifact@1#BlobArtifact" from="./${segmentId}-take.wav" media-type="audio/wav"/>`);
+ declarations.push(` <value id="stand-in-${segmentId}" type="@hypit/speech@1#SemanticTake" from="./${segmentId}.json"/>`);
+ satisfactions.push(` <satisfy output="${output}.take" candidate="stand-in-${segmentId}"/>`);
+ }
+ // The layers a Build has not made, as placeholders of the Canvas's own size. `make-placeholder` is
+ // the route's one tool for this: deterministic, Provider-free, and the same mock the comparison is
+ // told to bypass. A mock never enters the project's own Source — it is declared in the derived Run
+ // and nowhere else.
+ // Every picture mock at once. Each one is a solid fill, so they do not contend for anything but
+ // ffmpeg, and drawn one after another they cost more than every frame they stand in for.
+ const mocks = [...mockedMedia()];
+ await Promise.all(mocks
+ .filter(([, { picture }]) => picture)
+ .map(async ([id, { frames }]) => await writePlaceholder({
+ out: join(compareRoot, `${id}.mp4`), width: canvas.width, height: canvas.height,
+ video: true, seconds: Math.max(1, Math.ceil(frames / frameRate)), color: "mid",
+ })));
+ for (const [id, { frames, picture }] of mocks) {
+ const file = join(compareRoot, `${id}.mp4`);
+ // Every SynchronizedMedia carries audio, and it is validated as WAV, so the silence is written as
+ // one rather than pointed at the video. Both are declared: the picture is what gets drawn, the
+ // silence is what makes the value legal.
+ const wavPath = join(compareRoot, `${id}.wav`);
+ const wav = silentWav(Math.round(frames / frameRate * 48_000));
+ await writeFile(wavPath, wav);
+ const audioBlob = blobRef(wav, "audio/wav");
+ declarations.push(` <file id="mock-${id}-audio" type="@hypit/artifact@1#BlobArtifact" from="./${id}.wav" media-type="audio/wav"/>`);
+ let visual: SynchronizedMedia["visual"];
+ if (picture) {
+ const bytes = await readFile(file);
+ visual = { artifact: blobRef(bytes, "video/mp4"), width: canvas.width, height: canvas.height };
+ declarations.push(` <file id="mock-${id}" type="@hypit/artifact@1#BlobArtifact" from="./${id}.mp4" media-type="video/mp4"/>`);
+ }
+ const media: SynchronizedMedia = {
+ timeline: { frameRate: { numerator: frameRate, denominator: 1 }, frameCount: frames },
+ audio: { artifact: audioBlob },
+ ...(visual === undefined ? {} : { visual }),
+ };
+ await writeFile(join(compareRoot, `${id}.media.json`), `${JSON.stringify({ kind: "inline", value: media }, null, 2)}\n`, "utf8");
+ declarations.push(` <value id="media-${id}" type="@hypit/media@1#SynchronizedMedia" from="./${id}.media.json"/>`);
+ satisfactions.push(` <satisfy output="${id}.media" candidate="media-${id}"/>`);
+ }
+
+ // Still images the Source declares as generations. Same treatment, same tool, at the Canvas's size:
+ // a picture slot that is empty in the render is black, and black is not what will be there.
+ const imageIds = [...new Set([...svml.matchAll(/\{([a-z0-9-]+)\.image\}/gu)].map((match) => match[1] ?? ""))]
+ .filter((id) => !alreadySatisfied.has(`${id}.image`));
+ await Promise.all(imageIds.map(async (id) => await writePlaceholder({
+ out: join(compareRoot, `${id}.png`), width: canvas.width, height: canvas.height, color: "mid",
+ })));
+ for (const id of imageIds) {
+ declarations.push(` <file id="mock-${id}" type="@hypit/artifact@1#BlobArtifact" from="./${id}.png" media-type="image/png"/>`);
+ satisfactions.push(` <satisfy output="${id}.image" candidate="mock-${id}"/>`);
+ }
+
+ const derivedRun = join(compareRoot, "compare.svrun");
+ await writeFile(derivedRun, [
+ `<?svml using="@hypit/run-markup@1"?>`,
+ ``,
+ `<svrun version="1">`,
+ // The cut, when there was one: it sits beside this Run, and its own imports were repointed to
+ // reach the project from here.
+ sliced === undefined
+ ? ` <author source="../../${author.replace(/^\.\//u, "")}"/>`
+ : ` <author source="./sliced.svml"/>`,
+ // Whatever the Run brought, repointed: the derived Run sits two directories deeper than the one
+ // that declared these paths.
+ ...carried.map((line) => ` ${line.replace(/from="\.\//gu, 'from="../../')}`),
+ // Targeting the element's own output rather than the Film prunes the closure to what this one
+ // Track needs. Asking for the whole delivery would pull in every generation the Source declares
+ // and report each as unresolved, which is true and useless: none of them is what is being looked at.
+ ` <target output="final.video"/>`,
+ ``,
+ ...declarations,
+ ``,
+ ...satisfactions,
+ `</svrun>`,
+ ``,
+ ].join("\n"), "utf8");
+
+ const domain = await loadStudioDomain({ run: derivedRun, workspaceRoot: projectRoot, packageRoot });
+ const archive = await openStudioArchive(undefined, packageRoot);
+ let built: Preview;
+ try {
+ const run = await loadStudioRun({ run: derivedRun, domain, ...(archive === undefined ? {} : { archive }) });
+ const inspection = inspectStudioRun(run.source, run);
+ // Every Track, not only the one being looked at: the element is compared where it sits, over the
+ // mocked base rather than on its own, because text that is legible on black may not be on a picture.
+ built = await preview({
+ source: run.source,
+ run,
+ domain,
+ outputRefs: [inspection.filmComposition, ...inspection.projections.map((item) => item.ref)],
+ compositionRef: inspection.filmComposition,
+ projections: inspection.projections,
+ ...(archive === undefined ? {} : { archive }),
+ });
+ } catch (error) {
+ const issues = (error as { readonly issues?: unknown } | null)?.issues;
+ if (Array.isArray(issues)) {
+ throw new Error(["the Source does not project yet.", ...issues.slice(0, 12).map((issue) => ` ${String(issue)}`)].join("\n"));
+ }
+ throw error instanceof Error ? error : new Error(String(error));
+ }
+
+ const placed = built.tracks.find((track) => String(track.outputRef ?? "").endsWith(`::output::${element}.track`)
+ || String(track.outputRef ?? "").includes(`::output::${element}.`));
+ if (placed === undefined) {
+ throw new Error([
+ `the Source places no element named ${element}. It places:`,
+ ...built.tracks.map((track) => ` ${String(track.outputRef ?? "").split("::output::")[1] ?? track.name}`),
+ ].join("\n"));
+ }
+
+ // The window to render, named in words. A shot of the reference is found by the words spoken over it
+ // and those words are a Segment or a Selection here, so no reference timestamp is ever read across.
+ let window: AuthoringWindow = { startFrame: 0, endFrameExclusive: programFrames };
+ if (selectionArgument !== undefined) {
+ const marked = selections.get(selectionArgument);
+ assert(marked !== undefined, `the Script marks no Selection ${selectionArgument}`);
+ window = marked;
+ } else if (segmentArgument !== undefined) {
+ let cursor = 0;
+ const take = takes.find((item) => { const hit = item.segmentId === segmentArgument; if (!hit) cursor += item.take.segment.endFrameExclusive; return hit; });
+ assert(take !== undefined, `the Script has no Segment ${segmentArgument}`);
+ window = { startFrame: cursor, endFrameExclusive: cursor + take.take.segment.endFrameExclusive };
+ }
+
+ // Compile once, materialize with the artifact bytes written beside the document, and let the
+ // HyperFrames runtime draw it. This is the path packages/hyperframes/test/browser-visual.test.ts
+ // takes; nothing here is a private renderer.
+ const document = compileHyperframesDocument(built.composition, built.space as ProgramSpace);
+ const stage = join(compareRoot, "stage");
+ await mkdir(stage, { recursive: true });
+ const names = new Map<string, string>();
+ for (const [digest, file] of built.served) {
+ const name = `${digest.replace(/[^a-z0-9]/giu, "")}`;
+ await writeFile(join(stage, name), file.bytes);
+ names.set(digest, name);
+ }
+ await writeFile(join(stage, "index.html"), materializeHyperframesHtml(document, (artifact) => {
+ const name = names.get(artifact.digest);
+ assert(name !== undefined, `the projection references Artifact ${artifact.digest}, which was not served`);
+ return `./${name}`;
+ }), "utf8");
+
+ const clip = /\.(mp4|mov|webm)$/iu.test(outPath);
+ const frames = join(compareRoot, "frames");
+ await rm(frames, { recursive: true, force: true });
+ await mkdir(frames, { recursive: true });
+ const hyperframesCli = createRequire(join(packageRoot, "packages/provider-hyperframes-local/package.json"))
+ .resolve("hyperframes/bin/hyperframes.mjs");
+ const drawn = spawnSync(process.execPath, [
+ hyperframesCli, "render", stage,
+ "--format", "png-sequence", "--output", frames, "--fps", String(frameRate),
+ "--workers", String(Math.max(1, cpus().length - 2)),
+ // Halves the time and lands on the same pixels — verified frame for frame against a run without
+ // it, PSNR reporting no error at all. The flag is marked experimental upstream; that is the
+ // reason to check the pixels, which is done, rather than the reason to draw twice as long.
+ "--experimental-fast-capture", "--no-best-effort", "--quiet",
+ ], { encoding: "utf8", windowsHide: true, timeout: 600_000 });
+ assert(drawn.status === 0, `the HyperFrames runtime refused: ${(drawn.stderr ?? "").trim().slice(-2000)}`);
+
+ const written = (await readdir(frames)).filter((name) => name.endsWith(".png")).sort();
+ assert(written.length > 0, "the HyperFrames runtime wrote no frames");
+ const first = Math.min(window.startFrame, written.length - 1);
+ const last = Math.min(window.endFrameExclusive, written.length);
+ // The runtime draws with an alpha channel and leaves unpainted area transparent. What a viewer is
+ // under is the Film's own clear colour, so it is composited in here rather than left to whatever
+ // opens the file: a reference clip is opaque, and an observer handed a transparent counterpart reads
+ // the difference as design when it came from the encoding.
+ const clear = built.canvas?.clearColor ?? "#000000";
+ const background = `color=c=${clear.replace("#", "0x")}:s=${canvas.width}x${canvas.height}:r=${frameRate}`;
+ const count = Math.max(1, clip ? last - first : 1);
+ const encoded = spawnSync("ffmpeg", [
+ "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "lavfi", "-i", background,
+ "-framerate", String(frameRate), "-start_number", String(clip ? first : Math.min(first + Math.floor((last - first) / 2), written.length - 1)),
+ "-i", join(frames, "frame_%06d.png"),
+ "-filter_complex", "[0][1]overlay=shortest=1[v]", "-map", "[v]",
+ "-frames:v", String(count),
+ ...(clip ? ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "20"] : []),
+ outPath,
+ ], { encoding: "utf8", windowsHide: true, timeout: 600_000 });
+ assert(encoded.status === 0, `ffmpeg refused: ${(encoded.stderr ?? "").trim().slice(-2000)}`);
+
+ return {
+ element,
+ out: outPath,
+ compared: clip ? "clip" : "still",
+ canvas,
+ frame_rate: frameRate,
+ window,
+ program_frames: programFrames,
+ mocked: { media: mockedMedia().size, images: imageIds.length },
+ };
+}
+
+export type RenderPreviewsInput = {
+ readonly package_dirs: readonly string[];
+};
+
+/**
+ * Draw a package's catalogue preview images from the package's own preview Source.
+ *
+ * A Manifest hands Studio and the README a picture per Surface, read off disk with `readFile`. Those
+ * pictures were made once and committed, and nothing could make them again: a Recipe could change, a
+ * Surface could gain a port, and the catalogue would go on showing what the package used to draw.
+ *
+ * So the sample lives in the package as a Source it can be drawn from. `preview/preview.svml`,
+ * `preview/recipes.svs` and `preview/build.svrun` hold the package's own copy, its own Recipe values
+ * and its own Canvas — nothing about any project — and `renderElement` draws them through the
+ * real authoring path. A Surface that stopped working cannot produce a preview that looks fine.
+ *
+ * Which element draws which file comes from the Manifest's own naming: a Surface tagged `Track`
+ * declares `preview/Track.png`, so `Track.png` is drawn from whichever element in the preview Source
+ * carries that tag. No third file has to agree with the other two.
+ */
+export async function renderPreviews(input: RenderPreviewsInput): Promise<Record<string, unknown>> {
+ const directories = input.package_dirs;
+ assert(directories.length > 0, "package_dirs must name at least one package directory");
+
+ const cwd = invokedFrom();
+ const pictures: Record<string, unknown>[] = [];
+ let written = 0;
+ for (const directory of directories) {
+ const packageDir = resolve(cwd, directory);
+ const previewDir = join(packageDir, "preview");
+ const run = join(previewDir, "build.svrun");
+ const svml = await readFile(join(previewDir, "preview.svml"), "utf8").catch(() => undefined);
+ assert(svml !== undefined,
+ `${directory} has no preview/preview.svml. Write one: the package's own copy, its own Recipe values, its own Canvas.`);
+
+ // The alias the preview Source imports this package under. A preview Source places Tracks from
+ // several packages — it needs a semantic spine and a Film like any other — and `Track` is a common
+ // tag, so the tag alone would draw whichever one happened to be written first.
+ const manifestJson = JSON.parse(await readFile(join(packageDir, "package.json"), "utf8").catch(() => "{}")) as { readonly name?: unknown };
+ const specifier = manifestJson.name;
+ assert(typeof specifier === "string", `${directory} has no package.json name`);
+ const imported = [...svml.matchAll(/<import\s+as="([^"]+)"\s+from="(@[^"]+)@\d+"/gu)];
+ const alias = imported.find((match) => match[2] === specifier)?.[1];
+ assert(alias !== undefined,
+ `${directory}'s preview Source does not import ${specifier}, so nothing in it is this package's`);
+
+ // The pictures the Manifest promises, and the element tag each one is named for.
+ const manifest = await readFile(join(packageDir, "src", "manifest.ts"), "utf8").catch(() => "");
+ const promised = [...new Set([...manifest.matchAll(/previewImage\(\s*["']([^"']+)["']/gu)].map((match) => match[1] ?? ""))];
+ const existing = (await readdir(previewDir).catch(() => [] as string[]))
+ .filter((name) => /\.(png|jpe?g|svg)$/iu.test(name));
+ const promisedPictures = promised.length > 0 ? promised : existing;
+ assert(promisedPictures.length > 0, `${directory} promises no preview picture; nothing to draw`);
+
+ for (const picture of promisedPictures) {
+ if (/\.svg$/iu.test(picture)) {
+ // Drawn by hand, not from a Source.
+ pictures.push({ package_dir: directory, picture, drawn: false, reason: "drawn by hand, not from a Source" });
+ continue;
+ }
+ const tag = basename(picture).replace(/\.[^.]+$/u, "");
+ const element = new RegExp(`<${alias}:${tag}\\b[^>]*?\\bid="([^"]+)"`, "su").exec(svml)?.[1];
+ assert(element !== undefined,
+ `${directory} promises ${picture} but its preview Source places no <${alias}:${tag}> to draw it from`);
+ const out = join(previewDir, picture);
+ try {
+ await renderElement({ run, element, out });
+ } catch (error) {
+ throw new Error(`${directory} could not draw ${picture}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ pictures.push({ package_dir: directory, picture, drawn: true, tag, element, out });
+ written += 1;
+ }
+ }
+ return { package_dirs: directories, drew: written, pictures };
+}
diff --git a/packages/reference-video-tools/src/checks.ts b/packages/reference-video-tools/src/checks.ts
new file mode 100644
index 00000000..c989c90d
--- /dev/null
+++ b/packages/reference-video-tools/src/checks.ts
@@ -0,0 +1,420 @@
+import { readFile, readdir } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+
+import { markupSurfaceHostFacetAbi } from "@hypit/markup";
+import type { RegisteredSurface } from "@hypit/markup";
+import { loadNodePackageSelection } from "@hypit/package-loader-node";
+import { openStudioArchive } from "@hypit/studio/src/archive.js";
+import { loadStudioDomain } from "@hypit/studio/src/domain.js";
+import { loadStudioRun } from "@hypit/studio/src/run.js";
+import { readStudioSession } from "@hypit/studio/src/session.js";
+import type { StudioSession } from "@hypit/studio/src/session.js";
+import { inspectStudioRun } from "@hypit/studio/src/studio-preflight.js";
+
+import { invokedFrom } from "./authoring.js";
+import { assert } from "./media.js";
+
+export type PreviewCheckInput = {
+ readonly run: string;
+ readonly runtime?: string;
+};
+
+const AWAITING = "the Studio projection closure requires unresolved capabilities:";
+
+/**
+ * Preview-check a reconstruction before it is delivered.
+ *
+ * `pnpm hypit check` proves a Source is legal; it proves nothing about whether
+ * the tracks it declares can actually be built. A track that fails here fails
+ * the same way when the author opens Studio, so find out now.
+ *
+ * The input is the Run Source, not the Author SVML. Studio's unit of work is
+ * the Run — it reads the Author SVML back out of it — so a check that took the
+ * `.svml` would be checking something Studio never opens.
+ *
+ * Studio names what it cannot resolve and stops, so preflight throwing is itself
+ * the report rather than something to inspect around. Two kinds of issue come
+ * back, and they mean opposite things. An unresolved *capability* means the
+ * graph traced all the way to a Film and a semantic spine, and what remains is
+ * work a Provider has to do — the ordinary state of a Source that declares its
+ * generation rather than performing it. Every other issue means the graph is
+ * wrong and no amount of generation will fix it. Only the second kind is
+ * reported as unsound. `StudioPreflightError` carries `issues` as an array so
+ * the two can be told apart rather than matched out of one joined message.
+ */
+export async function previewCheck(
+ input: PreviewCheckInput,
+ roots: { readonly packageRoot: string },
+): Promise<Record<string, unknown>> {
+ const cwd = invokedFrom();
+ const runPath = resolve(cwd, input.run);
+ const runtimePath = input.runtime === undefined ? undefined : resolve(cwd, input.runtime);
+ const packageRoot = roots.packageRoot;
+ const workspaceRoot = dirname(runPath);
+
+ const domain = await loadStudioDomain({ run: runPath, workspaceRoot, packageRoot });
+ const archive = await openStudioArchive(runtimePath, packageRoot);
+
+ let session: StudioSession | undefined;
+ let refusal: string | undefined;
+ let awaiting: readonly string[] | undefined;
+ try {
+ const run = await loadStudioRun({
+ run: runPath,
+ domain,
+ ...(archive === undefined ? {} : { archive }),
+ });
+ // Preflight first, so an unopenable Run is reported as the refusal it is
+ // rather than as whatever the build happens to fail on afterwards.
+ inspectStudioRun(run.source, run);
+ session = await readStudioSession({
+ domain,
+ run,
+ ...(archive === undefined ? {} : { archive }),
+ revision: 0,
+ });
+ } catch (error) {
+ const issues = (error as { readonly issues?: unknown } | null)?.issues;
+ if (Array.isArray(issues) && issues.every((issue) => String(issue).startsWith(AWAITING))) {
+ awaiting = issues.flatMap((issue) => String(issue).slice(AWAITING.length).split(",").map((capability) => capability.trim()));
+ } else {
+ refusal = error instanceof Error ? error.message : String(error);
+ }
+ } finally {
+ // Close before reporting: a runtime archive left open outlives the check.
+ await archive?.close();
+ }
+
+ if (refusal !== undefined) return { run: runPath, sound: false, refused: refusal };
+
+ if (awaiting !== undefined) {
+ // The graph traced all the way to a Film and a semantic spine; what is left is
+ // work a Provider has to do. That is a pass for this gate, and the delivery
+ // measurements happen on the real Build either way.
+ const noun = awaiting.length === 1 ? "capability" : "capabilities";
+ return {
+ run: runPath,
+ sound: true,
+ summary: `the graph is sound, waiting on ${awaiting.length} ${noun}.`,
+ awaiting,
+ };
+ }
+
+ const tracks = session!.snapshot.tracks;
+ const problems: Record<string, unknown>[] = [];
+ for (const track of tracks) {
+ const { status, errors, output } = track.provenance;
+ if (errors.length > 0) problems.push({ track: track.label, errors });
+ else if (status === "unresolved") problems.push({ track: track.label, unresolved: output });
+ }
+
+ if (problems.length === 0) {
+ return { run: runPath, sound: true, summary: `every Track resolved (${tracks.length}).`, tracks: tracks.length };
+ }
+ return { run: runPath, sound: false, problems };
+}
+
+export type ReconstructionCheckInput = {
+ readonly run: string;
+ readonly reference_id?: string;
+};
+
+/** One element that draws a Track, and the comparisons recorded against its id. */
+type ElementReport = {
+ readonly element: string;
+ readonly id: string;
+ readonly package_name: string;
+ readonly comparisons: number;
+ readonly shots: readonly string[];
+ readonly state: string;
+ readonly note?: string;
+};
+
+/** One timed picture and the Recipe key that decides what it draws once its material ends. */
+type PlaybackReport = {
+ readonly id: string;
+ readonly tag: string;
+ readonly recipe: string;
+ readonly playback: string;
+};
+
+/**
+ * Report what the route can still settle after the Source is written and before a Build runs: which
+ * reconstructed elements have never been compared against the reference, and which timed pictures are
+ * configured to stop before their window ends.
+ *
+ * `preview_check` proves the graph is wired. It proves nothing about whether what the graph draws
+ * resembles the reference video, and a Source can pass every structural check while a component
+ * draws something the reference never contained. Closing that gap is
+ * `references/reconstruction/reconstruction-loop.md`, which is prose, and prose is what a route
+ * skips silently. This is the same requirement as a command that answers whether it was met.
+ *
+ * What it checks is **participation, not convergence**. The loop is deliberately bounded and may
+ * stop with visible differences remaining, so requiring convergence here would contradict it. An
+ * element that was compared once and stopped at its ceiling passes; an element nobody ever looked
+ * at does not.
+ *
+ * Every element that draws is required, whichever package draws it. A Track from installed
+ * vocabulary carries authored values exactly as a project-local one does — a caption Style's size,
+ * colour and placement are as unverified as a new package's — and `render_element` stands in for the
+ * speech, so it renders before a Build like any other.
+ *
+ * A comparison counts whether its answer came back in-band (`complete`, the gemini observer) or was
+ * handed out to be answered by looking (`pending`, the agent observer); only `failed` is not a
+ * comparison. The gate cannot judge whether the shot an element was compared against actually showed
+ * it, so the shots are reported for a reader, and a lone comparison is called out rather than assumed
+ * meaningful.
+ *
+ * A project that places no drawing element passes with nothing to require.
+ */
+export async function reconstructionCheck(
+ input: ReconstructionCheckInput,
+ roots: { readonly workspaceRoot: string; readonly packageRoot: string },
+): Promise<Record<string, unknown>> {
+ const cwd = invokedFrom();
+ const runPath = resolve(cwd, input.run);
+ const packageRoot = roots.packageRoot;
+
+ const runSource = await readFile(runPath, "utf8").catch(() => undefined);
+ assert(runSource !== undefined, `cannot read ${runPath}`);
+ const author = /<author\s+source="([^"]+)"/u.exec(runSource)?.[1];
+ assert(author !== undefined, `${input.run} declares no <author source="…"/>`);
+ const svmlPath = resolve(dirname(runPath), author);
+ const svml = await readFile(svmlPath, "utf8").catch(() => undefined);
+ assert(svml !== undefined, `cannot read ${svmlPath}`);
+
+ // Every package this Source imports.
+ const imports = [...svml.matchAll(/<import\s+as="([^"]+)"\s+from="(@hypit\/[^"@]+)@\d+"/gu)]
+ .map((match) => ({ alias: match[1] ?? "", specifier: match[2] ?? "" }));
+ if (imports.length === 0) {
+ return {
+ run: runPath,
+ passed: true,
+ summary: ["the Source imports no package; nothing to compare."],
+ elements: [],
+ playback: [],
+ };
+ }
+
+ // Which of their Surfaces draw a Track. A Style Surface publishes a Style and draws nothing, so
+ // requiring a comparison of it would be asking for a picture that does not exist.
+ const specifiers = [...new Set(imports.map((item) => item.specifier))];
+ const loaded = await loadNodePackageSelection(specifiers, packageRoot).catch(() => []);
+ const drawingTags = new Set<string>();
+ for (const pack of loaded) {
+ for (const facet of pack.contribution.hostFacets ?? []) {
+ if (facet.abi !== markupSurfaceHostFacetAbi) continue;
+ const surface = facet.implementation as RegisteredSurface;
+ const draws = surface.outputs.some((output) =>
+ output.module.name === "@hypit/composition" && (output.name === "VisualTrack" || output.name === "AudioTrack"));
+ if (draws) drawingTags.add(`${pack.specifier}#${surface.tag}`);
+ }
+ }
+
+ // Every use of one of those tags, by the id the Source gave it.
+ const drawn: { readonly id: string; readonly tag: string; readonly alias: string; readonly specifier: string }[] = [];
+ for (const { alias, specifier } of imports) {
+ const pattern = new RegExp(`<${alias}:([A-Za-z][A-Za-z0-9]*)\\b[^>]*?\\bid="([^"]+)"`, "gu");
+ for (const match of svml.matchAll(pattern)) {
+ const tag = match[1] ?? "";
+ const id = match[2] ?? "";
+ if (!drawingTags.has(`${specifier}#${tag}`)) continue;
+ if (!drawn.some((item) => item.id === id)) drawn.push({ id, tag, alias, specifier });
+ }
+ }
+
+ // ---- Timed pictures that stop before their window ends ----
+ //
+ // A generated take is asked for a whole number of seconds, and the window it has to fill comes from
+ // speech the same Build synthesizes. The two lengths are arrived at separately and do not meet: the
+ // estimate rounds, and the voice that finally speaks is not the voice the estimate predicted. So the
+ // material is routinely shorter than the window it was made for, by anything from a rounding
+ // remainder to a couple of seconds.
+ //
+ // What happens then is decided by one Recipe key. `playback` defaults to `once-start`, which draws
+ // the material once and then draws nothing at all — `sampling.ts` emits no segment for the remainder,
+ // so those frames fall through to whatever is beneath. Under a full-frame base that is the Film
+ // background, which is black. `hold-start` pins the last frame for the rest of the window instead,
+ // `loop-start` repeats, and `stretch` retimes to fit; any of the three fills it.
+ //
+ // This is `frame-coverage.md`'s inherited edge — "a generated take, which ends where its material
+ // ends rather than where the shot should" — in the one form the route can settle before a Build, from
+ // the Source and its Recipe sheets alone.
+ const playbackReport = async (): Promise<readonly PlaybackReport[]> => {
+ // Every Recipe body the Source can name, by the alias its sheet was imported under.
+ const sheets = new Map<string, Map<string, string>>();
+ for (const match of svml.matchAll(/<import\s+as="([^"]+)"\s+source="([^"]+\.svs)"/gu)) {
+ const alias = match[1] ?? "";
+ const source = match[2] ?? "";
+ const text = await readFile(resolve(dirname(svmlPath), source), "utf8").catch(() => undefined);
+ if (text === undefined) continue;
+ const recipes = new Map<string, string>();
+ for (const recipe of text.matchAll(/([A-Za-z0-9_.-]+)\s*\{([^}]*)\}/gu)) recipes.set(recipe[1] ?? "", recipe[2] ?? "");
+ sheets.set(alias, recipes);
+ }
+
+ // Which Normalize ids carry a picture. A take normalized with `video="none"` is a voice and has no
+ // window to fill.
+ const moving = new Set<string>();
+ for (const match of svml.matchAll(/<pipeline:Normalize\b([^>]*?)\/?>/gsu)) {
+ const attributes = match[1] ?? "";
+ const id = /\bid="([^"]+)"/u.exec(attributes)?.[1];
+ const video = /\bvideo="([^"]+)"/u.exec(attributes)?.[1];
+ if (id !== undefined && video !== undefined && video !== "none") moving.add(id);
+ }
+
+ // Which aliases belong to a package that draws. Plenty of elements consume a normalized media
+ // without placing it — `whisperx:SemanticTake` reads one to align speech against it and puts no
+ // picture on the Canvas, so it has no window to fill and no occupancy to choose. Requiring the
+ // alias to come from a package with a Track that outputs a VisualTrack keeps those out, and keeps
+ // the Items and Sequences written inside such a Track in, without this needing to know their tags.
+ const draws = new Set(imports
+ .filter(({ specifier }) => [...drawingTags].some((key) => key.startsWith(`${specifier}#`)))
+ .map(({ alias }) => alias));
+
+ // Every element that places one of those pictures, and what its Recipe says to do with a window the
+ // material does not fill.
+ const running: PlaybackReport[] = [];
+ for (const match of svml.matchAll(/<([a-z][a-z0-9-]*:[A-Za-z][A-Za-z0-9]*)\b([^>]*?)\/?>/gsu)) {
+ const tag = match[1] ?? "";
+ const attributes = match[2] ?? "";
+ if (!draws.has(tag.slice(0, tag.indexOf(":")))) continue;
+ const media = /\bmedia=\{([A-Za-z0-9_-]+)\.media\}/u.exec(attributes)?.[1];
+ if (media === undefined || !moving.has(media)) continue;
+ const appearance = /\bappearance=\{([A-Za-z0-9_-]+)\.([A-Za-z0-9_.-]+)\}/u.exec(attributes);
+ const body = appearance === null ? undefined : sheets.get(appearance[1] ?? "")?.get(appearance[2] ?? "");
+ const playback = body === undefined ? undefined : /\bplayback\s*:\s*([A-Za-z-]+)/u.exec(body)?.[1];
+ if (playback !== undefined && playback !== "once-start" && playback !== "once-end") continue;
+ running.push({
+ id: /\bid="([^"]+)"/u.exec(attributes)?.[1] ?? tag,
+ tag,
+ recipe: appearance === null ? "no appearance Recipe" : `${appearance[1]}.${appearance[2]}`,
+ playback: playback ?? "once-start, by default",
+ });
+ }
+ return running;
+ };
+
+ const running = await playbackReport();
+
+ if (drawn.length === 0 && running.length === 0) {
+ return {
+ run: runPath,
+ passed: true,
+ summary: ["no drawing element is placed in the Source; nothing to require."],
+ elements: [],
+ playback: [],
+ };
+ }
+
+ // The Source does not name the reference it reconstructs, so a single prepared reference is used
+ // when there is exactly one and named explicitly when there is more than one.
+ const referenceRoot = join(roots.workspaceRoot, ".hypit", "reference-video-tools");
+ const prepared = (await readdir(referenceRoot, { withFileTypes: true }).catch(() => []))
+ .filter((entry) => entry.isDirectory()).map((entry) => entry.name);
+ let reference = input.reference_id;
+ if (reference === undefined) {
+ assert(prepared.length > 0, `no prepared reference under ${referenceRoot}; run prepare_reference first`);
+ assert(prepared.length === 1, `${prepared.length} prepared references; pass --reference-id (${prepared.join(", ")})`);
+ reference = prepared[0]!;
+ }
+ assert(prepared.includes(reference), `reference ${reference} is not prepared under ${referenceRoot}`);
+
+ type LoggedComparison = { readonly element?: string; readonly shot_id: string; readonly status: string };
+ const logPath = join(referenceRoot, reference, "comparisons.jsonl");
+ const log = (await readFile(logPath, "utf8").catch(() => ""))
+ .split("\n").filter((line) => line.trim().length > 0)
+ .flatMap((line) => { try { return [JSON.parse(line) as LoggedComparison]; } catch { return []; } })
+ // A comparison counts when it was performed. On the gemini observer the answer comes back in-band
+ // as `complete`; on the agent observer it is handed out as `pending` and answered by looking at the
+ // images, which is participation too. Only `failed` means nothing was compared.
+ .filter((entry) => entry.status === "complete" || entry.status === "pending");
+
+ // Which shots each element was compared against, in order. The gate cannot judge whether a shot was
+ // the right one to compare against — it does not know what the element draws — so it reports them and
+ // lets a reader notice a component compared against a shot that never showed it.
+ const rounds = new Map<string, string[]>();
+ for (const entry of log) {
+ if (entry.element === undefined) continue;
+ const seen = rounds.get(entry.element) ?? [];
+ seen.push(entry.shot_id);
+ rounds.set(entry.element, seen);
+ }
+
+ const never = drawn.filter((element) => (rounds.get(element.id) ?? []).length === 0);
+ const unlabelled = log.filter((entry) => entry.element === undefined).length;
+ // A misspelled --element is otherwise silent: the comparison happens, the log grows, and the element
+ // it was meant for stays at zero for ever.
+ const known = new Set(drawn.map((item) => item.id));
+ const unknown = [...new Set([...rounds.keys()].filter((id) => !known.has(id)))];
+
+ const elements: ElementReport[] = drawn.map((element) => {
+ const shots = rounds.get(element.id) ?? [];
+ const state = shots.length === 0
+ ? "never compared"
+ : `${shots.length} comparison${shots.length === 1 ? "" : "s"} against ${[...new Set(shots)].join(", ")}`;
+ return {
+ element: `${element.alias}:${element.tag}`,
+ id: element.id,
+ package_name: element.specifier,
+ comparisons: shots.length,
+ shots: [...new Set(shots)],
+ state,
+ // The gate cannot judge whether the shot chosen actually showed the element, so a lone comparison
+ // is called out for a reader to confirm rather than silently accepted.
+ ...(shots.length === 1 ? { note: "single comparison — confirm this shot shows the element, not a look-alike" } : {}),
+ };
+ });
+
+ const summary: string[] = [];
+ if (never.length === 0 && running.length === 0) {
+ summary.push(`every drawing element has been compared (${elements.length}), and every timed picture fills its window.`);
+ }
+ if (never.length > 0) summary.push(`${never.length} of ${elements.length} elements have never been compared.`);
+ if (running.length > 0) {
+ summary.push(`${running.length} window${running.length === 1 ? "" : "s"} will empty before ${running.length === 1 ? "it ends" : "they end"}.`);
+ }
+
+ return {
+ run: runPath,
+ reference_id: reference,
+ passed: never.length === 0 && running.length === 0,
+ summary,
+ elements,
+ ...(never.length === 0 ? {} : {
+ never_compared: {
+ ids: never.map((element) => element.id),
+ next: "Read .claude/skills/hypit/references/reconstruction/reconstruction-loop.md, then for each: "
+ + "render the element as the Source configures it, mock the layers a Build has not made, "
+ + "and compare the whole shot blind — one comparison per shot the reference shows it in.",
+ commands: never.map((element) =>
+ `hypit-reference-video-tools compare_reconstruction --reference-id ${reference} `
+ + `--shot-id <each shot that shows ${element.id}> `
+ + `--video <rendered clip>.mp4 --element ${element.id}`),
+ },
+ }),
+ ...(unknown.length === 0 ? {} : {
+ unknown_elements: {
+ names: unknown,
+ note: `${unknown.length} logged element name${unknown.length === 1 ? " does" : "s do"} not exist in the Source. `
+ + "A misspelled --element credits nothing; the element it was meant for is still at zero.",
+ },
+ }),
+ ...(unlabelled === 0 ? {} : {
+ unlabelled_comparisons: {
+ count: unlabelled,
+ note: `${unlabelled} comparison${unlabelled === 1 ? " was" : "s were"} recorded without --element and cannot be credited to one.`,
+ },
+ }),
+ playback: running,
+ ...(running.length === 0 ? {} : {
+ playback_next: "A generated take is ordered in whole seconds and its window is measured from speech the "
+ + "Build has yet to synthesize, so the material is shorter than the window it fills more "
+ + "often than not. Under a full-frame picture the remainder is the Film background, which "
+ + "reads as a black gap; under a cutaway it is the layer beneath blinking through.\n\n"
+ + "Give each Recipe listed here a playback: hold-start to pin the last frame for the rest of the "
+ + "window, loop-start to repeat, or stretch to retime. Read playbooks/craft/frame-coverage.md "
+ + "on inherited edges before choosing — lengthening the material instead leaves the same edge.",
+ }),
+ };
+}
diff --git a/packages/reference-video-tools/src/cli.ts b/packages/reference-video-tools/src/cli.ts
index 606707ef..fb09de2d 100644
--- a/packages/reference-video-tools/src/cli.ts
+++ b/packages/reference-video-tools/src/cli.ts
@@ -16,6 +16,34 @@ function usage(): string {
" hypit-reference-video-tools inspect_svml_vocabulary --package <name> [--package <name> ...] [--tag <tag> ...] [--without-previews]",
" hypit-reference-video-tools compare_reconstruction --reference-id <id> --shot-id <id> --video <path>|--image <path> [--question <scope>] [--element <id>]",
" hypit-reference-video-tools make-placeholder --out <path> --width <w> --height <h> [--color light|mid|dark|white|black|#RRGGBB] [--video] [--seconds <s>]",
+ " hypit-reference-video-tools render_element <build.svrun> --element <id> --out <path.png|path.mp4> [--segment <id>] [--selection <id>]",
+ " hypit-reference-video-tools render_previews <package-dir> [...]",
+ " hypit-reference-video-tools preview_check <build.svrun> [<hypit.runtime.json>]",
+ " hypit-reference-video-tools reconstruction_check <build.svrun> [--reference-id <id>]",
+ "",
+ "preview_check opens the Run the way Studio does and reports whether the graph traces. `sound` is",
+ "true when every Track resolved, and also when the only thing missing is capabilities a Provider has",
+ "still to serve — those are listed under `awaiting`. It takes the Run Source, not the Author SVML:",
+ "Studio's unit of work is the Run, and it reads the .svml back out of it.",
+ "",
+ "reconstruction_check reports what the route can settle before a Build: which drawing elements have",
+ "never been compared against the reference, and which timed pictures are configured to stop before",
+ "their window ends. It asks for participation rather than convergence, so an element compared once",
+ "passes. With one prepared reference it uses that one; with several it requires --reference-id.",
+ "",
+ "render_element draws one element of a Source the way that Source configures it, without a Build",
+ "and without a Provider: the Canvas, frame rate, Recipe values and bindings are read from the",
+ "Source, the Segment skeleton comes from its own estimate:Speech, and the layers a Build has not",
+ "made are mocked with make-placeholder at the Canvas's size. Name the stretch in words —",
+ "--segment or --selection — so no reference timestamp is ever read across; without either, the",
+ "whole program is drawn. An --out ending .mp4, .mov or .webm writes the stretch as a clip, and any",
+ "other extension writes one still from the middle of it.",
+ "",
+ "render_previews draws a package's catalogue pictures from the package's own preview Source in",
+ "preview/preview.svml, preview/recipes.svs and preview/build.svrun. Which element draws which file",
+ "comes from the Manifest's own naming: a Surface tagged Track declares preview/Track.png, so",
+ "Track.png is drawn from whichever element in the preview Source carries that tag. An .svg the",
+ "Manifest promises is drawn by hand and left alone.",
"",
"--element names the reconstructed element the image draws. It is written to the reference's",
"comparison log and never sent to the observer, so the comparison stays blind while a later gate can",
@@ -50,13 +78,24 @@ function usage(): string {
].join("\n");
}
-function parse(argv: readonly string[]): { readonly command: string; readonly flags: Flags } {
+// The authoring and check commands name what they act on positionally — a Run for `render_element`,
+// `preview_check` and `reconstruction_check`, one or more package directories for `render_previews` —
+// so a token that is not a flag is collected rather than refused. Every other command still refuses
+// one, which is why the check is made per command rather than dropped here.
+const COMMANDS_WITH_OPERANDS = new Set(["render_element", "render_previews", "preview_check", "reconstruction_check"]);
+
+function parse(argv: readonly string[]): { readonly command: string; readonly operands: readonly string[]; readonly flags: Flags } {
const command = argv[0];
if (command === undefined || command === "--help" || command === "-h") throw new Error(usage());
const values = new Map<string, string | string[] | boolean>();
+ const operands: string[] = [];
for (let index = 1; index < argv.length; index += 1) {
const token = argv[index]!;
- if (!token.startsWith("--")) throw new Error(`unexpected argument ${token}\n\n${usage()}`);
+ if (!token.startsWith("--")) {
+ if (!COMMANDS_WITH_OPERANDS.has(command)) throw new Error(`unexpected argument ${token}\n\n${usage()}`);
+ operands.push(token);
+ continue;
+ }
const name = token.slice(2);
if (name.length === 0) throw new Error("empty option name");
const next = argv[index + 1];
@@ -69,7 +108,7 @@ function parse(argv: readonly string[]): { readonly command: string; readonly fl
if (current === undefined) values.set(name, next);
else values.set(name, [...(Array.isArray(current) ? current : [String(current)]), next]);
}
- return { command, flags: values };
+ return { command, operands, flags: values };
}
function one(flags: Flags, name: string): string | undefined {
@@ -106,7 +145,7 @@ process.stdout.write = ((chunk: string | Uint8Array, ...rest: readonly unknown[]
(process.stderr.write as (...args: readonly unknown[]) => boolean)(chunk, ...rest)) as typeof process.stdout.write;
async function main(): Promise<void> {
- const { command, flags } = parse(process.argv.slice(2));
+ const { command, operands, flags } = parse(process.argv.slice(2));
if (flags.has("rebuild") || flags.has("refresh")) {
throw new Error("--rebuild and --refresh were removed; use --redo on prepare_reference or --reobserve on observe_reference");
}
@@ -170,6 +209,39 @@ async function main(): Promise<void> {
...(one(flags, "seconds") === undefined ? {} : { seconds: Number(one(flags, "seconds")) }),
};
result = await tools.make_placeholder(input as { out: string; width: number; height: number; color?: string; video?: boolean; seconds?: number });
+ } else if (command === "render_element") {
+ const run = operands[0];
+ if (supplied === undefined && run === undefined) throw new Error(`a <build.svrun> is required\n\n${usage()}`);
+ const input = supplied ?? {
+ run,
+ element: required(flags, "element"),
+ out: required(flags, "out"),
+ ...(one(flags, "segment") === undefined ? {} : { segment: one(flags, "segment") }),
+ ...(one(flags, "selection") === undefined ? {} : { selection: one(flags, "selection") }),
+ };
+ result = await tools.render_element(input as { run: string; element: string; out: string; segment?: string; selection?: string });
+ } else if (command === "render_previews") {
+ if (supplied === undefined && operands.length === 0) throw new Error(`a <package-dir> is required\n\n${usage()}`);
+ const input = supplied ?? { package_dirs: operands };
+ result = await tools.render_previews(input as { package_dirs: readonly string[] });
+ } else if (command === "preview_check") {
+ // The runtime archive is the second operand rather than a flag, the way the Run itself is: both
+ // name a file this command opens, and the pair reads as one argument list.
+ const run = operands[0];
+ if (supplied === undefined && run === undefined) throw new Error(`a <build.svrun> is required\n\n${usage()}`);
+ const input = supplied ?? {
+ run,
+ ...(operands[1] === undefined ? {} : { runtime: operands[1] }),
+ };
+ result = await tools.preview_check(input as { run: string; runtime?: string });
+ } else if (command === "reconstruction_check") {
+ const run = operands[0];
+ if (supplied === undefined && run === undefined) throw new Error(`a <build.svrun> is required\n\n${usage()}`);
+ const input = supplied ?? {
+ run,
+ ...(one(flags, "reference-id") === undefined ? {} : { reference_id: one(flags, "reference-id") }),
+ };
+ result = await tools.reconstruction_check(input as { run: string; reference_id?: string });
} else {
throw new Error(`unknown command ${command}\n\n${usage()}`);
}
diff --git a/packages/reference-video-tools/src/placeholder.ts b/packages/reference-video-tools/src/placeholder.ts
new file mode 100644
index 00000000..f394759a
--- /dev/null
+++ b/packages/reference-video-tools/src/placeholder.ts
@@ -0,0 +1,139 @@
+/**
+ * The route's one placeholder: a flat fill with a contrasting inset border, at whatever size the
+ * Canvas asks for.
+ *
+ * It is written here rather than inside the tool that first needed it because the comparison render
+ * needs dozens of them per round. Reaching them through the CLI meant a Node process, and a TypeScript
+ * compile, per mock — forty-five of those cost more than drawing every frame they stand in for.
+ */
+import { mkdir, writeFile } from "node:fs/promises";
+import { spawn } from "node:child_process";
+import { dirname, resolve } from "node:path";
+import { deflateSync } from "node:zlib";
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function crc32(bytes: Uint8Array): number {
+ let crc = 0xFFFFFFFF;
+ for (const byte of bytes) {
+ crc ^= byte;
+ for (let bit = 0; bit < 8; bit += 1) crc = (crc >>> 1) ^ (crc & 1 ? 0xEDB88320 : 0);
+ }
+ return (crc ^ 0xFFFFFFFF) >>> 0;
+}
+
+function pngChunk(type: string, data: Uint8Array): Uint8Array {
+ const body = new Uint8Array(type.length + data.length);
+ for (let i = 0; i < type.length; i += 1) body[i] = type.charCodeAt(i);
+ body.set(data, type.length);
+ const out = new Uint8Array(8 + body.length);
+ const view = new DataView(out.buffer);
+ view.setUint32(0, data.length);
+ out.set(body, 4);
+ view.setUint32(4 + body.length, crc32(body));
+ return out;
+}
+
+const PLACEHOLDER_COLORS = {
+ light: "#E8EAED", // default — visible on a dark base
+ mid: "#9AA0A6",
+ dark: "#5F6368", // visible on a light base
+ white: "#FFFFFF",
+ black: "#202124",
+} as const;
+
+type PlaceholderPalette = {
+ readonly base: [number, number, number];
+ readonly border: [number, number, number];
+ readonly hex: string;
+};
+
+/**
+ * Resolve the mock's colour: one of the named presets, or a six-digit hex. The inset border is the
+ * contrast of the base — a dark border on a light fill, a light border on a dark fill — so the
+ * placeholder stays visible whichever base it sits on, which is the point of choosing at all: a mock
+ * the same shade as its surroundings is one the observer reads as a hole rather than a slot.
+ */
+function resolvePlaceholderColor(value: string | undefined): PlaceholderPalette {
+ const named = value === undefined ? PLACEHOLDER_COLORS.light
+ : (PLACEHOLDER_COLORS as Record<string, string>)[value];
+ const hex = named ?? value ?? PLACEHOLDER_COLORS.light;
+ assert(named !== undefined || /^#[0-9a-f]{6}$/iu.test(value!),
+ `color must be one of ${Object.keys(PLACEHOLDER_COLORS).join(", ")} or a six-digit hex like #E0E0E0.`);
+ const base: [number, number, number] = [
+ parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16),
+ ];
+ const luminance = 0.299 * base[0] + 0.587 * base[1] + 0.114 * base[2];
+ const border: [number, number, number] = luminance > 128 ? [32, 33, 36] : [232, 234, 237];
+ return { base, border, hex };
+}
+
+/**
+ * A correctly-sized placeholder image for a media slot the Source declares as a generation and a
+ * Build has not filled. The comparison loop needs a still; the slot must be mocked, and the mock is
+ * this tool's output — deterministic, Provider-free, never a real generation and never a hand-rolled
+ * script. A field with an inset frame reads as a slot waiting for content rather than a broken
+ * image, so the observer can bypass the region instead of reporting it every round.
+ */
+function placeholderPng(width: number, height: number, palette: PlaceholderPalette): Uint8Array {
+ const { base, border } = palette;
+ const raw = Buffer.alloc(height * (1 + width * 3));
+ const margin = Math.max(2, Math.round(Math.min(width, height) * 0.05));
+ for (let y = 0; y < height; y += 1) {
+ raw[y * (1 + width * 3)] = 0;
+ for (let x = 0; x < width; x += 1) {
+ const c = (x < margin || y < margin || x >= width - margin || y >= height - margin) ? border : base;
+ const i = y * (1 + width * 3) + 1 + x * 3;
+ raw[i] = c[0]; raw[i + 1] = c[1]; raw[i + 2] = c[2];
+ }
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8; ihdr[9] = 2; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
+ return Uint8Array.from(Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ pngChunk("IHDR", ihdr),
+ pngChunk("IDAT", deflateSync(raw)),
+ pngChunk("IEND", Buffer.alloc(0)),
+ ]));
+}
+
+export type PlaceholderRequest = {
+ readonly out: string;
+ readonly width: number;
+ readonly height: number;
+ readonly color?: string;
+ readonly video?: boolean;
+ readonly seconds?: number;
+};
+
+/** Write one placeholder and report what it wrote, in the shape the CLI returns. */
+export async function writePlaceholder(input: PlaceholderRequest): Promise<Record<string, unknown>> {
+ const palette = resolvePlaceholderColor(input.color);
+ const out = resolve(input.out);
+ await mkdir(dirname(out), { recursive: true });
+ if (input.video === true) {
+ // A slot that only accepts video needs a real video artifact; a short solid-colour clip is the
+ // mock. ffmpeg is part of the required local toolchain.
+ const seconds = input.seconds ?? 1;
+ const filter = `color=c=${palette.hex.slice(1)}:s=${input.width}x${input.height}:r=24:d=${seconds}`;
+ const result = await new Promise<{ status: number | null; error?: Error }>((done) => {
+ const child = spawn("ffmpeg", [
+ "-y", "-f", "lavfi", "-i", filter, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-t", String(seconds), out,
+ ]);
+ child.on("close", (status) => done({ status }));
+ child.on("error", (error) => done({ status: null, error }));
+ });
+ assert(result.status === 0,
+ `ffmpeg failed to write a placeholder video (${result.error?.message ?? `exit ${result.status}`}); ffmpeg is part of the required local toolchain`);
+ return { out, width: input.width, height: input.height, color: palette.hex, video: true, seconds };
+ }
+ await writeFile(out, placeholderPng(input.width, input.height, palette));
+ return { out, width: input.width, height: input.height, color: palette.hex, video: false };
+}
+
+export { resolvePlaceholderColor, placeholderPng };
+export type { PlaceholderPalette };
diff --git a/packages/reference-video-tools/src/slice.ts b/packages/reference-video-tools/src/slice.ts
new file mode 100644
index 00000000..b962af3a
--- /dev/null
+++ b/packages/reference-video-tools/src/slice.ts
@@ -0,0 +1,209 @@
+/**
+ * Cut an Author Source down to the one stretch a comparison is looking at, mechanically.
+ *
+ * Rendering an element means rendering a program, and a program is as long as its Script. Comparing
+ * six seconds of a sixty-second video meant drawing all sixty and cropping, which is most of the
+ * cost of a comparison round.
+ *
+ * The cut is a **transformation of the original text, not a rewrite**: every element that survives is
+ * copied out of the Source byte for byte, at the range the parse gave it. Nothing is authored here,
+ * so the fragment cannot describe something the Source does not.
+ *
+ * What decides survival is reference integrity, not distance from the element being looked at.
+ * Following inputs backwards from the target would keep what it depends on and drop everything else —
+ * and the Tracks that can collide with it on screen are exactly the ones it has no edge to. A caption
+ * sliced that way hangs over nothing, which is the shape of the defect this whole path exists to
+ * catch. So instead: keep the Segment, drop the rest of the Script, and then drop only what can no
+ * longer resolve — an element naming a Segment, Selection or Moment that is gone, and anything
+ * naming an element dropped for that reason, to a fixed point. A peer bound inside the kept Segment
+ * survives by construction, because its binding still resolves.
+ */
+
+export type SliceResult = {
+ /** The fragment, verbatim from the original except for what was removed. */
+ readonly text: string;
+ /** Element ids left out, and the name each one could no longer reach. */
+ readonly dropped: readonly { readonly id: string; readonly unresolved: string }[];
+ readonly keptSegment: string;
+};
+
+type Element = {
+ readonly id: string | undefined;
+ readonly start: number;
+ readonly end: number;
+ readonly depth: number;
+ readonly text: string;
+};
+
+/**
+ * Every element in the document with its byte range, including children. A tag is either
+ * self-closing or closed by name; comments and the Script's own prose are skipped, since a `<` inside
+ * spoken words is not a tag.
+ */
+function elements(source: string, skip: readonly (readonly [number, number])[]): Element[] {
+ const found: Element[] = [];
+ const open: { name: string; start: number; depth: number }[] = [];
+ const inside = (index: number): boolean => skip.some(([from, to]) => index >= from && index < to);
+ const pattern = /<(\/?)([a-z][a-z0-9-]*(?::[A-Za-z][A-Za-z0-9]*)?)\b([^>]*?)(\/?)>/gsu;
+ for (const match of source.matchAll(pattern)) {
+ const index = match.index;
+ if (inside(index)) continue;
+ const whole = match[0];
+ const closing = match[1]!;
+ const name = match[2]!;
+ const attributes = match[3]!;
+ const selfClosing = match[4]!;
+ if (closing === "/") {
+ const last = open.pop();
+ if (last !== undefined && last.name === name) {
+ found.push({
+ id: undefined, start: last.start, end: index + whole.length, depth: last.depth,
+ text: source.slice(last.start, index + whole.length),
+ });
+ }
+ continue;
+ }
+ if (selfClosing === "/") {
+ found.push({
+ id: /\bid="([^"]+)"/u.exec(attributes)?.[1], start: index, end: index + whole.length,
+ depth: open.length, text: whole,
+ });
+ continue;
+ }
+ open.push({ name, start: index, depth: open.length });
+ }
+ // A closed element's id has to be read back off its own opening tag.
+ return found.map((element) => element.id === undefined
+ ? { ...element, id: /^<[^>]*?\bid="([^"]+)"/su.exec(element.text)?.[1] }
+ : element);
+}
+
+/** The Script names an element reaches for, and the element ids it reaches for. */
+function references(text: string): { readonly story: Set<string>; readonly ids: Set<string> } {
+ const story = new Set<string>();
+ const ids = new Set<string>();
+ // A Script name is reached through more than one space — `story.selection.x` in word space and
+ // `story.caption.selection.x` in caption space name the same Selection. Matching only the first
+ // leaves an element holding a dead name in caption space, and the cut looks clean until the graph
+ // refuses it.
+ for (const match of text.matchAll(/\{story\.(?:[a-z]+\.)*?(segment|selection|moment)\.([A-Za-z0-9_-]+)/gu)) {
+ story.add(`${match[1]!}.${match[2]!}`);
+ }
+ for (const match of text.matchAll(/\{([A-Za-z][A-Za-z0-9_-]*)[.}]/gu)) {
+ const id = match[1]!;
+ if (id !== "story") ids.add(id);
+ }
+ return { story, ids };
+}
+
+/**
+ * @param source the Author SVML
+ * @param segment the Segment to keep, named in the Script
+ */
+export function sliceSource(source: string, segment: string): SliceResult {
+ const open = /<script\b[^>]*>/u.exec(source);
+ if (open === null) throw new Error("the Source declares no <script>");
+ const bodyStart = open.index + open[0].length;
+ const bodyEnd = source.indexOf("</script>", bodyStart);
+ if (bodyEnd < 0) throw new Error("the Source's <script> is not closed");
+
+ // The Segment to keep, taken out of the Script whole. A Segment is one element in the Script body,
+ // so this is a range, and what it contains — its Selections, its Moments — comes with it.
+ const body = source.slice(bodyStart, bodyEnd);
+ const kept = new RegExp(`<${segment}\\b[^>]*>.*?</${segment}>`, "su").exec(body);
+ if (kept === null) throw new Error(`the Script has no <${segment}> Segment`);
+
+ // Which Script names survive: the Segment itself, and every Selection and Moment marked inside it.
+ const alive = new Set<string>([`segment.${segment}`]);
+ for (const match of kept[0].matchAll(/@([a-z][a-z0-9-]*)\b/gu)) {
+ alive.add(`selection.${match[1]!}`);
+ alive.add(`moment.${match[1]!}`);
+ }
+
+ const skip: (readonly [number, number])[] = [[bodyStart, bodyEnd]];
+ for (const comment of source.matchAll(/<!--.*?-->/gsu)) skip.push([comment.index, comment.index + comment[0].length]);
+ const all = elements(source, skip);
+
+ // Drop to a fixed point: an element that names something gone is gone, and so is one that names it.
+ //
+ // What an element names is on its own opening tag. Reading its whole text instead makes a container
+ // inherit its children's references, so a Speech Track dies of one dead Take and takes the Film
+ // with it. Children are elements too and answer for themselves — which is also why the set is keyed
+ // by position: a `<speech:Take>` has no id, and still has to be droppable on its own.
+ const opening = (element: Element): string => /^<[^>]*>/su.exec(element.text)?.[0] ?? element.text;
+ const dropped = new Map<number, string>();
+ const byId = new Map(all.flatMap((element) => element.id === undefined ? [] : [[element.id, element] as const]));
+ const deadIds = new Set<string>();
+ for (;;) {
+ let changed = false;
+ for (const element of all) {
+ if (dropped.has(element.start)) continue;
+ const { story, ids } = references(opening(element));
+ const missingStory = [...story].find((name) => !alive.has(name));
+ if (missingStory !== undefined) {
+ dropped.set(element.start, `story.${missingStory}`);
+ if (element.id !== undefined) deadIds.add(element.id);
+ changed = true;
+ continue;
+ }
+ const missingId = [...ids].find((id) => deadIds.has(id) && byId.has(id));
+ if (missingId !== undefined) {
+ dropped.set(element.start, missingId);
+ if (element.id !== undefined) deadIds.add(element.id);
+ changed = true;
+ }
+ }
+ // A container emptied by the cut goes with its children. A Track written with Items is refused
+ // when it has none, and the refusal names the Track rather than the Segment that took its Items
+ // away, so leaving it in turns one clean cut into a graph error a reader has to trace back.
+ for (const element of all) {
+ if (dropped.has(element.start)) continue;
+ const children = all.filter((other) =>
+ other !== element && other.start > element.start && other.end <= element.end);
+ if (children.length === 0) continue;
+ if (children.some((child) => !dropped.has(child.start))) continue;
+ dropped.set(element.start, "every child was cut");
+ if (element.id !== undefined) deadIds.add(element.id);
+ changed = true;
+ }
+ if (!changed) break;
+ }
+
+ // Rebuild: the Script body becomes the one Segment, and every dropped element's range is removed.
+ // Only the outermost dropped element is cut, since cutting a child of a cut parent removes text
+ // twice and leaves the document short of a closing tag.
+ const cuts = all
+ .filter((element) => dropped.has(element.start))
+ .filter((element, _, list) => !list.some((other) =>
+ other !== element && other.start <= element.start && other.end >= element.end
+ && !(other.start === element.start && other.end === element.end)))
+ .sort((left, right) => left.start - right.start);
+
+ let text = "";
+ let cursor = 0;
+ for (const cut of cuts) {
+ if (cut.start < cursor) continue;
+ text += source.slice(cursor, cut.start);
+ cursor = cut.end;
+ // Take the rest of the line with it, so a removal never leaves a blank indented line behind.
+ while (source[cursor] === " " || source[cursor] === "\t") cursor += 1;
+ if (source[cursor] === "\n") cursor += 1;
+ }
+ text += source.slice(cursor);
+
+ // The Script body is replaced last, in the rebuilt text, since every range above indexes the
+ // original. Its content is unique enough to find again.
+ const rebuiltOpen = /<script\b[^>]*>/u.exec(text);
+ if (rebuiltOpen === null) throw new Error("the Script was removed by the cut");
+ const rebuiltStart = rebuiltOpen.index + rebuiltOpen[0].length;
+ const rebuiltEnd = text.indexOf("</script>", rebuiltStart);
+ text = `${text.slice(0, rebuiltStart)}\n ${kept[0]}\n ${text.slice(rebuiltEnd)}`;
+
+ return {
+ text,
+ dropped: all.flatMap((element) => dropped.has(element.start)
+ ? [{ id: element.id ?? opening(element).slice(0, 40), unresolved: dropped.get(element.start)! }]
+ : []),
+ keptSegment: segment,
+ };
+}
diff --git a/packages/reference-video-tools/src/tools.ts b/packages/reference-video-tools/src/tools.ts
index c44d57d1..69c77aac 100644
--- a/packages/reference-video-tools/src/tools.ts
+++ b/packages/reference-video-tools/src/tools.ts
@@ -11,6 +11,11 @@ import { markupSurfaceHostFacetAbi } from "@hypit/markup";
import type { RegisteredSurface, SurfaceVocabulary } from "@hypit/markup";
import { exactModelHostAbi } from "@hypit/model-kit";
+import { renderElement, renderPreviews } from "./authoring.js";
+import type { RenderElementInput, RenderPreviewsInput } from "./authoring.js";
+import { writePlaceholder } from "./placeholder.js";
+import { previewCheck, reconstructionCheck } from "./checks.js";
+import type { PreviewCheckInput, ReconstructionCheckInput } from "./checks.js";
import {
assert,
ensureDir,
@@ -78,6 +83,9 @@ export type MakePlaceholderInput = {
readonly seconds?: number;
};
+export type { RenderElementInput, RenderPreviewsInput } from "./authoring.js";
+export type { PreviewCheckInput, ReconstructionCheckInput } from "./checks.js";
+
export type ReferenceVideoTools = {
list_svml_packages(): Promise<Record<string, unknown>>;
prepare_reference(input: PrepareReferenceInput): Promise<PrepareResult>;
@@ -86,6 +94,10 @@ export type ReferenceVideoTools = {
compare_reconstruction(input: CompareReconstructionInput): Promise<Record<string, unknown>>;
record_observation(input: RecordObservationInput): Promise<Record<string, unknown>>;
make_placeholder(input: MakePlaceholderInput): Promise<Record<string, unknown>>;
+ render_element(input: RenderElementInput): Promise<Record<string, unknown>>;
+ render_previews(input: RenderPreviewsInput): Promise<Record<string, unknown>>;
+ preview_check(input: PreviewCheckInput): Promise<Record<string, unknown>>;
+ reconstruction_check(input: ReconstructionCheckInput): Promise<Record<string, unknown>>;
};
type ToolOptions = {
@@ -137,91 +149,7 @@ async function appendComparison(root: string, record: ComparisonRecord): Promise
await appendFile(join(root, "comparisons.jsonl"), `${JSON.stringify(record)}\n`, "utf8");
}
-function crc32(bytes: Uint8Array): number {
- let crc = 0xFFFFFFFF;
- for (const byte of bytes) {
- crc ^= byte;
- for (let bit = 0; bit < 8; bit += 1) crc = (crc >>> 1) ^ (crc & 1 ? 0xEDB88320 : 0);
- }
- return (crc ^ 0xFFFFFFFF) >>> 0;
-}
-
-function pngChunk(type: string, data: Uint8Array): Uint8Array {
- const body = new Uint8Array(type.length + data.length);
- for (let i = 0; i < type.length; i += 1) body[i] = type.charCodeAt(i);
- body.set(data, type.length);
- const out = new Uint8Array(8 + body.length);
- const view = new DataView(out.buffer);
- view.setUint32(0, data.length);
- out.set(body, 4);
- view.setUint32(4 + body.length, crc32(body));
- return out;
-}
-
-const PLACEHOLDER_COLORS = {
- light: "#E8EAED", // default — visible on a dark base
- mid: "#9AA0A6",
- dark: "#5F6368", // visible on a light base
- white: "#FFFFFF",
- black: "#202124",
-} as const;
-
-type PlaceholderPalette = {
- readonly base: [number, number, number];
- readonly border: [number, number, number];
- readonly hex: string;
-};
-
-/**
- * Resolve the mock's colour: one of the named presets, or a six-digit hex. The inset border is the
- * contrast of the base — a dark border on a light fill, a light border on a dark fill — so the
- * placeholder stays visible whichever base it sits on, which is the point of choosing at all: a mock
- * the same shade as its surroundings is one the observer reads as a hole rather than a slot.
- */
-function resolvePlaceholderColor(value: string | undefined): PlaceholderPalette {
- const named = value === undefined ? PLACEHOLDER_COLORS.light
- : (PLACEHOLDER_COLORS as Record<string, string>)[value];
- const hex = named ?? value ?? PLACEHOLDER_COLORS.light;
- assert(named !== undefined || /^#[0-9a-f]{6}$/iu.test(value!),
- `color must be one of ${Object.keys(PLACEHOLDER_COLORS).join(", ")} or a six-digit hex like #E0E0E0.`);
- const base: [number, number, number] = [
- parseInt(hex.slice(1, 3), 16), parseInt(hex.slice(3, 5), 16), parseInt(hex.slice(5, 7), 16),
- ];
- const luminance = 0.299 * base[0] + 0.587 * base[1] + 0.114 * base[2];
- const border: [number, number, number] = luminance > 128 ? [32, 33, 36] : [232, 234, 237];
- return { base, border, hex };
-}
-/**
- * A correctly-sized placeholder image for a media slot the Source declares as a generation and a
- * Build has not filled. The comparison loop needs a still; the slot must be mocked, and the mock is
- * this tool's output — deterministic, Provider-free, never a real generation and never a hand-rolled
- * script. A field with an inset frame reads as a slot waiting for content rather than a broken
- * image, so the observer can bypass the region instead of reporting it every round.
- */
-function placeholderPng(width: number, height: number, palette: PlaceholderPalette): Uint8Array {
- const { base, border } = palette;
- const raw = Buffer.alloc(height * (1 + width * 3));
- const margin = Math.max(2, Math.round(Math.min(width, height) * 0.05));
- for (let y = 0; y < height; y += 1) {
- raw[y * (1 + width * 3)] = 0;
- for (let x = 0; x < width; x += 1) {
- const c = (x < margin || y < margin || x >= width - margin || y >= height - margin) ? border : base;
- const i = y * (1 + width * 3) + 1 + x * 3;
- raw[i] = c[0]; raw[i + 1] = c[1]; raw[i + 2] = c[2];
- }
- }
- const ihdr = Buffer.alloc(13);
- ihdr.writeUInt32BE(width, 0);
- ihdr.writeUInt32BE(height, 4);
- ihdr[8] = 8; ihdr[9] = 2; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
- return Uint8Array.from(Buffer.concat([
- Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
- pngChunk("IHDR", ihdr),
- pngChunk("IDAT", deflateSync(raw)),
- pngChunk("IEND", Buffer.alloc(0)),
- ]));
-}
function positiveInt(value: number, label: string): number {
assert(Number.isSafeInteger(value) && value > 0, `${label} must be a positive integer.`);
@@ -926,30 +854,30 @@ export function createReferenceVideoTools(options: ToolOptions = {}): ReferenceV
// fixed, correctly-sized placeholder — the same tool on every run, never a real generation and
// never a script the agent writes by hand.
async make_placeholder(input): Promise<Record<string, unknown>> {
- const width = positiveInt(Number(input.width), "width");
- const height = positiveInt(Number(input.height), "height");
- const palette = resolvePlaceholderColor(input.color === undefined ? undefined : String(input.color));
- const out = resolve(String(input.out));
- await mkdir(dirname(out), { recursive: true });
- if (input.video === true) {
- // A slot that only accepts video needs a real video artifact; a short solid-colour clip is
- // the mock. ffmpeg is part of the required local toolchain.
- const seconds = input.seconds === undefined ? 1 : positiveInt(Number(input.seconds), "seconds");
- const filter = `color=c=${palette.hex.slice(1)}:s=${width}x${height}:r=24:d=${seconds}`;
- const result = await new Promise<{ status: number | null; error?: Error }>((done) => {
- const child = spawn("ffmpeg", [
- "-y", "-f", "lavfi", "-i", filter, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-t", String(seconds), out,
- ]);
- child.on("close", (status) => done({ status }));
- child.on("error", (error) => done({ status: null, error }));
- });
- if (result.status !== 0) {
- throw new Error(`ffmpeg failed to write a placeholder video (${result.error?.message ?? `exit ${result.status}`}); ffmpeg is part of the required local toolchain`);
- }
- return { out, width, height, color: palette.hex, video: true, seconds };
- }
- await writeFile(out, placeholderPng(width, height, palette));
- return { out, width, height, color: palette.hex, video: false };
+ return await writePlaceholder({
+ out: String(input.out),
+ width: positiveInt(Number(input.width), "width"),
+ height: positiveInt(Number(input.height), "height"),
+ ...(input.color === undefined ? {} : { color: String(input.color) }),
+ ...(input.video === true ? { video: true } : {}),
+ ...(input.seconds === undefined ? {} : { seconds: positiveInt(Number(input.seconds), "seconds") }),
+ });
+ },
+
+ async render_element(input): Promise<Record<string, unknown>> {
+ return await renderElement(input);
+ },
+
+ async render_previews(input): Promise<Record<string, unknown>> {
+ return await renderPreviews(input);
+ },
+
+ async preview_check(input): Promise<Record<string, unknown>> {
+ return await previewCheck(input, { packageRoot });
+ },
+
+ async reconstruction_check(input): Promise<Record<string, unknown>> {
+ return await reconstructionCheck(input, { workspaceRoot, packageRoot });
},
};
}